diff --git a/abstract-document/pom.xml b/abstract-document/pom.xml index 2b7d58519..ef190e088 100644 --- a/abstract-document/pom.xml +++ b/abstract-document/pom.xml @@ -34,6 +34,14 @@ abstract-document + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/abstract-document/src/main/java/com/iluwatar/abstractdocument/AbstractDocument.java b/abstract-document/src/main/java/com/iluwatar/abstractdocument/AbstractDocument.java index 701906041..ab5ccada1 100644 --- a/abstract-document/src/main/java/com/iluwatar/abstractdocument/AbstractDocument.java +++ b/abstract-document/src/main/java/com/iluwatar/abstractdocument/AbstractDocument.java @@ -31,9 +31,7 @@ import java.util.Objects; import java.util.function.Function; import java.util.stream.Stream; -/** - * Abstract implementation of Document interface. - */ +/** Abstract implementation of Document interface. */ public abstract class AbstractDocument implements Document { private final Map documentProperties; @@ -57,12 +55,12 @@ public abstract class AbstractDocument implements Document { @Override public Stream children(String key, Function, T> childConstructor) { return Stream.ofNullable(get(key)) - .filter(Objects::nonNull) - .map(el -> (List>) el) - .findAny() - .stream() - .flatMap(Collection::stream) - .map(childConstructor); + .filter(Objects::nonNull) + .map(el -> (List>) el) + .findAny() + .stream() + .flatMap(Collection::stream) + .map(childConstructor); } @Override @@ -100,5 +98,4 @@ public abstract class AbstractDocument implements Document { builder.append("]"); return builder.toString(); } - } diff --git a/abstract-document/src/main/java/com/iluwatar/abstractdocument/App.java b/abstract-document/src/main/java/com/iluwatar/abstractdocument/App.java index 6775523ef..607b4a7f7 100644 --- a/abstract-document/src/main/java/com/iluwatar/abstractdocument/App.java +++ b/abstract-document/src/main/java/com/iluwatar/abstractdocument/App.java @@ -49,20 +49,26 @@ public class App { public static void main(String[] args) { LOGGER.info("Constructing parts and car"); - var wheelProperties = Map.of( - Property.TYPE.toString(), "wheel", - Property.MODEL.toString(), "15C", - Property.PRICE.toString(), 100L); + var wheelProperties = + Map.of( + Property.TYPE.toString(), "wheel", + Property.MODEL.toString(), "15C", + Property.PRICE.toString(), 100L); - var doorProperties = Map.of( - Property.TYPE.toString(), "door", - Property.MODEL.toString(), "Lambo", - Property.PRICE.toString(), 300L); + var doorProperties = + Map.of( + Property.TYPE.toString(), "door", + Property.MODEL.toString(), "Lambo", + Property.PRICE.toString(), 300L); - var carProperties = Map.of( - Property.MODEL.toString(), "300SL", - Property.PRICE.toString(), 10000L, - Property.PARTS.toString(), List.of(wheelProperties, doorProperties)); + var carProperties = + Map.of( + Property.MODEL.toString(), + "300SL", + Property.PRICE.toString(), + 10000L, + Property.PARTS.toString(), + List.of(wheelProperties, doorProperties)); var car = new Car(carProperties); @@ -70,10 +76,13 @@ public class App { LOGGER.info("-> model: {}", car.getModel().orElseThrow()); LOGGER.info("-> price: {}", car.getPrice().orElseThrow()); LOGGER.info("-> parts: "); - car.getParts().forEach(p -> LOGGER.info("\t{}/{}/{}", - p.getType().orElse(null), - p.getModel().orElse(null), - p.getPrice().orElse(null)) - ); + car.getParts() + .forEach( + p -> + LOGGER.info( + "\t{}/{}/{}", + p.getType().orElse(null), + p.getModel().orElse(null), + p.getPrice().orElse(null))); } } diff --git a/abstract-document/src/main/java/com/iluwatar/abstractdocument/Document.java b/abstract-document/src/main/java/com/iluwatar/abstractdocument/Document.java index 198a543b5..79a51b610 100644 --- a/abstract-document/src/main/java/com/iluwatar/abstractdocument/Document.java +++ b/abstract-document/src/main/java/com/iluwatar/abstractdocument/Document.java @@ -28,15 +28,13 @@ import java.util.Map; import java.util.function.Function; import java.util.stream.Stream; -/** - * Document interface. - */ +/** Document interface. */ public interface Document { /** * Puts the value related to the key. * - * @param key element key + * @param key element key * @param value element value * @return Void */ @@ -53,7 +51,7 @@ public interface Document { /** * Gets the stream of child documents. * - * @param key element key + * @param key element key * @param constructor constructor of child class * @return child documents */ diff --git a/abstract-document/src/main/java/com/iluwatar/abstractdocument/domain/Car.java b/abstract-document/src/main/java/com/iluwatar/abstractdocument/domain/Car.java index 6b7bbcf52..93fbbb9c1 100644 --- a/abstract-document/src/main/java/com/iluwatar/abstractdocument/domain/Car.java +++ b/abstract-document/src/main/java/com/iluwatar/abstractdocument/domain/Car.java @@ -27,13 +27,10 @@ package com.iluwatar.abstractdocument.domain; import com.iluwatar.abstractdocument.AbstractDocument; import java.util.Map; -/** - * Car entity. - */ +/** Car entity. */ public class Car extends AbstractDocument implements HasModel, HasPrice, HasParts { public Car(Map properties) { super(properties); } - } diff --git a/abstract-document/src/main/java/com/iluwatar/abstractdocument/domain/HasModel.java b/abstract-document/src/main/java/com/iluwatar/abstractdocument/domain/HasModel.java index 008f5a257..6f517588e 100644 --- a/abstract-document/src/main/java/com/iluwatar/abstractdocument/domain/HasModel.java +++ b/abstract-document/src/main/java/com/iluwatar/abstractdocument/domain/HasModel.java @@ -28,13 +28,10 @@ import com.iluwatar.abstractdocument.Document; import com.iluwatar.abstractdocument.domain.enums.Property; import java.util.Optional; -/** - * HasModel trait for static access to 'model' property. - */ +/** HasModel trait for static access to 'model' property. */ public interface HasModel extends Document { default Optional getModel() { return Optional.ofNullable((String) get(Property.MODEL.toString())); } - } diff --git a/abstract-document/src/main/java/com/iluwatar/abstractdocument/domain/HasParts.java b/abstract-document/src/main/java/com/iluwatar/abstractdocument/domain/HasParts.java index 5dee245d1..8bffa753e 100644 --- a/abstract-document/src/main/java/com/iluwatar/abstractdocument/domain/HasParts.java +++ b/abstract-document/src/main/java/com/iluwatar/abstractdocument/domain/HasParts.java @@ -28,13 +28,10 @@ import com.iluwatar.abstractdocument.Document; import com.iluwatar.abstractdocument.domain.enums.Property; import java.util.stream.Stream; -/** - * HasParts trait for static access to 'parts' property. - */ +/** HasParts trait for static access to 'parts' property. */ public interface HasParts extends Document { default Stream getParts() { return children(Property.PARTS.toString(), Part::new); } - } diff --git a/abstract-document/src/main/java/com/iluwatar/abstractdocument/domain/HasPrice.java b/abstract-document/src/main/java/com/iluwatar/abstractdocument/domain/HasPrice.java index db985dfba..ce876e5fa 100644 --- a/abstract-document/src/main/java/com/iluwatar/abstractdocument/domain/HasPrice.java +++ b/abstract-document/src/main/java/com/iluwatar/abstractdocument/domain/HasPrice.java @@ -28,13 +28,10 @@ import com.iluwatar.abstractdocument.Document; import com.iluwatar.abstractdocument.domain.enums.Property; import java.util.Optional; -/** - * HasPrice trait for static access to 'price' property. - */ +/** HasPrice trait for static access to 'price' property. */ public interface HasPrice extends Document { default Optional getPrice() { return Optional.ofNullable((Number) get(Property.PRICE.toString())); } - } diff --git a/abstract-document/src/main/java/com/iluwatar/abstractdocument/domain/HasType.java b/abstract-document/src/main/java/com/iluwatar/abstractdocument/domain/HasType.java index bd83adecb..5e0f49df7 100644 --- a/abstract-document/src/main/java/com/iluwatar/abstractdocument/domain/HasType.java +++ b/abstract-document/src/main/java/com/iluwatar/abstractdocument/domain/HasType.java @@ -28,13 +28,10 @@ import com.iluwatar.abstractdocument.Document; import com.iluwatar.abstractdocument.domain.enums.Property; import java.util.Optional; -/** - * HasType trait for static access to 'type' property. - */ +/** HasType trait for static access to 'type' property. */ public interface HasType extends Document { default Optional getType() { return Optional.ofNullable((String) get(Property.TYPE.toString())); } - } diff --git a/abstract-document/src/main/java/com/iluwatar/abstractdocument/domain/Part.java b/abstract-document/src/main/java/com/iluwatar/abstractdocument/domain/Part.java index 9aa46be15..6eec08b0d 100644 --- a/abstract-document/src/main/java/com/iluwatar/abstractdocument/domain/Part.java +++ b/abstract-document/src/main/java/com/iluwatar/abstractdocument/domain/Part.java @@ -27,13 +27,10 @@ package com.iluwatar.abstractdocument.domain; import com.iluwatar.abstractdocument.AbstractDocument; import java.util.Map; -/** - * Part entity. - */ +/** Part entity. */ public class Part extends AbstractDocument implements HasType, HasModel, HasPrice { public Part(Map properties) { super(properties); } - } diff --git a/abstract-document/src/main/java/com/iluwatar/abstractdocument/domain/enums/Property.java b/abstract-document/src/main/java/com/iluwatar/abstractdocument/domain/enums/Property.java index 3aa97ba84..3e0d6d10a 100644 --- a/abstract-document/src/main/java/com/iluwatar/abstractdocument/domain/enums/Property.java +++ b/abstract-document/src/main/java/com/iluwatar/abstractdocument/domain/enums/Property.java @@ -24,10 +24,10 @@ */ package com.iluwatar.abstractdocument.domain.enums; -/** - * Enum To Describe Property type. - */ +/** Enum To Describe Property type. */ public enum Property { - - PARTS, TYPE, PRICE, MODEL + PARTS, + TYPE, + PRICE, + MODEL } diff --git a/abstract-document/src/test/java/com/iluwatar/abstractdocument/AbstractDocumentTest.java b/abstract-document/src/test/java/com/iluwatar/abstractdocument/AbstractDocumentTest.java index 61d1f1128..a098517c3 100644 --- a/abstract-document/src/test/java/com/iluwatar/abstractdocument/AbstractDocumentTest.java +++ b/abstract-document/src/test/java/com/iluwatar/abstractdocument/AbstractDocumentTest.java @@ -24,16 +24,14 @@ */ package com.iluwatar.abstractdocument; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; + import java.util.HashMap; import java.util.List; import java.util.Map; +import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.*; - -/** - * AbstractDocument test class - */ +/** AbstractDocument test class */ class AbstractDocumentTest { private static final String KEY = "key"; @@ -82,13 +80,16 @@ class AbstractDocumentTest { @Test void shouldHandleExceptionDuringConstruction() { - Map invalidProperties = null; // Invalid properties, causing NullPointerException + Map invalidProperties = + null; // Invalid properties, causing NullPointerException // Throw null pointer exception - assertThrows(NullPointerException.class, () -> { - // Attempt to construct a document with invalid properties - new DocumentImplementation(invalidProperties); - }); + assertThrows( + NullPointerException.class, + () -> { + // Attempt to construct a document with invalid properties + new DocumentImplementation(invalidProperties); + }); } @Test @@ -97,11 +98,11 @@ class AbstractDocumentTest { DocumentImplementation nestedDocument = new DocumentImplementation(new HashMap<>()); nestedDocument.put("nestedKey", "nestedValue"); - document.put("nested", nestedDocument); // Retrieving the nested document - DocumentImplementation retrievedNestedDocument = (DocumentImplementation) document.get("nested"); + DocumentImplementation retrievedNestedDocument = + (DocumentImplementation) document.get("nested"); assertNotNull(retrievedNestedDocument); assertEquals("nestedValue", retrievedNestedDocument.get("nestedKey")); diff --git a/abstract-document/src/test/java/com/iluwatar/abstractdocument/AppTest.java b/abstract-document/src/test/java/com/iluwatar/abstractdocument/AppTest.java index 09af6d7b5..16dcba0db 100644 --- a/abstract-document/src/test/java/com/iluwatar/abstractdocument/AppTest.java +++ b/abstract-document/src/test/java/com/iluwatar/abstractdocument/AppTest.java @@ -24,25 +24,21 @@ */ package com.iluwatar.abstractdocument; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -/** - * Simple App test - */ +import org.junit.jupiter.api.Test; + +/** Simple App test */ class AppTest { /** * Issue: Add at least one assertion to this test case. * - * Solution: Inserted assertion to check whether the execution of the main method in {@link App} - * throws an exception. + *

Solution: Inserted assertion to check whether the execution of the main method in {@link + * App} throws an exception. */ - @Test void shouldExecuteAppWithoutException() { assertDoesNotThrow(() -> App.main(null)); } - } diff --git a/abstract-document/src/test/java/com/iluwatar/abstractdocument/DomainTest.java b/abstract-document/src/test/java/com/iluwatar/abstractdocument/DomainTest.java index 4b52fa7a6..fc29dea45 100644 --- a/abstract-document/src/test/java/com/iluwatar/abstractdocument/DomainTest.java +++ b/abstract-document/src/test/java/com/iluwatar/abstractdocument/DomainTest.java @@ -24,18 +24,16 @@ */ package com.iluwatar.abstractdocument; +import static org.junit.jupiter.api.Assertions.assertEquals; + import com.iluwatar.abstractdocument.domain.Car; import com.iluwatar.abstractdocument.domain.Part; import com.iluwatar.abstractdocument.domain.enums.Property; -import org.junit.jupiter.api.Test; import java.util.List; import java.util.Map; +import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; - -/** - * Test for Part and Car - */ +/** Test for Part and Car */ class DomainTest { private static final String TEST_PART_TYPE = "test-part-type"; @@ -47,11 +45,11 @@ class DomainTest { @Test void shouldConstructPart() { - var partProperties = Map.of( - Property.TYPE.toString(), TEST_PART_TYPE, - Property.MODEL.toString(), TEST_PART_MODEL, - Property.PRICE.toString(), (Object) TEST_PART_PRICE - ); + var partProperties = + Map.of( + Property.TYPE.toString(), TEST_PART_TYPE, + Property.MODEL.toString(), TEST_PART_MODEL, + Property.PRICE.toString(), (Object) TEST_PART_PRICE); var part = new Part(partProperties); assertEquals(TEST_PART_TYPE, part.getType().orElseThrow()); assertEquals(TEST_PART_MODEL, part.getModel().orElseThrow()); @@ -60,15 +58,14 @@ class DomainTest { @Test void shouldConstructCar() { - var carProperties = Map.of( - Property.MODEL.toString(), TEST_CAR_MODEL, - Property.PRICE.toString(), TEST_CAR_PRICE, - Property.PARTS.toString(), List.of(Map.of(), Map.of()) - ); + var carProperties = + Map.of( + Property.MODEL.toString(), TEST_CAR_MODEL, + Property.PRICE.toString(), TEST_CAR_PRICE, + Property.PARTS.toString(), List.of(Map.of(), Map.of())); var car = new Car(carProperties); assertEquals(TEST_CAR_MODEL, car.getModel().orElseThrow()); assertEquals(TEST_CAR_PRICE, car.getPrice().orElseThrow()); assertEquals(2, car.getParts().count()); } - } diff --git a/abstract-factory/pom.xml b/abstract-factory/pom.xml index 99a92423b..60fbf72ef 100644 --- a/abstract-factory/pom.xml +++ b/abstract-factory/pom.xml @@ -34,6 +34,14 @@ abstract-factory + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/App.java b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/App.java index e360822ca..798cbe4fd 100644 --- a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/App.java +++ b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/App.java @@ -74,6 +74,7 @@ public class App implements Runnable { /** * Creates kingdom. + * * @param kingdomType type of Kingdom */ public void createKingdom(final Kingdom.FactoryMaker.KingdomType kingdomType) { @@ -82,4 +83,4 @@ public class App implements Runnable { kingdom.setCastle(kingdomFactory.createCastle()); kingdom.setArmy(kingdomFactory.createArmy()); } -} \ No newline at end of file +} diff --git a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/Army.java b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/Army.java index 3efec4c87..78c75323f 100644 --- a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/Army.java +++ b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/Army.java @@ -24,9 +24,7 @@ */ package com.iluwatar.abstractfactory; -/** - * Army interface. - */ +/** Army interface. */ public interface Army { String getDescription(); diff --git a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/Castle.java b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/Castle.java index 8fca06819..ee1e16f3c 100644 --- a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/Castle.java +++ b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/Castle.java @@ -24,9 +24,7 @@ */ package com.iluwatar.abstractfactory; -/** - * Castle interface. - */ +/** Castle interface. */ public interface Castle { String getDescription(); diff --git a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/ElfArmy.java b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/ElfArmy.java index 055d2cc75..d7e46c145 100644 --- a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/ElfArmy.java +++ b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/ElfArmy.java @@ -24,9 +24,7 @@ */ package com.iluwatar.abstractfactory; -/** - * ElfArmy. - */ +/** ElfArmy. */ public class ElfArmy implements Army { static final String DESCRIPTION = "This is the elven army!"; diff --git a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/ElfCastle.java b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/ElfCastle.java index 5b0c26c42..136afb11f 100644 --- a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/ElfCastle.java +++ b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/ElfCastle.java @@ -24,9 +24,7 @@ */ package com.iluwatar.abstractfactory; -/** - * ElfCastle. - */ +/** ElfCastle. */ public class ElfCastle implements Castle { static final String DESCRIPTION = "This is the elven castle!"; diff --git a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/ElfKing.java b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/ElfKing.java index 0696e1d09..9b0d3a6f1 100644 --- a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/ElfKing.java +++ b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/ElfKing.java @@ -24,9 +24,7 @@ */ package com.iluwatar.abstractfactory; -/** - * ElfKing. - */ +/** ElfKing. */ public class ElfKing implements King { static final String DESCRIPTION = "This is the elven king!"; diff --git a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/ElfKingdomFactory.java b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/ElfKingdomFactory.java index f45d2ee03..b09a2f47c 100644 --- a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/ElfKingdomFactory.java +++ b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/ElfKingdomFactory.java @@ -24,9 +24,7 @@ */ package com.iluwatar.abstractfactory; -/** - * ElfKingdomFactory concrete factory. - */ +/** ElfKingdomFactory concrete factory. */ public class ElfKingdomFactory implements KingdomFactory { @Override @@ -43,5 +41,4 @@ public class ElfKingdomFactory implements KingdomFactory { public Army createArmy() { return new ElfArmy(); } - } diff --git a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/King.java b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/King.java index 01af71a6a..9f65ed434 100644 --- a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/King.java +++ b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/King.java @@ -24,9 +24,7 @@ */ package com.iluwatar.abstractfactory; -/** - * King interface. - */ +/** King interface. */ public interface King { String getDescription(); diff --git a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/Kingdom.java b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/Kingdom.java index db1c65ca4..d1f85a6a4 100644 --- a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/Kingdom.java +++ b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/Kingdom.java @@ -27,9 +27,7 @@ package com.iluwatar.abstractfactory; import lombok.Getter; import lombok.Setter; -/** - * Helper class to manufacture {@link KingdomFactory} beans. - */ +/** Helper class to manufacture {@link KingdomFactory} beans. */ @Getter @Setter public class Kingdom { @@ -38,21 +36,16 @@ public class Kingdom { private Castle castle; private Army army; - /** - * The factory of kingdom factories. - */ + /** The factory of kingdom factories. */ public static class FactoryMaker { - /** - * Enumeration for the different types of Kingdoms. - */ + /** Enumeration for the different types of Kingdoms. */ public enum KingdomType { - ELF, ORC + ELF, + ORC } - /** - * The factory method to create KingdomFactory concrete objects. - */ + /** The factory method to create KingdomFactory concrete objects. */ public static KingdomFactory makeFactory(KingdomType type) { return switch (type) { case ELF -> new ElfKingdomFactory(); diff --git a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/KingdomFactory.java b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/KingdomFactory.java index fdfe19dc0..199c6697d 100644 --- a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/KingdomFactory.java +++ b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/KingdomFactory.java @@ -24,9 +24,7 @@ */ package com.iluwatar.abstractfactory; -/** - * KingdomFactory factory interface. - */ +/** KingdomFactory factory interface. */ public interface KingdomFactory { Castle createCastle(); @@ -34,5 +32,4 @@ public interface KingdomFactory { King createKing(); Army createArmy(); - } diff --git a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/OrcArmy.java b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/OrcArmy.java index d687c32e8..31ed6896d 100644 --- a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/OrcArmy.java +++ b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/OrcArmy.java @@ -24,9 +24,7 @@ */ package com.iluwatar.abstractfactory; -/** - * OrcArmy. - */ +/** OrcArmy. */ public class OrcArmy implements Army { static final String DESCRIPTION = "This is the orc army!"; diff --git a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/OrcCastle.java b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/OrcCastle.java index f842bb3c6..bdae5709a 100644 --- a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/OrcCastle.java +++ b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/OrcCastle.java @@ -24,9 +24,7 @@ */ package com.iluwatar.abstractfactory; -/** - * OrcCastle. - */ +/** OrcCastle. */ public class OrcCastle implements Castle { static final String DESCRIPTION = "This is the orc castle!"; diff --git a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/OrcKing.java b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/OrcKing.java index e25d93bfb..7f106d45a 100644 --- a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/OrcKing.java +++ b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/OrcKing.java @@ -24,9 +24,7 @@ */ package com.iluwatar.abstractfactory; -/** - * OrcKing. - */ +/** OrcKing. */ public class OrcKing implements King { static final String DESCRIPTION = "This is the orc king!"; diff --git a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/OrcKingdomFactory.java b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/OrcKingdomFactory.java index c80728a87..82d258570 100644 --- a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/OrcKingdomFactory.java +++ b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/OrcKingdomFactory.java @@ -24,9 +24,7 @@ */ package com.iluwatar.abstractfactory; -/** - * OrcKingdomFactory concrete factory. - */ +/** OrcKingdomFactory concrete factory. */ public class OrcKingdomFactory implements KingdomFactory { @Override 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 0f7708e07..b5dde940c 100644 --- a/abstract-factory/src/test/java/com/iluwatar/abstractfactory/AbstractFactoryTest.java +++ b/abstract-factory/src/test/java/com/iluwatar/abstractfactory/AbstractFactoryTest.java @@ -24,14 +24,12 @@ */ package com.iluwatar.abstractfactory; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; -/** - * Tests for abstract factory. - */ +import org.junit.jupiter.api.Test; + +/** Tests for abstract factory. */ class AbstractFactoryTest { private final App app = new App(); diff --git a/abstract-factory/src/test/java/com/iluwatar/abstractfactory/AppTest.java b/abstract-factory/src/test/java/com/iluwatar/abstractfactory/AppTest.java index 736a7f8b7..9f53691a5 100644 --- a/abstract-factory/src/test/java/com/iluwatar/abstractfactory/AppTest.java +++ b/abstract-factory/src/test/java/com/iluwatar/abstractfactory/AppTest.java @@ -24,18 +24,16 @@ */ package com.iluwatar.abstractfactory; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -/** - * Check whether the execution of the main method in {@link App} throws an exception. - */ +import org.junit.jupiter.api.Test; + +/** Check whether the execution of the main method in {@link App} throws an exception. */ class AppTest { - + @Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/active-object/pom.xml b/active-object/pom.xml index 08a09e664..aa26dbbe2 100644 --- a/active-object/pom.xml +++ b/active-object/pom.xml @@ -34,6 +34,14 @@ active-object + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/active-object/src/main/java/com/iluwatar/activeobject/ActiveCreature.java b/active-object/src/main/java/com/iluwatar/activeobject/ActiveCreature.java index c7b661845..5a440020c 100644 --- a/active-object/src/main/java/com/iluwatar/activeobject/ActiveCreature.java +++ b/active-object/src/main/java/com/iluwatar/activeobject/ActiveCreature.java @@ -29,86 +29,87 @@ import java.util.concurrent.LinkedBlockingQueue; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -/** - * ActiveCreature class is the base of the active object example. - * - */ +/** ActiveCreature class is the base of the active object example. */ public abstract class ActiveCreature { - + private static final Logger logger = LoggerFactory.getLogger(ActiveCreature.class.getName()); private BlockingQueue requests; - + private String name; - + private Thread thread; // Thread of execution. - + private int status; // status of the thread of execution. - /** - * Constructor and initialization. - */ + /** Constructor and initialization. */ protected ActiveCreature(String name) { this.name = name; this.status = 0; this.requests = new LinkedBlockingQueue<>(); - thread = new Thread(() -> { - boolean infinite = true; - while (infinite) { - try { - requests.take().run(); - } catch (InterruptedException e) { - if (this.status != 0) { - logger.error("Thread was interrupted. --> {}", e.getMessage()); - } - infinite = false; - Thread.currentThread().interrupt(); - } - } - }); + thread = + new Thread( + () -> { + boolean infinite = true; + while (infinite) { + try { + requests.take().run(); + } catch (InterruptedException e) { + if (this.status != 0) { + logger.error("Thread was interrupted. --> {}", e.getMessage()); + } + infinite = false; + Thread.currentThread().interrupt(); + } + } + }); thread.start(); } /** * Eats the porridge. + * * @throws InterruptedException due to firing a new Runnable. */ public void eat() throws InterruptedException { - requests.put(() -> { - logger.info("{} is eating!", name()); - logger.info("{} has finished eating!", name()); - }); + requests.put( + () -> { + logger.info("{} is eating!", name()); + logger.info("{} has finished eating!", name()); + }); } /** * Roam the wastelands. + * * @throws InterruptedException due to firing a new Runnable. */ public void roam() throws InterruptedException { - requests.put(() -> - logger.info("{} has started to roam in the wastelands.", name()) - ); + requests.put(() -> logger.info("{} has started to roam in the wastelands.", name())); } - + /** * Returns the name of the creature. + * * @return the name of the creature. */ public String name() { return this.name; } - + /** * Kills the thread of execution. + * * @param status of the thread of execution. 0 == OK, the rest is logging an error. */ public void kill(int status) { this.status = status; this.thread.interrupt(); } - + /** * Returns the status of the thread of execution. + * * @return the status of the thread of execution. */ public int getStatus() { diff --git a/active-object/src/main/java/com/iluwatar/activeobject/App.java b/active-object/src/main/java/com/iluwatar/activeobject/App.java index b88b4c559..ca3a5526e 100644 --- a/active-object/src/main/java/com/iluwatar/activeobject/App.java +++ b/active-object/src/main/java/com/iluwatar/activeobject/App.java @@ -30,17 +30,17 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * The Active Object pattern helps to solve synchronization difficulties without using - * 'synchronized' methods. The active object will contain a thread-safe data structure - * (such as BlockingQueue) and use to synchronize method calls by moving the logic of the method - * into an invocator(usually a Runnable) and store it in the DSA. - * + * The Active Object pattern helps to solve synchronization difficulties without using + * 'synchronized' methods. The active object will contain a thread-safe data structure (such as + * BlockingQueue) and use to synchronize method calls by moving the logic of the method into an + * invocator(usually a Runnable) and store it in the DSA. + * *

In this example, we fire 20 threads to modify a value in the target class. */ public class App implements Runnable { - + private static final Logger logger = LoggerFactory.getLogger(App.class.getName()); - + private static final int NUM_CREATURES = 3; /** @@ -48,11 +48,11 @@ public class App implements Runnable { * * @param args command line arguments. */ - public static void main(String[] args) { + public static void main(String[] args) { var app = new App(); app.run(); } - + @Override public void run() { List creatures = new ArrayList<>(); diff --git a/active-object/src/main/java/com/iluwatar/activeobject/Orc.java b/active-object/src/main/java/com/iluwatar/activeobject/Orc.java index 8f5570a86..30adde034 100644 --- a/active-object/src/main/java/com/iluwatar/activeobject/Orc.java +++ b/active-object/src/main/java/com/iluwatar/activeobject/Orc.java @@ -24,14 +24,10 @@ */ package com.iluwatar.activeobject; -/** - * An implementation of the ActiveCreature class. - * - */ +/** An implementation of the ActiveCreature class. */ public class Orc extends ActiveCreature { public Orc(String name) { super(name); } - } diff --git a/active-object/src/test/java/com/iluwatar/activeobject/ActiveCreatureTest.java b/active-object/src/test/java/com/iluwatar/activeobject/ActiveCreatureTest.java index 5441ed6b0..be79e2fb5 100644 --- a/active-object/src/test/java/com/iluwatar/activeobject/ActiveCreatureTest.java +++ b/active-object/src/test/java/com/iluwatar/activeobject/ActiveCreatureTest.java @@ -27,17 +27,16 @@ package com.iluwatar.activeobject; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; -class ActiveCreatureTest { - - @Test - void executionTest() throws InterruptedException { - ActiveCreature orc = new Orc("orc1"); - assertEquals("orc1",orc.name()); - assertEquals(0,orc.getStatus()); - orc.eat(); - orc.roam(); - orc.kill(0); - } - +class ActiveCreatureTest { + + @Test + void executionTest() throws InterruptedException { + ActiveCreature orc = new Orc("orc1"); + assertEquals("orc1", orc.name()); + assertEquals(0, orc.getStatus()); + orc.eat(); + orc.roam(); + orc.kill(0); + } } diff --git a/active-object/src/test/java/com/iluwatar/activeobject/AppTest.java b/active-object/src/test/java/com/iluwatar/activeobject/AppTest.java index 8ef2f142c..559e2a1f5 100644 --- a/active-object/src/test/java/com/iluwatar/activeobject/AppTest.java +++ b/active-object/src/test/java/com/iluwatar/activeobject/AppTest.java @@ -28,11 +28,10 @@ import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import org.junit.jupiter.api.Test; - class AppTest { - @Test - void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); - } + @Test + void shouldExecuteApplicationWithoutException() { + assertDoesNotThrow(() -> App.main(new String[] {})); + } } diff --git a/acyclic-visitor/pom.xml b/acyclic-visitor/pom.xml index 52604048e..b4f5646b7 100644 --- a/acyclic-visitor/pom.xml +++ b/acyclic-visitor/pom.xml @@ -34,6 +34,14 @@ acyclic-visitor + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/AllModemVisitor.java b/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/AllModemVisitor.java index 38da4923a..a3b1679a2 100644 --- a/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/AllModemVisitor.java +++ b/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/AllModemVisitor.java @@ -28,6 +28,4 @@ package com.iluwatar.acyclicvisitor; * All ModemVisitor interface extends all visitor interfaces. This interface provides ease of use * when a visitor needs to visit all modem types. */ -public interface AllModemVisitor extends ZoomVisitor, HayesVisitor { - -} +public interface AllModemVisitor extends ZoomVisitor, HayesVisitor {} diff --git a/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/App.java b/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/App.java index 64d4d039a..3b7c6cd61 100644 --- a/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/App.java +++ b/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/App.java @@ -37,9 +37,7 @@ package com.iluwatar.acyclicvisitor; */ public class App { - /** - * Program's entry point. - */ + /** Program's entry point. */ public static void main(String[] args) { var conUnix = new ConfigureForUnixVisitor(); var conDos = new ConfigureForDosVisitor(); @@ -50,6 +48,6 @@ public class App { hayes.accept(conDos); // Hayes modem with Dos configurator zoom.accept(conDos); // Zoom modem with Dos configurator hayes.accept(conUnix); // Hayes modem with Unix configurator - zoom.accept(conUnix); // Zoom modem with Unix configurator + zoom.accept(conUnix); // Zoom modem with Unix configurator } } diff --git a/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/ConfigureForDosVisitor.java b/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/ConfigureForDosVisitor.java index 9f9f29187..267a8d66a 100644 --- a/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/ConfigureForDosVisitor.java +++ b/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/ConfigureForDosVisitor.java @@ -27,8 +27,7 @@ package com.iluwatar.acyclicvisitor; import lombok.extern.slf4j.Slf4j; /** - * ConfigureForDosVisitor class implements both zoom's and hayes' visit method for Dos - * manufacturer. + * ConfigureForDosVisitor class implements both zoom's and hayes' visit method for Dos manufacturer. */ @Slf4j public class ConfigureForDosVisitor implements AllModemVisitor { diff --git a/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/ConfigureForUnixVisitor.java b/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/ConfigureForUnixVisitor.java index 097f19c0d..d9fd14f69 100644 --- a/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/ConfigureForUnixVisitor.java +++ b/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/ConfigureForUnixVisitor.java @@ -37,4 +37,4 @@ public class ConfigureForUnixVisitor implements ZoomVisitor { public void visit(Zoom zoom) { LOGGER.info(zoom + " used with Unix configurator."); } -} \ No newline at end of file +} diff --git a/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/Hayes.java b/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/Hayes.java index 384df8a4d..e0b2fcc2b 100644 --- a/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/Hayes.java +++ b/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/Hayes.java @@ -26,15 +26,11 @@ package com.iluwatar.acyclicvisitor; import lombok.extern.slf4j.Slf4j; -/** - * Hayes class implements its accept method. - */ +/** Hayes class implements its accept method. */ @Slf4j public class Hayes implements Modem { - /** - * Accepts all visitors but honors only HayesVisitor. - */ + /** Accepts all visitors but honors only HayesVisitor. */ @Override public void accept(ModemVisitor modemVisitor) { if (modemVisitor instanceof HayesVisitor) { @@ -42,12 +38,9 @@ public class Hayes implements Modem { } else { LOGGER.info("Only HayesVisitor is allowed to visit Hayes modem"); } - } - /** - * Hayes' modem's toString method. - */ + /** Hayes' modem's toString method. */ @Override public String toString() { return "Hayes modem"; diff --git a/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/HayesVisitor.java b/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/HayesVisitor.java index a33c87cfa..aad9b9709 100644 --- a/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/HayesVisitor.java +++ b/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/HayesVisitor.java @@ -24,9 +24,7 @@ */ package com.iluwatar.acyclicvisitor; -/** - * HayesVisitor interface. - */ +/** HayesVisitor interface. */ public interface HayesVisitor extends ModemVisitor { void visit(Hayes hayes); } diff --git a/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/Modem.java b/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/Modem.java index fd15ee422..855257445 100644 --- a/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/Modem.java +++ b/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/Modem.java @@ -24,10 +24,7 @@ */ package com.iluwatar.acyclicvisitor; -/** - * //Modem abstract class. - * converted to an interface - */ +/** //Modem abstract class. converted to an interface */ public interface Modem { void accept(ModemVisitor modemVisitor); } diff --git a/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/Zoom.java b/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/Zoom.java index e9f02e1ad..59b50a54a 100644 --- a/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/Zoom.java +++ b/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/Zoom.java @@ -26,15 +26,11 @@ package com.iluwatar.acyclicvisitor; import lombok.extern.slf4j.Slf4j; -/** - * Zoom class implements its accept method. - */ +/** Zoom class implements its accept method. */ @Slf4j public class Zoom implements Modem { - /** - * Accepts all visitors but honors only ZoomVisitor. - */ + /** Accepts all visitors but honors only ZoomVisitor. */ @Override public void accept(ModemVisitor modemVisitor) { if (modemVisitor instanceof ZoomVisitor) { @@ -44,9 +40,7 @@ public class Zoom implements Modem { } } - /** - * Zoom modem's toString method. - */ + /** Zoom modem's toString method. */ @Override public String toString() { return "Zoom modem"; diff --git a/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/ZoomVisitor.java b/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/ZoomVisitor.java index 639af1c65..5388ded6f 100644 --- a/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/ZoomVisitor.java +++ b/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/ZoomVisitor.java @@ -24,9 +24,7 @@ */ package com.iluwatar.acyclicvisitor; -/** - * ZoomVisitor interface. - */ +/** ZoomVisitor interface. */ public interface ZoomVisitor extends ModemVisitor { void visit(Zoom zoom); } diff --git a/acyclic-visitor/src/test/java/com/iluwatar/acyclicvisitor/AppTest.java b/acyclic-visitor/src/test/java/com/iluwatar/acyclicvisitor/AppTest.java index 9cc242d8f..7a21498a6 100644 --- a/acyclic-visitor/src/test/java/com/iluwatar/acyclicvisitor/AppTest.java +++ b/acyclic-visitor/src/test/java/com/iluwatar/acyclicvisitor/AppTest.java @@ -24,25 +24,22 @@ */ package com.iluwatar.acyclicvisitor; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -/** - * Tests that the Acyclic Visitor example runs without errors. - */ +import org.junit.jupiter.api.Test; + +/** Tests that the Acyclic Visitor example runs without errors. */ class AppTest { /** * Issue: Add at least one assertion to this test case. * - * Solution: Inserted assertion to check whether the execution of the main method in {@link App} - * throws an exception. + *

Solution: Inserted assertion to check whether the execution of the main method in {@link + * App} throws an exception. */ - @Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } -} \ No newline at end of file +} diff --git a/acyclic-visitor/src/test/java/com/iluwatar/acyclicvisitor/HayesTest.java b/acyclic-visitor/src/test/java/com/iluwatar/acyclicvisitor/HayesTest.java index 66640e3ca..a989d9287 100644 --- a/acyclic-visitor/src/test/java/com/iluwatar/acyclicvisitor/HayesTest.java +++ b/acyclic-visitor/src/test/java/com/iluwatar/acyclicvisitor/HayesTest.java @@ -24,14 +24,12 @@ */ package com.iluwatar.acyclicvisitor; -import org.junit.jupiter.api.Test; - import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.*; -/** - * Hayes test class - */ +import org.junit.jupiter.api.Test; + +/** Hayes test class */ class HayesTest { @Test diff --git a/acyclic-visitor/src/test/java/com/iluwatar/acyclicvisitor/ZoomTest.java b/acyclic-visitor/src/test/java/com/iluwatar/acyclicvisitor/ZoomTest.java index df7b7e840..d5fe79965 100644 --- a/acyclic-visitor/src/test/java/com/iluwatar/acyclicvisitor/ZoomTest.java +++ b/acyclic-visitor/src/test/java/com/iluwatar/acyclicvisitor/ZoomTest.java @@ -24,16 +24,13 @@ */ package com.iluwatar.acyclicvisitor; - -import org.junit.jupiter.api.Test; - import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; -/** - * Zoom test class - */ +import org.junit.jupiter.api.Test; + +/** Zoom test class */ class ZoomTest { @Test diff --git a/adapter/pom.xml b/adapter/pom.xml index d54cbd048..6e7f45a51 100644 --- a/adapter/pom.xml +++ b/adapter/pom.xml @@ -34,6 +34,14 @@ adapter + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/adapter/src/main/java/com/iluwatar/adapter/App.java b/adapter/src/main/java/com/iluwatar/adapter/App.java index 1f572813c..a4fa74274 100644 --- a/adapter/src/main/java/com/iluwatar/adapter/App.java +++ b/adapter/src/main/java/com/iluwatar/adapter/App.java @@ -37,16 +37,15 @@ package com.iluwatar.adapter; *

The Adapter ({@link FishingBoatAdapter}) converts the interface of the adaptee class ({@link * FishingBoat}) into a suitable one expected by the client ({@link RowingBoat}). * - *

The story of this implementation is this.
Pirates are coming! we need a {@link - * RowingBoat} to flee! We have a {@link FishingBoat} and our captain. We have no time to make up a - * new ship! we need to reuse this {@link FishingBoat}. The captain needs a rowing boat which he can - * operate. The spec is in {@link RowingBoat}. We will use the Adapter pattern to reuse {@link - * FishingBoat}. + *

The story of this implementation is this.
+ * Pirates are coming! we need a {@link RowingBoat} to flee! We have a {@link FishingBoat} and our + * captain. We have no time to make up a new ship! we need to reuse this {@link FishingBoat}. The + * captain needs a rowing boat which he can operate. The spec is in {@link RowingBoat}. We will use + * the Adapter pattern to reuse {@link FishingBoat}. */ public final class App { - private App() { - } + private App() {} /** * Program entry point. diff --git a/adapter/src/main/java/com/iluwatar/adapter/Captain.java b/adapter/src/main/java/com/iluwatar/adapter/Captain.java index 3d6d7746d..3b771e9d8 100644 --- a/adapter/src/main/java/com/iluwatar/adapter/Captain.java +++ b/adapter/src/main/java/com/iluwatar/adapter/Captain.java @@ -29,7 +29,8 @@ import lombok.NoArgsConstructor; import lombok.Setter; /** - * The Captain uses {@link RowingBoat} to sail.
This is the client in the pattern. + * The Captain uses {@link RowingBoat} to sail.
+ * This is the client in the pattern. */ @Setter @NoArgsConstructor @@ -41,5 +42,4 @@ public final class Captain { void row() { rowingBoat.row(); } - } diff --git a/adapter/src/main/java/com/iluwatar/adapter/FishingBoat.java b/adapter/src/main/java/com/iluwatar/adapter/FishingBoat.java index e692d8598..dd39f88f1 100644 --- a/adapter/src/main/java/com/iluwatar/adapter/FishingBoat.java +++ b/adapter/src/main/java/com/iluwatar/adapter/FishingBoat.java @@ -36,5 +36,4 @@ final class FishingBoat { void sail() { LOGGER.info("The fishing boat is sailing"); } - } diff --git a/adapter/src/main/java/com/iluwatar/adapter/RowingBoat.java b/adapter/src/main/java/com/iluwatar/adapter/RowingBoat.java index c8714ef91..55eeeaf4b 100644 --- a/adapter/src/main/java/com/iluwatar/adapter/RowingBoat.java +++ b/adapter/src/main/java/com/iluwatar/adapter/RowingBoat.java @@ -25,10 +25,10 @@ package com.iluwatar.adapter; /** - * The interface expected by the client.
A rowing boat is rowed to move. + * The interface expected by the client.
+ * A rowing boat is rowed to move. */ public interface RowingBoat { void row(); - } diff --git a/adapter/src/test/java/com/iluwatar/adapter/AdapterPatternTest.java b/adapter/src/test/java/com/iluwatar/adapter/AdapterPatternTest.java index 10024ff0d..bc4984da3 100644 --- a/adapter/src/test/java/com/iluwatar/adapter/AdapterPatternTest.java +++ b/adapter/src/test/java/com/iluwatar/adapter/AdapterPatternTest.java @@ -24,17 +24,15 @@ */ package com.iluwatar.adapter; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import java.util.HashMap; -import java.util.Map; - import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; -/** - * Tests for the adapter pattern. - */ +import java.util.HashMap; +import java.util.Map; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** Tests for the adapter pattern. */ class AdapterPatternTest { private Map beans; @@ -43,9 +41,7 @@ class AdapterPatternTest { private static final String ROWING_BEAN = "captain"; - /** - * This method runs before the test execution and sets the bean objects in the beans Map. - */ + /** This method runs before the test execution and sets the bean objects in the beans Map. */ @BeforeEach void setup() { beans = new HashMap<>(); diff --git a/adapter/src/test/java/com/iluwatar/adapter/AppTest.java b/adapter/src/test/java/com/iluwatar/adapter/AppTest.java index be51d2687..a2cc4c22b 100644 --- a/adapter/src/test/java/com/iluwatar/adapter/AppTest.java +++ b/adapter/src/test/java/com/iluwatar/adapter/AppTest.java @@ -24,23 +24,17 @@ */ package com.iluwatar.adapter; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -/** - * Tests that Adapter example runs without errors. - */ +import org.junit.jupiter.api.Test; + +/** Tests that Adapter example runs without errors. */ class AppTest { - /** - * Check whether the execution of the main method in {@link App} - * throws an exception. - */ - + /** Check whether the execution of the main method in {@link App} throws an exception. */ @Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/ambassador/pom.xml b/ambassador/pom.xml index a6d702426..15e4a07f0 100644 --- a/ambassador/pom.xml +++ b/ambassador/pom.xml @@ -34,6 +34,14 @@ 4.0.0 ambassador + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/ambassador/src/main/java/com/iluwatar/ambassador/App.java b/ambassador/src/main/java/com/iluwatar/ambassador/App.java index ff025d9b2..8de149fe0 100644 --- a/ambassador/src/main/java/com/iluwatar/ambassador/App.java +++ b/ambassador/src/main/java/com/iluwatar/ambassador/App.java @@ -28,8 +28,8 @@ package com.iluwatar.ambassador; * The ambassador pattern creates a helper service that sends network requests on behalf of a * client. It is often used in cloud-based applications to offload features of a remote service. * - *

An ambassador service can be thought of as an out-of-process proxy that is co-located with - * the client. Similar to the proxy design pattern, the ambassador service provides an interface for + *

An ambassador service can be thought of as an out-of-process proxy that is co-located with the + * client. Similar to the proxy design pattern, the ambassador service provides an interface for * another remote service. In addition to the interface, the ambassador provides extra functionality * and features, specifically offloaded common connectivity tasks. This usually consists of * monitoring, logging, routing, security etc. This is extremely useful in legacy applications where @@ -37,14 +37,11 @@ package com.iluwatar.ambassador; * capabilities. * *

In this example, we will the ({@link ServiceAmbassador}) class represents the ambassador while - * the - * ({@link RemoteService}) class represents a remote application. + * the ({@link RemoteService}) class represents a remote application. */ public class App { - /** - * Entry point. - */ + /** Entry point. */ public static void main(String[] args) { var host1 = new Client(); var host2 = new Client(); diff --git a/ambassador/src/main/java/com/iluwatar/ambassador/Client.java b/ambassador/src/main/java/com/iluwatar/ambassador/Client.java index d0f81c1dd..0baabf4ff 100644 --- a/ambassador/src/main/java/com/iluwatar/ambassador/Client.java +++ b/ambassador/src/main/java/com/iluwatar/ambassador/Client.java @@ -26,9 +26,7 @@ package com.iluwatar.ambassador; import lombok.extern.slf4j.Slf4j; -/** - * A simple Client. - */ +/** A simple Client. */ @Slf4j public class Client { diff --git a/ambassador/src/main/java/com/iluwatar/ambassador/RemoteService.java b/ambassador/src/main/java/com/iluwatar/ambassador/RemoteService.java index eba634494..d99348040 100644 --- a/ambassador/src/main/java/com/iluwatar/ambassador/RemoteService.java +++ b/ambassador/src/main/java/com/iluwatar/ambassador/RemoteService.java @@ -29,9 +29,7 @@ import static java.lang.Thread.sleep; import com.iluwatar.ambassador.util.RandomProvider; import lombok.extern.slf4j.Slf4j; -/** - * A remote legacy application represented by a Singleton implementation. - */ +/** A remote legacy application represented by a Singleton implementation. */ @Slf4j public class RemoteService implements RemoteServiceInterface { private static final int THRESHOLD = 200; @@ -49,9 +47,7 @@ public class RemoteService implements RemoteServiceInterface { this(Math::random); } - /** - * This constructor is used for testing purposes only. - */ + /** This constructor is used for testing purposes only. */ RemoteService(RandomProvider randomProvider) { this.randomProvider = randomProvider; } @@ -75,7 +71,8 @@ public class RemoteService implements RemoteServiceInterface { LOGGER.error("Thread sleep state interrupted", e); Thread.currentThread().interrupt(); } - return waitTime <= THRESHOLD ? value * 10 + return waitTime <= THRESHOLD + ? value * 10 : RemoteServiceStatus.FAILURE.getRemoteServiceStatusValue(); } } diff --git a/ambassador/src/main/java/com/iluwatar/ambassador/RemoteServiceInterface.java b/ambassador/src/main/java/com/iluwatar/ambassador/RemoteServiceInterface.java index 104d81ec2..aa6012bae 100644 --- a/ambassador/src/main/java/com/iluwatar/ambassador/RemoteServiceInterface.java +++ b/ambassador/src/main/java/com/iluwatar/ambassador/RemoteServiceInterface.java @@ -24,9 +24,7 @@ */ package com.iluwatar.ambassador; -/** - * Interface shared by ({@link RemoteService}) and ({@link ServiceAmbassador}). - */ +/** Interface shared by ({@link RemoteService}) and ({@link ServiceAmbassador}). */ interface RemoteServiceInterface { long doRemoteFunction(int value); diff --git a/ambassador/src/main/java/com/iluwatar/ambassador/RemoteServiceStatus.java b/ambassador/src/main/java/com/iluwatar/ambassador/RemoteServiceStatus.java index 8f1a0a1a4..8549ed724 100644 --- a/ambassador/src/main/java/com/iluwatar/ambassador/RemoteServiceStatus.java +++ b/ambassador/src/main/java/com/iluwatar/ambassador/RemoteServiceStatus.java @@ -29,17 +29,14 @@ import lombok.Getter; /** * Holds information regarding the status of the Remote Service. * - *

This Enum replaces the integer value previously - * stored in {@link RemoteServiceInterface} as SonarCloud was identifying - * it as an issue. All test cases have been checked after changes, - * without failures.

+ *

This Enum replaces the integer value previously stored in {@link RemoteServiceInterface} as + * SonarCloud was identifying it as an issue. All test cases have been checked after changes, + * without failures. */ - public enum RemoteServiceStatus { FAILURE(-1); - @Getter - private final long remoteServiceStatusValue; + @Getter private final long remoteServiceStatusValue; RemoteServiceStatus(long remoteServiceStatusValue) { this.remoteServiceStatusValue = remoteServiceStatusValue; diff --git a/ambassador/src/main/java/com/iluwatar/ambassador/ServiceAmbassador.java b/ambassador/src/main/java/com/iluwatar/ambassador/ServiceAmbassador.java index f3f30a09d..4d3101697 100644 --- a/ambassador/src/main/java/com/iluwatar/ambassador/ServiceAmbassador.java +++ b/ambassador/src/main/java/com/iluwatar/ambassador/ServiceAmbassador.java @@ -40,8 +40,7 @@ public class ServiceAmbassador implements RemoteServiceInterface { private static final int RETRIES = 3; private static final int DELAY_MS = 3000; - ServiceAmbassador() { - } + ServiceAmbassador() {} @Override public long doRemoteFunction(int value) { diff --git a/ambassador/src/main/java/com/iluwatar/ambassador/util/RandomProvider.java b/ambassador/src/main/java/com/iluwatar/ambassador/util/RandomProvider.java index e8243cdcc..4eba2fada 100644 --- a/ambassador/src/main/java/com/iluwatar/ambassador/util/RandomProvider.java +++ b/ambassador/src/main/java/com/iluwatar/ambassador/util/RandomProvider.java @@ -24,9 +24,7 @@ */ package com.iluwatar.ambassador.util; -/** - * An interface for randomness. Useful for testing purposes. - */ +/** An interface for randomness. Useful for testing purposes. */ public interface RandomProvider { double random(); } diff --git a/ambassador/src/test/java/com/iluwatar/ambassador/AppTest.java b/ambassador/src/test/java/com/iluwatar/ambassador/AppTest.java index cea0eeac7..ddb2d6eff 100644 --- a/ambassador/src/test/java/com/iluwatar/ambassador/AppTest.java +++ b/ambassador/src/test/java/com/iluwatar/ambassador/AppTest.java @@ -24,25 +24,22 @@ */ package com.iluwatar.ambassador; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -/** - * Application test - */ +import org.junit.jupiter.api.Test; + +/** Application test */ class AppTest { /** * Issue: Add at least one assertion to this test case. * - * Solution: Inserted assertion to check whether the execution of the main method in {@link App} - * throws an exception. + *

Solution: Inserted assertion to check whether the execution of the main method in {@link + * App} throws an exception. */ - @Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/ambassador/src/test/java/com/iluwatar/ambassador/ClientTest.java b/ambassador/src/test/java/com/iluwatar/ambassador/ClientTest.java index ff7f027f6..24603efff 100644 --- a/ambassador/src/test/java/com/iluwatar/ambassador/ClientTest.java +++ b/ambassador/src/test/java/com/iluwatar/ambassador/ClientTest.java @@ -24,13 +24,11 @@ */ package com.iluwatar.ambassador; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertTrue; -/** - * Test for {@link Client} - */ +import org.junit.jupiter.api.Test; + +/** Test for {@link Client} */ class ClientTest { @Test @@ -38,6 +36,7 @@ class ClientTest { Client client = new Client(); var result = client.useService(10); - assertTrue(result == 100 || result == RemoteServiceStatus.FAILURE.getRemoteServiceStatusValue()); + assertTrue( + result == 100 || result == RemoteServiceStatus.FAILURE.getRemoteServiceStatusValue()); } } diff --git a/ambassador/src/test/java/com/iluwatar/ambassador/RemoteServiceTest.java b/ambassador/src/test/java/com/iluwatar/ambassador/RemoteServiceTest.java index 5fed19a16..81e4f7441 100644 --- a/ambassador/src/test/java/com/iluwatar/ambassador/RemoteServiceTest.java +++ b/ambassador/src/test/java/com/iluwatar/ambassador/RemoteServiceTest.java @@ -29,9 +29,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import com.iluwatar.ambassador.util.RandomProvider; import org.junit.jupiter.api.Test; -/** - * Test for {@link RemoteService} - */ +/** Test for {@link RemoteService} */ class RemoteServiceTest { @Test diff --git a/ambassador/src/test/java/com/iluwatar/ambassador/ServiceAmbassadorTest.java b/ambassador/src/test/java/com/iluwatar/ambassador/ServiceAmbassadorTest.java index 50c354c14..0543b2e7e 100644 --- a/ambassador/src/test/java/com/iluwatar/ambassador/ServiceAmbassadorTest.java +++ b/ambassador/src/test/java/com/iluwatar/ambassador/ServiceAmbassadorTest.java @@ -24,18 +24,17 @@ */ package com.iluwatar.ambassador; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertTrue; -/** - * Test for {@link ServiceAmbassador} - */ +import org.junit.jupiter.api.Test; + +/** Test for {@link ServiceAmbassador} */ class ServiceAmbassadorTest { @Test void test() { long result = new ServiceAmbassador().doRemoteFunction(10); - assertTrue(result == 100 || result == RemoteServiceStatus.FAILURE.getRemoteServiceStatusValue()); + assertTrue( + result == 100 || result == RemoteServiceStatus.FAILURE.getRemoteServiceStatusValue()); } } diff --git a/anti-corruption-layer/pom.xml b/anti-corruption-layer/pom.xml index 711e006b7..2fddfd3ec 100644 --- a/anti-corruption-layer/pom.xml +++ b/anti-corruption-layer/pom.xml @@ -45,8 +45,8 @@ test - junit - junit + org.junit.jupiter + junit-jupiter-engine test diff --git a/anti-corruption-layer/src/main/java/com/iluwatar/corruption/App.java b/anti-corruption-layer/src/main/java/com/iluwatar/corruption/App.java index ce2dbffd6..f7cf8f075 100644 --- a/anti-corruption-layer/src/main/java/com/iluwatar/corruption/App.java +++ b/anti-corruption-layer/src/main/java/com/iluwatar/corruption/App.java @@ -28,9 +28,8 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** - * This layer translates communications between the two systems, - * allowing one system to remain unchanged while the other can avoid compromising - * its design and technological approach. + * This layer translates communications between the two systems, allowing one system to remain + * unchanged while the other can avoid compromising its design and technological approach. */ @SpringBootApplication public class App { diff --git a/anti-corruption-layer/src/main/java/com/iluwatar/corruption/package-info.java b/anti-corruption-layer/src/main/java/com/iluwatar/corruption/package-info.java index c8f72fca4..880d98c7d 100644 --- a/anti-corruption-layer/src/main/java/com/iluwatar/corruption/package-info.java +++ b/anti-corruption-layer/src/main/java/com/iluwatar/corruption/package-info.java @@ -23,30 +23,26 @@ * THE SOFTWARE. */ /** - * Context and problem - * Most applications rely on other systems for some data or functionality. - * For example, when a legacy application is migrated to a modern system, - * it may still need existing legacy resources. New features must be able to call the legacy system. - * This is especially true of gradual migrations, - * where different features of a larger application are moved to a modern system over time. + * Context and problem Most applications rely on other systems for some data or functionality. For + * example, when a legacy application is migrated to a modern system, it may still need existing + * legacy resources. New features must be able to call the legacy system. This is especially true of + * gradual migrations, where different features of a larger application are moved to a modern system + * over time. * - *

Often these legacy systems suffer from quality issues such as convoluted data schemas - * or obsolete APIs. - * The features and technologies used in legacy systems can vary widely from more modern systems. - * To interoperate with the legacy system, - * the new application may need to support outdated infrastructure, protocols, data models, APIs, - * or other features that you wouldn't otherwise put into a modern application. + *

Often these legacy systems suffer from quality issues such as convoluted data schemas or + * obsolete APIs. The features and technologies used in legacy systems can vary widely from more + * modern systems. To interoperate with the legacy system, the new application may need to support + * outdated infrastructure, protocols, data models, APIs, or other features that you wouldn't + * otherwise put into a modern application. * - *

Maintaining access between new and legacy systems can force the new system to adhere to - * at least some of the legacy system's APIs or other semantics. - * When these legacy features have quality issues, supporting them "corrupts" what might - * otherwise be a cleanly designed modern application. - * Similar issues can arise with any external system that your development team doesn't control, - * not just legacy systems. + *

Maintaining access between new and legacy systems can force the new system to adhere to at + * least some of the legacy system's APIs or other semantics. When these legacy features have + * quality issues, supporting them "corrupts" what might otherwise be a cleanly designed modern + * application. Similar issues can arise with any external system that your development team doesn't + * control, not just legacy systems. * *

Solution Isolate the different subsystems by placing an anti-corruption layer between them. - * This layer translates communications between the two systems, - * allowing one system to remain unchanged while the other can avoid compromising - * its design and technological approach. + * This layer translates communications between the two systems, allowing one system to remain + * unchanged while the other can avoid compromising its design and technological approach. */ package com.iluwatar.corruption; diff --git a/anti-corruption-layer/src/main/java/com/iluwatar/corruption/system/AntiCorruptionLayer.java b/anti-corruption-layer/src/main/java/com/iluwatar/corruption/system/AntiCorruptionLayer.java index fae658ee5..4e8a17fa5 100644 --- a/anti-corruption-layer/src/main/java/com/iluwatar/corruption/system/AntiCorruptionLayer.java +++ b/anti-corruption-layer/src/main/java/com/iluwatar/corruption/system/AntiCorruptionLayer.java @@ -33,36 +33,34 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** - * The class represents an anti-corruption layer. - * The main purpose of the class is to provide a layer between the modern and legacy systems. - * The class is responsible for converting the data from one system to another - * decoupling the systems to each other + * The class represents an anti-corruption layer. The main purpose of the class is to provide a + * layer between the modern and legacy systems. The class is responsible for converting the data + * from one system to another decoupling the systems to each other * - *

It allows using one system a domain model of the other system - * without changing the domain model of the system. + *

It allows using one system a domain model of the other system without changing the domain + * model of the system. */ @Service public class AntiCorruptionLayer { - @Autowired - private LegacyShop legacyShop; - + @Autowired private LegacyShop legacyShop; /** * The method converts the order from the legacy system to the modern system. + * * @param id the id of the order * @return the order in the modern system */ public Optional findOrderInLegacySystem(String id) { - return legacyShop.findOrder(id).map(o -> - new ModernOrder( - o.getId(), - new Customer(o.getCustomer()), - new Shipment(o.getItem(), o.getQty(), o.getPrice()), - "" - ) - ); + return legacyShop + .findOrder(id) + .map( + o -> + new ModernOrder( + o.getId(), + new Customer(o.getCustomer()), + new Shipment(o.getItem(), o.getQty(), o.getPrice()), + "")); } - } diff --git a/anti-corruption-layer/src/main/java/com/iluwatar/corruption/system/DataStore.java b/anti-corruption-layer/src/main/java/com/iluwatar/corruption/system/DataStore.java index e9fdaa14e..e84578528 100644 --- a/anti-corruption-layer/src/main/java/com/iluwatar/corruption/system/DataStore.java +++ b/anti-corruption-layer/src/main/java/com/iluwatar/corruption/system/DataStore.java @@ -29,6 +29,7 @@ import java.util.Optional; /** * The class represents a data store for the modern system. + * * @param the type of the value stored in the data store */ public abstract class DataStore { @@ -44,6 +45,5 @@ public abstract class DataStore { public Optional put(String key, V value) { return Optional.ofNullable(inner.put(key, value)); - } } diff --git a/anti-corruption-layer/src/main/java/com/iluwatar/corruption/system/ShopException.java b/anti-corruption-layer/src/main/java/com/iluwatar/corruption/system/ShopException.java index 103fcfccd..c0acd288e 100644 --- a/anti-corruption-layer/src/main/java/com/iluwatar/corruption/system/ShopException.java +++ b/anti-corruption-layer/src/main/java/com/iluwatar/corruption/system/ShopException.java @@ -24,9 +24,7 @@ */ package com.iluwatar.corruption.system; -/** - * The class represents a general exception for the shop. - */ +/** The class represents a general exception for the shop. */ public class ShopException extends Exception { public ShopException(String message) { super(message); @@ -41,9 +39,12 @@ public class ShopException extends Exception { * @throws ShopException the exception */ public static ShopException throwIncorrectData(String lhs, String rhs) throws ShopException { - throw new ShopException("The order is already placed but has an incorrect data:\n" - + "Incoming order: " + lhs + "\n" - + "Existing order: " + rhs); + throw new ShopException( + "The order is already placed but has an incorrect data:\n" + + "Incoming order: " + + lhs + + "\n" + + "Existing order: " + + rhs); } - } diff --git a/anti-corruption-layer/src/main/java/com/iluwatar/corruption/system/legacy/LegacyOrder.java b/anti-corruption-layer/src/main/java/com/iluwatar/corruption/system/legacy/LegacyOrder.java index 2481d19c8..45faa06cb 100644 --- a/anti-corruption-layer/src/main/java/com/iluwatar/corruption/system/legacy/LegacyOrder.java +++ b/anti-corruption-layer/src/main/java/com/iluwatar/corruption/system/legacy/LegacyOrder.java @@ -28,8 +28,8 @@ import lombok.AllArgsConstructor; import lombok.Data; /** - * The class represents an order in the legacy system. - * The class is used by the legacy system to store the data. + * The class represents an order in the legacy system. The class is used by the legacy system to + * store the data. */ @Data @AllArgsConstructor diff --git a/anti-corruption-layer/src/main/java/com/iluwatar/corruption/system/legacy/LegacyStore.java b/anti-corruption-layer/src/main/java/com/iluwatar/corruption/system/legacy/LegacyStore.java index b29b71d87..ec1d613a7 100644 --- a/anti-corruption-layer/src/main/java/com/iluwatar/corruption/system/legacy/LegacyStore.java +++ b/anti-corruption-layer/src/main/java/com/iluwatar/corruption/system/legacy/LegacyStore.java @@ -28,10 +28,8 @@ import com.iluwatar.corruption.system.DataStore; import org.springframework.stereotype.Service; /** - * The class represents a data store for the legacy system. - * The class is used by the legacy system to store the data. + * The class represents a data store for the legacy system. The class is used by the legacy system + * to store the data. */ @Service -public class LegacyStore extends DataStore { -} - +public class LegacyStore extends DataStore {} diff --git a/anti-corruption-layer/src/main/java/com/iluwatar/corruption/system/modern/Customer.java b/anti-corruption-layer/src/main/java/com/iluwatar/corruption/system/modern/Customer.java index dd3351415..130f36d39 100644 --- a/anti-corruption-layer/src/main/java/com/iluwatar/corruption/system/modern/Customer.java +++ b/anti-corruption-layer/src/main/java/com/iluwatar/corruption/system/modern/Customer.java @@ -27,9 +27,7 @@ package com.iluwatar.corruption.system.modern; import lombok.AllArgsConstructor; import lombok.Data; -/** - * The class represents a customer in the modern system. - */ +/** The class represents a customer in the modern system. */ @Data @AllArgsConstructor public class Customer { diff --git a/anti-corruption-layer/src/main/java/com/iluwatar/corruption/system/modern/ModernOrder.java b/anti-corruption-layer/src/main/java/com/iluwatar/corruption/system/modern/ModernOrder.java index 94c4f57b9..7b6298501 100644 --- a/anti-corruption-layer/src/main/java/com/iluwatar/corruption/system/modern/ModernOrder.java +++ b/anti-corruption-layer/src/main/java/com/iluwatar/corruption/system/modern/ModernOrder.java @@ -27,9 +27,7 @@ package com.iluwatar.corruption.system.modern; import lombok.AllArgsConstructor; import lombok.Data; -/** - * The class represents an order in the modern system. - */ +/** The class represents an order in the modern system. */ @Data @AllArgsConstructor public class ModernOrder { @@ -39,6 +37,4 @@ public class ModernOrder { private Shipment shipment; private String extra; - - } diff --git a/anti-corruption-layer/src/main/java/com/iluwatar/corruption/system/modern/ModernShop.java b/anti-corruption-layer/src/main/java/com/iluwatar/corruption/system/modern/ModernShop.java index 45cd355be..24080abe1 100644 --- a/anti-corruption-layer/src/main/java/com/iluwatar/corruption/system/modern/ModernShop.java +++ b/anti-corruption-layer/src/main/java/com/iluwatar/corruption/system/modern/ModernShop.java @@ -31,20 +31,18 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** - * The class represents a modern shop system. - * The main purpose of the class is to place orders and find orders. + * The class represents a modern shop system. The main purpose of the class is to place orders and + * find orders. */ @Service public class ModernShop { - @Autowired - private ModernStore store; + @Autowired private ModernStore store; - @Autowired - private AntiCorruptionLayer acl; + @Autowired private AntiCorruptionLayer acl; /** - * Places the order in the modern system. - * If the order is already present in the legacy system, then no need to place it again. + * Places the order in the modern system. If the order is already present in the legacy system, + * then no need to place it again. */ public void placeOrder(ModernOrder order) throws ShopException { @@ -62,9 +60,7 @@ public class ModernShop { } } - /** - * Finds the order in the modern system. - */ + /** Finds the order in the modern system. */ public Optional findOrder(String orderId) { return store.get(orderId); } diff --git a/anti-corruption-layer/src/main/java/com/iluwatar/corruption/system/modern/ModernStore.java b/anti-corruption-layer/src/main/java/com/iluwatar/corruption/system/modern/ModernStore.java index 4ec4d7dbc..4fb3952fa 100644 --- a/anti-corruption-layer/src/main/java/com/iluwatar/corruption/system/modern/ModernStore.java +++ b/anti-corruption-layer/src/main/java/com/iluwatar/corruption/system/modern/ModernStore.java @@ -27,10 +27,6 @@ package com.iluwatar.corruption.system.modern; import com.iluwatar.corruption.system.DataStore; import org.springframework.stereotype.Service; -/** - * The class represents a data store for the modern system. - */ +/** The class represents a data store for the modern system. */ @Service -public class ModernStore extends DataStore { -} - +public class ModernStore extends DataStore {} diff --git a/anti-corruption-layer/src/main/java/com/iluwatar/corruption/system/modern/Shipment.java b/anti-corruption-layer/src/main/java/com/iluwatar/corruption/system/modern/Shipment.java index 292c0d8e3..085a3921c 100644 --- a/anti-corruption-layer/src/main/java/com/iluwatar/corruption/system/modern/Shipment.java +++ b/anti-corruption-layer/src/main/java/com/iluwatar/corruption/system/modern/Shipment.java @@ -28,8 +28,8 @@ import lombok.AllArgsConstructor; import lombok.Data; /** - * The class represents a shipment in the modern system. - * The class is used by the modern system to store the data. + * The class represents a shipment in the modern system. The class is used by the modern system to + * store the data. */ @Data @AllArgsConstructor diff --git a/anti-corruption-layer/src/test/java/com/iluwatar/corruption/system/AntiCorruptionLayerTest.java b/anti-corruption-layer/src/test/java/com/iluwatar/corruption/system/AntiCorruptionLayerTest.java index ba24c8981..ee46d124e 100644 --- a/anti-corruption-layer/src/test/java/com/iluwatar/corruption/system/AntiCorruptionLayerTest.java +++ b/anti-corruption-layer/src/test/java/com/iluwatar/corruption/system/AntiCorruptionLayerTest.java @@ -24,88 +24,73 @@ */ package com.iluwatar.corruption.system; +import static org.junit.jupiter.api.Assertions.*; + import com.iluwatar.corruption.system.legacy.LegacyOrder; import com.iluwatar.corruption.system.legacy.LegacyShop; import com.iluwatar.corruption.system.modern.Customer; import com.iluwatar.corruption.system.modern.ModernOrder; import com.iluwatar.corruption.system.modern.ModernShop; import com.iluwatar.corruption.system.modern.Shipment; -import org.junit.Test; -import org.junit.runner.RunWith; +import java.util.Optional; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; -import java.util.Optional; - -import static org.junit.jupiter.api.Assertions.*; - -@RunWith(SpringRunner.class) +@ExtendWith(SpringExtension.class) @SpringBootTest public class AntiCorruptionLayerTest { - @Autowired - private LegacyShop legacyShop; + @Autowired private LegacyShop legacyShop; - @Autowired - private ModernShop modernShop; + @Autowired private ModernShop modernShop; + /** + * Test the anti-corruption layer. Main intention is to demonstrate how the anti-corruption layer + * works. The 2 shops (modern and legacy) should operate independently and in the same time + * synchronize the data. + */ + @Test + public void antiCorruptionLayerTest() throws ShopException { + // a new order comes to the legacy shop. + LegacyOrder legacyOrder = new LegacyOrder("1", "addr1", "item1", 1, 1); + // place the order in the legacy shop. + legacyShop.placeOrder(legacyOrder); + // the order is placed as usual since there is no other orders with the id in the both systems. + Optional legacyOrderWithIdOne = legacyShop.findOrder("1"); + assertEquals(Optional.of(legacyOrder), legacyOrderWithIdOne); - /** - * Test the anti-corruption layer. - * Main intention is to demonstrate how the anti-corruption layer works. - *

- * The 2 shops (modern and legacy) should operate independently and in the same time synchronize the data. - * To avoid corrupting the domain models of the 2 shops, we use an anti-corruption layer - * that transforms one model to another under the hood. - * - */ - @Test - public void antiCorruptionLayerTest() throws ShopException { + // a new order (or maybe just the same order) appears in the modern shop + ModernOrder modernOrder = + new ModernOrder("1", new Customer("addr1"), new Shipment("item1", 1, 1), ""); + // the system places it, but it checks if there is an order with the same id in the legacy shop. + modernShop.placeOrder(modernOrder); - // a new order comes to the legacy shop. - LegacyOrder legacyOrder = new LegacyOrder("1", "addr1", "item1", 1, 1); - // place the order in the legacy shop. - legacyShop.placeOrder(legacyOrder); - // the order is placed as usual since there is no other orders with the id in the both systems. - Optional legacyOrderWithIdOne = legacyShop.findOrder("1"); - assertEquals(Optional.of(legacyOrder), legacyOrderWithIdOne); + Optional modernOrderWithIdOne = modernShop.findOrder("1"); + // there is no new order placed since there is already an order with the same id in the legacy + // shop. + assertTrue(modernOrderWithIdOne.isEmpty()); + } - // a new order (or maybe just the same order) appears in the modern shop. - ModernOrder modernOrder = new ModernOrder("1", new Customer("addr1"), new Shipment("item1", 1, 1), ""); - - // the system places it, but it checks if there is an order with the same id in the legacy shop. - modernShop.placeOrder(modernOrder); - - Optional modernOrderWithIdOne = modernShop.findOrder("1"); - // there is no new order placed since there is already an order with the same id in the legacy shop. - assertTrue(modernOrderWithIdOne.isEmpty()); - - } - /** - * Test the anti-corruption layer. - * Main intention is to demonstrate how the anti-corruption layer works. - *

- * This test tests the anti-corruption layer from the rule the orders should be the same in the both systems. - * - */ - @Test(expected = ShopException.class) - public void antiCorruptionLayerWithExTest() throws ShopException { - - // a new order comes to the legacy shop. - LegacyOrder legacyOrder = new LegacyOrder("1", "addr1", "item1", 1, 1); - // place the order in the legacy shop. - legacyShop.placeOrder(legacyOrder); - // the order is placed as usual since there is no other orders with the id in the both systems. - Optional legacyOrderWithIdOne = legacyShop.findOrder("1"); - assertEquals(Optional.of(legacyOrder), legacyOrderWithIdOne); - - // a new order but with the same id and different data appears in the modern shop - ModernOrder modernOrder = new ModernOrder("1", new Customer("addr1"), new Shipment("item1", 10, 1), ""); - - // the system rejects the order since there are 2 orders with contradiction there. - modernShop.placeOrder(modernOrder); - - - } -} \ No newline at end of file + /** + * Test the anti-corruption layer when a conflict occurs between systems. This test ensures that + * an exception is thrown when conflicting orders are placed. + */ + @Test + public void antiCorruptionLayerWithExTest() throws ShopException { + // a new order comes to the legacy shop. + LegacyOrder legacyOrder = new LegacyOrder("1", "addr1", "item1", 1, 1); + // place the order in the legacy shop. + legacyShop.placeOrder(legacyOrder); + // the order is placed as usual since there is no other orders with the id in the both systems. + Optional legacyOrderWithIdOne = legacyShop.findOrder("1"); + assertEquals(Optional.of(legacyOrder), legacyOrderWithIdOne); + // a new order but with the same id and different data appears in the modern shop + ModernOrder modernOrder = + new ModernOrder("1", new Customer("addr1"), new Shipment("item1", 10, 1), ""); + // the system rejects the order since there are 2 orders with contradiction there. + assertThrows(ShopException.class, () -> modernShop.placeOrder(modernOrder)); + } +} diff --git a/arrange-act-assert/src/main/java/com/iluwatar/arrangeactassert/Cash.java b/arrange-act-assert/src/main/java/com/iluwatar/arrangeactassert/Cash.java index c3f5e6fe4..0c31b1f89 100644 --- a/arrange-act-assert/src/main/java/com/iluwatar/arrangeactassert/Cash.java +++ b/arrange-act-assert/src/main/java/com/iluwatar/arrangeactassert/Cash.java @@ -35,12 +35,12 @@ public class Cash { private int amount; - //plus + // plus void plus(int addend) { amount += addend; } - //minus + // minus boolean minus(int subtrahend) { if (amount >= subtrahend) { amount -= subtrahend; @@ -50,7 +50,7 @@ public class Cash { } } - //count + // count int count() { return amount; } diff --git a/arrange-act-assert/src/test/java/com/iluwatar/arrangeactassert/CashAAATest.java b/arrange-act-assert/src/test/java/com/iluwatar/arrangeactassert/CashAAATest.java index b771cb6e7..ebb261277 100644 --- a/arrange-act-assert/src/test/java/com/iluwatar/arrangeactassert/CashAAATest.java +++ b/arrange-act-assert/src/test/java/com/iluwatar/arrangeactassert/CashAAATest.java @@ -35,8 +35,11 @@ import org.junit.jupiter.api.Test; * tests, so they're easier to read, maintain and enhance. * *

It breaks tests down into three clear and distinct steps: + * *

1. Arrange: Perform the setup and initialization required for the test. + * *

2. Act: Take action(s) required for the test. + * *

3. Assert: Verify the outcome(s) of the test. * *

This pattern has several significant benefits. It creates a clear separation between a test's @@ -48,53 +51,52 @@ import org.junit.jupiter.api.Test; * clearly about the three steps your test will perform. But it makes tests more natural to write at * the same time since you already have an outline. * - *

In ({@link CashAAATest}) we have four test methods. Each of them has only one reason to - * change and one reason to fail. In a large and complicated code base, tests that honor the single + *

In ({@link CashAAATest}) we have four test methods. Each of them has only one reason to change + * and one reason to fail. In a large and complicated code base, tests that honor the single * responsibility principle are much easier to troubleshoot. */ - class CashAAATest { @Test void testPlus() { - //Arrange + // Arrange var cash = new Cash(3); - //Act + // Act cash.plus(4); - //Assert + // Assert assertEquals(7, cash.count()); } @Test void testMinus() { - //Arrange + // Arrange var cash = new Cash(8); - //Act + // Act var result = cash.minus(5); - //Assert + // Assert assertTrue(result); assertEquals(3, cash.count()); } @Test void testInsufficientMinus() { - //Arrange + // Arrange var cash = new Cash(1); - //Act + // Act var result = cash.minus(6); - //Assert + // Assert assertFalse(result); assertEquals(1, cash.count()); } @Test void testUpdate() { - //Arrange + // Arrange var cash = new Cash(5); - //Act + // Act cash.plus(6); var result = cash.minus(3); - //Assert + // Assert assertTrue(result); assertEquals(8, cash.count()); } diff --git a/arrange-act-assert/src/test/java/com/iluwatar/arrangeactassert/CashAntiAAATest.java b/arrange-act-assert/src/test/java/com/iluwatar/arrangeactassert/CashAntiAAATest.java index 142fd623a..575682251 100644 --- a/arrange-act-assert/src/test/java/com/iluwatar/arrangeactassert/CashAntiAAATest.java +++ b/arrange-act-assert/src/test/java/com/iluwatar/arrangeactassert/CashAntiAAATest.java @@ -37,23 +37,22 @@ import org.junit.jupiter.api.Test; * single responsibility principle. If this test method failed after a small code change, it might * take some digging to discover why. */ - class CashAntiAAATest { @Test void testCash() { - //initialize + // initialize var cash = new Cash(3); - //test plus + // test plus cash.plus(4); assertEquals(7, cash.count()); - //test minus + // test minus cash = new Cash(8); assertTrue(cash.minus(5)); assertEquals(3, cash.count()); assertFalse(cash.minus(6)); assertEquals(3, cash.count()); - //test update + // test update cash.plus(5); assertTrue(cash.minus(5)); assertEquals(3, cash.count()); diff --git a/async-method-invocation/pom.xml b/async-method-invocation/pom.xml index 52a03369f..d9ddd918c 100644 --- a/async-method-invocation/pom.xml +++ b/async-method-invocation/pom.xml @@ -34,6 +34,14 @@ async-method-invocation + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/App.java b/async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/App.java index 01fd8f1c6..ec3beed3b 100644 --- a/async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/App.java +++ b/async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/App.java @@ -30,15 +30,15 @@ import lombok.extern.slf4j.Slf4j; /** * In this example, we are launching space rockets and deploying lunar rovers. * - *

The application demonstrates the async method invocation pattern. The key parts of the - * pattern are AsyncResult which is an intermediate container for an asynchronously - * evaluated value, AsyncCallback which can be provided to be executed on task - * completion and AsyncExecutor that manages the execution of the async tasks. + *

The application demonstrates the async method invocation pattern. The key parts of the pattern + * are AsyncResult which is an intermediate container for an asynchronously evaluated + * value, AsyncCallback which can be provided to be executed on task completion and + * AsyncExecutor that manages the execution of the async tasks. * - *

The main method shows example flow of async invocations. The main thread starts multiple - * tasks with variable durations and then continues its own work. When the main thread has done it's - * job it collects the results of the async tasks. Two of the tasks are handled with callbacks, - * meaning the callbacks are executed immediately when the tasks complete. + *

The main method shows example flow of async invocations. The main thread starts multiple tasks + * with variable durations and then continues its own work. When the main thread has done it's job + * it collects the results of the async tasks. Two of the tasks are handled with callbacks, meaning + * the callbacks are executed immediately when the tasks complete. * *

Noteworthy difference of thread usage between the async results and callbacks is that the * async results are collected in the main thread but the callbacks are executed within the worker @@ -62,10 +62,7 @@ public class App { private static final String ROCKET_LAUNCH_LOG_PATTERN = "Space rocket <%s> launched successfully"; - /** - * Program entry point. - */ - + /** Program entry point. */ public static void main(String[] args) throws Exception { // construct a new executor that will run async tasks var executor = new ThreadAsyncExecutor(); @@ -74,8 +71,8 @@ public class App { final var asyncResult1 = executor.startProcess(lazyval(10, 500)); final var asyncResult2 = executor.startProcess(lazyval("test", 300)); final var asyncResult3 = executor.startProcess(lazyval(50L, 700)); - final var asyncResult4 = executor.startProcess(lazyval(20, 400), - callback("Deploying lunar rover")); + final var asyncResult4 = + executor.startProcess(lazyval(20, 400), callback("Deploying lunar rover")); final var asyncResult5 = executor.startProcess(lazyval("callback", 600), callback("Deploying lunar rover")); @@ -99,7 +96,7 @@ public class App { /** * Creates a callable that lazily evaluates to given value with artificial delay. * - * @param value value to evaluate + * @param value value to evaluate * @param delayMillis artificial delay in milliseconds * @return new callable for lazy evaluation */ diff --git a/async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/AsyncExecutor.java b/async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/AsyncExecutor.java index fcea6d071..3bae90830 100644 --- a/async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/AsyncExecutor.java +++ b/async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/AsyncExecutor.java @@ -27,9 +27,7 @@ package com.iluwatar.async.method.invocation; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; -/** - * AsyncExecutor interface. - */ +/** AsyncExecutor interface. */ public interface AsyncExecutor { /** @@ -44,7 +42,7 @@ public interface AsyncExecutor { * Starts processing of an async task. Returns immediately with async result. Executes callback * when the task is completed. * - * @param task task to be executed asynchronously + * @param task task to be executed asynchronously * @param callback callback to be executed on task completion * @return async result for the task */ @@ -56,7 +54,7 @@ public interface AsyncExecutor { * * @param asyncResult async result of a task * @return evaluated value of the completed task - * @throws ExecutionException if execution has failed, containing the root cause + * @throws ExecutionException if execution has failed, containing the root cause * @throws InterruptedException if the execution is interrupted */ T endProcess(AsyncResult asyncResult) throws ExecutionException, InterruptedException; 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 d71cf0def..3eebdc4e7 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 @@ -44,7 +44,7 @@ public interface AsyncResult { * Gets the value of completed async task. * * @return evaluated value or throws ExecutionException if execution has failed - * @throws ExecutionException if execution has failed, containing the root cause + * @throws ExecutionException if execution has failed, containing the root cause * @throws IllegalStateException if execution is not completed */ T getValue() throws ExecutionException; diff --git a/async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/ThreadAsyncExecutor.java b/async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/ThreadAsyncExecutor.java index f4a50e0d6..a1261f341 100644 --- a/async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/ThreadAsyncExecutor.java +++ b/async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/ThreadAsyncExecutor.java @@ -24,19 +24,14 @@ */ package com.iluwatar.async.method.invocation; -import java.util.Optional; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.atomic.AtomicInteger; -/** - * Implementation of async executor that creates a new thread for every task. - */ +/** Implementation of async executor that creates a new thread for every task. */ public class ThreadAsyncExecutor implements AsyncExecutor { - /** - * Index for thread naming. - */ + /** Index for thread naming. */ private final AtomicInteger idx = new AtomicInteger(0); @Override @@ -47,19 +42,22 @@ public class ThreadAsyncExecutor implements AsyncExecutor { @Override public AsyncResult startProcess(Callable task, AsyncCallback callback) { var result = new CompletableResult<>(callback); - new Thread(() -> { - try { - result.setValue(task.call()); - } catch (Exception ex) { - result.setException(ex); - } - }, "executor-" + idx.incrementAndGet()).start(); + new Thread( + () -> { + try { + result.setValue(task.call()); + } catch (Exception ex) { + result.setException(ex); + } + }, + "executor-" + idx.incrementAndGet()) + .start(); return result; } @Override - public T endProcess(AsyncResult asyncResult) throws ExecutionException, - InterruptedException { + public T endProcess(AsyncResult asyncResult) + throws ExecutionException, InterruptedException { if (!asyncResult.isCompleted()) { asyncResult.await(); } diff --git a/async-method-invocation/src/test/java/com/iluwatar/async/method/invocation/AppTest.java b/async-method-invocation/src/test/java/com/iluwatar/async/method/invocation/AppTest.java index f31c5549b..d58a3f6b5 100644 --- a/async-method-invocation/src/test/java/com/iluwatar/async/method/invocation/AppTest.java +++ b/async-method-invocation/src/test/java/com/iluwatar/async/method/invocation/AppTest.java @@ -24,26 +24,22 @@ */ package com.iluwatar.async.method.invocation; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -/** - * Application test - */ +import org.junit.jupiter.api.Test; + +/** Application test */ class AppTest { /** * Issue: Add at least one assertion to this test case. * - * Solution: Inserted assertion to check whether the execution of the main method in {@link App} - * throws an exception. + *

Solution: Inserted assertion to check whether the execution of the main method in {@link + * App} throws an exception. */ - @Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); - + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/async-method-invocation/src/test/java/com/iluwatar/async/method/invocation/ThreadAsyncExecutorTest.java b/async-method-invocation/src/test/java/com/iluwatar/async/method/invocation/ThreadAsyncExecutorTest.java index c9f85f48d..d6540ce77 100644 --- a/async-method-invocation/src/test/java/com/iluwatar/async/method/invocation/ThreadAsyncExecutorTest.java +++ b/async-method-invocation/src/test/java/com/iluwatar/async/method/invocation/ThreadAsyncExecutorTest.java @@ -33,7 +33,6 @@ import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import static org.mockito.internal.verification.VerificationModeFactory.times; -import java.util.Optional; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import org.junit.jupiter.api.BeforeEach; @@ -43,49 +42,43 @@ import org.mockito.Captor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; -/** - * ThreadAsyncExecutorTest - * - */ +/** ThreadAsyncExecutorTest */ class ThreadAsyncExecutorTest { - @Captor - private ArgumentCaptor exceptionCaptor; + @Captor private ArgumentCaptor exceptionCaptor; - @Mock - private Callable task; + @Mock private Callable task; - @Mock - private AsyncCallback callback; + @Mock private AsyncCallback callback; @BeforeEach void setUp() { MockitoAnnotations.openMocks(this); } - /** - * Test used to verify the happy path of {@link ThreadAsyncExecutor#startProcess(Callable)} - */ + /** Test used to verify the happy path of {@link ThreadAsyncExecutor#startProcess(Callable)} */ @Test void testSuccessfulTaskWithoutCallback() { - assertTimeout(ofMillis(3000), () -> { - // Instantiate a new executor and start a new 'null' task ... - final var executor = new ThreadAsyncExecutor(); + assertTimeout( + ofMillis(3000), + () -> { + // Instantiate a new executor and start a new 'null' task ... + final var executor = new ThreadAsyncExecutor(); - final var result = new Object(); - when(task.call()).thenReturn(result); + final var result = new Object(); + when(task.call()).thenReturn(result); - final var asyncResult = executor.startProcess(task); - assertNotNull(asyncResult); - asyncResult.await(); // Prevent timing issues, and wait until the result is available - assertTrue(asyncResult.isCompleted()); + final var asyncResult = executor.startProcess(task); + assertNotNull(asyncResult); + asyncResult.await(); // Prevent timing issues, and wait until the result is available + assertTrue(asyncResult.isCompleted()); - // Our task should only execute once ... - verify(task, times(1)).call(); + // Our task should only execute once ... + verify(task, times(1)).call(); - // ... and the result should be exactly the same object - assertSame(result, asyncResult.getValue()); - }); + // ... and the result should be exactly the same object + assertSame(result, asyncResult.getValue()); + }); } /** @@ -94,28 +87,30 @@ class ThreadAsyncExecutorTest { */ @Test void testSuccessfulTaskWithCallback() { - assertTimeout(ofMillis(3000), () -> { - // Instantiate a new executor and start a new 'null' task ... - final var executor = new ThreadAsyncExecutor(); + assertTimeout( + ofMillis(3000), + () -> { + // Instantiate a new executor and start a new 'null' task ... + final var executor = new ThreadAsyncExecutor(); - final var result = new Object(); - when(task.call()).thenReturn(result); + final var result = new Object(); + when(task.call()).thenReturn(result); - final var asyncResult = executor.startProcess(task, callback); - assertNotNull(asyncResult); - asyncResult.await(); // Prevent timing issues, and wait until the result is available - assertTrue(asyncResult.isCompleted()); + final var asyncResult = executor.startProcess(task, callback); + assertNotNull(asyncResult); + asyncResult.await(); // Prevent timing issues, and wait until the result is available + assertTrue(asyncResult.isCompleted()); - // Our task should only execute once ... - verify(task, times(1)).call(); + // Our task should only execute once ... + verify(task, times(1)).call(); - // ... same for the callback, we expect our object - verify(callback, times(1)).onComplete(eq(result)); - verify(callback, times(0)).onError(exceptionCaptor.capture()); + // ... same for the callback, we expect our object + verify(callback, times(1)).onComplete(eq(result)); + verify(callback, times(0)).onError(exceptionCaptor.capture()); - // ... and the result should be exactly the same object - assertSame(result, asyncResult.getValue()); - }); + // ... and the result should be exactly the same object + assertSame(result, asyncResult.getValue()); + }); } /** @@ -124,38 +119,43 @@ class ThreadAsyncExecutorTest { */ @Test void testLongRunningTaskWithoutCallback() { - assertTimeout(ofMillis(5000), () -> { - // Instantiate a new executor and start a new 'null' task ... - final var executor = new ThreadAsyncExecutor(); + assertTimeout( + ofMillis(5000), + () -> { + // Instantiate a new executor and start a new 'null' task ... + final var executor = new ThreadAsyncExecutor(); - final var result = new Object(); - when(task.call()).thenAnswer(i -> { - Thread.sleep(1500); - return result; - }); + final var result = new Object(); + when(task.call()) + .thenAnswer( + i -> { + Thread.sleep(1500); + return result; + }); - final var asyncResult = executor.startProcess(task); - assertNotNull(asyncResult); - assertFalse(asyncResult.isCompleted()); + final var asyncResult = executor.startProcess(task); + assertNotNull(asyncResult); + assertFalse(asyncResult.isCompleted()); - try { - asyncResult.getValue(); - fail("Expected IllegalStateException when calling AsyncResult#getValue on a non-completed task"); - } catch (IllegalStateException e) { - assertNotNull(e.getMessage()); - } + try { + asyncResult.getValue(); + fail( + "Expected IllegalStateException when calling AsyncResult#getValue on a non-completed task"); + } catch (IllegalStateException e) { + assertNotNull(e.getMessage()); + } - // Our task should only execute once, but it can take a while ... - verify(task, timeout(3000).times(1)).call(); + // Our task should only execute once, but it can take a while ... + verify(task, timeout(3000).times(1)).call(); - // Prevent timing issues, and wait until the result is available - asyncResult.await(); - assertTrue(asyncResult.isCompleted()); - verifyNoMoreInteractions(task); + // Prevent timing issues, and wait until the result is available + asyncResult.await(); + assertTrue(asyncResult.isCompleted()); + verifyNoMoreInteractions(task); - // ... and the result should be exactly the same object - assertSame(result, asyncResult.getValue()); - }); + // ... and the result should be exactly the same object + assertSame(result, asyncResult.getValue()); + }); } /** @@ -164,42 +164,47 @@ class ThreadAsyncExecutorTest { */ @Test void testLongRunningTaskWithCallback() { - assertTimeout(ofMillis(5000), () -> { - // Instantiate a new executor and start a new 'null' task ... - final var executor = new ThreadAsyncExecutor(); + assertTimeout( + ofMillis(5000), + () -> { + // Instantiate a new executor and start a new 'null' task ... + final var executor = new ThreadAsyncExecutor(); - final var result = new Object(); - when(task.call()).thenAnswer(i -> { - Thread.sleep(1500); - return result; - }); + final var result = new Object(); + when(task.call()) + .thenAnswer( + i -> { + Thread.sleep(1500); + return result; + }); - final var asyncResult = executor.startProcess(task, callback); - assertNotNull(asyncResult); - assertFalse(asyncResult.isCompleted()); + final var asyncResult = executor.startProcess(task, callback); + assertNotNull(asyncResult); + assertFalse(asyncResult.isCompleted()); - verifyNoMoreInteractions(callback); + verifyNoMoreInteractions(callback); - try { - asyncResult.getValue(); - fail("Expected IllegalStateException when calling AsyncResult#getValue on a non-completed task"); - } catch (IllegalStateException e) { - assertNotNull(e.getMessage()); - } + try { + asyncResult.getValue(); + fail( + "Expected IllegalStateException when calling AsyncResult#getValue on a non-completed task"); + } catch (IllegalStateException e) { + assertNotNull(e.getMessage()); + } - // Our task should only execute once, but it can take a while ... - verify(task, timeout(3000).times(1)).call(); - verify(callback, timeout(3000).times(1)).onComplete(eq(result)); - verify(callback, times(0)).onError(isA(Exception.class)); + // Our task should only execute once, but it can take a while ... + verify(task, timeout(3000).times(1)).call(); + verify(callback, timeout(3000).times(1)).onComplete(eq(result)); + verify(callback, times(0)).onError(isA(Exception.class)); - // Prevent timing issues, and wait until the result is available - asyncResult.await(); - assertTrue(asyncResult.isCompleted()); - verifyNoMoreInteractions(task, callback); + // Prevent timing issues, and wait until the result is available + asyncResult.await(); + assertTrue(asyncResult.isCompleted()); + verifyNoMoreInteractions(task, callback); - // ... and the result should be exactly the same object - assertSame(result, asyncResult.getValue()); - }); + // ... and the result should be exactly the same object + assertSame(result, asyncResult.getValue()); + }); } /** @@ -209,35 +214,40 @@ class ThreadAsyncExecutorTest { */ @Test void testEndProcess() { - assertTimeout(ofMillis(5000), () -> { - // Instantiate a new executor and start a new 'null' task ... - final var executor = new ThreadAsyncExecutor(); + assertTimeout( + ofMillis(5000), + () -> { + // Instantiate a new executor and start a new 'null' task ... + final var executor = new ThreadAsyncExecutor(); - final var result = new Object(); - when(task.call()).thenAnswer(i -> { - Thread.sleep(1500); - return result; - }); + final var result = new Object(); + when(task.call()) + .thenAnswer( + i -> { + Thread.sleep(1500); + return result; + }); - final var asyncResult = executor.startProcess(task); - assertNotNull(asyncResult); - assertFalse(asyncResult.isCompleted()); + final var asyncResult = executor.startProcess(task); + assertNotNull(asyncResult); + assertFalse(asyncResult.isCompleted()); - try { - asyncResult.getValue(); - fail("Expected IllegalStateException when calling AsyncResult#getValue on a non-completed task"); - } catch (IllegalStateException e) { - assertNotNull(e.getMessage()); - } + try { + asyncResult.getValue(); + fail( + "Expected IllegalStateException when calling AsyncResult#getValue on a non-completed task"); + } catch (IllegalStateException e) { + assertNotNull(e.getMessage()); + } - assertSame(result, executor.endProcess(asyncResult)); - verify(task, times(1)).call(); - assertTrue(asyncResult.isCompleted()); + assertSame(result, executor.endProcess(asyncResult)); + verify(task, times(1)).call(); + assertTrue(asyncResult.isCompleted()); - // Calling end process a second time while already finished should give the same result - assertSame(result, executor.endProcess(asyncResult)); - verifyNoMoreInteractions(task); - }); + // Calling end process a second time while already finished should give the same result + assertSame(result, executor.endProcess(asyncResult)); + verifyNoMoreInteractions(task); + }); } /** @@ -246,25 +256,28 @@ class ThreadAsyncExecutorTest { */ @Test void testNullTask() { - assertTimeout(ofMillis(3000), () -> { - // Instantiate a new executor and start a new 'null' task ... - final var executor = new ThreadAsyncExecutor(); - final var asyncResult = executor.startProcess(null); + assertTimeout( + ofMillis(3000), + () -> { + // Instantiate a new executor and start a new 'null' task ... + final var executor = new ThreadAsyncExecutor(); + final var asyncResult = executor.startProcess(null); - assertNotNull(asyncResult, "The AsyncResult should not be 'null', even though the task was 'null'."); - asyncResult.await(); // Prevent timing issues, and wait until the result is available - assertTrue(asyncResult.isCompleted()); - - try { - asyncResult.getValue(); - fail("Expected ExecutionException with NPE as cause"); - } catch (final ExecutionException e) { - assertNotNull(e.getMessage()); - assertNotNull(e.getCause()); - assertEquals(NullPointerException.class, e.getCause().getClass()); - } - }); + assertNotNull( + asyncResult, + "The AsyncResult should not be 'null', even though the task was 'null'."); + asyncResult.await(); // Prevent timing issues, and wait until the result is available + assertTrue(asyncResult.isCompleted()); + try { + asyncResult.getValue(); + fail("Expected ExecutionException with NPE as cause"); + } catch (final ExecutionException e) { + assertNotNull(e.getMessage()); + assertNotNull(e.getCause()); + assertEquals(NullPointerException.class, e.getCause().getClass()); + } + }); } /** @@ -273,32 +286,35 @@ class ThreadAsyncExecutorTest { */ @Test void testNullTaskWithCallback() { - assertTimeout(ofMillis(3000), () -> { - // Instantiate a new executor and start a new 'null' task ... - final var executor = new ThreadAsyncExecutor(); - final var asyncResult = executor.startProcess(null, callback); + assertTimeout( + ofMillis(3000), + () -> { + // Instantiate a new executor and start a new 'null' task ... + final var executor = new ThreadAsyncExecutor(); + final var asyncResult = executor.startProcess(null, callback); - assertNotNull(asyncResult, "The AsyncResult should not be 'null', even though the task was 'null'."); - asyncResult.await(); // Prevent timing issues, and wait until the result is available - assertTrue(asyncResult.isCompleted()); - verify(callback, times(0)).onComplete(any()); - verify(callback, times(1)).onError(exceptionCaptor.capture()); + assertNotNull( + asyncResult, + "The AsyncResult should not be 'null', even though the task was 'null'."); + asyncResult.await(); // Prevent timing issues, and wait until the result is available + assertTrue(asyncResult.isCompleted()); + verify(callback, times(0)).onComplete(any()); + verify(callback, times(1)).onError(exceptionCaptor.capture()); - final var exception = exceptionCaptor.getValue(); - assertNotNull(exception); + final var exception = exceptionCaptor.getValue(); + assertNotNull(exception); - assertEquals(NullPointerException.class, exception.getClass()); - - try { - asyncResult.getValue(); - fail("Expected ExecutionException with NPE as cause"); - } catch (final ExecutionException e) { - assertNotNull(e.getMessage()); - assertNotNull(e.getCause()); - assertEquals(NullPointerException.class, e.getCause().getClass()); - } - }); + assertEquals(NullPointerException.class, exception.getClass()); + try { + asyncResult.getValue(); + fail("Expected ExecutionException with NPE as cause"); + } catch (final ExecutionException e) { + assertNotNull(e.getMessage()); + assertNotNull(e.getCause()); + assertEquals(NullPointerException.class, e.getCause().getClass()); + } + }); } /** @@ -307,28 +323,27 @@ class ThreadAsyncExecutorTest { */ @Test void testNullTaskWithNullCallback() { - assertTimeout(ofMillis(3000), () -> { - // Instantiate a new executor and start a new 'null' task ... - final var executor = new ThreadAsyncExecutor(); - final var asyncResult = executor.startProcess(null, null); + assertTimeout( + ofMillis(3000), + () -> { + // Instantiate a new executor and start a new 'null' task ... + final var executor = new ThreadAsyncExecutor(); + final var asyncResult = executor.startProcess(null, null); - assertNotNull( - asyncResult, - "The AsyncResult should not be 'null', even though the task and callback were 'null'." - ); - asyncResult.await(); // Prevent timing issues, and wait until the result is available - assertTrue(asyncResult.isCompleted()); - - try { - asyncResult.getValue(); - fail("Expected ExecutionException with NPE as cause"); - } catch (final ExecutionException e) { - assertNotNull(e.getMessage()); - assertNotNull(e.getCause()); - assertEquals(NullPointerException.class, e.getCause().getClass()); - } - }); + assertNotNull( + asyncResult, + "The AsyncResult should not be 'null', even though the task and callback were 'null'."); + asyncResult.await(); // Prevent timing issues, and wait until the result is available + assertTrue(asyncResult.isCompleted()); + try { + asyncResult.getValue(); + fail("Expected ExecutionException with NPE as cause"); + } catch (final ExecutionException e) { + assertNotNull(e.getMessage()); + assertNotNull(e.getCause()); + assertEquals(NullPointerException.class, e.getCause().getClass()); + } + }); } - } diff --git a/balking/pom.xml b/balking/pom.xml index b9902e671..818f7549c 100644 --- a/balking/pom.xml +++ b/balking/pom.xml @@ -34,6 +34,14 @@ 4.0.0 balking + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/balking/src/main/java/com/iluwatar/balking/DelayProvider.java b/balking/src/main/java/com/iluwatar/balking/DelayProvider.java index f142c8c7b..f27922219 100644 --- a/balking/src/main/java/com/iluwatar/balking/DelayProvider.java +++ b/balking/src/main/java/com/iluwatar/balking/DelayProvider.java @@ -26,9 +26,7 @@ package com.iluwatar.balking; import java.util.concurrent.TimeUnit; -/** - * An interface to simulate delay while executing some work. - */ +/** An interface to simulate delay while executing some work. */ public interface DelayProvider { void executeAfterDelay(long interval, TimeUnit timeUnit, Runnable task); } diff --git a/balking/src/main/java/com/iluwatar/balking/WashingMachine.java b/balking/src/main/java/com/iluwatar/balking/WashingMachine.java index 794cfbd8a..52ce7c593 100644 --- a/balking/src/main/java/com/iluwatar/balking/WashingMachine.java +++ b/balking/src/main/java/com/iluwatar/balking/WashingMachine.java @@ -28,30 +28,26 @@ import java.util.concurrent.TimeUnit; import lombok.Getter; import lombok.extern.slf4j.Slf4j; -/** - * Washing machine class. - */ +/** Washing machine class. */ @Slf4j public class WashingMachine { private final DelayProvider delayProvider; - @Getter - private WashingMachineState washingMachineState; + @Getter private WashingMachineState washingMachineState; - /** - * Creates a new instance of WashingMachine. - */ + /** Creates a new instance of WashingMachine. */ public WashingMachine() { - this((interval, timeUnit, task) -> { - try { - Thread.sleep(timeUnit.toMillis(interval)); - } catch (InterruptedException ie) { - LOGGER.error("", ie); - Thread.currentThread().interrupt(); - } - task.run(); - }); + this( + (interval, timeUnit, task) -> { + try { + Thread.sleep(timeUnit.toMillis(interval)); + } catch (InterruptedException ie) { + LOGGER.error("", ie); + Thread.currentThread().interrupt(); + } + task.run(); + }); } /** @@ -63,9 +59,7 @@ public class WashingMachine { this.washingMachineState = WashingMachineState.ENABLED; } - /** - * Method responsible for washing if the object is in appropriate state. - */ + /** Method responsible for washing if the object is in appropriate state. */ public void wash() { synchronized (this) { var machineState = getWashingMachineState(); @@ -81,12 +75,9 @@ public class WashingMachine { this.delayProvider.executeAfterDelay(50, TimeUnit.MILLISECONDS, this::endOfWashing); } - /** - * Method is responsible for ending the washing by changing machine state. - */ + /** Method is responsible for 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/test/java/com/iluwatar/balking/AppTest.java b/balking/src/test/java/com/iluwatar/balking/AppTest.java index b744b6786..40beabf55 100644 --- a/balking/src/test/java/com/iluwatar/balking/AppTest.java +++ b/balking/src/test/java/com/iluwatar/balking/AppTest.java @@ -24,27 +24,22 @@ */ package com.iluwatar.balking; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + import org.junit.jupiter.api.Test; import org.junit.jupiter.api.function.Executable; -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; - - -/** - * Application test - */ +/** Application test */ class AppTest { /** * Issue: Add at least one assertion to this test case. * - * Solution: Inserted assertion to check whether the execution of the main method in {@link App} - * throws an exception. + *

Solution: Inserted assertion to check whether the execution of the main method in {@link + * App} throws an exception. */ - @Test void shouldExecuteApplicationWithoutException() { assertDoesNotThrow((Executable) App::main); } - -} \ 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 index f5c1e2de6..9bf7ac254 100644 --- a/balking/src/test/java/com/iluwatar/balking/WashingMachineTest.java +++ b/balking/src/test/java/com/iluwatar/balking/WashingMachineTest.java @@ -29,9 +29,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.Test; -/** - * Tests for {@link WashingMachine} - */ +/** Tests for {@link WashingMachine} */ class WashingMachineTest { private final FakeDelayProvider fakeDelayProvider = new FakeDelayProvider(); @@ -69,4 +67,4 @@ class WashingMachineTest { this.task = task; } } -} \ No newline at end of file +} diff --git a/bloc/pom.xml b/bloc/pom.xml index 765c6f584..cc52a3b99 100644 --- a/bloc/pom.xml +++ b/bloc/pom.xml @@ -38,7 +38,7 @@ org.junit.jupiter - junit-jupiter-api + junit-jupiter-engine test @@ -53,11 +53,6 @@ 3.27.3 test - - junit - junit - test - diff --git a/bloc/src/main/java/com/iluwatar/bloc/Bloc.java b/bloc/src/main/java/com/iluwatar/bloc/Bloc.java index 47a85b8f2..f6ab0a61c 100644 --- a/bloc/src/main/java/com/iluwatar/bloc/Bloc.java +++ b/bloc/src/main/java/com/iluwatar/bloc/Bloc.java @@ -30,17 +30,15 @@ import java.util.List; /** * The Bloc class is responsible for managing the current state and notifying registered listeners - * whenever the state changes. It implements the ListenerManager interface, allowing listeners - * to be added, removed, and notified of state changes. + * whenever the state changes. It implements the ListenerManager interface, allowing listeners to be + * added, removed, and notified of state changes. */ public class Bloc implements ListenerManager { private State currentState; private final List> listeners = new ArrayList<>(); - /** - * Constructs a new Bloc instance with an initial state of value 0. - */ + /** Constructs a new Bloc instance with an initial state of value 0. */ public Bloc() { this.currentState = new State(0); } @@ -88,16 +86,12 @@ public class Bloc implements ListenerManager { } } - /** - * Increments the current state value by 1 and notifies listeners of the change. - */ + /** Increments the current state value by 1 and notifies listeners of the change. */ public void increment() { emitState(new State(currentState.value() + 1)); } - /** - * Decrements the current state value by 1 and notifies listeners of the change. - */ + /** Decrements the current state value by 1 and notifies listeners of the change. */ public void decrement() { emitState(new State(currentState.value() - 1)); } diff --git a/bloc/src/main/java/com/iluwatar/bloc/BlocUi.java b/bloc/src/main/java/com/iluwatar/bloc/BlocUi.java index 1d0f706ec..500d455d8 100644 --- a/bloc/src/main/java/com/iluwatar/bloc/BlocUi.java +++ b/bloc/src/main/java/com/iluwatar/bloc/BlocUi.java @@ -32,14 +32,10 @@ import javax.swing.JLabel; import javax.swing.SwingConstants; import javax.swing.WindowConstants; -/** - * The BlocUI class handles the creation and management of the UI components. - */ +/** The BlocUI class handles the creation and management of the UI components. */ public class BlocUi { - /** - * Creates and shows the UI. - */ + /** Creates and shows the UI. */ public void createAndShowUi() { // Create a Bloc instance to manage the state final Bloc bloc = new Bloc(); @@ -70,19 +66,20 @@ public class BlocUi { // adding the listener to the Bloc instance bloc.addListener(stateListener); - toggleListenerButton.addActionListener(e -> { - if (bloc.getListeners().contains(stateListener)) { - bloc.removeListener(stateListener); - toggleListenerButton.setText("Enable Listener"); - } else { - bloc.addListener(stateListener); - toggleListenerButton.setText("Disable Listener"); - } - }); + toggleListenerButton.addActionListener( + e -> { + if (bloc.getListeners().contains(stateListener)) { + bloc.removeListener(stateListener); + toggleListenerButton.setText("Enable Listener"); + } else { + bloc.addListener(stateListener); + toggleListenerButton.setText("Disable Listener"); + } + }); incrementButton.addActionListener(e -> bloc.increment()); decrementButton.addActionListener(e -> bloc.decrement()); frame.setVisible(true); } -} \ No newline at end of file +} diff --git a/bloc/src/main/java/com/iluwatar/bloc/ListenerManager.java b/bloc/src/main/java/com/iluwatar/bloc/ListenerManager.java index ca4c5ff22..cd55b0fb3 100644 --- a/bloc/src/main/java/com/iluwatar/bloc/ListenerManager.java +++ b/bloc/src/main/java/com/iluwatar/bloc/ListenerManager.java @@ -23,6 +23,7 @@ * THE SOFTWARE. */ package com.iluwatar.bloc; + import java.util.List; /** @@ -30,7 +31,6 @@ import java.util.List; * * @param The type of state to be handled by the listeners. */ - public interface ListenerManager { /** diff --git a/bloc/src/main/java/com/iluwatar/bloc/Main.java b/bloc/src/main/java/com/iluwatar/bloc/Main.java index 5dae30ed5..b7a929bcf 100644 --- a/bloc/src/main/java/com/iluwatar/bloc/Main.java +++ b/bloc/src/main/java/com/iluwatar/bloc/Main.java @@ -25,19 +25,18 @@ package com.iluwatar.bloc; /** - * The BLoC (Business Logic Component) pattern is a software design pattern primarily used - * in Flutter applications. It facilitates the separation of business logic from UI code, - * making the application more modular, testable, and scalable. The BLoC pattern uses streams - * to manage the flow of data and state changes, allowing widgets to react to new states as - * they arrive. - * In the BLoC pattern, the application is divided into three key components: - * - Input streams: Represent user interactions or external events fed into the BLoC. - * - Business logic: Processes the input and determines the resulting state or actions. - * - Output streams: Emit the updated state for the UI to consume. - * The BLoC pattern is especially useful in reactive programming scenarios and aligns well with the declarative nature of Flutter. - * By using this pattern, developers can ensure a clear separation of concerns, enhance reusability, and maintain consistent state management throughout the application. + * The BLoC (Business Logic Component) pattern is a software design pattern primarily used in + * Flutter applications. It facilitates the separation of business logic from UI code, making the + * application more modular, testable, and scalable. The BLoC pattern uses streams to manage the + * flow of data and state changes, allowing widgets to react to new states as they arrive. In the + * BLoC pattern, the application is divided into three key components: - Input streams: Represent + * user interactions or external events fed into the BLoC. - Business logic: Processes the input and + * determines the resulting state or actions. - Output streams: Emit the updated state for the UI to + * consume. The BLoC pattern is especially useful in reactive programming scenarios and aligns well + * with the declarative nature of Flutter. By using this pattern, developers can ensure a clear + * separation of concerns, enhance reusability, and maintain consistent state management throughout + * the application. */ - public class Main { /** @@ -49,4 +48,4 @@ public class Main { BlocUi blocUi = new BlocUi(); blocUi.createAndShowUi(); } -} \ No newline at end of file +} diff --git a/bloc/src/main/java/com/iluwatar/bloc/State.java b/bloc/src/main/java/com/iluwatar/bloc/State.java index 9a08b3df7..430747548 100644 --- a/bloc/src/main/java/com/iluwatar/bloc/State.java +++ b/bloc/src/main/java/com/iluwatar/bloc/State.java @@ -25,8 +25,7 @@ package com.iluwatar.bloc; /** - * The {@code State} class represents a state with an integer value. - * This class encapsulates the value and provides methods to retrieve it. + * The {@code State} class represents a state with an integer value. This class encapsulates the + * value and provides methods to retrieve it. */ -public record State(int value) { -} \ No newline at end of file +public record State(int value) {} diff --git a/bloc/src/main/java/com/iluwatar/bloc/StateListener.java b/bloc/src/main/java/com/iluwatar/bloc/StateListener.java index f656b3f3d..77aac172e 100644 --- a/bloc/src/main/java/com/iluwatar/bloc/StateListener.java +++ b/bloc/src/main/java/com/iluwatar/bloc/StateListener.java @@ -26,7 +26,8 @@ package com.iluwatar.bloc; /** * The {@code StateListener} interface defines the contract for listening to state changes. - * Implementations of this interface should handle state changes and define actions to take when the state changes. + * Implementations of this interface should handle state changes and define actions to take when the + * state changes. * * @param the type of state that this listener will handle */ diff --git a/bloc/src/test/java/com/iluwatar/bloc/BlocTest.java b/bloc/src/test/java/com/iluwatar/bloc/BlocTest.java index bde72d6dd..98e34b8d4 100644 --- a/bloc/src/test/java/com/iluwatar/bloc/BlocTest.java +++ b/bloc/src/test/java/com/iluwatar/bloc/BlocTest.java @@ -23,19 +23,23 @@ * THE SOFTWARE. */ package com.iluwatar.bloc; + +import static org.junit.jupiter.api.Assertions.*; + +import java.util.concurrent.atomic.AtomicInteger; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.util.concurrent.atomic.AtomicInteger; -import static org.junit.jupiter.api.Assertions.*; class BlocTest { private Bloc bloc; private AtomicInteger stateValue; + @BeforeEach void setUp() { bloc = new Bloc(); stateValue = new AtomicInteger(0); } + @Test void initialState() { assertTrue(bloc.getListeners().isEmpty(), "No listeners should be present initially."); @@ -68,6 +72,7 @@ class BlocTest { bloc.removeListener(listener); assertTrue(bloc.getListeners().isEmpty(), "Listener count should be 0 after removal."); } + @Test void multipleListeners() { AtomicInteger secondValue = new AtomicInteger(); @@ -77,4 +82,4 @@ class BlocTest { assertEquals(1, stateValue.get(), "First listener should receive state 1."); assertEquals(1, secondValue.get(), "Second listener should receive state 1."); } -} \ No newline at end of file +} diff --git a/bloc/src/test/java/com/iluwatar/bloc/BlocUiTest.java b/bloc/src/test/java/com/iluwatar/bloc/BlocUiTest.java index 35f4c9c6b..1327e2cb2 100644 --- a/bloc/src/test/java/com/iluwatar/bloc/BlocUiTest.java +++ b/bloc/src/test/java/com/iluwatar/bloc/BlocUiTest.java @@ -24,14 +24,13 @@ */ package com.iluwatar.bloc; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; -import javax.swing.*; import java.awt.*; - -import static org.junit.Assert.assertEquals; +import javax.swing.*; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class BlocUiTest { @@ -43,9 +42,9 @@ public class BlocUiTest { private Bloc bloc; private StateListener stateListener; - @Before + @BeforeEach public void setUp() { - bloc = new Bloc(); // Re-initialize the Bloc for each test + bloc = new Bloc(); // Re-initialize the Bloc for each test frame = new JFrame("BloC example"); frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); @@ -69,26 +68,26 @@ public class BlocUiTest { incrementButton.addActionListener(e -> bloc.increment()); decrementButton.addActionListener(e -> bloc.decrement()); - toggleListenerButton.addActionListener(e -> { - if (bloc.getListeners().contains(stateListener)) { - bloc.removeListener(stateListener); - toggleListenerButton.setText("Enable Listener"); - } else { - bloc.addListener(stateListener); - toggleListenerButton.setText("Disable Listener"); - } - }); + toggleListenerButton.addActionListener( + e -> { + if (bloc.getListeners().contains(stateListener)) { + bloc.removeListener(stateListener); + toggleListenerButton.setText("Enable Listener"); + } else { + bloc.addListener(stateListener); + toggleListenerButton.setText("Disable Listener"); + } + }); frame.setVisible(true); } - @After + @AfterEach public void tearDown() { frame.dispose(); - bloc = new Bloc(); // Reset Bloc state after each test to avoid state carryover + bloc = new Bloc(); // Reset Bloc state after each test to avoid state carryover } - @Test public void testIncrementButton() { simulateButtonClick(incrementButton); diff --git a/bridge/pom.xml b/bridge/pom.xml index 915aee30a..3cfd33997 100644 --- a/bridge/pom.xml +++ b/bridge/pom.xml @@ -34,6 +34,14 @@ bridge + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/bridge/src/main/java/com/iluwatar/bridge/App.java b/bridge/src/main/java/com/iluwatar/bridge/App.java index 1550782a6..c3ea3d50c 100644 --- a/bridge/src/main/java/com/iluwatar/bridge/App.java +++ b/bridge/src/main/java/com/iluwatar/bridge/App.java @@ -35,9 +35,9 @@ import lombok.extern.slf4j.Slf4j; * have their own class hierarchies. The interface of the implementations can be changed without * affecting the clients. * - *

In this example we have two class hierarchies. One of weapons and another one of - * enchantments. We can easily combine any weapon with any enchantment using composition instead of - * creating deep class hierarchy. + *

In this example we have two class hierarchies. One of weapons and another one of enchantments. + * We can easily combine any weapon with any enchantment using composition instead of creating deep + * class hierarchy. */ @Slf4j public class App { diff --git a/bridge/src/main/java/com/iluwatar/bridge/Enchantment.java b/bridge/src/main/java/com/iluwatar/bridge/Enchantment.java index 95f4cc351..4bdd4502f 100644 --- a/bridge/src/main/java/com/iluwatar/bridge/Enchantment.java +++ b/bridge/src/main/java/com/iluwatar/bridge/Enchantment.java @@ -24,9 +24,7 @@ */ package com.iluwatar.bridge; -/** - * Enchantment. - */ +/** Enchantment. */ public interface Enchantment { void onActivate(); diff --git a/bridge/src/main/java/com/iluwatar/bridge/FlyingEnchantment.java b/bridge/src/main/java/com/iluwatar/bridge/FlyingEnchantment.java index 530fb3e5e..42da3523f 100644 --- a/bridge/src/main/java/com/iluwatar/bridge/FlyingEnchantment.java +++ b/bridge/src/main/java/com/iluwatar/bridge/FlyingEnchantment.java @@ -26,9 +26,7 @@ package com.iluwatar.bridge; import lombok.extern.slf4j.Slf4j; -/** - * FlyingEnchantment. - */ +/** FlyingEnchantment. */ @Slf4j public class FlyingEnchantment implements Enchantment { diff --git a/bridge/src/main/java/com/iluwatar/bridge/Hammer.java b/bridge/src/main/java/com/iluwatar/bridge/Hammer.java index a7a237c14..328f3b79e 100644 --- a/bridge/src/main/java/com/iluwatar/bridge/Hammer.java +++ b/bridge/src/main/java/com/iluwatar/bridge/Hammer.java @@ -27,9 +27,7 @@ package com.iluwatar.bridge; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; -/** - * Hammer. - */ +/** Hammer. */ @Slf4j @AllArgsConstructor public class Hammer implements Weapon { diff --git a/bridge/src/main/java/com/iluwatar/bridge/SoulEatingEnchantment.java b/bridge/src/main/java/com/iluwatar/bridge/SoulEatingEnchantment.java index 3c311ddbb..ed2217467 100644 --- a/bridge/src/main/java/com/iluwatar/bridge/SoulEatingEnchantment.java +++ b/bridge/src/main/java/com/iluwatar/bridge/SoulEatingEnchantment.java @@ -26,9 +26,7 @@ package com.iluwatar.bridge; import lombok.extern.slf4j.Slf4j; -/** - * SoulEatingEnchantment. - */ +/** SoulEatingEnchantment. */ @Slf4j public class SoulEatingEnchantment implements Enchantment { diff --git a/bridge/src/main/java/com/iluwatar/bridge/Sword.java b/bridge/src/main/java/com/iluwatar/bridge/Sword.java index 7b75ead21..417bc9334 100644 --- a/bridge/src/main/java/com/iluwatar/bridge/Sword.java +++ b/bridge/src/main/java/com/iluwatar/bridge/Sword.java @@ -27,9 +27,7 @@ package com.iluwatar.bridge; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; -/** - * Sword. - */ +/** Sword. */ @Slf4j @AllArgsConstructor public class Sword implements Weapon { diff --git a/bridge/src/main/java/com/iluwatar/bridge/Weapon.java b/bridge/src/main/java/com/iluwatar/bridge/Weapon.java index e9452343d..a9f0ab4bb 100644 --- a/bridge/src/main/java/com/iluwatar/bridge/Weapon.java +++ b/bridge/src/main/java/com/iluwatar/bridge/Weapon.java @@ -24,9 +24,7 @@ */ package com.iluwatar.bridge; -/** - * Weapon. - */ +/** Weapon. */ public interface Weapon { void wield(); diff --git a/bridge/src/test/java/com/iluwatar/bridge/AppTest.java b/bridge/src/test/java/com/iluwatar/bridge/AppTest.java index 5db5f3eb1..d1136fc90 100644 --- a/bridge/src/test/java/com/iluwatar/bridge/AppTest.java +++ b/bridge/src/test/java/com/iluwatar/bridge/AppTest.java @@ -24,24 +24,21 @@ */ package com.iluwatar.bridge; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -/** - * Application test - */ +import org.junit.jupiter.api.Test; + +/** Application test */ class AppTest { /** * Issue: Add at least one assertion to this test case. * - * Solution: Inserted assertion to check whether the execution of the main method in {@link App} - * throws an exception. + *

Solution: Inserted assertion to check whether the execution of the main method in {@link + * App} throws an exception. */ - @Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/bridge/src/test/java/com/iluwatar/bridge/HammerTest.java b/bridge/src/test/java/com/iluwatar/bridge/HammerTest.java index d6c38300c..d8853647c 100644 --- a/bridge/src/test/java/com/iluwatar/bridge/HammerTest.java +++ b/bridge/src/test/java/com/iluwatar/bridge/HammerTest.java @@ -29,9 +29,7 @@ import static org.mockito.Mockito.spy; import org.junit.jupiter.api.Test; -/** - * Tests for hammer - */ +/** Tests for hammer */ class HammerTest extends WeaponTest { /** @@ -43,4 +41,4 @@ class HammerTest extends WeaponTest { final var hammer = spy(new Hammer(mock(FlyingEnchantment.class))); testBasicWeaponActions(hammer); } -} \ No newline at end of file +} diff --git a/bridge/src/test/java/com/iluwatar/bridge/SwordTest.java b/bridge/src/test/java/com/iluwatar/bridge/SwordTest.java index d5849e78a..b021cd08d 100644 --- a/bridge/src/test/java/com/iluwatar/bridge/SwordTest.java +++ b/bridge/src/test/java/com/iluwatar/bridge/SwordTest.java @@ -29,9 +29,7 @@ import static org.mockito.Mockito.spy; import org.junit.jupiter.api.Test; -/** - * Tests for sword - */ +/** Tests for sword */ class SwordTest extends WeaponTest { /** @@ -43,4 +41,4 @@ class SwordTest extends WeaponTest { final var sword = spy(new Sword(mock(FlyingEnchantment.class))); testBasicWeaponActions(sword); } -} \ No newline at end of file +} diff --git a/bridge/src/test/java/com/iluwatar/bridge/WeaponTest.java b/bridge/src/test/java/com/iluwatar/bridge/WeaponTest.java index 47515f9b1..67648ea63 100644 --- a/bridge/src/test/java/com/iluwatar/bridge/WeaponTest.java +++ b/bridge/src/test/java/com/iluwatar/bridge/WeaponTest.java @@ -28,9 +28,7 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; -/** - * Base class for weapon tests - */ +/** Base class for weapon tests */ abstract class WeaponTest { /** @@ -54,6 +52,5 @@ abstract class WeaponTest { weapon.unwield(); verify(enchantment).onDeactivate(); verifyNoMoreInteractions(enchantment); - } } diff --git a/builder/pom.xml b/builder/pom.xml index 37176ce89..3677c187d 100644 --- a/builder/pom.xml +++ b/builder/pom.xml @@ -34,6 +34,14 @@ builder + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/builder/src/main/java/com/iluwatar/builder/App.java b/builder/src/main/java/com/iluwatar/builder/App.java index 347798cc1..acec73a48 100644 --- a/builder/src/main/java/com/iluwatar/builder/App.java +++ b/builder/src/main/java/com/iluwatar/builder/App.java @@ -58,22 +58,27 @@ public class App { */ public static void main(String[] args) { - var mage = new Hero.Builder(Profession.MAGE, "Riobard") - .withHairColor(HairColor.BLACK) - .withWeapon(Weapon.DAGGER) - .build(); + var mage = + new Hero.Builder(Profession.MAGE, "Riobard") + .withHairColor(HairColor.BLACK) + .withWeapon(Weapon.DAGGER) + .build(); LOGGER.info(mage.toString()); - var warrior = new Hero.Builder(Profession.WARRIOR, "Amberjill") - .withHairColor(HairColor.BLOND) - .withHairType(HairType.LONG_CURLY).withArmor(Armor.CHAIN_MAIL).withWeapon(Weapon.SWORD) - .build(); + var warrior = + new Hero.Builder(Profession.WARRIOR, "Amberjill") + .withHairColor(HairColor.BLOND) + .withHairType(HairType.LONG_CURLY) + .withArmor(Armor.CHAIN_MAIL) + .withWeapon(Weapon.SWORD) + .build(); LOGGER.info(warrior.toString()); - var thief = new Hero.Builder(Profession.THIEF, "Desmond") - .withHairType(HairType.BALD) - .withWeapon(Weapon.BOW) - .build(); + var thief = + new Hero.Builder(Profession.THIEF, "Desmond") + .withHairType(HairType.BALD) + .withWeapon(Weapon.BOW) + .build(); LOGGER.info(thief.toString()); } } diff --git a/builder/src/main/java/com/iluwatar/builder/Armor.java b/builder/src/main/java/com/iluwatar/builder/Armor.java index 52cbe1a06..1710f569a 100644 --- a/builder/src/main/java/com/iluwatar/builder/Armor.java +++ b/builder/src/main/java/com/iluwatar/builder/Armor.java @@ -26,12 +26,9 @@ package com.iluwatar.builder; import lombok.AllArgsConstructor; -/** - * Armor enumeration. - */ +/** Armor enumeration. */ @AllArgsConstructor public enum Armor { - CLOTHES("clothes"), LEATHER("leather"), CHAIN_MAIL("chain mail"), diff --git a/builder/src/main/java/com/iluwatar/builder/HairColor.java b/builder/src/main/java/com/iluwatar/builder/HairColor.java index 47fa9b4a9..7f767c98d 100644 --- a/builder/src/main/java/com/iluwatar/builder/HairColor.java +++ b/builder/src/main/java/com/iluwatar/builder/HairColor.java @@ -24,11 +24,8 @@ */ package com.iluwatar.builder; -/** - * HairColor enumeration. - */ +/** HairColor enumeration. */ public enum HairColor { - WHITE, BLOND, RED, @@ -39,5 +36,4 @@ public enum HairColor { public String toString() { return name().toLowerCase(); } - } diff --git a/builder/src/main/java/com/iluwatar/builder/HairType.java b/builder/src/main/java/com/iluwatar/builder/HairType.java index 45b514fb3..7ac31d0fa 100644 --- a/builder/src/main/java/com/iluwatar/builder/HairType.java +++ b/builder/src/main/java/com/iluwatar/builder/HairType.java @@ -26,12 +26,9 @@ package com.iluwatar.builder; import lombok.AllArgsConstructor; -/** - * HairType enumeration. - */ +/** HairType enumeration. */ @AllArgsConstructor public enum HairType { - BALD("bald"), SHORT("short"), CURLY("curly"), diff --git a/builder/src/main/java/com/iluwatar/builder/Hero.java b/builder/src/main/java/com/iluwatar/builder/Hero.java index 1d15ac2f0..a87137e51 100644 --- a/builder/src/main/java/com/iluwatar/builder/Hero.java +++ b/builder/src/main/java/com/iluwatar/builder/Hero.java @@ -24,24 +24,30 @@ */ package com.iluwatar.builder; -/** - * Hero,the record class. - */ - -public record Hero(Profession profession, String name, HairType hairType, HairColor hairColor, Armor armor, Weapon weapon) { +/** Hero,the record class. */ +public record Hero( + Profession profession, + String name, + HairType hairType, + HairColor hairColor, + Armor armor, + Weapon weapon) { private Hero(Builder builder) { - this(builder.profession, builder.name, builder.hairType, builder.hairColor, builder.armor, builder.weapon); + this( + builder.profession, + builder.name, + builder.hairType, + builder.hairColor, + builder.armor, + builder.weapon); } @Override public String toString() { var sb = new StringBuilder(); - sb.append("This is a ") - .append(profession) - .append(" named ") - .append(name); + sb.append("This is a ").append(profession).append(" named ").append(name); if (hairColor != null || hairType != null) { sb.append(" with "); if (hairColor != null) { @@ -62,9 +68,7 @@ public record Hero(Profession profession, String name, HairType hairType, HairCo return sb.toString(); } - /** - * The builder class. - */ + /** The builder class. */ public static class Builder { private final Profession profession; @@ -74,9 +78,7 @@ public record Hero(Profession profession, String name, HairType hairType, HairCo private Armor armor; private Weapon weapon; - /** - * Constructor. - */ + /** Constructor. */ public Builder(Profession profession, String name) { if (profession == null || name == null) { throw new IllegalArgumentException("profession and name can not be null"); diff --git a/builder/src/main/java/com/iluwatar/builder/Profession.java b/builder/src/main/java/com/iluwatar/builder/Profession.java index 9ab054677..c1be94984 100644 --- a/builder/src/main/java/com/iluwatar/builder/Profession.java +++ b/builder/src/main/java/com/iluwatar/builder/Profession.java @@ -24,12 +24,12 @@ */ package com.iluwatar.builder; -/** - * Profession enumeration. - */ +/** Profession enumeration. */ public enum Profession { - - WARRIOR, THIEF, MAGE, PRIEST; + WARRIOR, + THIEF, + MAGE, + PRIEST; @Override public String toString() { diff --git a/builder/src/main/java/com/iluwatar/builder/Weapon.java b/builder/src/main/java/com/iluwatar/builder/Weapon.java index 060482705..03a9565d0 100644 --- a/builder/src/main/java/com/iluwatar/builder/Weapon.java +++ b/builder/src/main/java/com/iluwatar/builder/Weapon.java @@ -24,12 +24,13 @@ */ package com.iluwatar.builder; -/** - * Weapon enumeration. - */ +/** Weapon enumeration. */ public enum Weapon { - - DAGGER, SWORD, AXE, WARHAMMER, BOW; + DAGGER, + SWORD, + AXE, + WARHAMMER, + BOW; @Override public String toString() { diff --git a/builder/src/test/java/com/iluwatar/builder/AppTest.java b/builder/src/test/java/com/iluwatar/builder/AppTest.java index d7b8c2579..367d3da1c 100644 --- a/builder/src/test/java/com/iluwatar/builder/AppTest.java +++ b/builder/src/test/java/com/iluwatar/builder/AppTest.java @@ -24,24 +24,21 @@ */ package com.iluwatar.builder; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -/** - * Application test - */ +import org.junit.jupiter.api.Test; + +/** Application test */ class AppTest { /** * Issue: Add at least one assertion to this test case. * - * Solution: Inserted assertion to check whether the execution of the main method in {@link App} - * throws an exception. + *

Solution: Inserted assertion to check whether the execution of the main method in {@link + * App} throws an exception. */ - @Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/builder/src/test/java/com/iluwatar/builder/HeroTest.java b/builder/src/test/java/com/iluwatar/builder/HeroTest.java index 48ec7db2a..5f67a56aa 100644 --- a/builder/src/test/java/com/iluwatar/builder/HeroTest.java +++ b/builder/src/test/java/com/iluwatar/builder/HeroTest.java @@ -30,41 +30,33 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import org.junit.jupiter.api.Test; -/** - * HeroTest - * - */ +/** HeroTest */ class HeroTest { - /** - * Test if we get the expected exception when trying to create a hero without a profession - */ + /** Test if we get the expected exception when trying to create a hero without a profession */ @Test void testMissingProfession() { assertThrows(IllegalArgumentException.class, () -> new Hero.Builder(null, "Sir without a job")); } - /** - * Test if we get the expected exception when trying to create a hero without a name - */ + /** Test if we get the expected exception when trying to create a hero without a name */ @Test void testMissingName() { assertThrows(IllegalArgumentException.class, () -> new Hero.Builder(Profession.THIEF, null)); } - /** - * Test if the hero build by the builder has the correct attributes, as requested - */ + /** Test if the hero build by the builder has the correct attributes, as requested */ @Test void testBuildHero() { final String heroName = "Sir Lancelot"; - final var hero = new Hero.Builder(Profession.WARRIOR, heroName) - .withArmor(Armor.CHAIN_MAIL) - .withWeapon(Weapon.SWORD) - .withHairType(HairType.LONG_CURLY) - .withHairColor(HairColor.BLOND) - .build(); + final var hero = + new Hero.Builder(Profession.WARRIOR, heroName) + .withArmor(Armor.CHAIN_MAIL) + .withWeapon(Weapon.SWORD) + .withHairType(HairType.LONG_CURLY) + .withHairColor(HairColor.BLOND) + .build(); assertNotNull(hero); assertNotNull(hero.toString()); @@ -74,7 +66,5 @@ class HeroTest { assertEquals(Weapon.SWORD, hero.weapon()); assertEquals(HairType.LONG_CURLY, hero.hairType()); assertEquals(HairColor.BLOND, hero.hairColor()); - } - -} \ No newline at end of file +} diff --git a/business-delegate/pom.xml b/business-delegate/pom.xml index 21046526f..a5bccb152 100644 --- a/business-delegate/pom.xml +++ b/business-delegate/pom.xml @@ -34,6 +34,14 @@ business-delegate + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/business-delegate/src/main/java/com/iluwatar/business/delegate/App.java b/business-delegate/src/main/java/com/iluwatar/business/delegate/App.java index 682bf68cc..c23ed42ca 100644 --- a/business-delegate/src/main/java/com/iluwatar/business/delegate/App.java +++ b/business-delegate/src/main/java/com/iluwatar/business/delegate/App.java @@ -34,9 +34,9 @@ package com.iluwatar.business.delegate; * retrieved through service lookups. The Business Delegate itself may contain business logic too * potentially tying together multiple service calls, exception handling, retrying etc. * - *

In this example the client ({@link MobileClient}) utilizes a business delegate ( - * {@link BusinessDelegate}) to search for movies in video streaming services. The Business Delegate - * then selects the appropriate service and makes the service call. + *

In this example the client ({@link MobileClient}) utilizes a business delegate ( {@link + * BusinessDelegate}) to search for movies in video streaming services. The Business Delegate then + * selects the appropriate service and makes the service call. */ public class App { diff --git a/business-delegate/src/main/java/com/iluwatar/business/delegate/BusinessDelegate.java b/business-delegate/src/main/java/com/iluwatar/business/delegate/BusinessDelegate.java index 388407fb8..81920c857 100644 --- a/business-delegate/src/main/java/com/iluwatar/business/delegate/BusinessDelegate.java +++ b/business-delegate/src/main/java/com/iluwatar/business/delegate/BusinessDelegate.java @@ -26,9 +26,7 @@ package com.iluwatar.business.delegate; import lombok.Setter; -/** - * BusinessDelegate separates the presentation and business tiers. - */ +/** BusinessDelegate separates the presentation and business tiers. */ @Setter public class BusinessDelegate { diff --git a/business-delegate/src/main/java/com/iluwatar/business/delegate/BusinessLookup.java b/business-delegate/src/main/java/com/iluwatar/business/delegate/BusinessLookup.java index b2d45b9e6..81a1b2f18 100644 --- a/business-delegate/src/main/java/com/iluwatar/business/delegate/BusinessLookup.java +++ b/business-delegate/src/main/java/com/iluwatar/business/delegate/BusinessLookup.java @@ -27,9 +27,7 @@ package com.iluwatar.business.delegate; import java.util.Locale; import lombok.Setter; -/** - * Class for performing service lookups. - */ +/** Class for performing service lookups. */ @Setter public class BusinessLookup { diff --git a/business-delegate/src/main/java/com/iluwatar/business/delegate/MobileClient.java b/business-delegate/src/main/java/com/iluwatar/business/delegate/MobileClient.java index cffc464d3..01b5b6427 100644 --- a/business-delegate/src/main/java/com/iluwatar/business/delegate/MobileClient.java +++ b/business-delegate/src/main/java/com/iluwatar/business/delegate/MobileClient.java @@ -24,9 +24,7 @@ */ package com.iluwatar.business.delegate; -/** - * MobileClient utilizes BusinessDelegate to call the business tier. - */ +/** MobileClient utilizes BusinessDelegate to call the business tier. */ public class MobileClient { private final BusinessDelegate businessDelegate; diff --git a/business-delegate/src/main/java/com/iluwatar/business/delegate/NetflixService.java b/business-delegate/src/main/java/com/iluwatar/business/delegate/NetflixService.java index 83b7cd46e..696480e67 100644 --- a/business-delegate/src/main/java/com/iluwatar/business/delegate/NetflixService.java +++ b/business-delegate/src/main/java/com/iluwatar/business/delegate/NetflixService.java @@ -26,9 +26,7 @@ package com.iluwatar.business.delegate; import lombok.extern.slf4j.Slf4j; -/** - * NetflixService implementation. - */ +/** NetflixService implementation. */ @Slf4j public class NetflixService implements VideoStreamingService { diff --git a/business-delegate/src/main/java/com/iluwatar/business/delegate/VideoStreamingService.java b/business-delegate/src/main/java/com/iluwatar/business/delegate/VideoStreamingService.java index 9ac09f265..594b51850 100644 --- a/business-delegate/src/main/java/com/iluwatar/business/delegate/VideoStreamingService.java +++ b/business-delegate/src/main/java/com/iluwatar/business/delegate/VideoStreamingService.java @@ -24,9 +24,7 @@ */ package com.iluwatar.business.delegate; -/** - * Interface for video streaming service implementations. - */ +/** Interface for video streaming service implementations. */ public interface VideoStreamingService { void doProcessing(); diff --git a/business-delegate/src/main/java/com/iluwatar/business/delegate/YouTubeService.java b/business-delegate/src/main/java/com/iluwatar/business/delegate/YouTubeService.java index 9b239d585..65c2e55ff 100644 --- a/business-delegate/src/main/java/com/iluwatar/business/delegate/YouTubeService.java +++ b/business-delegate/src/main/java/com/iluwatar/business/delegate/YouTubeService.java @@ -26,9 +26,7 @@ package com.iluwatar.business.delegate; import lombok.extern.slf4j.Slf4j; -/** - * YouTubeService implementation. - */ +/** YouTubeService implementation. */ @Slf4j public class YouTubeService implements VideoStreamingService { diff --git a/business-delegate/src/test/java/com/iluwatar/business/delegate/AppTest.java b/business-delegate/src/test/java/com/iluwatar/business/delegate/AppTest.java index 1449f81bd..5f862bf6e 100644 --- a/business-delegate/src/test/java/com/iluwatar/business/delegate/AppTest.java +++ b/business-delegate/src/test/java/com/iluwatar/business/delegate/AppTest.java @@ -24,25 +24,22 @@ */ package com.iluwatar.business.delegate; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -/** - * Tests that Business Delegate example runs without errors. - */ +import org.junit.jupiter.api.Test; + +/** Tests that Business Delegate example runs without errors. */ class AppTest { /** * Issue: Add at least one assertion to this test case. * - * Solution: Inserted assertion to check whether the execution of the main method in {@link App} - * throws an exception. + *

Solution: Inserted assertion to check whether the execution of the main method in {@link + * App} throws an exception. */ - @Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/business-delegate/src/test/java/com/iluwatar/business/delegate/BusinessDelegateTest.java b/business-delegate/src/test/java/com/iluwatar/business/delegate/BusinessDelegateTest.java index 8e8c8eddc..4b8e0ee77 100644 --- a/business-delegate/src/test/java/com/iluwatar/business/delegate/BusinessDelegateTest.java +++ b/business-delegate/src/test/java/com/iluwatar/business/delegate/BusinessDelegateTest.java @@ -24,18 +24,15 @@ */ package com.iluwatar.business.delegate; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - - import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; -/** - * Tests for the {@link BusinessDelegate} - */ +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** Tests for the {@link BusinessDelegate} */ class BusinessDelegateTest { private NetflixService netflixService; @@ -62,8 +59,8 @@ class BusinessDelegateTest { } /** - * In this example the client ({@link MobileClient}) utilizes a business delegate ( - * {@link BusinessDelegate}) to execute a task. The Business Delegate then selects the appropriate + * In this example the client ({@link MobileClient}) utilizes a business delegate ( {@link + * BusinessDelegate}) to execute a task. The Business Delegate then selects the appropriate * service and makes the service call. */ @Test diff --git a/bytecode/pom.xml b/bytecode/pom.xml index eabd294e4..2fb01fe2f 100644 --- a/bytecode/pom.xml +++ b/bytecode/pom.xml @@ -34,6 +34,14 @@ 4.0.0 bytecode + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/bytecode/src/main/java/com/iluwatar/bytecode/App.java b/bytecode/src/main/java/com/iluwatar/bytecode/App.java index c2e3a3b10..9293b5876 100644 --- a/bytecode/src/main/java/com/iluwatar/bytecode/App.java +++ b/bytecode/src/main/java/com/iluwatar/bytecode/App.java @@ -58,9 +58,7 @@ public class App { */ public static void main(String[] args) { - var vm = new VirtualMachine( - new Wizard(45, 7, 11, 0, 0), - new Wizard(36, 18, 8, 0, 0)); + var vm = new VirtualMachine(new Wizard(45, 7, 11, 0, 0), new Wizard(36, 18, 8, 0, 0)); vm.execute(InstructionConverterUtil.convertToByteCode(LITERAL_0)); vm.execute(InstructionConverterUtil.convertToByteCode(LITERAL_0)); diff --git a/bytecode/src/main/java/com/iluwatar/bytecode/Instruction.java b/bytecode/src/main/java/com/iluwatar/bytecode/Instruction.java index 91d394234..25330e73f 100644 --- a/bytecode/src/main/java/com/iluwatar/bytecode/Instruction.java +++ b/bytecode/src/main/java/com/iluwatar/bytecode/Instruction.java @@ -27,24 +27,21 @@ package com.iluwatar.bytecode; import lombok.AllArgsConstructor; import lombok.Getter; -/** - * Representation of instructions understandable by virtual machine. - */ +/** Representation of instructions understandable by virtual machine. */ @AllArgsConstructor @Getter public enum Instruction { - - LITERAL(1), // e.g. "LITERAL 0", push 0 to stack - SET_HEALTH(2), // e.g. "SET_HEALTH", pop health and wizard number, call set health - SET_WISDOM(3), // e.g. "SET_WISDOM", pop wisdom and wizard number, call set wisdom - SET_AGILITY(4), // e.g. "SET_AGILITY", pop agility and wizard number, call set agility - PLAY_SOUND(5), // e.g. "PLAY_SOUND", pop value as wizard number, call play sound + LITERAL(1), // e.g. "LITERAL 0", push 0 to stack + SET_HEALTH(2), // e.g. "SET_HEALTH", pop health and wizard number, call set health + SET_WISDOM(3), // e.g. "SET_WISDOM", pop wisdom and wizard number, call set wisdom + SET_AGILITY(4), // e.g. "SET_AGILITY", pop agility and wizard number, call set agility + PLAY_SOUND(5), // e.g. "PLAY_SOUND", pop value as wizard number, call play sound SPAWN_PARTICLES(6), // e.g. "SPAWN_PARTICLES", pop value as wizard number, call spawn particles - GET_HEALTH(7), // e.g. "GET_HEALTH", pop value as wizard number, push wizard's health - GET_AGILITY(8), // e.g. "GET_AGILITY", pop value as wizard number, push wizard's agility - GET_WISDOM(9), // e.g. "GET_WISDOM", pop value as wizard number, push wizard's wisdom - ADD(10), // e.g. "ADD", pop 2 values, push their sum - DIVIDE(11); // e.g. "DIVIDE", pop 2 values, push their division + GET_HEALTH(7), // e.g. "GET_HEALTH", pop value as wizard number, push wizard's health + GET_AGILITY(8), // e.g. "GET_AGILITY", pop value as wizard number, push wizard's agility + GET_WISDOM(9), // e.g. "GET_WISDOM", pop value as wizard number, push wizard's wisdom + ADD(10), // e.g. "ADD", pop 2 values, push their sum + DIVIDE(11); // e.g. "DIVIDE", pop 2 values, push their division private final int intValue; diff --git a/bytecode/src/main/java/com/iluwatar/bytecode/VirtualMachine.java b/bytecode/src/main/java/com/iluwatar/bytecode/VirtualMachine.java index 2133296ed..7f835d402 100644 --- a/bytecode/src/main/java/com/iluwatar/bytecode/VirtualMachine.java +++ b/bytecode/src/main/java/com/iluwatar/bytecode/VirtualMachine.java @@ -29,9 +29,7 @@ import java.util.concurrent.ThreadLocalRandom; import lombok.Getter; import lombok.extern.slf4j.Slf4j; -/** - * Implementation of virtual machine. - */ +/** Implementation of virtual machine. */ @Getter @Slf4j public class VirtualMachine { @@ -40,19 +38,13 @@ public class VirtualMachine { private final Wizard[] wizards = new Wizard[2]; - /** - * No-args constructor. - */ + /** No-args constructor. */ public VirtualMachine() { - wizards[0] = new Wizard(randomInt(3, 32), randomInt(3, 32), randomInt(3, 32), - 0, 0); - wizards[1] = new Wizard(randomInt(3, 32), randomInt(3, 32), randomInt(3, 32), - 0, 0); + wizards[0] = new Wizard(randomInt(3, 32), randomInt(3, 32), randomInt(3, 32), 0, 0); + wizards[1] = new Wizard(randomInt(3, 32), randomInt(3, 32), randomInt(3, 32), 0, 0); } - /** - * Constructor taking the wizards as arguments. - */ + /** Constructor taking the wizards as arguments. */ public VirtualMachine(Wizard wizard1, Wizard wizard2) { wizards[0] = wizard1; wizards[1] = wizard2; @@ -112,7 +104,6 @@ public class VirtualMachine { case PLAY_SOUND -> { var wizard = stack.pop(); getWizards()[wizard].playSound(); - } case SPAWN_PARTICLES -> { var wizard = stack.pop(); diff --git a/bytecode/src/main/java/com/iluwatar/bytecode/util/InstructionConverterUtil.java b/bytecode/src/main/java/com/iluwatar/bytecode/util/InstructionConverterUtil.java index 6501ac9a3..d45a2aa55 100644 --- a/bytecode/src/main/java/com/iluwatar/bytecode/util/InstructionConverterUtil.java +++ b/bytecode/src/main/java/com/iluwatar/bytecode/util/InstructionConverterUtil.java @@ -26,9 +26,7 @@ package com.iluwatar.bytecode.util; import com.iluwatar.bytecode.Instruction; -/** - * Utility class used for instruction validation and conversion. - */ +/** Utility class used for instruction validation and conversion. */ public class InstructionConverterUtil { /** * Converts instructions represented as String. diff --git a/bytecode/src/test/java/com/iluwatar/bytecode/AppTest.java b/bytecode/src/test/java/com/iluwatar/bytecode/AppTest.java index c56e84939..72d00eb34 100644 --- a/bytecode/src/test/java/com/iluwatar/bytecode/AppTest.java +++ b/bytecode/src/test/java/com/iluwatar/bytecode/AppTest.java @@ -24,24 +24,21 @@ */ package com.iluwatar.bytecode; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -/** - * Application test - */ +import org.junit.jupiter.api.Test; + +/** Application test */ class AppTest { /** * Issue: Add at least one assertion to this test case. * - * Solution: Inserted assertion to check whether the execution of the main method in {@link App} - * throws an exception. + *

Solution: Inserted assertion to check whether the execution of the main method in {@link + * App} throws an exception. */ - @Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/bytecode/src/test/java/com/iluwatar/bytecode/VirtualMachineTest.java b/bytecode/src/test/java/com/iluwatar/bytecode/VirtualMachineTest.java index b6ad5dfe6..1d9a5539f 100644 --- a/bytecode/src/test/java/com/iluwatar/bytecode/VirtualMachineTest.java +++ b/bytecode/src/test/java/com/iluwatar/bytecode/VirtualMachineTest.java @@ -30,9 +30,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import org.junit.jupiter.api.Test; -/** - * Test for {@link VirtualMachine} - */ +/** Test for {@link VirtualMachine} */ class VirtualMachineTest { @Test @@ -55,7 +53,7 @@ class VirtualMachineTest { bytecode[0] = LITERAL.getIntValue(); bytecode[1] = wizardNumber; bytecode[2] = LITERAL.getIntValue(); - bytecode[3] = 50; // health amount + bytecode[3] = 50; // health amount bytecode[4] = SET_HEALTH.getIntValue(); var vm = new VirtualMachine(); @@ -71,7 +69,7 @@ class VirtualMachineTest { bytecode[0] = LITERAL.getIntValue(); bytecode[1] = wizardNumber; bytecode[2] = LITERAL.getIntValue(); - bytecode[3] = 50; // agility amount + bytecode[3] = 50; // agility amount bytecode[4] = SET_AGILITY.getIntValue(); var vm = new VirtualMachine(); @@ -87,7 +85,7 @@ class VirtualMachineTest { bytecode[0] = LITERAL.getIntValue(); bytecode[1] = wizardNumber; bytecode[2] = LITERAL.getIntValue(); - bytecode[3] = 50; // wisdom amount + bytecode[3] = 50; // wisdom amount bytecode[4] = SET_WISDOM.getIntValue(); var vm = new VirtualMachine(); @@ -103,7 +101,7 @@ class VirtualMachineTest { bytecode[0] = LITERAL.getIntValue(); bytecode[1] = wizardNumber; bytecode[2] = LITERAL.getIntValue(); - bytecode[3] = 50; // health amount + bytecode[3] = 50; // health amount bytecode[4] = SET_HEALTH.getIntValue(); bytecode[5] = LITERAL.getIntValue(); bytecode[6] = wizardNumber; diff --git a/bytecode/src/test/java/com/iluwatar/bytecode/util/InstructionConverterUtilTest.java b/bytecode/src/test/java/com/iluwatar/bytecode/util/InstructionConverterUtilTest.java index 494fc9a2e..9dadba1ea 100644 --- a/bytecode/src/test/java/com/iluwatar/bytecode/util/InstructionConverterUtilTest.java +++ b/bytecode/src/test/java/com/iluwatar/bytecode/util/InstructionConverterUtilTest.java @@ -28,9 +28,7 @@ import com.iluwatar.bytecode.Instruction; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -/** - * Test for {@link InstructionConverterUtil} - */ +/** Test for {@link InstructionConverterUtil} */ class InstructionConverterUtilTest { @Test @@ -44,8 +42,9 @@ class InstructionConverterUtilTest { @Test void testInstructions() { - var instructions = "LITERAL 35 SET_HEALTH SET_WISDOM SET_AGILITY PLAY_SOUND" - + " SPAWN_PARTICLES GET_HEALTH ADD DIVIDE"; + var instructions = + "LITERAL 35 SET_HEALTH SET_WISDOM SET_AGILITY PLAY_SOUND" + + " SPAWN_PARTICLES GET_HEALTH ADD DIVIDE"; var bytecode = InstructionConverterUtil.convertToByteCode(instructions); @@ -61,5 +60,4 @@ class InstructionConverterUtilTest { Assertions.assertEquals(Instruction.ADD.getIntValue(), bytecode[8]); Assertions.assertEquals(Instruction.DIVIDE.getIntValue(), bytecode[9]); } - } diff --git a/caching/pom.xml b/caching/pom.xml index d7470b5e4..3ffce74af 100644 --- a/caching/pom.xml +++ b/caching/pom.xml @@ -34,6 +34,14 @@ caching + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/caching/src/main/java/com/iluwatar/caching/App.java b/caching/src/main/java/com/iluwatar/caching/App.java index 563b41afc..8d6af6c09 100644 --- a/caching/src/main/java/com/iluwatar/caching/App.java +++ b/caching/src/main/java/com/iluwatar/caching/App.java @@ -29,59 +29,44 @@ import com.iluwatar.caching.database.DbManagerFactory; import lombok.extern.slf4j.Slf4j; /** - * The Caching pattern describes how to avoid expensive re-acquisition of - * resources by not releasing the resources immediately after their use. - * The resources retain their identity, are kept in some fast-access storage, - * and are re-used to avoid having to acquire them again. There are four main - * caching strategies/techniques in this pattern; each with their own pros and - * cons. They are write-through which writes data to the cache and - * DB in a single transaction, write-around which writes data - * immediately into the DB instead of the cache, write-behind - * which writes data into the cache initially whilst the data is only - * written into the DB when the cache is full, and cache-aside - * which pushes the responsibility of keeping the data synchronized in both - * data sources to the application itself. The read-through - * strategy is also included in the mentioned four strategies -- - * returns data from the cache to the caller if it exists else - * queries from DB and stores it into the cache for future use. These strategies - * determine when the data in the cache should be written back to the backing - * store (i.e. Database) and help keep both data sources - * synchronized/up-to-date. This pattern can improve performance and also helps - * to maintainconsistency between data held in the cache and the data in - * the underlying data store. + * The Caching pattern describes how to avoid expensive re-acquisition of resources by not releasing + * the resources immediately after their use. The resources retain their identity, are kept in some + * fast-access storage, and are re-used to avoid having to acquire them again. There are four main + * caching strategies/techniques in this pattern; each with their own pros and cons. They are + * write-through which writes data to the cache and DB in a single transaction, + * write-around which writes data immediately into the DB instead of the cache, + * write-behind which writes data into the cache initially whilst the data is only written + * into the DB when the cache is full, and cache-aside which pushes the responsibility + * of keeping the data synchronized in both data sources to the application itself. The + * read-through strategy is also included in the mentioned four strategies -- returns data + * from the cache to the caller if it exists else queries from DB and stores it into + * the cache for future use. These strategies determine when the data in the cache should be written + * back to the backing store (i.e. Database) and help keep both data sources + * synchronized/up-to-date. This pattern can improve performance and also helps to + * maintainconsistency between data held in the cache and the data in the underlying data store. * - *

In this example, the user account ({@link UserAccount}) entity is used - * as the underlying application data. The cache itself is implemented as an - * internal (Java) data structure. It adopts a Least-Recently-Used (LRU) - * strategy for evicting data from itself when its full. The four - * strategies are individually tested. The testing of the cache is restricted - * towards saving and querying of user accounts from the - * underlying data store( {@link DbManager}). The main class ( {@link App} - * is not aware of the underlying mechanics of the application - * (i.e. save and query) and whether the data is coming from the cache or the - * DB (i.e. separation of concern). The AppManager ({@link AppManager}) handles - * the transaction of data to-and-from the underlying data store (depending on - * the preferred caching policy/strategy). - *

- * {@literal App --> AppManager --> CacheStore/LRUCache/CachingPolicy --> - * DBManager} - *

+ *

In this example, the user account ({@link UserAccount}) entity is used as the underlying + * application data. The cache itself is implemented as an internal (Java) data structure. It adopts + * a Least-Recently-Used (LRU) strategy for evicting data from itself when its full. The four + * strategies are individually tested. The testing of the cache is restricted towards saving and + * querying of user accounts from the underlying data store( {@link DbManager}). The main class ( + * {@link App} is not aware of the underlying mechanics of the application (i.e. save and query) and + * whether the data is coming from the cache or the DB (i.e. separation of concern). The AppManager + * ({@link AppManager}) handles the transaction of data to-and-from the underlying data store + * (depending on the preferred caching policy/strategy). * - *

- * There are 2 ways to launch the application. - * - to use "in Memory" database. - * - to use the MongoDb as a database + *

{@literal App --> AppManager --> CacheStore/LRUCache/CachingPolicy --> DBManager} * - * To run the application with "in Memory" database, just launch it without parameters - * Example: 'java -jar app.jar' + *

There are 2 ways to launch the application. - to use "in Memory" database. - to use the + * MongoDb as a database * - * To run the application with MongoDb you need to be installed the MongoDb - * in your system, or to launch it in the docker container. - * You may launch docker container from the root of current module with command: - * 'docker-compose up' - * Then you can start the application with parameter --mongo - * Example: 'java -jar app.jar --mongo' - *

+ *

To run the application with "in Memory" database, just launch it without parameters Example: + * 'java -jar app.jar' + * + *

To run the application with MongoDb you need to be installed the MongoDb in your system, or to + * launch it in the docker container. You may launch docker container from the root of current + * module with command: 'docker-compose up' Then you can start the application with parameter + * --mongo Example: 'java -jar app.jar --mongo' * * @see CacheStore * @see LruCache @@ -89,13 +74,10 @@ import lombok.extern.slf4j.Slf4j; */ @Slf4j public class App { - /** - * Constant parameter name to use mongoDB. - */ + /** Constant parameter name to use mongoDB. */ private static final String USE_MONGO_DB = "--mongo"; - /** - * Application manager. - */ + + /** Application manager. */ private final AppManager appManager; /** @@ -152,9 +134,7 @@ public class App { return false; } - /** - * Read-through and write-through. - */ + /** Read-through and write-through. */ public void useReadAndWriteThroughStrategy() { LOGGER.info("# CachingPolicy.THROUGH"); appManager.initCachingPolicy(CachingPolicy.THROUGH); @@ -167,9 +147,7 @@ public class App { appManager.find("001"); } - /** - * Read-through and write-around. - */ + /** Read-through and write-around. */ public void useReadThroughAndWriteAroundStrategy() { LOGGER.info("# CachingPolicy.AROUND"); appManager.initCachingPolicy(CachingPolicy.AROUND); @@ -189,22 +167,14 @@ public class App { appManager.find("002"); } - /** - * Read-through and write-behind. - */ + /** Read-through and write-behind. */ public void useReadThroughAndWriteBehindStrategy() { LOGGER.info("# CachingPolicy.BEHIND"); appManager.initCachingPolicy(CachingPolicy.BEHIND); - var userAccount3 = new UserAccount("003", - "Adam", - "He likes food."); - var userAccount4 = new UserAccount("004", - "Rita", - "She hates cats."); - var userAccount5 = new UserAccount("005", - "Isaac", - "He is allergic to mustard."); + var userAccount3 = new UserAccount("003", "Adam", "He likes food."); + var userAccount4 = new UserAccount("004", "Rita", "She hates cats."); + var userAccount5 = new UserAccount("005", "Isaac", "He is allergic to mustard."); appManager.save(userAccount3); appManager.save(userAccount4); @@ -212,32 +182,22 @@ public class App { LOGGER.info(appManager.printCacheContent()); appManager.find("003"); LOGGER.info(appManager.printCacheContent()); - UserAccount userAccount6 = new UserAccount("006", - "Yasha", - "She is an only child."); + UserAccount userAccount6 = new UserAccount("006", "Yasha", "She is an only child."); appManager.save(userAccount6); LOGGER.info(appManager.printCacheContent()); appManager.find("004"); LOGGER.info(appManager.printCacheContent()); } - /** - * Cache-Aside. - */ + /** Cache-Aside. */ public void useCacheAsideStrategy() { LOGGER.info("# CachingPolicy.ASIDE"); appManager.initCachingPolicy(CachingPolicy.ASIDE); LOGGER.info(appManager.printCacheContent()); - var userAccount3 = new UserAccount("003", - "Adam", - "He likes food."); - var userAccount4 = new UserAccount("004", - "Rita", - "She hates cats."); - var userAccount5 = new UserAccount("005", - "Isaac", - "He is allergic to mustard."); + var userAccount3 = new UserAccount("003", "Adam", "He likes food."); + var userAccount4 = new UserAccount("004", "Rita", "She hates cats."); + var userAccount5 = new UserAccount("005", "Isaac", "He is allergic to mustard."); appManager.save(userAccount3); appManager.save(userAccount4); appManager.save(userAccount5); diff --git a/caching/src/main/java/com/iluwatar/caching/AppManager.java b/caching/src/main/java/com/iluwatar/caching/AppManager.java index 3d2985375..c1d21fea3 100644 --- a/caching/src/main/java/com/iluwatar/caching/AppManager.java +++ b/caching/src/main/java/com/iluwatar/caching/AppManager.java @@ -29,26 +29,21 @@ import java.util.Optional; import lombok.extern.slf4j.Slf4j; /** - * AppManager helps to bridge the gap in communication between the main class - * and the application's back-end. DB connection is initialized through this - * class. The chosen caching strategy/policy is also initialized here. - * Before the cache can be used, the size of the cache has to be set. - * Depending on the chosen caching policy, AppManager will call the - * appropriate function in the CacheStore class. + * AppManager helps to bridge the gap in communication between the main class and the application's + * back-end. DB connection is initialized through this class. The chosen caching strategy/policy is + * also initialized here. Before the cache can be used, the size of the cache has to be set. + * Depending on the chosen caching policy, AppManager will call the appropriate function in the + * CacheStore class. */ @Slf4j public class AppManager { - /** - * Caching Policy. - */ + /** Caching Policy. */ private CachingPolicy cachingPolicy; - /** - * Database Manager. - */ + + /** Database Manager. */ private final DbManager dbManager; - /** - * Cache Store. - */ + + /** Cache Store. */ private final CacheStore cacheStore; /** @@ -62,9 +57,9 @@ public class AppManager { } /** - * Developer/Tester is able to choose whether the application should use - * MongoDB as its underlying data storage or a simple Java data structure - * to (temporarily) store the data/objects during runtime. + * Developer/Tester is able to choose whether the application should use MongoDB as its underlying + * data storage or a simple Java data structure to (temporarily) store the data/objects during + * runtime. */ public void initDb() { dbManager.connect(); @@ -91,8 +86,7 @@ public class AppManager { */ public UserAccount find(final String userId) { LOGGER.info("Trying to find {} in cache", userId); - if (cachingPolicy == CachingPolicy.THROUGH - || cachingPolicy == CachingPolicy.AROUND) { + if (cachingPolicy == CachingPolicy.THROUGH || cachingPolicy == CachingPolicy.AROUND) { return cacheStore.readThrough(userId); } else if (cachingPolicy == CachingPolicy.BEHIND) { return cacheStore.readThroughWithWriteBackPolicy(userId); @@ -147,12 +141,12 @@ public class AppManager { */ private UserAccount findAside(final String userId) { return Optional.ofNullable(cacheStore.get(userId)) - .or(() -> { - Optional userAccount = - Optional.ofNullable(dbManager.readFromDb(userId)); + .or( + () -> { + Optional userAccount = Optional.ofNullable(dbManager.readFromDb(userId)); userAccount.ifPresent(account -> cacheStore.set(userId, account)); return userAccount; }) - .orElse(null); + .orElse(null); } } diff --git a/caching/src/main/java/com/iluwatar/caching/CacheStore.java b/caching/src/main/java/com/iluwatar/caching/CacheStore.java index 2c7184f57..b26c52b22 100644 --- a/caching/src/main/java/com/iluwatar/caching/CacheStore.java +++ b/caching/src/main/java/com/iluwatar/caching/CacheStore.java @@ -30,27 +30,21 @@ import java.util.Optional; import java.util.stream.Collectors; import lombok.extern.slf4j.Slf4j; -/** - * The caching strategies are implemented in this class. - */ +/** The caching strategies are implemented in this class. */ @Slf4j public class CacheStore { - /** - * Cache capacity. - */ + /** Cache capacity. */ private static final int CAPACITY = 3; - /** - * Lru cache see {@link LruCache}. - */ + /** Lru cache see {@link LruCache}. */ private LruCache cache; - /** - * DbManager. - */ + + /** DbManager. */ private final DbManager dbManager; /** * Cache Store. + * * @param dataBaseManager {@link DbManager} */ public CacheStore(final DbManager dataBaseManager) { @@ -60,6 +54,7 @@ public class CacheStore { /** * Init cache capacity. + * * @param capacity int */ public void initCapacity(final int capacity) { @@ -72,6 +67,7 @@ public class CacheStore { /** * Get user account using read-through cache. + * * @param userId {@link String} * @return {@link UserAccount} */ @@ -88,6 +84,7 @@ public class CacheStore { /** * Get user account using write-through cache. + * * @param userAccount {@link UserAccount} */ public void writeThrough(final UserAccount userAccount) { @@ -101,6 +98,7 @@ public class CacheStore { /** * Get user account using write-around cache. + * * @param userAccount {@link UserAccount} */ public void writeAround(final UserAccount userAccount) { @@ -116,6 +114,7 @@ public class CacheStore { /** * Get user account using read-through cache with write-back policy. + * * @param userId {@link String} * @return {@link UserAccount} */ @@ -137,6 +136,7 @@ public class CacheStore { /** * Set user account. + * * @param userAccount {@link UserAccount} */ public void writeBehind(final UserAccount userAccount) { @@ -148,18 +148,14 @@ public class CacheStore { cache.set(userAccount.getUserId(), userAccount); } - /** - * Clears cache. - */ + /** Clears cache. */ public void clearCache() { if (cache != null) { cache.clear(); } } - /** - * Writes remaining content in the cache into the DB. - */ + /** Writes remaining content in the cache into the DB. */ public void flushCache() { LOGGER.info("# flushCache..."); Optional.ofNullable(cache) @@ -171,6 +167,7 @@ public class CacheStore { /** * Print user accounts. + * * @return {@link String} */ public String print() { @@ -184,6 +181,7 @@ public class CacheStore { /** * Delegate to backing cache store. + * * @param userId {@link String} * @return {@link UserAccount} */ @@ -193,6 +191,7 @@ public class CacheStore { /** * Delegate to backing cache store. + * * @param userId {@link String} * @param userAccount {@link UserAccount} */ @@ -202,6 +201,7 @@ public class CacheStore { /** * Delegate to backing cache store. + * * @param userId {@link String} */ public void invalidate(final String userId) { diff --git a/caching/src/main/java/com/iluwatar/caching/CachingPolicy.java b/caching/src/main/java/com/iluwatar/caching/CachingPolicy.java index dcd5711db..0ec07ced7 100644 --- a/caching/src/main/java/com/iluwatar/caching/CachingPolicy.java +++ b/caching/src/main/java/com/iluwatar/caching/CachingPolicy.java @@ -27,31 +27,19 @@ package com.iluwatar.caching; import lombok.AllArgsConstructor; import lombok.Getter; -/** - * Enum class containing the four caching strategies implemented in the pattern. - */ +/** Enum class containing the four caching strategies implemented in the pattern. */ @AllArgsConstructor @Getter public enum CachingPolicy { - /** - * Through. - */ + /** Through. */ THROUGH("through"), - /** - * AROUND. - */ + /** AROUND. */ AROUND("around"), - /** - * BEHIND. - */ + /** BEHIND. */ BEHIND("behind"), - /** - * ASIDE. - */ + /** ASIDE. */ ASIDE("aside"); - /** - * Policy value. - */ + /** Policy value. */ private final String policy; } diff --git a/caching/src/main/java/com/iluwatar/caching/LruCache.java b/caching/src/main/java/com/iluwatar/caching/LruCache.java index ef94bf482..9c9107de6 100644 --- a/caching/src/main/java/com/iluwatar/caching/LruCache.java +++ b/caching/src/main/java/com/iluwatar/caching/LruCache.java @@ -30,42 +30,33 @@ import java.util.List; import java.util.Map; import lombok.extern.slf4j.Slf4j; - /** - * Data structure/implementation of the application's cache. The data structure - * consists of a hash table attached with a doubly linked-list. The linked-list - * helps in capturing and maintaining the LRU data in the cache. When a data is - * queried (from the cache), added (to the cache), or updated, the data is - * moved to the front of the list to depict itself as the most-recently-used - * data. The LRU data is always at the end of the list. + * Data structure/implementation of the application's cache. The data structure consists of a hash + * table attached with a doubly linked-list. The linked-list helps in capturing and maintaining the + * LRU data in the cache. When a data is queried (from the cache), added (to the cache), or updated, + * the data is moved to the front of the list to depict itself as the most-recently-used data. The + * LRU data is always at the end of the list. */ @Slf4j public class LruCache { - /** - * Static class Node. - */ + /** Static class Node. */ static class Node { - /** - * user id. - */ + /** user id. */ private final String userId; - /** - * User Account. - */ + + /** User Account. */ private UserAccount userAccount; - /** - * previous. - */ + + /** previous. */ private Node previous; - /** - * next. - */ + + /** next. */ private Node next; /** * Node definition. * - * @param id String + * @param id String * @param account {@link UserAccount} */ Node(final String id, final UserAccount account) { @@ -74,21 +65,16 @@ public class LruCache { } } - /** - * Capacity of Cache. - */ + /** Capacity of Cache. */ private int capacity; - /** - * Cache {@link HashMap}. - */ + + /** Cache {@link HashMap}. */ private Map cache = new HashMap<>(); - /** - * Head. - */ + + /** Head. */ private Node head; - /** - * End. - */ + + /** End. */ private Node end; /** @@ -155,7 +141,7 @@ public class LruCache { * Set user account. * * @param userAccount {@link UserAccount} - * @param userId {@link String} + * @param userId {@link String} */ public void set(final String userId, final UserAccount userAccount) { if (cache.containsKey(userId)) { @@ -195,14 +181,14 @@ public class LruCache { public void invalidate(final String userId) { var toBeRemoved = cache.remove(userId); if (toBeRemoved != null) { - LOGGER.info("# {} has been updated! " - + "Removing older version from cache...", userId); + LOGGER.info("# {} has been updated! " + "Removing older version from cache...", userId); remove(toBeRemoved); } } /** * Check if the cache is full. + * * @return boolean */ public boolean isFull() { @@ -218,9 +204,7 @@ public class LruCache { return end.userAccount; } - /** - * Clear cache. - */ + /** Clear cache. */ public void clear() { head = null; end = null; diff --git a/caching/src/main/java/com/iluwatar/caching/UserAccount.java b/caching/src/main/java/com/iluwatar/caching/UserAccount.java index 73100c0a6..561c942ac 100644 --- a/caching/src/main/java/com/iluwatar/caching/UserAccount.java +++ b/caching/src/main/java/com/iluwatar/caching/UserAccount.java @@ -29,24 +29,18 @@ import lombok.Data; import lombok.EqualsAndHashCode; import lombok.ToString; -/** - * Entity class (stored in cache and DB) used in the application. - */ +/** Entity class (stored in cache and DB) used in the application. */ @Data @AllArgsConstructor @ToString @EqualsAndHashCode public class UserAccount { - /** - * User Id. - */ + /** User Id. */ private String userId; - /** - * User Name. - */ + + /** User Name. */ private String userName; - /** - * Additional Info. - */ + + /** Additional Info. */ private String additionalInfo; } diff --git a/caching/src/main/java/com/iluwatar/caching/constants/CachingConstants.java b/caching/src/main/java/com/iluwatar/caching/constants/CachingConstants.java index 908fca8ea..5e8fc415d 100644 --- a/caching/src/main/java/com/iluwatar/caching/constants/CachingConstants.java +++ b/caching/src/main/java/com/iluwatar/caching/constants/CachingConstants.java @@ -24,30 +24,20 @@ */ package com.iluwatar.caching.constants; -/** - * Constant class for defining constants. - */ +/** Constant class for defining constants. */ public final class CachingConstants { - /** - * User Account. - */ + /** User Account. */ public static final String USER_ACCOUNT = "user_accounts"; - /** - * User ID. - */ + + /** User ID. */ public static final String USER_ID = "userID"; - /** - * User Name. - */ + + /** User Name. */ public static final String USER_NAME = "userName"; - /** - * Additional Info. - */ + + /** Additional Info. */ public static final String ADD_INFO = "additionalInfo"; - /** - * Constructor. - */ - private CachingConstants() { - } + /** Constructor. */ + private CachingConstants() {} } diff --git a/caching/src/main/java/com/iluwatar/caching/constants/package-info.java b/caching/src/main/java/com/iluwatar/caching/constants/package-info.java index 9356e7e7b..b94476cba 100644 --- a/caching/src/main/java/com/iluwatar/caching/constants/package-info.java +++ b/caching/src/main/java/com/iluwatar/caching/constants/package-info.java @@ -22,7 +22,5 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -/** - * Constants. - */ +/** Constants. */ package com.iluwatar.caching.constants; diff --git a/caching/src/main/java/com/iluwatar/caching/database/DbManager.java b/caching/src/main/java/com/iluwatar/caching/database/DbManager.java index 16b60fc82..14b98a66b 100644 --- a/caching/src/main/java/com/iluwatar/caching/database/DbManager.java +++ b/caching/src/main/java/com/iluwatar/caching/database/DbManager.java @@ -27,19 +27,15 @@ package com.iluwatar.caching.database; import com.iluwatar.caching.UserAccount; /** - *

DBManager handles the communication with the underlying data store i.e. - * Database. It contains the implemented methods for querying, inserting, - * and updating data. MongoDB was used as the database for the application.

+ * DBManager handles the communication with the underlying data store i.e. Database. It contains the + * implemented methods for querying, inserting, and updating data. MongoDB was used as the database + * for the application. */ public interface DbManager { - /** - * Connect to DB. - */ + /** Connect to DB. */ void connect(); - /** - * Disconnect from DB. - */ + /** Disconnect from DB. */ void disconnect(); /** diff --git a/caching/src/main/java/com/iluwatar/caching/database/DbManagerFactory.java b/caching/src/main/java/com/iluwatar/caching/database/DbManagerFactory.java index ee7a4a04b..92031b7c9 100644 --- a/caching/src/main/java/com/iluwatar/caching/database/DbManagerFactory.java +++ b/caching/src/main/java/com/iluwatar/caching/database/DbManagerFactory.java @@ -24,15 +24,10 @@ */ package com.iluwatar.caching.database; -/** - * Creates the database connection according the input parameter. - */ +/** Creates the database connection according the input parameter. */ public final class DbManagerFactory { - /** - * Private constructor. - */ - private DbManagerFactory() { - } + /** Private constructor. */ + private DbManagerFactory() {} /** * Init database. diff --git a/caching/src/main/java/com/iluwatar/caching/database/MongoDb.java b/caching/src/main/java/com/iluwatar/caching/database/MongoDb.java index f2fa696cc..e47eef55c 100644 --- a/caching/src/main/java/com/iluwatar/caching/database/MongoDb.java +++ b/caching/src/main/java/com/iluwatar/caching/database/MongoDb.java @@ -40,10 +40,7 @@ import com.mongodb.client.model.UpdateOptions; import lombok.extern.slf4j.Slf4j; import org.bson.Document; -/** - * Implementation of DatabaseManager. - * implements base methods to work with MongoDb. - */ +/** Implementation of DatabaseManager. implements base methods to work with MongoDb. */ @Slf4j public class MongoDb implements DbManager { private static final String DATABASE_NAME = "admin"; @@ -56,14 +53,11 @@ public class MongoDb implements DbManager { this.db = db; } - /** - * Connect to Db. Check th connection - */ + /** Connect to Db. Check th connection */ @Override public void connect() { - MongoCredential mongoCredential = MongoCredential.createCredential(MONGO_USER, - DATABASE_NAME, - MONGO_PASSWORD.toCharArray()); + MongoCredential mongoCredential = + MongoCredential.createCredential(MONGO_USER, DATABASE_NAME, MONGO_PASSWORD.toCharArray()); MongoClientOptions options = MongoClientOptions.builder().build(); client = new MongoClient(new ServerAddress(), mongoCredential, options); db = client.getDatabase(DATABASE_NAME); @@ -82,9 +76,8 @@ public class MongoDb implements DbManager { */ @Override public UserAccount readFromDb(final String userId) { - var iterable = db - .getCollection(CachingConstants.USER_ACCOUNT) - .find(new Document(USER_ID, userId)); + var iterable = + db.getCollection(CachingConstants.USER_ACCOUNT).find(new Document(USER_ID, userId)); if (iterable.first() == null) { return null; } @@ -106,11 +99,11 @@ public class MongoDb implements DbManager { */ @Override public UserAccount writeToDb(final UserAccount userAccount) { - db.getCollection(USER_ACCOUNT).insertOne( + db.getCollection(USER_ACCOUNT) + .insertOne( new Document(USER_ID, userAccount.getUserId()) - .append(USER_NAME, userAccount.getUserName()) - .append(ADD_INFO, userAccount.getAdditionalInfo()) - ); + .append(USER_NAME, userAccount.getUserName()) + .append(ADD_INFO, userAccount.getAdditionalInfo())); return userAccount; } @@ -123,10 +116,10 @@ public class MongoDb implements DbManager { @Override public UserAccount updateDb(final UserAccount userAccount) { Document id = new Document(USER_ID, userAccount.getUserId()); - Document dataSet = new Document(USER_NAME, userAccount.getUserName()) + Document dataSet = + new Document(USER_NAME, userAccount.getUserName()) .append(ADD_INFO, userAccount.getAdditionalInfo()); - db.getCollection(CachingConstants.USER_ACCOUNT) - .updateOne(id, new Document("$set", dataSet)); + db.getCollection(CachingConstants.USER_ACCOUNT).updateOne(id, new Document("$set", dataSet)); return userAccount; } @@ -141,15 +134,15 @@ public class MongoDb implements DbManager { String userId = userAccount.getUserId(); String userName = userAccount.getUserName(); String additionalInfo = userAccount.getAdditionalInfo(); - db.getCollection(CachingConstants.USER_ACCOUNT).updateOne( + db.getCollection(CachingConstants.USER_ACCOUNT) + .updateOne( new Document(USER_ID, userId), - new Document("$set", - new Document(USER_ID, userId) - .append(USER_NAME, userName) - .append(ADD_INFO, additionalInfo) - ), - new UpdateOptions().upsert(true) - ); + new Document( + "$set", + new Document(USER_ID, userId) + .append(USER_NAME, userName) + .append(ADD_INFO, additionalInfo)), + new UpdateOptions().upsert(true)); return userAccount; } } diff --git a/caching/src/main/java/com/iluwatar/caching/database/VirtualDb.java b/caching/src/main/java/com/iluwatar/caching/database/VirtualDb.java index 6155e1d69..6040ca174 100644 --- a/caching/src/main/java/com/iluwatar/caching/database/VirtualDb.java +++ b/caching/src/main/java/com/iluwatar/caching/database/VirtualDb.java @@ -28,19 +28,12 @@ import com.iluwatar.caching.UserAccount; import java.util.HashMap; import java.util.Map; -/** - * Implementation of DatabaseManager. - * implements base methods to work with hashMap as database. - */ +/** Implementation of DatabaseManager. implements base methods to work with hashMap as database. */ public class VirtualDb implements DbManager { - /** - * Virtual DataBase. - */ + /** Virtual DataBase. */ private Map db; - /** - * Creates new HashMap. - */ + /** Creates new HashMap. */ @Override public void connect() { db = new HashMap<>(); diff --git a/caching/src/main/java/com/iluwatar/caching/database/package-info.java b/caching/src/main/java/com/iluwatar/caching/database/package-info.java index 535771a7d..631cb4c58 100644 --- a/caching/src/main/java/com/iluwatar/caching/database/package-info.java +++ b/caching/src/main/java/com/iluwatar/caching/database/package-info.java @@ -22,7 +22,5 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -/** - * Database classes. - */ +/** Database classes. */ package com.iluwatar.caching.database; diff --git a/caching/src/test/java/com/iluwatar/caching/AppTest.java b/caching/src/test/java/com/iluwatar/caching/AppTest.java index 510b3a256..35e01edbc 100644 --- a/caching/src/test/java/com/iluwatar/caching/AppTest.java +++ b/caching/src/test/java/com/iluwatar/caching/AppTest.java @@ -24,23 +24,20 @@ */ package com.iluwatar.caching; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -/** - * Tests that Caching example runs without errors. - */ +import org.junit.jupiter.api.Test; + +/** Tests that Caching example runs without errors. */ class AppTest { /** * Issue: Add at least one assertion to this test case. - *

- * Solution: Inserted assertion to check whether the execution of the main method in {@link App} - * throws an exception. + * + *

Solution: Inserted assertion to check whether the execution of the main method in {@link + * App} throws an exception. */ - @Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/caching/src/test/java/com/iluwatar/caching/CachingTest.java b/caching/src/test/java/com/iluwatar/caching/CachingTest.java index 89c447dc1..d17cff5bd 100644 --- a/caching/src/test/java/com/iluwatar/caching/CachingTest.java +++ b/caching/src/test/java/com/iluwatar/caching/CachingTest.java @@ -24,20 +24,16 @@ */ package com.iluwatar.caching; +import static org.junit.jupiter.api.Assertions.assertNotNull; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertNotNull; - -/** - * Application test - */ +/** Application test */ class CachingTest { private App app; - /** - * Setup of application test includes: initializing DB connection and cache size/capacity. - */ + /** Setup of application test includes: initializing DB connection and cache size/capacity. */ @BeforeEach void setUp() { // VirtualDB (instead of MongoDB) was used in running the JUnit tests diff --git a/caching/src/test/java/com/iluwatar/caching/database/MongoDbTest.java b/caching/src/test/java/com/iluwatar/caching/database/MongoDbTest.java index 5cb130a34..87cc1ed6f 100644 --- a/caching/src/test/java/com/iluwatar/caching/database/MongoDbTest.java +++ b/caching/src/test/java/com/iluwatar/caching/database/MongoDbTest.java @@ -24,6 +24,13 @@ */ package com.iluwatar.caching.database; +import static com.iluwatar.caching.constants.CachingConstants.ADD_INFO; +import static com.iluwatar.caching.constants.CachingConstants.USER_ID; +import static com.iluwatar.caching.constants.CachingConstants.USER_NAME; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.*; + import com.iluwatar.caching.UserAccount; import com.iluwatar.caching.constants.CachingConstants; import com.mongodb.client.FindIterable; @@ -34,20 +41,12 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mock; -import static com.iluwatar.caching.constants.CachingConstants.ADD_INFO; -import static com.iluwatar.caching.constants.CachingConstants.USER_ID; -import static com.iluwatar.caching.constants.CachingConstants.USER_NAME; -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.Mockito.*; - class MongoDbTest { private static final String ID = "123"; private static final String NAME = "Some user"; private static final String ADDITIONAL_INFO = "Some app Info"; - @Mock - MongoDatabase db; + @Mock MongoDatabase db; private MongoDb mongoDb = new MongoDb(); private UserAccount userAccount; @@ -66,9 +65,8 @@ class MongoDbTest { @Test void readFromDb() { - Document document = new Document(USER_ID, ID) - .append(USER_NAME, NAME) - .append(ADD_INFO, ADDITIONAL_INFO); + Document document = + new Document(USER_ID, ID).append(USER_NAME, NAME).append(ADD_INFO, ADDITIONAL_INFO); MongoCollection mongoCollection = mock(MongoCollection.class); when(db.getCollection(CachingConstants.USER_ACCOUNT)).thenReturn(mongoCollection); @@ -77,27 +75,36 @@ class MongoDbTest { when(findIterable.first()).thenReturn(document); - assertEquals(mongoDb.readFromDb(ID),userAccount); + assertEquals(mongoDb.readFromDb(ID), userAccount); } @Test void writeToDb() { MongoCollection mongoCollection = mock(MongoCollection.class); when(db.getCollection(CachingConstants.USER_ACCOUNT)).thenReturn(mongoCollection); - assertDoesNotThrow(()-> {mongoDb.writeToDb(userAccount);}); + assertDoesNotThrow( + () -> { + mongoDb.writeToDb(userAccount); + }); } @Test void updateDb() { MongoCollection mongoCollection = mock(MongoCollection.class); when(db.getCollection(CachingConstants.USER_ACCOUNT)).thenReturn(mongoCollection); - assertDoesNotThrow(()-> {mongoDb.updateDb(userAccount);}); + assertDoesNotThrow( + () -> { + mongoDb.updateDb(userAccount); + }); } @Test void upsertDb() { MongoCollection mongoCollection = mock(MongoCollection.class); when(db.getCollection(CachingConstants.USER_ACCOUNT)).thenReturn(mongoCollection); - assertDoesNotThrow(()-> {mongoDb.upsertDb(userAccount);}); + assertDoesNotThrow( + () -> { + mongoDb.upsertDb(userAccount); + }); } -} \ No newline at end of file +} diff --git a/callback/pom.xml b/callback/pom.xml index cdae8e870..772615f45 100644 --- a/callback/pom.xml +++ b/callback/pom.xml @@ -34,6 +34,14 @@ callback + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/callback/src/main/java/com/iluwatar/callback/App.java b/callback/src/main/java/com/iluwatar/callback/App.java index a574126c4..7b630f8da 100644 --- a/callback/src/main/java/com/iluwatar/callback/App.java +++ b/callback/src/main/java/com/iluwatar/callback/App.java @@ -34,12 +34,9 @@ import lombok.extern.slf4j.Slf4j; @Slf4j public final class App { - private App() { - } + private App() {} - /** - * Program entry point. - */ + /** Program entry point. */ public static void main(final String[] args) { var task = new SimpleTask(); task.executeWith(() -> LOGGER.info("I'm done now.")); diff --git a/callback/src/main/java/com/iluwatar/callback/Callback.java b/callback/src/main/java/com/iluwatar/callback/Callback.java index 14de46b21..7b75b5c71 100644 --- a/callback/src/main/java/com/iluwatar/callback/Callback.java +++ b/callback/src/main/java/com/iluwatar/callback/Callback.java @@ -24,9 +24,7 @@ */ package com.iluwatar.callback; -/** - * Callback interface. - */ +/** Callback interface. */ public interface Callback { void call(); diff --git a/callback/src/main/java/com/iluwatar/callback/SimpleTask.java b/callback/src/main/java/com/iluwatar/callback/SimpleTask.java index a7ac0a939..bbf060a6f 100644 --- a/callback/src/main/java/com/iluwatar/callback/SimpleTask.java +++ b/callback/src/main/java/com/iluwatar/callback/SimpleTask.java @@ -26,9 +26,7 @@ package com.iluwatar.callback; import lombok.extern.slf4j.Slf4j; -/** - * Implementation of task that need to be executed. - */ +/** Implementation of task that need to be executed. */ @Slf4j public final class SimpleTask extends Task { diff --git a/callback/src/main/java/com/iluwatar/callback/Task.java b/callback/src/main/java/com/iluwatar/callback/Task.java index 30481f747..d69697454 100644 --- a/callback/src/main/java/com/iluwatar/callback/Task.java +++ b/callback/src/main/java/com/iluwatar/callback/Task.java @@ -26,14 +26,10 @@ package com.iluwatar.callback; import java.util.Optional; -/** - * Template-method class for callback hook execution. - */ +/** Template-method class for callback hook execution. */ public abstract class Task { - /** - * Execute with callback. - */ + /** Execute with callback. */ final void executeWith(Callback callback) { execute(); Optional.ofNullable(callback).ifPresent(Callback::call); diff --git a/callback/src/test/java/com/iluwatar/callback/AppTest.java b/callback/src/test/java/com/iluwatar/callback/AppTest.java index 26c5df95f..ca0e93072 100644 --- a/callback/src/test/java/com/iluwatar/callback/AppTest.java +++ b/callback/src/test/java/com/iluwatar/callback/AppTest.java @@ -24,25 +24,22 @@ */ package com.iluwatar.callback; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -/** - * Tests that Callback example runs without errors. - */ +import org.junit.jupiter.api.Test; + +/** Tests that Callback example runs without errors. */ class AppTest { /** * Issue: Add at least one assertion to this test case. * - * Solution: Inserted assertion to check whether the execution of the main method in {@link App} - * throws an exception. + *

Solution: Inserted assertion to check whether the execution of the main method in {@link + * App} throws an exception. */ - @Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/callback/src/test/java/com/iluwatar/callback/CallbackTest.java b/callback/src/test/java/com/iluwatar/callback/CallbackTest.java index d8dab98e6..99939d491 100644 --- a/callback/src/test/java/com/iluwatar/callback/CallbackTest.java +++ b/callback/src/test/java/com/iluwatar/callback/CallbackTest.java @@ -31,8 +31,8 @@ import org.junit.jupiter.api.Test; /** * Add a field as a counter. Every time the callback method is called increment this field. Unit * test checks that the field is being incremented. - *

- * Could be done with mock objects as well where the call method call is verified. + * + *

Could be done with mock objects as well where the call method call is verified. */ class CallbackTest { @@ -53,6 +53,5 @@ class CallbackTest { task.executeWith(callback); assertEquals(Integer.valueOf(2), callingCount, "Callback called twice"); - } } diff --git a/chain-of-responsibility/pom.xml b/chain-of-responsibility/pom.xml index f72502045..e6a7fb974 100644 --- a/chain-of-responsibility/pom.xml +++ b/chain-of-responsibility/pom.xml @@ -34,6 +34,14 @@ chain-of-responsibility + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/chain-of-responsibility/src/main/java/com/iluwatar/chain/OrcCommander.java b/chain-of-responsibility/src/main/java/com/iluwatar/chain/OrcCommander.java index 70ea09463..ad3749c98 100644 --- a/chain-of-responsibility/src/main/java/com/iluwatar/chain/OrcCommander.java +++ b/chain-of-responsibility/src/main/java/com/iluwatar/chain/OrcCommander.java @@ -26,9 +26,7 @@ package com.iluwatar.chain; import lombok.extern.slf4j.Slf4j; -/** - * OrcCommander. - */ +/** OrcCommander. */ @Slf4j public class OrcCommander implements RequestHandler { @Override diff --git a/chain-of-responsibility/src/main/java/com/iluwatar/chain/OrcKing.java b/chain-of-responsibility/src/main/java/com/iluwatar/chain/OrcKing.java index c01aa151a..7500ebf3a 100644 --- a/chain-of-responsibility/src/main/java/com/iluwatar/chain/OrcKing.java +++ b/chain-of-responsibility/src/main/java/com/iluwatar/chain/OrcKing.java @@ -28,9 +28,7 @@ import java.util.Arrays; import java.util.Comparator; import java.util.List; -/** - * OrcKing makes requests that are handled by the chain. - */ +/** OrcKing makes requests that are handled by the chain. */ public class OrcKing { private List handlers; @@ -43,12 +41,9 @@ public class OrcKing { handlers = Arrays.asList(new OrcCommander(), new OrcOfficer(), new OrcSoldier()); } - /** - * Handle request by the chain. - */ + /** Handle request by the chain. */ public void makeRequest(Request req) { - handlers - .stream() + handlers.stream() .sorted(Comparator.comparing(RequestHandler::getPriority)) .filter(handler -> handler.canHandleRequest(req)) .findFirst() diff --git a/chain-of-responsibility/src/main/java/com/iluwatar/chain/OrcOfficer.java b/chain-of-responsibility/src/main/java/com/iluwatar/chain/OrcOfficer.java index 7138a001c..0edb57911 100644 --- a/chain-of-responsibility/src/main/java/com/iluwatar/chain/OrcOfficer.java +++ b/chain-of-responsibility/src/main/java/com/iluwatar/chain/OrcOfficer.java @@ -26,9 +26,7 @@ package com.iluwatar.chain; import lombok.extern.slf4j.Slf4j; -/** - * OrcOfficer. - */ +/** OrcOfficer. */ @Slf4j public class OrcOfficer implements RequestHandler { @Override @@ -52,4 +50,3 @@ public class OrcOfficer implements RequestHandler { return "Orc officer"; } } - diff --git a/chain-of-responsibility/src/main/java/com/iluwatar/chain/OrcSoldier.java b/chain-of-responsibility/src/main/java/com/iluwatar/chain/OrcSoldier.java index 6650b3474..7398844cd 100644 --- a/chain-of-responsibility/src/main/java/com/iluwatar/chain/OrcSoldier.java +++ b/chain-of-responsibility/src/main/java/com/iluwatar/chain/OrcSoldier.java @@ -26,9 +26,7 @@ package com.iluwatar.chain; import lombok.extern.slf4j.Slf4j; -/** - * OrcSoldier. - */ +/** OrcSoldier. */ @Slf4j public class OrcSoldier implements RequestHandler { @Override diff --git a/chain-of-responsibility/src/main/java/com/iluwatar/chain/Request.java b/chain-of-responsibility/src/main/java/com/iluwatar/chain/Request.java index 05c0d88d5..2f9442264 100644 --- a/chain-of-responsibility/src/main/java/com/iluwatar/chain/Request.java +++ b/chain-of-responsibility/src/main/java/com/iluwatar/chain/Request.java @@ -27,9 +27,7 @@ package com.iluwatar.chain; import java.util.Objects; import lombok.Getter; -/** - * Request. - */ +/** Request. */ @Getter public class Request { @@ -39,9 +37,7 @@ public class Request { */ private final RequestType requestType; - /** - * A description of the request. - */ + /** A description of the request. */ private final String requestDescription; /** @@ -53,7 +49,7 @@ public class Request { /** * Create a new request of the given type and accompanied description. * - * @param requestType The type of request + * @param requestType The type of request * @param requestDescription The description of the request */ public Request(final RequestType requestType, final String requestDescription) { @@ -61,9 +57,7 @@ public class Request { this.requestDescription = Objects.requireNonNull(requestDescription); } - /** - * Mark the request as handled. - */ + /** Mark the request as handled. */ public void markHandled() { this.handled = true; } @@ -72,5 +66,4 @@ public class Request { public String toString() { return getRequestDescription(); } - } diff --git a/chain-of-responsibility/src/main/java/com/iluwatar/chain/RequestHandler.java b/chain-of-responsibility/src/main/java/com/iluwatar/chain/RequestHandler.java index ca46c44bb..89eafbdcb 100644 --- a/chain-of-responsibility/src/main/java/com/iluwatar/chain/RequestHandler.java +++ b/chain-of-responsibility/src/main/java/com/iluwatar/chain/RequestHandler.java @@ -24,9 +24,7 @@ */ package com.iluwatar.chain; -/** - * RequestHandler. - */ +/** RequestHandler. */ public interface RequestHandler { boolean canHandleRequest(Request req); diff --git a/chain-of-responsibility/src/main/java/com/iluwatar/chain/RequestType.java b/chain-of-responsibility/src/main/java/com/iluwatar/chain/RequestType.java index 17277cad3..f3cc73c97 100644 --- a/chain-of-responsibility/src/main/java/com/iluwatar/chain/RequestType.java +++ b/chain-of-responsibility/src/main/java/com/iluwatar/chain/RequestType.java @@ -24,13 +24,9 @@ */ package com.iluwatar.chain; -/** - * RequestType enumeration. - */ +/** RequestType enumeration. */ public enum RequestType { - DEFEND_CASTLE, TORTURE_PRISONER, COLLECT_TAX - } diff --git a/chain-of-responsibility/src/test/java/com/iluwatar/chain/AppTest.java b/chain-of-responsibility/src/test/java/com/iluwatar/chain/AppTest.java index 702d58dcb..4d2cd6899 100644 --- a/chain-of-responsibility/src/test/java/com/iluwatar/chain/AppTest.java +++ b/chain-of-responsibility/src/test/java/com/iluwatar/chain/AppTest.java @@ -24,25 +24,22 @@ */ package com.iluwatar.chain; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -/** - * Application test - */ +import org.junit.jupiter.api.Test; + +/** Application test */ class AppTest { /** * Issue: Add at least one assertion to this test case. * - * Solution: Inserted assertion to check whether the execution of the main method in {@link App} - * throws an exception. + *

Solution: Inserted assertion to check whether the execution of the main method in {@link + * App} throws an exception. */ - @Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/chain-of-responsibility/src/test/java/com/iluwatar/chain/OrcKingTest.java b/chain-of-responsibility/src/test/java/com/iluwatar/chain/OrcKingTest.java index 7bb9de901..ec53a4117 100644 --- a/chain-of-responsibility/src/test/java/com/iluwatar/chain/OrcKingTest.java +++ b/chain-of-responsibility/src/test/java/com/iluwatar/chain/OrcKingTest.java @@ -29,32 +29,26 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.List; import org.junit.jupiter.api.Test; -/** - * OrcKingTest - * - */ +/** OrcKingTest */ class OrcKingTest { - /** - * All possible requests - */ - private static final List REQUESTS = List.of( - new Request(RequestType.DEFEND_CASTLE, "Don't let the barbarians enter my castle!!"), - new Request(RequestType.TORTURE_PRISONER, "Don't just stand there, tickle him!"), - new Request(RequestType.COLLECT_TAX, "Don't steal, the King hates competition ...") - ); + /** All possible requests */ + private static final List REQUESTS = + List.of( + new Request(RequestType.DEFEND_CASTLE, "Don't let the barbarians enter my castle!!"), + new Request(RequestType.TORTURE_PRISONER, "Don't just stand there, tickle him!"), + new Request(RequestType.COLLECT_TAX, "Don't steal, the King hates competition ...")); @Test void testMakeRequest() { final var king = new OrcKing(); - REQUESTS.forEach(request -> { - king.makeRequest(request); - assertTrue( - request.isHandled(), - "Expected all requests from King to be handled, but [" + request + "] was not!" - ); - }); + REQUESTS.forEach( + request -> { + king.makeRequest(request); + assertTrue( + request.isHandled(), + "Expected all requests from King to be handled, but [" + request + "] was not!"); + }); } - -} \ No newline at end of file +} diff --git a/circuit-breaker/pom.xml b/circuit-breaker/pom.xml index eda24a4f4..5b2be0c56 100644 --- a/circuit-breaker/pom.xml +++ b/circuit-breaker/pom.xml @@ -34,6 +34,14 @@ circuit-breaker + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/App.java b/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/App.java index a29b6d769..6011aa9d1 100644 --- a/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/App.java +++ b/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/App.java @@ -27,33 +27,29 @@ package com.iluwatar.circuitbreaker; import lombok.extern.slf4j.Slf4j; /** - *

* The intention of the Circuit Builder pattern is to handle remote failures robustly, which is to * mean that if a service is dependent on n number of other services, and m of them fail, we should * be able to recover from that failure by ensuring that the user can still use the services that * are actually functional, and resources are not tied up by uselessly by the services which are not * working. However, we should also be able to detect when any of the m failing services become * operational again, so that we can use it - *

- *

- * In this example, the circuit breaker pattern is demonstrated by using three services: {@link + * + *

In this example, the circuit breaker pattern is demonstrated by using three services: {@link * DelayedRemoteService}, {@link QuickRemoteService} and {@link MonitoringService}. The monitoring - * service is responsible for calling three services: a local service, a quick remove service - * {@link QuickRemoteService} and a delayed remote service {@link DelayedRemoteService} , and by - * using the circuit breaker construction we ensure that if the call to remote service is going to - * fail, we are going to save our resources and not make the function call at all, by wrapping our - * call to the remote services in the {@link DefaultCircuitBreaker} implementation object. - *

- *

- * This works as follows: The {@link DefaultCircuitBreaker} object can be in one of three states: - * Open, Closed and Half-Open, which represents the real world circuits. If - * the state is closed (initial), we assume everything is alright and perform the function call. + * service is responsible for calling three services: a local service, a quick remove service {@link + * QuickRemoteService} and a delayed remote service {@link DelayedRemoteService} , and by using the + * circuit breaker construction we ensure that if the call to remote service is going to fail, we + * are going to save our resources and not make the function call at all, by wrapping our call to + * the remote services in the {@link DefaultCircuitBreaker} implementation object. + * + *

This works as follows: The {@link DefaultCircuitBreaker} object can be in one of three states: + * Open, Closed and Half-Open, which represents the real world circuits. If the + * state is closed (initial), we assume everything is alright and perform the function call. * However, every time the call fails, we note it and once it crosses a threshold, we set the state * to Open, preventing any further calls to the remote server. Then, after a certain retry period * (during which we expect thee service to recover), we make another call to the remote server and * this state is called the Half-Open state, where it stays till the service is down, and once it * recovers, it goes back to the closed state and the cycle continues. - *

*/ @Slf4j public class App { @@ -68,45 +64,45 @@ public class App { var serverStartTime = System.nanoTime(); var delayedService = new DelayedRemoteService(serverStartTime, 5); - var delayedServiceCircuitBreaker = new DefaultCircuitBreaker(delayedService, 3000, 2, - 2000 * 1000 * 1000); + var delayedServiceCircuitBreaker = + new DefaultCircuitBreaker(delayedService, 3000, 2, 2000 * 1000 * 1000); var quickService = new QuickRemoteService(); - var quickServiceCircuitBreaker = new DefaultCircuitBreaker(quickService, 3000, 2, - 2000 * 1000 * 1000); + var quickServiceCircuitBreaker = + new DefaultCircuitBreaker(quickService, 3000, 2, 2000 * 1000 * 1000); - //Create an object of monitoring service which makes both local and remote calls - var monitoringService = new MonitoringService(delayedServiceCircuitBreaker, - quickServiceCircuitBreaker); + // Create an object of monitoring service which makes both local and remote calls + var monitoringService = + new MonitoringService(delayedServiceCircuitBreaker, quickServiceCircuitBreaker); - //Fetch response from local resource + // Fetch response from local resource LOGGER.info(monitoringService.localResourceResponse()); - //Fetch response from delayed service 2 times, to meet the failure threshold + // Fetch response from delayed service 2 times, to meet the failure threshold LOGGER.info(monitoringService.delayedServiceResponse()); LOGGER.info(monitoringService.delayedServiceResponse()); - //Fetch current state of delayed service circuit breaker after crossing failure threshold limit - //which is OPEN now + // Fetch current state of delayed service circuit breaker after crossing failure threshold limit + // which is OPEN now LOGGER.info(delayedServiceCircuitBreaker.getState()); - //Meanwhile, the delayed service is down, fetch response from the healthy quick service + // Meanwhile, the delayed service is down, fetch response from the healthy quick service LOGGER.info(monitoringService.quickServiceResponse()); LOGGER.info(quickServiceCircuitBreaker.getState()); - //Wait for the delayed service to become responsive + // Wait for the delayed service to become responsive try { LOGGER.info("Waiting for delayed service to become responsive"); Thread.sleep(5000); } catch (InterruptedException e) { LOGGER.error("An error occurred: ", e); } - //Check the state of delayed circuit breaker, should be HALF_OPEN + // Check the state of delayed circuit breaker, should be HALF_OPEN LOGGER.info(delayedServiceCircuitBreaker.getState()); - //Fetch response from delayed service, which should be healthy by now + // Fetch response from delayed service, which should be healthy by now LOGGER.info(monitoringService.delayedServiceResponse()); - //As successful response is fetched, it should be CLOSED again. + // As successful response is fetched, it should be CLOSED again. LOGGER.info(delayedServiceCircuitBreaker.getState()); } } diff --git a/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/CircuitBreaker.java b/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/CircuitBreaker.java index aaccd65b1..31e11751a 100644 --- a/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/CircuitBreaker.java +++ b/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/CircuitBreaker.java @@ -24,9 +24,7 @@ */ package com.iluwatar.circuitbreaker; -/** - * The Circuit breaker interface. - */ +/** The Circuit breaker interface. */ public interface CircuitBreaker { // Success response. Reset everything to defaults diff --git a/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/DefaultCircuitBreaker.java b/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/DefaultCircuitBreaker.java index 18febbb6b..762c04d6b 100644 --- a/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/DefaultCircuitBreaker.java +++ b/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/DefaultCircuitBreaker.java @@ -45,14 +45,14 @@ public class DefaultCircuitBreaker implements CircuitBreaker { /** * Constructor to create an instance of Circuit Breaker. * - * @param timeout Timeout for the API request. Not necessary for this simple example + * @param timeout Timeout for the API request. Not necessary for this simple example * @param failureThreshold Number of failures we receive from the depended on service before - * changing state to 'OPEN' - * @param retryTimePeriod Time, in nanoseconds, period after which a new request is made to - * remote service for status check. + * changing state to 'OPEN' + * @param retryTimePeriod Time, in nanoseconds, period after which a new request is made to remote + * service for status check. */ - DefaultCircuitBreaker(RemoteService serviceToCall, long timeout, int failureThreshold, - long retryTimePeriod) { + DefaultCircuitBreaker( + RemoteService serviceToCall, long timeout, int failureThreshold, long retryTimePeriod) { this.service = serviceToCall; // We start in a closed state hoping that everything is fine this.state = State.CLOSED; @@ -61,7 +61,7 @@ public class DefaultCircuitBreaker implements CircuitBreaker { // Used to break the calls made to remote resource if it exceeds the limit this.timeout = timeout; this.retryTimePeriod = retryTimePeriod; - //An absurd amount of time in future which basically indicates the last failure never happened + // An absurd amount of time in future which basically indicates the last failure never happened this.lastFailureTime = System.nanoTime() + futureTime; this.failureCount = 0; } @@ -84,16 +84,16 @@ public class DefaultCircuitBreaker implements CircuitBreaker { // Evaluate the current state based on failureThreshold, failureCount and lastFailureTime. protected void evaluateState() { - if (failureCount >= failureThreshold) { //Then something is wrong with remote service + if (failureCount >= failureThreshold) { // Then something is wrong with remote service if ((System.nanoTime() - lastFailureTime) > retryTimePeriod) { - //We have waited long enough and should try checking if service is up + // We have waited long enough and should try checking if service is up state = State.HALF_OPEN; } else { - //Service would still probably be down + // Service would still probably be down state = State.OPEN; } } else { - //Everything is working fine + // Everything is working fine state = State.CLOSED; } } @@ -140,9 +140,9 @@ public class DefaultCircuitBreaker implements CircuitBreaker { } else { // Make the API request if the circuit is not OPEN try { - //In a real application, this would be run in a thread and the timeout - //parameter of the circuit breaker would be utilized to know if service - //is working. Here, we simulate that based on server response itself + // In a real application, this would be run in a thread and the timeout + // parameter of the circuit breaker would be utilized to know if service + // is working. Here, we simulate that based on server response itself var response = service.call(); // Yay!! the API responded fine. Let's reset everything. recordSuccess(); diff --git a/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/DelayedRemoteService.java b/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/DelayedRemoteService.java index 4db298814..ad87f1a6e 100644 --- a/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/DelayedRemoteService.java +++ b/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/DelayedRemoteService.java @@ -56,12 +56,12 @@ public class DelayedRemoteService implements RemoteService { @Override public String call() throws RemoteServiceException { var currentTime = System.nanoTime(); - //Since currentTime and serverStartTime are both in nanoseconds, we convert it to - //seconds by diving by 10e9 and ensure floating point division by multiplying it - //with 1.0 first. We then check if it is greater or less than specified delay and then - //send the reply + // Since currentTime and serverStartTime are both in nanoseconds, we convert it to + // seconds by diving by 10e9 and ensure floating point division by multiplying it + // with 1.0 first. We then check if it is greater or less than specified delay and then + // send the reply if ((currentTime - serverStartTime) * 1.0 / (1000 * 1000 * 1000) < delay) { - //Can use Thread.sleep() here to block and simulate a hung server + // Can use Thread.sleep() here to block and simulate a hung server throw new RemoteServiceException("Delayed service is down"); } return "Delayed service is working"; diff --git a/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/MonitoringService.java b/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/MonitoringService.java index 33564acc1..3fa5cd776 100644 --- a/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/MonitoringService.java +++ b/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/MonitoringService.java @@ -39,7 +39,7 @@ public class MonitoringService { this.quickService = quickService; } - //Assumption: Local service won't fail, no need to wrap it in a circuit breaker logic + // Assumption: Local service won't fail, no need to wrap it in a circuit breaker logic public String localResourceResponse() { return "Local Service is working"; } @@ -69,4 +69,4 @@ public class MonitoringService { return e.getMessage(); } } -} \ No newline at end of file +} diff --git a/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/QuickRemoteService.java b/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/QuickRemoteService.java index 404f1c05b..2367e4923 100644 --- a/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/QuickRemoteService.java +++ b/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/QuickRemoteService.java @@ -24,9 +24,7 @@ */ package com.iluwatar.circuitbreaker; -/** - * A quick response remote service, that responds healthy without any delay or failure. - */ +/** A quick response remote service, that responds healthy without any delay or failure. */ public class QuickRemoteService implements RemoteService { @Override diff --git a/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/RemoteService.java b/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/RemoteService.java index dac616f03..ced5d3ac9 100644 --- a/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/RemoteService.java +++ b/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/RemoteService.java @@ -30,6 +30,6 @@ package com.iluwatar.circuitbreaker; */ public interface RemoteService { - //Fetch response from remote service. + // Fetch response from remote service. String call() throws RemoteServiceException; } diff --git a/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/RemoteServiceException.java b/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/RemoteServiceException.java index eb033cd8e..48deec756 100644 --- a/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/RemoteServiceException.java +++ b/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/RemoteServiceException.java @@ -24,9 +24,7 @@ */ package com.iluwatar.circuitbreaker; -/** - * Exception thrown when {@link RemoteService} does not respond successfully. - */ +/** Exception thrown when {@link RemoteService} does not respond successfully. */ public class RemoteServiceException extends Exception { public RemoteServiceException(String message) { diff --git a/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/State.java b/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/State.java index e59b6ce8b..f2668281e 100644 --- a/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/State.java +++ b/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/State.java @@ -24,11 +24,9 @@ */ package com.iluwatar.circuitbreaker; -/** - * Enumeration for states the circuit breaker could be in. - */ +/** Enumeration for states the circuit breaker could be in. */ public enum State { CLOSED, OPEN, HALF_OPEN -} \ No newline at end of file +} diff --git a/circuit-breaker/src/test/java/com/iluwatar/circuitbreaker/AppTest.java b/circuit-breaker/src/test/java/com/iluwatar/circuitbreaker/AppTest.java index 108695706..3cbeadcd1 100644 --- a/circuit-breaker/src/test/java/com/iluwatar/circuitbreaker/AppTest.java +++ b/circuit-breaker/src/test/java/com/iluwatar/circuitbreaker/AppTest.java @@ -31,20 +31,18 @@ import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -/** - * App Test showing usage of circuit breaker. - */ +/** App Test showing usage of circuit breaker. */ class AppTest { private static final Logger LOGGER = LoggerFactory.getLogger(AppTest.class); - //Startup delay for delayed service (in seconds) + // Startup delay for delayed service (in seconds) private static final int STARTUP_DELAY = 4; - //Number of failed requests for circuit breaker to open + // Number of failed requests for circuit breaker to open private static final int FAILURE_THRESHOLD = 1; - //Time period in seconds for circuit breaker to retry service + // Time period in seconds for circuit breaker to retry service private static final int RETRY_PERIOD = 2; private MonitoringService monitoringService; @@ -62,75 +60,75 @@ class AppTest { @BeforeEach void setupCircuitBreakers() { var delayedService = new DelayedRemoteService(System.nanoTime(), STARTUP_DELAY); - //Set the circuit Breaker parameters - delayedServiceCircuitBreaker = new DefaultCircuitBreaker(delayedService, 3000, - FAILURE_THRESHOLD, - RETRY_PERIOD * 1000 * 1000 * 1000); + // Set the circuit Breaker parameters + delayedServiceCircuitBreaker = + new DefaultCircuitBreaker( + delayedService, 3000, FAILURE_THRESHOLD, RETRY_PERIOD * 1000 * 1000 * 1000); var quickService = new QuickRemoteService(); - //Set the circuit Breaker parameters - quickServiceCircuitBreaker = new DefaultCircuitBreaker(quickService, 3000, FAILURE_THRESHOLD, - RETRY_PERIOD * 1000 * 1000 * 1000); - - monitoringService = new MonitoringService(delayedServiceCircuitBreaker, - quickServiceCircuitBreaker); + // Set the circuit Breaker parameters + quickServiceCircuitBreaker = + new DefaultCircuitBreaker( + quickService, 3000, FAILURE_THRESHOLD, RETRY_PERIOD * 1000 * 1000 * 1000); + monitoringService = + new MonitoringService(delayedServiceCircuitBreaker, quickServiceCircuitBreaker); } @Test void testFailure_OpenStateTransition() { - //Calling delayed service, which will be unhealthy till 4 seconds + // Calling delayed service, which will be unhealthy till 4 seconds assertEquals("Delayed service is down", monitoringService.delayedServiceResponse()); - //As failure threshold is "1", the circuit breaker is changed to OPEN + // As failure threshold is "1", the circuit breaker is changed to OPEN assertEquals("OPEN", delayedServiceCircuitBreaker.getState()); - //As circuit state is OPEN, we expect a quick fallback response from circuit breaker. + // As circuit state is OPEN, we expect a quick fallback response from circuit breaker. assertEquals("Delayed service is down", monitoringService.delayedServiceResponse()); - //Meanwhile, the quick service is responding and the circuit state is CLOSED + // Meanwhile, the quick service is responding and the circuit state is CLOSED assertEquals("Quick Service is working", monitoringService.quickServiceResponse()); assertEquals("CLOSED", quickServiceCircuitBreaker.getState()); - } @Test void testFailure_HalfOpenStateTransition() { - //Calling delayed service, which will be unhealthy till 4 seconds + // Calling delayed service, which will be unhealthy till 4 seconds assertEquals("Delayed service is down", monitoringService.delayedServiceResponse()); - //As failure threshold is "1", the circuit breaker is changed to OPEN + // As failure threshold is "1", the circuit breaker is changed to OPEN assertEquals("OPEN", delayedServiceCircuitBreaker.getState()); - //Waiting for recovery period of 2 seconds for circuit breaker to retry service. + // Waiting for recovery period of 2 seconds for circuit breaker to retry service. try { LOGGER.info("Waiting 2s for delayed service to become responsive"); Thread.sleep(2000); } catch (InterruptedException e) { LOGGER.error("An error occurred: ", e); } - //After 2 seconds, the circuit breaker should move to "HALF_OPEN" state and retry fetching response from service again + // After 2 seconds, the circuit breaker should move to "HALF_OPEN" state and retry fetching + // response from service again assertEquals("HALF_OPEN", delayedServiceCircuitBreaker.getState()); - } @Test void testRecovery_ClosedStateTransition() { - //Calling delayed service, which will be unhealthy till 4 seconds + // Calling delayed service, which will be unhealthy till 4 seconds assertEquals("Delayed service is down", monitoringService.delayedServiceResponse()); - //As failure threshold is "1", the circuit breaker is changed to OPEN + // As failure threshold is "1", the circuit breaker is changed to OPEN assertEquals("OPEN", delayedServiceCircuitBreaker.getState()); - //Waiting for 4 seconds, which is enough for DelayedService to become healthy and respond successfully. + // Waiting for 4 seconds, which is enough for DelayedService to become healthy and respond + // successfully. try { LOGGER.info("Waiting 4s for delayed service to become responsive"); Thread.sleep(4000); } catch (InterruptedException e) { LOGGER.error("An error occurred: ", e); } - //As retry period is 2 seconds (<4 seconds of wait), hence the circuit breaker should be back in HALF_OPEN state. + // As retry period is 2 seconds (<4 seconds of wait), hence the circuit breaker should be back + // in HALF_OPEN state. assertEquals("HALF_OPEN", delayedServiceCircuitBreaker.getState()); - //Check the success response from delayed service. + // Check the success response from delayed service. assertEquals("Delayed service is working", monitoringService.delayedServiceResponse()); - //As the response is success, the state should be CLOSED + // As the response is success, the state should be CLOSED assertEquals("CLOSED", delayedServiceCircuitBreaker.getState()); } - } diff --git a/circuit-breaker/src/test/java/com/iluwatar/circuitbreaker/DefaultCircuitBreakerTest.java b/circuit-breaker/src/test/java/com/iluwatar/circuitbreaker/DefaultCircuitBreakerTest.java index 465371a3a..c184a8376 100644 --- a/circuit-breaker/src/test/java/com/iluwatar/circuitbreaker/DefaultCircuitBreakerTest.java +++ b/circuit-breaker/src/test/java/com/iluwatar/circuitbreaker/DefaultCircuitBreakerTest.java @@ -28,29 +28,27 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; -/** - * Circuit Breaker test - */ +/** Circuit Breaker test */ class DefaultCircuitBreakerTest { - //long timeout, int failureThreshold, long retryTimePeriod + // long timeout, int failureThreshold, long retryTimePeriod @Test void testEvaluateState() { var circuitBreaker = new DefaultCircuitBreaker(null, 1, 1, 100); - //Right now, failureCountfailureThreshold, and lastFailureTime is nearly equal to current time, - //state should be half-open + // Since failureCount>failureThreshold, and lastFailureTime is nearly equal to current time, + // state should be half-open assertEquals(circuitBreaker.getState(), "HALF_OPEN"); - //Since failureCount>failureThreshold, and lastFailureTime is much lesser current time, - //state should be open + // Since failureCount>failureThreshold, and lastFailureTime is much lesser current time, + // state should be open circuitBreaker.lastFailureTime = System.nanoTime() - 1000 * 1000 * 1000 * 1000; circuitBreaker.evaluateState(); assertEquals(circuitBreaker.getState(), "OPEN"); - //Now set it back again to closed to test idempotency + // Now set it back again to closed to test idempotency circuitBreaker.failureCount = 0; circuitBreaker.evaluateState(); assertEquals(circuitBreaker.getState(), "CLOSED"); @@ -59,23 +57,24 @@ class DefaultCircuitBreakerTest { @Test void testSetStateForBypass() { var circuitBreaker = new DefaultCircuitBreaker(null, 1, 1, 2000 * 1000 * 1000); - //Right now, failureCount { - var obj = new DelayedRemoteService(); - obj.call(); - }); + Assertions.assertThrows( + RemoteServiceException.class, + () -> { + var obj = new DelayedRemoteService(); + obj.call(); + }); } /** @@ -54,7 +54,7 @@ class DelayedRemoteServiceTest { */ @Test void testParameterizedConstructor() throws RemoteServiceException { - var obj = new DelayedRemoteService(System.nanoTime()-2000*1000*1000,1); - assertEquals("Delayed service is working",obj.call()); + var obj = new DelayedRemoteService(System.nanoTime() - 2000 * 1000 * 1000, 1); + assertEquals("Delayed service is working", obj.call()); } } diff --git a/circuit-breaker/src/test/java/com/iluwatar/circuitbreaker/MonitoringServiceTest.java b/circuit-breaker/src/test/java/com/iluwatar/circuitbreaker/MonitoringServiceTest.java index 51dde10ec..f7781fd1c 100644 --- a/circuit-breaker/src/test/java/com/iluwatar/circuitbreaker/MonitoringServiceTest.java +++ b/circuit-breaker/src/test/java/com/iluwatar/circuitbreaker/MonitoringServiceTest.java @@ -28,28 +28,25 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; -/** - * Monitoring Service test - */ +/** Monitoring Service test */ class MonitoringServiceTest { - //long timeout, int failureThreshold, long retryTimePeriod + // long timeout, int failureThreshold, long retryTimePeriod @Test void testLocalResponse() { - var monitoringService = new MonitoringService(null,null); + var monitoringService = new MonitoringService(null, null); var response = monitoringService.localResourceResponse(); assertEquals(response, "Local Service is working"); } @Test void testDelayedRemoteResponseSuccess() { - var delayedService = new DelayedRemoteService(System.nanoTime()-2*1000*1000*1000, 2); - var delayedServiceCircuitBreaker = new DefaultCircuitBreaker(delayedService, 3000, - 1, - 2 * 1000 * 1000 * 1000); + var delayedService = new DelayedRemoteService(System.nanoTime() - 2 * 1000 * 1000 * 1000, 2); + var delayedServiceCircuitBreaker = + new DefaultCircuitBreaker(delayedService, 3000, 1, 2 * 1000 * 1000 * 1000); - var monitoringService = new MonitoringService(delayedServiceCircuitBreaker,null); - //Set time in past to make the server work + var monitoringService = new MonitoringService(delayedServiceCircuitBreaker, null); + // Set time in past to make the server work var response = monitoringService.delayedServiceResponse(); assertEquals(response, "Delayed service is working"); } @@ -57,11 +54,10 @@ class MonitoringServiceTest { @Test void testDelayedRemoteResponseFailure() { var delayedService = new DelayedRemoteService(System.nanoTime(), 2); - var delayedServiceCircuitBreaker = new DefaultCircuitBreaker(delayedService, 3000, - 1, - 2 * 1000 * 1000 * 1000); - var monitoringService = new MonitoringService(delayedServiceCircuitBreaker,null); - //Set time as current time as initially server fails + var delayedServiceCircuitBreaker = + new DefaultCircuitBreaker(delayedService, 3000, 1, 2 * 1000 * 1000 * 1000); + var monitoringService = new MonitoringService(delayedServiceCircuitBreaker, null); + // Set time as current time as initially server fails var response = monitoringService.delayedServiceResponse(); assertEquals(response, "Delayed service is down"); } @@ -69,11 +65,10 @@ class MonitoringServiceTest { @Test void testQuickRemoteServiceResponse() { var delayedService = new QuickRemoteService(); - var delayedServiceCircuitBreaker = new DefaultCircuitBreaker(delayedService, 3000, - 1, - 2 * 1000 * 1000 * 1000); - var monitoringService = new MonitoringService(delayedServiceCircuitBreaker,null); - //Set time as current time as initially server fails + var delayedServiceCircuitBreaker = + new DefaultCircuitBreaker(delayedService, 3000, 1, 2 * 1000 * 1000 * 1000); + var monitoringService = new MonitoringService(delayedServiceCircuitBreaker, null); + // Set time as current time as initially server fails var response = monitoringService.delayedServiceResponse(); assertEquals(response, "Quick Service is working"); } diff --git a/client-session/pom.xml b/client-session/pom.xml index b7ff08637..1b2ea4564 100644 --- a/client-session/pom.xml +++ b/client-session/pom.xml @@ -34,6 +34,14 @@ client-session + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/client-session/src/main/java/com/iluwatar/client/session/App.java b/client-session/src/main/java/com/iluwatar/client/session/App.java index 282d8a7f3..8f744353e 100644 --- a/client-session/src/main/java/com/iluwatar/client/session/App.java +++ b/client-session/src/main/java/com/iluwatar/client/session/App.java @@ -29,12 +29,11 @@ package com.iluwatar.client.session; * The Client-Session pattern allows the session data to be stored on the client side and send this * data to the server with each request. * - *

In this example, The {@link Server} class represents the server that would process the + *

In this example, The {@link Server} class represents the server that would process the * incoming {@link Request} and also assign {@link Session} to a client. Here one instance of Server * is created. The we create two sessions for two different clients. These sessions are then passed * on to the server in the request along with the data. The server is then able to interpret the * client based on the session associated with it. - *

*/ public class App { diff --git a/client-session/src/main/java/com/iluwatar/client/session/Request.java b/client-session/src/main/java/com/iluwatar/client/session/Request.java index 008011f18..e47ed2775 100644 --- a/client-session/src/main/java/com/iluwatar/client/session/Request.java +++ b/client-session/src/main/java/com/iluwatar/client/session/Request.java @@ -28,9 +28,7 @@ package com.iluwatar.client.session; import lombok.AllArgsConstructor; import lombok.Data; -/** - * The Request class which contains the Session details and data. - */ +/** The Request class which contains the Session details and data. */ @Data @AllArgsConstructor public class Request { @@ -38,5 +36,4 @@ public class Request { private String data; private Session session; - } diff --git a/client-session/src/main/java/com/iluwatar/client/session/Server.java b/client-session/src/main/java/com/iluwatar/client/session/Server.java index 6d9dc3dbc..13a43a2dd 100644 --- a/client-session/src/main/java/com/iluwatar/client/session/Server.java +++ b/client-session/src/main/java/com/iluwatar/client/session/Server.java @@ -31,7 +31,8 @@ import lombok.Data; import lombok.extern.slf4j.Slf4j; /** - * The Server class. The client communicates with the server and request processing and getting a new session. + * The Server class. The client communicates with the server and request processing and getting a + * new session. */ @Slf4j @Data @@ -41,12 +42,10 @@ public class Server { private int port; - /** * Creates a new session. * * @param name name of the client - * * @return Session Object */ public Session getSession(String name) { @@ -59,7 +58,10 @@ public class Server { * @param request Request object with data and Session */ public void process(Request request) { - LOGGER.info("Processing Request with client: " + request.getSession().getClientName() + " data: " + request.getData()); + LOGGER.info( + "Processing Request with client: " + + request.getSession().getClientName() + + " data: " + + request.getData()); } - } diff --git a/client-session/src/main/java/com/iluwatar/client/session/Session.java b/client-session/src/main/java/com/iluwatar/client/session/Session.java index bb9f7246c..a7639485b 100644 --- a/client-session/src/main/java/com/iluwatar/client/session/Session.java +++ b/client-session/src/main/java/com/iluwatar/client/session/Session.java @@ -29,20 +29,16 @@ import lombok.AllArgsConstructor; import lombok.Data; /** - * The Session class. Each client get assigned a Session which is then used for further communications. + * The Session class. Each client get assigned a Session which is then used for further + * communications. */ @Data @AllArgsConstructor public class Session { - /** - * Session id. - */ + /** Session id. */ private String id; - /** - * Client name. - */ + /** Client name. */ private String clientName; - } diff --git a/client-session/src/test/java/com/iluwatar/client/session/AppTest.java b/client-session/src/test/java/com/iluwatar/client/session/AppTest.java index 0e33f74f4..63951ae48 100644 --- a/client-session/src/test/java/com/iluwatar/client/session/AppTest.java +++ b/client-session/src/test/java/com/iluwatar/client/session/AppTest.java @@ -33,6 +33,6 @@ class AppTest { @Test void appStartsWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/client-session/src/test/java/com/iluwatar/client/session/ServerTest.java b/client-session/src/test/java/com/iluwatar/client/session/ServerTest.java index 72f960332..0037ca633 100644 --- a/client-session/src/test/java/com/iluwatar/client/session/ServerTest.java +++ b/client-session/src/test/java/com/iluwatar/client/session/ServerTest.java @@ -24,9 +24,10 @@ */ package com.iluwatar.client.session; -import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; + class ServerTest { @Test diff --git a/collecting-parameter/pom.xml b/collecting-parameter/pom.xml index 8f7fdc2b5..8c5c01546 100644 --- a/collecting-parameter/pom.xml +++ b/collecting-parameter/pom.xml @@ -39,11 +39,6 @@ junit-jupiter-engine test
- - junit - junit - test -
diff --git a/collecting-parameter/src/main/java/com/iluwatar/collectingparameter/App.java b/collecting-parameter/src/main/java/com/iluwatar/collectingparameter/App.java index 93ead620d..d505970fb 100644 --- a/collecting-parameter/src/main/java/com/iluwatar/collectingparameter/App.java +++ b/collecting-parameter/src/main/java/com/iluwatar/collectingparameter/App.java @@ -28,23 +28,23 @@ import java.util.LinkedList; import java.util.Queue; /** - * The Collecting Parameter Design Pattern aims to return a result that is the collaborative result of several - * methods. This design pattern uses a 'collecting parameter' that is passed to several functions, accumulating results - * as it travels from method-to-method. This is different to the Composed Method design pattern, where a single - * collection is modified via several methods. + * The Collecting Parameter Design Pattern aims to return a result that is the collaborative result + * of several methods. This design pattern uses a 'collecting parameter' that is passed to several + * functions, accumulating results as it travels from method-to-method. This is different to the + * Composed Method design pattern, where a single collection is modified via several methods. * - *

This example is inspired by Kent Beck's example in his book, 'Smalltalk Best Practice Patterns'. The context for this - * situation is that there is a single printer queue {@link PrinterQueue} that holds numerous print jobs - * {@link PrinterItem} that must be distributed to various print centers. - * Each print center has its own requirements and printing limitations. In this example, the following requirements are: - * If an A4 document is coloured, it must also be single-sided. All other non-coloured A4 documents are accepted. - * All A3 documents must be non-coloured and single sided. All A2 documents must be a single page, single sided, and + *

This example is inspired by Kent Beck's example in his book, 'Smalltalk Best Practice + * Patterns'. The context for this situation is that there is a single printer queue {@link + * PrinterQueue} that holds numerous print jobs {@link PrinterItem} that must be distributed to + * various print centers. Each print center has its own requirements and printing limitations. In + * this example, the following requirements are: If an A4 document is coloured, it must also be + * single-sided. All other non-coloured A4 documents are accepted. All A3 documents must be + * non-coloured and single sided. All A2 documents must be a single page, single sided, and * non-coloured. * - *

A collecting parameter (the result variable) is used to filter the global printer queue so that it meets the - * requirements for this centre, - **/ - + *

A collecting parameter (the result variable) is used to filter the global printer queue so + * that it meets the requirements for this centre, + */ public class App { static PrinterQueue printerQueue = PrinterQueue.getInstance(); @@ -75,16 +75,16 @@ public class App { } /** - * Adds A4 document jobs to the collecting parameter according to some policy that can be whatever the client - * (the print center) wants. + * Adds A4 document jobs to the collecting parameter according to some policy that can be whatever + * the client (the print center) wants. * * @param printerItemsCollection the collecting parameter */ public static void addValidA4Papers(Queue printerItemsCollection) { /* - Iterate through the printer queue, and add A4 papers according to the correct policy to the collecting parameter, - which is 'printerItemsCollection' in this case. - */ + Iterate through the printer queue, and add A4 papers according to the correct policy to the collecting parameter, + which is 'printerItemsCollection' in this case. + */ for (PrinterItem nextItem : printerQueue.getPrinterQueue()) { if (nextItem.paperSize.equals(PaperSizes.A4)) { var isColouredAndSingleSided = nextItem.isColour && !nextItem.isDoubleSided; @@ -96,9 +96,9 @@ public class App { } /** - * Adds A3 document jobs to the collecting parameter according to some policy that can be whatever the client - * (the print center) wants. The code is similar to the 'addA4Papers' method. The code can be changed to accommodate - * the wants of the client. + * Adds A3 document jobs to the collecting parameter according to some policy that can be whatever + * the client (the print center) wants. The code is similar to the 'addA4Papers' method. The code + * can be changed to accommodate the wants of the client. * * @param printerItemsCollection the collecting parameter */ @@ -106,7 +106,8 @@ public class App { for (PrinterItem nextItem : printerQueue.getPrinterQueue()) { if (nextItem.paperSize.equals(PaperSizes.A3)) { - // Encoding the policy into a Boolean: the A3 paper cannot be coloured and double-sided at the same time + // Encoding the policy into a Boolean: the A3 paper cannot be coloured and double-sided at + // the same time var isNotColouredAndSingleSided = !nextItem.isColour && !nextItem.isDoubleSided; if (isNotColouredAndSingleSided) { printerItemsCollection.add(nextItem); @@ -116,9 +117,9 @@ public class App { } /** - * Adds A2 document jobs to the collecting parameter according to some policy that can be whatever the client - * (the print center) wants. The code is similar to the 'addA4Papers' method. The code can be changed to accommodate - * the wants of the client. + * Adds A2 document jobs to the collecting parameter according to some policy that can be whatever + * the client (the print center) wants. The code is similar to the 'addA4Papers' method. The code + * can be changed to accommodate the wants of the client. * * @param printerItemsCollection the collecting parameter */ @@ -126,9 +127,10 @@ public class App { for (PrinterItem nextItem : printerQueue.getPrinterQueue()) { if (nextItem.paperSize.equals(PaperSizes.A2)) { - // Encoding the policy into a Boolean: the A2 paper must be single page, single-sided, and non-coloured. - var isNotColouredSingleSidedAndOnePage = nextItem.pageCount == 1 && !nextItem.isDoubleSided - && !nextItem.isColour; + // Encoding the policy into a Boolean: the A2 paper must be single page, single-sided, and + // non-coloured. + var isNotColouredSingleSidedAndOnePage = + nextItem.pageCount == 1 && !nextItem.isDoubleSided && !nextItem.isColour; if (isNotColouredSingleSidedAndOnePage) { printerItemsCollection.add(nextItem); } diff --git a/collecting-parameter/src/main/java/com/iluwatar/collectingparameter/PrinterItem.java b/collecting-parameter/src/main/java/com/iluwatar/collectingparameter/PrinterItem.java index 3f0a24854..5669f744d 100644 --- a/collecting-parameter/src/main/java/com/iluwatar/collectingparameter/PrinterItem.java +++ b/collecting-parameter/src/main/java/com/iluwatar/collectingparameter/PrinterItem.java @@ -26,18 +26,14 @@ package com.iluwatar.collectingparameter; import java.util.Objects; -/** - * This class represents a Print Item, that should be added to the queue. - **/ +/** This class represents a Print Item, that should be added to the queue. */ public class PrinterItem { PaperSizes paperSize; int pageCount; boolean isDoubleSided; boolean isColour; - /** - * The {@link PrinterItem} constructor. - **/ + /** The {@link PrinterItem} constructor. */ public PrinterItem(PaperSizes paperSize, int pageCount, boolean isDoubleSided, boolean isColour) { if (!Objects.isNull(paperSize)) { this.paperSize = paperSize; @@ -53,6 +49,5 @@ public class PrinterItem { this.isColour = isColour; this.isDoubleSided = isDoubleSided; - } -} \ No newline at end of file +} diff --git a/collecting-parameter/src/main/java/com/iluwatar/collectingparameter/PrinterQueue.java b/collecting-parameter/src/main/java/com/iluwatar/collectingparameter/PrinterQueue.java index 882fc5277..8cdfc8410 100644 --- a/collecting-parameter/src/main/java/com/iluwatar/collectingparameter/PrinterQueue.java +++ b/collecting-parameter/src/main/java/com/iluwatar/collectingparameter/PrinterQueue.java @@ -29,15 +29,17 @@ import java.util.Objects; import java.util.Queue; /** - * This class represents a singleton Printer Queue. It contains a queue that can be filled up with {@link PrinterItem}. - **/ + * This class represents a singleton Printer Queue. It contains a queue that can be filled up with + * {@link PrinterItem}. + */ public class PrinterQueue { static PrinterQueue currentInstance = null; private final Queue printerItemQueue; /** - * This class is a singleton. The getInstance method will ensure that only one instance exists at a time. + * This class is a singleton. The getInstance method will ensure that only one instance exists at + * a time. */ public static PrinterQueue getInstance() { if (Objects.isNull(currentInstance)) { @@ -46,16 +48,12 @@ public class PrinterQueue { return currentInstance; } - /** - * Empty the printer queue. - */ + /** Empty the printer queue. */ public void emptyQueue() { currentInstance.getPrinterQueue().clear(); } - /** - * Private constructor prevents instantiation, unless using the getInstance() method. - */ + /** Private constructor prevents instantiation, unless using the getInstance() method. */ private PrinterQueue() { printerItemQueue = new LinkedList<>(); } @@ -72,5 +70,4 @@ public class PrinterQueue { public void addPrinterItem(PrinterItem printerItem) { currentInstance.getPrinterQueue().add(printerItem); } - } diff --git a/collecting-parameter/src/test/java/com/iluwatar/collectingparameter/AppTest.java b/collecting-parameter/src/test/java/com/iluwatar/collectingparameter/AppTest.java index 57f903777..8597c4d6f 100644 --- a/collecting-parameter/src/test/java/com/iluwatar/collectingparameter/AppTest.java +++ b/collecting-parameter/src/test/java/com/iluwatar/collectingparameter/AppTest.java @@ -24,16 +24,14 @@ */ package com.iluwatar.collectingparameter; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import org.junit.jupiter.api.Test; + class AppTest { - /** - * Checks whether {@link App} executes without throwing exception - */ + /** Checks whether {@link App} executes without throwing exception */ @Test void executesWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/collecting-parameter/src/test/java/com/iluwatar/collectingparameter/CollectingParameterTest.java b/collecting-parameter/src/test/java/com/iluwatar/collectingparameter/CollectingParameterTest.java index 9818dbb18..c53c5ac2c 100644 --- a/collecting-parameter/src/test/java/com/iluwatar/collectingparameter/CollectingParameterTest.java +++ b/collecting-parameter/src/test/java/com/iluwatar/collectingparameter/CollectingParameterTest.java @@ -24,11 +24,11 @@ */ package com.iluwatar.collectingparameter; +import java.util.LinkedList; +import java.util.Queue; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; -import java.util.LinkedList; -import java.util.Queue; class CollectingParameterTest { diff --git a/collecting-parameter/src/test/java/com/iluwatar/collectingparameter/PrinterQueueTest.java b/collecting-parameter/src/test/java/com/iluwatar/collectingparameter/PrinterQueueTest.java index fc633108b..8c03eea90 100644 --- a/collecting-parameter/src/test/java/com/iluwatar/collectingparameter/PrinterQueueTest.java +++ b/collecting-parameter/src/test/java/com/iluwatar/collectingparameter/PrinterQueueTest.java @@ -24,12 +24,12 @@ */ package com.iluwatar.collectingparameter; +import static org.junit.jupiter.api.Assertions.*; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; -import static org.junit.jupiter.api.Assertions.*; - class PrinterQueueTest { @Test @@ -43,13 +43,14 @@ class PrinterQueueTest { @Test() @Timeout(1000) void negativePageCount() throws IllegalArgumentException { - Assertions.assertThrows(IllegalArgumentException.class, () -> new PrinterItem(PaperSizes.A4, -1, true, true)); + Assertions.assertThrows( + IllegalArgumentException.class, () -> new PrinterItem(PaperSizes.A4, -1, true, true)); } @Test() @Timeout(1000) void nullPageSize() throws IllegalArgumentException { - Assertions.assertThrows(IllegalArgumentException.class, () -> new PrinterItem(null, 1, true, true)); + Assertions.assertThrows( + IllegalArgumentException.class, () -> new PrinterItem(null, 1, true, true)); } - -} \ No newline at end of file +} diff --git a/collection-pipeline/pom.xml b/collection-pipeline/pom.xml index 63de6d75f..b3c36cf06 100644 --- a/collection-pipeline/pom.xml +++ b/collection-pipeline/pom.xml @@ -34,6 +34,14 @@ collection-pipeline + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/Car.java b/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/Car.java index 2cfeb963b..7b4537800 100644 --- a/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/Car.java +++ b/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/Car.java @@ -25,8 +25,5 @@ package com.iluwatar.collectionpipeline; -/** - * A Car class that has the properties of make, model, year and category. - */ -public record Car(String make, String model, int year, Category category) { -} +/** A Car class that has the properties of make, model, year and category. */ +public record Car(String make, String model, int year, Category category) {} diff --git a/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/CarFactory.java b/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/CarFactory.java index b96af01db..2bfaa6760 100644 --- a/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/CarFactory.java +++ b/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/CarFactory.java @@ -26,12 +26,9 @@ package com.iluwatar.collectionpipeline; import java.util.List; -/** - * A factory class to create a collection of {@link Car} instances. - */ +/** A factory class to create a collection of {@link Car} instances. */ public class CarFactory { - private CarFactory() { - } + private CarFactory() {} /** * Factory method to create a {@link List} of {@link Car} instances. @@ -39,11 +36,12 @@ public class CarFactory { * @return {@link List} of {@link Car} */ public static List createCars() { - return List.of(new Car("Jeep", "Wrangler", 2011, Category.JEEP), + return List.of( + new Car("Jeep", "Wrangler", 2011, Category.JEEP), new Car("Jeep", "Comanche", 1990, Category.JEEP), new Car("Dodge", "Avenger", 2010, Category.SEDAN), new Car("Buick", "Cascada", 2016, Category.CONVERTIBLE), new Car("Ford", "Focus", 2012, Category.SEDAN), new Car("Chevrolet", "Geo Metro", 1992, Category.CONVERTIBLE)); } -} \ No newline at end of file +} diff --git a/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/Category.java b/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/Category.java index c7b3dfcdc..9de7e4da3 100644 --- a/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/Category.java +++ b/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/Category.java @@ -24,9 +24,7 @@ */ package com.iluwatar.collectionpipeline; -/** - * Enum for the category of car. - */ +/** Enum for the category of car. */ public enum Category { JEEP, SEDAN, diff --git a/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/FunctionalProgramming.java b/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/FunctionalProgramming.java index 20bf77d29..dfe2d9ea5 100644 --- a/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/FunctionalProgramming.java +++ b/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/FunctionalProgramming.java @@ -33,20 +33,19 @@ import java.util.stream.Collectors; /** * Iterating and sorting with a collection pipeline * - *

In functional programming, it's common to sequence complex operations through - * a series of smaller modular functions or operations. The series is called a composition of - * functions, or a function composition. When a collection of data flows through a function - * composition, it becomes a collection pipeline. Function Composition and Collection Pipeline are - * two design patterns frequently used in functional-style programming. + *

In functional programming, it's common to sequence complex operations through a series of + * smaller modular functions or operations. The series is called a composition of functions, or a + * function composition. When a collection of data flows through a function composition, it becomes + * a collection pipeline. Function Composition and Collection Pipeline are two design patterns + * frequently used in functional-style programming. * - *

Instead of passing a lambda expression to the map method, we passed the - * method reference Car::getModel. Likewise, instead of passing the lambda expression car -> - * car.getYear() to the comparing method, we passed the method reference Car::getYear. Method - * references are short, concise, and expressive. It is best to use them wherever possible. + *

Instead of passing a lambda expression to the map method, we passed the method reference + * Car::getModel. Likewise, instead of passing the lambda expression car -> car.getYear() to the + * comparing method, we passed the method reference Car::getYear. Method references are short, + * concise, and expressive. It is best to use them wherever possible. */ public class FunctionalProgramming { - private FunctionalProgramming() { - } + private FunctionalProgramming() {} /** * Method to get models using for collection pipeline. @@ -55,8 +54,11 @@ public class FunctionalProgramming { * @return {@link List} of {@link String} representing models built after year 2000 */ public static List getModelsAfter2000(List cars) { - return cars.stream().filter(car -> car.year() > 2000).sorted(Comparator.comparing(Car::year)) - .map(Car::model).toList(); + return cars.stream() + .filter(car -> car.year() > 2000) + .sorted(Comparator.comparing(Car::year)) + .map(Car::model) + .toList(); } /** @@ -76,8 +78,11 @@ public class FunctionalProgramming { * @return {@link List} of {@link Car} to belonging to the group */ public static List getSedanCarsOwnedSortedByDate(List persons) { - return persons.stream().map(Person::cars).flatMap(List::stream) + return persons.stream() + .map(Person::cars) + .flatMap(List::stream) .filter(car -> Category.SEDAN.equals(car.category())) - .sorted(Comparator.comparing(Car::year)).toList(); + .sorted(Comparator.comparing(Car::year)) + .toList(); } } diff --git a/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/ImperativeProgramming.java b/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/ImperativeProgramming.java index 2a85334c6..24c0b965e 100644 --- a/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/ImperativeProgramming.java +++ b/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/ImperativeProgramming.java @@ -35,21 +35,20 @@ import java.util.Map; * Imperative-style programming to iterate over the list and get the names of cars made later than * the year 2000. We then sort the models in ascending order by year. * - *

As you can see, there's a lot of looping in this code. First, the - * getModelsAfter2000UsingFor method takes a list of cars as its parameter. It extracts or filters - * out cars made after the year 2000, putting them into a new list named carsSortedByYear. Next, it - * sorts that list in ascending order by year-of-make. Finally, it loops through the list - * carsSortedByYear to get the model names and returns them in a list. + *

As you can see, there's a lot of looping in this code. First, the getModelsAfter2000UsingFor + * method takes a list of cars as its parameter. It extracts or filters out cars made after the year + * 2000, putting them into a new list named carsSortedByYear. Next, it sorts that list in ascending + * order by year-of-make. Finally, it loops through the list carsSortedByYear to get the model names + * and returns them in a list. * - *

This short example demonstrates what I call the effect of statements. While - * functions and methods in general can be used as expressions, the {@link Collections} sort method - * doesn't return a result. Because it is used as a statement, it mutates the list given as - * argument. Both of the for loops also mutate lists as they iterate. Being statements, that's just - * how these elements work. As a result, the code contains unnecessary garbage variables + *

This short example demonstrates what I call the effect of statements. While functions and + * methods in general can be used as expressions, the {@link Collections} sort method doesn't return + * a result. Because it is used as a statement, it mutates the list given as argument. Both of the + * for loops also mutate lists as they iterate. Being statements, that's just how these elements + * work. As a result, the code contains unnecessary garbage variables */ public class ImperativeProgramming { - private ImperativeProgramming() { - } + private ImperativeProgramming() {} /** * Method to return the car models built after year 2000 using for loops. @@ -66,12 +65,14 @@ public class ImperativeProgramming { } } - Collections.sort(carsSortedByYear, new Comparator() { - @Override - public int compare(Car car1, Car car2) { - return car1.year() - car2.year(); - } - }); + Collections.sort( + carsSortedByYear, + new Comparator() { + @Override + public int compare(Car car1, Car car2) { + return car1.year() - car2.year(); + } + }); List models = new ArrayList<>(); for (Car car : carsSortedByYear) { @@ -121,12 +122,13 @@ public class ImperativeProgramming { } } - sedanCars.sort(new Comparator() { - @Override - public int compare(Car o1, Car o2) { - return o1.year() - o2.year(); - } - }); + sedanCars.sort( + new Comparator() { + @Override + public int compare(Car o1, Car o2) { + return o1.year() - o2.year(); + } + }); return sedanCars; } diff --git a/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/Person.java b/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/Person.java index 992596125..a84dc7f72 100644 --- a/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/Person.java +++ b/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/Person.java @@ -26,7 +26,5 @@ package com.iluwatar.collectionpipeline; import java.util.List; -/** - * A Person class that has the list of cars that the person owns and use. - */ +/** A Person class that has the list of cars that the person owns and use. */ public record Person(List cars) {} diff --git a/collection-pipeline/src/test/java/com/iluwatar/collectionpipeline/AppTest.java b/collection-pipeline/src/test/java/com/iluwatar/collectionpipeline/AppTest.java index 959d0c6b5..9a990b09e 100644 --- a/collection-pipeline/src/test/java/com/iluwatar/collectionpipeline/AppTest.java +++ b/collection-pipeline/src/test/java/com/iluwatar/collectionpipeline/AppTest.java @@ -31,9 +31,7 @@ import java.util.Map; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.Test; -/** - * Tests that Collection Pipeline methods work as expected. - */ +/** Tests that Collection Pipeline methods work as expected. */ @Slf4j class AppTest { @@ -53,19 +51,20 @@ class AppTest { @Test void testGetGroupingOfCarsByCategory() { - var modelsExpected = Map.of( - Category.CONVERTIBLE, List.of( - new Car("Buick", "Cascada", 2016, Category.CONVERTIBLE), - new Car("Chevrolet", "Geo Metro", 1992, Category.CONVERTIBLE) - ), - Category.SEDAN, List.of( - new Car("Dodge", "Avenger", 2010, Category.SEDAN), - new Car("Ford", "Focus", 2012, Category.SEDAN) - ), - Category.JEEP, List.of( - new Car("Jeep", "Wrangler", 2011, Category.JEEP), - new Car("Jeep", "Comanche", 1990, Category.JEEP)) - ); + var modelsExpected = + Map.of( + Category.CONVERTIBLE, + List.of( + new Car("Buick", "Cascada", 2016, Category.CONVERTIBLE), + new Car("Chevrolet", "Geo Metro", 1992, Category.CONVERTIBLE)), + Category.SEDAN, + List.of( + new Car("Dodge", "Avenger", 2010, Category.SEDAN), + new Car("Ford", "Focus", 2012, Category.SEDAN)), + Category.JEEP, + List.of( + new Car("Jeep", "Wrangler", 2011, Category.JEEP), + new Car("Jeep", "Comanche", 1990, Category.JEEP))); var modelsFunctional = FunctionalProgramming.getGroupingOfCarsByCategory(cars); var modelsImperative = ImperativeProgramming.getGroupingOfCarsByCategory(cars); LOGGER.info("Category " + modelsFunctional); @@ -76,10 +75,10 @@ class AppTest { @Test void testGetSedanCarsOwnedSortedByDate() { var john = new Person(cars); - var modelsExpected = List.of( - new Car("Dodge", "Avenger", 2010, Category.SEDAN), - new Car("Ford", "Focus", 2012, Category.SEDAN) - ); + var modelsExpected = + List.of( + new Car("Dodge", "Avenger", 2010, Category.SEDAN), + new Car("Ford", "Focus", 2012, Category.SEDAN)); var modelsFunctional = FunctionalProgramming.getSedanCarsOwnedSortedByDate(List.of(john)); var modelsImperative = ImperativeProgramming.getSedanCarsOwnedSortedByDate(List.of(john)); assertEquals(modelsExpected, modelsFunctional); diff --git a/combinator/pom.xml b/combinator/pom.xml index 0e2f41962..d366b383a 100644 --- a/combinator/pom.xml +++ b/combinator/pom.xml @@ -34,10 +34,37 @@ combinator + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.combinator.CombinatorApp + + + + + + + + diff --git a/combinator/src/main/java/com/iluwatar/combinator/CombinatorApp.java b/combinator/src/main/java/com/iluwatar/combinator/CombinatorApp.java index 2ca6e16d7..bf1ec4a01 100644 --- a/combinator/src/main/java/com/iluwatar/combinator/CombinatorApp.java +++ b/combinator/src/main/java/com/iluwatar/combinator/CombinatorApp.java @@ -26,25 +26,20 @@ package com.iluwatar.combinator; import lombok.extern.slf4j.Slf4j; - /** - * The functional pattern representing a style of organizing libraries - * centered around the idea of combining functions. - * Putting it simply, there is some type T, some functions - * for constructing "primitive" values of type T, - * and some "combinators" which can combine values of type T - * in various ways to build up more complex values of type T. - * The class {@link Finder} defines a simple function {@link Finder#find(String)} - * and connected functions - * {@link Finder#or(Finder)}, - * {@link Finder#not(Finder)}, - * {@link Finder#and(Finder)} - * Using them the became possible to get more complex functions {@link Finders} + * The functional pattern representing a style of organizing libraries centered around the idea of + * combining functions. Putting it simply, there is some type T, some functions for constructing + * "primitive" values of type T, and some "combinators" which can combine values of type T in + * various ways to build up more complex values of type T. The class {@link Finder} defines a simple + * function {@link Finder#find(String)} and connected functions {@link Finder#or(Finder)}, {@link + * Finder#not(Finder)}, {@link Finder#and(Finder)} Using them the became possible to get more + * complex functions {@link Finders} */ @Slf4j public class CombinatorApp { - private static final String TEXT = """ + private static final String TEXT = + """ It was many and many a year ago, In a kingdom by the sea, That a maiden there lived whom you may know @@ -60,15 +55,16 @@ public class CombinatorApp { /** * main. + * * @param args args */ public static void main(String[] args) { - var queriesOr = new String[]{"many", "Annabel"}; + var queriesOr = new String[] {"many", "Annabel"}; var finder = Finders.expandedFinder(queriesOr); var res = finder.find(text()); LOGGER.info("the result of expanded(or) query[{}] is {}", queriesOr, res); - var queriesAnd = new String[]{"Annabel", "my"}; + var queriesAnd = new String[] {"Annabel", "my"}; finder = Finders.specializedFinder(queriesAnd); res = finder.find(text()); LOGGER.info("the result of specialized(and) query[{}] is {}", queriesAnd, res); @@ -79,12 +75,10 @@ public class CombinatorApp { res = Finders.filteredFinder(" was ", "many", "child").find(text()); LOGGER.info("the result of filtered query is {}", res); - } private static String text() { return TEXT; } - } diff --git a/combinator/src/main/java/com/iluwatar/combinator/Finder.java b/combinator/src/main/java/com/iluwatar/combinator/Finder.java index 1189367de..cc2d5ce84 100644 --- a/combinator/src/main/java/com/iluwatar/combinator/Finder.java +++ b/combinator/src/main/java/com/iluwatar/combinator/Finder.java @@ -28,13 +28,12 @@ import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; -/** - * Functional interface to find lines in text. - */ +/** Functional interface to find lines in text. */ public interface Finder { /** * The function to find lines in text. + * * @param text full tet * @return result of searching */ @@ -42,17 +41,20 @@ public interface Finder { /** * Simple implementation of function {@link #find(String)}. + * * @param word for searching * @return this */ static Finder contains(String word) { - return txt -> Stream.of(txt.split("\n")) - .filter(line -> line.toLowerCase().contains(word.toLowerCase())) - .collect(Collectors.toList()); + return txt -> + Stream.of(txt.split("\n")) + .filter(line -> line.toLowerCase().contains(word.toLowerCase())) + .collect(Collectors.toList()); } /** * combinator not. + * * @param notFinder finder to combine * @return new finder including previous finders */ @@ -66,6 +68,7 @@ public interface Finder { /** * combinator or. + * * @param orFinder finder to combine * @return new finder including previous finders */ @@ -79,16 +82,14 @@ public interface Finder { /** * combinator and. + * * @param andFinder finder to combine * @return new finder including previous finders */ default Finder and(Finder andFinder) { - return - txt -> this - .find(txt) - .stream() + return txt -> + this.find(txt).stream() .flatMap(line -> andFinder.find(line).stream()) .collect(Collectors.toList()); } - } diff --git a/combinator/src/main/java/com/iluwatar/combinator/Finders.java b/combinator/src/main/java/com/iluwatar/combinator/Finders.java index 1920c85d4..a6f8dd7ca 100644 --- a/combinator/src/main/java/com/iluwatar/combinator/Finders.java +++ b/combinator/src/main/java/com/iluwatar/combinator/Finders.java @@ -28,30 +28,25 @@ import java.util.ArrayList; import java.util.stream.Collectors; import java.util.stream.Stream; -/** - * Complex finders consisting of simple finder. - */ +/** Complex finders consisting of simple finder. */ public class Finders { - private Finders() { - } - + private Finders() {} /** * Finder to find a complex query. + * * @param query to find * @param orQuery alternative to find * @param notQuery exclude from search * @return new finder */ public static Finder advancedFinder(String query, String orQuery, String notQuery) { - return - Finder.contains(query) - .or(Finder.contains(orQuery)) - .not(Finder.contains(notQuery)); + return Finder.contains(query).or(Finder.contains(orQuery)).not(Finder.contains(notQuery)); } /** * Filtered finder looking a query with excluded queries as well. + * * @param query to find * @param excludeQueries to exclude * @return new finder @@ -63,11 +58,11 @@ public class Finders { finder = finder.not(Finder.contains(q)); } return finder; - } /** * Specialized query. Every next query is looked in previous result. + * * @param queries array with queries * @return new finder */ @@ -82,6 +77,7 @@ public class Finders { /** * Expanded query. Looking for alternatives. + * * @param queries array with queries. * @return new finder */ diff --git a/combinator/src/test/java/com/iluwatar/combinator/CombinatorAppTest.java b/combinator/src/test/java/com/iluwatar/combinator/CombinatorAppTest.java index 02f8581df..4a7a6fff7 100644 --- a/combinator/src/test/java/com/iluwatar/combinator/CombinatorAppTest.java +++ b/combinator/src/test/java/com/iluwatar/combinator/CombinatorAppTest.java @@ -32,12 +32,12 @@ class CombinatorAppTest { /** * Issue: Add at least one assertion to this test case. - *

- * Solution: Inserted assertion to check whether the execution of the main method in {@link CombinatorApp#main(String[])} - * throws an exception. + * + *

Solution: Inserted assertion to check whether the execution of the main method in {@link + * CombinatorApp#main(String[])} throws an exception. */ @Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> CombinatorApp.main(new String[]{})); + assertDoesNotThrow(() -> CombinatorApp.main(new String[] {})); } } diff --git a/combinator/src/test/java/com/iluwatar/combinator/FindersTest.java b/combinator/src/test/java/com/iluwatar/combinator/FindersTest.java index aa84b9350..f8a23927c 100644 --- a/combinator/src/test/java/com/iluwatar/combinator/FindersTest.java +++ b/combinator/src/test/java/com/iluwatar/combinator/FindersTest.java @@ -65,7 +65,6 @@ class FindersTest { assertEquals("In this kingdom by the sea;", res.get(2)); } - private String text() { return """ It was many and many a year ago, @@ -81,5 +80,4 @@ class FindersTest { With a love that the winged seraphs of heaven Coveted her and me."""; } - } diff --git a/command-query-responsibility-segregation/pom.xml b/command-query-responsibility-segregation/pom.xml index bc2659cdc..c3c277dd0 100644 --- a/command-query-responsibility-segregation/pom.xml +++ b/command-query-responsibility-segregation/pom.xml @@ -34,6 +34,14 @@ command-query-responsibility-segregation + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine @@ -46,14 +54,17 @@ org.hibernate hibernate-core + 5.6.15.Final org.glassfish.jaxb jaxb-runtime + 2.3.3 javax.xml.bind jaxb-api + 2.3.1 diff --git a/command-query-responsibility-segregation/src/main/java/com/iluwatar/cqrs/app/App.java b/command-query-responsibility-segregation/src/main/java/com/iluwatar/cqrs/app/App.java index 52b8ead45..623176389 100644 --- a/command-query-responsibility-segregation/src/main/java/com/iluwatar/cqrs/app/App.java +++ b/command-query-responsibility-segregation/src/main/java/com/iluwatar/cqrs/app/App.java @@ -62,8 +62,8 @@ public class App { commands.bookAddedToAuthor("Effective Java", 40.54, AppConstants.J_BLOCH); commands.bookAddedToAuthor("Java Puzzlers", 39.99, AppConstants.J_BLOCH); commands.bookAddedToAuthor("Java Concurrency in Practice", 29.40, AppConstants.J_BLOCH); - commands.bookAddedToAuthor("Patterns of Enterprise" - + " Application Architecture", 54.01, AppConstants.M_FOWLER); + commands.bookAddedToAuthor( + "Patterns of Enterprise" + " Application Architecture", 54.01, AppConstants.M_FOWLER); commands.bookAddedToAuthor("Domain Specific Languages", 48.89, AppConstants.M_FOWLER); commands.authorNameUpdated(AppConstants.E_EVANS, "Eric J. Evans"); @@ -86,5 +86,4 @@ public class App { HibernateUtil.getSessionFactory().close(); } - } diff --git a/command-query-responsibility-segregation/src/main/java/com/iluwatar/cqrs/commandes/CommandService.java b/command-query-responsibility-segregation/src/main/java/com/iluwatar/cqrs/commandes/CommandService.java index 114280afb..9cf8c52cb 100644 --- a/command-query-responsibility-segregation/src/main/java/com/iluwatar/cqrs/commandes/CommandService.java +++ b/command-query-responsibility-segregation/src/main/java/com/iluwatar/cqrs/commandes/CommandService.java @@ -24,9 +24,7 @@ */ package com.iluwatar.cqrs.commandes; -/** - * This interface represents the commands of the CQRS pattern. - */ +/** This interface represents the commands of the CQRS pattern. */ public interface CommandService { void authorCreated(String username, String name, String email); @@ -42,5 +40,4 @@ public interface CommandService { void bookTitleUpdated(String oldTitle, String newTitle); void bookPriceUpdated(String title, double price); - } diff --git a/command-query-responsibility-segregation/src/main/java/com/iluwatar/cqrs/commandes/CommandServiceImpl.java b/command-query-responsibility-segregation/src/main/java/com/iluwatar/cqrs/commandes/CommandServiceImpl.java index 52b32dc45..b4a368c98 100644 --- a/command-query-responsibility-segregation/src/main/java/com/iluwatar/cqrs/commandes/CommandServiceImpl.java +++ b/command-query-responsibility-segregation/src/main/java/com/iluwatar/cqrs/commandes/CommandServiceImpl.java @@ -140,5 +140,4 @@ public class CommandServiceImpl implements CommandService { session.getTransaction().commit(); } } - } diff --git a/command-query-responsibility-segregation/src/main/java/com/iluwatar/cqrs/constants/AppConstants.java b/command-query-responsibility-segregation/src/main/java/com/iluwatar/cqrs/constants/AppConstants.java index 5753f8c2b..71d266f43 100644 --- a/command-query-responsibility-segregation/src/main/java/com/iluwatar/cqrs/constants/AppConstants.java +++ b/command-query-responsibility-segregation/src/main/java/com/iluwatar/cqrs/constants/AppConstants.java @@ -24,14 +24,11 @@ */ package com.iluwatar.cqrs.constants; -/** - * Class to define the constants. - */ +/** Class to define the constants. */ public class AppConstants { public static final String E_EVANS = "eEvans"; public static final String J_BLOCH = "jBloch"; public static final String M_FOWLER = "mFowler"; public static final String USER_NAME = "username"; - } diff --git a/command-query-responsibility-segregation/src/main/java/com/iluwatar/cqrs/domain/model/Author.java b/command-query-responsibility-segregation/src/main/java/com/iluwatar/cqrs/domain/model/Author.java index ff9192717..03155d67a 100644 --- a/command-query-responsibility-segregation/src/main/java/com/iluwatar/cqrs/domain/model/Author.java +++ b/command-query-responsibility-segregation/src/main/java/com/iluwatar/cqrs/domain/model/Author.java @@ -32,9 +32,7 @@ import lombok.Getter; import lombok.Setter; import lombok.ToString; -/** - * This is an Author entity. It is used by Hibernate for persistence. - */ +/** This is an Author entity. It is used by Hibernate for persistence. */ @ToString @Getter @Setter @@ -43,6 +41,7 @@ public class Author { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private long id; + private String username; private String name; private String email; @@ -51,8 +50,8 @@ public class Author { * Constructor. * * @param username username of the author - * @param name name of the author - * @param email email of the author + * @param name name of the author + * @param email email of the author */ public Author(String username, String name, String email) { this.username = username; @@ -60,7 +59,5 @@ public class Author { this.email = email; } - protected Author() { - } - + protected Author() {} } diff --git a/command-query-responsibility-segregation/src/main/java/com/iluwatar/cqrs/domain/model/Book.java b/command-query-responsibility-segregation/src/main/java/com/iluwatar/cqrs/domain/model/Book.java index 171c91d4d..2e2c35652 100644 --- a/command-query-responsibility-segregation/src/main/java/com/iluwatar/cqrs/domain/model/Book.java +++ b/command-query-responsibility-segregation/src/main/java/com/iluwatar/cqrs/domain/model/Book.java @@ -45,16 +45,16 @@ public class Book { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private long id; + private String title; private double price; - @ManyToOne - private Author author; + @ManyToOne private Author author; /** * Constructor. * - * @param title title of the book - * @param price price of the book + * @param title title of the book + * @param price price of the book * @param author author of the book */ public Book(String title, double price, Author author) { @@ -63,7 +63,5 @@ public class Book { this.author = author; } - protected Book() { - } - + protected Book() {} } diff --git a/command-query-responsibility-segregation/src/main/java/com/iluwatar/cqrs/dto/Author.java b/command-query-responsibility-segregation/src/main/java/com/iluwatar/cqrs/dto/Author.java index 35a565cfa..58074e6da 100644 --- a/command-query-responsibility-segregation/src/main/java/com/iluwatar/cqrs/dto/Author.java +++ b/command-query-responsibility-segregation/src/main/java/com/iluwatar/cqrs/dto/Author.java @@ -30,9 +30,7 @@ import lombok.Getter; import lombok.NoArgsConstructor; import lombok.ToString; -/** - * This is a DTO (Data Transfer Object) author, contains only useful information to be returned. - */ +/** This is a DTO (Data Transfer Object) author, contains only useful information to be returned. */ @ToString @EqualsAndHashCode @Getter @@ -43,5 +41,4 @@ public class Author { private String name; private String email; private String username; - } diff --git a/command-query-responsibility-segregation/src/main/java/com/iluwatar/cqrs/dto/Book.java b/command-query-responsibility-segregation/src/main/java/com/iluwatar/cqrs/dto/Book.java index a938c65d3..72ce5b8c2 100644 --- a/command-query-responsibility-segregation/src/main/java/com/iluwatar/cqrs/dto/Book.java +++ b/command-query-responsibility-segregation/src/main/java/com/iluwatar/cqrs/dto/Book.java @@ -30,9 +30,7 @@ import lombok.Getter; import lombok.NoArgsConstructor; import lombok.ToString; -/** - * This is a DTO (Data Transfer Object) book, contains only useful information to be returned. - */ +/** This is a DTO (Data Transfer Object) book, contains only useful information to be returned. */ @ToString @EqualsAndHashCode @Getter @@ -42,5 +40,4 @@ public class Book { private String title; private double price; - } diff --git a/command-query-responsibility-segregation/src/main/java/com/iluwatar/cqrs/queries/QueryService.java b/command-query-responsibility-segregation/src/main/java/com/iluwatar/cqrs/queries/QueryService.java index c226c6f21..b37c1dad0 100644 --- a/command-query-responsibility-segregation/src/main/java/com/iluwatar/cqrs/queries/QueryService.java +++ b/command-query-responsibility-segregation/src/main/java/com/iluwatar/cqrs/queries/QueryService.java @@ -29,9 +29,7 @@ import com.iluwatar.cqrs.dto.Book; import java.math.BigInteger; import java.util.List; -/** - * This interface represents the query methods of the CQRS pattern. - */ +/** This interface represents the query methods of the CQRS pattern. */ public interface QueryService { Author getAuthorByUsername(String username); @@ -43,5 +41,4 @@ public interface QueryService { BigInteger getAuthorBooksCount(String username); BigInteger getAuthorsCount(); - } diff --git a/command-query-responsibility-segregation/src/main/java/com/iluwatar/cqrs/queries/QueryServiceImpl.java b/command-query-responsibility-segregation/src/main/java/com/iluwatar/cqrs/queries/QueryServiceImpl.java index ed6db0b50..60847d1c6 100644 --- a/command-query-responsibility-segregation/src/main/java/com/iluwatar/cqrs/queries/QueryServiceImpl.java +++ b/command-query-responsibility-segregation/src/main/java/com/iluwatar/cqrs/queries/QueryServiceImpl.java @@ -45,9 +45,10 @@ public class QueryServiceImpl implements QueryService { public Author getAuthorByUsername(String username) { Author authorDto; try (var session = sessionFactory.openSession()) { - Query sqlQuery = session.createQuery( + Query sqlQuery = + session.createQuery( "select new com.iluwatar.cqrs.dto.Author(a.name, a.email, a.username)" - + " from com.iluwatar.cqrs.domain.model.Author a where a.username=:username"); + + " from com.iluwatar.cqrs.domain.model.Author a where a.username=:username"); sqlQuery.setParameter(AppConstants.USER_NAME, username); authorDto = sqlQuery.uniqueResult(); } @@ -58,9 +59,10 @@ public class QueryServiceImpl implements QueryService { public Book getBook(String title) { Book bookDto; try (var session = sessionFactory.openSession()) { - Query sqlQuery = session.createQuery( + Query sqlQuery = + session.createQuery( "select new com.iluwatar.cqrs.dto.Book(b.title, b.price)" - + " from com.iluwatar.cqrs.domain.model.Book b where b.title=:title"); + + " from com.iluwatar.cqrs.domain.model.Book b where b.title=:title"); sqlQuery.setParameter("title", title); bookDto = sqlQuery.uniqueResult(); } @@ -71,10 +73,11 @@ public class QueryServiceImpl implements QueryService { public List getAuthorBooks(String username) { List bookDtos; try (var session = sessionFactory.openSession()) { - Query sqlQuery = session.createQuery( + Query sqlQuery = + session.createQuery( "select new com.iluwatar.cqrs.dto.Book(b.title, b.price)" - + " from com.iluwatar.cqrs.domain.model.Author a, com.iluwatar.cqrs.domain.model.Book b " - + "where b.author.id = a.id and a.username=:username"); + + " from com.iluwatar.cqrs.domain.model.Author a, com.iluwatar.cqrs.domain.model.Book b " + + "where b.author.id = a.id and a.username=:username"); sqlQuery.setParameter(AppConstants.USER_NAME, username); bookDtos = sqlQuery.list(); } @@ -85,9 +88,11 @@ public class QueryServiceImpl implements QueryService { public BigInteger getAuthorBooksCount(String username) { BigInteger bookcount; try (var session = sessionFactory.openSession()) { - var sqlQuery = session.createNativeQuery( - "SELECT count(b.title)" + " FROM Book b, Author a" - + " where b.author_id = a.id and a.username=:username"); + var sqlQuery = + session.createNativeQuery( + "SELECT count(b.title)" + + " FROM Book b, Author a" + + " where b.author_id = a.id and a.username=:username"); sqlQuery.setParameter(AppConstants.USER_NAME, username); bookcount = (BigInteger) sqlQuery.uniqueResult(); } @@ -103,5 +108,4 @@ public class QueryServiceImpl implements QueryService { } return authorcount; } - } diff --git a/command-query-responsibility-segregation/src/main/java/com/iluwatar/cqrs/util/HibernateUtil.java b/command-query-responsibility-segregation/src/main/java/com/iluwatar/cqrs/util/HibernateUtil.java index b7f6e76f3..0b777fc59 100644 --- a/command-query-responsibility-segregation/src/main/java/com/iluwatar/cqrs/util/HibernateUtil.java +++ b/command-query-responsibility-segregation/src/main/java/com/iluwatar/cqrs/util/HibernateUtil.java @@ -54,5 +54,4 @@ public class HibernateUtil { public static SessionFactory getSessionFactory() { return SESSIONFACTORY; } - } diff --git a/command-query-responsibility-segregation/src/test/java/com/iluwatar/cqrs/IntegrationTest.java b/command-query-responsibility-segregation/src/test/java/com/iluwatar/cqrs/IntegrationTest.java index d7df072aa..a4fb9ed3b 100644 --- a/command-query-responsibility-segregation/src/test/java/com/iluwatar/cqrs/IntegrationTest.java +++ b/command-query-responsibility-segregation/src/test/java/com/iluwatar/cqrs/IntegrationTest.java @@ -36,9 +36,7 @@ import java.math.BigInteger; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; -/** - * Integration test of IQueryService and ICommandService with h2 data - */ +/** Integration test of IQueryService and ICommandService with h2 data */ class IntegrationTest { private static QueryService queryService; @@ -64,7 +62,6 @@ class IntegrationTest { commandService.bookAddedToAuthor("title2", 20, "username1"); commandService.bookPriceUpdated("title2", 30); commandService.bookTitleUpdated("title2", "new_title2"); - } @Test @@ -80,7 +77,6 @@ class IntegrationTest { var author = queryService.getAuthorByUsername("new_username2"); var expectedAuthor = new Author("new_name2", "new_email2", "new_username2"); assertEquals(expectedAuthor, author); - } @Test @@ -109,5 +105,4 @@ class IntegrationTest { var authorCount = queryService.getAuthorsCount(); assertEquals(new BigInteger("2"), authorCount); } - } diff --git a/command/pom.xml b/command/pom.xml index d6532a8db..83fb68cbf 100644 --- a/command/pom.xml +++ b/command/pom.xml @@ -34,6 +34,14 @@ command + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/command/src/main/java/com/iluwatar/command/App.java b/command/src/main/java/com/iluwatar/command/App.java index 18dd6eee3..a8e0edcdf 100644 --- a/command/src/main/java/com/iluwatar/command/App.java +++ b/command/src/main/java/com/iluwatar/command/App.java @@ -32,9 +32,9 @@ package com.iluwatar.command; *

Four terms always associated with the command pattern are command, receiver, invoker and * client. A command object (spell) knows about the receiver (target) and invokes a method of the * receiver. An invoker object (wizard) receives a reference to the command to be executed and - * optionally does bookkeeping about the command execution. The invoker does not know anything - * about how the command is executed. The client decides which commands to execute at which - * points. To execute a command, it passes a reference of the function to the invoker object. + * optionally does bookkeeping about the command execution. The invoker does not know anything about + * how the command is executed. The client decides which commands to execute at which points. To + * execute a command, it passes a reference of the function to the invoker object. * *

In other words, in this example the wizard casts spells on the goblin. The wizard keeps track * of the previous spells cast, so it is easy to undo them. In addition, the wizard keeps track of diff --git a/command/src/main/java/com/iluwatar/command/Goblin.java b/command/src/main/java/com/iluwatar/command/Goblin.java index ed9ee49b8..911983c7b 100644 --- a/command/src/main/java/com/iluwatar/command/Goblin.java +++ b/command/src/main/java/com/iluwatar/command/Goblin.java @@ -24,9 +24,7 @@ */ package com.iluwatar.command; -/** - * Goblin is the target of the spells. - */ +/** Goblin is the target of the spells. */ public class Goblin extends Target { public Goblin() { diff --git a/command/src/main/java/com/iluwatar/command/Size.java b/command/src/main/java/com/iluwatar/command/Size.java index d16149c1d..203f190a8 100644 --- a/command/src/main/java/com/iluwatar/command/Size.java +++ b/command/src/main/java/com/iluwatar/command/Size.java @@ -26,12 +26,9 @@ package com.iluwatar.command; import lombok.RequiredArgsConstructor; -/** - * Enumeration for target size. - */ +/** Enumeration for target size. */ @RequiredArgsConstructor public enum Size { - SMALL("small"), NORMAL("normal"); diff --git a/command/src/main/java/com/iluwatar/command/Target.java b/command/src/main/java/com/iluwatar/command/Target.java index 7afd847b2..5885e0c4a 100644 --- a/command/src/main/java/com/iluwatar/command/Target.java +++ b/command/src/main/java/com/iluwatar/command/Target.java @@ -1,66 +1,58 @@ -/* - * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). - * - * The MIT License - * Copyright © 2014-2022 Ilkka Seppälä - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package com.iluwatar.command; - -import lombok.Getter; -import lombok.Setter; -import lombok.extern.slf4j.Slf4j; - -/** - * Base class for spell targets. - */ -@Slf4j -@Getter -@Setter -public abstract class Target { - - private Size size; - - private Visibility visibility; - - /** - * Print status. - */ - public void printStatus() { - LOGGER.info("{}, [size={}] [visibility={}]", this, getSize(), getVisibility()); - } - - /** - * Changes the size of the target. - */ - public void changeSize() { - var oldSize = getSize() == Size.NORMAL ? Size.SMALL : Size.NORMAL; - setSize(oldSize); - } - - /** - * Changes the visibility of the target. - */ - public void changeVisibility() { - var visible = getVisibility() == Visibility.INVISIBLE - ? Visibility.VISIBLE : Visibility.INVISIBLE; - setVisibility(visible); - } -} +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.command; + +import lombok.Getter; +import lombok.Setter; +import lombok.extern.slf4j.Slf4j; + +/** Base class for spell targets. */ +@Slf4j +@Getter +@Setter +public abstract class Target { + + private Size size; + + private Visibility visibility; + + /** Print status. */ + public void printStatus() { + LOGGER.info("{}, [size={}] [visibility={}]", this, getSize(), getVisibility()); + } + + /** Changes the size of the target. */ + public void changeSize() { + var oldSize = getSize() == Size.NORMAL ? Size.SMALL : Size.NORMAL; + setSize(oldSize); + } + + /** Changes the visibility of the target. */ + public void changeVisibility() { + var visible = + getVisibility() == Visibility.INVISIBLE ? Visibility.VISIBLE : Visibility.INVISIBLE; + setVisibility(visible); + } +} diff --git a/command/src/main/java/com/iluwatar/command/Visibility.java b/command/src/main/java/com/iluwatar/command/Visibility.java index d1539482e..a07e7876b 100644 --- a/command/src/main/java/com/iluwatar/command/Visibility.java +++ b/command/src/main/java/com/iluwatar/command/Visibility.java @@ -26,12 +26,9 @@ package com.iluwatar.command; import lombok.RequiredArgsConstructor; -/** - * Enumeration for target visibility. - */ +/** Enumeration for target visibility. */ @RequiredArgsConstructor public enum Visibility { - VISIBLE("visible"), INVISIBLE("invisible"); diff --git a/command/src/main/java/com/iluwatar/command/Wizard.java b/command/src/main/java/com/iluwatar/command/Wizard.java index 93d23cd68..797c41ec0 100644 --- a/command/src/main/java/com/iluwatar/command/Wizard.java +++ b/command/src/main/java/com/iluwatar/command/Wizard.java @@ -28,26 +28,20 @@ import java.util.Deque; import java.util.LinkedList; import lombok.extern.slf4j.Slf4j; -/** - * Wizard is the invoker of the commands. - */ +/** Wizard is the invoker of the commands. */ @Slf4j public class Wizard { private final Deque undoStack = new LinkedList<>(); private final Deque redoStack = new LinkedList<>(); - /** - * Cast spell. - */ + /** Cast spell. */ public void castSpell(Runnable runnable) { runnable.run(); undoStack.offerLast(runnable); } - /** - * Undo last spell. - */ + /** Undo last spell. */ public void undoLastSpell() { if (!undoStack.isEmpty()) { var previousSpell = undoStack.pollLast(); @@ -56,9 +50,7 @@ public class Wizard { } } - /** - * Redo last spell. - */ + /** Redo last spell. */ public void redoLastSpell() { if (!redoStack.isEmpty()) { var previousSpell = redoStack.pollLast(); diff --git a/command/src/test/java/com/iluwatar/command/AppTest.java b/command/src/test/java/com/iluwatar/command/AppTest.java index 830fee8fb..874bc3609 100644 --- a/command/src/test/java/com/iluwatar/command/AppTest.java +++ b/command/src/test/java/com/iluwatar/command/AppTest.java @@ -24,23 +24,21 @@ */ package com.iluwatar.command; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -/** - * Tests that Command example runs without errors. - */ +import org.junit.jupiter.api.Test; + +/** Tests that Command example runs without errors. */ class AppTest { /** * Issue: Add at least one assertion to this test case. * - * Solution: Inserted assertion to check whether the execution of the main method in {@link App#main(String[])} - * throws an exception. + *

Solution: Inserted assertion to check whether the execution of the main method in {@link + * App#main(String[])} throws an exception. */ @Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/command/src/test/java/com/iluwatar/command/CommandTest.java b/command/src/test/java/com/iluwatar/command/CommandTest.java index 766cede95..5e41c8846 100644 --- a/command/src/test/java/com/iluwatar/command/CommandTest.java +++ b/command/src/test/java/com/iluwatar/command/CommandTest.java @@ -80,17 +80,18 @@ class CommandTest { * This method asserts that the passed goblin object has the name as expectedName, size as * expectedSize and visibility as expectedVisibility. * - * @param goblin a goblin object whose state is to be verified against other - * parameters - * @param expectedName expectedName of the goblin - * @param expectedSize expected size of the goblin + * @param goblin a goblin object whose state is to be verified against other parameters + * @param expectedName expectedName of the goblin + * @param expectedSize expected size of the goblin * @param expectedVisibility expected visibility of the goblin */ - private void verifyGoblin(Goblin goblin, String expectedName, Size expectedSize, - Visibility expectedVisibility) { + private void verifyGoblin( + Goblin goblin, String expectedName, Size expectedSize, Visibility expectedVisibility) { assertEquals(expectedName, goblin.toString(), "Goblin's name must be same as expectedName"); assertEquals(expectedSize, goblin.getSize(), "Goblin's size must be same as expectedSize"); - assertEquals(expectedVisibility, goblin.getVisibility(), + assertEquals( + expectedVisibility, + goblin.getVisibility(), "Goblin's visibility must be same as expectedVisibility"); } } diff --git a/commander/src/main/java/com/iluwatar/commander/AppAllCases.java b/commander/src/main/java/com/iluwatar/commander/AppAllCases.java index e9a9bffc7..51fa1fed4 100644 --- a/commander/src/main/java/com/iluwatar/commander/AppAllCases.java +++ b/commander/src/main/java/com/iluwatar/commander/AppAllCases.java @@ -38,71 +38,86 @@ import com.iluwatar.commander.shippingservice.ShippingDatabase; import com.iluwatar.commander.shippingservice.ShippingService; /** - * The {@code AppAllCases} class tests various scenarios for the microservices involved - * in the order placement process. This class consolidates previously separated cases - * into a single class to manage different success and failure scenarios for each service. + * The {@code AppAllCases} class tests various scenarios for the microservices involved in the order + * placement process. This class consolidates previously separated cases into a single class to + * manage different success and failure scenarios for each service. + * + *

The application consists of abstract classes {@link Database} and {@link Service} which are + * extended by all the databases and services. Each service has a corresponding database to be + * updated and receives requests from an external user through the {@link Commander} class. There + * are 5 microservices: * - *

The application consists of abstract classes {@link Database} and {@link Service} - * which are extended by all the databases and services. Each service has a corresponding - * database to be updated and receives requests from an external user through the - * {@link Commander} class. There are 5 microservices: *

    - *
  • {@link ShippingService}
  • - *
  • {@link PaymentService}
  • - *
  • {@link MessagingService}
  • - *
  • {@link EmployeeHandle}
  • - *
  • {@link QueueDatabase}
  • + *
  • {@link ShippingService} + *
  • {@link PaymentService} + *
  • {@link MessagingService} + *
  • {@link EmployeeHandle} + *
  • {@link QueueDatabase} *
* - *

Retries are managed using the {@link Retry} class, ensuring idempotence by performing - * checks before making requests to services and updating the {@link Order} class fields - * upon request success or definitive failure. + *

Retries are managed using the {@link Retry} class, ensuring idempotence by performing checks + * before making requests to services and updating the {@link Order} class fields upon request + * success or definitive failure. * *

This class tests the following scenarios: + * *

    - *
  • Employee database availability and unavailability
  • - *
  • Payment service success and failures
  • - *
  • Messaging service database availability and unavailability
  • - *
  • Queue database availability and unavailability
  • - *
  • Shipping service success and failures
  • + *
  • Employee database availability and unavailability + *
  • Payment service success and failures + *
  • Messaging service database availability and unavailability + *
  • Queue database availability and unavailability + *
  • Shipping service success and failures *
* - *

Each scenario is encapsulated in a corresponding method that sets up the service - * conditions and tests the order placement process. + *

Each scenario is encapsulated in a corresponding method that sets up the service conditions + * and tests the order placement process. * - *

The main method executes all success and failure cases to verify the application's - * behavior under different conditions. + *

The main method executes all success and failure cases to verify the application's behavior + * under different conditions. * *

Usage: - *

- * {@code
+ *
+ * 
{@code
  * public static void main(String[] args) {
  *     AppAllCases app = new AppAllCases();
  *     app.testAllScenarios();
  * }
- * }
- * 
+ * }
*/ - public class AppAllCases { private static final RetryParams retryParams = RetryParams.DEFAULT; private static final TimeLimits timeLimits = TimeLimits.DEFAULT; // Employee Database Fail Case void employeeDatabaseUnavailableCase() { - var ps = new PaymentService(new PaymentDatabase(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException()); + var ps = + new PaymentService( + new PaymentDatabase(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException()); var ss = new ShippingService(new ShippingDatabase()); var ms = new MessagingService(new MessagingDatabase()); - var eh = new EmployeeHandle(new EmployeeDatabase(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException()); - var qdb = new QueueDatabase(new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException()); + var eh = + new EmployeeHandle( + new EmployeeDatabase(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException()); + var qdb = + new QueueDatabase( + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException()); var c = new Commander(eh, ps, ss, ms, qdb, retryParams, timeLimits); var user = new User("Jim", "ABCD"); var order = new Order(user, "book", 10f); @@ -114,8 +129,11 @@ public class AppAllCases { var ps = new PaymentService(new PaymentDatabase()); var ss = new ShippingService(new ShippingDatabase(), new ItemUnavailableException()); var ms = new MessagingService(new MessagingDatabase()); - var eh = new EmployeeHandle(new EmployeeDatabase(), new DatabaseUnavailableException(), - new DatabaseUnavailableException()); + var eh = + new EmployeeHandle( + new EmployeeDatabase(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException()); var qdb = new QueueDatabase(); var c = new Commander(eh, ps, ss, ms, qdb, retryParams, timeLimits); var user = new User("Jim", "ABCD"); @@ -127,10 +145,15 @@ public class AppAllCases { void messagingDatabaseUnavailableCasePaymentSuccess() { var ps = new PaymentService(new PaymentDatabase()); var ss = new ShippingService(new ShippingDatabase()); - var ms = new MessagingService(new MessagingDatabase(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException()); + var ms = + new MessagingService( + new MessagingDatabase(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException()); var eh = new EmployeeHandle(new EmployeeDatabase()); var qdb = new QueueDatabase(); var c = new Commander(eh, ps, ss, ms, qdb, retryParams, timeLimits); @@ -140,19 +163,34 @@ public class AppAllCases { } void messagingDatabaseUnavailableCasePaymentError() { - var ps = new PaymentService(new PaymentDatabase(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException()); + var ps = + new PaymentService( + new PaymentDatabase(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException()); var ss = new ShippingService(new ShippingDatabase()); - var ms = new MessagingService(new MessagingDatabase(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException()); + var ms = + new MessagingService( + new MessagingDatabase(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException()); var eh = new EmployeeHandle(new EmployeeDatabase()); var qdb = new QueueDatabase(); var c = new Commander(eh, ps, ss, ms, qdb, retryParams, timeLimits); @@ -161,21 +199,35 @@ public class AppAllCases { c.placeOrder(order); } - void messagingDatabaseUnavailableCasePaymentFailure() { - var ps = new PaymentService(new PaymentDatabase(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException()); + var ps = + new PaymentService( + new PaymentDatabase(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException()); var ss = new ShippingService(new ShippingDatabase()); - var ms = new MessagingService(new MessagingDatabase(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException()); + var ms = + new MessagingService( + new MessagingDatabase(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException()); var eh = new EmployeeHandle(new EmployeeDatabase()); - var qdb = new QueueDatabase(new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException()); + var qdb = + new QueueDatabase( + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException()); var c = new Commander(eh, ps, ss, ms, qdb, retryParams, timeLimits); var user = new User("Jim", "ABCD"); var order = new Order(user, "book", 10f); @@ -184,8 +236,11 @@ public class AppAllCases { // Messaging Database Success Case void messagingSuccessCase() { - var ps = new PaymentService(new PaymentDatabase(), new DatabaseUnavailableException(), - new DatabaseUnavailableException()); + var ps = + new PaymentService( + new PaymentDatabase(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException()); var ss = new ShippingService(new ShippingDatabase()); var ms = new MessagingService(new MessagingDatabase(), new DatabaseUnavailableException()); var eh = new EmployeeHandle(new EmployeeDatabase()); @@ -198,8 +253,11 @@ public class AppAllCases { // Payment Database Fail Cases void paymentNotPossibleCase() { - var ps = new PaymentService(new PaymentDatabase(), new DatabaseUnavailableException(), - new PaymentDetailsErrorException()); + var ps = + new PaymentService( + new PaymentDatabase(), + new DatabaseUnavailableException(), + new PaymentDetailsErrorException()); var ss = new ShippingService(new ShippingDatabase()); var ms = new MessagingService(new MessagingDatabase(), new DatabaseUnavailableException()); var eh = new EmployeeHandle(new EmployeeDatabase()); @@ -211,10 +269,15 @@ public class AppAllCases { } void paymentDatabaseUnavailableCase() { - var ps = new PaymentService(new PaymentDatabase(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException()); + var ps = + new PaymentService( + new PaymentDatabase(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException()); var ss = new ShippingService(new ShippingDatabase()); var ms = new MessagingService(new MessagingDatabase()); var eh = new EmployeeHandle(new EmployeeDatabase()); @@ -227,8 +290,11 @@ public class AppAllCases { // Payment Database Success Case void paymentSuccessCase() { - var ps = new PaymentService(new PaymentDatabase(), new DatabaseUnavailableException(), - new DatabaseUnavailableException()); + var ps = + new PaymentService( + new PaymentDatabase(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException()); var ss = new ShippingService(new ShippingDatabase()); var ms = new MessagingService(new MessagingDatabase(), new DatabaseUnavailableException()); var eh = new EmployeeHandle(new EmployeeDatabase()); @@ -241,16 +307,26 @@ public class AppAllCases { // Queue Database Fail Cases void queuePaymentTaskDatabaseUnavailableCase() { - var ps = new PaymentService(new PaymentDatabase(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException()); + var ps = + new PaymentService( + new PaymentDatabase(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException()); var ss = new ShippingService(new ShippingDatabase()); var ms = new MessagingService(new MessagingDatabase()); var eh = new EmployeeHandle(new EmployeeDatabase()); - var qdb = new QueueDatabase(new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException()); + var qdb = + new QueueDatabase( + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException()); var c = new Commander(eh, ps, ss, ms, qdb, retryParams, timeLimits); var user = new User("Jim", "ABCD"); var order = new Order(user, "book", 10f); @@ -260,14 +336,24 @@ public class AppAllCases { void queueMessageTaskDatabaseUnavailableCase() { var ps = new PaymentService(new PaymentDatabase()); var ss = new ShippingService(new ShippingDatabase()); - var ms = new MessagingService(new MessagingDatabase(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException()); + var ms = + new MessagingService( + new MessagingDatabase(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException()); var eh = new EmployeeHandle(new EmployeeDatabase()); - var qdb = new QueueDatabase(new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException()); + var qdb = + new QueueDatabase( + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException()); var c = new Commander(eh, ps, ss, ms, qdb, retryParams, timeLimits); var user = new User("Jim", "ABCD"); var order = new Order(user, "book", 10f); @@ -278,20 +364,35 @@ public class AppAllCases { var ps = new PaymentService(new PaymentDatabase()); var ss = new ShippingService(new ShippingDatabase(), new ItemUnavailableException()); var ms = new MessagingService(new MessagingDatabase()); - var eh = new EmployeeHandle(new EmployeeDatabase(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException()); + var eh = + new EmployeeHandle( + new EmployeeDatabase(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException()); var qdb = - new QueueDatabase(new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException()); + new QueueDatabase( + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException()); var c = new Commander(eh, ps, ss, ms, qdb, retryParams, timeLimits); var user = new User("Jim", "ABCD"); var order = new Order(user, "book", 10f); @@ -303,8 +404,11 @@ public class AppAllCases { var ps = new PaymentService(new PaymentDatabase()); var ss = new ShippingService(new ShippingDatabase(), new ItemUnavailableException()); var ms = new MessagingService(new MessagingDatabase()); - var eh = new EmployeeHandle(new EmployeeDatabase(), new DatabaseUnavailableException(), - new DatabaseUnavailableException()); + var eh = + new EmployeeHandle( + new EmployeeDatabase(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException()); var qdb = new QueueDatabase(); var c = new Commander(eh, ps, ss, ms, qdb, retryParams, timeLimits); var user = new User("Jim", "ABCD"); @@ -327,10 +431,16 @@ public class AppAllCases { void shippingDatabaseUnavailableCase() { var ps = new PaymentService(new PaymentDatabase()); - var ss = new ShippingService(new ShippingDatabase(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException()); + var ss = + new ShippingService( + new ShippingDatabase(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException()); var ms = new MessagingService(new MessagingDatabase()); var eh = new EmployeeHandle(new EmployeeDatabase()); var qdb = new QueueDatabase(); @@ -357,8 +467,11 @@ public class AppAllCases { var ps = new PaymentService(new PaymentDatabase()); var ss = new ShippingService(new ShippingDatabase(), new ItemUnavailableException()); var ms = new MessagingService(new MessagingDatabase(), new DatabaseUnavailableException()); - var eh = new EmployeeHandle(new EmployeeDatabase(), new DatabaseUnavailableException(), - new DatabaseUnavailableException()); + var eh = + new EmployeeHandle( + new EmployeeDatabase(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException()); var qdb = new QueueDatabase(); var c = new Commander(eh, ps, ss, ms, qdb, retryParams, timeLimits); var user = new User("Jim", "ABCD"); @@ -368,6 +481,7 @@ public class AppAllCases { /** * Program entry point. + * * @param args command line arguments */ public static void main(String[] args) { @@ -383,7 +497,7 @@ public class AppAllCases { app.messagingDatabaseUnavailableCasePaymentFailure(); app.messagingSuccessCase(); - //Payment Database cases + // Payment Database cases app.paymentNotPossibleCase(); app.paymentDatabaseUnavailableCase(); app.paymentSuccessCase(); @@ -400,4 +514,4 @@ public class AppAllCases { app.shippingItemNotPossibleCase(); app.shippingSuccessCase(); } -} \ No newline at end of file +} diff --git a/commander/src/main/java/com/iluwatar/commander/Commander.java b/commander/src/main/java/com/iluwatar/commander/Commander.java index 24648bce3..b25e1c128 100644 --- a/commander/src/main/java/com/iluwatar/commander/Commander.java +++ b/commander/src/main/java/com/iluwatar/commander/Commander.java @@ -42,36 +42,34 @@ import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - /** - *

Commander pattern is used to handle all issues that can come up while making a - * distributed transaction. The idea is to have a commander, which coordinates the execution of all - * instructions and ensures proper completion using retries and taking care of idempotence. By - * queueing instructions while they haven't been done, we can ensure a state of 'eventual - * consistency'.

- *

In our example, we have an e-commerce application. When the user places an order, - * the shipping service is intimated first. If the service does not respond for some reason, the - * order is not placed. If response is received, the commander then calls for the payment service to - * be intimated. If this fails, the shipping still takes place (order converted to COD) and the item - * is queued. If the queue is also found to be unavailable, the payment is noted to be not done and + * Commander pattern is used to handle all issues that can come up while making a distributed + * transaction. The idea is to have a commander, which coordinates the execution of all instructions + * and ensures proper completion using retries and taking care of idempotence. By queueing + * instructions while they haven't been done, we can ensure a state of 'eventual consistency'. + * + *

In our example, we have an e-commerce application. When the user places an order, the shipping + * service is intimated first. If the service does not respond for some reason, the order is not + * placed. If response is received, the commander then calls for the payment service to be + * intimated. If this fails, the shipping still takes place (order converted to COD) and the item is + * queued. If the queue is also found to be unavailable, the payment is noted to be not done and * this is added to an employee database. Three types of messages are sent to the user - one, if * payment succeeds; two, if payment fails definitively; and three, if payment fails in the first * attempt. If the message is not sent, this is also queued and is added to employee db. We also * have a time limit for each instruction to be completed, after which, the instruction is not * executed, thereby ensuring that resources are not held for too long. In the rare occasion in - * which everything fails, an individual would have to step in to figure out how to solve the - * issue.

- *

We have abstract classes {@link Database} and {@link Service} which are extended - * by all the databases and services. Each service has a database to be updated, and receives - * request from an outside user (the {@link Commander} class here). There are 5 microservices - - * {@link ShippingService}, {@link PaymentService}, {@link MessagingService}, {@link EmployeeHandle} - * and a {@link QueueDatabase}. We use retries to execute any instruction using {@link Retry} class, - * and idempotence is ensured by going through some checks before making requests to services and - * making change in {@link Order} class fields if request succeeds or definitively fails. There is - * a single class {@link AppAllCases} that looks at the different scenarios that may be encountered - * during the placing of an order, including both success and failure cases for each service.

+ * which everything fails, an individual would have to step in to figure out how to solve the issue. + * + *

We have abstract classes {@link Database} and {@link Service} which are extended by all the + * databases and services. Each service has a database to be updated, and receives request from an + * outside user (the {@link Commander} class here). There are 5 microservices - {@link + * ShippingService}, {@link PaymentService}, {@link MessagingService}, {@link EmployeeHandle} and a + * {@link QueueDatabase}. We use retries to execute any instruction using {@link Retry} class, and + * idempotence is ensured by going through some checks before making requests to services and making + * change in {@link Order} class fields if request succeeds or definitively fails. There is a single + * class {@link AppAllCases} that looks at the different scenarios that may be encountered during + * the placing of an order, including both success and failure cases for each service. */ - public class Commander { private final QueueDatabase queue; @@ -79,7 +77,8 @@ public class Commander { private final PaymentService paymentService; private final ShippingService shippingService; private final MessagingService messagingService; - private int queueItems = 0; //keeping track here only so don't need access to queue db to get this + private int queueItems = + 0; // keeping track here only so don't need access to queue db to get this private final int numOfRetries; private final long retryDuration; private final long queueTime; @@ -90,19 +89,24 @@ public class Commander { private boolean finalSiteMsgShown; private static final Logger LOG = LoggerFactory.getLogger(Commander.class); - //we could also have another db where it stores all orders + // we could also have another db where it stores all orders private static final String ORDER_ID = "Order {}"; private static final String REQUEST_ID = " request Id: {}"; private static final String ERROR_CONNECTING_MSG_SVC = - ": Error in connecting to messaging service "; - private static final String TRY_CONNECTING_MSG_SVC = - ": Trying to connect to messaging service.."; + ": Error in connecting to messaging service "; + private static final String TRY_CONNECTING_MSG_SVC = ": Trying to connect to messaging service.."; private static final String DEFAULT_EXCEPTION_MESSAGE = "An exception occurred"; - Commander(EmployeeHandle empDb, PaymentService paymentService, ShippingService shippingService, - MessagingService messagingService, QueueDatabase qdb, RetryParams retryParams, TimeLimits timeLimits) { + Commander( + EmployeeHandle empDb, + PaymentService paymentService, + ShippingService shippingService, + MessagingService messagingService, + QueueDatabase qdb, + RetryParams retryParams, + TimeLimits timeLimits) { this.paymentService = paymentService; this.shippingService = shippingService; this.messagingService = messagingService; @@ -124,47 +128,68 @@ public class Commander { private void sendShippingRequest(Order order) { var list = shippingService.exceptionsList; - Retry.Operation op = l -> { - if (!l.isEmpty()) { - if (DatabaseUnavailableException.class.isAssignableFrom(l.get(0).getClass())) { - LOG.debug(ORDER_ID + ": Error in connecting to shipping service, " - + "trying again..", order.id); - } else { - LOG.debug(ORDER_ID + ": Error in creating shipping request..", order.id); - } - throw l.remove(0); - } - String transactionId = shippingService.receiveRequest(order.item, order.user.address); - //could save this transaction id in a db too - LOG.info(ORDER_ID + ": Shipping placed successfully, transaction id: {}", - order.id, transactionId); - LOG.info("Order has been placed and will be shipped to you. Please wait while we make your" - + " payment... "); - sendPaymentRequest(order); - }; - Retry.HandleErrorIssue handleError = (o, err) -> { - if (ShippingNotPossibleException.class.isAssignableFrom(err.getClass())) { - LOG.info("Shipping is currently not possible to your address. We are working on the problem" - + " and will get back to you asap."); - finalSiteMsgShown = true; - LOG.info(ORDER_ID + ": Shipping not possible to address, trying to add problem " - + "to employee db..", order.id); - employeeHandleIssue(o); - } else if (ItemUnavailableException.class.isAssignableFrom(err.getClass())) { - LOG.info("This item is currently unavailable. We will inform you as soon as the item " - + "becomes available again."); - finalSiteMsgShown = true; - LOG.info(ORDER_ID + ": Item {}" + " unavailable, trying to add " - + "problem to employee handle..", order.id, order.item); - employeeHandleIssue(o); - } else { - LOG.info("Sorry, there was a problem in creating your order. Please try later."); - LOG.error(ORDER_ID + ": Shipping service unavailable, order not placed..", order.id); - finalSiteMsgShown = true; - } - }; - var r = new Retry<>(op, handleError, numOfRetries, retryDuration, - e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass())); + Retry.Operation op = + l -> { + if (!l.isEmpty()) { + if (DatabaseUnavailableException.class.isAssignableFrom(l.get(0).getClass())) { + LOG.debug( + ORDER_ID + ": Error in connecting to shipping service, " + "trying again..", + order.id); + } else { + LOG.debug(ORDER_ID + ": Error in creating shipping request..", order.id); + } + throw l.remove(0); + } + String transactionId = shippingService.receiveRequest(order.item, order.user.address); + // could save this transaction id in a db too + LOG.info( + ORDER_ID + ": Shipping placed successfully, transaction id: {}", + order.id, + transactionId); + LOG.info( + "Order has been placed and will be shipped to you. Please wait while we make your" + + " payment... "); + sendPaymentRequest(order); + }; + Retry.HandleErrorIssue handleError = + (o, err) -> { + if (ShippingNotPossibleException.class.isAssignableFrom(err.getClass())) { + LOG.info( + "Shipping is currently not possible to your address. We are working on the problem" + + " and will get back to you asap."); + finalSiteMsgShown = true; + LOG.info( + ORDER_ID + + ": Shipping not possible to address, trying to add problem " + + "to employee db..", + order.id); + employeeHandleIssue(o); + } else if (ItemUnavailableException.class.isAssignableFrom(err.getClass())) { + LOG.info( + "This item is currently unavailable. We will inform you as soon as the item " + + "becomes available again."); + finalSiteMsgShown = true; + LOG.info( + ORDER_ID + + ": Item {}" + + " unavailable, trying to add " + + "problem to employee handle..", + order.id, + order.item); + employeeHandleIssue(o); + } else { + LOG.info("Sorry, there was a problem in creating your order. Please try later."); + LOG.error(ORDER_ID + ": Shipping service unavailable, order not placed..", order.id); + finalSiteMsgShown = true; + } + }; + var r = + new Retry<>( + op, + handleError, + numOfRetries, + retryDuration, + e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass())); r.perform(list, order); } @@ -174,23 +199,30 @@ public class Commander { order.paid = PaymentStatus.NOT_DONE; sendPaymentFailureMessage(order); LOG.error(ORDER_ID + ": Payment time for order over, failed and returning..", order.id); - } //if succeeded or failed, would have been dequeued, no attempt to make payment + } // if succeeded or failed, would have been dequeued, no attempt to make payment return; } var list = paymentService.exceptionsList; - var t = new Thread(() -> { - Retry.Operation op = getRetryOperation(order); + var t = + new Thread( + () -> { + Retry.Operation op = getRetryOperation(order); - Retry.HandleErrorIssue handleError = getRetryHandleErrorIssue(order); + Retry.HandleErrorIssue handleError = getRetryHandleErrorIssue(order); - var r = new Retry<>(op, handleError, numOfRetries, retryDuration, - e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass())); - try { - r.perform(list, order); - } catch (Exception e1) { - LOG.error(DEFAULT_EXCEPTION_MESSAGE, e1); - } - }); + var r = + new Retry<>( + op, + handleError, + numOfRetries, + retryDuration, + e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass())); + try { + r.perform(list, order); + } catch (Exception e1) { + LOG.error(DEFAULT_EXCEPTION_MESSAGE, e1); + } + }); t.start(); } @@ -203,8 +235,8 @@ public class Commander { if (o.messageSent.equals(MessageSent.NONE_SENT)) { handlePaymentError(order.id, o); } - if (o.paid.equals(PaymentStatus.TRYING) && System - .currentTimeMillis() - o.createdTime < paymentTime) { + if (o.paid.equals(PaymentStatus.TRYING) + && System.currentTimeMillis() - o.createdTime < paymentTime) { var qt = new QueueTask(o, TaskType.PAYMENT, -1); updateQueue(qt); } @@ -214,8 +246,9 @@ public class Commander { private void handlePaymentError(String orderId, Order o) { if (!finalSiteMsgShown) { - LOG.info("There was an error in payment. We are on it, and will get back to you " - + "asap. Don't worry, your order has been placed and will be shipped."); + LOG.info( + "There was an error in payment. We are on it, and will get back to you " + + "asap. Don't worry, your order has been placed and will be shipped."); finalSiteMsgShown = true; } LOG.warn(ORDER_ID + ": Payment error, going to queue..", orderId); @@ -224,9 +257,10 @@ public class Commander { private void handlePaymentDetailsError(String orderId, Order o) { if (!finalSiteMsgShown) { - LOG.info("There was an error in payment. Your account/card details " - + "may have been incorrect. " - + "Meanwhile, your order has been converted to COD and will be shipped."); + LOG.info( + "There was an error in payment. Your account/card details " + + "may have been incorrect. " + + "Meanwhile, your order has been converted to COD and will be shipped."); finalSiteMsgShown = true; } LOG.error(ORDER_ID + ": Payment details incorrect, failed..", orderId); @@ -238,8 +272,8 @@ public class Commander { return l -> { if (!l.isEmpty()) { if (DatabaseUnavailableException.class.isAssignableFrom(l.get(0).getClass())) { - LOG.debug(ORDER_ID + ": Error in connecting to payment service," - + " trying again..", order.id); + LOG.debug( + ORDER_ID + ": Error in connecting to payment service," + " trying again..", order.id); } else { LOG.debug(ORDER_ID + ": Error in creating payment request..", order.id); } @@ -248,8 +282,7 @@ public class Commander { if (order.paid.equals(PaymentStatus.TRYING)) { var transactionId = paymentService.receiveRequest(order.price); order.paid = PaymentStatus.DONE; - LOG.info(ORDER_ID + ": Payment successful, transaction Id: {}", - order.id, transactionId); + LOG.info(ORDER_ID + ": Payment successful, transaction Id: {}", order.id, transactionId); if (!finalSiteMsgShown) { LOG.info("Payment made successfully, thank you for shopping with us!!"); finalSiteMsgShown = true; @@ -266,92 +299,122 @@ public class Commander { LOG.trace(ORDER_ID + ": Queue time for order over, failed..", qt.order.id); return; } else if (qt.taskType.equals(TaskType.PAYMENT) && !qt.order.paid.equals(PaymentStatus.TRYING) - || qt.taskType.equals(TaskType.MESSAGING) && (qt.messageType == 1 - && !qt.order.messageSent.equals(MessageSent.NONE_SENT) - || qt.order.messageSent.equals(MessageSent.PAYMENT_FAIL) - || qt.order.messageSent.equals(MessageSent.PAYMENT_SUCCESSFUL)) + || qt.taskType.equals(TaskType.MESSAGING) + && (qt.messageType == 1 && !qt.order.messageSent.equals(MessageSent.NONE_SENT) + || qt.order.messageSent.equals(MessageSent.PAYMENT_FAIL) + || qt.order.messageSent.equals(MessageSent.PAYMENT_SUCCESSFUL)) || qt.taskType.equals(TaskType.EMPLOYEE_DB) && qt.order.addedToEmployeeHandle) { LOG.trace(ORDER_ID + ": Not queueing task since task already done..", qt.order.id); return; } var list = queue.exceptionsList; - Thread t = new Thread(() -> { - Retry.Operation op = list1 -> { - if (!list1.isEmpty()) { - LOG.warn(ORDER_ID + ": Error in connecting to queue db, trying again..", qt.order.id); - throw list1.remove(0); - } - queue.add(qt); - queueItems++; - LOG.info(ORDER_ID + ": {}" + " task enqueued..", qt.order.id, qt.getType()); - tryDoingTasksInQueue(); - }; - Retry.HandleErrorIssue handleError = (qt1, err) -> { - if (qt1.taskType.equals(TaskType.PAYMENT)) { - qt1.order.paid = PaymentStatus.NOT_DONE; - sendPaymentFailureMessage(qt1.order); - LOG.error(ORDER_ID + ": Unable to enqueue payment task," - + " payment failed..", qt1.order.id); - } - LOG.error(ORDER_ID + ": Unable to enqueue task of type {}" - + ", trying to add to employee handle..", qt1.order.id, qt1.getType()); - employeeHandleIssue(qt1.order); - }; - var r = new Retry<>(op, handleError, numOfRetries, retryDuration, - e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass())); - try { - r.perform(list, qt); - } catch (Exception e1) { - LOG.error(DEFAULT_EXCEPTION_MESSAGE, e1); - } - }); + Thread t = + new Thread( + () -> { + Retry.Operation op = + list1 -> { + if (!list1.isEmpty()) { + LOG.warn( + ORDER_ID + ": Error in connecting to queue db, trying again..", + qt.order.id); + throw list1.remove(0); + } + queue.add(qt); + queueItems++; + LOG.info(ORDER_ID + ": {}" + " task enqueued..", qt.order.id, qt.getType()); + tryDoingTasksInQueue(); + }; + Retry.HandleErrorIssue handleError = + (qt1, err) -> { + if (qt1.taskType.equals(TaskType.PAYMENT)) { + qt1.order.paid = PaymentStatus.NOT_DONE; + sendPaymentFailureMessage(qt1.order); + LOG.error( + ORDER_ID + ": Unable to enqueue payment task," + " payment failed..", + qt1.order.id); + } + LOG.error( + ORDER_ID + + ": Unable to enqueue task of type {}" + + ", trying to add to employee handle..", + qt1.order.id, + qt1.getType()); + employeeHandleIssue(qt1.order); + }; + var r = + new Retry<>( + op, + handleError, + numOfRetries, + retryDuration, + e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass())); + try { + r.perform(list, qt); + } catch (Exception e1) { + LOG.error(DEFAULT_EXCEPTION_MESSAGE, e1); + } + }); t.start(); } - private void tryDoingTasksInQueue() { //commander controls operations done to queue + private void tryDoingTasksInQueue() { // commander controls operations done to queue var list = queue.exceptionsList; - var t2 = new Thread(() -> { - Retry.Operation op = list1 -> { - if (!list1.isEmpty()) { - LOG.warn("Error in accessing queue db to do tasks, trying again.."); - throw list1.remove(0); - } - doTasksInQueue(); - }; - Retry.HandleErrorIssue handleError = (o, err) -> { - }; - var r = new Retry<>(op, handleError, numOfRetries, retryDuration, - e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass())); - try { - r.perform(list, null); - } catch (Exception e1) { - LOG.error(DEFAULT_EXCEPTION_MESSAGE, e1); - } - }); + var t2 = + new Thread( + () -> { + Retry.Operation op = + list1 -> { + if (!list1.isEmpty()) { + LOG.warn("Error in accessing queue db to do tasks, trying again.."); + throw list1.remove(0); + } + doTasksInQueue(); + }; + Retry.HandleErrorIssue handleError = (o, err) -> {}; + var r = + new Retry<>( + op, + handleError, + numOfRetries, + retryDuration, + e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass())); + try { + r.perform(list, null); + } catch (Exception e1) { + LOG.error(DEFAULT_EXCEPTION_MESSAGE, e1); + } + }); t2.start(); } private void tryDequeue() { var list = queue.exceptionsList; - var t3 = new Thread(() -> { - Retry.Operation op = list1 -> { - if (!list1.isEmpty()) { - LOG.warn("Error in accessing queue db to dequeue task, trying again.."); - throw list1.remove(0); - } - queue.dequeue(); - queueItems--; - }; - Retry.HandleErrorIssue handleError = (o, err) -> { - }; - var r = new Retry<>(op, handleError, numOfRetries, retryDuration, - e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass())); - try { - r.perform(list, null); - } catch (Exception e1) { - LOG.error(DEFAULT_EXCEPTION_MESSAGE, e1); - } - }); + var t3 = + new Thread( + () -> { + Retry.Operation op = + list1 -> { + if (!list1.isEmpty()) { + LOG.warn("Error in accessing queue db to dequeue task, trying again.."); + throw list1.remove(0); + } + queue.dequeue(); + queueItems--; + }; + Retry.HandleErrorIssue handleError = (o, err) -> {}; + var r = + new Retry<>( + op, + handleError, + numOfRetries, + retryDuration, + e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass())); + try { + r.perform(list, null); + } catch (Exception e1) { + LOG.error(DEFAULT_EXCEPTION_MESSAGE, e1); + } + }); t3.start(); } @@ -361,28 +424,39 @@ public class Commander { return; } var list = messagingService.exceptionsList; - Thread t = new Thread(() -> { - Retry.Operation op = handleSuccessMessageRetryOperation(order); - Retry.HandleErrorIssue handleError = (o, err) -> handleSuccessMessageErrorIssue(order, o); - var r = new Retry<>(op, handleError, numOfRetries, retryDuration, - e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass())); - try { - r.perform(list, order); - } catch (Exception e1) { - LOG.error(DEFAULT_EXCEPTION_MESSAGE, e1); - } - }); + Thread t = + new Thread( + () -> { + Retry.Operation op = handleSuccessMessageRetryOperation(order); + Retry.HandleErrorIssue handleError = + (o, err) -> handleSuccessMessageErrorIssue(order, o); + var r = + new Retry<>( + op, + handleError, + numOfRetries, + retryDuration, + e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass())); + try { + r.perform(list, order); + } catch (Exception e1) { + LOG.error(DEFAULT_EXCEPTION_MESSAGE, e1); + } + }); t.start(); } private void handleSuccessMessageErrorIssue(Order order, Order o) { - if ((o.messageSent.equals(MessageSent.NONE_SENT) || o.messageSent - .equals(MessageSent.PAYMENT_TRYING)) + if ((o.messageSent.equals(MessageSent.NONE_SENT) + || o.messageSent.equals(MessageSent.PAYMENT_TRYING)) && System.currentTimeMillis() - o.createdTime < messageTime) { var qt = new QueueTask(order, TaskType.MESSAGING, 2); updateQueue(qt); - LOG.info(ORDER_ID + ": Error in sending Payment Success message, trying to" - + " queue task and add to employee handle..", order.id); + LOG.info( + ORDER_ID + + ": Error in sending Payment Success message, trying to" + + " queue task and add to employee handle..", + order.id); employeeHandleIssue(order); } } @@ -391,11 +465,12 @@ public class Commander { return l -> { if (!l.isEmpty()) { if (DatabaseUnavailableException.class.isAssignableFrom(l.get(0).getClass())) { - LOG.debug(ORDER_ID + ERROR_CONNECTING_MSG_SVC - + "(Payment Success msg), trying again..", order.id); + LOG.debug( + ORDER_ID + ERROR_CONNECTING_MSG_SVC + "(Payment Success msg), trying again..", + order.id); } else { - LOG.debug(ORDER_ID + ": Error in creating Payment Success" - + " messaging request..", order.id); + LOG.debug( + ORDER_ID + ": Error in creating Payment Success" + " messaging request..", order.id); } throw l.remove(0); } @@ -403,8 +478,7 @@ public class Commander { && !order.messageSent.equals(MessageSent.PAYMENT_SUCCESSFUL)) { var requestId = messagingService.receiveRequest(2); order.messageSent = MessageSent.PAYMENT_SUCCESSFUL; - LOG.info(ORDER_ID + ": Payment Success message sent," - + REQUEST_ID, order.id, requestId); + LOG.info(ORDER_ID + ": Payment Success message sent," + REQUEST_ID, order.id, requestId); } }; } @@ -415,38 +489,53 @@ public class Commander { return; } var list = messagingService.exceptionsList; - var t = new Thread(() -> { - Retry.Operation op = l -> handlePaymentFailureRetryOperation(order, l); - Retry.HandleErrorIssue handleError = (o, err) -> handlePaymentErrorIssue(order, o); - var r = new Retry<>(op, handleError, numOfRetries, retryDuration, - e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass())); - try { - r.perform(list, order); - } catch (Exception e1) { - LOG.error(DEFAULT_EXCEPTION_MESSAGE, e1); - } - }); + var t = + new Thread( + () -> { + Retry.Operation op = l -> handlePaymentFailureRetryOperation(order, l); + Retry.HandleErrorIssue handleError = + (o, err) -> handlePaymentErrorIssue(order, o); + var r = + new Retry<>( + op, + handleError, + numOfRetries, + retryDuration, + e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass())); + try { + r.perform(list, order); + } catch (Exception e1) { + LOG.error(DEFAULT_EXCEPTION_MESSAGE, e1); + } + }); t.start(); } private void handlePaymentErrorIssue(Order order, Order o) { - if ((o.messageSent.equals(MessageSent.NONE_SENT) || o.messageSent - .equals(MessageSent.PAYMENT_TRYING)) + if ((o.messageSent.equals(MessageSent.NONE_SENT) + || o.messageSent.equals(MessageSent.PAYMENT_TRYING)) && System.currentTimeMillis() - o.createdTime < messageTime) { var qt = new QueueTask(order, TaskType.MESSAGING, 0); updateQueue(qt); - LOG.warn(ORDER_ID + ": Error in sending Payment Failure message, " - + "trying to queue task and add to employee handle..", order.id); + LOG.warn( + ORDER_ID + + ": Error in sending Payment Failure message, " + + "trying to queue task and add to employee handle..", + order.id); employeeHandleIssue(o); } } - private void handlePaymentFailureRetryOperation(Order order, List l) throws IndexOutOfBoundsException, DatabaseUnavailableException { + private void handlePaymentFailureRetryOperation(Order order, List l) + throws IndexOutOfBoundsException, DatabaseUnavailableException { if (!l.isEmpty()) { if (DatabaseUnavailableException.class.isAssignableFrom(l.get(0).getClass())) { - LOG.debug(ORDER_ID + ERROR_CONNECTING_MSG_SVC + "(Payment Failure msg), trying again..", order.id); + LOG.debug( + ORDER_ID + ERROR_CONNECTING_MSG_SVC + "(Payment Failure msg), trying again..", + order.id); } else { - LOG.debug(ORDER_ID + ": Error in creating Payment Failure" + " message request..", order.id); + LOG.debug( + ORDER_ID + ": Error in creating Payment Failure" + " message request..", order.id); } throw new IndexOutOfBoundsException(); } @@ -454,8 +543,10 @@ public class Commander { && !order.messageSent.equals(MessageSent.PAYMENT_SUCCESSFUL)) { var requestId = messagingService.receiveRequest(0); order.messageSent = MessageSent.PAYMENT_FAIL; - LOG.info(ORDER_ID + ": Payment Failure message sent successfully," - + REQUEST_ID, order.id, requestId); + LOG.info( + ORDER_ID + ": Payment Failure message sent successfully," + REQUEST_ID, + order.id, + requestId); } } @@ -465,28 +556,37 @@ public class Commander { return; } var list = messagingService.exceptionsList; - var t = new Thread(() -> { - Retry.Operation op = l -> handlePaymentPossibleErrorMsgRetryOperation(order, l); - Retry.HandleErrorIssue handleError = (o, err) -> handlePaymentPossibleErrorMsgErrorIssue(order, o); - var r = new Retry<>(op, handleError, numOfRetries, retryDuration, - e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass())); - try { - r.perform(list, order); - } catch (Exception e1) { - LOG.error(DEFAULT_EXCEPTION_MESSAGE, e1); - } - }); + var t = + new Thread( + () -> { + Retry.Operation op = l -> handlePaymentPossibleErrorMsgRetryOperation(order, l); + Retry.HandleErrorIssue handleError = + (o, err) -> handlePaymentPossibleErrorMsgErrorIssue(order, o); + var r = + new Retry<>( + op, + handleError, + numOfRetries, + retryDuration, + e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass())); + try { + r.perform(list, order); + } catch (Exception e1) { + LOG.error(DEFAULT_EXCEPTION_MESSAGE, e1); + } + }); t.start(); } private void handlePaymentPossibleErrorMsgErrorIssue(Order order, Order o) { - if (o.messageSent.equals(MessageSent.NONE_SENT) && order.paid - .equals(PaymentStatus.TRYING) + if (o.messageSent.equals(MessageSent.NONE_SENT) + && order.paid.equals(PaymentStatus.TRYING) && System.currentTimeMillis() - o.createdTime < messageTime) { var qt = new QueueTask(order, TaskType.MESSAGING, 1); updateQueue(qt); - LOG.warn("Order {}: Error in sending Payment Error message, trying to queue task and add to employee handle..", - order.id); + LOG.warn( + "Order {}: Error in sending Payment Error message, trying to queue task and add to employee handle..", + order.id); employeeHandleIssue(o); } } @@ -495,20 +595,22 @@ public class Commander { throws IndexOutOfBoundsException, DatabaseUnavailableException { if (!l.isEmpty()) { if (DatabaseUnavailableException.class.isAssignableFrom(l.get(0).getClass())) { - LOG.debug(ORDER_ID + ERROR_CONNECTING_MSG_SVC - + "(Payment Error msg), trying again..", order.id); + LOG.debug( + ORDER_ID + ERROR_CONNECTING_MSG_SVC + "(Payment Error msg), trying again..", order.id); } else { - LOG.debug(ORDER_ID + ": Error in creating Payment Error" - + " messaging request..", order.id); + LOG.debug( + ORDER_ID + ": Error in creating Payment Error" + " messaging request..", order.id); } throw new IndexOutOfBoundsException(); } - if (order.paid.equals(PaymentStatus.TRYING) && order.messageSent - .equals(MessageSent.NONE_SENT)) { + if (order.paid.equals(PaymentStatus.TRYING) + && order.messageSent.equals(MessageSent.NONE_SENT)) { var requestId = messagingService.receiveRequest(1); order.messageSent = MessageSent.PAYMENT_TRYING; - LOG.info(ORDER_ID + ": Payment Error message sent successfully," - + REQUEST_ID, order.id, requestId); + LOG.info( + ORDER_ID + ": Payment Error message sent successfully," + REQUEST_ID, + order.id, + requestId); } } @@ -518,51 +620,70 @@ public class Commander { return; } var list = employeeDb.exceptionsList; - var t = new Thread(() -> { - Retry.Operation op = l -> { - if (!l.isEmpty()) { - LOG.warn(ORDER_ID + ": Error in connecting to employee handle," - + " trying again..", order.id); - throw l.remove(0); - } - if (!order.addedToEmployeeHandle) { - employeeDb.receiveRequest(order); - order.addedToEmployeeHandle = true; - LOG.info(ORDER_ID + ": Added order to employee database", order.id); - } - }; - Retry.HandleErrorIssue handleError = (o, err) -> { - if (!o.addedToEmployeeHandle && System - .currentTimeMillis() - order.createdTime < employeeTime) { - var qt = new QueueTask(order, TaskType.EMPLOYEE_DB, -1); - updateQueue(qt); - LOG.warn(ORDER_ID + ": Error in adding to employee db," - + " trying to queue task..", order.id); - } - }; - var r = new Retry<>(op, handleError, numOfRetries, retryDuration, - e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass())); - try { - r.perform(list, order); - } catch (Exception e1) { - LOG.error(DEFAULT_EXCEPTION_MESSAGE, e1); - } - }); + var t = + new Thread( + () -> { + Retry.Operation op = + l -> { + if (!l.isEmpty()) { + LOG.warn( + ORDER_ID + + ": Error in connecting to employee handle," + + " trying again..", + order.id); + throw l.remove(0); + } + if (!order.addedToEmployeeHandle) { + employeeDb.receiveRequest(order); + order.addedToEmployeeHandle = true; + LOG.info(ORDER_ID + ": Added order to employee database", order.id); + } + }; + Retry.HandleErrorIssue handleError = + (o, err) -> { + if (!o.addedToEmployeeHandle + && System.currentTimeMillis() - order.createdTime < employeeTime) { + var qt = new QueueTask(order, TaskType.EMPLOYEE_DB, -1); + updateQueue(qt); + LOG.warn( + ORDER_ID + + ": Error in adding to employee db," + + " trying to queue task..", + order.id); + } + }; + var r = + new Retry<>( + op, + handleError, + numOfRetries, + retryDuration, + e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass())); + try { + r.perform(list, order); + } catch (Exception e1) { + LOG.error(DEFAULT_EXCEPTION_MESSAGE, e1); + } + }); t.start(); } private void doTasksInQueue() throws IsEmptyException, InterruptedException { if (queueItems != 0) { - var qt = queue.peek(); //this should probably be cloned here - //this is why we have retry for doTasksInQueue + var qt = queue.peek(); // this should probably be cloned here + // this is why we have retry for doTasksInQueue LOG.trace(ORDER_ID + ": Started doing task of type {}", qt.order.id, qt.getType()); if (qt.isFirstAttempt()) { qt.setFirstAttemptTime(System.currentTimeMillis()); } if (System.currentTimeMillis() - qt.getFirstAttemptTime() >= queueTaskTime) { tryDequeue(); - LOG.trace(ORDER_ID + ": This queue task of type {}" - + " does not need to be done anymore (timeout), dequeue..", qt.order.id, qt.getType()); + LOG.trace( + ORDER_ID + + ": This queue task of type {}" + + " does not need to be done anymore (timeout), dequeue..", + qt.order.id, + qt.getType()); } else { switch (qt.taskType) { case PAYMENT -> doPaymentTask(qt); @@ -583,8 +704,7 @@ public class Commander { private void doEmployeeDbTask(QueueTask qt) { if (qt.order.addedToEmployeeHandle) { tryDequeue(); - LOG.trace(ORDER_ID + ": This employee handle task already done," - + " dequeue..", qt.order.id); + LOG.trace(ORDER_ID + ": This employee handle task already done," + " dequeue..", qt.order.id); } else { employeeHandleIssue(qt.order); LOG.debug(ORDER_ID + ": Trying to connect to employee handle..", qt.order.id); @@ -596,11 +716,12 @@ public class Commander { || qt.order.messageSent.equals(MessageSent.PAYMENT_SUCCESSFUL)) { tryDequeue(); LOG.trace(ORDER_ID + ": This messaging task already done, dequeue..", qt.order.id); - } else if (qt.messageType == 1 && (!qt.order.messageSent.equals(MessageSent.NONE_SENT) - || !qt.order.paid.equals(PaymentStatus.TRYING))) { + } else if (qt.messageType == 1 + && (!qt.order.messageSent.equals(MessageSent.NONE_SENT) + || !qt.order.paid.equals(PaymentStatus.TRYING))) { tryDequeue(); - LOG.trace(ORDER_ID + ": This messaging task does not need to be done," - + " dequeue..", qt.order.id); + LOG.trace( + ORDER_ID + ": This messaging task does not need to be done," + " dequeue..", qt.order.id); } else if (qt.messageType == 0) { sendPaymentFailureMessage(qt.order); LOG.debug(ORDER_ID + TRY_CONNECTING_MSG_SVC, qt.order.id); @@ -622,5 +743,4 @@ public class Commander { LOG.debug(ORDER_ID + ": Trying to connect to payment service..", qt.order.id); } } - -} \ No newline at end of file +} diff --git a/commander/src/main/java/com/iluwatar/commander/Database.java b/commander/src/main/java/com/iluwatar/commander/Database.java index e118ed3ad..a3e3da169 100644 --- a/commander/src/main/java/com/iluwatar/commander/Database.java +++ b/commander/src/main/java/com/iluwatar/commander/Database.java @@ -32,7 +32,6 @@ import com.iluwatar.commander.exceptions.DatabaseUnavailableException; * * @param T is the type of object being held by database. */ - public abstract class Database { public abstract T add(T obj) throws DatabaseUnavailableException; diff --git a/commander/src/main/java/com/iluwatar/commander/Order.java b/commander/src/main/java/com/iluwatar/commander/Order.java index 262aba6fe..b998a0297 100644 --- a/commander/src/main/java/com/iluwatar/commander/Order.java +++ b/commander/src/main/java/com/iluwatar/commander/Order.java @@ -28,11 +28,8 @@ import java.security.SecureRandom; import java.util.HashMap; import java.util.Map; -/** - * Order class holds details of the order. - */ - -public class Order { //can store all transactions ids also +/** Order class holds details of the order. */ +public class Order { // can store all transactions ids also enum PaymentStatus { NOT_DONE, @@ -56,8 +53,8 @@ public class Order { //can store all transactions ids also private static final String ALL_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; private static final Map USED_IDS = new HashMap<>(); PaymentStatus paid; - MessageSent messageSent; //to avoid sending error msg on page and text more than once - boolean addedToEmployeeHandle; //to avoid creating more to enqueue + MessageSent messageSent; // to avoid sending error msg on page and text more than once + boolean addedToEmployeeHandle; // to avoid creating more to enqueue Order(User user, String item, float price) { this.createdTime = System.currentTimeMillis(); @@ -85,5 +82,4 @@ public class Order { //can store all transactions ids also } return random.toString(); } - } diff --git a/commander/src/main/java/com/iluwatar/commander/Retry.java b/commander/src/main/java/com/iluwatar/commander/Retry.java index 716146682..661f47917 100644 --- a/commander/src/main/java/com/iluwatar/commander/Retry.java +++ b/commander/src/main/java/com/iluwatar/commander/Retry.java @@ -36,13 +36,9 @@ import java.util.function.Predicate; * * @param is the type of object passed into HandleErrorIssue as a parameter. */ - public class Retry { - /** - * Operation Interface will define method to be implemented. - */ - + /** Operation Interface will define method to be implemented. */ public interface Operation { void operation(List list) throws Exception; } @@ -52,7 +48,6 @@ public class Retry { * * @param is the type of object to be passed into the method as parameter. */ - public interface HandleErrorIssue { void handleIssue(T obj, Exception e); } @@ -67,8 +62,12 @@ public class Retry { private final Predicate test; private final List errors; - Retry(Operation op, HandleErrorIssue handleError, int maxAttempts, - long maxDelay, Predicate... ignoreTests) { + Retry( + Operation op, + HandleErrorIssue handleError, + int maxAttempts, + long maxDelay, + Predicate... ignoreTests) { this.op = op; this.handleError = handleError; this.maxAttempts = maxAttempts; @@ -82,9 +81,8 @@ public class Retry { * Performing the operation with retries. * * @param list is the exception list - * @param obj is the parameter to be passed into handleIsuue method + * @param obj is the parameter to be passed into handleIsuue method */ - public void perform(List list, T obj) { do { try { @@ -94,7 +92,7 @@ public class Retry { this.errors.add(e); if (this.attempts.incrementAndGet() >= this.maxAttempts || !this.test.test(e)) { this.handleError.handleIssue(obj, e); - return; //return here... don't go further + return; // return here... don't go further } try { long testDelay = @@ -102,10 +100,9 @@ public class Retry { long delay = Math.min(testDelay, this.maxDelay); Thread.sleep(delay); } catch (InterruptedException f) { - //ignore + // ignore } } } while (true); } - } diff --git a/commander/src/main/java/com/iluwatar/commander/RetryParams.java b/commander/src/main/java/com/iluwatar/commander/RetryParams.java index ee3bf537f..9988af8a4 100644 --- a/commander/src/main/java/com/iluwatar/commander/RetryParams.java +++ b/commander/src/main/java/com/iluwatar/commander/RetryParams.java @@ -26,9 +26,10 @@ package com.iluwatar.commander; /** * Record to hold the parameters related to retries. + * * @param numOfRetries number of retries * @param retryDuration retry duration */ public record RetryParams(int numOfRetries, long retryDuration) { public static final RetryParams DEFAULT = new RetryParams(3, 30000L); -} \ No newline at end of file +} diff --git a/commander/src/main/java/com/iluwatar/commander/Service.java b/commander/src/main/java/com/iluwatar/commander/Service.java index e3177fc30..06aa9a3ce 100644 --- a/commander/src/main/java/com/iluwatar/commander/Service.java +++ b/commander/src/main/java/com/iluwatar/commander/Service.java @@ -38,7 +38,6 @@ import java.util.List; * for the transactions/requests, which are then sent back. These could be stored by the {@link * Commander} class in a separate database for reference (though we are not doing that here). */ - public abstract class Service { protected final Database database; diff --git a/commander/src/main/java/com/iluwatar/commander/TimeLimits.java b/commander/src/main/java/com/iluwatar/commander/TimeLimits.java index bdb7caaf4..9051fdf29 100644 --- a/commander/src/main/java/com/iluwatar/commander/TimeLimits.java +++ b/commander/src/main/java/com/iluwatar/commander/TimeLimits.java @@ -25,16 +25,17 @@ package com.iluwatar.commander; /** - * Record to hold parameters related to time limit - * for various tasks. + * Record to hold parameters related to time limit for various tasks. + * * @param queueTime time limit for queue * @param queueTaskTime time limit for queuing task * @param paymentTime time limit for payment error message * @param messageTime time limit for message time order * @param employeeTime time limit for employee handle time */ -public record TimeLimits(long queueTime, long queueTaskTime, long paymentTime, - long messageTime, long employeeTime) { +public record TimeLimits( + long queueTime, long queueTaskTime, long paymentTime, long messageTime, long employeeTime) { - public static final TimeLimits DEFAULT = new TimeLimits(240000L, 60000L, 120000L, 150000L, 240000L); -} \ No newline at end of file + public static final TimeLimits DEFAULT = + new TimeLimits(240000L, 60000L, 120000L, 150000L, 240000L); +} diff --git a/commander/src/main/java/com/iluwatar/commander/User.java b/commander/src/main/java/com/iluwatar/commander/User.java index b6989e1d9..e32d0024a 100644 --- a/commander/src/main/java/com/iluwatar/commander/User.java +++ b/commander/src/main/java/com/iluwatar/commander/User.java @@ -26,9 +26,7 @@ package com.iluwatar.commander; import lombok.AllArgsConstructor; -/** - * User class contains details of user who places order. - */ +/** User class contains details of user who places order. */ @AllArgsConstructor public class User { String name; diff --git a/commander/src/main/java/com/iluwatar/commander/employeehandle/EmployeeDatabase.java b/commander/src/main/java/com/iluwatar/commander/employeehandle/EmployeeDatabase.java index c584d2ebd..a139ab323 100644 --- a/commander/src/main/java/com/iluwatar/commander/employeehandle/EmployeeDatabase.java +++ b/commander/src/main/java/com/iluwatar/commander/employeehandle/EmployeeDatabase.java @@ -30,10 +30,7 @@ import com.iluwatar.commander.exceptions.DatabaseUnavailableException; import java.util.HashMap; import java.util.Map; -/** - * The Employee Database is where orders which have encountered some issue(s) are added. - */ - +/** The Employee Database is where orders which have encountered some issue(s) are added. */ public class EmployeeDatabase extends Database { private final Map data = new HashMap<>(); diff --git a/commander/src/main/java/com/iluwatar/commander/employeehandle/EmployeeHandle.java b/commander/src/main/java/com/iluwatar/commander/employeehandle/EmployeeHandle.java index 441ce920f..745b71d90 100644 --- a/commander/src/main/java/com/iluwatar/commander/employeehandle/EmployeeHandle.java +++ b/commander/src/main/java/com/iluwatar/commander/employeehandle/EmployeeHandle.java @@ -32,7 +32,6 @@ import com.iluwatar.commander.exceptions.DatabaseUnavailableException; * The EmployeeHandle class is the middle-man between {@link com.iluwatar.commander.Commander} and * {@link EmployeeDatabase}. */ - public class EmployeeHandle extends Service { public EmployeeHandle(EmployeeDatabase db, Exception... exc) { @@ -47,9 +46,8 @@ public class EmployeeHandle extends Service { var o = (Order) parameters[0]; if (database.get(o.id) == null) { database.add(o); - return o.id; //true rcvd - change addedToEmployeeHandle to true else don't do anything + return o.id; // true rcvd - change addedToEmployeeHandle to true else don't do anything } return null; } - } diff --git a/commander/src/main/java/com/iluwatar/commander/exceptions/DatabaseUnavailableException.java b/commander/src/main/java/com/iluwatar/commander/exceptions/DatabaseUnavailableException.java index 5d368180c..51f27832f 100644 --- a/commander/src/main/java/com/iluwatar/commander/exceptions/DatabaseUnavailableException.java +++ b/commander/src/main/java/com/iluwatar/commander/exceptions/DatabaseUnavailableException.java @@ -28,7 +28,6 @@ package com.iluwatar.commander.exceptions; * DatabaseUnavailableException is thrown when database is unavailable and nothing can be added or * retrieved. */ - public class DatabaseUnavailableException extends Exception { private static final long serialVersionUID = 2459603L; } diff --git a/commander/src/main/java/com/iluwatar/commander/exceptions/IsEmptyException.java b/commander/src/main/java/com/iluwatar/commander/exceptions/IsEmptyException.java index 3ab6b22b3..5cb06214f 100644 --- a/commander/src/main/java/com/iluwatar/commander/exceptions/IsEmptyException.java +++ b/commander/src/main/java/com/iluwatar/commander/exceptions/IsEmptyException.java @@ -24,10 +24,7 @@ */ package com.iluwatar.commander.exceptions; -/** - * IsEmptyException is thrown when it is attempted to dequeue from an empty queue. - */ - +/** IsEmptyException is thrown when it is attempted to dequeue from an empty queue. */ public class IsEmptyException extends Exception { private static final long serialVersionUID = 123546L; } diff --git a/commander/src/main/java/com/iluwatar/commander/exceptions/ItemUnavailableException.java b/commander/src/main/java/com/iluwatar/commander/exceptions/ItemUnavailableException.java index 4ff39543e..9d6f2849f 100644 --- a/commander/src/main/java/com/iluwatar/commander/exceptions/ItemUnavailableException.java +++ b/commander/src/main/java/com/iluwatar/commander/exceptions/ItemUnavailableException.java @@ -24,10 +24,7 @@ */ package com.iluwatar.commander.exceptions; -/** - * ItemUnavailableException is thrown when item is not available for shipping. - */ - +/** ItemUnavailableException is thrown when item is not available for shipping. */ public class ItemUnavailableException extends Exception { private static final long serialVersionUID = 575940L; } diff --git a/commander/src/main/java/com/iluwatar/commander/exceptions/PaymentDetailsErrorException.java b/commander/src/main/java/com/iluwatar/commander/exceptions/PaymentDetailsErrorException.java index 844dab389..1406b43de 100644 --- a/commander/src/main/java/com/iluwatar/commander/exceptions/PaymentDetailsErrorException.java +++ b/commander/src/main/java/com/iluwatar/commander/exceptions/PaymentDetailsErrorException.java @@ -28,7 +28,6 @@ package com.iluwatar.commander.exceptions; * PaymentDetailsErrorException is thrown when the details entered are incorrect or payment cannot * be made with the details given. */ - public class PaymentDetailsErrorException extends Exception { private static final long serialVersionUID = 867203L; } diff --git a/commander/src/main/java/com/iluwatar/commander/exceptions/ShippingNotPossibleException.java b/commander/src/main/java/com/iluwatar/commander/exceptions/ShippingNotPossibleException.java index ac6267dfc..51036aaea 100644 --- a/commander/src/main/java/com/iluwatar/commander/exceptions/ShippingNotPossibleException.java +++ b/commander/src/main/java/com/iluwatar/commander/exceptions/ShippingNotPossibleException.java @@ -28,7 +28,6 @@ package com.iluwatar.commander.exceptions; * ShippingNotPossibleException is thrown when the address entered cannot be shipped to by service * currently for some reason. */ - public class ShippingNotPossibleException extends Exception { private static final long serialVersionUID = 342055L; } diff --git a/commander/src/main/java/com/iluwatar/commander/messagingservice/MessagingDatabase.java b/commander/src/main/java/com/iluwatar/commander/messagingservice/MessagingDatabase.java index e4a000f1c..b6af7d7b5 100644 --- a/commander/src/main/java/com/iluwatar/commander/messagingservice/MessagingDatabase.java +++ b/commander/src/main/java/com/iluwatar/commander/messagingservice/MessagingDatabase.java @@ -29,10 +29,7 @@ import com.iluwatar.commander.messagingservice.MessagingService.MessageRequest; import java.util.Hashtable; import java.util.Map; -/** - * The MessagingDatabase is where the MessageRequest is added. - */ - +/** The MessagingDatabase is where the MessageRequest is added. */ public class MessagingDatabase extends Database { private final Map data = new Hashtable<>(); @@ -45,5 +42,4 @@ public class MessagingDatabase extends Database { public MessageRequest get(String requestId) { return data.get(requestId); } - } diff --git a/commander/src/main/java/com/iluwatar/commander/messagingservice/MessagingService.java b/commander/src/main/java/com/iluwatar/commander/messagingservice/MessagingService.java index e00bde499..44b58e5e0 100644 --- a/commander/src/main/java/com/iluwatar/commander/messagingservice/MessagingService.java +++ b/commander/src/main/java/com/iluwatar/commander/messagingservice/MessagingService.java @@ -26,7 +26,6 @@ package com.iluwatar.commander.messagingservice; import com.iluwatar.commander.Service; import com.iluwatar.commander.exceptions.DatabaseUnavailableException; -import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; /** @@ -34,7 +33,6 @@ import lombok.extern.slf4j.Slf4j; * In case an error is encountered in payment and this service is found to be unavailable, the order * is added to the {@link com.iluwatar.commander.employeehandle.EmployeeDatabase}. */ - @Slf4j public class MessagingService extends Service { @@ -50,9 +48,7 @@ public class MessagingService extends Service { super(db, exc); } - /** - * Public method which will receive request from {@link com.iluwatar.commander.Commander}. - */ + /** Public method which will receive request from {@link com.iluwatar.commander.Commander}. */ public String receiveRequest(Object... parameters) throws DatabaseUnavailableException { var messageToSend = (int) parameters[0]; var id = generateId(); @@ -61,7 +57,7 @@ public class MessagingService extends Service { msg = MessageToSend.PAYMENT_FAIL; } else if (messageToSend == 1) { msg = MessageToSend.PAYMENT_TRYING; - } else { //messageToSend == 2 + } else { // messageToSend == 2 msg = MessageToSend.PAYMENT_SUCCESSFUL; } var req = new MessageRequest(id, msg); @@ -70,8 +66,8 @@ public class MessagingService extends Service { protected String updateDb(Object... parameters) throws DatabaseUnavailableException { var req = (MessageRequest) parameters[0]; - if (this.database.get(req.reqId) == null) { //idempotence, in case db fails here - database.add(req); //if successful: + if (this.database.get(req.reqId) == null) { // idempotence, in case db fails here + database.add(req); // if successful: LOGGER.info(sendMessage(req.msg)); return req.reqId; } diff --git a/commander/src/main/java/com/iluwatar/commander/paymentservice/PaymentDatabase.java b/commander/src/main/java/com/iluwatar/commander/paymentservice/PaymentDatabase.java index 3c2a6129b..354c1c958 100644 --- a/commander/src/main/java/com/iluwatar/commander/paymentservice/PaymentDatabase.java +++ b/commander/src/main/java/com/iluwatar/commander/paymentservice/PaymentDatabase.java @@ -29,12 +29,10 @@ import com.iluwatar.commander.paymentservice.PaymentService.PaymentRequest; import java.util.Hashtable; import java.util.Map; -/** - * PaymentDatabase is where the PaymentRequest is added, along with details. - */ +/** PaymentDatabase is where the PaymentRequest is added, along with details. */ public class PaymentDatabase extends Database { - //0-fail, 1-error, 2-success + // 0-fail, 1-error, 2-success private final Map data = new Hashtable<>(); @Override @@ -46,5 +44,4 @@ public class PaymentDatabase extends Database { public PaymentRequest get(String requestId) { return data.get(requestId); } - } diff --git a/commander/src/main/java/com/iluwatar/commander/paymentservice/PaymentService.java b/commander/src/main/java/com/iluwatar/commander/paymentservice/PaymentService.java index 28fda2eb2..953c46165 100644 --- a/commander/src/main/java/com/iluwatar/commander/paymentservice/PaymentService.java +++ b/commander/src/main/java/com/iluwatar/commander/paymentservice/PaymentService.java @@ -32,7 +32,6 @@ import lombok.RequiredArgsConstructor; * The PaymentService class receives request from the {@link com.iluwatar.commander.Commander} and * adds to the {@link PaymentDatabase}. */ - public class PaymentService extends Service { @RequiredArgsConstructor @@ -46,12 +45,9 @@ public class PaymentService extends Service { super(db, exc); } - /** - * Public method which will receive request from {@link com.iluwatar.commander.Commander}. - */ - + /** Public method which will receive request from {@link com.iluwatar.commander.Commander}. */ public String receiveRequest(Object... parameters) throws DatabaseUnavailableException { - //it could also be sending an userid, payment details here or something, not added here + // it could also be sending an userid, payment details here or something, not added here var id = generateId(); var req = new PaymentRequest(id, (float) parameters[0]); return updateDb(req); diff --git a/commander/src/main/java/com/iluwatar/commander/queue/QueueDatabase.java b/commander/src/main/java/com/iluwatar/commander/queue/QueueDatabase.java index b8189e6f0..41b54a276 100644 --- a/commander/src/main/java/com/iluwatar/commander/queue/QueueDatabase.java +++ b/commander/src/main/java/com/iluwatar/commander/queue/QueueDatabase.java @@ -29,10 +29,7 @@ import com.iluwatar.commander.exceptions.IsEmptyException; import java.util.ArrayList; import java.util.List; -/** - * QueueDatabase id where the instructions to be implemented are queued. - */ - +/** QueueDatabase id where the instructions to be implemented are queued. */ public class QueueDatabase extends Database { private final Queue data; @@ -47,16 +44,15 @@ public class QueueDatabase extends Database { public QueueTask add(QueueTask t) { data.enqueue(t); return t; - //even if same thing queued twice, it is taken care of in other dbs + // even if same thing queued twice, it is taken care of in other dbs } /** * peek method returns object at front without removing it from queue. * * @return object at front of queue - * @throws IsEmptyException if queue is empty + * @throws IsEmptyException if queue is empty */ - public QueueTask peek() throws IsEmptyException { return this.data.peek(); } @@ -65,9 +61,8 @@ public class QueueDatabase extends Database { * dequeue method removes the object at front and returns it. * * @return object at front of queue - * @throws IsEmptyException if queue is empty + * @throws IsEmptyException if queue is empty */ - public QueueTask dequeue() throws IsEmptyException { return this.data.dequeue(); } @@ -76,5 +71,4 @@ public class QueueDatabase extends Database { public QueueTask get(String taskId) { return null; } - } diff --git a/commander/src/main/java/com/iluwatar/commander/queue/QueueTask.java b/commander/src/main/java/com/iluwatar/commander/queue/QueueTask.java index e0194508d..aedf55a9e 100644 --- a/commander/src/main/java/com/iluwatar/commander/queue/QueueTask.java +++ b/commander/src/main/java/com/iluwatar/commander/queue/QueueTask.java @@ -29,15 +29,11 @@ import lombok.Getter; import lombok.RequiredArgsConstructor; import lombok.Setter; -/** - * QueueTask object is the object enqueued in queue. - */ +/** QueueTask object is the object enqueued in queue. */ @RequiredArgsConstructor public class QueueTask { - /** - * TaskType is the type of task to be done. - */ + /** TaskType is the type of task to be done. */ public enum TaskType { MESSAGING, PAYMENT, @@ -46,13 +42,11 @@ public class QueueTask { public final Order order; public final TaskType taskType; - public final int messageType; //0-fail, 1-error, 2-success - + public final int messageType; // 0-fail, 1-error, 2-success + /*we could have varargs Object instead to pass in any parameter instead of just message type but keeping it simple here*/ - @Getter - @Setter - private long firstAttemptTime = -1L; //when first time attempt made to do task + @Getter @Setter private long firstAttemptTime = -1L; // when first time attempt made to do task /** * getType method. @@ -76,4 +70,4 @@ public class QueueTask { public boolean isFirstAttempt() { return this.firstAttemptTime == -1L; } -} \ No newline at end of file +} diff --git a/commander/src/main/java/com/iluwatar/commander/shippingservice/ShippingDatabase.java b/commander/src/main/java/com/iluwatar/commander/shippingservice/ShippingDatabase.java index f1a11d591..390683427 100644 --- a/commander/src/main/java/com/iluwatar/commander/shippingservice/ShippingDatabase.java +++ b/commander/src/main/java/com/iluwatar/commander/shippingservice/ShippingDatabase.java @@ -29,10 +29,7 @@ import com.iluwatar.commander.shippingservice.ShippingService.ShippingRequest; import java.util.Hashtable; import java.util.Map; -/** - * ShippingDatabase is where the ShippingRequest objects are added. - */ - +/** ShippingDatabase is where the ShippingRequest objects are added. */ public class ShippingDatabase extends Database { private final Map data = new Hashtable<>(); @@ -45,5 +42,4 @@ public class ShippingDatabase extends Database { public ShippingRequest get(String trasnactionId) { return data.get(trasnactionId); } - } diff --git a/commander/src/main/java/com/iluwatar/commander/shippingservice/ShippingService.java b/commander/src/main/java/com/iluwatar/commander/shippingservice/ShippingService.java index 8144fde90..cc97159b7 100644 --- a/commander/src/main/java/com/iluwatar/commander/shippingservice/ShippingService.java +++ b/commander/src/main/java/com/iluwatar/commander/shippingservice/ShippingService.java @@ -32,7 +32,6 @@ import lombok.AllArgsConstructor; * ShippingService class receives request from {@link com.iluwatar.commander.Commander} class and * adds it to the {@link ShippingDatabase}. */ - public class ShippingService extends Service { @AllArgsConstructor @@ -46,10 +45,7 @@ public class ShippingService extends Service { super(db, exc); } - /** - * Public method which will receive request from {@link com.iluwatar.commander.Commander}. - */ - + /** Public method which will receive request from {@link com.iluwatar.commander.Commander}. */ public String receiveRequest(Object... parameters) throws DatabaseUnavailableException { var id = generateId(); var item = (String) parameters[0]; diff --git a/commander/src/test/java/com/iluwatar/commander/CommanderTest.java b/commander/src/test/java/com/iluwatar/commander/CommanderTest.java index 87d065a30..664268965 100644 --- a/commander/src/test/java/com/iluwatar/commander/CommanderTest.java +++ b/commander/src/test/java/com/iluwatar/commander/CommanderTest.java @@ -24,6 +24,8 @@ */ package com.iluwatar.commander; +import static org.junit.jupiter.api.Assertions.assertFalse; + import com.iluwatar.commander.employeehandle.EmployeeDatabase; import com.iluwatar.commander.employeehandle.EmployeeHandle; import com.iluwatar.commander.exceptions.DatabaseUnavailableException; @@ -37,589 +39,645 @@ import com.iluwatar.commander.paymentservice.PaymentService; import com.iluwatar.commander.queue.QueueDatabase; import com.iluwatar.commander.shippingservice.ShippingDatabase; import com.iluwatar.commander.shippingservice.ShippingService; -import org.junit.jupiter.api.Test; -import org.junit.platform.commons.util.StringUtils; import java.util.ArrayList; import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertFalse; +import org.junit.jupiter.api.Test; +import org.junit.platform.commons.util.StringUtils; class CommanderTest { - private final RetryParams retryParams = new RetryParams(1, 1_000L); + private final RetryParams retryParams = new RetryParams(1, 1_000L); - private final TimeLimits timeLimits = new TimeLimits(1L, 1000L, 6000L, 5000L, 2000L); + private final TimeLimits timeLimits = new TimeLimits(1L, 1000L, 6000L, 5000L, 2000L); - private static final List exceptionList = new ArrayList<>(); + private static final List exceptionList = new ArrayList<>(); - private static final AppAllCases appAllCases = new AppAllCases(); + private static final AppAllCases appAllCases = new AppAllCases(); - static { - exceptionList.add(new DatabaseUnavailableException()); - exceptionList.add(new ShippingNotPossibleException()); - exceptionList.add(new ItemUnavailableException()); - exceptionList.add(new PaymentDetailsErrorException()); - exceptionList.add(new IllegalStateException()); + static { + exceptionList.add(new DatabaseUnavailableException()); + exceptionList.add(new ShippingNotPossibleException()); + exceptionList.add(new ItemUnavailableException()); + exceptionList.add(new PaymentDetailsErrorException()); + exceptionList.add(new IllegalStateException()); + } + + private Commander buildCommanderObject() { + return buildCommanderObject(false); + } + + private Commander buildCommanderObject(boolean nonPaymentException) { + PaymentService paymentService = + new PaymentService( + new PaymentDatabase(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException()); + + ShippingService shippingService; + MessagingService messagingService; + if (nonPaymentException) { + shippingService = + new ShippingService(new ShippingDatabase(), new DatabaseUnavailableException()); + messagingService = + new MessagingService(new MessagingDatabase(), new DatabaseUnavailableException()); + + } else { + shippingService = + new ShippingService(new ShippingDatabase(), new DatabaseUnavailableException()); + messagingService = + new MessagingService(new MessagingDatabase(), new DatabaseUnavailableException()); + } + var employeeHandle = + new EmployeeHandle( + new EmployeeDatabase(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException()); + var qdb = + new QueueDatabase( + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException()); + return new Commander( + employeeHandle, + paymentService, + shippingService, + messagingService, + qdb, + retryParams, + timeLimits); + } + + private Commander buildCommanderObjectVanilla() { + PaymentService paymentService = + new PaymentService( + new PaymentDatabase(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException()); + var shippingService = new ShippingService(new ShippingDatabase()); + var messagingService = new MessagingService(new MessagingDatabase()); + var employeeHandle = + new EmployeeHandle( + new EmployeeDatabase(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException()); + var qdb = + new QueueDatabase( + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException(), + new DatabaseUnavailableException()); + return new Commander( + employeeHandle, + paymentService, + shippingService, + messagingService, + qdb, + retryParams, + timeLimits); + } + + private Commander buildCommanderObjectUnknownException() { + PaymentService paymentService = + new PaymentService(new PaymentDatabase(), new IllegalStateException()); + var shippingService = new ShippingService(new ShippingDatabase()); + var messagingService = new MessagingService(new MessagingDatabase()); + var employeeHandle = new EmployeeHandle(new EmployeeDatabase(), new IllegalStateException()); + var qdb = new QueueDatabase(new DatabaseUnavailableException(), new IllegalStateException()); + return new Commander( + employeeHandle, + paymentService, + shippingService, + messagingService, + qdb, + retryParams, + timeLimits); + } + + private Commander buildCommanderObjectNoPaymentException1() { + PaymentService paymentService = new PaymentService(new PaymentDatabase()); + var shippingService = new ShippingService(new ShippingDatabase()); + var messagingService = new MessagingService(new MessagingDatabase()); + var employeeHandle = new EmployeeHandle(new EmployeeDatabase(), new IllegalStateException()); + var qdb = new QueueDatabase(new DatabaseUnavailableException(), new IllegalStateException()); + return new Commander( + employeeHandle, + paymentService, + shippingService, + messagingService, + qdb, + retryParams, + timeLimits); + } + + private Commander buildCommanderObjectNoPaymentException2() { + PaymentService paymentService = new PaymentService(new PaymentDatabase()); + var shippingService = new ShippingService(new ShippingDatabase()); + var messagingService = + new MessagingService(new MessagingDatabase(), new IllegalStateException()); + var employeeHandle = new EmployeeHandle(new EmployeeDatabase(), new IllegalStateException()); + var qdb = new QueueDatabase(new DatabaseUnavailableException(), new IllegalStateException()); + return new Commander( + employeeHandle, + paymentService, + shippingService, + messagingService, + qdb, + retryParams, + timeLimits); + } + + private Commander buildCommanderObjectNoPaymentException3() { + PaymentService paymentService = new PaymentService(new PaymentDatabase()); + var shippingService = new ShippingService(new ShippingDatabase()); + var messagingService = + new MessagingService(new MessagingDatabase(), new DatabaseUnavailableException()); + var employeeHandle = new EmployeeHandle(new EmployeeDatabase(), new IllegalStateException()); + var qdb = new QueueDatabase(new DatabaseUnavailableException(), new IllegalStateException()); + return new Commander( + employeeHandle, + paymentService, + shippingService, + messagingService, + qdb, + retryParams, + timeLimits); + } + + private Commander buildCommanderObjectWithDB() { + return buildCommanderObjectWithoutDB(false, false, new IllegalStateException()); + } + + private Commander buildCommanderObjectWithDB( + boolean includeException, boolean includeDBException, Exception e) { + var l = includeDBException ? new DatabaseUnavailableException() : e; + PaymentService paymentService; + ShippingService shippingService; + MessagingService messagingService; + EmployeeHandle employeeHandle; + if (includeException) { + paymentService = new PaymentService(new PaymentDatabase(), l); + shippingService = new ShippingService(new ShippingDatabase(), l); + messagingService = new MessagingService(new MessagingDatabase(), l); + employeeHandle = new EmployeeHandle(new EmployeeDatabase(), l); + } else { + paymentService = new PaymentService(null); + shippingService = new ShippingService(null); + messagingService = new MessagingService(null); + employeeHandle = new EmployeeHandle(null); } - private Commander buildCommanderObject() { - return buildCommanderObject(false); + return new Commander( + employeeHandle, + paymentService, + shippingService, + messagingService, + null, + retryParams, + timeLimits); + } + + private Commander buildCommanderObjectWithoutDB() { + return buildCommanderObjectWithoutDB(false, false, new IllegalStateException()); + } + + private Commander buildCommanderObjectWithoutDB( + boolean includeException, boolean includeDBException, Exception e) { + var l = includeDBException ? new DatabaseUnavailableException() : e; + PaymentService paymentService; + ShippingService shippingService; + MessagingService messagingService; + EmployeeHandle employeeHandle; + if (includeException) { + paymentService = new PaymentService(null, l); + shippingService = new ShippingService(null, l); + messagingService = new MessagingService(null, l); + employeeHandle = new EmployeeHandle(null, l); + } else { + paymentService = new PaymentService(null); + shippingService = new ShippingService(null); + messagingService = new MessagingService(null); + employeeHandle = new EmployeeHandle(null); } - private Commander buildCommanderObject(boolean nonPaymentException) { - PaymentService paymentService = new PaymentService - (new PaymentDatabase(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException()); + return new Commander( + employeeHandle, + paymentService, + shippingService, + messagingService, + null, + retryParams, + timeLimits); + } - ShippingService shippingService; - MessagingService messagingService; - if (nonPaymentException) { - shippingService = new ShippingService(new ShippingDatabase(), new DatabaseUnavailableException()); - messagingService = new MessagingService(new MessagingDatabase(), new DatabaseUnavailableException()); - - } else { - shippingService = new ShippingService(new ShippingDatabase(), new DatabaseUnavailableException()); - messagingService = new MessagingService(new MessagingDatabase(), new DatabaseUnavailableException()); - - } - var employeeHandle = new EmployeeHandle - (new EmployeeDatabase(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException()); - var qdb = new QueueDatabase - (new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException()); - return new Commander(employeeHandle, paymentService, shippingService, - messagingService, qdb, retryParams, timeLimits); + @Test + void testPlaceOrderVanilla() { + long paymentTime = timeLimits.paymentTime(); + long queueTaskTime = timeLimits.queueTaskTime(); + for (double d = 0.1; d < 2; d = d + 0.1) { + paymentTime *= d; + queueTaskTime *= d; + Commander c = buildCommanderObjectVanilla(); + var order = new Order(new User("K", "J"), "pen", 1f); + for (Order.MessageSent ms : Order.MessageSent.values()) { + c.placeOrder(order); + assertFalse(StringUtils.isBlank(order.id)); + } } + } - private Commander buildCommanderObjectVanilla() { - PaymentService paymentService = new PaymentService - (new PaymentDatabase(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException()); - var shippingService = new ShippingService(new ShippingDatabase()); - var messagingService = new MessagingService(new MessagingDatabase()); - var employeeHandle = new EmployeeHandle - (new EmployeeDatabase(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException()); - var qdb = new QueueDatabase - (new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException(), - new DatabaseUnavailableException(), new DatabaseUnavailableException()); - return new Commander(employeeHandle, paymentService, shippingService, - messagingService, qdb, retryParams, timeLimits); + @Test + void testPlaceOrder() throws Exception { + long paymentTime = timeLimits.paymentTime(); + long queueTaskTime = timeLimits.queueTaskTime(); + for (double d = 0.1; d < 2; d = d + 0.1) { + paymentTime *= d; + queueTaskTime *= d; + Commander c = buildCommanderObject(true); + var order = new Order(new User("K", "J"), "pen", 1f); + for (Order.MessageSent ms : Order.MessageSent.values()) { + c.placeOrder(order); + assertFalse(StringUtils.isBlank(order.id)); + } } + } - private Commander buildCommanderObjectUnknownException() { - PaymentService paymentService = new PaymentService - (new PaymentDatabase(), new IllegalStateException()); - var shippingService = new ShippingService(new ShippingDatabase()); - var messagingService = new MessagingService(new MessagingDatabase()); - var employeeHandle = new EmployeeHandle - (new EmployeeDatabase(), new IllegalStateException()); - var qdb = new QueueDatabase - (new DatabaseUnavailableException(), new IllegalStateException()); - return new Commander(employeeHandle, paymentService, shippingService, - messagingService, qdb, retryParams, timeLimits); + @Test + void testPlaceOrder2() throws Exception { + long paymentTime = timeLimits.paymentTime(); + long queueTaskTime = timeLimits.queueTaskTime(); + for (double d = 0.1; d < 2; d = d + 0.1) { + paymentTime *= d; + queueTaskTime *= d; + Commander c = buildCommanderObject(false); + var order = new Order(new User("K", "J"), "pen", 1f); + for (Order.MessageSent ms : Order.MessageSent.values()) { + c.placeOrder(order); + assertFalse(StringUtils.isBlank(order.id)); + } } + } - private Commander buildCommanderObjectNoPaymentException1() { - PaymentService paymentService = new PaymentService - (new PaymentDatabase()); - var shippingService = new ShippingService(new ShippingDatabase()); - var messagingService = new MessagingService(new MessagingDatabase()); - var employeeHandle = new EmployeeHandle - (new EmployeeDatabase(), new IllegalStateException()); - var qdb = new QueueDatabase - (new DatabaseUnavailableException(), new IllegalStateException()); - return new Commander(employeeHandle, paymentService, shippingService, - messagingService, qdb, retryParams, timeLimits); + @Test + void testPlaceOrderNoException1() throws Exception { + long paymentTime = timeLimits.paymentTime(); + long queueTaskTime = timeLimits.queueTaskTime(); + for (double d = 0.1; d < 2; d = d + 0.1) { + paymentTime *= d; + queueTaskTime *= d; + Commander c = buildCommanderObjectNoPaymentException1(); + var order = new Order(new User("K", "J"), "pen", 1f); + for (Order.MessageSent ms : Order.MessageSent.values()) { + c.placeOrder(order); + assertFalse(StringUtils.isBlank(order.id)); + } } + } - private Commander buildCommanderObjectNoPaymentException2() { - PaymentService paymentService = new PaymentService - (new PaymentDatabase()); - var shippingService = new ShippingService(new ShippingDatabase()); - var messagingService = new MessagingService(new MessagingDatabase(), new IllegalStateException()); - var employeeHandle = new EmployeeHandle - (new EmployeeDatabase(), new IllegalStateException()); - var qdb = new QueueDatabase - (new DatabaseUnavailableException(), new IllegalStateException()); - return new Commander(employeeHandle, paymentService, shippingService, - messagingService, qdb, retryParams, timeLimits); + @Test + void testPlaceOrderNoException2() throws Exception { + long paymentTime = timeLimits.paymentTime(); + long queueTaskTime = timeLimits.queueTaskTime(); + for (double d = 0.1; d < 2; d = d + 0.1) { + paymentTime *= d; + queueTaskTime *= d; + Commander c = buildCommanderObjectNoPaymentException2(); + var order = new Order(new User("K", "J"), "pen", 1f); + for (Order.MessageSent ms : Order.MessageSent.values()) { + c.placeOrder(order); + assertFalse(StringUtils.isBlank(order.id)); + } } + } - private Commander buildCommanderObjectNoPaymentException3() { - PaymentService paymentService = new PaymentService - (new PaymentDatabase()); - var shippingService = new ShippingService(new ShippingDatabase()); - var messagingService = new MessagingService(new MessagingDatabase(), new DatabaseUnavailableException()); - var employeeHandle = new EmployeeHandle - (new EmployeeDatabase(), new IllegalStateException()); - var qdb = new QueueDatabase - (new DatabaseUnavailableException(), new IllegalStateException()); - return new Commander(employeeHandle, paymentService, shippingService, - messagingService, qdb, retryParams, timeLimits); + @Test + void testPlaceOrderNoException3() throws Exception { + long paymentTime = timeLimits.paymentTime(); + long queueTaskTime = timeLimits.queueTaskTime(); + for (double d = 0.1; d < 2; d = d + 0.1) { + paymentTime *= d; + queueTaskTime *= d; + Commander c = buildCommanderObjectNoPaymentException3(); + var order = new Order(new User("K", "J"), "pen", 1f); + for (Order.MessageSent ms : Order.MessageSent.values()) { + c.placeOrder(order); + assertFalse(StringUtils.isBlank(order.id)); + } } + } - private Commander buildCommanderObjectWithDB() { - return buildCommanderObjectWithoutDB(false, false, new IllegalStateException()); + @Test + void testPlaceOrderNoException4() throws Exception { + long paymentTime = timeLimits.paymentTime(); + long queueTaskTime = timeLimits.queueTaskTime(); + for (double d = 0.1; d < 2; d = d + 0.1) { + paymentTime *= d; + queueTaskTime *= d; + Commander c = buildCommanderObjectNoPaymentException3(); + var order = new Order(new User("K", "J"), "pen", 1f); + for (Order.MessageSent ms : Order.MessageSent.values()) { + c.placeOrder(order); + c.placeOrder(order); + c.placeOrder(order); + assertFalse(StringUtils.isBlank(order.id)); + } } + } - private Commander buildCommanderObjectWithDB(boolean includeException, boolean includeDBException, Exception e) { - var l = includeDBException ? new DatabaseUnavailableException() : e; - PaymentService paymentService; - ShippingService shippingService; - MessagingService messagingService; - EmployeeHandle employeeHandle; - if (includeException) { - paymentService = new PaymentService - (new PaymentDatabase(), l); - shippingService = new ShippingService(new ShippingDatabase(), l); - messagingService = new MessagingService(new MessagingDatabase(), l); - employeeHandle = new EmployeeHandle - (new EmployeeDatabase(), l); - } else { - paymentService = new PaymentService - (null); - shippingService = new ShippingService(null); - messagingService = new MessagingService(null); - employeeHandle = new EmployeeHandle - (null); + @Test + void testPlaceOrderUnknownException() throws Exception { + long paymentTime = timeLimits.paymentTime(); + long queueTaskTime = timeLimits.queueTaskTime(); + long messageTime = timeLimits.messageTime(); + long employeeTime = timeLimits.employeeTime(); + long queueTime = timeLimits.queueTime(); + for (double d = 0.1; d < 2; d = d + 0.1) { + paymentTime *= d; + queueTaskTime *= d; + messageTime *= d; + employeeTime *= d; + queueTime *= d; + Commander c = buildCommanderObjectUnknownException(); + var order = new Order(new User("K", "J"), "pen", 1f); + for (Order.MessageSent ms : Order.MessageSent.values()) { + c.placeOrder(order); + assertFalse(StringUtils.isBlank(order.id)); + } + } + } + + @Test + void testPlaceOrderShortDuration() throws Exception { + long paymentTime = timeLimits.paymentTime(); + long queueTaskTime = timeLimits.queueTaskTime(); + long messageTime = timeLimits.messageTime(); + long employeeTime = timeLimits.employeeTime(); + long queueTime = timeLimits.queueTime(); + for (double d = 0.1; d < 2; d = d + 0.1) { + paymentTime *= d; + queueTaskTime *= d; + messageTime *= d; + employeeTime *= d; + queueTime *= d; + Commander c = buildCommanderObject(true); + var order = new Order(new User("K", "J"), "pen", 1f); + for (Order.MessageSent ms : Order.MessageSent.values()) { + c.placeOrder(order); + assertFalse(StringUtils.isBlank(order.id)); + } + } + } + + @Test + void testPlaceOrderShortDuration2() throws Exception { + long paymentTime = timeLimits.paymentTime(); + long queueTaskTime = timeLimits.queueTaskTime(); + long messageTime = timeLimits.messageTime(); + long employeeTime = timeLimits.employeeTime(); + long queueTime = timeLimits.queueTime(); + for (double d = 0.1; d < 2; d = d + 0.1) { + paymentTime *= d; + queueTaskTime *= d; + messageTime *= d; + employeeTime *= d; + queueTime *= d; + Commander c = buildCommanderObject(false); + var order = new Order(new User("K", "J"), "pen", 1f); + for (Order.MessageSent ms : Order.MessageSent.values()) { + c.placeOrder(order); + assertFalse(StringUtils.isBlank(order.id)); + } + } + } + + @Test + void testPlaceOrderNoExceptionShortMsgDuration() throws Exception { + long paymentTime = timeLimits.paymentTime(); + long queueTaskTime = timeLimits.queueTaskTime(); + long messageTime = timeLimits.messageTime(); + long employeeTime = timeLimits.employeeTime(); + long queueTime = timeLimits.queueTime(); + for (double d = 0.1; d < 2; d = d + 0.1) { + paymentTime *= d; + queueTaskTime *= d; + messageTime *= d; + employeeTime *= d; + queueTime *= d; + Commander c = buildCommanderObjectNoPaymentException1(); + var order = new Order(new User("K", "J"), "pen", 1f); + for (Order.MessageSent ms : Order.MessageSent.values()) { + c.placeOrder(order); + assertFalse(StringUtils.isBlank(order.id)); + } + } + } + + @Test + void testPlaceOrderNoExceptionShortQueueDuration() throws Exception { + long paymentTime = timeLimits.paymentTime(); + long queueTaskTime = timeLimits.queueTaskTime(); + long messageTime = timeLimits.messageTime(); + long employeeTime = timeLimits.employeeTime(); + long queueTime = timeLimits.queueTime(); + for (double d = 0.1; d < 2; d = d + 0.1) { + paymentTime *= d; + queueTaskTime *= d; + messageTime *= d; + employeeTime *= d; + queueTime *= d; + Commander c = buildCommanderObjectUnknownException(); + var order = new Order(new User("K", "J"), "pen", 1f); + for (Order.MessageSent ms : Order.MessageSent.values()) { + c.placeOrder(order); + assertFalse(StringUtils.isBlank(order.id)); + } + } + } + + @Test + void testPlaceOrderWithDatabase() throws Exception { + long paymentTime = timeLimits.paymentTime(); + long queueTaskTime = timeLimits.queueTaskTime(); + long messageTime = timeLimits.messageTime(); + long employeeTime = timeLimits.employeeTime(); + long queueTime = timeLimits.queueTime(); + for (double d = 0.1; d < 2; d = d + 0.1) { + paymentTime *= d; + queueTaskTime *= d; + messageTime *= d; + employeeTime *= d; + queueTime *= d; + Commander c = buildCommanderObjectWithDB(); + var order = new Order(new User("K", null), "pen", 1f); + for (Order.MessageSent ms : Order.MessageSent.values()) { + c.placeOrder(order); + assertFalse(StringUtils.isBlank(order.id)); + } + } + } + + @Test + void testPlaceOrderWithDatabaseAndExceptions() throws Exception { + long paymentTime = timeLimits.paymentTime(); + long queueTaskTime = timeLimits.queueTaskTime(); + long messageTime = timeLimits.messageTime(); + long employeeTime = timeLimits.employeeTime(); + long queueTime = timeLimits.queueTime(); + for (double d = 0.1; d < 2; d = d + 0.1) { + paymentTime *= d; + queueTaskTime *= d; + messageTime *= d; + employeeTime *= d; + queueTime *= d; + + for (Exception e : exceptionList) { + + Commander c = buildCommanderObjectWithDB(true, true, e); + var order = new Order(new User("K", null), "pen", 1f); + for (Order.MessageSent ms : Order.MessageSent.values()) { + c.placeOrder(order); + assertFalse(StringUtils.isBlank(order.id)); } - - return new Commander(employeeHandle, paymentService, shippingService, - messagingService, null, retryParams, timeLimits); - } - - private Commander buildCommanderObjectWithoutDB() { - return buildCommanderObjectWithoutDB(false, false, new IllegalStateException()); - } - - private Commander buildCommanderObjectWithoutDB(boolean includeException, boolean includeDBException, Exception e) { - var l = includeDBException ? new DatabaseUnavailableException() : e; - PaymentService paymentService; - ShippingService shippingService; - MessagingService messagingService; - EmployeeHandle employeeHandle; - if (includeException) { - paymentService = new PaymentService - (null, l); - shippingService = new ShippingService(null, l); - messagingService = new MessagingService(null, l); - employeeHandle = new EmployeeHandle - (null, l); - } else { - paymentService = new PaymentService - (null); - shippingService = new ShippingService(null); - messagingService = new MessagingService(null); - employeeHandle = new EmployeeHandle - (null); + c = buildCommanderObjectWithDB(true, false, e); + order = new Order(new User("K", null), "pen", 1f); + for (Order.MessageSent ms : Order.MessageSent.values()) { + c.placeOrder(order); + assertFalse(StringUtils.isBlank(order.id)); } - - return new Commander(employeeHandle, paymentService, shippingService, - messagingService, null, retryParams, timeLimits); - } - - @Test - void testPlaceOrderVanilla() { - long paymentTime = timeLimits.paymentTime(); - long queueTaskTime = timeLimits.queueTaskTime(); - for (double d = 0.1; d < 2; d = d + 0.1) { - paymentTime *= d; - queueTaskTime *= d; - Commander c = buildCommanderObjectVanilla(); - var order = new Order(new User("K", "J"), "pen", 1f); - for (Order.MessageSent ms : Order.MessageSent.values()) { - c.placeOrder(order); - assertFalse(StringUtils.isBlank(order.id)); - } + c = buildCommanderObjectWithDB(false, false, e); + order = new Order(new User("K", null), "pen", 1f); + for (Order.MessageSent ms : Order.MessageSent.values()) { + c.placeOrder(order); + assertFalse(StringUtils.isBlank(order.id)); } - } - @Test - void testPlaceOrder() throws Exception { - long paymentTime = timeLimits.paymentTime(); - long queueTaskTime = timeLimits.queueTaskTime(); - for (double d = 0.1; d < 2; d = d + 0.1) { - paymentTime *= d; - queueTaskTime *= d; - Commander c = buildCommanderObject(true); - var order = new Order(new User("K", "J"), "pen", 1f); - for (Order.MessageSent ms : Order.MessageSent.values()) { - c.placeOrder(order); - assertFalse(StringUtils.isBlank(order.id)); - } + c = buildCommanderObjectWithDB(false, true, e); + order = new Order(new User("K", null), "pen", 1f); + for (Order.MessageSent ms : Order.MessageSent.values()) { + c.placeOrder(order); + assertFalse(StringUtils.isBlank(order.id)); } + } } + } - @Test - void testPlaceOrder2() throws Exception { - long paymentTime = timeLimits.paymentTime(); - long queueTaskTime = timeLimits.queueTaskTime(); - for (double d = 0.1; d < 2; d = d + 0.1) { - paymentTime *= d; - queueTaskTime *= d; - Commander c = buildCommanderObject(false); - var order = new Order(new User("K", "J"), "pen", 1f); - for (Order.MessageSent ms : Order.MessageSent.values()) { - c.placeOrder(order); - assertFalse(StringUtils.isBlank(order.id)); - } + @Test + void testPlaceOrderWithoutDatabase() throws Exception { + long paymentTime = timeLimits.paymentTime(); + long queueTaskTime = timeLimits.queueTaskTime(); + long messageTime = timeLimits.messageTime(); + long employeeTime = timeLimits.employeeTime(); + long queueTime = timeLimits.queueTime(); + for (double d = 0.1; d < 2; d = d + 0.1) { + paymentTime *= d; + queueTaskTime *= d; + messageTime *= d; + employeeTime *= d; + queueTime *= d; + Commander c = buildCommanderObjectWithoutDB(); + var order = new Order(new User("K", null), "pen", 1f); + for (Order.MessageSent ms : Order.MessageSent.values()) { + c.placeOrder(order); + assertFalse(StringUtils.isBlank(order.id)); + } + } + } + + @Test + void testPlaceOrderWithoutDatabaseAndExceptions() throws Exception { + long paymentTime = timeLimits.paymentTime(); + long queueTaskTime = timeLimits.queueTaskTime(); + long messageTime = timeLimits.messageTime(); + long employeeTime = timeLimits.employeeTime(); + long queueTime = timeLimits.queueTime(); + for (double d = 0.1; d < 2; d = d + 0.1) { + paymentTime *= d; + queueTaskTime *= d; + messageTime *= d; + employeeTime *= d; + queueTime *= d; + + for (Exception e : exceptionList) { + + Commander c = buildCommanderObjectWithoutDB(true, true, e); + var order = new Order(new User("K", null), "pen", 1f); + for (Order.MessageSent ms : Order.MessageSent.values()) { + c.placeOrder(order); + assertFalse(StringUtils.isBlank(order.id)); } - } - @Test - void testPlaceOrderNoException1() throws Exception { - long paymentTime = timeLimits.paymentTime(); - long queueTaskTime = timeLimits.queueTaskTime(); - for (double d = 0.1; d < 2; d = d + 0.1) { - paymentTime *= d; - queueTaskTime *= d; - Commander c = buildCommanderObjectNoPaymentException1(); - var order = new Order(new User("K", "J"), "pen", 1f); - for (Order.MessageSent ms : Order.MessageSent.values()) { - c.placeOrder(order); - assertFalse(StringUtils.isBlank(order.id)); - } + c = buildCommanderObjectWithoutDB(true, false, e); + order = new Order(new User("K", null), "pen", 1f); + for (Order.MessageSent ms : Order.MessageSent.values()) { + c.placeOrder(order); + assertFalse(StringUtils.isBlank(order.id)); } - } - @Test - void testPlaceOrderNoException2() throws Exception { - long paymentTime = timeLimits.paymentTime(); - long queueTaskTime = timeLimits.queueTaskTime(); - for (double d = 0.1; d < 2; d = d + 0.1) { - paymentTime *= d; - queueTaskTime *= d; - Commander c = buildCommanderObjectNoPaymentException2(); - var order = new Order(new User("K", "J"), "pen", 1f); - for (Order.MessageSent ms : Order.MessageSent.values()) { - c.placeOrder(order); - assertFalse(StringUtils.isBlank(order.id)); - } + c = buildCommanderObjectWithoutDB(false, false, e); + order = new Order(new User("K", null), "pen", 1f); + for (Order.MessageSent ms : Order.MessageSent.values()) { + c.placeOrder(order); + assertFalse(StringUtils.isBlank(order.id)); } - } - @Test - void testPlaceOrderNoException3() throws Exception { - long paymentTime = timeLimits.paymentTime(); - long queueTaskTime = timeLimits.queueTaskTime(); - for (double d = 0.1; d < 2; d = d + 0.1) { - paymentTime *= d; - queueTaskTime *= d; - Commander c = buildCommanderObjectNoPaymentException3(); - var order = new Order(new User("K", "J"), "pen", 1f); - for (Order.MessageSent ms : Order.MessageSent.values()) { - c.placeOrder(order); - assertFalse(StringUtils.isBlank(order.id)); - } + c = buildCommanderObjectWithoutDB(false, true, e); + order = new Order(new User("K", null), "pen", 1f); + for (Order.MessageSent ms : Order.MessageSent.values()) { + c.placeOrder(order); + assertFalse(StringUtils.isBlank(order.id)); } + } } + } - @Test - void testPlaceOrderNoException4() throws Exception { - long paymentTime = timeLimits.paymentTime(); - long queueTaskTime = timeLimits.queueTaskTime(); - for (double d = 0.1; d < 2; d = d + 0.1) { - paymentTime *= d; - queueTaskTime *= d; - Commander c = buildCommanderObjectNoPaymentException3(); - var order = new Order(new User("K", "J"), "pen", 1f); - for (Order.MessageSent ms : Order.MessageSent.values()) { - c.placeOrder(order); - c.placeOrder(order); - c.placeOrder(order); - assertFalse(StringUtils.isBlank(order.id)); - } - } - } + @Test + void testAllSuccessCases() throws Exception { + appAllCases.employeeDbSuccessCase(); + appAllCases.messagingSuccessCase(); + appAllCases.paymentSuccessCase(); + appAllCases.queueSuccessCase(); + appAllCases.shippingSuccessCase(); + } - @Test - void testPlaceOrderUnknownException() throws Exception { - long paymentTime = timeLimits.paymentTime(); - long queueTaskTime = timeLimits.queueTaskTime(); - long messageTime = timeLimits.messageTime(); - long employeeTime = timeLimits.employeeTime(); - long queueTime = timeLimits.queueTime(); - for (double d = 0.1; d < 2; d = d + 0.1) { - paymentTime *= d; - queueTaskTime *= d; - messageTime *= d; - employeeTime *= d; - queueTime *= d; - Commander c = buildCommanderObjectUnknownException(); - var order = new Order(new User("K", "J"), "pen", 1f); - for (Order.MessageSent ms : Order.MessageSent.values()) { - c.placeOrder(order); - assertFalse(StringUtils.isBlank(order.id)); - } - } - } + @Test + void testAllUnavailableCase() throws Exception { + appAllCases.employeeDatabaseUnavailableCase(); + appAllCases.messagingDatabaseUnavailableCasePaymentSuccess(); + appAllCases.messagingDatabaseUnavailableCasePaymentError(); + appAllCases.messagingDatabaseUnavailableCasePaymentFailure(); + appAllCases.paymentDatabaseUnavailableCase(); + appAllCases.queuePaymentTaskDatabaseUnavailableCase(); + appAllCases.queueMessageTaskDatabaseUnavailableCase(); + appAllCases.queueEmployeeDbTaskDatabaseUnavailableCase(); + appAllCases.itemUnavailableCase(); + appAllCases.shippingDatabaseUnavailableCase(); + } - @Test - void testPlaceOrderShortDuration() throws Exception { - long paymentTime = timeLimits.paymentTime(); - long queueTaskTime = timeLimits.queueTaskTime(); - long messageTime = timeLimits.messageTime(); - long employeeTime = timeLimits.employeeTime(); - long queueTime = timeLimits.queueTime(); - for (double d = 0.1; d < 2; d = d + 0.1) { - paymentTime *= d; - queueTaskTime *= d; - messageTime *= d; - employeeTime *= d; - queueTime *= d; - Commander c = buildCommanderObject(true); - var order = new Order(new User("K", "J"), "pen", 1f); - for (Order.MessageSent ms : Order.MessageSent.values()) { - c.placeOrder(order); - assertFalse(StringUtils.isBlank(order.id)); - } - } - } - - @Test - void testPlaceOrderShortDuration2() throws Exception { - long paymentTime = timeLimits.paymentTime(); - long queueTaskTime = timeLimits.queueTaskTime(); - long messageTime = timeLimits.messageTime(); - long employeeTime = timeLimits.employeeTime(); - long queueTime = timeLimits.queueTime(); - for (double d = 0.1; d < 2; d = d + 0.1) { - paymentTime *= d; - queueTaskTime *= d; - messageTime *= d; - employeeTime *= d; - queueTime *= d; - Commander c = buildCommanderObject(false); - var order = new Order(new User("K", "J"), "pen", 1f); - for (Order.MessageSent ms : Order.MessageSent.values()) { - c.placeOrder(order); - assertFalse(StringUtils.isBlank(order.id)); - } - } - } - - @Test - void testPlaceOrderNoExceptionShortMsgDuration() throws Exception { - long paymentTime = timeLimits.paymentTime(); - long queueTaskTime = timeLimits.queueTaskTime(); - long messageTime = timeLimits.messageTime(); - long employeeTime = timeLimits.employeeTime(); - long queueTime = timeLimits.queueTime(); - for (double d = 0.1; d < 2; d = d + 0.1) { - paymentTime *= d; - queueTaskTime *= d; - messageTime *= d; - employeeTime *= d; - queueTime *= d; - Commander c = buildCommanderObjectNoPaymentException1(); - var order = new Order(new User("K", "J"), "pen", 1f); - for (Order.MessageSent ms : Order.MessageSent.values()) { - c.placeOrder(order); - assertFalse(StringUtils.isBlank(order.id)); - } - } - } - - @Test - void testPlaceOrderNoExceptionShortQueueDuration() throws Exception { - long paymentTime = timeLimits.paymentTime(); - long queueTaskTime = timeLimits.queueTaskTime(); - long messageTime = timeLimits.messageTime(); - long employeeTime = timeLimits.employeeTime(); - long queueTime = timeLimits.queueTime(); - for (double d = 0.1; d < 2; d = d + 0.1) { - paymentTime *= d; - queueTaskTime *= d; - messageTime *= d; - employeeTime *= d; - queueTime *= d; - Commander c = buildCommanderObjectUnknownException(); - var order = new Order(new User("K", "J"), "pen", 1f); - for (Order.MessageSent ms : Order.MessageSent.values()) { - c.placeOrder(order); - assertFalse(StringUtils.isBlank(order.id)); - } - } - } - - @Test - void testPlaceOrderWithDatabase() throws Exception { - long paymentTime = timeLimits.paymentTime(); - long queueTaskTime = timeLimits.queueTaskTime(); - long messageTime = timeLimits.messageTime(); - long employeeTime = timeLimits.employeeTime(); - long queueTime = timeLimits.queueTime(); - for (double d = 0.1; d < 2; d = d + 0.1) { - paymentTime *= d; - queueTaskTime *= d; - messageTime *= d; - employeeTime *= d; - queueTime *= d; - Commander c = buildCommanderObjectWithDB(); - var order = new Order(new User("K", null), "pen", 1f); - for (Order.MessageSent ms : Order.MessageSent.values()) { - c.placeOrder(order); - assertFalse(StringUtils.isBlank(order.id)); - } - } - } - - @Test - void testPlaceOrderWithDatabaseAndExceptions() throws Exception { - long paymentTime = timeLimits.paymentTime(); - long queueTaskTime = timeLimits.queueTaskTime(); - long messageTime = timeLimits.messageTime(); - long employeeTime = timeLimits.employeeTime(); - long queueTime = timeLimits.queueTime(); - for (double d = 0.1; d < 2; d = d + 0.1) { - paymentTime *= d; - queueTaskTime *= d; - messageTime *= d; - employeeTime *= d; - queueTime *= d; - - for (Exception e : exceptionList) { - - Commander c = buildCommanderObjectWithDB(true, true, e); - var order = new Order(new User("K", null), "pen", 1f); - for (Order.MessageSent ms : Order.MessageSent.values()) { - c.placeOrder(order); - assertFalse(StringUtils.isBlank(order.id)); - } - - c = buildCommanderObjectWithDB(true, false, e); - order = new Order(new User("K", null), "pen", 1f); - for (Order.MessageSent ms : Order.MessageSent.values()) { - c.placeOrder(order); - assertFalse(StringUtils.isBlank(order.id)); - } - - c = buildCommanderObjectWithDB(false, false, e); - order = new Order(new User("K", null), "pen", 1f); - for (Order.MessageSent ms : Order.MessageSent.values()) { - c.placeOrder(order); - assertFalse(StringUtils.isBlank(order.id)); - } - - c = buildCommanderObjectWithDB(false, true, e); - order = new Order(new User("K", null), "pen", 1f); - for (Order.MessageSent ms : Order.MessageSent.values()) { - c.placeOrder(order); - assertFalse(StringUtils.isBlank(order.id)); - } - } - } - } - - @Test - void testPlaceOrderWithoutDatabase() throws Exception { - long paymentTime = timeLimits.paymentTime(); - long queueTaskTime = timeLimits.queueTaskTime(); - long messageTime = timeLimits.messageTime(); - long employeeTime = timeLimits.employeeTime(); - long queueTime = timeLimits.queueTime(); - for (double d = 0.1; d < 2; d = d + 0.1) { - paymentTime *= d; - queueTaskTime *= d; - messageTime *= d; - employeeTime *= d; - queueTime *= d; - Commander c = buildCommanderObjectWithoutDB(); - var order = new Order(new User("K", null), "pen", 1f); - for (Order.MessageSent ms : Order.MessageSent.values()) { - c.placeOrder(order); - assertFalse(StringUtils.isBlank(order.id)); - } - } - } - - @Test - void testPlaceOrderWithoutDatabaseAndExceptions() throws Exception { - long paymentTime = timeLimits.paymentTime(); - long queueTaskTime = timeLimits.queueTaskTime(); - long messageTime = timeLimits.messageTime(); - long employeeTime = timeLimits.employeeTime(); - long queueTime = timeLimits.queueTime(); - for (double d = 0.1; d < 2; d = d + 0.1) { - paymentTime *= d; - queueTaskTime *= d; - messageTime *= d; - employeeTime *= d; - queueTime *= d; - - for (Exception e : exceptionList) { - - Commander c = buildCommanderObjectWithoutDB(true, true, e); - var order = new Order(new User("K", null), "pen", 1f); - for (Order.MessageSent ms : Order.MessageSent.values()) { - c.placeOrder(order); - assertFalse(StringUtils.isBlank(order.id)); - } - - c = buildCommanderObjectWithoutDB(true, false, e); - order = new Order(new User("K", null), "pen", 1f); - for (Order.MessageSent ms : Order.MessageSent.values()) { - c.placeOrder(order); - assertFalse(StringUtils.isBlank(order.id)); - } - - c = buildCommanderObjectWithoutDB(false, false, e); - order = new Order(new User("K", null), "pen", 1f); - for (Order.MessageSent ms : Order.MessageSent.values()) { - c.placeOrder(order); - assertFalse(StringUtils.isBlank(order.id)); - } - - c = buildCommanderObjectWithoutDB(false, true, e); - order = new Order(new User("K", null), "pen", 1f); - for (Order.MessageSent ms : Order.MessageSent.values()) { - c.placeOrder(order); - assertFalse(StringUtils.isBlank(order.id)); - } - } - } - } - - @Test - void testAllSuccessCases() throws Exception{ - appAllCases.employeeDbSuccessCase(); - appAllCases.messagingSuccessCase(); - appAllCases.paymentSuccessCase(); - appAllCases.queueSuccessCase(); - appAllCases.shippingSuccessCase(); - } - - @Test - void testAllUnavailableCase() throws Exception { - appAllCases.employeeDatabaseUnavailableCase(); - appAllCases.messagingDatabaseUnavailableCasePaymentSuccess(); - appAllCases.messagingDatabaseUnavailableCasePaymentError(); - appAllCases.messagingDatabaseUnavailableCasePaymentFailure(); - appAllCases.paymentDatabaseUnavailableCase(); - appAllCases.queuePaymentTaskDatabaseUnavailableCase(); - appAllCases.queueMessageTaskDatabaseUnavailableCase(); - appAllCases.queueEmployeeDbTaskDatabaseUnavailableCase(); - appAllCases.itemUnavailableCase(); - appAllCases.shippingDatabaseUnavailableCase(); - } - - @Test - void testAllNotPossibleCase() throws Exception { - appAllCases.paymentNotPossibleCase(); - appAllCases.shippingItemNotPossibleCase(); - } -} \ No newline at end of file + @Test + void testAllNotPossibleCase() throws Exception { + appAllCases.paymentNotPossibleCase(); + appAllCases.shippingItemNotPossibleCase(); + } +} diff --git a/commander/src/test/java/com/iluwatar/commander/RetryTest.java b/commander/src/test/java/com/iluwatar/commander/RetryTest.java index c74fb94d0..389a45c2a 100644 --- a/commander/src/test/java/com/iluwatar/commander/RetryTest.java +++ b/commander/src/test/java/com/iluwatar/commander/RetryTest.java @@ -40,33 +40,47 @@ class RetryTest { @Test void performTest() { - Retry.Operation op = (l) -> { - if (!l.isEmpty()) { - throw l.remove(0); - } - }; - Retry.HandleErrorIssue handleError = (o, e) -> { - }; - var r1 = new Retry<>(op, handleError, 3, 30000, - e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass())); - var r2 = new Retry<>(op, handleError, 3, 30000, - e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass())); + Retry.Operation op = + (l) -> { + if (!l.isEmpty()) { + throw l.remove(0); + } + }; + Retry.HandleErrorIssue handleError = (o, e) -> {}; + var r1 = + new Retry<>( + op, + handleError, + 3, + 30000, + e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass())); + var r2 = + new Retry<>( + op, + handleError, + 3, + 30000, + e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass())); var user = new User("Jim", "ABCD"); var order = new Order(user, "book", 10f); - var arr1 = new ArrayList<>(List.of(new ItemUnavailableException(), new DatabaseUnavailableException())); + var arr1 = + new ArrayList<>( + List.of(new ItemUnavailableException(), new DatabaseUnavailableException())); try { r1.perform(arr1, order); } catch (Exception e1) { LOG.error("An exception occurred", e1); } - var arr2 = new ArrayList<>(List.of(new DatabaseUnavailableException(), new ItemUnavailableException())); + var arr2 = + new ArrayList<>( + List.of(new DatabaseUnavailableException(), new ItemUnavailableException())); try { r2.perform(arr2, order); } catch (Exception e1) { LOG.error("An exception occurred", e1); } - //r1 stops at ItemUnavailableException, r2 retries because it encounters DatabaseUnavailableException + // r1 stops at ItemUnavailableException, r2 retries because it encounters + // DatabaseUnavailableException assertTrue(arr1.size() == 1 && arr2.isEmpty()); } - } diff --git a/component/pom.xml b/component/pom.xml index e71b1cc59..e666e2834 100644 --- a/component/pom.xml +++ b/component/pom.xml @@ -37,9 +37,17 @@ component + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter - junit-jupiter-api + junit-jupiter-engine test diff --git a/component/src/main/java/com/iluwatar/component/App.java b/component/src/main/java/com/iluwatar/component/App.java index e6e005a1b..9401483e9 100644 --- a/component/src/main/java/com/iluwatar/component/App.java +++ b/component/src/main/java/com/iluwatar/component/App.java @@ -28,19 +28,18 @@ import java.awt.event.KeyEvent; import lombok.extern.slf4j.Slf4j; /** - * The component design pattern is a common game design structure. This pattern is often - * used to reduce duplication of code as well as to improve maintainability. - * In this implementation, component design pattern has been used to provide two game - * objects with varying component interfaces (features). As opposed to copying and - * pasting same code for the two game objects, the component interfaces allow game - * objects to inherit these components from the component classes. + * The component design pattern is a common game design structure. This pattern is often used to + * reduce duplication of code as well as to improve maintainability. In this implementation, + * component design pattern has been used to provide two game objects with varying component + * interfaces (features). As opposed to copying and pasting same code for the two game objects, the + * component interfaces allow game objects to inherit these components from the component classes. * - *

The implementation has decoupled graphic, physics and input components from - * the player and NPC objects. As a result, it avoids the creation of monolithic java classes. + *

The implementation has decoupled graphic, physics and input components from the player and NPC + * objects. As a result, it avoids the creation of monolithic java classes. * - *

The below example in this App class demonstrates the use of the component interfaces - * for separate objects (player & NPC) and updating of these components as per the - * implementations in GameObject class and the component classes. + *

The below example in this App class demonstrates the use of the component interfaces for + * separate objects (player & NPC) and updating of these components as per the implementations in + * GameObject class and the component classes. */ @Slf4j public final class App { @@ -53,7 +52,6 @@ public final class App { final var player = GameObject.createPlayer(); final var npc = GameObject.createNpc(); - LOGGER.info("Player Update:"); player.update(KeyEvent.KEY_LOCATION_LEFT); LOGGER.info("NPC Update:"); diff --git a/component/src/main/java/com/iluwatar/component/GameObject.java b/component/src/main/java/com/iluwatar/component/GameObject.java index c67970d06..87c35b24e 100644 --- a/component/src/main/java/com/iluwatar/component/GameObject.java +++ b/component/src/main/java/com/iluwatar/component/GameObject.java @@ -35,8 +35,8 @@ import lombok.Getter; import lombok.RequiredArgsConstructor; /** - * The GameObject class has three component class instances that allow - * the creation of different game objects based on the game design requirements. + * The GameObject class has three component class instances that allow the creation of different + * game objects based on the game design requirements. */ @Getter @RequiredArgsConstructor @@ -55,13 +55,13 @@ public class GameObject { * @return player object */ public static GameObject createPlayer() { - return new GameObject(new PlayerInputComponent(), + return new GameObject( + new PlayerInputComponent(), new ObjectPhysicComponent(), new ObjectGraphicComponent(), "player"); } - /** * Creates a NPC game object. * @@ -69,16 +69,12 @@ public class GameObject { */ public static GameObject createNpc() { return new GameObject( - new DemoInputComponent(), - new ObjectPhysicComponent(), - new ObjectGraphicComponent(), - "npc"); + new DemoInputComponent(), new ObjectPhysicComponent(), new ObjectGraphicComponent(), "npc"); } /** - * Updates the three components of the NPC object used in the demo in App.java - * note that this is simply a duplicate of update() without the key event for - * demonstration purposes. + * Updates the three components of the NPC object used in the demo in App.java note that this is + * simply a duplicate of update() without the key event for demonstration purposes. * *

This method is usually used in games if the player becomes inactive. */ @@ -108,10 +104,7 @@ public class GameObject { this.velocity += acceleration; } - - /** - * Set the c based on the current velocity. - */ + /** Set the c based on the current velocity. */ public void updateCoordinate() { this.coordinate += this.velocity; } diff --git a/component/src/main/java/com/iluwatar/component/component/graphiccomponent/GraphicComponent.java b/component/src/main/java/com/iluwatar/component/component/graphiccomponent/GraphicComponent.java index f8e1f7094..600ee8e52 100644 --- a/component/src/main/java/com/iluwatar/component/component/graphiccomponent/GraphicComponent.java +++ b/component/src/main/java/com/iluwatar/component/component/graphiccomponent/GraphicComponent.java @@ -26,9 +26,7 @@ package com.iluwatar.component.component.graphiccomponent; import com.iluwatar.component.GameObject; -/** - * Generic GraphicComponent interface. - */ +/** Generic GraphicComponent interface. */ public interface GraphicComponent { void update(GameObject gameObject); } diff --git a/component/src/main/java/com/iluwatar/component/component/graphiccomponent/ObjectGraphicComponent.java b/component/src/main/java/com/iluwatar/component/component/graphiccomponent/ObjectGraphicComponent.java index fc260b45e..7f595763f 100644 --- a/component/src/main/java/com/iluwatar/component/component/graphiccomponent/ObjectGraphicComponent.java +++ b/component/src/main/java/com/iluwatar/component/component/graphiccomponent/ObjectGraphicComponent.java @@ -27,9 +27,7 @@ package com.iluwatar.component.component.graphiccomponent; import com.iluwatar.component.GameObject; import lombok.extern.slf4j.Slf4j; -/** - * ObjectGraphicComponent class mimics the graphic component of the Game Object. - */ +/** ObjectGraphicComponent class mimics the graphic component of the Game Object. */ @Slf4j public class ObjectGraphicComponent implements GraphicComponent { diff --git a/component/src/main/java/com/iluwatar/component/component/inputcomponent/DemoInputComponent.java b/component/src/main/java/com/iluwatar/component/component/inputcomponent/DemoInputComponent.java index ccf05738e..b7ff51c3f 100644 --- a/component/src/main/java/com/iluwatar/component/component/inputcomponent/DemoInputComponent.java +++ b/component/src/main/java/com/iluwatar/component/component/inputcomponent/DemoInputComponent.java @@ -28,11 +28,11 @@ import com.iluwatar.component.GameObject; import lombok.extern.slf4j.Slf4j; /** - * Take this component class to control player or the NPC for demo mode. - * and implemented the InputComponent interface. + * Take this component class to control player or the NPC for demo mode. and implemented the + * InputComponent interface. * - *

Essentially, the demo mode is utilised during a game if the user become inactive. - * Please see: http://gameprogrammingpatterns.com/component.html + *

Essentially, the demo mode is utilised during a game if the user become inactive. Please see: + * http://gameprogrammingpatterns.com/component.html */ @Slf4j public class DemoInputComponent implements InputComponent { @@ -42,7 +42,7 @@ public class DemoInputComponent implements InputComponent { * Redundant method in the demo mode. * * @param gameObject the gameObject instance - * @param e key event instance + * @param e key event instance */ @Override public void update(GameObject gameObject, int e) { diff --git a/component/src/main/java/com/iluwatar/component/component/inputcomponent/InputComponent.java b/component/src/main/java/com/iluwatar/component/component/inputcomponent/InputComponent.java index 3ab30c148..65bab37fc 100644 --- a/component/src/main/java/com/iluwatar/component/component/inputcomponent/InputComponent.java +++ b/component/src/main/java/com/iluwatar/component/component/inputcomponent/InputComponent.java @@ -26,9 +26,7 @@ package com.iluwatar.component.component.inputcomponent; import com.iluwatar.component.GameObject; -/** - * Generic InputComponent interface. - */ +/** Generic InputComponent interface. */ public interface InputComponent { void update(GameObject gameObject, int e); } diff --git a/component/src/main/java/com/iluwatar/component/component/inputcomponent/PlayerInputComponent.java b/component/src/main/java/com/iluwatar/component/component/inputcomponent/PlayerInputComponent.java index eb9e9d800..d38682de4 100644 --- a/component/src/main/java/com/iluwatar/component/component/inputcomponent/PlayerInputComponent.java +++ b/component/src/main/java/com/iluwatar/component/component/inputcomponent/PlayerInputComponent.java @@ -29,8 +29,8 @@ import java.awt.event.KeyEvent; import lombok.extern.slf4j.Slf4j; /** - * PlayerInputComponent is used to handle user key event inputs, - * and thus it implements the InputComponent interface. + * PlayerInputComponent is used to handle user key event inputs, and thus it implements the + * InputComponent interface. */ @Slf4j public class PlayerInputComponent implements InputComponent { @@ -40,7 +40,7 @@ public class PlayerInputComponent implements InputComponent { * The update method to change the velocity based on the input key event. * * @param gameObject the gameObject instance - * @param e key event instance + * @param e key event instance */ @Override public void update(GameObject gameObject, int e) { diff --git a/component/src/main/java/com/iluwatar/component/component/physiccomponent/ObjectPhysicComponent.java b/component/src/main/java/com/iluwatar/component/component/physiccomponent/ObjectPhysicComponent.java index b8d880138..a7c189efc 100644 --- a/component/src/main/java/com/iluwatar/component/component/physiccomponent/ObjectPhysicComponent.java +++ b/component/src/main/java/com/iluwatar/component/component/physiccomponent/ObjectPhysicComponent.java @@ -27,9 +27,7 @@ package com.iluwatar.component.component.physiccomponent; import com.iluwatar.component.GameObject; import lombok.extern.slf4j.Slf4j; -/** - * Take this component class to update the x coordinate for the Game Object instance. - */ +/** Take this component class to update the x coordinate for the Game Object instance. */ @Slf4j public class ObjectPhysicComponent implements PhysicComponent { diff --git a/component/src/main/java/com/iluwatar/component/component/physiccomponent/PhysicComponent.java b/component/src/main/java/com/iluwatar/component/component/physiccomponent/PhysicComponent.java index 25e2dfd40..67c330260 100644 --- a/component/src/main/java/com/iluwatar/component/component/physiccomponent/PhysicComponent.java +++ b/component/src/main/java/com/iluwatar/component/component/physiccomponent/PhysicComponent.java @@ -26,9 +26,7 @@ package com.iluwatar.component.component.physiccomponent; import com.iluwatar.component.GameObject; -/** - * Generic PhysicComponent interface. - */ +/** Generic PhysicComponent interface. */ public interface PhysicComponent { void update(GameObject gameObject); } diff --git a/component/src/test/java/com/iluwatar/component/AppTest.java b/component/src/test/java/com/iluwatar/component/AppTest.java index 6fa191804..7de0745e7 100644 --- a/component/src/test/java/com/iluwatar/component/AppTest.java +++ b/component/src/test/java/com/iluwatar/component/AppTest.java @@ -24,18 +24,18 @@ */ package com.iluwatar.component; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import org.junit.jupiter.api.Test; + /** - * Tests App class : src/main/java/com/iluwatar/component/App.java - * General execution test of the application. + * Tests App class : src/main/java/com/iluwatar/component/App.java General execution test of the + * application. */ class AppTest { - @Test - void shouldExecuteComponentWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); - } + @Test + void shouldExecuteComponentWithoutException() { + assertDoesNotThrow(() -> App.main(new String[] {})); + } } diff --git a/component/src/test/java/com/iluwatar/component/GameObjectTest.java b/component/src/test/java/com/iluwatar/component/GameObjectTest.java index 66b6c6a55..09b3b3995 100644 --- a/component/src/test/java/com/iluwatar/component/GameObjectTest.java +++ b/component/src/test/java/com/iluwatar/component/GameObjectTest.java @@ -24,72 +24,64 @@ */ package com.iluwatar.component; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; + import java.awt.event.KeyEvent; import lombok.extern.slf4j.Slf4j; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -/** - * Tests GameObject class. - * src/main/java/com/iluwatar/component/GameObject.java - */ +/** Tests GameObject class. src/main/java/com/iluwatar/component/GameObject.java */ @Slf4j class GameObjectTest { - GameObject playerTest; - GameObject npcTest; - @BeforeEach - public void initEach() { - //creates player & npc objects for testing - //note that velocity and coordinates are initialised to 0 in GameObject.java - playerTest = GameObject.createPlayer(); - npcTest = GameObject.createNpc(); - } + GameObject playerTest; + GameObject npcTest; - /** - * Tests the create methods - createPlayer() and createNPC(). - */ - @Test - void objectTest(){ - LOGGER.info("objectTest:"); - assertEquals("player",playerTest.getName()); - assertEquals("npc",npcTest.getName()); - } + @BeforeEach + public void initEach() { + // creates player & npc objects for testing + // note that velocity and coordinates are initialised to 0 in GameObject.java + playerTest = GameObject.createPlayer(); + npcTest = GameObject.createNpc(); + } - /** - * Tests the input component with varying key event inputs. - * Targets the player game object. - */ - @Test - void eventInputTest(){ - LOGGER.info("eventInputTest:"); - playerTest.update(KeyEvent.KEY_LOCATION_LEFT); - assertEquals(-1, playerTest.getVelocity()); - assertEquals(-1, playerTest.getCoordinate()); + /** Tests the create methods - createPlayer() and createNPC(). */ + @Test + void objectTest() { + LOGGER.info("objectTest:"); + assertEquals("player", playerTest.getName()); + assertEquals("npc", npcTest.getName()); + } - playerTest.update(KeyEvent.KEY_LOCATION_RIGHT); - playerTest.update(KeyEvent.KEY_LOCATION_RIGHT); - assertEquals(1, playerTest.getVelocity()); - assertEquals(0, playerTest.getCoordinate()); + /** Tests the input component with varying key event inputs. Targets the player game object. */ + @Test + void eventInputTest() { + LOGGER.info("eventInputTest:"); + playerTest.update(KeyEvent.KEY_LOCATION_LEFT); + assertEquals(-1, playerTest.getVelocity()); + assertEquals(-1, playerTest.getCoordinate()); - LOGGER.info(Integer.toString(playerTest.getCoordinate())); - LOGGER.info(Integer.toString(playerTest.getVelocity())); + playerTest.update(KeyEvent.KEY_LOCATION_RIGHT); + playerTest.update(KeyEvent.KEY_LOCATION_RIGHT); + assertEquals(1, playerTest.getVelocity()); + assertEquals(0, playerTest.getCoordinate()); - GameObject p2 = GameObject.createPlayer(); - p2.update(KeyEvent.KEY_LOCATION_LEFT); - //in the case of an unknown, object stats are set to default - p2.update(KeyEvent.KEY_LOCATION_UNKNOWN); - assertEquals(-1, p2.getVelocity()); - } + LOGGER.info(Integer.toString(playerTest.getCoordinate())); + LOGGER.info(Integer.toString(playerTest.getVelocity())); - /** - * Tests the demo component interface. - */ - @Test - void npcDemoTest(){ - LOGGER.info("npcDemoTest:"); - npcTest.demoUpdate(); - assertEquals(2, npcTest.getVelocity()); - assertEquals(2, npcTest.getCoordinate()); - } + GameObject p2 = GameObject.createPlayer(); + p2.update(KeyEvent.KEY_LOCATION_LEFT); + // in the case of an unknown, object stats are set to default + p2.update(KeyEvent.KEY_LOCATION_UNKNOWN); + assertEquals(-1, p2.getVelocity()); + } + + /** Tests the demo component interface. */ + @Test + void npcDemoTest() { + LOGGER.info("npcDemoTest:"); + npcTest.demoUpdate(); + assertEquals(2, npcTest.getVelocity()); + assertEquals(2, npcTest.getCoordinate()); + } } diff --git a/composite-entity/pom.xml b/composite-entity/pom.xml index bed5c3a40..5d11234c3 100644 --- a/composite-entity/pom.xml +++ b/composite-entity/pom.xml @@ -34,6 +34,14 @@ 4.0.0 composite-entity + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/composite-entity/src/main/java/com/iluwatar/compositeentity/App.java b/composite-entity/src/main/java/com/iluwatar/compositeentity/App.java index 68569b37d..c3ae1181a 100644 --- a/composite-entity/src/main/java/com/iluwatar/compositeentity/App.java +++ b/composite-entity/src/main/java/com/iluwatar/compositeentity/App.java @@ -27,7 +27,6 @@ package com.iluwatar.compositeentity; import java.util.Arrays; import lombok.extern.slf4j.Slf4j; - /** * Composite entity is a Java EE Software design pattern and it is used to model, represent, and * manage a set of interrelated persistent objects rather than representing them as individual @@ -36,10 +35,7 @@ import lombok.extern.slf4j.Slf4j; @Slf4j public class App { - - /** - * An instance that a console manages two related objects. - */ + /** An instance that a console manages two related objects. */ public App(String message, String signal) { var console = new CompositeEntity(); console.init(); @@ -57,6 +53,5 @@ public class App { public static void main(String[] args) { new App("No Danger", "Green Light"); - } } diff --git a/composite-entity/src/main/java/com/iluwatar/compositeentity/CoarseGrainedObject.java b/composite-entity/src/main/java/com/iluwatar/compositeentity/CoarseGrainedObject.java index 1eefbf2e4..fa195c2cd 100644 --- a/composite-entity/src/main/java/com/iluwatar/compositeentity/CoarseGrainedObject.java +++ b/composite-entity/src/main/java/com/iluwatar/compositeentity/CoarseGrainedObject.java @@ -32,7 +32,6 @@ import java.util.stream.IntStream; * other objects. It can be an object contained in the composite entity, or, composite entity itself * can be the coarse-grained object which holds dependent objects. */ - public abstract class CoarseGrainedObject { DependentObject[] dependentObjects; diff --git a/composite-entity/src/main/java/com/iluwatar/compositeentity/CompositeEntity.java b/composite-entity/src/main/java/com/iluwatar/compositeentity/CompositeEntity.java index cd52841ca..0c4a05155 100644 --- a/composite-entity/src/main/java/com/iluwatar/compositeentity/CompositeEntity.java +++ b/composite-entity/src/main/java/com/iluwatar/compositeentity/CompositeEntity.java @@ -28,7 +28,6 @@ package com.iluwatar.compositeentity; * Composite entity is the coarse-grained entity bean which may be the coarse-grained object, or may * contain a reference to the coarse-grained object. */ - public class CompositeEntity { private final ConsoleCoarseGrainedObject console = new ConsoleCoarseGrainedObject(); @@ -44,4 +43,4 @@ public class CompositeEntity { public void init() { console.init(); } -} \ No newline at end of file +} diff --git a/composite-entity/src/main/java/com/iluwatar/compositeentity/ConsoleCoarseGrainedObject.java b/composite-entity/src/main/java/com/iluwatar/compositeentity/ConsoleCoarseGrainedObject.java index 4ec8413a9..422fdc541 100644 --- a/composite-entity/src/main/java/com/iluwatar/compositeentity/ConsoleCoarseGrainedObject.java +++ b/composite-entity/src/main/java/com/iluwatar/compositeentity/ConsoleCoarseGrainedObject.java @@ -24,21 +24,16 @@ */ package com.iluwatar.compositeentity; -/** - * A specific CoarseGrainedObject to implement a console. - */ - +/** A specific CoarseGrainedObject to implement a console. */ public class ConsoleCoarseGrainedObject extends CoarseGrainedObject { @Override public String[] getData() { - return new String[]{ - dependentObjects[0].getData(), dependentObjects[1].getData() - }; + return new String[] {dependentObjects[0].getData(), dependentObjects[1].getData()}; } public void init() { - dependentObjects = new DependentObject[]{ - new MessageDependentObject(), new SignalDependentObject()}; + dependentObjects = + new DependentObject[] {new MessageDependentObject(), new SignalDependentObject()}; } -} \ No newline at end of file +} diff --git a/composite-entity/src/main/java/com/iluwatar/compositeentity/DependentObject.java b/composite-entity/src/main/java/com/iluwatar/compositeentity/DependentObject.java index 29380af54..90f2024bc 100644 --- a/composite-entity/src/main/java/com/iluwatar/compositeentity/DependentObject.java +++ b/composite-entity/src/main/java/com/iluwatar/compositeentity/DependentObject.java @@ -37,5 +37,4 @@ import lombok.Setter; public abstract class DependentObject { T data; - } diff --git a/composite-entity/src/main/java/com/iluwatar/compositeentity/MessageDependentObject.java b/composite-entity/src/main/java/com/iluwatar/compositeentity/MessageDependentObject.java index 98b351fe6..199e5ee1d 100644 --- a/composite-entity/src/main/java/com/iluwatar/compositeentity/MessageDependentObject.java +++ b/composite-entity/src/main/java/com/iluwatar/compositeentity/MessageDependentObject.java @@ -24,10 +24,5 @@ */ package com.iluwatar.compositeentity; -/** - * The first DependentObject to show message. - */ - -public class MessageDependentObject extends DependentObject { - -} \ No newline at end of file +/** The first DependentObject to show message. */ +public class MessageDependentObject extends DependentObject {} diff --git a/composite-entity/src/main/java/com/iluwatar/compositeentity/SignalDependentObject.java b/composite-entity/src/main/java/com/iluwatar/compositeentity/SignalDependentObject.java index 58b868e8d..cc3847c29 100644 --- a/composite-entity/src/main/java/com/iluwatar/compositeentity/SignalDependentObject.java +++ b/composite-entity/src/main/java/com/iluwatar/compositeentity/SignalDependentObject.java @@ -24,10 +24,5 @@ */ package com.iluwatar.compositeentity; -/** - * The second DependentObject to show message. - */ - -public class SignalDependentObject extends DependentObject { - -} \ No newline at end of file +/** The second DependentObject to show message. */ +public class SignalDependentObject extends DependentObject {} diff --git a/composite-entity/src/test/java/com/iluwatar/compositeentity/AppTest.java b/composite-entity/src/test/java/com/iluwatar/compositeentity/AppTest.java index 85b8da7d6..4010c2912 100644 --- a/composite-entity/src/test/java/com/iluwatar/compositeentity/AppTest.java +++ b/composite-entity/src/test/java/com/iluwatar/compositeentity/AppTest.java @@ -28,22 +28,18 @@ import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import org.junit.jupiter.api.Test; -/** - * com.iluwatar.compositeentity.App running test - */ +/** com.iluwatar.compositeentity.App running test */ class AppTest { /** * Issue: Add at least one assertion to this test case. - *

- * Solution: Inserted assertion to check whether the execution of the main method in {@link + * + *

Solution: Inserted assertion to check whether the execution of the main method in {@link * App#main(String[])} throws an exception. */ - @Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); - + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/composite-entity/src/test/java/com/iluwatar/compositeentity/PersistenceTest.java b/composite-entity/src/test/java/com/iluwatar/compositeentity/PersistenceTest.java index b90272f3b..08e7899b4 100644 --- a/composite-entity/src/test/java/com/iluwatar/compositeentity/PersistenceTest.java +++ b/composite-entity/src/test/java/com/iluwatar/compositeentity/PersistenceTest.java @@ -24,13 +24,13 @@ */ package com.iluwatar.compositeentity; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; + class PersistenceTest { - final static ConsoleCoarseGrainedObject console = new ConsoleCoarseGrainedObject(); + static final ConsoleCoarseGrainedObject console = new ConsoleCoarseGrainedObject(); @Test void dependentObjectChangedForPersistenceTest() { diff --git a/composite-view/pom.xml b/composite-view/pom.xml index d7913c3b0..f8b38b523 100644 --- a/composite-view/pom.xml +++ b/composite-view/pom.xml @@ -37,13 +37,16 @@ composite-view - org.junit.jupiter - junit-jupiter-engine - test + org.slf4j + slf4j-api - junit - junit + ch.qos.logback + logback-classic + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/composite-view/src/main/java/com/iluwatar/compositeview/AppServlet.java b/composite-view/src/main/java/com/iluwatar/compositeview/AppServlet.java index a10d98c52..3b803a615 100644 --- a/composite-view/src/main/java/com/iluwatar/compositeview/AppServlet.java +++ b/composite-view/src/main/java/com/iluwatar/compositeview/AppServlet.java @@ -32,16 +32,14 @@ import java.io.PrintWriter; import lombok.NoArgsConstructor; import lombok.extern.slf4j.Slf4j; -/** - * A servlet object that extends HttpServlet. - * Runs on Tomcat 10 and handles Http requests - */ +/** A servlet object that extends HttpServlet. Runs on Tomcat 10 and handles Http requests */ @Slf4j @NoArgsConstructor public final class AppServlet extends HttpServlet { private static final String CONTENT_TYPE = "text/html"; private String msgPartOne = "

This Server Doesn't Support"; - private String msgPartTwo = """ + private String msgPartTwo = + """ Requests

Use a GET request with boolean values for the following parameters

'name'

@@ -93,4 +91,4 @@ public final class AppServlet extends HttpServlet { LOGGER.error("Exception occurred PUT request processing ", e); } } -} \ No newline at end of file +} diff --git a/composite-view/src/main/java/com/iluwatar/compositeview/ClientPropertiesBean.java b/composite-view/src/main/java/com/iluwatar/compositeview/ClientPropertiesBean.java index 8baf2ee53..ecda0cb38 100644 --- a/composite-view/src/main/java/com/iluwatar/compositeview/ClientPropertiesBean.java +++ b/composite-view/src/main/java/com/iluwatar/compositeview/ClientPropertiesBean.java @@ -30,15 +30,13 @@ import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; - /** - * A Java beans class that parses a http request and stores parameters. - * Java beans used in JSP's to dynamically include elements in view. - * DEFAULT_NAME = a constant, default name to be used for the default constructor - * worldNewsInterest = whether current request has world news interest - * sportsInterest = whether current request has a sportsInterest - * businessInterest = whether current request has a businessInterest - * scienceNewsInterest = whether current request has a scienceNewsInterest + * A Java beans class that parses a http request and stores parameters. Java beans used in JSP's to + * dynamically include elements in view. DEFAULT_NAME = a constant, default name to be used for the + * default constructor worldNewsInterest = whether current request has world news interest + * sportsInterest = whether current request has a sportsInterest businessInterest = whether current + * request has a businessInterest scienceNewsInterest = whether current request has a + * scienceNewsInterest */ @Getter @Setter @@ -51,7 +49,7 @@ public class ClientPropertiesBean implements Serializable { private static final String BUSINESS_PARAM = "bus"; private static final String NAME_PARAM = "name"; - private static final String DEFAULT_NAME = "DEFAULT_NAME"; + private static final String DEFAULT_NAME = "DEFAULT_NAME"; private boolean worldNewsInterest = true; private boolean sportsInterest = true; private boolean businessInterest = true; diff --git a/composite-view/src/test/java/com/iluwatar/compositeview/AppServletTest.java b/composite-view/src/test/java/com/iluwatar/compositeview/AppServletTest.java index c585be29e..8219a56e4 100644 --- a/composite-view/src/test/java/com/iluwatar/compositeview/AppServletTest.java +++ b/composite-view/src/test/java/com/iluwatar/compositeview/AppServletTest.java @@ -24,88 +24,93 @@ */ package com.iluwatar.compositeview; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.*; + import jakarta.servlet.RequestDispatcher; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; -import org.junit.jupiter.api.Test; -import org.mockito.Mockito; import java.io.PrintWriter; import java.io.StringWriter; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.*; +class AppServletTest { -/* Written with reference from https://stackoverflow.com/questions/5434419/how-to-test-my-servlet-using-junit -and https://stackoverflow.com/questions/50211433/servlets-unit-testing - */ - -class AppServletTest extends Mockito{ - private String msgPartOne = "

This Server Doesn't Support"; - private String msgPartTwo = """ - Requests

-

Use a GET request with boolean values for the following parameters

-

'name'

-

'bus'

-

'sports'

-

'sci'

-

'world'

"""; - private String destination = "newsDisplay.jsp"; + private final String msgPartOne = "

This Server Doesn't Support"; + private final String msgPartTwo = + """ + Requests

+

Use a GET request with boolean values for the following parameters

+

'name'

+

'bus'

+

'sports'

+

'sci'

+

'world'

"""; + private final String destination = "newsDisplay.jsp"; @Test void testDoGet() throws Exception { - HttpServletRequest mockReq = Mockito.mock(HttpServletRequest.class); - HttpServletResponse mockResp = Mockito.mock(HttpServletResponse.class); - RequestDispatcher mockDispatcher = Mockito.mock(RequestDispatcher.class); + HttpServletRequest mockReq = mock(HttpServletRequest.class); + HttpServletResponse mockResp = mock(HttpServletResponse.class); + RequestDispatcher mockDispatcher = mock(RequestDispatcher.class); StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter); + when(mockResp.getWriter()).thenReturn(printWriter); when(mockReq.getRequestDispatcher(destination)).thenReturn(mockDispatcher); + AppServlet curServlet = new AppServlet(); curServlet.doGet(mockReq, mockResp); + verify(mockReq, times(1)).getRequestDispatcher(destination); verify(mockDispatcher).forward(mockReq, mockResp); - - } @Test void testDoPost() throws Exception { - HttpServletRequest mockReq = Mockito.mock(HttpServletRequest.class); - HttpServletResponse mockResp = Mockito.mock(HttpServletResponse.class); + HttpServletRequest mockReq = mock(HttpServletRequest.class); + HttpServletResponse mockResp = mock(HttpServletResponse.class); StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter); + when(mockResp.getWriter()).thenReturn(printWriter); AppServlet curServlet = new AppServlet(); curServlet.doPost(mockReq, mockResp); printWriter.flush(); + assertTrue(stringWriter.toString().contains(msgPartOne + " Post " + msgPartTwo)); } @Test void testDoPut() throws Exception { - HttpServletRequest mockReq = Mockito.mock(HttpServletRequest.class); - HttpServletResponse mockResp = Mockito.mock(HttpServletResponse.class); + HttpServletRequest mockReq = mock(HttpServletRequest.class); + HttpServletResponse mockResp = mock(HttpServletResponse.class); StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter); + when(mockResp.getWriter()).thenReturn(printWriter); AppServlet curServlet = new AppServlet(); curServlet.doPut(mockReq, mockResp); printWriter.flush(); + assertTrue(stringWriter.toString().contains(msgPartOne + " Put " + msgPartTwo)); } @Test void testDoDelete() throws Exception { - HttpServletRequest mockReq = Mockito.mock(HttpServletRequest.class); - HttpServletResponse mockResp = Mockito.mock(HttpServletResponse.class); + HttpServletRequest mockReq = mock(HttpServletRequest.class); + HttpServletResponse mockResp = mock(HttpServletResponse.class); StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter); + when(mockResp.getWriter()).thenReturn(printWriter); AppServlet curServlet = new AppServlet(); curServlet.doDelete(mockReq, mockResp); printWriter.flush(); + assertTrue(stringWriter.toString().contains(msgPartOne + " Delete " + msgPartTwo)); } } diff --git a/composite-view/src/test/java/com/iluwatar/compositeview/JavaBeansTest.java b/composite-view/src/test/java/com/iluwatar/compositeview/JavaBeansTest.java index 826a00881..8e27a20e0 100644 --- a/composite-view/src/test/java/com/iluwatar/compositeview/JavaBeansTest.java +++ b/composite-view/src/test/java/com/iluwatar/compositeview/JavaBeansTest.java @@ -24,72 +24,78 @@ */ package com.iluwatar.compositeview; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + import jakarta.servlet.http.HttpServletRequest; import org.junit.jupiter.api.Test; -import org.mockito.Mockito; - -import static org.junit.Assert.*; class JavaBeansTest { - @Test - void testDefaultConstructor() { - ClientPropertiesBean newBean = new ClientPropertiesBean(); - assertEquals("DEFAULT_NAME", newBean.getName()); - assertTrue(newBean.isBusinessInterest()); - assertTrue(newBean.isScienceNewsInterest()); - assertTrue(newBean.isSportsInterest()); - assertTrue(newBean.isWorldNewsInterest()); - } + @Test + void testDefaultConstructor() { + ClientPropertiesBean newBean = new ClientPropertiesBean(); + assertEquals("DEFAULT_NAME", newBean.getName()); + assertTrue(newBean.isBusinessInterest()); + assertTrue(newBean.isScienceNewsInterest()); + assertTrue(newBean.isSportsInterest()); + assertTrue(newBean.isWorldNewsInterest()); + } - @Test - void testNameGetterSetter() { - ClientPropertiesBean newBean = new ClientPropertiesBean(); - assertEquals("DEFAULT_NAME", newBean.getName()); - newBean.setName("TEST_NAME_ONE"); - assertEquals("TEST_NAME_ONE", newBean.getName()); - } + @Test + void testNameGetterSetter() { + ClientPropertiesBean newBean = new ClientPropertiesBean(); + assertEquals("DEFAULT_NAME", newBean.getName()); - @Test - void testBusinessSetterGetter() { - ClientPropertiesBean newBean = new ClientPropertiesBean(); - assertTrue(newBean.isBusinessInterest()); - newBean.setBusinessInterest(false); - assertFalse(newBean.isBusinessInterest()); - } + newBean.setName("TEST_NAME_ONE"); + assertEquals("TEST_NAME_ONE", newBean.getName()); + } - @Test - void testScienceSetterGetter() { - ClientPropertiesBean newBean = new ClientPropertiesBean(); - assertTrue(newBean.isScienceNewsInterest()); - newBean.setScienceNewsInterest(false); - assertFalse(newBean.isScienceNewsInterest()); - } + @Test + void testBusinessSetterGetter() { + ClientPropertiesBean newBean = new ClientPropertiesBean(); + assertTrue(newBean.isBusinessInterest()); - @Test - void testSportsSetterGetter() { - ClientPropertiesBean newBean = new ClientPropertiesBean(); - assertTrue(newBean.isSportsInterest()); - newBean.setSportsInterest(false); - assertFalse(newBean.isSportsInterest()); - } + newBean.setBusinessInterest(false); + assertFalse(newBean.isBusinessInterest()); + } - @Test - void testWorldSetterGetter() { - ClientPropertiesBean newBean = new ClientPropertiesBean(); - assertTrue(newBean.isWorldNewsInterest()); - newBean.setWorldNewsInterest(false); - assertFalse(newBean.isWorldNewsInterest()); - } + @Test + void testScienceSetterGetter() { + ClientPropertiesBean newBean = new ClientPropertiesBean(); + assertTrue(newBean.isScienceNewsInterest()); - @Test - void testRequestConstructor(){ - HttpServletRequest mockReq = Mockito.mock(HttpServletRequest.class); - ClientPropertiesBean newBean = new ClientPropertiesBean((mockReq)); - assertEquals("DEFAULT_NAME", newBean.getName()); - assertFalse(newBean.isWorldNewsInterest()); - assertFalse(newBean.isBusinessInterest()); - assertFalse(newBean.isScienceNewsInterest()); - assertFalse(newBean.isSportsInterest()); - } + newBean.setScienceNewsInterest(false); + assertFalse(newBean.isScienceNewsInterest()); + } + + @Test + void testSportsSetterGetter() { + ClientPropertiesBean newBean = new ClientPropertiesBean(); + assertTrue(newBean.isSportsInterest()); + + newBean.setSportsInterest(false); + assertFalse(newBean.isSportsInterest()); + } + + @Test + void testWorldSetterGetter() { + ClientPropertiesBean newBean = new ClientPropertiesBean(); + assertTrue(newBean.isWorldNewsInterest()); + + newBean.setWorldNewsInterest(false); + assertFalse(newBean.isWorldNewsInterest()); + } + + @Test + void testRequestConstructor() { + HttpServletRequest mockReq = mock(HttpServletRequest.class); + ClientPropertiesBean newBean = new ClientPropertiesBean(mockReq); + + assertEquals("DEFAULT_NAME", newBean.getName()); + assertFalse(newBean.isWorldNewsInterest()); + assertFalse(newBean.isBusinessInterest()); + assertFalse(newBean.isScienceNewsInterest()); + assertFalse(newBean.isSportsInterest()); + } } diff --git a/composite/pom.xml b/composite/pom.xml index d9893de05..7beb910d9 100644 --- a/composite/pom.xml +++ b/composite/pom.xml @@ -34,6 +34,14 @@ composite + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/composite/src/main/java/com/iluwatar/composite/App.java b/composite/src/main/java/com/iluwatar/composite/App.java index d890328de..366ceffa4 100644 --- a/composite/src/main/java/com/iluwatar/composite/App.java +++ b/composite/src/main/java/com/iluwatar/composite/App.java @@ -35,7 +35,6 @@ import lombok.extern.slf4j.Slf4j; * *

In this example we have sentences composed of words composed of letters. All of the objects * can be treated through the same interface ({@link LetterComposite}). - * */ @Slf4j public class App { diff --git a/composite/src/main/java/com/iluwatar/composite/Letter.java b/composite/src/main/java/com/iluwatar/composite/Letter.java index 152299d3c..4adcba864 100644 --- a/composite/src/main/java/com/iluwatar/composite/Letter.java +++ b/composite/src/main/java/com/iluwatar/composite/Letter.java @@ -26,9 +26,7 @@ package com.iluwatar.composite; import lombok.RequiredArgsConstructor; -/** - * Letter. - */ +/** Letter. */ @RequiredArgsConstructor public class Letter extends LetterComposite { diff --git a/composite/src/main/java/com/iluwatar/composite/LetterComposite.java b/composite/src/main/java/com/iluwatar/composite/LetterComposite.java index 2b11d1cc4..a5b0d1cc3 100644 --- a/composite/src/main/java/com/iluwatar/composite/LetterComposite.java +++ b/composite/src/main/java/com/iluwatar/composite/LetterComposite.java @@ -27,9 +27,7 @@ package com.iluwatar.composite; import java.util.ArrayList; import java.util.List; -/** - * Composite interface. - */ +/** Composite interface. */ public abstract class LetterComposite { private final List children = new ArrayList<>(); @@ -42,15 +40,11 @@ public abstract class LetterComposite { return children.size(); } - protected void printThisBefore() { - } + protected void printThisBefore() {} - protected void printThisAfter() { - } + protected void printThisAfter() {} - /** - * Print. - */ + /** Print. */ public void print() { printThisBefore(); children.forEach(LetterComposite::print); diff --git a/composite/src/main/java/com/iluwatar/composite/Messenger.java b/composite/src/main/java/com/iluwatar/composite/Messenger.java index 011f91b82..3af972bc6 100644 --- a/composite/src/main/java/com/iluwatar/composite/Messenger.java +++ b/composite/src/main/java/com/iluwatar/composite/Messenger.java @@ -26,42 +26,37 @@ package com.iluwatar.composite; import java.util.List; -/** - * Messenger. - */ +/** Messenger. */ public class Messenger { LetterComposite messageFromOrcs() { - var words = List.of( - new Word('W', 'h', 'e', 'r', 'e'), - new Word('t', 'h', 'e', 'r', 'e'), - new Word('i', 's'), - new Word('a'), - new Word('w', 'h', 'i', 'p'), - new Word('t', 'h', 'e', 'r', 'e'), - new Word('i', 's'), - new Word('a'), - new Word('w', 'a', 'y') - ); + var words = + List.of( + new Word('W', 'h', 'e', 'r', 'e'), + new Word('t', 'h', 'e', 'r', 'e'), + new Word('i', 's'), + new Word('a'), + new Word('w', 'h', 'i', 'p'), + new Word('t', 'h', 'e', 'r', 'e'), + new Word('i', 's'), + new Word('a'), + new Word('w', 'a', 'y')); return new Sentence(words); - } LetterComposite messageFromElves() { - var words = List.of( - new Word('M', 'u', 'c', 'h'), - new Word('w', 'i', 'n', 'd'), - new Word('p', 'o', 'u', 'r', 's'), - new Word('f', 'r', 'o', 'm'), - new Word('y', 'o', 'u', 'r'), - new Word('m', 'o', 'u', 't', 'h') - ); + var words = + List.of( + new Word('M', 'u', 'c', 'h'), + new Word('w', 'i', 'n', 'd'), + new Word('p', 'o', 'u', 'r', 's'), + new Word('f', 'r', 'o', 'm'), + new Word('y', 'o', 'u', 'r'), + new Word('m', 'o', 'u', 't', 'h')); return new Sentence(words); - } - } diff --git a/composite/src/main/java/com/iluwatar/composite/Sentence.java b/composite/src/main/java/com/iluwatar/composite/Sentence.java index 95143b83f..448d2096c 100644 --- a/composite/src/main/java/com/iluwatar/composite/Sentence.java +++ b/composite/src/main/java/com/iluwatar/composite/Sentence.java @@ -26,14 +26,10 @@ package com.iluwatar.composite; import java.util.List; -/** - * Sentence. - */ +/** Sentence. */ public class Sentence extends LetterComposite { - /** - * Constructor. - */ + /** Constructor. */ public Sentence(List words) { words.forEach(this::add); } diff --git a/composite/src/main/java/com/iluwatar/composite/Word.java b/composite/src/main/java/com/iluwatar/composite/Word.java index e84bd0791..5b0f82049 100644 --- a/composite/src/main/java/com/iluwatar/composite/Word.java +++ b/composite/src/main/java/com/iluwatar/composite/Word.java @@ -26,20 +26,17 @@ package com.iluwatar.composite; import java.util.List; -/** - * Word. - */ +/** Word. */ public class Word extends LetterComposite { - /** - * Constructor. - */ + /** Constructor. */ public Word(List letters) { letters.forEach(this::add); } /** * Constructor. + * * @param letters to include */ public Word(char... letters) { diff --git a/composite/src/test/java/com/iluwatar/composite/AppTest.java b/composite/src/test/java/com/iluwatar/composite/AppTest.java index a8cd66afe..b1c79d735 100644 --- a/composite/src/test/java/com/iluwatar/composite/AppTest.java +++ b/composite/src/test/java/com/iluwatar/composite/AppTest.java @@ -27,20 +27,17 @@ package com.iluwatar.composite; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -/** - * Application test - */ +/** Application test */ class AppTest { /** * Issue: Add at least one assertion to this test case. * - * Solution: Inserted assertion to check whether the execution of the main method in {@link App#main(String[])} - * throws an exception. + *

Solution: Inserted assertion to check whether the execution of the main method in {@link + * App#main(String[])} throws an exception. */ - @Test void shouldExecuteApplicationWithoutException() { - Assertions.assertDoesNotThrow(() -> App.main(new String[]{})); + Assertions.assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/composite/src/test/java/com/iluwatar/composite/MessengerTest.java b/composite/src/test/java/com/iluwatar/composite/MessengerTest.java index 53698ff97..b22b94cc6 100644 --- a/composite/src/test/java/com/iluwatar/composite/MessengerTest.java +++ b/composite/src/test/java/com/iluwatar/composite/MessengerTest.java @@ -33,20 +33,13 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -/** - * MessengerTest - * - */ +/** MessengerTest */ class MessengerTest { - /** - * The buffer used to capture every write to {@link System#out} - */ + /** The buffer used to capture every write to {@link System#out} */ private ByteArrayOutputStream stdOutBuffer = new ByteArrayOutputStream(); - /** - * Keep the original std-out so it can be restored after the test - */ + /** Keep the original std-out so it can be restored after the test */ private final PrintStream realStdOut = System.out; /** @@ -58,43 +51,31 @@ class MessengerTest { System.setOut(new PrintStream(stdOutBuffer)); } - /** - * Removed the mocked std-out {@link PrintStream} again from the {@link System} class - */ + /** Removed the mocked std-out {@link PrintStream} again from the {@link System} class */ @AfterEach void tearDown() { System.setOut(realStdOut); } - /** - * Test the message from the orcs - */ + /** Test the message from the orcs */ @Test void testMessageFromOrcs() { final var messenger = new Messenger(); - testMessage( - messenger.messageFromOrcs(), - "Where there is a whip there is a way." - ); + testMessage(messenger.messageFromOrcs(), "Where there is a whip there is a way."); } - /** - * Test the message from the elves - */ + /** Test the message from the elves */ @Test void testMessageFromElves() { final var messenger = new Messenger(); - testMessage( - messenger.messageFromElves(), - "Much wind pours from your mouth." - ); + testMessage(messenger.messageFromElves(), "Much wind pours from your mouth."); } /** * Test if the given composed message matches the expected message * * @param composedMessage The composed message, received from the messenger - * @param message The expected message + * @param message The expected message */ private void testMessage(final LetterComposite composedMessage, final String message) { // Test is the composed message has the correct number of words @@ -108,5 +89,4 @@ class MessengerTest { // ... and verify if the message matches with the expected one assertEquals(message, new String(this.stdOutBuffer.toByteArray()).trim()); } - } diff --git a/context-object/pom.xml b/context-object/pom.xml index 4eb0237a6..82f8862b6 100644 --- a/context-object/pom.xml +++ b/context-object/pom.xml @@ -34,6 +34,14 @@ context-object + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/context-object/src/main/java/com/iluwatar/context/object/App.java b/context-object/src/main/java/com/iluwatar/context/object/App.java index 440239f0c..f0fc505c3 100644 --- a/context-object/src/main/java/com/iluwatar/context/object/App.java +++ b/context-object/src/main/java/com/iluwatar/context/object/App.java @@ -27,12 +27,14 @@ package com.iluwatar.context.object; import lombok.extern.slf4j.Slf4j; /** - * In the context object pattern, information and data from underlying protocol-specific classes/systems is decoupled - * and stored into a protocol-independent object in an organised format. The pattern ensures the data contained within - * the context object can be shared and further structured between different layers of a software system. + * In the context object pattern, information and data from underlying protocol-specific + * classes/systems is decoupled and stored into a protocol-independent object in an organised + * format. The pattern ensures the data contained within the context object can be shared and + * further structured between different layers of a software system. * - *

In this example we show how a context object {@link ServiceContext} can be initiated, edited and passed/retrieved - * in different layers of the program ({@link LayerA}, {@link LayerB}, {@link LayerC}) through use of static methods.

+ *

In this example we show how a context object {@link ServiceContext} can be initiated, edited + * and passed/retrieved in different layers of the program ({@link LayerA}, {@link LayerB}, {@link + * LayerC}) through use of static methods. */ @Slf4j public class App { @@ -45,19 +47,21 @@ public class App { * @param args command line args */ public static void main(String[] args) { - //Initiate first layer and add service information into context + // Initiate first layer and add service information into context var layerA = new LayerA(); layerA.addAccountInfo(SERVICE); logContext(layerA.getContext()); - //Initiate second layer and preserving information retrieved in first layer through passing context object + // Initiate second layer and preserving information retrieved in first layer through passing + // context object var layerB = new LayerB(layerA); layerB.addSessionInfo(SERVICE); logContext(layerB.getContext()); - //Initiate third layer and preserving information retrieved in first and second layer through passing context object + // Initiate third layer and preserving information retrieved in first and second layer through + // passing context object var layerC = new LayerC(layerB); layerC.addSearchInfo(SERVICE); @@ -67,4 +71,4 @@ public class App { private static void logContext(ServiceContext context) { LOGGER.info("Context = {}", context); } -} \ No newline at end of file +} diff --git a/context-object/src/main/java/com/iluwatar/context/object/LayerA.java b/context-object/src/main/java/com/iluwatar/context/object/LayerA.java index 87faec2a8..4d37f0790 100644 --- a/context-object/src/main/java/com/iluwatar/context/object/LayerA.java +++ b/context-object/src/main/java/com/iluwatar/context/object/LayerA.java @@ -26,9 +26,7 @@ package com.iluwatar.context.object; import lombok.Getter; -/** - * Layer A in the context object pattern. - */ +/** Layer A in the context object pattern. */ @Getter public class LayerA { diff --git a/context-object/src/main/java/com/iluwatar/context/object/LayerB.java b/context-object/src/main/java/com/iluwatar/context/object/LayerB.java index d4991f17f..a67aba9bd 100644 --- a/context-object/src/main/java/com/iluwatar/context/object/LayerB.java +++ b/context-object/src/main/java/com/iluwatar/context/object/LayerB.java @@ -26,9 +26,7 @@ package com.iluwatar.context.object; import lombok.Getter; -/** - * Layer B in the context object pattern. - */ +/** Layer B in the context object pattern. */ @Getter public class LayerB { diff --git a/context-object/src/main/java/com/iluwatar/context/object/LayerC.java b/context-object/src/main/java/com/iluwatar/context/object/LayerC.java index 78c6dcec5..d33a62998 100644 --- a/context-object/src/main/java/com/iluwatar/context/object/LayerC.java +++ b/context-object/src/main/java/com/iluwatar/context/object/LayerC.java @@ -26,9 +26,7 @@ package com.iluwatar.context.object; import lombok.Getter; -/** - * Layer C in the context object pattern. - */ +/** Layer C in the context object pattern. */ @Getter public class LayerC { diff --git a/context-object/src/main/java/com/iluwatar/context/object/ServiceContext.java b/context-object/src/main/java/com/iluwatar/context/object/ServiceContext.java index 2092ddf78..3de91a20e 100644 --- a/context-object/src/main/java/com/iluwatar/context/object/ServiceContext.java +++ b/context-object/src/main/java/com/iluwatar/context/object/ServiceContext.java @@ -27,9 +27,7 @@ package com.iluwatar.context.object; import lombok.Getter; import lombok.Setter; -/** - * Where context objects are defined. - */ +/** Where context objects are defined. */ @Getter @Setter public class ServiceContext { diff --git a/context-object/src/main/java/com/iluwatar/context/object/ServiceContextFactory.java b/context-object/src/main/java/com/iluwatar/context/object/ServiceContextFactory.java index d7094a0c0..bee65e828 100644 --- a/context-object/src/main/java/com/iluwatar/context/object/ServiceContextFactory.java +++ b/context-object/src/main/java/com/iluwatar/context/object/ServiceContextFactory.java @@ -24,9 +24,7 @@ */ package com.iluwatar.context.object; -/** - * An interface to create context objects passed through layers. - */ +/** An interface to create context objects passed through layers. */ public class ServiceContextFactory { public static ServiceContext createContext() { diff --git a/context-object/src/test/java/com/iluwatar/contect/object/AppTest.java b/context-object/src/test/java/com/iluwatar/contect/object/AppTest.java index 9c5d72fde..2cb5e901a 100644 --- a/context-object/src/test/java/com/iluwatar/contect/object/AppTest.java +++ b/context-object/src/test/java/com/iluwatar/contect/object/AppTest.java @@ -24,16 +24,14 @@ */ package com.iluwatar.contect.object; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + import com.iluwatar.context.object.App; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; - public class AppTest { - /** - * Test example app runs without error. - */ + /** Test example app runs without error. */ @Test void shouldExecuteWithoutException() { assertDoesNotThrow(() -> App.main(new String[] {})); diff --git a/context-object/src/test/java/com/iluwatar/contect/object/ServiceContextTest.java b/context-object/src/test/java/com/iluwatar/contect/object/ServiceContextTest.java index ab72de567..fdfd56af7 100644 --- a/context-object/src/test/java/com/iluwatar/contect/object/ServiceContextTest.java +++ b/context-object/src/test/java/com/iluwatar/contect/object/ServiceContextTest.java @@ -24,6 +24,11 @@ */ package com.iluwatar.contect.object; +import static org.junit.jupiter.api.Assertions.assertAll; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; + import com.iluwatar.context.object.LayerA; import com.iluwatar.context.object.LayerB; import com.iluwatar.context.object.LayerC; @@ -31,15 +36,7 @@ import com.iluwatar.context.object.ServiceContext; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertAll; -import static org.junit.jupiter.api.Assertions.assertSame; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNull; - -/** - * ServiceContextTest - * - */ +/** ServiceContextTest */ public class ServiceContextTest { private static final String SERVICE = "SERVICE"; @@ -82,27 +79,23 @@ public class ServiceContextTest { assertAll( () -> assertNull(layerA.getContext().getAccountService()), () -> assertNull(layerA.getContext().getSearchService()), - () -> assertNull(layerA.getContext().getSessionService()) - ); + () -> assertNull(layerA.getContext().getSessionService())); layerA.addAccountInfo(SERVICE); assertAll( () -> assertEquals(SERVICE, layerA.getContext().getAccountService()), () -> assertNull(layerA.getContext().getSearchService()), - () -> assertNull(layerA.getContext().getSessionService()) - ); + () -> assertNull(layerA.getContext().getSessionService())); var layerB = new LayerB(layerA); layerB.addSessionInfo(SERVICE); assertAll( () -> assertEquals(SERVICE, layerB.getContext().getAccountService()), () -> assertEquals(SERVICE, layerB.getContext().getSessionService()), - () -> assertNull(layerB.getContext().getSearchService()) - ); + () -> assertNull(layerB.getContext().getSearchService())); var layerC = new LayerC(layerB); layerC.addSearchInfo(SERVICE); assertAll( () -> assertEquals(SERVICE, layerC.getContext().getAccountService()), () -> assertEquals(SERVICE, layerC.getContext().getSearchService()), - () -> assertEquals(SERVICE, layerC.getContext().getSessionService()) - ); + () -> assertEquals(SERVICE, layerC.getContext().getSessionService())); } } diff --git a/converter/pom.xml b/converter/pom.xml index c26e68dd1..525237ed1 100644 --- a/converter/pom.xml +++ b/converter/pom.xml @@ -34,6 +34,14 @@ converter 4.0.0 + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/converter/src/main/java/com/iluwatar/converter/App.java b/converter/src/main/java/com/iluwatar/converter/App.java index 38d4f101d..100913501 100644 --- a/converter/src/main/java/com/iluwatar/converter/App.java +++ b/converter/src/main/java/com/iluwatar/converter/App.java @@ -48,11 +48,11 @@ public class App { User user = userConverter.convertFromDto(dtoUser); LOGGER.info("Entity converted from DTO: {}", user); - var users = List.of( - new User("Camile", "Tough", false, "124sad"), - new User("Marti", "Luther", true, "42309fd"), - new User("Kate", "Smith", true, "if0243") - ); + var users = + List.of( + new User("Camile", "Tough", false, "124sad"), + new User("Marti", "Luther", true, "42309fd"), + new User("Kate", "Smith", true, "if0243")); LOGGER.info("Domain entities:"); users.stream().map(User::toString).forEach(LOGGER::info); diff --git a/converter/src/main/java/com/iluwatar/converter/Converter.java b/converter/src/main/java/com/iluwatar/converter/Converter.java index bd7a73f98..374b2ce5d 100644 --- a/converter/src/main/java/com/iluwatar/converter/Converter.java +++ b/converter/src/main/java/com/iluwatar/converter/Converter.java @@ -86,5 +86,4 @@ public class Converter { public final List createFromEntities(final Collection entities) { return entities.stream().map(this::convertFromEntity).toList(); } - } diff --git a/converter/src/main/java/com/iluwatar/converter/User.java b/converter/src/main/java/com/iluwatar/converter/User.java index a8287af76..9f68047f1 100644 --- a/converter/src/main/java/com/iluwatar/converter/User.java +++ b/converter/src/main/java/com/iluwatar/converter/User.java @@ -24,7 +24,5 @@ */ package com.iluwatar.converter; -/** - * User record. - */ +/** User record. */ public record User(String firstName, String lastName, boolean active, String userId) {} diff --git a/converter/src/main/java/com/iluwatar/converter/UserConverter.java b/converter/src/main/java/com/iluwatar/converter/UserConverter.java index 4ded63712..f7dbd3138 100644 --- a/converter/src/main/java/com/iluwatar/converter/UserConverter.java +++ b/converter/src/main/java/com/iluwatar/converter/UserConverter.java @@ -24,9 +24,7 @@ */ package com.iluwatar.converter; -/** - * Example implementation of the simple User converter. - */ +/** Example implementation of the simple User converter. */ public class UserConverter extends Converter { public UserConverter() { diff --git a/converter/src/main/java/com/iluwatar/converter/UserDto.java b/converter/src/main/java/com/iluwatar/converter/UserDto.java index 9703292b7..dc1d861dd 100644 --- a/converter/src/main/java/com/iluwatar/converter/UserDto.java +++ b/converter/src/main/java/com/iluwatar/converter/UserDto.java @@ -24,7 +24,5 @@ */ package com.iluwatar.converter; -/** - * UserDto record. - */ +/** UserDto record. */ public record UserDto(String firstName, String lastName, boolean active, String email) {} diff --git a/converter/src/test/java/com/iluwatar/converter/AppTest.java b/converter/src/test/java/com/iluwatar/converter/AppTest.java index c22a0e7d6..366adef7b 100644 --- a/converter/src/test/java/com/iluwatar/converter/AppTest.java +++ b/converter/src/test/java/com/iluwatar/converter/AppTest.java @@ -24,25 +24,20 @@ */ package com.iluwatar.converter; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -/** - * App running test - */ +import org.junit.jupiter.api.Test; + +/** App running test */ class AppTest { /** - * Issue: Add at least one assertion to this test case. - * Solution: Inserted assertion to check whether the execution of the main method in {@link App#main(String[])} - * throws an exception. + * Issue: Add at least one assertion to this test case. Solution: Inserted assertion to check + * whether the execution of the main method in {@link App#main(String[])} throws an exception. */ - @Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } - } diff --git a/converter/src/test/java/com/iluwatar/converter/ConverterTest.java b/converter/src/test/java/com/iluwatar/converter/ConverterTest.java index d2f9c6a85..da14e3e5a 100644 --- a/converter/src/test/java/com/iluwatar/converter/ConverterTest.java +++ b/converter/src/test/java/com/iluwatar/converter/ConverterTest.java @@ -30,16 +30,12 @@ import java.util.List; import java.util.Random; import org.junit.jupiter.api.Test; -/** - * Tests for {@link Converter} - */ +/** Tests for {@link Converter} */ class ConverterTest { private final UserConverter userConverter = new UserConverter(); - /** - * Tests whether a converter created of opposite functions holds equality as a bijection. - */ + /** Tests whether a converter created of opposite functions holds equality as a bijection. */ @Test void testConversionsStartingFromDomain() { var u1 = new User("Tom", "Hanks", true, "tom@hanks.com"); @@ -47,9 +43,7 @@ class ConverterTest { assertEquals(u1, u2); } - /** - * Tests whether a converter created of opposite functions holds equality as a bijection. - */ + /** Tests whether a converter created of opposite functions holds equality as a bijection. */ @Test void testConversionsStartingFromDto() { var u1 = new UserDto("Tom", "Hanks", true, "tom@hanks.com"); @@ -63,19 +57,22 @@ class ConverterTest { */ @Test void testCustomConverter() { - var converter = new Converter( - userDto -> new User( - userDto.firstName(), - userDto.lastName(), - userDto.active(), - String.valueOf(new Random().nextInt()) - ), - user -> new UserDto( - user.firstName(), - user.lastName(), - user.active(), - user.firstName().toLowerCase() + user.lastName().toLowerCase() + "@whatever.com") - ); + var converter = + new Converter( + userDto -> + new User( + userDto.firstName(), + userDto.lastName(), + userDto.active(), + String.valueOf(new Random().nextInt())), + user -> + new UserDto( + user.firstName(), + user.lastName(), + user.active(), + user.firstName().toLowerCase() + + user.lastName().toLowerCase() + + "@whatever.com")); var u1 = new User("John", "Doe", false, "12324"); var userDto = converter.convertFromEntity(u1); assertEquals("johndoe@whatever.com", userDto.email()); @@ -87,11 +84,11 @@ class ConverterTest { */ @Test void testCollectionConversion() { - var users = List.of( - new User("Camile", "Tough", false, "124sad"), - new User("Marti", "Luther", true, "42309fd"), - new User("Kate", "Smith", true, "if0243") - ); + var users = + List.of( + new User("Camile", "Tough", false, "124sad"), + new User("Marti", "Luther", true, "42309fd"), + new User("Kate", "Smith", true, "if0243")); var fromDtos = userConverter.createFromDtos(userConverter.createFromEntities(users)); assertEquals(users, fromDtos); } diff --git a/curiously-recurring-template-pattern/pom.xml b/curiously-recurring-template-pattern/pom.xml index 5f2227684..ab7ed0b19 100644 --- a/curiously-recurring-template-pattern/pom.xml +++ b/curiously-recurring-template-pattern/pom.xml @@ -36,6 +36,14 @@ curiously-recurring-template-pattern + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/curiously-recurring-template-pattern/src/main/java/crtp/App.java b/curiously-recurring-template-pattern/src/main/java/crtp/App.java index a9683115e..d592dd717 100644 --- a/curiously-recurring-template-pattern/src/main/java/crtp/App.java +++ b/curiously-recurring-template-pattern/src/main/java/crtp/App.java @@ -40,12 +40,16 @@ public class App { */ public static void main(String[] args) { - MmaBantamweightFighter fighter1 = new MmaBantamweightFighter("Joe", "Johnson", "The Geek", "Muay Thai"); - MmaBantamweightFighter fighter2 = new MmaBantamweightFighter("Ed", "Edwards", "The Problem Solver", "Judo"); + MmaBantamweightFighter fighter1 = + new MmaBantamweightFighter("Joe", "Johnson", "The Geek", "Muay Thai"); + MmaBantamweightFighter fighter2 = + new MmaBantamweightFighter("Ed", "Edwards", "The Problem Solver", "Judo"); fighter1.fight(fighter2); - MmaHeavyweightFighter fighter3 = new MmaHeavyweightFighter("Dave", "Davidson", "The Bug Smasher", "Kickboxing"); - MmaHeavyweightFighter fighter4 = new MmaHeavyweightFighter("Jack", "Jackson", "The Pragmatic", "Brazilian Jiu-Jitsu"); + MmaHeavyweightFighter fighter3 = + new MmaHeavyweightFighter("Dave", "Davidson", "The Bug Smasher", "Kickboxing"); + MmaHeavyweightFighter fighter4 = + new MmaHeavyweightFighter("Jack", "Jackson", "The Pragmatic", "Brazilian Jiu-Jitsu"); fighter3.fight(fighter4); } } diff --git a/curiously-recurring-template-pattern/src/main/java/crtp/Fighter.java b/curiously-recurring-template-pattern/src/main/java/crtp/Fighter.java index 40a7367ce..da149229c 100644 --- a/curiously-recurring-template-pattern/src/main/java/crtp/Fighter.java +++ b/curiously-recurring-template-pattern/src/main/java/crtp/Fighter.java @@ -32,5 +32,4 @@ package crtp; public interface Fighter { void fight(T t); - } diff --git a/curiously-recurring-template-pattern/src/main/java/crtp/MmaBantamweightFighter.java b/curiously-recurring-template-pattern/src/main/java/crtp/MmaBantamweightFighter.java index 25258c8bc..08886a3b3 100644 --- a/curiously-recurring-template-pattern/src/main/java/crtp/MmaBantamweightFighter.java +++ b/curiously-recurring-template-pattern/src/main/java/crtp/MmaBantamweightFighter.java @@ -24,13 +24,10 @@ */ package crtp; -/** - * MmaBantamweightFighter class. - */ +/** MmaBantamweightFighter class. */ class MmaBantamweightFighter extends MmaFighter { public MmaBantamweightFighter(String name, String surname, String nickName, String speciality) { super(name, surname, nickName, speciality); } - -} \ No newline at end of file +} diff --git a/curiously-recurring-template-pattern/src/main/java/crtp/MmaHeavyweightFighter.java b/curiously-recurring-template-pattern/src/main/java/crtp/MmaHeavyweightFighter.java index 74c1f9147..1ed545ede 100644 --- a/curiously-recurring-template-pattern/src/main/java/crtp/MmaHeavyweightFighter.java +++ b/curiously-recurring-template-pattern/src/main/java/crtp/MmaHeavyweightFighter.java @@ -24,13 +24,10 @@ */ package crtp; -/** - * MmaHeavyweightFighter. - */ +/** MmaHeavyweightFighter. */ public class MmaHeavyweightFighter extends MmaFighter { public MmaHeavyweightFighter(String name, String surname, String nickName, String speciality) { super(name, surname, nickName, speciality); } - } diff --git a/curiously-recurring-template-pattern/src/main/java/crtp/MmaLightweightFighter.java b/curiously-recurring-template-pattern/src/main/java/crtp/MmaLightweightFighter.java index 4a3d606a8..433b1934f 100644 --- a/curiously-recurring-template-pattern/src/main/java/crtp/MmaLightweightFighter.java +++ b/curiously-recurring-template-pattern/src/main/java/crtp/MmaLightweightFighter.java @@ -24,13 +24,10 @@ */ package crtp; -/** - * MmaLightweightFighter class. - */ +/** MmaLightweightFighter class. */ class MmaLightweightFighter extends MmaFighter { public MmaLightweightFighter(String name, String surname, String nickName, String speciality) { super(name, surname, nickName, speciality); } - } diff --git a/curiously-recurring-template-pattern/src/test/java/crtp/AppTest.java b/curiously-recurring-template-pattern/src/test/java/crtp/AppTest.java index ee3e79786..fb19aa31a 100644 --- a/curiously-recurring-template-pattern/src/test/java/crtp/AppTest.java +++ b/curiously-recurring-template-pattern/src/test/java/crtp/AppTest.java @@ -28,13 +28,11 @@ import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import org.junit.jupiter.api.Test; -/** - * Application test - */ +/** Application test */ class AppTest { @Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/curiously-recurring-template-pattern/src/test/java/crtp/FightTest.java b/curiously-recurring-template-pattern/src/test/java/crtp/FightTest.java index 279730d48..a70edd0d6 100644 --- a/curiously-recurring-template-pattern/src/test/java/crtp/FightTest.java +++ b/curiously-recurring-template-pattern/src/test/java/crtp/FightTest.java @@ -24,37 +24,38 @@ */ package crtp; -import lombok.extern.slf4j.Slf4j; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.ArrayList; import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; +import lombok.extern.slf4j.Slf4j; +import org.junit.jupiter.api.Test; @Slf4j public class FightTest { /** - * A fighter has signed a contract with a promotion, and he will face some other fighters. A list of opponents is ready - * but for some reason not all of them belong to the same weight class. Let's ensure that the fighter will only face - * opponents in the same weight class. + * A fighter has signed a contract with a promotion, and he will face some other fighters. A list + * of opponents is ready but for some reason not all of them belong to the same weight class. + * Let's ensure that the fighter will only face opponents in the same weight class. */ @Test void testFighterCanFightOnlyAgainstSameWeightOpponents() { - MmaBantamweightFighter fighter = new MmaBantamweightFighter("Joe", "Johnson", "The Geek", "Muay Thai"); + MmaBantamweightFighter fighter = + new MmaBantamweightFighter("Joe", "Johnson", "The Geek", "Muay Thai"); List> opponents = getOpponents(); List> challenged = new ArrayList<>(); - opponents.forEach(challenger -> { - try { - ((MmaBantamweightFighter) challenger).fight(fighter); - challenged.add(challenger); - } catch (ClassCastException e) { - LOGGER.error(e.getMessage()); - } - }); + opponents.forEach( + challenger -> { + try { + ((MmaBantamweightFighter) challenger).fight(fighter); + challenged.add(challenger); + } catch (ClassCastException e) { + LOGGER.error(e.getMessage()); + } + }); assertFalse(challenged.isEmpty()); assertTrue(challenged.stream().allMatch(c -> c instanceof MmaBantamweightFighter)); @@ -62,13 +63,10 @@ public class FightTest { private static List> getOpponents() { return List.of( - new MmaBantamweightFighter("Ed", "Edwards", "The Problem Solver", "Judo"), - new MmaLightweightFighter("Evan", "Evans", "Clean Coder", "Sambo"), - new MmaHeavyweightFighter("Dave", "Davidson", "The Bug Smasher", "Kickboxing"), - new MmaBantamweightFighter("Ray", "Raymond", "Scrum Master", "Karate"), - new MmaHeavyweightFighter("Jack", "Jackson", "The Pragmatic", "Brazilian Jiu-Jitsu") - ); + new MmaBantamweightFighter("Ed", "Edwards", "The Problem Solver", "Judo"), + new MmaLightweightFighter("Evan", "Evans", "Clean Coder", "Sambo"), + new MmaHeavyweightFighter("Dave", "Davidson", "The Bug Smasher", "Kickboxing"), + new MmaBantamweightFighter("Ray", "Raymond", "Scrum Master", "Karate"), + new MmaHeavyweightFighter("Jack", "Jackson", "The Pragmatic", "Brazilian Jiu-Jitsu")); } - - } diff --git a/currying/pom.xml b/currying/pom.xml index 5b5385c45..5244aa279 100644 --- a/currying/pom.xml +++ b/currying/pom.xml @@ -36,6 +36,14 @@ currying + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/currying/src/main/java/com/iluwatar/currying/App.java b/currying/src/main/java/com/iluwatar/currying/App.java index d3ca262b5..d91988753 100644 --- a/currying/src/main/java/com/iluwatar/currying/App.java +++ b/currying/src/main/java/com/iluwatar/currying/App.java @@ -28,19 +28,17 @@ import java.time.LocalDate; import lombok.extern.slf4j.Slf4j; /** -* Currying decomposes a function with multiple arguments in multiple functions that -* take a single argument. A curried function which has only been passed some of its -* arguments is called a partial application. Partial application is useful since it can -* be used to create specialised functions in a concise way. -* -*

In this example, a librarian uses a curried book builder function create books belonging to -* desired genres and written by specific authors. -*/ + * Currying decomposes a function with multiple arguments in multiple functions that take a single + * argument. A curried function which has only been passed some of its arguments is called a partial + * application. Partial application is useful since it can be used to create specialised functions + * in a concise way. + * + *

In this example, a librarian uses a curried book builder function create books belonging to + * desired genres and written by specific authors. + */ @Slf4j public class App { - /** - * Main entry point of the program. - */ + /** Main entry point of the program. */ public static void main(String[] args) { LOGGER.info("Librarian begins their work."); @@ -55,20 +53,28 @@ public class App { Book.AddTitle rowlingFantasyBooksFunc = fantasyBookFunc.withAuthor("J.K. Rowling"); // Creates books by Stephen King (horror and fantasy genres) - Book shining = kingHorrorBooksFunc.withTitle("The Shining") - .withPublicationDate(LocalDate.of(1977, 1, 28)); - Book darkTower = kingFantasyBooksFunc.withTitle("The Dark Tower: Gunslinger") + Book shining = + kingHorrorBooksFunc.withTitle("The Shining").withPublicationDate(LocalDate.of(1977, 1, 28)); + Book darkTower = + kingFantasyBooksFunc + .withTitle("The Dark Tower: Gunslinger") .withPublicationDate(LocalDate.of(1982, 6, 10)); // Creates fantasy books by J.K. Rowling - Book chamberOfSecrets = rowlingFantasyBooksFunc.withTitle("Harry Potter and the Chamber of Secrets") + Book chamberOfSecrets = + rowlingFantasyBooksFunc + .withTitle("Harry Potter and the Chamber of Secrets") .withPublicationDate(LocalDate.of(1998, 7, 2)); // Create sci-fi books - Book dune = scifiBookFunc.withAuthor("Frank Herbert") + Book dune = + scifiBookFunc + .withAuthor("Frank Herbert") .withTitle("Dune") .withPublicationDate(LocalDate.of(1965, 8, 1)); - Book foundation = scifiBookFunc.withAuthor("Isaac Asimov") + Book foundation = + scifiBookFunc + .withAuthor("Isaac Asimov") .withTitle("Foundation") .withPublicationDate(LocalDate.of(1942, 5, 1)); @@ -83,4 +89,4 @@ public class App { LOGGER.info(dune.toString()); LOGGER.info(foundation.toString()); } -} \ No newline at end of file +} diff --git a/currying/src/main/java/com/iluwatar/currying/Book.java b/currying/src/main/java/com/iluwatar/currying/Book.java index f9b7be051..7ec4ed8cb 100644 --- a/currying/src/main/java/com/iluwatar/currying/Book.java +++ b/currying/src/main/java/com/iluwatar/currying/Book.java @@ -29,9 +29,7 @@ import java.util.Objects; import java.util.function.Function; import lombok.AllArgsConstructor; -/** - * Book class. - */ +/** Book class. */ @AllArgsConstructor public class Book { private final Genre genre; @@ -49,9 +47,9 @@ public class Book { } Book book = (Book) o; return Objects.equals(author, book.author) - && Objects.equals(genre, book.genre) - && Objects.equals(title, book.title) - && Objects.equals(publicationDate, book.publicationDate); + && Objects.equals(genre, book.genre) + && Objects.equals(title, book.title) + && Objects.equals(publicationDate, book.publicationDate); } @Override @@ -61,57 +59,55 @@ public class Book { @Override public String toString() { - return "Book{" + "genre=" + genre + ", author='" + author + '\'' - + ", title='" + title + '\'' + ", publicationDate=" + publicationDate + '}'; + return "Book{" + + "genre=" + + genre + + ", author='" + + author + + '\'' + + ", title='" + + title + + '\'' + + ", publicationDate=" + + publicationDate + + '}'; } - /** - * Curried book builder/creator function. - */ - static Function>>> book_creator - = bookGenre - -> bookAuthor - -> bookTitle - -> bookPublicationDate - -> new Book(bookGenre, bookAuthor, bookTitle, bookPublicationDate); + /** Curried book builder/creator function. */ + static Function>>> + book_creator = + bookGenre -> + bookAuthor -> + bookTitle -> + bookPublicationDate -> + new Book(bookGenre, bookAuthor, bookTitle, bookPublicationDate); /** * Implements the builder pattern using functional interfaces to create a more readable book * creator function. This function is equivalent to the BOOK_CREATOR function. */ public static AddGenre builder() { - return genre - -> author - -> title - -> publicationDate - -> new Book(genre, author, title, publicationDate); + return genre -> + author -> title -> publicationDate -> new Book(genre, author, title, publicationDate); } - /** - * Functional interface which adds the genre to a book. - */ + /** Functional interface which adds the genre to a book. */ public interface AddGenre { Book.AddAuthor withGenre(Genre genre); } - /** - * Functional interface which adds the author to a book. - */ + /** Functional interface which adds the author to a book. */ public interface AddAuthor { Book.AddTitle withAuthor(String author); } - /** - * Functional interface which adds the title to a book. - */ + /** Functional interface which adds the title to a book. */ public interface AddTitle { Book.AddPublicationDate withTitle(String title); } - /** - * Functional interface which adds the publication date to a book. - */ + /** Functional interface which adds the publication date to a book. */ public interface AddPublicationDate { Book withPublicationDate(LocalDate publicationDate); } -} \ No newline at end of file +} diff --git a/currying/src/main/java/com/iluwatar/currying/Genre.java b/currying/src/main/java/com/iluwatar/currying/Genre.java index 8e9fbfd63..ad41f4004 100644 --- a/currying/src/main/java/com/iluwatar/currying/Genre.java +++ b/currying/src/main/java/com/iluwatar/currying/Genre.java @@ -24,9 +24,7 @@ */ package com.iluwatar.currying; -/** - * Enum representing different book genres. - */ +/** Enum representing different book genres. */ public enum Genre { FANTASY, HORROR, diff --git a/currying/src/test/java/com/iluwatar/currying/AppTest.java b/currying/src/test/java/com/iluwatar/currying/AppTest.java index 83fd99363..3074628f2 100644 --- a/currying/src/test/java/com/iluwatar/currying/AppTest.java +++ b/currying/src/test/java/com/iluwatar/currying/AppTest.java @@ -28,12 +28,10 @@ import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; -/** - * Tests that the App can be run without throwing any exceptions. - */ +/** Tests that the App can be run without throwing any exceptions. */ class AppTest { @Test void executesWithoutExceptions() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/currying/src/test/java/com/iluwatar/currying/BookCurryingTest.java b/currying/src/test/java/com/iluwatar/currying/BookCurryingTest.java index 74ac4ead3..f22ff6285 100644 --- a/currying/src/test/java/com/iluwatar/currying/BookCurryingTest.java +++ b/currying/src/test/java/com/iluwatar/currying/BookCurryingTest.java @@ -26,36 +26,31 @@ package com.iluwatar.currying; import static org.junit.jupiter.api.Assertions.*; +import java.time.LocalDate; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; -import java.time.LocalDate; -/** - * Unit tests for the Book class - */ +/** Unit tests for the Book class */ class BookCurryingTest { private static Book expectedBook; @BeforeAll public static void initialiseBook() { - expectedBook = new Book(Genre.FANTASY, - "Dave", - "Into the Night", - LocalDate.of(2002, 4, 7)); + expectedBook = new Book(Genre.FANTASY, "Dave", "Into the Night", LocalDate.of(2002, 4, 7)); } - /** - * Tests that the expected book can be created via curried functions - */ + /** Tests that the expected book can be created via curried functions */ @Test void createsExpectedBook() { - Book builderCurriedBook = Book.builder() - .withGenre(Genre.FANTASY) - .withAuthor("Dave") - .withTitle("Into the Night") - .withPublicationDate(LocalDate.of(2002, 4, 7)); + Book builderCurriedBook = + Book.builder() + .withGenre(Genre.FANTASY) + .withAuthor("Dave") + .withTitle("Into the Night") + .withPublicationDate(LocalDate.of(2002, 4, 7)); - Book funcCurriedBook = Book.book_creator + Book funcCurriedBook = + Book.book_creator .apply(Genre.FANTASY) .apply("Dave") .apply("Into the Night") @@ -65,17 +60,15 @@ class BookCurryingTest { assertEquals(expectedBook, funcCurriedBook); } - /** - * Tests that an intermediate curried function can be used to create the expected book - */ + /** Tests that an intermediate curried function can be used to create the expected book */ @Test void functionCreatesExpectedBook() { - Book.AddTitle daveFantasyBookFunc = Book.builder() - .withGenre(Genre.FANTASY) - .withAuthor("Dave"); + Book.AddTitle daveFantasyBookFunc = Book.builder().withGenre(Genre.FANTASY).withAuthor("Dave"); - Book curriedBook = daveFantasyBookFunc.withTitle("Into the Night") - .withPublicationDate(LocalDate.of(2002, 4, 7)); + Book curriedBook = + daveFantasyBookFunc + .withTitle("Into the Night") + .withPublicationDate(LocalDate.of(2002, 4, 7)); assertEquals(expectedBook, curriedBook); } diff --git a/data-access-object/pom.xml b/data-access-object/pom.xml index 9685cbb96..f96bf54cd 100644 --- a/data-access-object/pom.xml +++ b/data-access-object/pom.xml @@ -34,6 +34,14 @@ data-access-object + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/data-access-object/src/main/java/com/iluwatar/dao/App.java b/data-access-object/src/main/java/com/iluwatar/dao/App.java index f0d19749c..106b7458c 100644 --- a/data-access-object/src/main/java/com/iluwatar/dao/App.java +++ b/data-access-object/src/main/java/com/iluwatar/dao/App.java @@ -66,14 +66,14 @@ public class App { private static void deleteSchema(DataSource dataSource) throws SQLException { try (var connection = dataSource.getConnection(); - var statement = connection.createStatement()) { + var statement = connection.createStatement()) { statement.execute(CustomerSchemaSql.DELETE_SCHEMA_SQL); } } private static void createSchema(DataSource dataSource) throws SQLException { try (var connection = dataSource.getConnection(); - var statement = connection.createStatement()) { + var statement = connection.createStatement()) { statement.execute(CustomerSchemaSql.CREATE_SCHEMA_SQL); } } diff --git a/data-access-object/src/main/java/com/iluwatar/dao/CustomException.java b/data-access-object/src/main/java/com/iluwatar/dao/CustomException.java index de907a641..79470bd81 100644 --- a/data-access-object/src/main/java/com/iluwatar/dao/CustomException.java +++ b/data-access-object/src/main/java/com/iluwatar/dao/CustomException.java @@ -26,13 +26,10 @@ package com.iluwatar.dao; import java.io.Serial; -/** - * Custom exception. - */ +/** Custom exception. */ public class CustomException extends Exception { - @Serial - private static final long serialVersionUID = 1L; + @Serial private static final long serialVersionUID = 1L; public CustomException(String message, Throwable cause) { super(message, cause); diff --git a/data-access-object/src/main/java/com/iluwatar/dao/Customer.java b/data-access-object/src/main/java/com/iluwatar/dao/Customer.java index 89e0bfb5e..17a15fc1b 100644 --- a/data-access-object/src/main/java/com/iluwatar/dao/Customer.java +++ b/data-access-object/src/main/java/com/iluwatar/dao/Customer.java @@ -30,9 +30,7 @@ import lombok.Getter; import lombok.Setter; import lombok.ToString; -/** - * A customer POJO that represents the data that will be read from the data source. - */ +/** A customer POJO that represents the data that will be read from the data source. */ @Setter @Getter @ToString @@ -40,8 +38,7 @@ import lombok.ToString; @AllArgsConstructor public class Customer { - @EqualsAndHashCode.Include - private int id; + @EqualsAndHashCode.Include private int id; private String firstName; private String lastName; } diff --git a/data-access-object/src/main/java/com/iluwatar/dao/CustomerSchemaSql.java b/data-access-object/src/main/java/com/iluwatar/dao/CustomerSchemaSql.java index 501b4155a..aab41423a 100644 --- a/data-access-object/src/main/java/com/iluwatar/dao/CustomerSchemaSql.java +++ b/data-access-object/src/main/java/com/iluwatar/dao/CustomerSchemaSql.java @@ -24,18 +24,13 @@ */ package com.iluwatar.dao; -/** - * Customer Schema SQL Class. - */ +/** Customer Schema SQL Class. */ public final class CustomerSchemaSql { - private CustomerSchemaSql() { - } + private CustomerSchemaSql() {} public static final String CREATE_SCHEMA_SQL = - "CREATE TABLE CUSTOMERS (ID NUMBER, FNAME VARCHAR(100), " - + "LNAME VARCHAR(100))"; + "CREATE TABLE CUSTOMERS (ID NUMBER, FNAME VARCHAR(100), " + "LNAME VARCHAR(100))"; public static final String DELETE_SCHEMA_SQL = "DROP TABLE CUSTOMERS"; - } diff --git a/data-access-object/src/main/java/com/iluwatar/dao/DbCustomerDao.java b/data-access-object/src/main/java/com/iluwatar/dao/DbCustomerDao.java index f369cb69e..cb75b195d 100644 --- a/data-access-object/src/main/java/com/iluwatar/dao/DbCustomerDao.java +++ b/data-access-object/src/main/java/com/iluwatar/dao/DbCustomerDao.java @@ -38,9 +38,7 @@ import javax.sql.DataSource; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; -/** - * An implementation of {@link CustomerDao} that persists customers in RDBMS. - */ +/** An implementation of {@link CustomerDao} that persists customers in RDBMS. */ @Slf4j @RequiredArgsConstructor public class DbCustomerDao implements CustomerDao { @@ -60,22 +58,24 @@ public class DbCustomerDao implements CustomerDao { var connection = getConnection(); var statement = connection.prepareStatement("SELECT * FROM CUSTOMERS"); // NOSONAR var resultSet = statement.executeQuery(); // NOSONAR - return StreamSupport.stream(new Spliterators.AbstractSpliterator(Long.MAX_VALUE, - Spliterator.ORDERED) { + return StreamSupport.stream( + new Spliterators.AbstractSpliterator(Long.MAX_VALUE, Spliterator.ORDERED) { - @Override - public boolean tryAdvance(Consumer action) { - try { - if (!resultSet.next()) { - return false; - } - action.accept(createCustomer(resultSet)); - return true; - } catch (SQLException e) { - throw new RuntimeException(e); // NOSONAR - } - } - }, false).onClose(() -> mutedClose(connection, statement, resultSet)); + @Override + public boolean tryAdvance(Consumer action) { + try { + if (!resultSet.next()) { + return false; + } + action.accept(createCustomer(resultSet)); + return true; + } catch (SQLException e) { + throw new RuntimeException(e); // NOSONAR + } + } + }, + false) + .onClose(() -> mutedClose(connection, statement, resultSet)); } catch (SQLException e) { throw new CustomException(e.getMessage(), e); } @@ -96,21 +96,18 @@ public class DbCustomerDao implements CustomerDao { } private Customer createCustomer(ResultSet resultSet) throws SQLException { - return new Customer(resultSet.getInt("ID"), - resultSet.getString("FNAME"), - resultSet.getString("LNAME")); + return new Customer( + resultSet.getInt("ID"), resultSet.getString("FNAME"), resultSet.getString("LNAME")); } - /** - * {@inheritDoc} - */ + /** {@inheritDoc} */ @Override public Optional getById(int id) throws Exception { ResultSet resultSet = null; try (var connection = getConnection(); - var statement = connection.prepareStatement("SELECT * FROM CUSTOMERS WHERE ID = ?")) { + var statement = connection.prepareStatement("SELECT * FROM CUSTOMERS WHERE ID = ?")) { statement.setInt(1, id); resultSet = statement.executeQuery(); @@ -128,9 +125,7 @@ public class DbCustomerDao implements CustomerDao { } } - /** - * {@inheritDoc} - */ + /** {@inheritDoc} */ @Override public boolean add(Customer customer) throws Exception { if (getById(customer.getId()).isPresent()) { @@ -138,7 +133,7 @@ public class DbCustomerDao implements CustomerDao { } try (var connection = getConnection(); - var statement = connection.prepareStatement("INSERT INTO CUSTOMERS VALUES (?,?,?)")) { + var statement = connection.prepareStatement("INSERT INTO CUSTOMERS VALUES (?,?,?)")) { statement.setInt(1, customer.getId()); statement.setString(2, customer.getFirstName()); statement.setString(3, customer.getLastName()); @@ -149,15 +144,12 @@ public class DbCustomerDao implements CustomerDao { } } - /** - * {@inheritDoc} - */ + /** {@inheritDoc} */ @Override public boolean update(Customer customer) throws Exception { try (var connection = getConnection(); - var statement = - connection - .prepareStatement("UPDATE CUSTOMERS SET FNAME = ?, LNAME = ? WHERE ID = ?")) { + var statement = + connection.prepareStatement("UPDATE CUSTOMERS SET FNAME = ?, LNAME = ? WHERE ID = ?")) { statement.setString(1, customer.getFirstName()); statement.setString(2, customer.getLastName()); statement.setInt(3, customer.getId()); @@ -167,13 +159,11 @@ public class DbCustomerDao implements CustomerDao { } } - /** - * {@inheritDoc} - */ + /** {@inheritDoc} */ @Override public boolean delete(Customer customer) throws Exception { try (var connection = getConnection(); - var statement = connection.prepareStatement("DELETE FROM CUSTOMERS WHERE ID = ?")) { + var statement = connection.prepareStatement("DELETE FROM CUSTOMERS WHERE ID = ?")) { statement.setInt(1, customer.getId()); return statement.executeUpdate() > 0; } catch (SQLException ex) { diff --git a/data-access-object/src/main/java/com/iluwatar/dao/InMemoryCustomerDao.java b/data-access-object/src/main/java/com/iluwatar/dao/InMemoryCustomerDao.java index 19979ff66..b5b7eb0c4 100644 --- a/data-access-object/src/main/java/com/iluwatar/dao/InMemoryCustomerDao.java +++ b/data-access-object/src/main/java/com/iluwatar/dao/InMemoryCustomerDao.java @@ -31,17 +31,14 @@ import java.util.stream.Stream; /** * An in memory implementation of {@link CustomerDao}, which stores the customers in JVM memory and - * data is lost when the application exits. - *
+ * data is lost when the application exits.
* This implementation is useful as temporary database or for testing. */ public class InMemoryCustomerDao implements CustomerDao { private final Map idToCustomer = new HashMap<>(); - /** - * An eagerly evaluated stream of customers stored in memory. - */ + /** An eagerly evaluated stream of customers stored in memory. */ @Override public Stream getAll() { return idToCustomer.values().stream(); diff --git a/data-access-object/src/test/java/com/iluwatar/dao/AppTest.java b/data-access-object/src/test/java/com/iluwatar/dao/AppTest.java index 64d8b2805..a43f37353 100644 --- a/data-access-object/src/test/java/com/iluwatar/dao/AppTest.java +++ b/data-access-object/src/test/java/com/iluwatar/dao/AppTest.java @@ -24,23 +24,19 @@ */ package com.iluwatar.dao; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -/** - * Tests that DAO example runs without errors. - */ +import org.junit.jupiter.api.Test; + +/** Tests that DAO example runs without errors. */ class AppTest { /** - * Issue: Add at least one assertion to this test case. - * Solution: Inserted assertion to check whether the execution of the main method in {@link App#main(String[])} - * throws an exception. + * Issue: Add at least one assertion to this test case. Solution: Inserted assertion to check + * whether the execution of the main method in {@link App#main(String[])} throws an exception. */ - @Test void shouldExecuteDaoWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/data-access-object/src/test/java/com/iluwatar/dao/CustomerTest.java b/data-access-object/src/test/java/com/iluwatar/dao/CustomerTest.java index 7ceab4eae..f53c28935 100644 --- a/data-access-object/src/test/java/com/iluwatar/dao/CustomerTest.java +++ b/data-access-object/src/test/java/com/iluwatar/dao/CustomerTest.java @@ -30,9 +30,7 @@ import static org.junit.jupiter.api.Assertions.assertNotEquals; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -/** - * Tests {@link Customer}. - */ +/** Tests {@link Customer}. */ class CustomerTest { private Customer customer; @@ -89,7 +87,10 @@ class CustomerTest { @Test void testToString() { - assertEquals(String.format("Customer(id=%s, firstName=%s, lastName=%s)", - customer.getId(), customer.getFirstName(), customer.getLastName()), customer.toString()); + assertEquals( + String.format( + "Customer(id=%s, firstName=%s, lastName=%s)", + customer.getId(), customer.getFirstName(), customer.getLastName()), + customer.toString()); } } diff --git a/data-access-object/src/test/java/com/iluwatar/dao/DbCustomerDaoTest.java b/data-access-object/src/test/java/com/iluwatar/dao/DbCustomerDaoTest.java index 759ab155c..2f116d108 100644 --- a/data-access-object/src/test/java/com/iluwatar/dao/DbCustomerDaoTest.java +++ b/data-access-object/src/test/java/com/iluwatar/dao/DbCustomerDaoTest.java @@ -44,9 +44,7 @@ import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.mockito.Mockito; -/** - * Tests {@link DbCustomerDao}. - */ +/** Tests {@link DbCustomerDao}. */ class DbCustomerDaoTest { private static final String DB_URL = "jdbc:h2:mem:dao;DB_CLOSE_DELAY=-1"; @@ -61,14 +59,12 @@ class DbCustomerDaoTest { @BeforeEach void createSchema() throws SQLException { try (var connection = DriverManager.getConnection(DB_URL); - var statement = connection.createStatement()) { + var statement = connection.createStatement()) { statement.execute(CustomerSchemaSql.CREATE_SCHEMA_SQL); } } - /** - * Represents the scenario where DB connectivity is present. - */ + /** Represents the scenario where DB connectivity is present. */ @Nested class ConnectionSuccess { @@ -160,8 +156,8 @@ class DbCustomerDaoTest { } @Test - void updationShouldBeSuccessAndAccessingTheSameCustomerShouldReturnUpdatedInformation() throws - Exception { + void updationShouldBeSuccessAndAccessingTheSameCustomerShouldReturnUpdatedInformation() + throws Exception { final var newFirstname = "Bernard"; final var newLastname = "Montgomery"; final var customer = new Customer(existingCustomer.getId(), newFirstname, newLastname); @@ -218,7 +214,9 @@ class DbCustomerDaoTest { void updatingACustomerFailsWithFeedbackToTheClient() { final var newFirstname = "Bernard"; final var newLastname = "Montgomery"; - assertThrows(Exception.class, () -> dao.update(new Customer(existingCustomer.getId(), newFirstname, newLastname))); + assertThrows( + Exception.class, + () -> dao.update(new Customer(existingCustomer.getId(), newFirstname, newLastname))); } @Test @@ -230,7 +228,6 @@ class DbCustomerDaoTest { void retrievingAllCustomersFailsWithExceptionAsFeedbackToClient() { assertThrows(Exception.class, () -> dao.getAll()); } - } /** @@ -241,7 +238,7 @@ class DbCustomerDaoTest { @AfterEach void deleteSchema() throws SQLException { try (var connection = DriverManager.getConnection(DB_URL); - var statement = connection.createStatement()) { + var statement = connection.createStatement()) { statement.execute(CustomerSchemaSql.DELETE_SCHEMA_SQL); } } diff --git a/data-access-object/src/test/java/com/iluwatar/dao/InMemoryCustomerDaoTest.java b/data-access-object/src/test/java/com/iluwatar/dao/InMemoryCustomerDaoTest.java index 340a0920c..93ce2475f 100644 --- a/data-access-object/src/test/java/com/iluwatar/dao/InMemoryCustomerDaoTest.java +++ b/data-access-object/src/test/java/com/iluwatar/dao/InMemoryCustomerDaoTest.java @@ -33,9 +33,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; -/** - * Tests {@link InMemoryCustomerDao}. - */ +/** Tests {@link InMemoryCustomerDao}. */ class InMemoryCustomerDaoTest { private InMemoryCustomerDao dao; @@ -48,8 +46,7 @@ class InMemoryCustomerDaoTest { } /** - * Represents the scenario when the DAO operations are being performed on a non-existent - * customer. + * Represents the scenario when the DAO operations are being performed on a non-existent customer. */ @Nested class NonExistingCustomer { @@ -121,8 +118,8 @@ class InMemoryCustomerDaoTest { } @Test - void updationShouldBeSuccessAndAccessingTheSameCustomerShouldReturnUpdatedInformation() throws - Exception { + void updationShouldBeSuccessAndAccessingTheSameCustomerShouldReturnUpdatedInformation() + throws Exception { final var newFirstname = "Bernard"; final var newLastname = "Montgomery"; final var customer = new Customer(CUSTOMER.getId(), newFirstname, newLastname); diff --git a/data-bus/pom.xml b/data-bus/pom.xml index aef3a0cd6..ef7c88acb 100644 --- a/data-bus/pom.xml +++ b/data-bus/pom.xml @@ -34,6 +34,14 @@ data-bus + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/data-bus/src/main/java/com/iluwatar/databus/AbstractDataType.java b/data-bus/src/main/java/com/iluwatar/databus/AbstractDataType.java index 311bed1ef..aa1ce3d45 100644 --- a/data-bus/src/main/java/com/iluwatar/databus/AbstractDataType.java +++ b/data-bus/src/main/java/com/iluwatar/databus/AbstractDataType.java @@ -51,10 +51,7 @@ package com.iluwatar.databus; import lombok.Getter; import lombok.Setter; -/** - * Base for data to send via the Data-Bus. - * - */ +/** Base for data to send via the Data-Bus. */ @Getter @Setter public class AbstractDataType implements DataType { diff --git a/data-bus/src/main/java/com/iluwatar/databus/App.java b/data-bus/src/main/java/com/iluwatar/databus/App.java index 1c0d99bd2..2c1d6b5e8 100644 --- a/data-bus/src/main/java/com/iluwatar/databus/App.java +++ b/data-bus/src/main/java/com/iluwatar/databus/App.java @@ -35,26 +35,25 @@ 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.

+ *

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.

+ * 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. */ class App { diff --git a/data-bus/src/main/java/com/iluwatar/databus/DataBus.java b/data-bus/src/main/java/com/iluwatar/databus/DataBus.java index 4b1fe1a74..f302d741f 100644 --- a/data-bus/src/main/java/com/iluwatar/databus/DataBus.java +++ b/data-bus/src/main/java/com/iluwatar/databus/DataBus.java @@ -30,8 +30,7 @@ import java.util.Set; /** * The Data-Bus implementation. * - *

This implementation uses a Singleton.

- * + *

This implementation uses a Singleton. */ public class DataBus { diff --git a/data-bus/src/main/java/com/iluwatar/databus/DataType.java b/data-bus/src/main/java/com/iluwatar/databus/DataType.java index 728199592..b84797bf0 100644 --- a/data-bus/src/main/java/com/iluwatar/databus/DataType.java +++ b/data-bus/src/main/java/com/iluwatar/databus/DataType.java @@ -48,11 +48,7 @@ SOFTWARE. package com.iluwatar.databus; -/** - * Events are sent via the Data-Bus. - * - */ - +/** Events are sent via the Data-Bus. */ public interface DataType { /** diff --git a/data-bus/src/main/java/com/iluwatar/databus/Member.java b/data-bus/src/main/java/com/iluwatar/databus/Member.java index 9eff9078e..3d4e97640 100644 --- a/data-bus/src/main/java/com/iluwatar/databus/Member.java +++ b/data-bus/src/main/java/com/iluwatar/databus/Member.java @@ -50,10 +50,7 @@ package com.iluwatar.databus; import java.util.function.Consumer; -/** - * Members receive events from the Data-Bus. - * - */ +/** Members receive events from the Data-Bus. */ 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 index 55228975e..970fc6973 100644 --- a/data-bus/src/main/java/com/iluwatar/databus/data/MessageData.java +++ b/data-bus/src/main/java/com/iluwatar/databus/data/MessageData.java @@ -29,10 +29,7 @@ import com.iluwatar.databus.DataType; import lombok.AllArgsConstructor; import lombok.Getter; -/** - * An event raised when a string message is sent. - * - */ +/** An event raised when a string message is sent. */ @Getter @AllArgsConstructor public class MessageData extends AbstractDataType { 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 index 793e31446..554a0ff71 100644 --- a/data-bus/src/main/java/com/iluwatar/databus/data/StartingData.java +++ b/data-bus/src/main/java/com/iluwatar/databus/data/StartingData.java @@ -30,10 +30,7 @@ import java.time.LocalDateTime; import lombok.Getter; import lombok.RequiredArgsConstructor; -/** - * An event raised when applications starts, containing the start time of the application. - * - */ +/** An event raised when applications starts, containing the start time of the application. */ @RequiredArgsConstructor @Getter public class StartingData extends AbstractDataType { 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 index 605db3937..090f31265 100644 --- a/data-bus/src/main/java/com/iluwatar/databus/data/StoppingData.java +++ b/data-bus/src/main/java/com/iluwatar/databus/data/StoppingData.java @@ -30,10 +30,7 @@ import java.time.LocalDateTime; import lombok.Getter; import lombok.RequiredArgsConstructor; -/** - * An event raised when applications stops, containing the stop time of the application. - * - */ +/** An event raised when applications stops, containing the stop time of the application. */ @RequiredArgsConstructor @Getter public class StoppingData extends AbstractDataType { 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 index 1ebbdf8d8..8eb81da1a 100644 --- a/data-bus/src/main/java/com/iluwatar/databus/members/MessageCollectorMember.java +++ b/data-bus/src/main/java/com/iluwatar/databus/members/MessageCollectorMember.java @@ -31,10 +31,7 @@ import java.util.ArrayList; import java.util.List; import lombok.extern.slf4j.Slf4j; -/** - * Receiver of Data-Bus events that collects the messages from each {@link MessageData}. - * - */ +/** Receiver of Data-Bus events that collects the messages from each {@link MessageData}. */ @Slf4j public class MessageCollectorMember implements Member { 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 index 5790f6b72..d6aab7730 100644 --- a/data-bus/src/main/java/com/iluwatar/databus/members/StatusMember.java +++ b/data-bus/src/main/java/com/iluwatar/databus/members/StatusMember.java @@ -34,10 +34,7 @@ import lombok.Getter; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; -/** - * Receiver of Data-Bus events. - * - */ +/** Receiver of Data-Bus events. */ @Getter @Slf4j @RequiredArgsConstructor @@ -69,5 +66,4 @@ public class StatusMember implements Member { LOGGER.info("Receiver {} sending goodbye message", id); data.getDataBus().publish(MessageData.of(String.format("Goodbye cruel world from #%d!", id))); } - } diff --git a/data-bus/src/test/java/com/iluwatar/databus/DataBusTest.java b/data-bus/src/test/java/com/iluwatar/databus/DataBusTest.java index d9f0c6a6c..a948201b4 100644 --- a/data-bus/src/test/java/com/iluwatar/databus/DataBusTest.java +++ b/data-bus/src/test/java/com/iluwatar/databus/DataBusTest.java @@ -32,17 +32,12 @@ import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; -/** - * Tests for {@link DataBus}. - * - */ +/** Tests for {@link DataBus}. */ class DataBusTest { - @Mock - private Member member; + @Mock private Member member; - @Mock - private DataType event; + @Mock private DataType event; @BeforeEach void setUp() { @@ -51,25 +46,24 @@ class DataBusTest { @Test void publishedEventIsReceivedBySubscribedMember() { - //given + // given final var dataBus = DataBus.getInstance(); dataBus.subscribe(member); - //when + // when dataBus.publish(event); - //then + // then then(member).should().accept(event); } @Test void publishedEventIsNotReceivedByMemberAfterUnsubscribing() { - //given + // given final var dataBus = DataBus.getInstance(); dataBus.subscribe(member); dataBus.unsubscribe(member); - //when + // when dataBus.publish(event); - //then + // 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 index 45df955a7..e0f881108 100644 --- a/data-bus/src/test/java/com/iluwatar/databus/members/MessageCollectorMemberTest.java +++ b/data-bus/src/test/java/com/iluwatar/databus/members/MessageCollectorMemberTest.java @@ -32,33 +32,29 @@ import com.iluwatar.databus.data.StartingData; import java.time.LocalDateTime; import org.junit.jupiter.api.Test; -/** - * Tests for {@link MessageCollectorMember}. - * - */ +/** Tests for {@link MessageCollectorMember}. */ class MessageCollectorMemberTest { @Test void collectMessageFromMessageData() { - //given + // given final var message = "message"; final var messageData = new MessageData(message); final var collector = new MessageCollectorMember("collector"); - //when + // when collector.accept(messageData); - //then + // then assertTrue(collector.getMessages().contains(message)); } @Test void collectIgnoresMessageFromOtherDataTypes() { - //given + // given final var startingData = new StartingData(LocalDateTime.now()); final var collector = new MessageCollectorMember("collector"); - //when + // when collector.accept(startingData); - //then + // then assertEquals(0, collector.getMessages().size()); } - } diff --git a/data-bus/src/test/java/com/iluwatar/databus/members/StatusMemberTest.java b/data-bus/src/test/java/com/iluwatar/databus/members/StatusMemberTest.java index 342ec4806..b7aa8b826 100644 --- a/data-bus/src/test/java/com/iluwatar/databus/members/StatusMemberTest.java +++ b/data-bus/src/test/java/com/iluwatar/databus/members/StatusMemberTest.java @@ -35,47 +35,43 @@ import java.time.LocalDateTime; import java.time.Month; import org.junit.jupiter.api.Test; -/** - * Tests for {@link StatusMember}. - * - */ +/** Tests for {@link StatusMember}. */ class StatusMemberTest { @Test void statusRecordsTheStartTime() { - //given + // given final var startTime = LocalDateTime.of(2017, Month.APRIL, 1, 19, 9); final var startingData = new StartingData(startTime); final var statusMember = new StatusMember(1); - //when + // when statusMember.accept(startingData); - //then + // then assertEquals(startTime, statusMember.getStarted()); } @Test void statusRecordsTheStopTime() { - //given + // given final var stop = LocalDateTime.of(2017, Month.APRIL, 1, 19, 12); final var stoppingData = new StoppingData(stop); stoppingData.setDataBus(DataBus.getInstance()); final var statusMember = new StatusMember(1); - //when + // when statusMember.accept(stoppingData); - //then + // then assertEquals(stop, statusMember.getStopped()); } @Test void statusIgnoresMessageData() { - //given + // given final var messageData = new MessageData("message"); final var statusMember = new StatusMember(1); - //when + // when statusMember.accept(messageData); - //then + // then assertNull(statusMember.getStarted()); assertNull(statusMember.getStopped()); } - } diff --git a/data-locality/pom.xml b/data-locality/pom.xml index c5ba5531f..593f67934 100644 --- a/data-locality/pom.xml +++ b/data-locality/pom.xml @@ -34,6 +34,14 @@ data-locality + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/data-locality/src/main/java/com/iluwatar/data/locality/Application.java b/data-locality/src/main/java/com/iluwatar/data/locality/Application.java index 1e87c8e3c..862fa1173 100644 --- a/data-locality/src/main/java/com/iluwatar/data/locality/Application.java +++ b/data-locality/src/main/java/com/iluwatar/data/locality/Application.java @@ -32,17 +32,15 @@ import lombok.extern.slf4j.Slf4j; * improve performance by increasing data locality — keeping data in contiguous memory in the order * that you process it. * - *

Example: Game loop that processes a bunch of game entities. Those entities are decomposed - * into different domains  — AI, physics, and rendering — using the Component pattern. + *

Example: Game loop that processes a bunch of game entities. Those entities are decomposed into + * different domains  — AI, physics, and rendering — using the Component pattern. */ @Slf4j public class Application { private static final int NUM_ENTITIES = 5; - /** - * Start game loop with each component have NUM_ENTITIES instance. - */ + /** Start game loop with each component have NUM_ENTITIES instance. */ public static void main(String[] args) { LOGGER.info("Start Game Application using Data-Locality pattern"); var gameEntity = new GameEntity(NUM_ENTITIES); diff --git a/data-locality/src/main/java/com/iluwatar/data/locality/game/GameEntity.java b/data-locality/src/main/java/com/iluwatar/data/locality/game/GameEntity.java index 06989e6f6..92ce918a7 100644 --- a/data-locality/src/main/java/com/iluwatar/data/locality/game/GameEntity.java +++ b/data-locality/src/main/java/com/iluwatar/data/locality/game/GameEntity.java @@ -46,9 +46,7 @@ public class GameEntity { private final PhysicsComponentManager physicsComponentManager; private final RenderComponentManager renderComponentManager; - /** - * Init components. - */ + /** Init components. */ public GameEntity(int numEntities) { LOGGER.info("Init Game with #Entity : {}", numEntities); aiComponentManager = new AiComponentManager(numEntities); @@ -56,9 +54,7 @@ public class GameEntity { renderComponentManager = new RenderComponentManager(numEntities); } - /** - * start all component. - */ + /** start all component. */ public void start() { LOGGER.info("Start Game"); aiComponentManager.start(); @@ -66,9 +62,7 @@ public class GameEntity { renderComponentManager.start(); } - /** - * update all component. - */ + /** update all component. */ public void update() { LOGGER.info("Update Game Component"); // Process AI. @@ -80,5 +74,4 @@ public class GameEntity { // Draw to screen. renderComponentManager.render(); } - } diff --git a/data-locality/src/main/java/com/iluwatar/data/locality/game/component/AiComponent.java b/data-locality/src/main/java/com/iluwatar/data/locality/game/component/AiComponent.java index efa8a948d..2f3cb043f 100644 --- a/data-locality/src/main/java/com/iluwatar/data/locality/game/component/AiComponent.java +++ b/data-locality/src/main/java/com/iluwatar/data/locality/game/component/AiComponent.java @@ -26,15 +26,11 @@ package com.iluwatar.data.locality.game.component; import lombok.extern.slf4j.Slf4j; -/** - * Implementation of AI component for Game. - */ +/** Implementation of AI component for Game. */ @Slf4j public class AiComponent implements Component { - /** - * Update ai component. - */ + /** Update ai component. */ @Override public void update() { LOGGER.info("update AI component"); diff --git a/data-locality/src/main/java/com/iluwatar/data/locality/game/component/Component.java b/data-locality/src/main/java/com/iluwatar/data/locality/game/component/Component.java index 263d09281..5775804fb 100644 --- a/data-locality/src/main/java/com/iluwatar/data/locality/game/component/Component.java +++ b/data-locality/src/main/java/com/iluwatar/data/locality/game/component/Component.java @@ -24,9 +24,7 @@ */ package com.iluwatar.data.locality.game.component; -/** - * Implement different Game component update and render process. - */ +/** Implement different Game component update and render process. */ public interface Component { void update(); diff --git a/data-locality/src/main/java/com/iluwatar/data/locality/game/component/PhysicsComponent.java b/data-locality/src/main/java/com/iluwatar/data/locality/game/component/PhysicsComponent.java index 632836ea3..43b762aaf 100644 --- a/data-locality/src/main/java/com/iluwatar/data/locality/game/component/PhysicsComponent.java +++ b/data-locality/src/main/java/com/iluwatar/data/locality/game/component/PhysicsComponent.java @@ -26,15 +26,11 @@ package com.iluwatar.data.locality.game.component; import lombok.extern.slf4j.Slf4j; -/** - * Implementation of Physics Component of Game. - */ +/** Implementation of Physics Component of Game. */ @Slf4j public class PhysicsComponent implements Component { - /** - * update physics component of game. - */ + /** update physics component of game. */ @Override public void update() { LOGGER.info("Update physics component of game"); diff --git a/data-locality/src/main/java/com/iluwatar/data/locality/game/component/RenderComponent.java b/data-locality/src/main/java/com/iluwatar/data/locality/game/component/RenderComponent.java index 45f61eba1..c04b2bc8f 100644 --- a/data-locality/src/main/java/com/iluwatar/data/locality/game/component/RenderComponent.java +++ b/data-locality/src/main/java/com/iluwatar/data/locality/game/component/RenderComponent.java @@ -26,9 +26,7 @@ package com.iluwatar.data.locality.game.component; import lombok.extern.slf4j.Slf4j; -/** - * Implementation of Render Component of Game. - */ +/** Implementation of Render Component of Game. */ @Slf4j public class RenderComponent implements Component { @@ -37,9 +35,7 @@ public class RenderComponent implements Component { // do nothing } - /** - * render. - */ + /** render. */ @Override public void render() { LOGGER.info("Render Component"); diff --git a/data-locality/src/main/java/com/iluwatar/data/locality/game/component/manager/AiComponentManager.java b/data-locality/src/main/java/com/iluwatar/data/locality/game/component/manager/AiComponentManager.java index 90c234a97..a69d77b13 100644 --- a/data-locality/src/main/java/com/iluwatar/data/locality/game/component/manager/AiComponentManager.java +++ b/data-locality/src/main/java/com/iluwatar/data/locality/game/component/manager/AiComponentManager.java @@ -29,9 +29,7 @@ import com.iluwatar.data.locality.game.component.Component; import java.util.stream.IntStream; import lombok.extern.slf4j.Slf4j; -/** - * AI component manager for Game. - */ +/** AI component manager for Game. */ @Slf4j public class AiComponentManager { @@ -45,17 +43,13 @@ public class AiComponentManager { this.numEntities = numEntities; } - /** - * start AI component of Game. - */ + /** start AI component of Game. */ public void start() { LOGGER.info("Start AI Game Component"); IntStream.range(0, numEntities).forEach(i -> aiComponents[i] = new AiComponent()); } - /** - * Update AI component of Game. - */ + /** Update AI component of Game. */ public void update() { LOGGER.info("Update AI Game Component"); IntStream.range(0, numEntities) diff --git a/data-locality/src/main/java/com/iluwatar/data/locality/game/component/manager/PhysicsComponentManager.java b/data-locality/src/main/java/com/iluwatar/data/locality/game/component/manager/PhysicsComponentManager.java index 58c85f2fd..c9b1a9bbe 100644 --- a/data-locality/src/main/java/com/iluwatar/data/locality/game/component/manager/PhysicsComponentManager.java +++ b/data-locality/src/main/java/com/iluwatar/data/locality/game/component/manager/PhysicsComponentManager.java @@ -29,9 +29,7 @@ import com.iluwatar.data.locality.game.component.PhysicsComponent; import java.util.stream.IntStream; import lombok.extern.slf4j.Slf4j; -/** - * Physics component Manager for Game. - */ +/** Physics component Manager for Game. */ @Slf4j public class PhysicsComponentManager { @@ -45,18 +43,13 @@ public class PhysicsComponentManager { this.numEntities = numEntities; } - /** - * Start physics component of Game. - */ + /** Start physics component of Game. */ public void start() { LOGGER.info("Start Physics Game Component "); IntStream.range(0, numEntities).forEach(i -> physicsComponents[i] = new PhysicsComponent()); } - - /** - * Update physics component of Game. - */ + /** Update physics component of Game. */ public void update() { LOGGER.info("Update Physics Game Component "); // Process physics. diff --git a/data-locality/src/main/java/com/iluwatar/data/locality/game/component/manager/RenderComponentManager.java b/data-locality/src/main/java/com/iluwatar/data/locality/game/component/manager/RenderComponentManager.java index 40cd0815b..cff4bc3ac 100644 --- a/data-locality/src/main/java/com/iluwatar/data/locality/game/component/manager/RenderComponentManager.java +++ b/data-locality/src/main/java/com/iluwatar/data/locality/game/component/manager/RenderComponentManager.java @@ -29,9 +29,7 @@ import com.iluwatar.data.locality.game.component.RenderComponent; import java.util.stream.IntStream; import lombok.extern.slf4j.Slf4j; -/** - * Render component manager for Game. - */ +/** Render component manager for Game. */ @Slf4j public class RenderComponentManager { @@ -45,18 +43,13 @@ public class RenderComponentManager { this.numEntities = numEntities; } - /** - * Start render component. - */ + /** Start render component. */ public void start() { LOGGER.info("Start Render Game Component "); IntStream.range(0, numEntities).forEach(i -> renderComponents[i] = new RenderComponent()); } - - /** - * render component. - */ + /** render component. */ public void render() { LOGGER.info("Update Render Game Component "); // Process Render. diff --git a/data-locality/src/test/java/com/iluwatar/data/locality/ApplicationTest.java b/data-locality/src/test/java/com/iluwatar/data/locality/ApplicationTest.java index 1f1689425..badf5aadd 100644 --- a/data-locality/src/test/java/com/iluwatar/data/locality/ApplicationTest.java +++ b/data-locality/src/test/java/com/iluwatar/data/locality/ApplicationTest.java @@ -24,24 +24,20 @@ */ package com.iluwatar.data.locality; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; - -/** - * Test Game Application - */ +/** Test Game Application */ class ApplicationTest { /** - * Issue: Add at least one assertion to this test case. - * Solution: Inserted assertion to check whether the execution of the main method in {@link Application#main(String[])} - * throws an exception. + * Issue: Add at least one assertion to this test case. Solution: Inserted assertion to check + * whether the execution of the main method in {@link Application#main(String[])} throws an + * exception. */ - @Test void shouldExecuteGameApplicationWithoutException() { - assertDoesNotThrow(() -> Application.main(new String[]{})); + assertDoesNotThrow(() -> Application.main(new String[] {})); } -} \ No newline at end of file +} diff --git a/data-mapper/pom.xml b/data-mapper/pom.xml index 0c7907cb5..40e8c3cee 100644 --- a/data-mapper/pom.xml +++ b/data-mapper/pom.xml @@ -34,6 +34,14 @@ data-mapper + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/data-mapper/src/main/java/com/iluwatar/datamapper/App.java b/data-mapper/src/main/java/com/iluwatar/datamapper/App.java index 5969ee2f2..3a7ed69f9 100644 --- a/data-mapper/src/main/java/com/iluwatar/datamapper/App.java +++ b/data-mapper/src/main/java/com/iluwatar/datamapper/App.java @@ -77,6 +77,5 @@ public final class App { mapper.delete(student); } - private App() { - } + private App() {} } diff --git a/data-mapper/src/main/java/com/iluwatar/datamapper/DataMapperException.java b/data-mapper/src/main/java/com/iluwatar/datamapper/DataMapperException.java index fcbe56ac0..f02dcef33 100644 --- a/data-mapper/src/main/java/com/iluwatar/datamapper/DataMapperException.java +++ b/data-mapper/src/main/java/com/iluwatar/datamapper/DataMapperException.java @@ -29,19 +29,17 @@ import java.io.Serial; /** * Using Runtime Exception for avoiding dependency on implementation exceptions. This helps in * decoupling. - * */ public final class DataMapperException extends RuntimeException { - @Serial - private static final long serialVersionUID = 1L; + @Serial private static final long serialVersionUID = 1L; /** * Constructs a new runtime exception with the specified detail message. The cause is not * initialized, and may subsequently be initialized by a call to {@link #initCause}. * * @param message the detail message. The detail message is saved for later retrieval by the - * {@link #getMessage()} method. + * {@link #getMessage()} method. */ public DataMapperException(final String message) { super(message); 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 1691d1233..8d8a42116 100644 --- a/data-mapper/src/main/java/com/iluwatar/datamapper/Student.java +++ b/data-mapper/src/main/java/com/iluwatar/datamapper/Student.java @@ -1,53 +1,48 @@ -/* - * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). - * - * The MIT License - * Copyright © 2014-2022 Ilkka Seppälä - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package com.iluwatar.datamapper; - -import java.io.Serial; -import java.io.Serializable; -import lombok.AllArgsConstructor; -import lombok.EqualsAndHashCode; -import lombok.Getter; -import lombok.Setter; -import lombok.ToString; - -/** - * Class defining Student. - */ -@EqualsAndHashCode(onlyExplicitlyIncluded = true) -@ToString -@Getter -@Setter -@AllArgsConstructor -public final class Student implements Serializable { - - @Serial - private static final long serialVersionUID = 1L; - - @EqualsAndHashCode.Include - private int studentId; - private String name; - private char grade; - -} +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.datamapper; + +import java.io.Serial; +import java.io.Serializable; +import lombok.AllArgsConstructor; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +/** Class defining Student. */ +@EqualsAndHashCode(onlyExplicitlyIncluded = true) +@ToString +@Getter +@Setter +@AllArgsConstructor +public final class Student implements Serializable { + + @Serial private static final long serialVersionUID = 1L; + + @EqualsAndHashCode.Include private int studentId; + private String name; + private char grade; +} 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 2700e30f0..ab28bd3dc 100644 --- a/data-mapper/src/main/java/com/iluwatar/datamapper/StudentDataMapper.java +++ b/data-mapper/src/main/java/com/iluwatar/datamapper/StudentDataMapper.java @@ -1,41 +1,39 @@ -/* - * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). - * - * The MIT License - * Copyright © 2014-2022 Ilkka Seppälä - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package com.iluwatar.datamapper; - -import java.util.Optional; - -/** - * Interface lists out the possible behaviour for all possible student mappers. - */ -public interface StudentDataMapper { - - Optional find(int studentId); - - void insert(Student student) throws DataMapperException; - - void update(Student student) throws DataMapperException; - - void delete(Student student) throws DataMapperException; -} +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.datamapper; + +import java.util.Optional; + +/** Interface lists out the possible behaviour for all possible student mappers. */ +public interface StudentDataMapper { + + Optional find(int studentId); + + void insert(Student student) throws DataMapperException; + + void update(Student student) throws DataMapperException; + + void delete(Student student) throws DataMapperException; +} 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 9da1c8f7d..67ddc0ce6 100644 --- a/data-mapper/src/main/java/com/iluwatar/datamapper/StudentDataMapperImpl.java +++ b/data-mapper/src/main/java/com/iluwatar/datamapper/StudentDataMapperImpl.java @@ -29,9 +29,7 @@ import java.util.List; import java.util.Optional; import lombok.Getter; -/** - * Implementation of Actions on Students Data. - */ +/** Implementation of Actions on Students Data. */ @Getter public final class StudentDataMapperImpl implements StudentDataMapper { @@ -46,11 +44,12 @@ public final class StudentDataMapperImpl implements StudentDataMapper { @Override public void update(Student studentToBeUpdated) throws DataMapperException { String name = studentToBeUpdated.getName(); - Integer index = Optional.of(studentToBeUpdated) - .map(Student::getStudentId) - .flatMap(this::find) - .map(students::indexOf) - .orElseThrow(() -> new DataMapperException("Student [" + name + "] is not found")); + Integer index = + Optional.of(studentToBeUpdated) + .map(Student::getStudentId) + .flatMap(this::find) + .map(students::indexOf) + .orElseThrow(() -> new DataMapperException("Student [" + name + "] is not found")); students.set(index, studentToBeUpdated); } diff --git a/data-mapper/src/test/java/com/iluwatar/datamapper/AppTest.java b/data-mapper/src/test/java/com/iluwatar/datamapper/AppTest.java index f45f6cc32..a7118721d 100644 --- a/data-mapper/src/test/java/com/iluwatar/datamapper/AppTest.java +++ b/data-mapper/src/test/java/com/iluwatar/datamapper/AppTest.java @@ -1,48 +1,44 @@ -/* - * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). - * - * The MIT License - * Copyright © 2014-2022 Ilkka Seppälä - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package com.iluwatar.datamapper; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.function.Executable; - -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; - -/** - * Tests that Data-Mapper example runs without errors. - */ -final class AppTest { - - /** - * Issue: Add at least one assertion to this test case. - * Solution: Inserted assertion to check whether the execution of the main method in {@link App#main(String[])} - * throws an exception. - */ - - @Test - void shouldExecuteApplicationWithoutException() { - - assertDoesNotThrow((Executable) App::main); - } -} +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.datamapper; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.function.Executable; + +/** Tests that Data-Mapper example runs without errors. */ +final class AppTest { + + /** + * Issue: Add at least one assertion to this test case. Solution: Inserted assertion to check + * whether the execution of the main method in {@link App#main(String[])} throws an exception. + */ + @Test + void shouldExecuteApplicationWithoutException() { + + assertDoesNotThrow((Executable) App::main); + } +} diff --git a/data-mapper/src/test/java/com/iluwatar/datamapper/DataMapperTest.java b/data-mapper/src/test/java/com/iluwatar/datamapper/DataMapperTest.java index ee85252ee..53782b7eb 100644 --- a/data-mapper/src/test/java/com/iluwatar/datamapper/DataMapperTest.java +++ b/data-mapper/src/test/java/com/iluwatar/datamapper/DataMapperTest.java @@ -36,13 +36,12 @@ import org.junit.jupiter.api.Test; * present; they need no SQL interface code, and certainly no knowledge of the database schema. (The * database schema is always ignorant of the objects that use it.) Since it's a form of Mapper , * Data Mapper itself is even unknown to the domain layer. + * *

*/ class DataMapperTest { - /** - * This test verify that first data mapper is able to perform all CRUD operations on Student - */ + /** This test verify that first data mapper is able to perform all CRUD operations on Student */ @Test void testFirstDataMapper() { 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 9a9866e3b..237ea7a3c 100644 --- a/data-mapper/src/test/java/com/iluwatar/datamapper/StudentTest.java +++ b/data-mapper/src/test/java/com/iluwatar/datamapper/StudentTest.java @@ -29,9 +29,7 @@ import static org.junit.jupiter.api.Assertions.assertNotEquals; import org.junit.jupiter.api.Test; -/** - * Tests {@link Student}. - */ +/** Tests {@link Student}. */ final class StudentTest { /** diff --git a/data-transfer-object/pom.xml b/data-transfer-object/pom.xml index b6404194b..5370250f6 100644 --- a/data-transfer-object/pom.xml +++ b/data-transfer-object/pom.xml @@ -34,6 +34,14 @@ data-transfer-object + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/data-transfer-object/src/main/java/com/iluwatar/datatransfer/App.java b/data-transfer-object/src/main/java/com/iluwatar/datatransfer/App.java index ac96e53c4..0a6fc9f04 100644 --- a/data-transfer-object/src/main/java/com/iluwatar/datatransfer/App.java +++ b/data-transfer-object/src/main/java/com/iluwatar/datatransfer/App.java @@ -38,17 +38,16 @@ import lombok.extern.slf4j.Slf4j; * The Data Transfer Object pattern is a design pattern in which an data transfer object is used to * serve related information together to avoid multiple call for each piece of information. * - *

In the first example, {@link App} is a customer details consumer i.e. client to - * request for customer details to server. {@link CustomerResource} act as server to serve customer - * information. {@link CustomerDto} is data transfer object to share customer information. + *

In the first example, {@link App} is a customer details consumer i.e. client to request for + * customer details to server. {@link CustomerResource} act as server to serve customer information. + * {@link CustomerDto} is data transfer object to share customer information. * - *

In the second example, {@link App} is a product details consumer i.e. client to - * request for product details to server. {@link ProductResource} acts as server to serve - * product information. {@link ProductDto} is data transfer object to share product information. + *

In the second example, {@link App} is a product details consumer i.e. client to request for + * product details to server. {@link ProductResource} acts as server to serve product information. + * {@link ProductDto} is data transfer object to share product information. * *

The pattern implementation is a bit different in each of the examples. The first can be * thought as a traditional example and the second is an enum based implementation. - * */ @Slf4j public class App { @@ -88,28 +87,32 @@ public class App { // Example 2: Product DTO - Product tv = Product.builder().id(1L).name("TV").supplier("Sony").price(1000D).cost(1090D).build(); + Product tv = + Product.builder().id(1L).name("TV").supplier("Sony").price(1000D).cost(1090D).build(); Product microwave = Product.builder() .id(2L) .name("microwave") .supplier("Delonghi") .price(1000D) - .cost(1090D).build(); + .cost(1090D) + .build(); Product refrigerator = Product.builder() .id(3L) .name("refrigerator") .supplier("Botsch") .price(1000D) - .cost(1090D).build(); + .cost(1090D) + .build(); Product airConditioner = Product.builder() .id(4L) .name("airConditioner") .supplier("LG") .price(1000D) - .cost(1090D).build(); + .cost(1090D) + .build(); List products = new ArrayList<>(Arrays.asList(tv, microwave, refrigerator, airConditioner)); ProductResource productResource = new ProductResource(products); diff --git a/data-transfer-object/src/main/java/com/iluwatar/datatransfer/customer/CustomerDto.java b/data-transfer-object/src/main/java/com/iluwatar/datatransfer/customer/CustomerDto.java index 402075e4d..64e44f64d 100644 --- a/data-transfer-object/src/main/java/com/iluwatar/datatransfer/customer/CustomerDto.java +++ b/data-transfer-object/src/main/java/com/iluwatar/datatransfer/customer/CustomerDto.java @@ -24,9 +24,6 @@ */ package com.iluwatar.datatransfer.customer; -import lombok.Getter; -import lombok.RequiredArgsConstructor; - /** * {@link CustomerDto} is a data transfer object POJO. Instead of sending individual information to * client We can send related information together in POJO. diff --git a/data-transfer-object/src/main/java/com/iluwatar/datatransfer/customer/CustomerResource.java b/data-transfer-object/src/main/java/com/iluwatar/datatransfer/customer/CustomerResource.java index 0fcae3e91..427c87521 100644 --- a/data-transfer-object/src/main/java/com/iluwatar/datatransfer/customer/CustomerResource.java +++ b/data-transfer-object/src/main/java/com/iluwatar/datatransfer/customer/CustomerResource.java @@ -25,8 +25,6 @@ package com.iluwatar.datatransfer.customer; import java.util.List; -import lombok.Getter; -import lombok.RequiredArgsConstructor; /** * The resource class which serves customer information. This class act as server in the demo. Which diff --git a/data-transfer-object/src/main/java/com/iluwatar/datatransfer/product/Product.java b/data-transfer-object/src/main/java/com/iluwatar/datatransfer/product/Product.java index 633c0b829..a29fda158 100644 --- a/data-transfer-object/src/main/java/com/iluwatar/datatransfer/product/Product.java +++ b/data-transfer-object/src/main/java/com/iluwatar/datatransfer/product/Product.java @@ -29,9 +29,7 @@ import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; -/** - * {@link Product} is a entity class for product entity. This class act as entity in the demo. - */ +/** {@link Product} is a entity class for product entity. This class act as entity in the demo. */ @Data @Builder @NoArgsConstructor @@ -46,11 +44,18 @@ public final class Product { @Override public String toString() { return "Product{" - + "id=" + id - + ", name='" + name + '\'' - + ", price=" + price - + ", cost=" + cost - + ", supplier='" + supplier + '\'' - + '}'; + + "id=" + + id + + ", name='" + + name + + '\'' + + ", price=" + + price + + ", cost=" + + cost + + ", supplier='" + + supplier + + '\'' + + '}'; } } diff --git a/data-transfer-object/src/main/java/com/iluwatar/datatransfer/product/ProductDto.java b/data-transfer-object/src/main/java/com/iluwatar/datatransfer/product/ProductDto.java index 9f13398a7..d254e2fc1 100644 --- a/data-transfer-object/src/main/java/com/iluwatar/datatransfer/product/ProductDto.java +++ b/data-transfer-object/src/main/java/com/iluwatar/datatransfer/product/ProductDto.java @@ -25,8 +25,7 @@ package com.iluwatar.datatransfer.product; /** - * {@link ProductDto} is a data transfer object POJO. - * Instead of sending individual information to + * {@link ProductDto} is a data transfer object POJO. Instead of sending individual information to * client We can send related information together in POJO. * *

Dto will not have any business logic in it. @@ -35,15 +34,13 @@ public enum ProductDto { ; /** - * This is Request class which consist of Create or any other request DTO's - * you might want to use in your API. + * This is Request class which consist of Create or any other request DTO's you might want to use + * in your API. */ public enum Request { ; - /** - * This is Create dto class for requesting create new product. - */ + /** This is Create dto class for requesting create new product. */ public static final class Create implements Name, Price, Cost, Supplier { private String name; private Double price; @@ -93,15 +90,13 @@ public enum ProductDto { } /** - * This is Response class which consist of any response DTO's - * you might want to provide to your clients. + * This is Response class which consist of any response DTO's you might want to provide to your + * clients. */ public enum Response { ; - /** - * This is Public dto class for API response with the lowest data security. - */ + /** This is Public dto class for API response with the lowest data security. */ public static final class Public implements Id, Name, Price { private Long id; private String name; @@ -139,21 +134,11 @@ public enum ProductDto { @Override public String toString() { - return "Public{" - + "id=" - + id - + ", name='" - + name - + '\'' - + ", price=" - + price - + '}'; + return "Public{" + "id=" + id + ", name='" + name + '\'' + ", price=" + price + '}'; } } - /** - * This is Private dto class for API response with the highest data security. - */ + /** This is Private dto class for API response with the highest data security. */ public static final class Private implements Id, Name, Price, Cost { private Long id; private String name; @@ -203,28 +188,21 @@ public enum ProductDto { @Override public String toString() { return "Private{" - + - "id=" + + "id=" + id - + - ", name='" + + ", name='" + name + '\'' - + - ", price=" + + ", price=" + price - + - ", cost=" + + ", cost=" + cost - + - '}'; + + '}'; } } } - /** - * Use this interface whenever you want to provide the product Id in your DTO. - */ + /** Use this interface whenever you want to provide the product Id in your DTO. */ private interface Id { /** * Unique identifier of the product. @@ -234,9 +212,7 @@ public enum ProductDto { Long getId(); } - /** - * Use this interface whenever you want to provide the product Name in your DTO. - */ + /** Use this interface whenever you want to provide the product Name in your DTO. */ private interface Name { /** * The name of the product. @@ -246,40 +222,32 @@ public enum ProductDto { String getName(); } - /** - * Use this interface whenever you want to provide the product Price in your DTO. - */ + /** Use this interface whenever you want to provide the product Price in your DTO. */ private interface Price { /** - * The amount we sell a product for. - * This data is not confidential + * The amount we sell a product for. This data is not confidential * * @return : price of the product. */ Double getPrice(); } - /** - * Use this interface whenever you want to provide the product Cost in your DTO. - */ + /** Use this interface whenever you want to provide the product Cost in your DTO. */ private interface Cost { /** - * The amount that it costs us to purchase this product - * For the amount we sell a product for, see the {@link Price Price} parameter. - * This data is confidential + * The amount that it costs us to purchase this product For the amount we sell a product for, + * see the {@link Price Price} parameter. This data is confidential * * @return : cost of the product. */ Double getCost(); } - /** - * Use this interface whenever you want to provide the product Supplier in your DTO. - */ + /** Use this interface whenever you want to provide the product Supplier in your DTO. */ private interface Supplier { /** - * The name of supplier of the product or its manufacturer. - * This data is highly confidential + * The name of supplier of the product or its manufacturer. This data is highly + * confidential * * @return : supplier of the product. */ diff --git a/data-transfer-object/src/main/java/com/iluwatar/datatransfer/product/ProductResource.java b/data-transfer-object/src/main/java/com/iluwatar/datatransfer/product/ProductResource.java index e0345b411..d0b3fcbd7 100644 --- a/data-transfer-object/src/main/java/com/iluwatar/datatransfer/product/ProductResource.java +++ b/data-transfer-object/src/main/java/com/iluwatar/datatransfer/product/ProductResource.java @@ -37,11 +37,14 @@ public record ProductResource(List products) { * @return : all products in list but in the scheme of private dto. */ public List getAllProductsForAdmin() { - return products - .stream() - .map(p -> new ProductDto.Response.Private().setId(p.getId()).setName(p.getName()) - .setCost(p.getCost()) - .setPrice(p.getPrice())) + return products.stream() + .map( + p -> + new ProductDto.Response.Private() + .setId(p.getId()) + .setName(p.getName()) + .setCost(p.getCost()) + .setPrice(p.getPrice())) .toList(); } @@ -51,10 +54,13 @@ public record ProductResource(List products) { * @return : all products in list but in the scheme of public dto. */ public List getAllProductsForCustomer() { - return products - .stream() - .map(p -> new ProductDto.Response.Public().setId(p.getId()).setName(p.getName()) - .setPrice(p.getPrice())) + return products.stream() + .map( + p -> + new ProductDto.Response.Public() + .setId(p.getId()) + .setName(p.getName()) + .setPrice(p.getPrice())) .toList(); } @@ -64,12 +70,13 @@ public record ProductResource(List products) { * @param createProductDto save new product to list. */ public void save(ProductDto.Request.Create createProductDto) { - products.add(Product.builder() - .id((long) (products.size() + 1)) - .name(createProductDto.getName()) - .supplier(createProductDto.getSupplier()) - .price(createProductDto.getPrice()) - .cost(createProductDto.getCost()) - .build()); + products.add( + Product.builder() + .id((long) (products.size() + 1)) + .name(createProductDto.getName()) + .supplier(createProductDto.getSupplier()) + .price(createProductDto.getPrice()) + .cost(createProductDto.getCost()) + .build()); } -} \ No newline at end of file +} diff --git a/data-transfer-object/src/test/java/com/iluwatar/datatransfer/AppTest.java b/data-transfer-object/src/test/java/com/iluwatar/datatransfer/AppTest.java index 49edb5c73..d0e32976c 100644 --- a/data-transfer-object/src/test/java/com/iluwatar/datatransfer/AppTest.java +++ b/data-transfer-object/src/test/java/com/iluwatar/datatransfer/AppTest.java @@ -24,21 +24,20 @@ */ package com.iluwatar.datatransfer; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import org.junit.jupiter.api.Test; + class AppTest { /** * Issue: Add at least one assertion to this test case. * - * Solution: Inserted assertion to check whether the execution of the main method in {@link App#main(String[])} - * throws an exception. + *

Solution: Inserted assertion to check whether the execution of the main method in {@link + * App#main(String[])} throws an exception. */ - @Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/data-transfer-object/src/test/java/com/iluwatar/datatransfer/customer/CustomerResourceTest.java b/data-transfer-object/src/test/java/com/iluwatar/datatransfer/customer/CustomerResourceTest.java index 1a90a15e1..006fd0b23 100644 --- a/data-transfer-object/src/test/java/com/iluwatar/datatransfer/customer/CustomerResourceTest.java +++ b/data-transfer-object/src/test/java/com/iluwatar/datatransfer/customer/CustomerResourceTest.java @@ -31,9 +31,7 @@ import java.util.ArrayList; import java.util.List; import org.junit.jupiter.api.Test; -/** - * tests {@link CustomerResource}. - */ +/** tests {@link CustomerResource}. */ class CustomerResourceTest { @Test diff --git a/decorator/pom.xml b/decorator/pom.xml index 60e8f493e..380e3a634 100644 --- a/decorator/pom.xml +++ b/decorator/pom.xml @@ -34,6 +34,14 @@ decorator + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/decorator/src/main/java/com/iluwatar/decorator/ClubbedTroll.java b/decorator/src/main/java/com/iluwatar/decorator/ClubbedTroll.java index 127fd8d23..10110facd 100644 --- a/decorator/src/main/java/com/iluwatar/decorator/ClubbedTroll.java +++ b/decorator/src/main/java/com/iluwatar/decorator/ClubbedTroll.java @@ -27,9 +27,7 @@ package com.iluwatar.decorator; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; -/** - * Decorator that adds a club for the troll. - */ +/** Decorator that adds a club for the troll. */ @Slf4j @RequiredArgsConstructor public class ClubbedTroll implements Troll { diff --git a/decorator/src/main/java/com/iluwatar/decorator/SimpleTroll.java b/decorator/src/main/java/com/iluwatar/decorator/SimpleTroll.java index cc13c95da..2c1789611 100644 --- a/decorator/src/main/java/com/iluwatar/decorator/SimpleTroll.java +++ b/decorator/src/main/java/com/iluwatar/decorator/SimpleTroll.java @@ -26,9 +26,7 @@ package com.iluwatar.decorator; import lombok.extern.slf4j.Slf4j; -/** - * SimpleTroll implements {@link Troll} interface directly. - */ +/** SimpleTroll implements {@link Troll} interface directly. */ @Slf4j public class SimpleTroll implements Troll { diff --git a/decorator/src/main/java/com/iluwatar/decorator/Troll.java b/decorator/src/main/java/com/iluwatar/decorator/Troll.java index aba900a9c..8c2ff3913 100644 --- a/decorator/src/main/java/com/iluwatar/decorator/Troll.java +++ b/decorator/src/main/java/com/iluwatar/decorator/Troll.java @@ -1,38 +1,35 @@ -/* - * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). - * - * The MIT License - * Copyright © 2014-2022 Ilkka Seppälä - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package com.iluwatar.decorator; - -/** - * Interface for trolls. - */ -public interface Troll { - - void attack(); - - int getAttackPower(); - - void fleeBattle(); - -} +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.decorator; + +/** Interface for trolls. */ +public interface Troll { + + void attack(); + + int getAttackPower(); + + void fleeBattle(); +} diff --git a/decorator/src/test/java/com/iluwatar/decorator/AppTest.java b/decorator/src/test/java/com/iluwatar/decorator/AppTest.java index 15285dd11..917057446 100644 --- a/decorator/src/test/java/com/iluwatar/decorator/AppTest.java +++ b/decorator/src/test/java/com/iluwatar/decorator/AppTest.java @@ -24,23 +24,19 @@ */ package com.iluwatar.decorator; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -/** - * Application test - */ +import org.junit.jupiter.api.Test; + +/** Application test */ class AppTest { /** - * Issue: Add at least one assertion to this test case. - * Solution: Inserted assertion to check whether the execution of the main method in {@link App#main(String[])} - * throws an exception. + * Issue: Add at least one assertion to this test case. Solution: Inserted assertion to check + * whether the execution of the main method in {@link App#main(String[])} throws an exception. */ - @Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/decorator/src/test/java/com/iluwatar/decorator/ClubbedTrollTest.java b/decorator/src/test/java/com/iluwatar/decorator/ClubbedTrollTest.java index 1dd6cb188..8f06a9712 100644 --- a/decorator/src/test/java/com/iluwatar/decorator/ClubbedTrollTest.java +++ b/decorator/src/test/java/com/iluwatar/decorator/ClubbedTrollTest.java @@ -32,9 +32,7 @@ import static org.mockito.internal.verification.VerificationModeFactory.times; import org.junit.jupiter.api.Test; -/** - * Tests for {@link ClubbedTroll} - */ +/** Tests for {@link ClubbedTroll} */ class ClubbedTrollTest { @Test diff --git a/decorator/src/test/java/com/iluwatar/decorator/SimpleTrollTest.java b/decorator/src/test/java/com/iluwatar/decorator/SimpleTrollTest.java index 65bde0455..fd14fb9da 100644 --- a/decorator/src/test/java/com/iluwatar/decorator/SimpleTrollTest.java +++ b/decorator/src/test/java/com/iluwatar/decorator/SimpleTrollTest.java @@ -36,9 +36,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.slf4j.LoggerFactory; -/** - * Tests for {@link SimpleTroll} - */ +/** Tests for {@link SimpleTroll} */ class SimpleTrollTest { private InMemoryAppender appender; diff --git a/delegation/pom.xml b/delegation/pom.xml index d1f18027e..ec9c1c76a 100644 --- a/delegation/pom.xml +++ b/delegation/pom.xml @@ -34,6 +34,14 @@ 4.0.0 delegation + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/delegation/src/main/java/com/iluwatar/delegation/simple/App.java b/delegation/src/main/java/com/iluwatar/delegation/simple/App.java index 7986643c6..a7c6dff3a 100644 --- a/delegation/src/main/java/com/iluwatar/delegation/simple/App.java +++ b/delegation/src/main/java/com/iluwatar/delegation/simple/App.java @@ -60,5 +60,4 @@ public class App { canonPrinterController.print(MESSAGE_TO_PRINT); epsonPrinterController.print(MESSAGE_TO_PRINT); } - } diff --git a/delegation/src/main/java/com/iluwatar/delegation/simple/printers/CanonPrinter.java b/delegation/src/main/java/com/iluwatar/delegation/simple/printers/CanonPrinter.java index 1490c1768..744752256 100644 --- a/delegation/src/main/java/com/iluwatar/delegation/simple/printers/CanonPrinter.java +++ b/delegation/src/main/java/com/iluwatar/delegation/simple/printers/CanonPrinter.java @@ -36,12 +36,9 @@ import lombok.extern.slf4j.Slf4j; @Slf4j public class CanonPrinter implements Printer { - /** - * {@inheritDoc} - */ + /** {@inheritDoc} */ @Override public void print(String message) { LOGGER.info("Canon Printer : {}", message); } - } diff --git a/delegation/src/main/java/com/iluwatar/delegation/simple/printers/EpsonPrinter.java b/delegation/src/main/java/com/iluwatar/delegation/simple/printers/EpsonPrinter.java index 4fcac417f..9ede17ded 100644 --- a/delegation/src/main/java/com/iluwatar/delegation/simple/printers/EpsonPrinter.java +++ b/delegation/src/main/java/com/iluwatar/delegation/simple/printers/EpsonPrinter.java @@ -28,20 +28,17 @@ import com.iluwatar.delegation.simple.Printer; import lombok.extern.slf4j.Slf4j; /** - * Specialised Implementation of {@link Printer} for an Epson Printer, in this case the message to be - * printed is appended to "Epson Printer : ". + * Specialised Implementation of {@link Printer} for an Epson Printer, in this case the message to + * be printed is appended to "Epson Printer : ". * * @see Printer */ @Slf4j public class EpsonPrinter implements Printer { - /** - * {@inheritDoc} - */ + /** {@inheritDoc} */ @Override public void print(String message) { LOGGER.info("Epson Printer : {}", message); } - } diff --git a/delegation/src/main/java/com/iluwatar/delegation/simple/printers/HpPrinter.java b/delegation/src/main/java/com/iluwatar/delegation/simple/printers/HpPrinter.java index 1705a775e..a7f210bca 100644 --- a/delegation/src/main/java/com/iluwatar/delegation/simple/printers/HpPrinter.java +++ b/delegation/src/main/java/com/iluwatar/delegation/simple/printers/HpPrinter.java @@ -36,12 +36,9 @@ import lombok.extern.slf4j.Slf4j; @Slf4j public class HpPrinter implements Printer { - /** - * {@inheritDoc} - */ + /** {@inheritDoc} */ @Override public void print(String message) { LOGGER.info("HP Printer : {}", message); } - } 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 cd57181c2..8ad967c9d 100644 --- a/delegation/src/test/java/com/iluwatar/delegation/simple/AppTest.java +++ b/delegation/src/test/java/com/iluwatar/delegation/simple/AppTest.java @@ -24,24 +24,19 @@ */ package com.iluwatar.delegation.simple; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -/** - * Application Test Entry - */ +import org.junit.jupiter.api.Test; + +/** Application Test Entry */ class AppTest { /** - * Issue: Add at least one assertion to this test case. - * Solution: Inserted assertion to check whether the execution of the main method in {@link App#main(String[])} - * throws an exception. + * Issue: Add at least one assertion to this test case. Solution: Inserted assertion to check + * whether the execution of the main method in {@link App#main(String[])} throws an exception. */ - @Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } - } 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 4c0273f68..7160eb56a 100644 --- a/delegation/src/test/java/com/iluwatar/delegation/simple/DelegateTest.java +++ b/delegation/src/test/java/com/iluwatar/delegation/simple/DelegateTest.java @@ -39,9 +39,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.slf4j.LoggerFactory; -/** - * Test for Delegation Pattern - */ +/** Test for Delegation Pattern */ class DelegateTest { private InMemoryAppender appender; @@ -82,9 +80,7 @@ class DelegateTest { assertEquals("Epson Printer : Test Message Printed", appender.getLastMessage()); } - /** - * Logging Appender - */ + /** Logging Appender */ private static class InMemoryAppender extends AppenderBase { private final List log = new LinkedList<>(); @@ -107,5 +103,4 @@ class DelegateTest { return log.size(); } } - } diff --git a/dependency-injection/pom.xml b/dependency-injection/pom.xml index 71d18bd2e..f0626f2cd 100644 --- a/dependency-injection/pom.xml +++ b/dependency-injection/pom.xml @@ -34,6 +34,14 @@ dependency-injection + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/dependency-injection/src/main/java/com/iluwatar/dependency/injection/AdvancedSorceress.java b/dependency-injection/src/main/java/com/iluwatar/dependency/injection/AdvancedSorceress.java index 95f2e0857..0ebf875c2 100644 --- a/dependency-injection/src/main/java/com/iluwatar/dependency/injection/AdvancedSorceress.java +++ b/dependency-injection/src/main/java/com/iluwatar/dependency/injection/AdvancedSorceress.java @@ -1,42 +1,42 @@ -/* - * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). - * - * The MIT License - * Copyright © 2014-2022 Ilkka Seppälä - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package com.iluwatar.dependency.injection; - -import lombok.Setter; - -/** - * AdvancedSorceress implements inversion of control. It depends on abstraction that can be injected - * through its setter. - */ -@Setter -public class AdvancedSorceress implements Wizard { - - private Tobacco tobacco; - - @Override - public void smoke() { - tobacco.smoke(this); - } -} +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.dependency.injection; + +import lombok.Setter; + +/** + * AdvancedSorceress implements inversion of control. It depends on abstraction that can be injected + * through its setter. + */ +@Setter +public class AdvancedSorceress implements Wizard { + + private Tobacco tobacco; + + @Override + public void smoke() { + tobacco.smoke(this); + } +} diff --git a/dependency-injection/src/main/java/com/iluwatar/dependency/injection/App.java b/dependency-injection/src/main/java/com/iluwatar/dependency/injection/App.java index 1b52a315f..2f8ecf07f 100644 --- a/dependency-injection/src/main/java/com/iluwatar/dependency/injection/App.java +++ b/dependency-injection/src/main/java/com/iluwatar/dependency/injection/App.java @@ -32,16 +32,15 @@ import com.google.inject.Guice; * - High-level modules should not depend on low-level modules. Both should depend on abstractions. * - Abstractions should not depend on details. Details should depend on abstractions. * - *

In this example we show you three different wizards. The first one ({@link SimpleWizard}) is - * a naive implementation violating the inversion of control principle. It depends directly on a + *

In this example we show you three different wizards. The first one ({@link SimpleWizard}) is a + * naive implementation violating the inversion of control principle. It depends directly on a * concrete implementation which cannot be changed. * *

The second and third wizards({@link AdvancedWizard} and {@link AdvancedSorceress}) are more * flexible. They do not depend on any concrete implementation but abstraction. They utilize * Dependency Injection pattern allowing their {@link Tobacco} dependency to be injected through * constructor ({@link AdvancedWizard}) or setter ({@link AdvancedSorceress}). This way, handling - * the dependency is no longer the wizard's responsibility. It is resolved outside the wizard - * class. + * the dependency is no longer the wizard's responsibility. It is resolved outside the wizard class. * *

The fourth example takes the pattern a step further. It uses Guice framework for Dependency * Injection. {@link TobaccoModule} binds a concrete implementation to abstraction. Injector is then diff --git a/dependency-injection/src/main/java/com/iluwatar/dependency/injection/OldTobyTobacco.java b/dependency-injection/src/main/java/com/iluwatar/dependency/injection/OldTobyTobacco.java index 6538415de..0bdd5479c 100644 --- a/dependency-injection/src/main/java/com/iluwatar/dependency/injection/OldTobyTobacco.java +++ b/dependency-injection/src/main/java/com/iluwatar/dependency/injection/OldTobyTobacco.java @@ -24,8 +24,5 @@ */ package com.iluwatar.dependency.injection; -/** - * OldTobyTobacco concrete {@link Tobacco} implementation. - */ -public class OldTobyTobacco extends Tobacco { -} +/** OldTobyTobacco concrete {@link Tobacco} implementation. */ +public class OldTobyTobacco extends Tobacco {} diff --git a/dependency-injection/src/main/java/com/iluwatar/dependency/injection/RivendellTobacco.java b/dependency-injection/src/main/java/com/iluwatar/dependency/injection/RivendellTobacco.java index 1f971d3cf..1238a7594 100644 --- a/dependency-injection/src/main/java/com/iluwatar/dependency/injection/RivendellTobacco.java +++ b/dependency-injection/src/main/java/com/iluwatar/dependency/injection/RivendellTobacco.java @@ -24,8 +24,5 @@ */ package com.iluwatar.dependency.injection; -/** - * RivendellTobacco concrete {@link Tobacco} implementation. - */ -public class RivendellTobacco extends Tobacco { -} +/** RivendellTobacco concrete {@link Tobacco} implementation. */ +public class RivendellTobacco extends Tobacco {} diff --git a/dependency-injection/src/main/java/com/iluwatar/dependency/injection/SecondBreakfastTobacco.java b/dependency-injection/src/main/java/com/iluwatar/dependency/injection/SecondBreakfastTobacco.java index 951df91e6..34cf201f4 100644 --- a/dependency-injection/src/main/java/com/iluwatar/dependency/injection/SecondBreakfastTobacco.java +++ b/dependency-injection/src/main/java/com/iluwatar/dependency/injection/SecondBreakfastTobacco.java @@ -24,8 +24,5 @@ */ package com.iluwatar.dependency.injection; -/** - * SecondBreakfastTobacco concrete {@link Tobacco} implementation. - */ -public class SecondBreakfastTobacco extends Tobacco { -} +/** SecondBreakfastTobacco concrete {@link Tobacco} implementation. */ +public class SecondBreakfastTobacco extends Tobacco {} diff --git a/dependency-injection/src/main/java/com/iluwatar/dependency/injection/Tobacco.java b/dependency-injection/src/main/java/com/iluwatar/dependency/injection/Tobacco.java index b62fc6f76..b1aa7e87c 100644 --- a/dependency-injection/src/main/java/com/iluwatar/dependency/injection/Tobacco.java +++ b/dependency-injection/src/main/java/com/iluwatar/dependency/injection/Tobacco.java @@ -26,14 +26,12 @@ package com.iluwatar.dependency.injection; import lombok.extern.slf4j.Slf4j; -/** - * Tobacco abstraction. - */ +/** Tobacco abstraction. */ @Slf4j public abstract class Tobacco { public void smoke(Wizard wizard) { - LOGGER.info("{} smoking {}", wizard.getClass().getSimpleName(), - this.getClass().getSimpleName()); + LOGGER.info( + "{} smoking {}", wizard.getClass().getSimpleName(), this.getClass().getSimpleName()); } } diff --git a/dependency-injection/src/main/java/com/iluwatar/dependency/injection/TobaccoModule.java b/dependency-injection/src/main/java/com/iluwatar/dependency/injection/TobaccoModule.java index 4880878f5..0dc6a6d3b 100644 --- a/dependency-injection/src/main/java/com/iluwatar/dependency/injection/TobaccoModule.java +++ b/dependency-injection/src/main/java/com/iluwatar/dependency/injection/TobaccoModule.java @@ -26,9 +26,7 @@ package com.iluwatar.dependency.injection; import com.google.inject.AbstractModule; -/** - * Guice module for binding certain concrete {@link Tobacco} implementation. - */ +/** Guice module for binding certain concrete {@link Tobacco} implementation. */ public class TobaccoModule extends AbstractModule { @Override diff --git a/dependency-injection/src/main/java/com/iluwatar/dependency/injection/Wizard.java b/dependency-injection/src/main/java/com/iluwatar/dependency/injection/Wizard.java index 55ceead12..4ba641727 100644 --- a/dependency-injection/src/main/java/com/iluwatar/dependency/injection/Wizard.java +++ b/dependency-injection/src/main/java/com/iluwatar/dependency/injection/Wizard.java @@ -24,11 +24,8 @@ */ package com.iluwatar.dependency.injection; -/** - * Wizard interface. - */ +/** Wizard interface. */ public interface Wizard { void smoke(); - } diff --git a/dependency-injection/src/test/java/com/iluwatar/dependency/injection/AdvancedSorceressTest.java b/dependency-injection/src/test/java/com/iluwatar/dependency/injection/AdvancedSorceressTest.java index c00e980d3..f2cf32db0 100644 --- a/dependency-injection/src/test/java/com/iluwatar/dependency/injection/AdvancedSorceressTest.java +++ b/dependency-injection/src/test/java/com/iluwatar/dependency/injection/AdvancedSorceressTest.java @@ -1,81 +1,74 @@ -/* - * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). - * - * The MIT License - * Copyright © 2014-2022 Ilkka Seppälä - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package com.iluwatar.dependency.injection; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import com.iluwatar.dependency.injection.utils.InMemoryAppender; -import java.util.List; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - - -/** - * AdvancedSorceressTest - * - */ - -class AdvancedSorceressTest { - - private InMemoryAppender appender; - - @BeforeEach - void setUp() { - appender = new InMemoryAppender(Tobacco.class); - } - - @AfterEach - void tearDown() { - appender.stop(); - } - - /** - * Test if the {@link AdvancedSorceress} smokes whatever instance of {@link Tobacco} is passed to - * her through the setter's parameter - */ - @Test - void testSmokeEveryThing() { - - List tobaccos = List.of( - new OldTobyTobacco(), - new RivendellTobacco(), - new SecondBreakfastTobacco() - ); - - // Verify if the sorceress is smoking the correct tobacco ... - tobaccos.forEach(tobacco -> { - final var advancedSorceress = new AdvancedSorceress(); - advancedSorceress.setTobacco(tobacco); - advancedSorceress.smoke(); - String lastMessage = appender.getLastMessage(); - assertEquals("AdvancedSorceress smoking " + tobacco.getClass().getSimpleName(), lastMessage); - }); - - // ... and nothing else is happening. - assertEquals(tobaccos.size(), appender.getLogSize()); - - } -} +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.dependency.injection; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import com.iluwatar.dependency.injection.utils.InMemoryAppender; +import java.util.List; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** AdvancedSorceressTest */ +class AdvancedSorceressTest { + + private InMemoryAppender appender; + + @BeforeEach + void setUp() { + appender = new InMemoryAppender(Tobacco.class); + } + + @AfterEach + void tearDown() { + appender.stop(); + } + + /** + * Test if the {@link AdvancedSorceress} smokes whatever instance of {@link Tobacco} is passed to + * her through the setter's parameter + */ + @Test + void testSmokeEveryThing() { + + List tobaccos = + List.of(new OldTobyTobacco(), new RivendellTobacco(), new SecondBreakfastTobacco()); + + // Verify if the sorceress is smoking the correct tobacco ... + tobaccos.forEach( + tobacco -> { + final var advancedSorceress = new AdvancedSorceress(); + advancedSorceress.setTobacco(tobacco); + advancedSorceress.smoke(); + String lastMessage = appender.getLastMessage(); + assertEquals( + "AdvancedSorceress smoking " + tobacco.getClass().getSimpleName(), lastMessage); + }); + + // ... and nothing else is happening. + assertEquals(tobaccos.size(), appender.getLogSize()); + } +} diff --git a/dependency-injection/src/test/java/com/iluwatar/dependency/injection/AdvancedWizardTest.java b/dependency-injection/src/test/java/com/iluwatar/dependency/injection/AdvancedWizardTest.java index 6c6b37d1a..7a1692db6 100644 --- a/dependency-injection/src/test/java/com/iluwatar/dependency/injection/AdvancedWizardTest.java +++ b/dependency-injection/src/test/java/com/iluwatar/dependency/injection/AdvancedWizardTest.java @@ -32,11 +32,7 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; - -/** - * AdvancedWizardTest - * - */ +/** AdvancedWizardTest */ class AdvancedWizardTest { private InMemoryAppender appender; @@ -58,23 +54,19 @@ class AdvancedWizardTest { @Test void testSmokeEveryThing() { - List tobaccos = List.of( - new OldTobyTobacco(), - new RivendellTobacco(), - new SecondBreakfastTobacco() - ); + List tobaccos = + List.of(new OldTobyTobacco(), new RivendellTobacco(), new SecondBreakfastTobacco()); // Verify if the wizard is smoking the correct tobacco ... - tobaccos.forEach(tobacco -> { - final AdvancedWizard advancedWizard = new AdvancedWizard(tobacco); - advancedWizard.smoke(); - String lastMessage = appender.getLastMessage(); - assertEquals("AdvancedWizard smoking " + tobacco.getClass().getSimpleName(), lastMessage); - }); + tobaccos.forEach( + tobacco -> { + final AdvancedWizard advancedWizard = new AdvancedWizard(tobacco); + advancedWizard.smoke(); + String lastMessage = appender.getLastMessage(); + assertEquals("AdvancedWizard smoking " + tobacco.getClass().getSimpleName(), lastMessage); + }); // ... and nothing else is happening. assertEquals(tobaccos.size(), appender.getLogSize()); - } - } diff --git a/dependency-injection/src/test/java/com/iluwatar/dependency/injection/AppTest.java b/dependency-injection/src/test/java/com/iluwatar/dependency/injection/AppTest.java index 3d3d4d409..1894227ec 100644 --- a/dependency-injection/src/test/java/com/iluwatar/dependency/injection/AppTest.java +++ b/dependency-injection/src/test/java/com/iluwatar/dependency/injection/AppTest.java @@ -24,23 +24,19 @@ */ package com.iluwatar.dependency.injection; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -/** - * Application test - */ +import org.junit.jupiter.api.Test; + +/** Application test */ class AppTest { /** - * Issue: Add at least one assertion to this test case. - * Solution: Inserted assertion to check whether the execution of the main method in {@link App#main(String[])} - * throws an exception. + * Issue: Add at least one assertion to this test case. Solution: Inserted assertion to check + * whether the execution of the main method in {@link App#main(String[])} throws an exception. */ - @Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/dependency-injection/src/test/java/com/iluwatar/dependency/injection/GuiceWizardTest.java b/dependency-injection/src/test/java/com/iluwatar/dependency/injection/GuiceWizardTest.java index 72bd95046..400a079d9 100644 --- a/dependency-injection/src/test/java/com/iluwatar/dependency/injection/GuiceWizardTest.java +++ b/dependency-injection/src/test/java/com/iluwatar/dependency/injection/GuiceWizardTest.java @@ -34,10 +34,7 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -/** - * GuiceWizardTest - * - */ +/** GuiceWizardTest */ class GuiceWizardTest { private InMemoryAppender appender; @@ -59,19 +56,17 @@ class GuiceWizardTest { @Test void testSmokeEveryThingThroughConstructor() { - List tobaccos = List.of( - new OldTobyTobacco(), - new RivendellTobacco(), - new SecondBreakfastTobacco() - ); + List tobaccos = + List.of(new OldTobyTobacco(), new RivendellTobacco(), new SecondBreakfastTobacco()); // Verify if the wizard is smoking the correct tobacco ... - tobaccos.forEach(tobacco -> { - final GuiceWizard guiceWizard = new GuiceWizard(tobacco); - guiceWizard.smoke(); - String lastMessage = appender.getLastMessage(); - assertEquals("GuiceWizard smoking " + tobacco.getClass().getSimpleName(), lastMessage); - }); + tobaccos.forEach( + tobacco -> { + final GuiceWizard guiceWizard = new GuiceWizard(tobacco); + guiceWizard.smoke(); + String lastMessage = appender.getLastMessage(); + assertEquals("GuiceWizard smoking " + tobacco.getClass().getSimpleName(), lastMessage); + }); // ... and nothing else is happening. assertEquals(tobaccos.size(), appender.getLogSize()); @@ -84,30 +79,29 @@ class GuiceWizardTest { @Test void testSmokeEveryThingThroughInjectionFramework() { - List> tobaccos = List.of( - OldTobyTobacco.class, - RivendellTobacco.class, - SecondBreakfastTobacco.class - ); + List> tobaccos = + List.of(OldTobyTobacco.class, RivendellTobacco.class, SecondBreakfastTobacco.class); // Configure the tobacco in the injection framework ... // ... and create a new wizard with it // Verify if the wizard is smoking the correct tobacco ... - tobaccos.forEach(tobaccoClass -> { - final var injector = Guice.createInjector(new AbstractModule() { - @Override - protected void configure() { - bind(Tobacco.class).to(tobaccoClass); - } - }); - final var guiceWizard = injector.getInstance(GuiceWizard.class); - guiceWizard.smoke(); - String lastMessage = appender.getLastMessage(); - assertEquals("GuiceWizard smoking " + tobaccoClass.getSimpleName(), lastMessage); - }); + tobaccos.forEach( + tobaccoClass -> { + final var injector = + Guice.createInjector( + new AbstractModule() { + @Override + protected void configure() { + bind(Tobacco.class).to(tobaccoClass); + } + }); + final var guiceWizard = injector.getInstance(GuiceWizard.class); + guiceWizard.smoke(); + String lastMessage = appender.getLastMessage(); + assertEquals("GuiceWizard smoking " + tobaccoClass.getSimpleName(), lastMessage); + }); // ... and nothing else is happening. assertEquals(tobaccos.size(), appender.getLogSize()); } - } diff --git a/dependency-injection/src/test/java/com/iluwatar/dependency/injection/SimpleWizardTest.java b/dependency-injection/src/test/java/com/iluwatar/dependency/injection/SimpleWizardTest.java index 7e2c8f047..f9354b49b 100644 --- a/dependency-injection/src/test/java/com/iluwatar/dependency/injection/SimpleWizardTest.java +++ b/dependency-injection/src/test/java/com/iluwatar/dependency/injection/SimpleWizardTest.java @@ -31,10 +31,7 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -/** - * SimpleWizardTest - * - */ +/** SimpleWizardTest */ class SimpleWizardTest { private InMemoryAppender appender; @@ -60,5 +57,4 @@ class SimpleWizardTest { assertEquals("SimpleWizard smoking OldTobyTobacco", appender.getLastMessage()); assertEquals(1, appender.getLogSize()); } - } 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 f39877810..319216e18 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 @@ -27,14 +27,11 @@ package com.iluwatar.dependency.injection.utils; import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.AppenderBase; -import org.slf4j.LoggerFactory; import java.util.LinkedList; import java.util.List; +import org.slf4j.LoggerFactory; - -/** - * InMemory Log Appender Util. - */ +/** InMemory Log Appender Util. */ public class InMemoryAppender extends AppenderBase { private final List log = new LinkedList<>(); diff --git a/dirty-flag/pom.xml b/dirty-flag/pom.xml index 2bbbf285d..d6032c589 100644 --- a/dirty-flag/pom.xml +++ b/dirty-flag/pom.xml @@ -40,6 +40,14 @@ UTF-8 + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/dirty-flag/src/main/java/com/iluwatar/dirtyflag/App.java b/dirty-flag/src/main/java/com/iluwatar/dirtyflag/App.java index 595f1889b..6798c68ea 100644 --- a/dirty-flag/src/main/java/com/iluwatar/dirtyflag/App.java +++ b/dirty-flag/src/main/java/com/iluwatar/dirtyflag/App.java @@ -36,16 +36,16 @@ import lombok.extern.slf4j.Slf4j; * calculated will need to be calculated again when they’re requested. Once the results are * re-calculated, then the bool value can be cleared. * - *

There are some points that need to be considered before diving into using this pattern:- - * there are some things you’ll need to consider:- (1) Do you need it? This design pattern works - * well when the results to be calculated are difficult or resource intensive to compute. You want - * to save them. You also don’t want to be calculating them several times in a row when only the - * last one counts. (2) When do you set the dirty flag? Make sure that you set the dirty flag within - * the class itself whenever an important property changes. This property should affect the result - * of the calculated result and by changing the property, that makes the last result invalid. (3) - * When do you clear the dirty flag? It might seem obvious that the dirty flag should be cleared - * whenever the result is calculated with up-to-date information but there are other times when you - * might want to clear the flag. + *

There are some points that need to be considered before diving into using this pattern:- there + * are some things you’ll need to consider:- (1) Do you need it? This design pattern works well when + * the results to be calculated are difficult or resource intensive to compute. You want to save + * them. You also don’t want to be calculating them several times in a row when only the last one + * counts. (2) When do you set the dirty flag? Make sure that you set the dirty flag within the + * class itself whenever an important property changes. This property should affect the result of + * the calculated result and by changing the property, that makes the last result invalid. (3) When + * do you clear the dirty flag? It might seem obvious that the dirty flag should be cleared whenever + * the result is calculated with up-to-date information but there are other times when you might + * want to clear the flag. * *

In this example, the {@link DataFetcher} holds the dirty flag. It fetches and * re-fetches from world.txt when needed. {@link World} mainly serves the data to the @@ -54,21 +54,23 @@ import lombok.extern.slf4j.Slf4j; @Slf4j public class App { - /** - * Program execution point. - */ + /** Program execution point. */ public void run() { final var executorService = Executors.newSingleThreadScheduledExecutor(); - executorService.scheduleAtFixedRate(new Runnable() { - final World world = new World(); + executorService.scheduleAtFixedRate( + new Runnable() { + final World world = new World(); - @Override - public void run() { - var countries = world.fetch(); - LOGGER.info("Our world currently has the following countries:-"); - countries.stream().map(country -> "\t" + country).forEach(LOGGER::info); - } - }, 0, 15, TimeUnit.SECONDS); // Run at every 15 seconds. + @Override + public void run() { + var countries = world.fetch(); + LOGGER.info("Our world currently has the following countries:-"); + countries.stream().map(country -> "\t" + country).forEach(LOGGER::info); + } + }, + 0, + 15, + TimeUnit.SECONDS); // Run at every 15 seconds. } /** diff --git a/dirty-flag/src/main/java/com/iluwatar/dirtyflag/DataFetcher.java b/dirty-flag/src/main/java/com/iluwatar/dirtyflag/DataFetcher.java index 88997b86e..0d902b3c0 100644 --- a/dirty-flag/src/main/java/com/iluwatar/dirtyflag/DataFetcher.java +++ b/dirty-flag/src/main/java/com/iluwatar/dirtyflag/DataFetcher.java @@ -32,10 +32,7 @@ import java.util.List; import java.util.stream.Collectors; import lombok.extern.slf4j.Slf4j; -/** - * A mock database manager -- Fetches data from a raw file. - * - */ +/** A mock database manager -- Fetches data from a raw file. */ @Slf4j public class DataFetcher { diff --git a/dirty-flag/src/main/java/com/iluwatar/dirtyflag/World.java b/dirty-flag/src/main/java/com/iluwatar/dirtyflag/World.java index 5c9201a62..bc876814b 100644 --- a/dirty-flag/src/main/java/com/iluwatar/dirtyflag/World.java +++ b/dirty-flag/src/main/java/com/iluwatar/dirtyflag/World.java @@ -27,10 +27,7 @@ package com.iluwatar.dirtyflag; import java.util.ArrayList; import java.util.List; -/** - * A middle-layer app that calls/passes along data from the back-end. - * - */ +/** A middle-layer app that calls/passes along data from the back-end. */ public class World { private List countries; diff --git a/dirty-flag/src/test/java/org/dirty/flag/AppTest.java b/dirty-flag/src/test/java/org/dirty/flag/AppTest.java index 8dc52ea44..8e09b0192 100644 --- a/dirty-flag/src/test/java/org/dirty/flag/AppTest.java +++ b/dirty-flag/src/test/java/org/dirty/flag/AppTest.java @@ -24,24 +24,20 @@ */ package org.dirty.flag; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + import com.iluwatar.dirtyflag.App; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; - -/** - * Tests that Dirty-Flag example runs without errors. - */ +/** Tests that Dirty-Flag example runs without errors. */ class AppTest { /** - * Issue: Add at least one assertion to this test case. - * Solution: Inserted assertion to check whether the execution of the main method in {@link App#main(String[])} - * throws an exception. + * Issue: Add at least one assertion to this test case. Solution: Inserted assertion to check + * whether the execution of the main method in {@link App#main(String[])} throws an exception. */ - @Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/dirty-flag/src/test/java/org/dirty/flag/DirtyFlagTest.java b/dirty-flag/src/test/java/org/dirty/flag/DirtyFlagTest.java index de0c62903..7d512deaf 100644 --- a/dirty-flag/src/test/java/org/dirty/flag/DirtyFlagTest.java +++ b/dirty-flag/src/test/java/org/dirty/flag/DirtyFlagTest.java @@ -28,9 +28,7 @@ import com.iluwatar.dirtyflag.DataFetcher; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -/** - * Application test - */ +/** Application test */ class DirtyFlagTest { @Test diff --git a/domain-model/pom.xml b/domain-model/pom.xml index 9eb7e23bf..933c18679 100644 --- a/domain-model/pom.xml +++ b/domain-model/pom.xml @@ -34,6 +34,14 @@ 4.0.0 domain-model + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + com.h2database h2 diff --git a/domain-model/src/main/java/com/iluwatar/domainmodel/App.java b/domain-model/src/main/java/com/iluwatar/domainmodel/App.java index aade9924a..3f209a35a 100644 --- a/domain-model/src/main/java/com/iluwatar/domainmodel/App.java +++ b/domain-model/src/main/java/com/iluwatar/domainmodel/App.java @@ -32,7 +32,6 @@ import javax.sql.DataSource; import org.h2.jdbcx.JdbcDataSource; import org.joda.money.Money; - /** * Domain Model pattern is a more complex solution for organizing domain logic than Transaction * Script and Table Module. It provides an object-oriented way of dealing with complicated logic. @@ -42,10 +41,10 @@ import org.joda.money.Money; * is that in Table Module a single class encapsulates all the domain logic for all records stored * in table when in Domain Model every single class represents only one record in underlying table. * - *

In this example, we will use the Domain Model pattern to implement buying of products - * by customers in a Shop. The main method will create a customer and a few products. - * Customer will do a few purchases, try to buy product which are too expensive for him, - * return product which he bought to return money.

+ *

In this example, we will use the Domain Model pattern to implement buying of products by + * customers in a Shop. The main method will create a customer and a few products. Customer will do + * a few purchases, try to buy product which are too expensive for him, return product which he + * bought to return money. */ public class App { @@ -80,11 +79,7 @@ public class App { var customerDao = new CustomerDaoImpl(dataSource); var tom = - Customer.builder() - .name("Tom") - .money(Money.of(USD, 30)) - .customerDao(customerDao) - .build(); + Customer.builder().name("Tom").money(Money.of(USD, 30)).customerDao(customerDao).build(); tom.save(); diff --git a/domain-model/src/main/java/com/iluwatar/domainmodel/Customer.java b/domain-model/src/main/java/com/iluwatar/domainmodel/Customer.java index e0f646a77..019a06c84 100644 --- a/domain-model/src/main/java/com/iluwatar/domainmodel/Customer.java +++ b/domain-model/src/main/java/com/iluwatar/domainmodel/Customer.java @@ -36,9 +36,8 @@ import lombok.extern.slf4j.Slf4j; import org.joda.money.Money; /** - * This class organizes domain logic of customer. - * A single instance of this class - * contains both the data and behavior of a single customer. + * This class organizes domain logic of customer. A single instance of this class contains both the + * data and behavior of a single customer. */ @Slf4j @Getter @@ -51,9 +50,7 @@ public class Customer { @NonNull private String name; @NonNull private Money money; - /** - * Save customer or update if customer already exist. - */ + /** Save customer or update if customer already exist. */ public void save() { try { Optional customer = customerDao.findByName(name); @@ -117,9 +114,7 @@ public class Customer { } } - /** - * Print customer's purchases. - */ + /** Print customer's purchases. */ public void showPurchases() { Optional purchasesToShow = purchases.stream() @@ -133,9 +128,7 @@ public class Customer { } } - /** - * Print customer's money balance. - */ + /** Print customer's money balance. */ public void showBalance() { LOGGER.info(name + " balance: " + money); } diff --git a/domain-model/src/main/java/com/iluwatar/domainmodel/CustomerDao.java b/domain-model/src/main/java/com/iluwatar/domainmodel/CustomerDao.java index 1375a0323..18db0ab0b 100644 --- a/domain-model/src/main/java/com/iluwatar/domainmodel/CustomerDao.java +++ b/domain-model/src/main/java/com/iluwatar/domainmodel/CustomerDao.java @@ -27,9 +27,7 @@ package com.iluwatar.domainmodel; import java.sql.SQLException; import java.util.Optional; -/** - * DAO interface for customer transactions. - */ +/** DAO interface for customer transactions. */ public interface CustomerDao { Optional findByName(String name) throws SQLException; diff --git a/domain-model/src/main/java/com/iluwatar/domainmodel/CustomerDaoImpl.java b/domain-model/src/main/java/com/iluwatar/domainmodel/CustomerDaoImpl.java index b24da7a49..cff4e30bc 100644 --- a/domain-model/src/main/java/com/iluwatar/domainmodel/CustomerDaoImpl.java +++ b/domain-model/src/main/java/com/iluwatar/domainmodel/CustomerDaoImpl.java @@ -32,9 +32,7 @@ import java.util.Optional; import javax.sql.DataSource; import org.joda.money.Money; -/** - * Implementations for database operations of Customer. - */ +/** Implementations for database operations of Customer. */ public class CustomerDaoImpl implements CustomerDao { private final DataSource dataSource; diff --git a/domain-model/src/main/java/com/iluwatar/domainmodel/Product.java b/domain-model/src/main/java/com/iluwatar/domainmodel/Product.java index 6d2f37a02..9d9177977 100644 --- a/domain-model/src/main/java/com/iluwatar/domainmodel/Product.java +++ b/domain-model/src/main/java/com/iluwatar/domainmodel/Product.java @@ -40,9 +40,8 @@ import lombok.extern.slf4j.Slf4j; import org.joda.money.Money; /** - * This class organizes domain logic of product. - * A single instance of this class - * contains both the data and behavior of a single product. + * This class organizes domain logic of product. A single instance of this class contains both the + * data and behavior of a single product. */ @Slf4j @Getter @@ -59,9 +58,7 @@ public class Product { @NonNull private Money price; @NonNull private LocalDate expirationDate; - /** - * Save product or update if product already exist. - */ + /** Save product or update if product already exist. */ public void save() { try { Optional product = productDao.findByName(name); @@ -75,16 +72,14 @@ public class Product { } } - /** - * Calculate sale price of product with discount. - */ + /** Calculate sale price of product with discount. */ public Money getSalePrice() { return price.minus(calculateDiscount()); } private Money calculateDiscount() { if (ChronoUnit.DAYS.between(LocalDate.now(), expirationDate) - < DAYS_UNTIL_EXPIRATION_WHEN_DISCOUNT_ACTIVE) { + < DAYS_UNTIL_EXPIRATION_WHEN_DISCOUNT_ACTIVE) { return price.multipliedBy(DISCOUNT_RATE, RoundingMode.DOWN); } diff --git a/domain-model/src/main/java/com/iluwatar/domainmodel/ProductDao.java b/domain-model/src/main/java/com/iluwatar/domainmodel/ProductDao.java index bfedc5098..5a2644829 100644 --- a/domain-model/src/main/java/com/iluwatar/domainmodel/ProductDao.java +++ b/domain-model/src/main/java/com/iluwatar/domainmodel/ProductDao.java @@ -27,9 +27,7 @@ package com.iluwatar.domainmodel; import java.sql.SQLException; import java.util.Optional; -/** - * DAO interface for product transactions. - */ +/** DAO interface for product transactions. */ public interface ProductDao { Optional findByName(String name) throws SQLException; diff --git a/domain-model/src/main/java/com/iluwatar/domainmodel/ProductDaoImpl.java b/domain-model/src/main/java/com/iluwatar/domainmodel/ProductDaoImpl.java index 781bc3a80..6313e8afa 100644 --- a/domain-model/src/main/java/com/iluwatar/domainmodel/ProductDaoImpl.java +++ b/domain-model/src/main/java/com/iluwatar/domainmodel/ProductDaoImpl.java @@ -33,9 +33,7 @@ import java.util.Optional; import javax.sql.DataSource; import org.joda.money.Money; -/** - * Implementations for database transactions of Product. - */ +/** Implementations for database transactions of Product. */ public class ProductDaoImpl implements ProductDao { private final DataSource dataSource; diff --git a/domain-model/src/test/java/com/iluwatar/domainmodel/AppTest.java b/domain-model/src/test/java/com/iluwatar/domainmodel/AppTest.java index 06a260e5f..f15b33c2d 100644 --- a/domain-model/src/test/java/com/iluwatar/domainmodel/AppTest.java +++ b/domain-model/src/test/java/com/iluwatar/domainmodel/AppTest.java @@ -24,10 +24,10 @@ */ package com.iluwatar.domainmodel; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import org.junit.jupiter.api.Test; + /** Tests that Domain Model example runs without errors. */ final class AppTest { @@ -35,5 +35,4 @@ final class AppTest { void shouldExecuteApplicationWithoutException() { assertDoesNotThrow(() -> App.main(new String[] {})); } - } diff --git a/domain-model/src/test/java/com/iluwatar/domainmodel/CustomerDaoImplTest.java b/domain-model/src/test/java/com/iluwatar/domainmodel/CustomerDaoImplTest.java index 9251420ba..aeab249ba 100644 --- a/domain-model/src/test/java/com/iluwatar/domainmodel/CustomerDaoImplTest.java +++ b/domain-model/src/test/java/com/iluwatar/domainmodel/CustomerDaoImplTest.java @@ -24,18 +24,18 @@ */ package com.iluwatar.domainmodel; +import static org.joda.money.CurrencyUnit.USD; +import static org.junit.jupiter.api.Assertions.*; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.time.LocalDate; +import javax.sql.DataSource; import org.joda.money.CurrencyUnit; import org.joda.money.Money; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import javax.sql.DataSource; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.time.LocalDate; - -import static org.joda.money.CurrencyUnit.USD; -import static org.junit.jupiter.api.Assertions.*; class CustomerDaoImplTest { @@ -62,7 +62,12 @@ class CustomerDaoImplTest { // setup objects customerDao = new CustomerDaoImpl(dataSource); - customer = Customer.builder().name("customer").money(Money.of(CurrencyUnit.USD,100.0)).customerDao(customerDao).build(); + customer = + Customer.builder() + .name("customer") + .money(Money.of(CurrencyUnit.USD, 100.0)) + .customerDao(customerDao) + .build(); product = Product.builder() diff --git a/domain-model/src/test/java/com/iluwatar/domainmodel/CustomerTest.java b/domain-model/src/test/java/com/iluwatar/domainmodel/CustomerTest.java index cb55f3303..9d5f83a92 100644 --- a/domain-model/src/test/java/com/iluwatar/domainmodel/CustomerTest.java +++ b/domain-model/src/test/java/com/iluwatar/domainmodel/CustomerTest.java @@ -24,89 +24,90 @@ */ package com.iluwatar.domainmodel; -import org.joda.money.CurrencyUnit; -import org.joda.money.Money; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; +import static org.joda.money.CurrencyUnit.USD; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.*; + import java.sql.SQLException; import java.time.LocalDate; import java.util.ArrayList; import java.util.Arrays; import java.util.Optional; - -import static org.joda.money.CurrencyUnit.USD; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.Mockito.*; +import org.joda.money.CurrencyUnit; +import org.joda.money.Money; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; class CustomerTest { - private CustomerDao customerDao; - private Customer customer; - private Product product; + private CustomerDao customerDao; + private Customer customer; + private Product product; - @BeforeEach - void setUp() { - customerDao = mock(CustomerDao.class); + @BeforeEach + void setUp() { + customerDao = mock(CustomerDao.class); - customer = Customer.builder() - .name("customer") - .money(Money.of(CurrencyUnit.USD, 100.0)) - .customerDao(customerDao) - .build(); + customer = + Customer.builder() + .name("customer") + .money(Money.of(CurrencyUnit.USD, 100.0)) + .customerDao(customerDao) + .build(); - product = Product.builder() - .name("product") - .price(Money.of(USD, 100.0)) - .expirationDate(LocalDate.now().plusDays(10)) - .productDao(mock(ProductDao.class)) - .build(); - } + product = + Product.builder() + .name("product") + .price(Money.of(USD, 100.0)) + .expirationDate(LocalDate.now().plusDays(10)) + .productDao(mock(ProductDao.class)) + .build(); + } - @Test - void shouldSaveCustomer() throws SQLException { - when(customerDao.findByName("customer")).thenReturn(Optional.empty()); + @Test + void shouldSaveCustomer() throws SQLException { + when(customerDao.findByName("customer")).thenReturn(Optional.empty()); - customer.save(); + customer.save(); - verify(customerDao, times(1)).save(customer); + verify(customerDao, times(1)).save(customer); - when(customerDao.findByName("customer")).thenReturn(Optional.of(customer)); + when(customerDao.findByName("customer")).thenReturn(Optional.of(customer)); - customer.save(); + customer.save(); - verify(customerDao, times(1)).update(customer); - } + verify(customerDao, times(1)).update(customer); + } - @Test - void shouldAddProductToPurchases() { - product.setPrice(Money.of(USD, 200.0)); + @Test + void shouldAddProductToPurchases() { + product.setPrice(Money.of(USD, 200.0)); - customer.buyProduct(product); + customer.buyProduct(product); - assertEquals(customer.getPurchases(), new ArrayList<>()); - assertEquals(customer.getMoney(), Money.of(USD,100)); + assertEquals(customer.getPurchases(), new ArrayList<>()); + assertEquals(customer.getMoney(), Money.of(USD, 100)); - product.setPrice(Money.of(USD, 100.0)); + product.setPrice(Money.of(USD, 100.0)); - customer.buyProduct(product); + customer.buyProduct(product); - assertEquals(new ArrayList<>(Arrays.asList(product)), customer.getPurchases()); - assertEquals(Money.zero(USD), customer.getMoney()); - } + assertEquals(new ArrayList<>(Arrays.asList(product)), customer.getPurchases()); + assertEquals(Money.zero(USD), customer.getMoney()); + } - @Test - void shouldRemoveProductFromPurchases() { - customer.setPurchases(new ArrayList<>(Arrays.asList(product))); + @Test + void shouldRemoveProductFromPurchases() { + customer.setPurchases(new ArrayList<>(Arrays.asList(product))); - customer.returnProduct(product); + customer.returnProduct(product); - assertEquals(new ArrayList<>(), customer.getPurchases()); - assertEquals(Money.of(USD, 200), customer.getMoney()); + assertEquals(new ArrayList<>(), customer.getPurchases()); + assertEquals(Money.of(USD, 200), customer.getMoney()); - customer.returnProduct(product); + customer.returnProduct(product); - assertEquals(new ArrayList<>(), customer.getPurchases()); - assertEquals(Money.of(USD, 200), customer.getMoney()); - } + assertEquals(new ArrayList<>(), customer.getPurchases()); + assertEquals(Money.of(USD, 200), customer.getMoney()); + } } - diff --git a/domain-model/src/test/java/com/iluwatar/domainmodel/ProductDaoImplTest.java b/domain-model/src/test/java/com/iluwatar/domainmodel/ProductDaoImplTest.java index ae2985afa..7631c3581 100644 --- a/domain-model/src/test/java/com/iluwatar/domainmodel/ProductDaoImplTest.java +++ b/domain-model/src/test/java/com/iluwatar/domainmodel/ProductDaoImplTest.java @@ -24,104 +24,104 @@ */ package com.iluwatar.domainmodel; +import static org.joda.money.CurrencyUnit.USD; +import static org.junit.jupiter.api.Assertions.*; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.time.LocalDate; +import javax.sql.DataSource; import org.joda.money.Money; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import javax.sql.DataSource; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.time.LocalDate; - -import static org.joda.money.CurrencyUnit.USD; -import static org.junit.jupiter.api.Assertions.*; class ProductDaoImplTest { - public static final String INSERT_PRODUCT_SQL = - "insert into PRODUCTS values('product', 100, DATE '2021-06-27')"; - public static final String SELECT_PRODUCTS_SQL = - "select name, price, expiration_date from PRODUCTS"; + public static final String INSERT_PRODUCT_SQL = + "insert into PRODUCTS values('product', 100, DATE '2021-06-27')"; + public static final String SELECT_PRODUCTS_SQL = + "select name, price, expiration_date from PRODUCTS"; - private DataSource dataSource; - private ProductDao productDao; - private Product product; + private DataSource dataSource; + private ProductDao productDao; + private Product product; - @BeforeEach - void setUp() throws SQLException { - // create schema - dataSource = TestUtils.createDataSource(); + @BeforeEach + void setUp() throws SQLException { + // create schema + dataSource = TestUtils.createDataSource(); - TestUtils.deleteSchema(dataSource); - TestUtils.createSchema(dataSource); + TestUtils.deleteSchema(dataSource); + TestUtils.createSchema(dataSource); - // setup objects - productDao = new ProductDaoImpl(dataSource); + // setup objects + productDao = new ProductDaoImpl(dataSource); - product = - Product.builder() - .name("product") - .price(Money.of(USD, 100.0)) - .expirationDate(LocalDate.parse("2021-06-27")) - .productDao(productDao) - .build(); + product = + Product.builder() + .name("product") + .price(Money.of(USD, 100.0)) + .expirationDate(LocalDate.parse("2021-06-27")) + .productDao(productDao) + .build(); + } + + @AfterEach + void tearDown() throws SQLException { + TestUtils.deleteSchema(dataSource); + } + + @Test + void shouldFindProductByName() throws SQLException { + var product = productDao.findByName("product"); + + assertTrue(product.isEmpty()); + + TestUtils.executeSQL(INSERT_PRODUCT_SQL, dataSource); + + product = productDao.findByName("product"); + + assertTrue(product.isPresent()); + assertEquals("product", product.get().getName()); + assertEquals(Money.of(USD, 100), product.get().getPrice()); + assertEquals(LocalDate.parse("2021-06-27"), product.get().getExpirationDate()); + } + + @Test + void shouldSaveProduct() throws SQLException { + + productDao.save(product); + + try (var connection = dataSource.getConnection(); + var statement = connection.createStatement(); + ResultSet rs = statement.executeQuery(SELECT_PRODUCTS_SQL)) { + + assertTrue(rs.next()); + assertEquals(product.getName(), rs.getString("name")); + assertEquals(product.getPrice(), Money.of(USD, rs.getBigDecimal("price"))); + assertEquals(product.getExpirationDate(), rs.getDate("expiration_date").toLocalDate()); } - @AfterEach - void tearDown() throws SQLException { - TestUtils.deleteSchema(dataSource); - } - - @Test - void shouldFindProductByName() throws SQLException { - var product = productDao.findByName("product"); - - assertTrue(product.isEmpty()); - - TestUtils.executeSQL(INSERT_PRODUCT_SQL, dataSource); - - product = productDao.findByName("product"); - - assertTrue(product.isPresent()); - assertEquals("product", product.get().getName()); - assertEquals(Money.of(USD, 100), product.get().getPrice()); - assertEquals(LocalDate.parse("2021-06-27"), product.get().getExpirationDate()); - } - - @Test - void shouldSaveProduct() throws SQLException { - - productDao.save(product); - - try (var connection = dataSource.getConnection(); - var statement = connection.createStatement(); - ResultSet rs = statement.executeQuery(SELECT_PRODUCTS_SQL)) { - - assertTrue(rs.next()); - assertEquals(product.getName(), rs.getString("name")); - assertEquals(product.getPrice(), Money.of(USD, rs.getBigDecimal("price"))); - assertEquals(product.getExpirationDate(), rs.getDate("expiration_date").toLocalDate()); - } - - assertThrows(SQLException.class, () -> productDao.save(product)); - } - - @Test - void shouldUpdateProduct() throws SQLException { - TestUtils.executeSQL(INSERT_PRODUCT_SQL, dataSource); - - product.setPrice(Money.of(USD, 99.0)); - - productDao.update(product); - - try (var connection = dataSource.getConnection(); - var statement = connection.createStatement(); - ResultSet rs = statement.executeQuery(SELECT_PRODUCTS_SQL)) { - - assertTrue(rs.next()); - assertEquals(product.getName(), rs.getString("name")); - assertEquals(product.getPrice(), Money.of(USD, rs.getBigDecimal("price"))); - assertEquals(product.getExpirationDate(), rs.getDate("expiration_date").toLocalDate()); - } + assertThrows(SQLException.class, () -> productDao.save(product)); + } + + @Test + void shouldUpdateProduct() throws SQLException { + TestUtils.executeSQL(INSERT_PRODUCT_SQL, dataSource); + + product.setPrice(Money.of(USD, 99.0)); + + productDao.update(product); + + try (var connection = dataSource.getConnection(); + var statement = connection.createStatement(); + ResultSet rs = statement.executeQuery(SELECT_PRODUCTS_SQL)) { + + assertTrue(rs.next()); + assertEquals(product.getName(), rs.getString("name")); + assertEquals(product.getPrice(), Money.of(USD, rs.getBigDecimal("price"))); + assertEquals(product.getExpirationDate(), rs.getDate("expiration_date").toLocalDate()); } + } } diff --git a/domain-model/src/test/java/com/iluwatar/domainmodel/ProductTest.java b/domain-model/src/test/java/com/iluwatar/domainmodel/ProductTest.java index f3326fe3b..f3193ce9b 100644 --- a/domain-model/src/test/java/com/iluwatar/domainmodel/ProductTest.java +++ b/domain-model/src/test/java/com/iluwatar/domainmodel/ProductTest.java @@ -24,55 +24,56 @@ */ package com.iluwatar.domainmodel; -import org.joda.money.Money; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import java.sql.SQLException; -import java.time.LocalDate; -import java.util.Optional; - import static org.joda.money.CurrencyUnit.USD; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.*; +import java.sql.SQLException; +import java.time.LocalDate; +import java.util.Optional; +import org.joda.money.Money; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + class ProductTest { - private ProductDao productDao; - private Product product; + private ProductDao productDao; + private Product product; - @BeforeEach - void setUp() { - productDao = mock(ProductDaoImpl.class); + @BeforeEach + void setUp() { + productDao = mock(ProductDaoImpl.class); - product = Product.builder() - .name("product") - .price(Money.of(USD, 100.0)) - .expirationDate(LocalDate.now().plusDays(10)) - .productDao(productDao) - .build(); - } + product = + Product.builder() + .name("product") + .price(Money.of(USD, 100.0)) + .expirationDate(LocalDate.now().plusDays(10)) + .productDao(productDao) + .build(); + } - @Test - void shouldSaveProduct() throws SQLException { - when(productDao.findByName("product")).thenReturn(Optional.empty()); + @Test + void shouldSaveProduct() throws SQLException { + when(productDao.findByName("product")).thenReturn(Optional.empty()); - product.save(); + product.save(); - verify(productDao, times(1)).save(product); + verify(productDao, times(1)).save(product); - when(productDao.findByName("product")).thenReturn(Optional.of(product)); + when(productDao.findByName("product")).thenReturn(Optional.of(product)); - product.save(); + product.save(); - verify(productDao, times(1)).update(product); - } + verify(productDao, times(1)).update(product); + } - @Test - void shouldGetSalePriceOfProduct() { - assertEquals(Money.of(USD, 100), product.getSalePrice()); + @Test + void shouldGetSalePriceOfProduct() { + assertEquals(Money.of(USD, 100), product.getSalePrice()); - product.setExpirationDate(LocalDate.now().plusDays(2)); + product.setExpirationDate(LocalDate.now().plusDays(2)); - assertEquals(Money.of(USD, 80), product.getSalePrice()); - } + assertEquals(Money.of(USD, 80), product.getSalePrice()); + } } diff --git a/domain-model/src/test/java/com/iluwatar/domainmodel/TestUtils.java b/domain-model/src/test/java/com/iluwatar/domainmodel/TestUtils.java index 5c788fa8e..8555cedc8 100644 --- a/domain-model/src/test/java/com/iluwatar/domainmodel/TestUtils.java +++ b/domain-model/src/test/java/com/iluwatar/domainmodel/TestUtils.java @@ -24,13 +24,13 @@ */ package com.iluwatar.domainmodel; -import org.h2.jdbcx.JdbcDataSource; -import javax.sql.DataSource; import java.sql.SQLException; +import javax.sql.DataSource; +import org.h2.jdbcx.JdbcDataSource; public class TestUtils { - public static void executeSQL( String sql, DataSource dataSource) throws SQLException { + public static void executeSQL(String sql, DataSource dataSource) throws SQLException { try (var connection = dataSource.getConnection(); var statement = connection.createStatement()) { statement.executeUpdate(sql); diff --git a/double-buffer/pom.xml b/double-buffer/pom.xml index 5718eddf1..ad5bf6c3e 100644 --- a/double-buffer/pom.xml +++ b/double-buffer/pom.xml @@ -34,9 +34,18 @@ 4.0.0 double-buffer + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.apache.commons commons-lang3 + 3.17.0 org.junit.jupiter diff --git a/double-buffer/src/main/java/com/iluwatar/doublebuffer/App.java b/double-buffer/src/main/java/com/iluwatar/doublebuffer/App.java index bbd4ad8d4..899f71466 100644 --- a/double-buffer/src/main/java/com/iluwatar/doublebuffer/App.java +++ b/double-buffer/src/main/java/com/iluwatar/doublebuffer/App.java @@ -45,19 +45,13 @@ public class App { */ public static void main(String[] args) { final var scene = new Scene(); - var drawPixels1 = List.of( - new MutablePair<>(1, 1), - new MutablePair<>(5, 6), - new MutablePair<>(3, 2) - ); + var drawPixels1 = + List.of(new MutablePair<>(1, 1), new MutablePair<>(5, 6), new MutablePair<>(3, 2)); scene.draw(drawPixels1); var buffer1 = scene.getBuffer(); printBlackPixelCoordinate(buffer1); - var drawPixels2 = List.of( - new MutablePair<>(3, 7), - new MutablePair<>(6, 1) - ); + var drawPixels2 = List.of(new MutablePair<>(3, 7), new MutablePair<>(6, 1)); scene.draw(drawPixels2); var buffer2 = scene.getBuffer(); printBlackPixelCoordinate(buffer2); diff --git a/double-buffer/src/main/java/com/iluwatar/doublebuffer/Buffer.java b/double-buffer/src/main/java/com/iluwatar/doublebuffer/Buffer.java index dfa2dbe48..191ad0e12 100644 --- a/double-buffer/src/main/java/com/iluwatar/doublebuffer/Buffer.java +++ b/double-buffer/src/main/java/com/iluwatar/doublebuffer/Buffer.java @@ -24,9 +24,7 @@ */ package com.iluwatar.doublebuffer; -/** - * Buffer interface. - */ +/** Buffer interface. */ public interface Buffer { /** @@ -45,9 +43,7 @@ public interface Buffer { */ void draw(int x, int y); - /** - * Clear all the pixels. - */ + /** Clear all the pixels. */ void clearAll(); /** @@ -56,5 +52,4 @@ public interface Buffer { * @return pixel list */ Pixel[] getPixels(); - } diff --git a/double-buffer/src/main/java/com/iluwatar/doublebuffer/FrameBuffer.java b/double-buffer/src/main/java/com/iluwatar/doublebuffer/FrameBuffer.java index ef86549b4..e015bb62e 100644 --- a/double-buffer/src/main/java/com/iluwatar/doublebuffer/FrameBuffer.java +++ b/double-buffer/src/main/java/com/iluwatar/doublebuffer/FrameBuffer.java @@ -26,9 +26,7 @@ package com.iluwatar.doublebuffer; import java.util.Arrays; -/** - * FrameBuffer implementation class. - */ +/** FrameBuffer implementation class. */ public class FrameBuffer implements Buffer { public static final int WIDTH = 10; diff --git a/double-buffer/src/main/java/com/iluwatar/doublebuffer/Pixel.java b/double-buffer/src/main/java/com/iluwatar/doublebuffer/Pixel.java index c6c2a1637..eea701e8a 100644 --- a/double-buffer/src/main/java/com/iluwatar/doublebuffer/Pixel.java +++ b/double-buffer/src/main/java/com/iluwatar/doublebuffer/Pixel.java @@ -24,11 +24,8 @@ */ package com.iluwatar.doublebuffer; -/** - * Pixel enum. Each pixel can be white (not drawn) or black (drawn). - */ +/** Pixel enum. Each pixel can be white (not drawn) or black (drawn). */ public enum Pixel { - WHITE, BLACK } diff --git a/double-buffer/src/main/java/com/iluwatar/doublebuffer/Scene.java b/double-buffer/src/main/java/com/iluwatar/doublebuffer/Scene.java index 692249dd0..79a528fab 100644 --- a/double-buffer/src/main/java/com/iluwatar/doublebuffer/Scene.java +++ b/double-buffer/src/main/java/com/iluwatar/doublebuffer/Scene.java @@ -28,9 +28,7 @@ import java.util.List; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.tuple.Pair; -/** - * Scene class. Render the output frame. - */ +/** Scene class. Render the output frame. */ @Slf4j public class Scene { @@ -40,9 +38,7 @@ public class Scene { private int next; - /** - * Constructor of Scene. - */ + /** Constructor of Scene. */ public Scene() { frameBuffers = new FrameBuffer[2]; frameBuffers[0] = new FrameBuffer(); @@ -60,11 +56,12 @@ public class Scene { LOGGER.info("Start drawing next frame"); LOGGER.info("Current buffer: " + current + " Next buffer: " + next); frameBuffers[next].clearAll(); - coordinateList.forEach(coordinate -> { - var x = coordinate.getKey(); - var y = coordinate.getValue(); - frameBuffers[next].draw(x, y); - }); + coordinateList.forEach( + coordinate -> { + var x = coordinate.getKey(); + var y = coordinate.getValue(); + frameBuffers[next].draw(x, y); + }); LOGGER.info("Swap current and next buffer"); swap(); LOGGER.info("Finish swapping"); @@ -81,5 +78,4 @@ public class Scene { next = current ^ next; current = current ^ next; } - } diff --git a/double-buffer/src/test/java/com/iluwatar/doublebuffer/AppTest.java b/double-buffer/src/test/java/com/iluwatar/doublebuffer/AppTest.java index 2338fde59..4c1d8674d 100644 --- a/double-buffer/src/test/java/com/iluwatar/doublebuffer/AppTest.java +++ b/double-buffer/src/test/java/com/iluwatar/doublebuffer/AppTest.java @@ -28,21 +28,17 @@ import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import org.junit.jupiter.api.Test; -/** - * App unit test. - */ +/** App unit test. */ class AppTest { /** * Issue: Add at least one assertion to this test case. - *

- * Solution: Inserted assertion to check whether the execution of the main method in {@link App#main(String[])} - * throws an exception. + * + *

Solution: Inserted assertion to check whether the execution of the main method in {@link + * App#main(String[])} throws an exception. */ - @Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } - } diff --git a/double-buffer/src/test/java/com/iluwatar/doublebuffer/FrameBufferTest.java b/double-buffer/src/test/java/com/iluwatar/doublebuffer/FrameBufferTest.java index ea842c3c5..2bd852a35 100644 --- a/double-buffer/src/test/java/com/iluwatar/doublebuffer/FrameBufferTest.java +++ b/double-buffer/src/test/java/com/iluwatar/doublebuffer/FrameBufferTest.java @@ -30,9 +30,7 @@ import static org.junit.jupiter.api.Assertions.fail; import java.util.Arrays; import org.junit.jupiter.api.Test; -/** - * FrameBuffer unit test. - */ +/** FrameBuffer unit test. */ class FrameBufferTest { @Test @@ -91,5 +89,4 @@ class FrameBufferTest { fail("Fail to modify field access."); } } - } diff --git a/double-buffer/src/test/java/com/iluwatar/doublebuffer/SceneTest.java b/double-buffer/src/test/java/com/iluwatar/doublebuffer/SceneTest.java index 6176bf792..41806e566 100644 --- a/double-buffer/src/test/java/com/iluwatar/doublebuffer/SceneTest.java +++ b/double-buffer/src/test/java/com/iluwatar/doublebuffer/SceneTest.java @@ -30,9 +30,7 @@ import static org.junit.jupiter.api.Assertions.fail; import java.util.ArrayList; import org.junit.jupiter.api.Test; -/** - * Scene unit tests. - */ +/** Scene unit tests. */ class SceneTest { @Test diff --git a/double-checked-locking/pom.xml b/double-checked-locking/pom.xml index a339de7c0..650c76700 100644 --- a/double-checked-locking/pom.xml +++ b/double-checked-locking/pom.xml @@ -33,6 +33,14 @@ double-checked-locking + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/double-checked-locking/src/main/java/com/iluwatar/doublechecked/locking/App.java b/double-checked-locking/src/main/java/com/iluwatar/doublechecked/locking/App.java index 8a5198229..99dd6d05c 100644 --- a/double-checked-locking/src/main/java/com/iluwatar/doublechecked/locking/App.java +++ b/double-checked-locking/src/main/java/com/iluwatar/doublechecked/locking/App.java @@ -35,10 +35,9 @@ import lombok.extern.slf4j.Slf4j; * lock. Only if the locking criterion check indicates that locking is required does the actual * locking logic proceed. * - *

In {@link Inventory} we store the items with a given size. However, we do not store more - * items than the inventory size. To address concurrent access problems we use double checked - * locking to add item to inventory. In this method, the thread which gets the lock first adds the - * item. + *

In {@link Inventory} we store the items with a given size. However, we do not store more items + * than the inventory size. To address concurrent access problems we use double checked locking to + * add item to inventory. In this method, the thread which gets the lock first adds the item. */ @Slf4j public class App { @@ -51,11 +50,15 @@ public class App { public static void main(String[] args) { final var inventory = new Inventory(1000); var executorService = Executors.newFixedThreadPool(3); - IntStream.range(0, 3).mapToObj(i -> () -> { - while (inventory.addItem(new Item())) { - LOGGER.info("Adding another item"); - } - }).forEach(executorService::execute); + IntStream.range(0, 3) + .mapToObj( + i -> + () -> { + while (inventory.addItem(new Item())) { + LOGGER.info("Adding another item"); + } + }) + .forEach(executorService::execute); executorService.shutdown(); try { diff --git a/double-checked-locking/src/main/java/com/iluwatar/doublechecked/locking/Inventory.java b/double-checked-locking/src/main/java/com/iluwatar/doublechecked/locking/Inventory.java index 83f72fca2..84b76a576 100644 --- a/double-checked-locking/src/main/java/com/iluwatar/doublechecked/locking/Inventory.java +++ b/double-checked-locking/src/main/java/com/iluwatar/doublechecked/locking/Inventory.java @@ -30,9 +30,7 @@ import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import lombok.extern.slf4j.Slf4j; -/** - * Inventory. - */ +/** Inventory. */ @Slf4j public class Inventory { @@ -40,18 +38,14 @@ public class Inventory { private final List items; private final Lock lock; - /** - * Constructor. - */ + /** Constructor. */ public Inventory(int inventorySize) { this.inventorySize = inventorySize; this.items = new ArrayList<>(inventorySize); this.lock = new ReentrantLock(); } - /** - * Add item. - */ + /** Add item. */ public boolean addItem(Item item) { if (items.size() < inventorySize) { lock.lock(); @@ -77,5 +71,4 @@ public class Inventory { public final List getItems() { return List.copyOf(items); } - } diff --git a/double-checked-locking/src/main/java/com/iluwatar/doublechecked/locking/Item.java b/double-checked-locking/src/main/java/com/iluwatar/doublechecked/locking/Item.java index 1e25d77c4..8f16ea69f 100644 --- a/double-checked-locking/src/main/java/com/iluwatar/doublechecked/locking/Item.java +++ b/double-checked-locking/src/main/java/com/iluwatar/doublechecked/locking/Item.java @@ -24,8 +24,5 @@ */ package com.iluwatar.doublechecked.locking; -/** - * Item. - */ -public class Item { -} +/** Item. */ +public class Item {} diff --git a/double-checked-locking/src/test/java/com/iluwatar/doublechecked/locking/AppTest.java b/double-checked-locking/src/test/java/com/iluwatar/doublechecked/locking/AppTest.java index 33a66d601..9d9ae3496 100644 --- a/double-checked-locking/src/test/java/com/iluwatar/doublechecked/locking/AppTest.java +++ b/double-checked-locking/src/test/java/com/iluwatar/doublechecked/locking/AppTest.java @@ -24,24 +24,19 @@ */ package com.iluwatar.doublechecked.locking; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -/** - * Application test - */ +import org.junit.jupiter.api.Test; + +/** Application test */ class AppTest { /** - * Issue: Add at least one assertion to this test case. - * Solution: Inserted assertion to check whether the execution of the main method in {@link App#main(String[])} - * throws an exception. + * Issue: Add at least one assertion to this test case. Solution: Inserted assertion to check + * whether the execution of the main method in {@link App#main(String[])} throws an exception. */ - - @Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/double-checked-locking/src/test/java/com/iluwatar/doublechecked/locking/InventoryTest.java b/double-checked-locking/src/test/java/com/iluwatar/doublechecked/locking/InventoryTest.java index 9067bf8e5..d79f6b660 100644 --- a/double-checked-locking/src/test/java/com/iluwatar/doublechecked/locking/InventoryTest.java +++ b/double-checked-locking/src/test/java/com/iluwatar/doublechecked/locking/InventoryTest.java @@ -43,10 +43,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.slf4j.LoggerFactory; -/** - * InventoryTest - * - */ +/** InventoryTest */ class InventoryTest { private InMemoryAppender appender; @@ -67,9 +64,7 @@ class InventoryTest { */ private static final int THREAD_COUNT = 8; - /** - * The maximum number of {@link Item}s allowed in the {@link Inventory} - */ + /** The maximum number of {@link Item}s allowed in the {@link Inventory} */ private static final int INVENTORY_SIZE = 1000; /** @@ -80,34 +75,42 @@ class InventoryTest { */ @Test void testAddItem() { - assertTimeout(ofMillis(10000), () -> { - // Create a new inventory with a limit of 1000 items and put some load on the add method - final var inventory = new Inventory(INVENTORY_SIZE); - final var executorService = Executors.newFixedThreadPool(THREAD_COUNT); - IntStream.range(0, THREAD_COUNT).mapToObj(i -> () -> { - while (inventory.addItem(new Item())) ; - }).forEach(executorService::execute); + assertTimeout( + ofMillis(10000), + () -> { + // Create a new inventory with a limit of 1000 items and put some load on the add method + final var inventory = new Inventory(INVENTORY_SIZE); + final var executorService = Executors.newFixedThreadPool(THREAD_COUNT); + IntStream.range(0, THREAD_COUNT) + .mapToObj( + i -> + () -> { + while (inventory.addItem(new Item())) + ; + }) + .forEach(executorService::execute); - // Wait until all threads have finished - executorService.shutdown(); - executorService.awaitTermination(5, TimeUnit.SECONDS); + // Wait until all threads have finished + executorService.shutdown(); + executorService.awaitTermination(5, TimeUnit.SECONDS); - // Check the number of items in the inventory. It should not have exceeded the allowed maximum - final var items = inventory.getItems(); - assertNotNull(items); - assertEquals(INVENTORY_SIZE, items.size()); + // Check the number of items in the inventory. It should not have exceeded the allowed + // maximum + final var items = inventory.getItems(); + assertNotNull(items); + assertEquals(INVENTORY_SIZE, items.size()); - assertEquals(INVENTORY_SIZE, appender.getLogSize()); + assertEquals(INVENTORY_SIZE, appender.getLogSize()); - // ... and check if the inventory size is increasing continuously - IntStream.range(0, items.size()) - .mapToObj(i -> appender.log.get(i).getFormattedMessage() - .contains("items.size()=" + (i + 1))) - .forEach(Assertions::assertTrue); - }); + // ... and check if the inventory size is increasing continuously + IntStream.range(0, items.size()) + .mapToObj( + i -> + appender.log.get(i).getFormattedMessage().contains("items.size()=" + (i + 1))) + .forEach(Assertions::assertTrue); + }); } - private static class InMemoryAppender extends AppenderBase { private final List log = new LinkedList<>(); @@ -125,5 +128,4 @@ class InventoryTest { return log.size(); } } - } diff --git a/double-dispatch/pom.xml b/double-dispatch/pom.xml index 297e93b9d..035732318 100644 --- a/double-dispatch/pom.xml +++ b/double-dispatch/pom.xml @@ -34,6 +34,14 @@ double-dispatch + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/double-dispatch/src/main/java/com/iluwatar/doubledispatch/App.java b/double-dispatch/src/main/java/com/iluwatar/doubledispatch/App.java index 6fa438760..bc38d0ee6 100644 --- a/double-dispatch/src/main/java/com/iluwatar/doubledispatch/App.java +++ b/double-dispatch/src/main/java/com/iluwatar/doubledispatch/App.java @@ -37,9 +37,9 @@ import lombok.extern.slf4j.Slf4j; * to change the method's implementation and add a new instanceof-check. This violates the single * responsibility principle - a class should have only one reason to change. * - *

Instead of the instanceof-checks a better way is to make another virtual call on the - * parameter object. This way new functionality can be easily added without the need to modify - * existing implementation (open-closed principle). + *

Instead of the instanceof-checks a better way is to make another virtual call on the parameter + * object. This way new functionality can be easily added without the need to modify existing + * implementation (open-closed principle). * *

In this example we have hierarchy of objects ({@link GameObject}) that can collide to each * other. Each object has its own coordinates which are checked against the other objects' @@ -57,21 +57,24 @@ public class App { public static void main(String[] args) { // initialize game objects and print their status LOGGER.info("Init objects and print their status"); - var objects = List.of( - new FlamingAsteroid(0, 0, 5, 5), - new SpaceStationMir(1, 1, 2, 2), - new Meteoroid(10, 10, 15, 15), - new SpaceStationIss(12, 12, 14, 14) - ); + var objects = + List.of( + new FlamingAsteroid(0, 0, 5, 5), + new SpaceStationMir(1, 1, 2, 2), + new Meteoroid(10, 10, 15, 15), + new SpaceStationIss(12, 12, 14, 14)); objects.forEach(o -> LOGGER.info(o.toString())); // collision check LOGGER.info("Collision check"); - objects.forEach(o1 -> objects.forEach(o2 -> { - if (o1 != o2 && o1.intersectsWith(o2)) { - o1.collision(o2); - } - })); + objects.forEach( + o1 -> + objects.forEach( + o2 -> { + if (o1 != o2 && o1.intersectsWith(o2)) { + o1.collision(o2); + } + })); // output eventual object statuses LOGGER.info("Print object status after collision checks"); diff --git a/double-dispatch/src/main/java/com/iluwatar/doubledispatch/FlamingAsteroid.java b/double-dispatch/src/main/java/com/iluwatar/doubledispatch/FlamingAsteroid.java index 9789fc3bb..98b4c6c7a 100644 --- a/double-dispatch/src/main/java/com/iluwatar/doubledispatch/FlamingAsteroid.java +++ b/double-dispatch/src/main/java/com/iluwatar/doubledispatch/FlamingAsteroid.java @@ -24,9 +24,7 @@ */ package com.iluwatar.doubledispatch; -/** - * Flaming asteroid game object. - */ +/** Flaming asteroid game object. */ public class FlamingAsteroid extends Meteoroid { public FlamingAsteroid(int left, int top, int right, int bottom) { diff --git a/double-dispatch/src/main/java/com/iluwatar/doubledispatch/GameObject.java b/double-dispatch/src/main/java/com/iluwatar/doubledispatch/GameObject.java index cd9a8b9ef..85ef3aa85 100644 --- a/double-dispatch/src/main/java/com/iluwatar/doubledispatch/GameObject.java +++ b/double-dispatch/src/main/java/com/iluwatar/doubledispatch/GameObject.java @@ -27,9 +27,7 @@ package com.iluwatar.doubledispatch; import lombok.Getter; import lombok.Setter; -/** - * Game objects have coordinates and some other status information. - */ +/** Game objects have coordinates and some other status information. */ @Getter @Setter public abstract class GameObject extends Rectangle { @@ -43,8 +41,9 @@ public abstract class GameObject extends Rectangle { @Override public String toString() { - return String.format("%s at %s damaged=%b onFire=%b", this.getClass().getSimpleName(), - super.toString(), isDamaged(), isOnFire()); + return String.format( + "%s at %s damaged=%b onFire=%b", + this.getClass().getSimpleName(), super.toString(), isDamaged(), isOnFire()); } public abstract void collision(GameObject gameObject); diff --git a/double-dispatch/src/main/java/com/iluwatar/doubledispatch/Meteoroid.java b/double-dispatch/src/main/java/com/iluwatar/doubledispatch/Meteoroid.java index 7d9d950a8..f2e058759 100644 --- a/double-dispatch/src/main/java/com/iluwatar/doubledispatch/Meteoroid.java +++ b/double-dispatch/src/main/java/com/iluwatar/doubledispatch/Meteoroid.java @@ -27,9 +27,7 @@ package com.iluwatar.doubledispatch; import com.iluwatar.doubledispatch.constants.AppConstants; import lombok.extern.slf4j.Slf4j; -/** - * Meteoroid game object. - */ +/** Meteoroid game object. */ @Slf4j public class Meteoroid extends GameObject { @@ -44,14 +42,14 @@ public class Meteoroid extends GameObject { @Override public void collisionResolve(FlamingAsteroid asteroid) { - LOGGER.info(AppConstants.HITS, asteroid.getClass().getSimpleName(), this.getClass() - .getSimpleName()); + LOGGER.info( + AppConstants.HITS, asteroid.getClass().getSimpleName(), this.getClass().getSimpleName()); } @Override public void collisionResolve(Meteoroid meteoroid) { - LOGGER.info(AppConstants.HITS, meteoroid.getClass().getSimpleName(), this.getClass() - .getSimpleName()); + LOGGER.info( + AppConstants.HITS, meteoroid.getClass().getSimpleName(), this.getClass().getSimpleName()); } @Override diff --git a/double-dispatch/src/main/java/com/iluwatar/doubledispatch/Rectangle.java b/double-dispatch/src/main/java/com/iluwatar/doubledispatch/Rectangle.java index 7f5e88994..4dfe8f22a 100644 --- a/double-dispatch/src/main/java/com/iluwatar/doubledispatch/Rectangle.java +++ b/double-dispatch/src/main/java/com/iluwatar/doubledispatch/Rectangle.java @@ -27,9 +27,7 @@ package com.iluwatar.doubledispatch; import lombok.Getter; import lombok.RequiredArgsConstructor; -/** - * Rectangle has coordinates and can be checked for overlap against other Rectangles. - */ +/** Rectangle has coordinates and can be checked for overlap against other Rectangles. */ @Getter @RequiredArgsConstructor public class Rectangle { @@ -40,8 +38,10 @@ public class Rectangle { private final int bottom; boolean intersectsWith(Rectangle r) { - return !(r.getLeft() > getRight() || r.getRight() < getLeft() || r.getTop() > getBottom() || r - .getBottom() < getTop()); + return !(r.getLeft() > getRight() + || r.getRight() < getLeft() + || r.getTop() > getBottom() + || r.getBottom() < getTop()); } @Override diff --git a/double-dispatch/src/main/java/com/iluwatar/doubledispatch/SpaceStationIss.java b/double-dispatch/src/main/java/com/iluwatar/doubledispatch/SpaceStationIss.java index 0ab506092..14c44c596 100644 --- a/double-dispatch/src/main/java/com/iluwatar/doubledispatch/SpaceStationIss.java +++ b/double-dispatch/src/main/java/com/iluwatar/doubledispatch/SpaceStationIss.java @@ -24,9 +24,7 @@ */ package com.iluwatar.doubledispatch; -/** - * Space station ISS game object. - */ +/** Space station ISS game object. */ public class SpaceStationIss extends SpaceStationMir { public SpaceStationIss(int left, int top, int right, int bottom) { diff --git a/double-dispatch/src/main/java/com/iluwatar/doubledispatch/SpaceStationMir.java b/double-dispatch/src/main/java/com/iluwatar/doubledispatch/SpaceStationMir.java index 3f718c8d9..045698256 100644 --- a/double-dispatch/src/main/java/com/iluwatar/doubledispatch/SpaceStationMir.java +++ b/double-dispatch/src/main/java/com/iluwatar/doubledispatch/SpaceStationMir.java @@ -27,9 +27,7 @@ package com.iluwatar.doubledispatch; import com.iluwatar.doubledispatch.constants.AppConstants; import lombok.extern.slf4j.Slf4j; -/** - * Space station Mir game object. - */ +/** Space station Mir game object. */ @Slf4j public class SpaceStationMir extends GameObject { @@ -44,10 +42,12 @@ public class SpaceStationMir extends GameObject { @Override public void collisionResolve(FlamingAsteroid asteroid) { - LOGGER.info(AppConstants.HITS + " {} is damaged! {} is set on fire!", asteroid.getClass() - .getSimpleName(), - this.getClass().getSimpleName(), this.getClass().getSimpleName(), this.getClass() - .getSimpleName()); + LOGGER.info( + AppConstants.HITS + " {} is damaged! {} is set on fire!", + asteroid.getClass().getSimpleName(), + this.getClass().getSimpleName(), + this.getClass().getSimpleName(), + this.getClass().getSimpleName()); setDamaged(true); setOnFire(true); } @@ -71,7 +71,11 @@ public class SpaceStationMir extends GameObject { } private void logHits(GameObject gameObject) { - LOGGER.info(AppConstants.HITS, " {} is damaged!", gameObject.getClass().getSimpleName(), - this.getClass().getSimpleName(), this.getClass().getSimpleName()); + LOGGER.info( + AppConstants.HITS, + " {} is damaged!", + gameObject.getClass().getSimpleName(), + this.getClass().getSimpleName(), + this.getClass().getSimpleName()); } -} \ No newline at end of file +} diff --git a/double-dispatch/src/main/java/com/iluwatar/doubledispatch/constants/AppConstants.java b/double-dispatch/src/main/java/com/iluwatar/doubledispatch/constants/AppConstants.java index 0f4a51da1..f664092fa 100644 --- a/double-dispatch/src/main/java/com/iluwatar/doubledispatch/constants/AppConstants.java +++ b/double-dispatch/src/main/java/com/iluwatar/doubledispatch/constants/AppConstants.java @@ -24,9 +24,7 @@ */ package com.iluwatar.doubledispatch.constants; -/** - * Constants class to define all constants. - */ +/** Constants class to define all constants. */ public class AppConstants { public static final String HITS = "{} hits {}."; diff --git a/double-dispatch/src/test/java/com/iluwatar/doubledispatch/AppTest.java b/double-dispatch/src/test/java/com/iluwatar/doubledispatch/AppTest.java index 24b695244..1abff6a45 100644 --- a/double-dispatch/src/test/java/com/iluwatar/doubledispatch/AppTest.java +++ b/double-dispatch/src/test/java/com/iluwatar/doubledispatch/AppTest.java @@ -24,24 +24,19 @@ */ package com.iluwatar.doubledispatch; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -/** - * Application test - */ +import org.junit.jupiter.api.Test; + +/** Application test */ class AppTest { /** - * Issue: Add at least one assertion to this test case. - * Solution: Inserted assertion to check whether the execution of the main method in {@link App#main(String[])} - * throws an exception. + * Issue: Add at least one assertion to this test case. Solution: Inserted assertion to check + * whether the execution of the main method in {@link App#main(String[])} throws an exception. */ - - @Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } } 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 709b8517a..7d11fa850 100644 --- a/double-dispatch/src/test/java/com/iluwatar/doubledispatch/CollisionTest.java +++ b/double-dispatch/src/test/java/com/iluwatar/doubledispatch/CollisionTest.java @@ -46,14 +46,18 @@ public abstract class CollisionTest { * Collide the tested item with the other given item and verify if the damage and fire state is as * expected * - * @param other The other object we have to collide with + * @param other The other object we have to collide with * @param otherDamaged Indicates if the other object should be damaged after the collision - * @param otherOnFire Indicates if the other object should be burning after the collision - * @param thisDamaged Indicates if the test object should be damaged after the collision - * @param thisOnFire Indicates if the other object should be burning after the collision + * @param otherOnFire Indicates if the other object should be burning after the collision + * @param thisDamaged Indicates if the test object should be damaged after the collision + * @param thisOnFire Indicates if the other object should be burning after the collision */ - void testCollision(final GameObject other, final boolean otherDamaged, final boolean otherOnFire, - final boolean thisDamaged, final boolean thisOnFire) { + void testCollision( + final GameObject other, + final boolean otherDamaged, + final boolean otherOnFire, + final boolean thisDamaged, + final boolean thisOnFire) { Objects.requireNonNull(other); Objects.requireNonNull(getTestedObject()); @@ -67,24 +71,33 @@ public abstract class CollisionTest { testOnFire(tested, other, thisOnFire); testDamaged(tested, other, thisDamaged); - } /** * Test if the fire state of the target matches the expected state after colliding with the given * object * - * @param target The target object - * @param other The other object + * @param target The target object + * @param other The other object * @param expectTargetOnFire The expected state of fire on the target object */ - private void testOnFire(final GameObject target, final GameObject other, final boolean expectTargetOnFire) { + private void testOnFire( + final GameObject target, final GameObject other, final boolean expectTargetOnFire) { final var targetName = target.getClass().getSimpleName(); final var otherName = other.getClass().getSimpleName(); - final var errorMessage = expectTargetOnFire - ? "Expected [" + targetName + "] to be on fire after colliding with [" + otherName + "] but it was not!" - : "Expected [" + targetName + "] not to be on fire after colliding with [" + otherName + "] but it was!"; + final var errorMessage = + expectTargetOnFire + ? "Expected [" + + targetName + + "] to be on fire after colliding with [" + + otherName + + "] but it was not!" + : "Expected [" + + targetName + + "] not to be on fire after colliding with [" + + otherName + + "] but it was!"; assertEquals(expectTargetOnFire, target.isOnFire(), errorMessage); } @@ -93,19 +106,28 @@ public abstract class CollisionTest { * Test if the damage state of the target matches the expected state after colliding with the * given object * - * @param target The target object - * @param other The other object + * @param target The target object + * @param other The other object * @param expectedDamage The expected state of damage on the target object */ - private void testDamaged(final GameObject target, final GameObject other, final boolean expectedDamage) { + private void testDamaged( + final GameObject target, final GameObject other, final boolean expectedDamage) { final var targetName = target.getClass().getSimpleName(); final var otherName = other.getClass().getSimpleName(); - final var errorMessage = expectedDamage - ? "Expected [" + targetName + "] to be damaged after colliding with [" + otherName + "] but it was not!" - : "Expected [" + targetName + "] not to be damaged after colliding with [" + otherName + "] but it was!"; + final var errorMessage = + expectedDamage + ? "Expected [" + + targetName + + "] to be damaged after colliding with [" + + otherName + + "] but it was not!" + : "Expected [" + + targetName + + "] not to be damaged after colliding with [" + + otherName + + "] but it was!"; assertEquals(expectedDamage, target.isDamaged(), errorMessage); } - } diff --git a/double-dispatch/src/test/java/com/iluwatar/doubledispatch/FlamingAsteroidTest.java b/double-dispatch/src/test/java/com/iluwatar/doubledispatch/FlamingAsteroidTest.java index 78401b86a..65cd7cbd1 100644 --- a/double-dispatch/src/test/java/com/iluwatar/doubledispatch/FlamingAsteroidTest.java +++ b/double-dispatch/src/test/java/com/iluwatar/doubledispatch/FlamingAsteroidTest.java @@ -30,10 +30,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; -/** - * FlamingAsteroidTest - * - */ +/** FlamingAsteroidTest */ class FlamingAsteroidTest extends CollisionTest { @Override @@ -41,9 +38,7 @@ class FlamingAsteroidTest extends CollisionTest { return new FlamingAsteroid(1, 2, 3, 4); } - /** - * Test the constructor parameters - */ + /** Test the constructor parameters */ @Test void testConstructor() { final var asteroid = new FlamingAsteroid(1, 2, 3, 4); @@ -56,52 +51,27 @@ class FlamingAsteroidTest extends CollisionTest { assertEquals("FlamingAsteroid at [1,2,3,4] damaged=false onFire=true", asteroid.toString()); } - /** - * Test what happens we collide with an asteroid - */ + /** Test what happens we collide with an asteroid */ @Test void testCollideFlamingAsteroid() { - testCollision( - new FlamingAsteroid(1, 2, 3, 4), - false, true, - false, true - ); + testCollision(new FlamingAsteroid(1, 2, 3, 4), false, true, false, true); } - /** - * Test what happens we collide with an meteoroid - */ + /** Test what happens we collide with an meteoroid */ @Test void testCollideMeteoroid() { - testCollision( - new Meteoroid(1, 1, 3, 4), - false, false, - false, true - ); + testCollision(new Meteoroid(1, 1, 3, 4), false, false, false, true); } - /** - * Test what happens we collide with ISS - */ + /** Test what happens we collide with ISS */ @Test void testCollideSpaceStationIss() { - testCollision( - new SpaceStationIss(1, 1, 3, 4), - true, true, - false, true - ); + testCollision(new SpaceStationIss(1, 1, 3, 4), true, true, false, true); } - /** - * Test what happens we collide with MIR - */ + /** Test what happens we collide with MIR */ @Test void testCollideSpaceStationMir() { - testCollision( - new SpaceStationMir(1, 1, 3, 4), - true, true, - false, true - ); + testCollision(new SpaceStationMir(1, 1, 3, 4), true, true, false, true); } - -} \ No newline at end of file +} diff --git a/double-dispatch/src/test/java/com/iluwatar/doubledispatch/MeteoroidTest.java b/double-dispatch/src/test/java/com/iluwatar/doubledispatch/MeteoroidTest.java index aa02f1940..17d529523 100644 --- a/double-dispatch/src/test/java/com/iluwatar/doubledispatch/MeteoroidTest.java +++ b/double-dispatch/src/test/java/com/iluwatar/doubledispatch/MeteoroidTest.java @@ -29,10 +29,7 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import org.junit.jupiter.api.Test; -/** - * MeteoroidTest - * - */ +/** MeteoroidTest */ class MeteoroidTest extends CollisionTest { @Override @@ -40,9 +37,7 @@ class MeteoroidTest extends CollisionTest { return new Meteoroid(1, 2, 3, 4); } - /** - * Test the constructor parameters - */ + /** Test the constructor parameters */ @Test void testConstructor() { final var meteoroid = new Meteoroid(1, 2, 3, 4); @@ -55,52 +50,27 @@ class MeteoroidTest extends CollisionTest { assertEquals("Meteoroid at [1,2,3,4] damaged=false onFire=false", meteoroid.toString()); } - /** - * Test what happens we collide with an asteroid - */ + /** Test what happens we collide with an asteroid */ @Test void testCollideFlamingAsteroid() { - testCollision( - new FlamingAsteroid(1, 1, 3, 4), - false, true, - false, false - ); + testCollision(new FlamingAsteroid(1, 1, 3, 4), false, true, false, false); } - /** - * Test what happens we collide with an meteoroid - */ + /** Test what happens we collide with an meteoroid */ @Test void testCollideMeteoroid() { - testCollision( - new Meteoroid(1, 1, 3, 4), - false, false, - false, false - ); + testCollision(new Meteoroid(1, 1, 3, 4), false, false, false, false); } - /** - * Test what happens we collide with ISS - */ + /** Test what happens we collide with ISS */ @Test void testCollideSpaceStationIss() { - testCollision( - new SpaceStationIss(1, 1, 3, 4), - true, false, - false, false - ); + testCollision(new SpaceStationIss(1, 1, 3, 4), true, false, false, false); } - /** - * Test what happens we collide with MIR - */ + /** Test what happens we collide with MIR */ @Test void testCollideSpaceStationMir() { - testCollision( - new SpaceStationMir(1, 1, 3, 4), - true, false, - false, false - ); + testCollision(new SpaceStationMir(1, 1, 3, 4), true, false, false, false); } - -} \ No newline at end of file +} diff --git a/double-dispatch/src/test/java/com/iluwatar/doubledispatch/RectangleTest.java b/double-dispatch/src/test/java/com/iluwatar/doubledispatch/RectangleTest.java index 8a042f09d..6b143643a 100644 --- a/double-dispatch/src/test/java/com/iluwatar/doubledispatch/RectangleTest.java +++ b/double-dispatch/src/test/java/com/iluwatar/doubledispatch/RectangleTest.java @@ -30,9 +30,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; -/** - * Unit test for Rectangle - */ +/** Unit test for Rectangle */ class RectangleTest { /** @@ -48,8 +46,7 @@ class RectangleTest { } /** - * Test if the values passed through the constructor matches the values in the {@link - * #toString()} + * Test if the values passed through the constructor matches the values in the {@link #toString()} */ @Test void testToString() { @@ -57,9 +54,7 @@ class RectangleTest { assertEquals("[1,2,3,4]", rectangle.toString()); } - /** - * Test if the {@link Rectangle} class can detect if it intersects with another rectangle. - */ + /** Test if the {@link Rectangle} class can detect if it intersects with another rectangle. */ @Test void testIntersection() { assertTrue(new Rectangle(0, 0, 1, 1).intersectsWith(new Rectangle(0, 0, 1, 1))); @@ -67,5 +62,4 @@ class RectangleTest { assertFalse(new Rectangle(0, 0, 1, 1).intersectsWith(new Rectangle(2, 2, 3, 3))); assertFalse(new Rectangle(0, 0, 1, 1).intersectsWith(new Rectangle(-2, -2, -1, -1))); } - } diff --git a/double-dispatch/src/test/java/com/iluwatar/doubledispatch/SpaceStationIssTest.java b/double-dispatch/src/test/java/com/iluwatar/doubledispatch/SpaceStationIssTest.java index b45875686..593caf3d6 100644 --- a/double-dispatch/src/test/java/com/iluwatar/doubledispatch/SpaceStationIssTest.java +++ b/double-dispatch/src/test/java/com/iluwatar/doubledispatch/SpaceStationIssTest.java @@ -29,10 +29,7 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import org.junit.jupiter.api.Test; -/** - * SpaceStationIssTest - * - */ +/** SpaceStationIssTest */ class SpaceStationIssTest extends CollisionTest { @Override @@ -40,9 +37,7 @@ class SpaceStationIssTest extends CollisionTest { return new SpaceStationIss(1, 2, 3, 4); } - /** - * Test the constructor parameters - */ + /** Test the constructor parameters */ @Test void testConstructor() { final var iss = new SpaceStationIss(1, 2, 3, 4); @@ -55,52 +50,27 @@ class SpaceStationIssTest extends CollisionTest { assertEquals("SpaceStationIss at [1,2,3,4] damaged=false onFire=false", iss.toString()); } - /** - * Test what happens we collide with an asteroid - */ + /** Test what happens we collide with an asteroid */ @Test void testCollideFlamingAsteroid() { - testCollision( - new FlamingAsteroid(1, 1, 3, 4), - false, true, - false, false - ); + testCollision(new FlamingAsteroid(1, 1, 3, 4), false, true, false, false); } - /** - * Test what happens we collide with an meteoroid - */ + /** Test what happens we collide with an meteoroid */ @Test void testCollideMeteoroid() { - testCollision( - new Meteoroid(1, 1, 3, 4), - false, false, - false, false - ); + testCollision(new Meteoroid(1, 1, 3, 4), false, false, false, false); } - /** - * Test what happens we collide with ISS - */ + /** Test what happens we collide with ISS */ @Test void testCollideSpaceStationIss() { - testCollision( - new SpaceStationIss(1, 1, 3, 4), - true, false, - false, false - ); + testCollision(new SpaceStationIss(1, 1, 3, 4), true, false, false, false); } - /** - * Test what happens we collide with MIR - */ + /** Test what happens we collide with MIR */ @Test void testCollideSpaceStationMir() { - testCollision( - new SpaceStationMir(1, 1, 3, 4), - true, false, - false, false - ); + testCollision(new SpaceStationMir(1, 1, 3, 4), true, false, false, false); } - -} \ No newline at end of file +} diff --git a/double-dispatch/src/test/java/com/iluwatar/doubledispatch/SpaceStationMirTest.java b/double-dispatch/src/test/java/com/iluwatar/doubledispatch/SpaceStationMirTest.java index 540d148f1..155595253 100644 --- a/double-dispatch/src/test/java/com/iluwatar/doubledispatch/SpaceStationMirTest.java +++ b/double-dispatch/src/test/java/com/iluwatar/doubledispatch/SpaceStationMirTest.java @@ -29,10 +29,7 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import org.junit.jupiter.api.Test; -/** - * SpaceStationMirTest - * - */ +/** SpaceStationMirTest */ class SpaceStationMirTest extends CollisionTest { @Override @@ -40,9 +37,7 @@ class SpaceStationMirTest extends CollisionTest { return new SpaceStationMir(1, 2, 3, 4); } - /** - * Test the constructor parameters - */ + /** Test the constructor parameters */ @Test void testConstructor() { final var mir = new SpaceStationMir(1, 2, 3, 4); @@ -55,52 +50,27 @@ class SpaceStationMirTest extends CollisionTest { assertEquals("SpaceStationMir at [1,2,3,4] damaged=false onFire=false", mir.toString()); } - /** - * Test what happens we collide with an asteroid - */ + /** Test what happens we collide with an asteroid */ @Test void testCollideFlamingAsteroid() { - testCollision( - new FlamingAsteroid(1, 1, 3, 4), - false, true, - false, false - ); + testCollision(new FlamingAsteroid(1, 1, 3, 4), false, true, false, false); } - /** - * Test what happens we collide with an meteoroid - */ + /** Test what happens we collide with an meteoroid */ @Test void testCollideMeteoroid() { - testCollision( - new Meteoroid(1, 1, 3, 4), - false, false, - false, false - ); + testCollision(new Meteoroid(1, 1, 3, 4), false, false, false, false); } - /** - * Test what happens we collide with ISS - */ + /** Test what happens we collide with ISS */ @Test void testCollideSpaceStationIss() { - testCollision( - new SpaceStationIss(1, 1, 3, 4), - true, false, - false, false - ); + testCollision(new SpaceStationIss(1, 1, 3, 4), true, false, false, false); } - /** - * Test what happens we collide with MIR - */ + /** Test what happens we collide with MIR */ @Test void testCollideSpaceStationMir() { - testCollision( - new SpaceStationMir(1, 1, 3, 4), - true, false, - false, false - ); + testCollision(new SpaceStationMir(1, 1, 3, 4), true, false, false, false); } - -} \ No newline at end of file +} diff --git a/dynamic-proxy/pom.xml b/dynamic-proxy/pom.xml index 28df8f030..50f90ee63 100644 --- a/dynamic-proxy/pom.xml +++ b/dynamic-proxy/pom.xml @@ -35,6 +35,14 @@ dynamic-proxy + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + com.fasterxml.jackson.core jackson-core @@ -48,6 +56,7 @@ org.springframework spring-web + 7.0.0-M3 org.junit.jupiter diff --git a/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/Album.java b/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/Album.java index 1a4efc606..c61223008 100644 --- a/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/Album.java +++ b/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/Album.java @@ -30,8 +30,8 @@ import lombok.Data; import lombok.NoArgsConstructor; /** - * This class represents an endpoint resource that - * we are going to interchange with a Rest API server. + * This class represents an endpoint resource that we are going to interchange with a Rest API + * server. */ @Data @AllArgsConstructor @@ -42,5 +42,4 @@ public class Album { private Integer id; private String title; private Integer userId; - } diff --git a/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/AlbumInvocationHandler.java b/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/AlbumInvocationHandler.java index e53485ae0..84a0b22d0 100644 --- a/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/AlbumInvocationHandler.java +++ b/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/AlbumInvocationHandler.java @@ -31,8 +31,8 @@ import java.net.http.HttpClient; import lombok.extern.slf4j.Slf4j; /** - * Class whose method 'invoke' will be called every time that an interface's method is called. - * That interface is linked to this class by the Proxy class. + * Class whose method 'invoke' will be called every time that an interface's method is called. That + * interface is linked to this class by the Proxy class. */ @Slf4j public class AlbumInvocationHandler implements InvocationHandler { @@ -42,7 +42,7 @@ public class AlbumInvocationHandler implements InvocationHandler { /** * Class constructor. It instantiates a TinyRestClient object. * - * @param baseUrl Root url for endpoints. + * @param baseUrl Root url for endpoints. * @param httpClient Handle the http communication. */ public AlbumInvocationHandler(String baseUrl, HttpClient httpClient) { @@ -52,10 +52,11 @@ public class AlbumInvocationHandler implements InvocationHandler { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { - LOGGER.info("===== Calling the method {}.{}()", - method.getDeclaringClass().getSimpleName(), method.getName()); + LOGGER.info( + "===== Calling the method {}.{}()", + method.getDeclaringClass().getSimpleName(), + method.getName()); return restClient.send(method, args); } - } diff --git a/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/AlbumService.java b/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/AlbumService.java index c0975b6e6..8b4c0d02d 100644 --- a/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/AlbumService.java +++ b/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/AlbumService.java @@ -34,8 +34,8 @@ import java.util.List; /** * Every method in this interface is annotated with the necessary metadata to represents an endpoint - * that we can call to communicate with a host server which is serving a resource by Rest API. - * This interface is focused in the resource Album. + * that we can call to communicate with a host server which is serving a resource by Rest API. This + * interface is focused in the resource Album. */ public interface AlbumService { @@ -69,7 +69,7 @@ public interface AlbumService { * Updates an existing album. * * @param albumId Album's id to be modified. - * @param album New album's data. + * @param album New album's data. * @return Updated album's data. */ @Put("/albums/{albumId}") @@ -83,5 +83,4 @@ public interface AlbumService { */ @Delete("/albums/{albumId}") Album deleteAlbum(@Path("albumId") Integer albumId); - } diff --git a/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/App.java b/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/App.java index 61118694d..d5a19184b 100644 --- a/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/App.java +++ b/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/App.java @@ -30,14 +30,14 @@ import lombok.extern.slf4j.Slf4j; /** * Application to demonstrate the Dynamic Proxy pattern. This application allow us to hit the public - * fake API https://jsonplaceholder.typicode.com for the resource Album through an interface. - * The call to Proxy.newProxyInstance creates a new dynamic proxy for the AlbumService interface and + * fake API https://jsonplaceholder.typicode.com for the resource Album through an interface. The + * call to Proxy.newProxyInstance creates a new dynamic proxy for the AlbumService interface and * sets the AlbumInvocationHandler class as the handler to intercept all the interface's methods. * Everytime that we call an AlbumService's method, the handler's method "invoke" will be call * automatically, and it will pass all the method's metadata and arguments to other specialized - * class - TinyRestClient - to prepare the Rest API call accordingly. - * In this demo, the Dynamic Proxy pattern help us to run business logic through interfaces without - * an explicit implementation of the interfaces and supported on the Java Reflection approach. + * class - TinyRestClient - to prepare the Rest API call accordingly. In this demo, the Dynamic + * Proxy pattern help us to run business logic through interfaces without an explicit implementation + * of the interfaces and supported on the Java Reflection approach. */ @Slf4j public class App { @@ -51,7 +51,7 @@ public class App { /** * Class constructor. * - * @param baseUrl Root url for endpoints. + * @param baseUrl Root url for endpoints. * @param httpClient Handle the http communication. */ public App(String baseUrl, HttpClient httpClient) { @@ -71,18 +71,23 @@ public class App { } /** - * Create the Dynamic Proxy linked to the AlbumService interface and to the AlbumInvocationHandler. + * Create the Dynamic Proxy linked to the AlbumService interface and to the + * AlbumInvocationHandler. */ public void createDynamicProxy() { AlbumInvocationHandler albumInvocationHandler = new AlbumInvocationHandler(baseUrl, httpClient); - albumServiceProxy = (AlbumService) Proxy.newProxyInstance( - App.class.getClassLoader(), new Class[]{AlbumService.class}, albumInvocationHandler); + albumServiceProxy = + (AlbumService) + Proxy.newProxyInstance( + App.class.getClassLoader(), + new Class[] {AlbumService.class}, + albumInvocationHandler); } /** - * Call the methods of the Dynamic Proxy, in other words, the AlbumService interface's methods - * and receive the responses from the Rest API. + * Call the methods of the Dynamic Proxy, in other words, the AlbumService interface's methods and + * receive the responses from the Rest API. */ public void callMethods() { int albumId = 17; @@ -94,16 +99,16 @@ public class App { var album = albumServiceProxy.readAlbum(albumId); LOGGER.info("{}", album); - var newAlbum = albumServiceProxy.createAlbum(Album.builder() - .title("Big World").userId(userId).build()); + var newAlbum = + albumServiceProxy.createAlbum(Album.builder().title("Big World").userId(userId).build()); LOGGER.info("{}", newAlbum); - var editAlbum = albumServiceProxy.updateAlbum(albumId, Album.builder() - .title("Green Valley").userId(userId).build()); + var editAlbum = + albumServiceProxy.updateAlbum( + albumId, Album.builder().title("Green Valley").userId(userId).build()); LOGGER.info("{}", editAlbum); var removedAlbum = albumServiceProxy.deleteAlbum(albumId); LOGGER.info("{}", removedAlbum); } - } diff --git a/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/tinyrestclient/JsonUtil.java b/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/tinyrestclient/JsonUtil.java index f76fe88ec..d474c59da 100644 --- a/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/tinyrestclient/JsonUtil.java +++ b/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/tinyrestclient/JsonUtil.java @@ -32,22 +32,19 @@ import java.util.ArrayList; import java.util.List; import lombok.extern.slf4j.Slf4j; -/** - * Utility class to handle Json operations. - */ +/** Utility class to handle Json operations. */ @Slf4j public class JsonUtil { private static ObjectMapper objectMapper = new ObjectMapper(); - private JsonUtil() { - } + private JsonUtil() {} /** * Convert an object to a Json string representation. * * @param object Object to convert. - * @param Object's class. + * @param Object's class. * @return Json string. */ public static String objectToJson(T object) { @@ -62,9 +59,9 @@ public class JsonUtil { /** * Convert a Json string to an object of a class. * - * @param json Json string to convert. + * @param json Json string to convert. * @param clazz Object's class. - * @param Object's generic class. + * @param Object's generic class. * @return Object. */ public static T jsonToObject(String json, Class clazz) { @@ -79,20 +76,19 @@ public class JsonUtil { /** * Convert a Json string to a List of objects of a class. * - * @param json Json string to convert. + * @param json Json string to convert. * @param clazz Object's class. - * @param Object's generic class. + * @param Object's generic class. * @return List of objects. */ public static List jsonToList(String json, Class clazz) { try { - CollectionType listType = objectMapper.getTypeFactory() - .constructCollectionType(ArrayList.class, clazz); + CollectionType listType = + objectMapper.getTypeFactory().constructCollectionType(ArrayList.class, clazz); return objectMapper.reader().forType(listType).readValue(json); } catch (JsonProcessingException e) { LOGGER.error("Cannot convert the Json " + json + " to List of " + clazz.getName() + ".", e); return List.of(); } } - } diff --git a/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/tinyrestclient/TinyRestClient.java b/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/tinyrestclient/TinyRestClient.java index fe777beca..dd952f479 100644 --- a/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/tinyrestclient/TinyRestClient.java +++ b/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/tinyrestclient/TinyRestClient.java @@ -45,8 +45,8 @@ import lombok.extern.slf4j.Slf4j; import org.springframework.web.util.UriUtils; /** - * Class to handle all the http communication with a Rest API. - * It is supported by the HttpClient Java library. + * Class to handle all the http communication with a Rest API. It is supported by the HttpClient + * Java library. */ @Slf4j public class TinyRestClient { @@ -59,7 +59,7 @@ public class TinyRestClient { /** * Class constructor. * - * @param baseUrl Root url for endpoints. + * @param baseUrl Root url for endpoints. * @param httpClient Handle the http communication. */ public TinyRestClient(String baseUrl, HttpClient httpClient) { @@ -71,9 +71,9 @@ public class TinyRestClient { * Creates a http communication to request and receive data from an endpoint. * * @param method Interface's method which is annotated with a http method. - * @param args Method's arguments passed in the call. + * @param args Method's arguments passed in the call. * @return Response from the endpoint. - * @throws IOException Exception thrown when any fail happens in the call. + * @throws IOException Exception thrown when any fail happens in the call. * @throws InterruptedException Exception thrown when call is interrupted. */ public Object send(Method method, Object[] args) throws IOException, InterruptedException { @@ -84,11 +84,12 @@ public class TinyRestClient { var httpAnnotationName = httpAnnotation.annotationType().getSimpleName().toUpperCase(); var url = baseUrl + buildUrl(method, args, httpAnnotation); var bodyPublisher = buildBodyPublisher(method, args); - var httpRequest = HttpRequest.newBuilder() - .uri(URI.create(url)) - .header("Content-Type", "application/json") - .method(httpAnnotationName, bodyPublisher) - .build(); + var httpRequest = + HttpRequest.newBuilder() + .uri(URI.create(url)) + .header("Content-Type", "application/json") + .method(httpAnnotationName, bodyPublisher) + .build(); var httpResponse = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString()); var statusCode = httpResponse.statusCode(); if (statusCode >= HttpURLConnection.HTTP_BAD_REQUEST) { @@ -140,8 +141,8 @@ public class TinyRestClient { return null; } if (returnType instanceof ParameterizedType) { - Class responseClass = (Class) (((ParameterizedType) returnType) - .getActualTypeArguments()[0]); + Class responseClass = + (Class) (((ParameterizedType) returnType).getActualTypeArguments()[0]); return JsonUtil.jsonToList(rawData, responseClass); } else { Class responseClass = method.getReturnType(); @@ -150,22 +151,28 @@ public class TinyRestClient { } private Annotation getHttpAnnotation(Method method) { - return httpAnnotationByMethod.computeIfAbsent(method, m -> - Arrays.stream(m.getDeclaredAnnotations()) - .filter(annot -> annot.annotationType().isAnnotationPresent(Http.class)) - .findFirst().orElse(null)); + return httpAnnotationByMethod.computeIfAbsent( + method, + m -> + Arrays.stream(m.getDeclaredAnnotations()) + .filter(annot -> annot.annotationType().isAnnotationPresent(Http.class)) + .findFirst() + .orElse(null)); } private Annotation getAnnotationOf(Annotation[] annotations, Class clazz) { return Arrays.stream(annotations) .filter(annot -> annot.annotationType().equals(clazz)) - .findFirst().orElse(null); + .findFirst() + .orElse(null); } private String annotationValue(Annotation annotation) { - var valueMethod = Arrays.stream(annotation.annotationType().getDeclaredMethods()) - .filter(methodAnnot -> methodAnnot.getName().equals("value")) - .findFirst().orElse(null); + var valueMethod = + Arrays.stream(annotation.annotationType().getDeclaredMethods()) + .filter(methodAnnot -> methodAnnot.getName().equals("value")) + .findFirst() + .orElse(null); if (valueMethod == null) { return null; } @@ -173,8 +180,13 @@ public class TinyRestClient { try { result = valueMethod.invoke(annotation, (Object[]) null); } catch (Exception e) { - LOGGER.error("Cannot read the value " + annotation.annotationType().getSimpleName() - + "." + valueMethod.getName() + "()", e); + LOGGER.error( + "Cannot read the value " + + annotation.annotationType().getSimpleName() + + "." + + valueMethod.getName() + + "()", + e); result = null; } return (result instanceof String strResult ? strResult : null); diff --git a/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/tinyrestclient/annotation/Body.java b/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/tinyrestclient/annotation/Body.java index 1d91c0af1..df8973193 100644 --- a/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/tinyrestclient/annotation/Body.java +++ b/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/tinyrestclient/annotation/Body.java @@ -30,10 +30,9 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** - * Annotation to mark a method's parameter as a Body parameter. - * It is typically used on Post and Put http methods. + * Annotation to mark a method's parameter as a Body parameter. It is typically used on Post and Put + * http methods. */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.PARAMETER) -public @interface Body { -} +public @interface Body {} diff --git a/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/tinyrestclient/annotation/Delete.java b/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/tinyrestclient/annotation/Delete.java index 5f21457ab..a43df9057 100644 --- a/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/tinyrestclient/annotation/Delete.java +++ b/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/tinyrestclient/annotation/Delete.java @@ -29,9 +29,7 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -/** - * Annotation to mark an interface's method as a DELETE http method. - */ +/** Annotation to mark an interface's method as a DELETE http method. */ @Http @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) diff --git a/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/tinyrestclient/annotation/Get.java b/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/tinyrestclient/annotation/Get.java index 163a65ad9..74f96ac06 100644 --- a/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/tinyrestclient/annotation/Get.java +++ b/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/tinyrestclient/annotation/Get.java @@ -29,9 +29,7 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -/** - * Annotation to mark an interface's method as a GET http method. - */ +/** Annotation to mark an interface's method as a GET http method. */ @Http @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) diff --git a/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/tinyrestclient/annotation/Http.java b/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/tinyrestclient/annotation/Http.java index beabcdb69..f12878de2 100644 --- a/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/tinyrestclient/annotation/Http.java +++ b/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/tinyrestclient/annotation/Http.java @@ -29,10 +29,7 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -/** - * Annotation to mark other annotations to be recognized as http methods. - */ +/** Annotation to mark other annotations to be recognized as http methods. */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.ANNOTATION_TYPE) -public @interface Http { -} +public @interface Http {} diff --git a/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/tinyrestclient/annotation/Path.java b/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/tinyrestclient/annotation/Path.java index 0f2bcd007..4ff1faea4 100644 --- a/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/tinyrestclient/annotation/Path.java +++ b/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/tinyrestclient/annotation/Path.java @@ -29,9 +29,7 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -/** - * Annotation to mark a method's parameter as a Path parameter. - */ +/** Annotation to mark a method's parameter as a Path parameter. */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.PARAMETER) public @interface Path { diff --git a/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/tinyrestclient/annotation/Post.java b/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/tinyrestclient/annotation/Post.java index 9885389c4..f10f38c83 100644 --- a/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/tinyrestclient/annotation/Post.java +++ b/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/tinyrestclient/annotation/Post.java @@ -29,9 +29,7 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -/** - * Annotation to mark an interface's method as a POST http method. - */ +/** Annotation to mark an interface's method as a POST http method. */ @Http @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) diff --git a/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/tinyrestclient/annotation/Put.java b/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/tinyrestclient/annotation/Put.java index 851303ed8..9af9b27c4 100644 --- a/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/tinyrestclient/annotation/Put.java +++ b/dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/tinyrestclient/annotation/Put.java @@ -29,9 +29,7 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -/** - * Annotation to mark an interface's method as a PUT http method. - */ +/** Annotation to mark an interface's method as a PUT http method. */ @Http @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) diff --git a/dynamic-proxy/src/test/java/com/iluwatar/dynamicproxy/AppTest.java b/dynamic-proxy/src/test/java/com/iluwatar/dynamicproxy/AppTest.java index 72412ca5b..107255695 100644 --- a/dynamic-proxy/src/test/java/com/iluwatar/dynamicproxy/AppTest.java +++ b/dynamic-proxy/src/test/java/com/iluwatar/dynamicproxy/AppTest.java @@ -24,14 +24,14 @@ */ package com.iluwatar.dynamicproxy; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import org.junit.jupiter.api.Test; + class AppTest { @Test void shouldRunAppWithoutExceptions() { - assertDoesNotThrow(() -> App.main(null)); + assertDoesNotThrow(() -> App.main(null)); } } diff --git a/event-aggregator/pom.xml b/event-aggregator/pom.xml index 2bf8797f4..3e7e58120 100644 --- a/event-aggregator/pom.xml +++ b/event-aggregator/pom.xml @@ -34,6 +34,14 @@ event-aggregator + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/App.java b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/App.java index 60a6381c9..4b5e9a615 100644 --- a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/App.java +++ b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/App.java @@ -67,12 +67,7 @@ public class App { var baelish = new LordBaelish(kingsHand, Event.STARK_SIGHTED); - var emitters = List.of( - kingsHand, - baelish, - varys, - scout - ); + var emitters = List.of(kingsHand, baelish, varys, scout); Arrays.stream(Weekday.values()) .>map(day -> emitter -> emitter.timePasses(day)) diff --git a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/Event.java b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/Event.java index dd839410c..87b1f5eaf 100644 --- a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/Event.java +++ b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/Event.java @@ -26,12 +26,9 @@ package com.iluwatar.event.aggregator; import lombok.RequiredArgsConstructor; -/** - * Event enumeration. - */ +/** Event enumeration. */ @RequiredArgsConstructor public enum Event { - WHITE_WALKERS_SIGHTED("White walkers sighted"), STARK_SIGHTED("Stark sighted"), WARSHIPS_APPROACHING("Warships approaching"), diff --git a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/EventEmitter.java b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/EventEmitter.java index 60bc05639..ccff62740 100644 --- a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/EventEmitter.java +++ b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/EventEmitter.java @@ -29,9 +29,7 @@ import java.util.LinkedList; import java.util.List; import java.util.Map; -/** - * EventEmitter is the base class for event producers that can be observed. - */ +/** EventEmitter is the base class for event producers that can be observed. */ public abstract class EventEmitter { private final Map> observerLists; @@ -46,11 +44,11 @@ public abstract class EventEmitter { } /** - * Registers observer for specific event in the related list. - * - * @param obs the observer that observers this emitter - * @param e the specific event for that observation occurs - * */ + * Registers observer for specific event in the related list. + * + * @param obs the observer that observers this emitter + * @param e the specific event for that observation occurs + */ public final void registerObserver(EventObserver obs, Event e) { if (!observerLists.containsKey(e)) { observerLists.put(e, new LinkedList<>()); @@ -62,9 +60,7 @@ public abstract class EventEmitter { protected void notifyObservers(Event e) { if (observerLists.containsKey(e)) { - observerLists - .get(e) - .forEach(observer -> observer.onEvent(e)); + observerLists.get(e).forEach(observer -> observer.onEvent(e)); } } diff --git a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/EventObserver.java b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/EventObserver.java index 631e24cb8..2db98f939 100644 --- a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/EventObserver.java +++ b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/EventObserver.java @@ -24,11 +24,8 @@ */ package com.iluwatar.event.aggregator; -/** - * Observers of events implement this interface. - */ +/** Observers of events implement this interface. */ public interface EventObserver { void onEvent(Event e); - } diff --git a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/KingJoffrey.java b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/KingJoffrey.java index 6273fdd59..90036f664 100644 --- a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/KingJoffrey.java +++ b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/KingJoffrey.java @@ -26,9 +26,7 @@ package com.iluwatar.event.aggregator; import lombok.extern.slf4j.Slf4j; -/** - * KingJoffrey observes events from {@link KingsHand}. - */ +/** KingJoffrey observes events from {@link KingsHand}. */ @Slf4j public class KingJoffrey implements EventObserver { diff --git a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/KingsHand.java b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/KingsHand.java index aa249c13c..c9089a68f 100644 --- a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/KingsHand.java +++ b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/KingsHand.java @@ -24,13 +24,10 @@ */ package com.iluwatar.event.aggregator; -/** - * KingsHand observes events from multiple sources and delivers them to listeners. - */ +/** KingsHand observes events from multiple sources and delivers them to listeners. */ public class KingsHand extends EventEmitter implements EventObserver { - public KingsHand() { - } + public KingsHand() {} public KingsHand(EventObserver obs, Event e) { super(obs, e); @@ -43,7 +40,8 @@ public class KingsHand extends EventEmitter implements EventObserver { @Override public void timePasses(Weekday day) { - // This method is intentionally left empty because KingsHand does not handle time-based events directly. + // This method is intentionally left empty because KingsHand does not handle time-based events + // directly. // It serves as a placeholder to fulfill the EventObserver interface contract. } } diff --git a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/LordBaelish.java b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/LordBaelish.java index 00033805f..f133a774d 100644 --- a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/LordBaelish.java +++ b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/LordBaelish.java @@ -24,13 +24,10 @@ */ package com.iluwatar.event.aggregator; -/** - * LordBaelish produces events. - */ +/** LordBaelish produces events. */ public class LordBaelish extends EventEmitter { - public LordBaelish() { - } + public LordBaelish() {} public LordBaelish(EventObserver obs, Event e) { super(obs, e); diff --git a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/LordVarys.java b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/LordVarys.java index 883560bc7..5472e2288 100644 --- a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/LordVarys.java +++ b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/LordVarys.java @@ -26,14 +26,11 @@ package com.iluwatar.event.aggregator; import lombok.extern.slf4j.Slf4j; -/** - * LordVarys produces events. - */ +/** LordVarys produces events. */ @Slf4j public class LordVarys extends EventEmitter implements EventObserver { - public LordVarys() { - } + public LordVarys() {} public LordVarys(EventObserver obs, Event e) { super(obs, e); @@ -46,7 +43,6 @@ public class LordVarys extends EventEmitter implements EventObserver { } } - @Override public void onEvent(Event e) { notifyObservers(e); diff --git a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/Scout.java b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/Scout.java index ef983585e..d1566571a 100644 --- a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/Scout.java +++ b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/Scout.java @@ -24,13 +24,10 @@ */ package com.iluwatar.event.aggregator; -/** - * Scout produces events. - */ +/** Scout produces events. */ public class Scout extends EventEmitter { - public Scout() { - } + public Scout() {} public Scout(EventObserver obs, Event e) { super(obs, e); diff --git a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/Weekday.java b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/Weekday.java index 6dbbd75c9..b232ad54b 100644 --- a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/Weekday.java +++ b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/Weekday.java @@ -26,12 +26,9 @@ package com.iluwatar.event.aggregator; import lombok.RequiredArgsConstructor; -/** - * Weekday enumeration. - */ +/** Weekday enumeration. */ @RequiredArgsConstructor public enum Weekday { - MONDAY("Monday"), TUESDAY("Tuesday"), WEDNESDAY("Wednesday"), diff --git a/event-aggregator/src/test/java/com/iluwatar/event/aggregator/AppTest.java b/event-aggregator/src/test/java/com/iluwatar/event/aggregator/AppTest.java index 3b0a66027..2ccd559a8 100644 --- a/event-aggregator/src/test/java/com/iluwatar/event/aggregator/AppTest.java +++ b/event-aggregator/src/test/java/com/iluwatar/event/aggregator/AppTest.java @@ -24,23 +24,19 @@ */ package com.iluwatar.event.aggregator; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -/** - * Application test - */ +import org.junit.jupiter.api.Test; + +/** Application test */ class AppTest { /** - * Issue: Add at least one assertion to this test case. - * Solution: Inserted assertion to check whether the execution of the main method in {@link App#main(String[])} - * throws an exception. + * Issue: Add at least one assertion to this test case. Solution: Inserted assertion to check + * whether the execution of the main method in {@link App#main(String[])} throws an exception. */ - @Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } } 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 2dba768f3..bfc00e6cd 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 @@ -42,32 +42,26 @@ import org.junit.jupiter.api.Test; */ abstract class EventEmitterTest { - /** - * Factory used to create a new instance of the test object with a default observer - */ + /** Factory used to create a new instance of the test object with a default observer */ private final BiFunction factoryWithDefaultObserver; - /** - * Factory used to create a new instance of the test object without passing a default observer - */ + /** Factory used to create a new instance of the test object without passing a default observer */ private final Supplier factoryWithoutDefaultObserver; - /** - * The day of the week an event is expected - */ + /** The day of the week an event is expected */ private final Weekday specialDay; - /** - * The expected event, emitted on the special day - */ + /** The expected event, emitted on the special day */ private final Event event; /** * Create a new event emitter test, using the given test object factories, special day and event */ - EventEmitterTest(final Weekday specialDay, final Event event, - final BiFunction factoryWithDefaultObserver, - final Supplier factoryWithoutDefaultObserver) { + EventEmitterTest( + final Weekday specialDay, + final Event event, + final BiFunction factoryWithDefaultObserver, + final Supplier factoryWithoutDefaultObserver) { this.specialDay = specialDay; this.event = event; @@ -90,12 +84,15 @@ abstract class EventEmitterTest { * received the correct event on the special day. * * @param specialDay The special day on which an event is emitted - * @param event The expected event emitted by the test object - * @param emitter The event emitter - * @param observers The registered observer mocks + * @param event The expected event emitted by the test object + * @param emitter The event emitter + * @param observers The registered observer mocks */ - private void testAllDays(final Weekday specialDay, final Event event, final E emitter, - final EventObserver... observers) { + private void testAllDays( + final Weekday specialDay, + final Event event, + final E emitter, + final EventObserver... observers) { for (final var weekday : Weekday.values()) { // Pass each week of the day, day by day to the event emitter @@ -121,7 +118,7 @@ abstract class EventEmitterTest { * event emitter without a default observer * * @param specialDay The special day on which an event is emitted - * @param event The expected event emitted by the test object + * @param event The expected event emitted by the test object */ private void testAllDaysWithoutDefaultObserver(final Weekday specialDay, final Event event) { final var observer1 = mock(EventObserver.class); @@ -138,7 +135,7 @@ abstract class EventEmitterTest { * Go over every day of the month, and check if the event is emitted on the given day. * * @param specialDay The special day on which an event is emitted - * @param event The expected event emitted by the test object + * @param event The expected event emitted by the test object */ private void testAllDaysWithDefaultObserver(final Weekday specialDay, final Event event) { final var defaultObserver = mock(EventObserver.class); @@ -151,5 +148,4 @@ abstract class EventEmitterTest { testAllDays(specialDay, event, emitter, defaultObserver, observer1, observer2); } - } diff --git a/event-aggregator/src/test/java/com/iluwatar/event/aggregator/EventTest.java b/event-aggregator/src/test/java/com/iluwatar/event/aggregator/EventTest.java index b5f65c1bb..20c3c4899 100644 --- a/event-aggregator/src/test/java/com/iluwatar/event/aggregator/EventTest.java +++ b/event-aggregator/src/test/java/com/iluwatar/event/aggregator/EventTest.java @@ -30,21 +30,18 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import java.util.Arrays; import org.junit.jupiter.api.Test; -/** - * EventTest - * - */ +/** EventTest */ class EventTest { - /** - * Verify if every event has a non-null, non-empty description - */ + /** Verify if every event has a non-null, non-empty description */ @Test void testToString() { - Arrays.stream(Event.values()).map(Event::toString).forEach(toString -> { - assertNotNull(toString); - assertFalse(toString.trim().isEmpty()); - }); + Arrays.stream(Event.values()) + .map(Event::toString) + .forEach( + toString -> { + assertNotNull(toString); + assertFalse(toString.trim().isEmpty()); + }); } - -} \ No newline at end of file +} diff --git a/event-aggregator/src/test/java/com/iluwatar/event/aggregator/KingJoffreyTest.java b/event-aggregator/src/test/java/com/iluwatar/event/aggregator/KingJoffreyTest.java index 70d731d20..aa689a34e 100644 --- a/event-aggregator/src/test/java/com/iluwatar/event/aggregator/KingJoffreyTest.java +++ b/event-aggregator/src/test/java/com/iluwatar/event/aggregator/KingJoffreyTest.java @@ -37,10 +37,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.slf4j.LoggerFactory; -/** - * KingJoffreyTest - * - */ +/** KingJoffreyTest */ class KingJoffreyTest { private InMemoryAppender appender; @@ -55,22 +52,21 @@ class KingJoffreyTest { appender.stop(); } - /** - * Test if {@link KingJoffrey} tells us what event he received - */ + /** Test if {@link KingJoffrey} tells us what event he received */ @Test void testOnEvent() { final var kingJoffrey = new KingJoffrey(); - IntStream.range(0, Event.values().length).forEach(i -> { - assertEquals(i, appender.getLogSize()); - var event = Event.values()[i]; - kingJoffrey.onEvent(event); - final var expectedMessage = "Received event from the King's Hand: " + event; - assertEquals(expectedMessage, appender.getLastMessage()); - assertEquals(i + 1, appender.getLogSize()); - }); - + IntStream.range(0, Event.values().length) + .forEach( + i -> { + assertEquals(i, appender.getLogSize()); + var event = Event.values()[i]; + kingJoffrey.onEvent(event); + final var expectedMessage = "Received event from the King's Hand: " + event; + assertEquals(expectedMessage, appender.getLastMessage()); + assertEquals(i + 1, appender.getLogSize()); + }); } private static class InMemoryAppender extends AppenderBase { @@ -94,5 +90,4 @@ class KingJoffreyTest { return log.size(); } } - } diff --git a/event-aggregator/src/test/java/com/iluwatar/event/aggregator/KingsHandTest.java b/event-aggregator/src/test/java/com/iluwatar/event/aggregator/KingsHandTest.java index 533252a2d..e06a50fc8 100644 --- a/event-aggregator/src/test/java/com/iluwatar/event/aggregator/KingsHandTest.java +++ b/event-aggregator/src/test/java/com/iluwatar/event/aggregator/KingsHandTest.java @@ -33,15 +33,10 @@ import static org.mockito.Mockito.verifyNoMoreInteractions; import java.util.Arrays; import org.junit.jupiter.api.Test; -/** - * KingsHandTest - * - */ +/** KingsHandTest */ class KingsHandTest extends EventEmitterTest { - /** - * Create a new test instance, using the correct object factory - */ + /** Create a new test instance, using the correct object factory */ public KingsHandTest() { super(null, null, KingsHand::new, KingsHand::new); } @@ -64,12 +59,12 @@ class KingsHandTest extends EventEmitterTest { verifyNoMoreInteractions(observer); // Verify if each event is passed on to the observer, nothing less, nothing more. - Arrays.stream(Event.values()).forEach(event -> { - kingsHand.onEvent(event); - verify(observer, times(1)).onEvent(eq(event)); - verifyNoMoreInteractions(observer); - }); - + Arrays.stream(Event.values()) + .forEach( + event -> { + kingsHand.onEvent(event); + verify(observer, times(1)).onEvent(eq(event)); + verifyNoMoreInteractions(observer); + }); } - -} \ No newline at end of file +} diff --git a/event-aggregator/src/test/java/com/iluwatar/event/aggregator/LordBaelishTest.java b/event-aggregator/src/test/java/com/iluwatar/event/aggregator/LordBaelishTest.java index 75481c2af..c90ccd993 100644 --- a/event-aggregator/src/test/java/com/iluwatar/event/aggregator/LordBaelishTest.java +++ b/event-aggregator/src/test/java/com/iluwatar/event/aggregator/LordBaelishTest.java @@ -24,17 +24,11 @@ */ package com.iluwatar.event.aggregator; -/** - * LordBaelishTest - * - */ +/** LordBaelishTest */ class LordBaelishTest extends EventEmitterTest { - /** - * Create a new test instance, using the correct object factory - */ + /** Create a new test instance, using the correct object factory */ public LordBaelishTest() { super(Weekday.FRIDAY, Event.STARK_SIGHTED, LordBaelish::new, LordBaelish::new); } - -} \ No newline at end of file +} diff --git a/event-aggregator/src/test/java/com/iluwatar/event/aggregator/LordVarysTest.java b/event-aggregator/src/test/java/com/iluwatar/event/aggregator/LordVarysTest.java index 68aaff394..5ddd0a65e 100644 --- a/event-aggregator/src/test/java/com/iluwatar/event/aggregator/LordVarysTest.java +++ b/event-aggregator/src/test/java/com/iluwatar/event/aggregator/LordVarysTest.java @@ -24,17 +24,11 @@ */ package com.iluwatar.event.aggregator; -/** - * LordVarysTest - * - */ +/** LordVarysTest */ class LordVarysTest extends EventEmitterTest { - /** - * Create a new test instance, using the correct object factory - */ + /** Create a new test instance, using the correct object factory */ public LordVarysTest() { super(Weekday.SATURDAY, Event.TRAITOR_DETECTED, LordVarys::new, LordVarys::new); } - -} \ No newline at end of file +} diff --git a/event-aggregator/src/test/java/com/iluwatar/event/aggregator/ScoutTest.java b/event-aggregator/src/test/java/com/iluwatar/event/aggregator/ScoutTest.java index 0b10c86c1..b6f86123e 100644 --- a/event-aggregator/src/test/java/com/iluwatar/event/aggregator/ScoutTest.java +++ b/event-aggregator/src/test/java/com/iluwatar/event/aggregator/ScoutTest.java @@ -24,19 +24,12 @@ */ package com.iluwatar.event.aggregator; -/** - * ScoutTest - * - */ +/** ScoutTest */ class ScoutTest extends EventEmitterTest { - /** - * Create a new test instance, using the correct object factory - */ + /** Create a new test instance, using the correct object factory */ public ScoutTest() { - super(Weekday.TUESDAY, Event.WARSHIPS_APPROACHING, Scout::new, Scout::new); - + super(Weekday.TUESDAY, Event.WARSHIPS_APPROACHING, Scout::new, Scout::new); } - -} \ No newline at end of file +} diff --git a/event-aggregator/src/test/java/com/iluwatar/event/aggregator/WeekdayTest.java b/event-aggregator/src/test/java/com/iluwatar/event/aggregator/WeekdayTest.java index 972605009..e078951e4 100644 --- a/event-aggregator/src/test/java/com/iluwatar/event/aggregator/WeekdayTest.java +++ b/event-aggregator/src/test/java/com/iluwatar/event/aggregator/WeekdayTest.java @@ -30,19 +30,17 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import java.util.Arrays; import org.junit.jupiter.api.Test; -/** - * WeekdayTest - * - */ +/** WeekdayTest */ class WeekdayTest { @Test void testToString() { - Arrays.stream(Weekday.values()).forEach(weekday -> { - final String toString = weekday.toString(); - assertNotNull(toString); - assertEquals(weekday.name(), toString.toUpperCase()); - }); + Arrays.stream(Weekday.values()) + .forEach( + weekday -> { + final String toString = weekday.toString(); + assertNotNull(toString); + assertEquals(weekday.name(), toString.toUpperCase()); + }); } - -} \ No newline at end of file +} diff --git a/event-based-asynchronous/pom.xml b/event-based-asynchronous/pom.xml index 1c1a9346c..b0ff6e9bc 100644 --- a/event-based-asynchronous/pom.xml +++ b/event-based-asynchronous/pom.xml @@ -34,6 +34,14 @@ event-based-asynchronous + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/event-based-asynchronous/src/main/java/com/iluwatar/event/asynchronous/App.java b/event-based-asynchronous/src/main/java/com/iluwatar/event/asynchronous/App.java index fd94357d0..731cd1691 100644 --- a/event-based-asynchronous/src/main/java/com/iluwatar/event/asynchronous/App.java +++ b/event-based-asynchronous/src/main/java/com/iluwatar/event/asynchronous/App.java @@ -97,9 +97,7 @@ public class App { } } - /** - * Run program in either interactive mode or not. - */ + /** Run program in either interactive mode or not. */ public void run() { if (interactiveMode) { runInteractiveMode(); @@ -108,9 +106,7 @@ public class App { } } - /** - * Run program in non-interactive mode. - */ + /** Run program in non-interactive mode. */ public void quickRun() { var eventManager = new EventManager(); @@ -135,15 +131,15 @@ public class App { eventManager.cancel(syncEventId); LOGGER.info("Sync Event [{}] has been stopped.", syncEventId); - } catch (MaxNumOfEventsAllowedException | LongRunningEventException | EventDoesNotExistException + } catch (MaxNumOfEventsAllowedException + | LongRunningEventException + | EventDoesNotExistException | InvalidOperationException e) { LOGGER.error(e.getMessage()); } } - /** - * Run program in interactive mode. - */ + /** Run program in interactive mode. */ public void runInteractiveMode() { var eventManager = new EventManager(); @@ -151,7 +147,8 @@ public class App { var option = -1; while (option != 4) { LOGGER.info("Hello. Would you like to boil some eggs?"); - LOGGER.info(""" + LOGGER.info( + """ (1) BOIL AN EGG (2) STOP BOILING THIS EGG (3) HOW ARE MY EGGS? @@ -214,7 +211,8 @@ public class App { var eventId = eventManager.createAsync(eventTime); eventManager.start(eventId); LOGGER.info("Egg [{}] is being boiled.", eventId); - } catch (MaxNumOfEventsAllowedException | LongRunningEventException + } catch (MaxNumOfEventsAllowedException + | LongRunningEventException | EventDoesNotExistException e) { LOGGER.error(e.getMessage()); } @@ -223,13 +221,14 @@ public class App { var eventId = eventManager.create(eventTime); eventManager.start(eventId); LOGGER.info("Egg [{}] is being boiled.", eventId); - } catch (MaxNumOfEventsAllowedException | InvalidOperationException - | LongRunningEventException | EventDoesNotExistException e) { + } catch (MaxNumOfEventsAllowedException + | InvalidOperationException + | LongRunningEventException + | EventDoesNotExistException e) { LOGGER.error(e.getMessage()); } } else { LOGGER.info("Unknown event type."); } } - -} \ No newline at end of file +} diff --git a/event-based-asynchronous/src/main/java/com/iluwatar/event/asynchronous/AsyncEvent.java b/event-based-asynchronous/src/main/java/com/iluwatar/event/asynchronous/AsyncEvent.java index 7537afd44..b58848f0a 100644 --- a/event-based-asynchronous/src/main/java/com/iluwatar/event/asynchronous/AsyncEvent.java +++ b/event-based-asynchronous/src/main/java/com/iluwatar/event/asynchronous/AsyncEvent.java @@ -32,17 +32,14 @@ import lombok.Getter; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; -/** - * Each Event runs as a separate/individual thread. - */ +/** Each Event runs as a separate/individual thread. */ @Slf4j @RequiredArgsConstructor public class AsyncEvent implements Event, Runnable { private final int eventId; private final Duration eventTime; - @Getter - private final boolean synchronous; + @Getter private final boolean synchronous; private Thread thread; private final AtomicBoolean isComplete = new AtomicBoolean(false); private ThreadCompleteListener eventListener; @@ -97,4 +94,4 @@ public class AsyncEvent implements Event, Runnable { eventListener.completedEventHandler(eventId); } } -} \ No newline at end of file +} diff --git a/event-based-asynchronous/src/main/java/com/iluwatar/event/asynchronous/Event.java b/event-based-asynchronous/src/main/java/com/iluwatar/event/asynchronous/Event.java index 663ba5a7e..6c51f8584 100644 --- a/event-based-asynchronous/src/main/java/com/iluwatar/event/asynchronous/Event.java +++ b/event-based-asynchronous/src/main/java/com/iluwatar/event/asynchronous/Event.java @@ -34,5 +34,4 @@ public interface Event { void stop(); void status(); - } diff --git a/event-based-asynchronous/src/main/java/com/iluwatar/event/asynchronous/EventDoesNotExistException.java b/event-based-asynchronous/src/main/java/com/iluwatar/event/asynchronous/EventDoesNotExistException.java index 8069060fe..ad6a649c0 100644 --- a/event-based-asynchronous/src/main/java/com/iluwatar/event/asynchronous/EventDoesNotExistException.java +++ b/event-based-asynchronous/src/main/java/com/iluwatar/event/asynchronous/EventDoesNotExistException.java @@ -26,13 +26,10 @@ package com.iluwatar.event.asynchronous; import java.io.Serial; -/** - * Custom Exception Class for Non-Existent Event. - */ +/** Custom Exception Class for Non-Existent Event. */ public class EventDoesNotExistException extends Exception { - @Serial - private static final long serialVersionUID = -3398463738273811509L; + @Serial private static final long serialVersionUID = -3398463738273811509L; public EventDoesNotExistException(String message) { super(message); diff --git a/event-based-asynchronous/src/main/java/com/iluwatar/event/asynchronous/EventManager.java b/event-based-asynchronous/src/main/java/com/iluwatar/event/asynchronous/EventManager.java index 44561d6e2..cef3697ff 100644 --- a/event-based-asynchronous/src/main/java/com/iluwatar/event/asynchronous/EventManager.java +++ b/event-based-asynchronous/src/main/java/com/iluwatar/event/asynchronous/EventManager.java @@ -31,9 +31,9 @@ import java.util.concurrent.ConcurrentHashMap; import lombok.Getter; /** - * EventManager handles and maintains a pool of event threads. {@link AsyncEvent} threads are created - * upon user request. Thre are two types of events; Asynchronous and Synchronous. There can be - * multiple Asynchronous events running at once but only one Synchronous event running at a time. + * EventManager handles and maintains a pool of event threads. {@link AsyncEvent} threads are + * created upon user request. Thre are two types of events; Asynchronous and Synchronous. There can + * be multiple Asynchronous events running at once but only one Synchronous event running at a time. * Currently supported event operations are: start, stop, and getStatus. Once an event is complete, * it then notifies EventManager through a listener. The EventManager then takes the event out of * the pool. @@ -48,18 +48,14 @@ public class EventManager implements ThreadCompleteListener { private int currentlyRunningSyncEvent = -1; private final SecureRandom rand; - @Getter - private final Map eventPool; + @Getter private final Map eventPool; private static final String DOES_NOT_EXIST = " does not exist."; - /** - * EventManager constructor. - */ + /** EventManager constructor. */ public EventManager() { rand = new SecureRandom(); eventPool = new ConcurrentHashMap<>(MAX_RUNNING_EVENTS); - } /** @@ -68,15 +64,18 @@ public class EventManager implements ThreadCompleteListener { * @param eventTime Time an event should run for. * @return eventId * @throws MaxNumOfEventsAllowedException When too many events are running at a time. - * @throws InvalidOperationException No new synchronous events can be created when one is - * already running. - * @throws LongRunningEventException Long-running events are not allowed in the app. + * @throws InvalidOperationException No new synchronous events can be created when one is already + * running. + * @throws LongRunningEventException Long-running events are not allowed in the app. */ public int create(Duration eventTime) throws MaxNumOfEventsAllowedException, InvalidOperationException, LongRunningEventException { if (currentlyRunningSyncEvent != -1) { - throw new InvalidOperationException("Event [" + currentlyRunningSyncEvent + "] is still" - + " running. Please wait until it finishes and try again."); + throw new InvalidOperationException( + "Event [" + + currentlyRunningSyncEvent + + "] is still" + + " running. Please wait until it finishes and try again."); } var eventId = createEvent(eventTime, true); @@ -91,10 +90,10 @@ public class EventManager implements ThreadCompleteListener { * @param eventTime Time an event should run for. * @return eventId * @throws MaxNumOfEventsAllowedException When too many events are running at a time. - * @throws LongRunningEventException Long-running events are not allowed in the app. + * @throws LongRunningEventException Long-running events are not allowed in the app. */ - public int createAsync(Duration eventTime) throws MaxNumOfEventsAllowedException, - LongRunningEventException { + public int createAsync(Duration eventTime) + throws MaxNumOfEventsAllowedException, LongRunningEventException { return createEvent(eventTime, false); } @@ -105,8 +104,8 @@ public class EventManager implements ThreadCompleteListener { } if (eventPool.size() == MAX_RUNNING_EVENTS) { - throw new MaxNumOfEventsAllowedException("Too many events are running at the moment." - + " Please try again later."); + throw new MaxNumOfEventsAllowedException( + "Too many events are running at the moment." + " Please try again later."); } if (eventTime.getSeconds() > MAX_EVENT_TIME.getSeconds()) { @@ -170,17 +169,13 @@ public class EventManager implements ThreadCompleteListener { eventPool.get(eventId).status(); } - /** - * Gets status of all running events. - */ + /** Gets status of all running events. */ @SuppressWarnings("rawtypes") public void statusOfAllEvents() { eventPool.entrySet().forEach(entry -> ((AsyncEvent) ((Map.Entry) entry).getValue()).status()); } - /** - * Stop all running events. - */ + /** Stop all running events. */ @SuppressWarnings("rawtypes") public void shutdown() { eventPool.entrySet().forEach(entry -> ((AsyncEvent) ((Map.Entry) entry).getValue()).stop()); @@ -188,8 +183,7 @@ public class EventManager implements ThreadCompleteListener { /** * Returns a pseudo-random number between min and max, inclusive. The difference between min and - * max can be at most - * Integer.MAX_VALUE - 1. + * max can be at most Integer.MAX_VALUE - 1. */ private int generateId() { // nextInt is normally exclusive of the top value, @@ -203,7 +197,8 @@ public class EventManager implements ThreadCompleteListener { } /** - * Callback from an {@link AsyncEvent} (once it is complete). The Event is then removed from the pool. + * Callback from an {@link AsyncEvent} (once it is complete). The Event is then removed from the + * pool. */ @Override public void completedEventHandler(int eventId) { @@ -214,10 +209,8 @@ public class EventManager implements ThreadCompleteListener { eventPool.remove(eventId); } - /** - * Get number of currently running Synchronous events. - */ + /** Get number of currently running Synchronous events. */ public int numOfCurrentlyRunningSyncEvent() { return currentlyRunningSyncEvent; } -} \ No newline at end of file +} diff --git a/event-based-asynchronous/src/main/java/com/iluwatar/event/asynchronous/InvalidOperationException.java b/event-based-asynchronous/src/main/java/com/iluwatar/event/asynchronous/InvalidOperationException.java index cffe3a3cc..f8a591460 100644 --- a/event-based-asynchronous/src/main/java/com/iluwatar/event/asynchronous/InvalidOperationException.java +++ b/event-based-asynchronous/src/main/java/com/iluwatar/event/asynchronous/InvalidOperationException.java @@ -26,16 +26,12 @@ package com.iluwatar.event.asynchronous; import java.io.Serial; -/** - * Type of Exception raised when the Operation being invoked is Invalid. - */ +/** Type of Exception raised when the Operation being invoked is Invalid. */ public class InvalidOperationException extends Exception { - @Serial - private static final long serialVersionUID = -6191545255213410803L; + @Serial private static final long serialVersionUID = -6191545255213410803L; public InvalidOperationException(String message) { super(message); } - } diff --git a/event-based-asynchronous/src/main/java/com/iluwatar/event/asynchronous/LongRunningEventException.java b/event-based-asynchronous/src/main/java/com/iluwatar/event/asynchronous/LongRunningEventException.java index 54e2717c8..9045b6dcf 100644 --- a/event-based-asynchronous/src/main/java/com/iluwatar/event/asynchronous/LongRunningEventException.java +++ b/event-based-asynchronous/src/main/java/com/iluwatar/event/asynchronous/LongRunningEventException.java @@ -26,13 +26,10 @@ package com.iluwatar.event.asynchronous; import java.io.Serial; -/** - * Type of Exception raised when the Operation being invoked is Long Running. - */ +/** Type of Exception raised when the Operation being invoked is Long Running. */ public class LongRunningEventException extends Exception { - @Serial - private static final long serialVersionUID = -483423544320148809L; + @Serial private static final long serialVersionUID = -483423544320148809L; public LongRunningEventException(String message) { super(message); diff --git a/event-based-asynchronous/src/main/java/com/iluwatar/event/asynchronous/MaxNumOfEventsAllowedException.java b/event-based-asynchronous/src/main/java/com/iluwatar/event/asynchronous/MaxNumOfEventsAllowedException.java index af4da61f0..16fa5502d 100644 --- a/event-based-asynchronous/src/main/java/com/iluwatar/event/asynchronous/MaxNumOfEventsAllowedException.java +++ b/event-based-asynchronous/src/main/java/com/iluwatar/event/asynchronous/MaxNumOfEventsAllowedException.java @@ -26,13 +26,10 @@ package com.iluwatar.event.asynchronous; import java.io.Serial; -/** - * Type of Exception raised when the max number of allowed events is exceeded. - */ +/** Type of Exception raised when the max number of allowed events is exceeded. */ public class MaxNumOfEventsAllowedException extends Exception { - @Serial - private static final long serialVersionUID = -8430876973516292695L; + @Serial private static final long serialVersionUID = -8430876973516292695L; public MaxNumOfEventsAllowedException(String message) { super(message); diff --git a/event-based-asynchronous/src/main/java/com/iluwatar/event/asynchronous/ThreadCompleteListener.java b/event-based-asynchronous/src/main/java/com/iluwatar/event/asynchronous/ThreadCompleteListener.java index 334cada2c..f30eb5135 100644 --- a/event-based-asynchronous/src/main/java/com/iluwatar/event/asynchronous/ThreadCompleteListener.java +++ b/event-based-asynchronous/src/main/java/com/iluwatar/event/asynchronous/ThreadCompleteListener.java @@ -24,9 +24,7 @@ */ package com.iluwatar.event.asynchronous; -/** - * Interface with listener behaviour related to Thread Completion. - */ +/** Interface with listener behaviour related to Thread Completion. */ public interface ThreadCompleteListener { void completedEventHandler(final int eventId); } diff --git a/event-based-asynchronous/src/test/java/com/iluwatar/event/asynchronous/AppTest.java b/event-based-asynchronous/src/test/java/com/iluwatar/event/asynchronous/AppTest.java index 4e4e33ac6..4b5094033 100644 --- a/event-based-asynchronous/src/test/java/com/iluwatar/event/asynchronous/AppTest.java +++ b/event-based-asynchronous/src/test/java/com/iluwatar/event/asynchronous/AppTest.java @@ -24,23 +24,19 @@ */ package com.iluwatar.event.asynchronous; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -/** - * Tests that EventAsynchronous example runs without errors. - */ +import org.junit.jupiter.api.Test; + +/** Tests that EventAsynchronous example runs without errors. */ class AppTest { /** - * Issue: Add at least one assertion to this test case. - * Solution: Inserted assertion to check whether the execution of the main method in {@link App#main(String[])} - * throws an exception. + * Issue: Add at least one assertion to this test case. Solution: Inserted assertion to check + * whether the execution of the main method in {@link App#main(String[])} throws an exception. */ - @Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/event-based-asynchronous/src/test/java/com/iluwatar/event/asynchronous/EventAsynchronousTest.java b/event-based-asynchronous/src/test/java/com/iluwatar/event/asynchronous/EventAsynchronousTest.java index 5de006341..ab9dd70bb 100644 --- a/event-based-asynchronous/src/test/java/com/iluwatar/event/asynchronous/EventAsynchronousTest.java +++ b/event-based-asynchronous/src/test/java/com/iluwatar/event/asynchronous/EventAsynchronousTest.java @@ -31,13 +31,11 @@ import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import java.time.Duration; import lombok.SneakyThrows; import org.junit.jupiter.api.Test; -import java.time.Duration; -/** - * Application test - */ +/** Application test */ class EventAsynchronousTest { @Test @@ -46,7 +44,7 @@ class EventAsynchronousTest { var eventManager = new EventManager(); var aEventId = eventManager.createAsync(Duration.ofSeconds(60)); - assertDoesNotThrow(() ->eventManager.start(aEventId)); + assertDoesNotThrow(() -> eventManager.start(aEventId)); assertEquals(1, eventManager.getEventPool().size()); assertTrue(eventManager.getEventPool().size() < EventManager.MAX_RUNNING_EVENTS); @@ -54,7 +52,6 @@ class EventAsynchronousTest { assertDoesNotThrow(() -> eventManager.cancel(aEventId)); assertTrue(eventManager.getEventPool().isEmpty()); - } @Test @@ -70,7 +67,6 @@ class EventAsynchronousTest { assertDoesNotThrow(() -> eventManager.cancel(sEventId)); assertTrue(eventManager.getEventPool().isEmpty()); - } @Test @@ -86,21 +82,21 @@ class EventAsynchronousTest { eventManager.start(sEventId); await().until(() -> eventManager.getEventPool().isEmpty()); - } @Test @SneakyThrows void testUnsuccessfulSynchronousEvent() { - assertThrows(InvalidOperationException.class, () -> { - var eventManager = new EventManager(); + assertThrows( + InvalidOperationException.class, + () -> { + var eventManager = new EventManager(); - var sEventId = assertDoesNotThrow(() -> eventManager.create(Duration.ofSeconds(60))); - eventManager.start(sEventId); - sEventId = eventManager.create(Duration.ofSeconds(60)); - eventManager.start(sEventId); - - }); + var sEventId = assertDoesNotThrow(() -> eventManager.create(Duration.ofSeconds(60))); + eventManager.start(sEventId); + sEventId = eventManager.create(Duration.ofSeconds(60)); + eventManager.start(sEventId); + }); } @Test @@ -119,28 +115,27 @@ class EventAsynchronousTest { eventManager.start(aEventId3); await().until(() -> eventManager.getEventPool().isEmpty()); - } @Test - void testLongRunningEventException(){ - assertThrows(LongRunningEventException.class, () -> { - var eventManager = new EventManager(); - eventManager.createAsync(Duration.ofMinutes(31)); - }); + void testLongRunningEventException() { + assertThrows( + LongRunningEventException.class, + () -> { + var eventManager = new EventManager(); + eventManager.createAsync(Duration.ofMinutes(31)); + }); } - @Test - void testMaxNumOfEventsAllowedException(){ - assertThrows(MaxNumOfEventsAllowedException.class, () -> { - final var eventManager = new EventManager(); - for(int i=0;i<1100;i++){ - eventManager.createAsync(Duration.ofSeconds(i)); - } - }); + void testMaxNumOfEventsAllowedException() { + assertThrows( + MaxNumOfEventsAllowedException.class, + () -> { + final var eventManager = new EventManager(); + for (int i = 0; i < 1100; i++) { + eventManager.createAsync(Duration.ofSeconds(i)); + } + }); } - - - -} \ No newline at end of file +} diff --git a/event-driven-architecture/pom.xml b/event-driven-architecture/pom.xml index eac196170..8a9fc2787 100644 --- a/event-driven-architecture/pom.xml +++ b/event-driven-architecture/pom.xml @@ -34,6 +34,14 @@ event-driven-architecture + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/event-driven-architecture/src/main/java/com/iluwatar/eda/App.java b/event-driven-architecture/src/main/java/com/iluwatar/eda/App.java index c4aaa6bc3..3b2ea6ae2 100644 --- a/event-driven-architecture/src/main/java/com/iluwatar/eda/App.java +++ b/event-driven-architecture/src/main/java/com/iluwatar/eda/App.java @@ -61,5 +61,4 @@ public class App { dispatcher.dispatch(new UserCreatedEvent(user)); dispatcher.dispatch(new UserUpdatedEvent(user)); } - } diff --git a/event-driven-architecture/src/main/java/com/iluwatar/eda/event/AbstractEvent.java b/event-driven-architecture/src/main/java/com/iluwatar/eda/event/AbstractEvent.java index 9a8834ff9..0add94462 100644 --- a/event-driven-architecture/src/main/java/com/iluwatar/eda/event/AbstractEvent.java +++ b/event-driven-architecture/src/main/java/com/iluwatar/eda/event/AbstractEvent.java @@ -30,10 +30,12 @@ import com.iluwatar.eda.framework.EventDispatcher; /** * The {@link AbstractEvent} class serves as a base class for defining custom events happening with * your system. In this example we have two types of events defined. + * *

    - *
  • {@link UserCreatedEvent} - used when a user is created
  • - *
  • {@link UserUpdatedEvent} - used when a user is updated
  • + *
  • {@link UserCreatedEvent} - used when a user is created + *
  • {@link UserUpdatedEvent} - used when a user is updated *
+ * * Events can be distinguished using the {@link #getType() getType} method. */ public abstract class AbstractEvent implements Event { @@ -47,4 +49,4 @@ public abstract class AbstractEvent implements Event { public Class getType() { return getClass(); } -} \ No newline at end of file +} diff --git a/event-driven-architecture/src/main/java/com/iluwatar/eda/event/UserCreatedEvent.java b/event-driven-architecture/src/main/java/com/iluwatar/eda/event/UserCreatedEvent.java index 245f79b4c..06cbe3122 100644 --- a/event-driven-architecture/src/main/java/com/iluwatar/eda/event/UserCreatedEvent.java +++ b/event-driven-architecture/src/main/java/com/iluwatar/eda/event/UserCreatedEvent.java @@ -29,9 +29,9 @@ import lombok.Getter; import lombok.RequiredArgsConstructor; /** - * The {@link UserCreatedEvent} should be dispatched whenever a user has been created. - * This class can be extended to contain details about the user has been created. - * In this example, the entire {@link User} object is passed on as data with the event. + * The {@link UserCreatedEvent} should be dispatched whenever a user has been created. This class + * can be extended to contain details about the user has been created. In this example, the entire + * {@link User} object is passed on as data with the event. */ @RequiredArgsConstructor @Getter diff --git a/event-driven-architecture/src/main/java/com/iluwatar/eda/event/UserUpdatedEvent.java b/event-driven-architecture/src/main/java/com/iluwatar/eda/event/UserUpdatedEvent.java index 6fa1832cb..5fd0e4a7d 100644 --- a/event-driven-architecture/src/main/java/com/iluwatar/eda/event/UserUpdatedEvent.java +++ b/event-driven-architecture/src/main/java/com/iluwatar/eda/event/UserUpdatedEvent.java @@ -29,9 +29,9 @@ import lombok.Getter; import lombok.RequiredArgsConstructor; /** - * The {@link UserUpdatedEvent} should be dispatched whenever a user has been updated. - * This class can be extended to contain details about the user has been updated. - * In this example, the entire {@link User} object is passed on as data with the event. + * The {@link UserUpdatedEvent} should be dispatched whenever a user has been updated. This class + * can be extended to contain details about the user has been updated. In this example, the entire + * {@link User} object is passed on as data with the event. */ @RequiredArgsConstructor @Getter diff --git a/event-driven-architecture/src/main/java/com/iluwatar/eda/framework/EventDispatcher.java b/event-driven-architecture/src/main/java/com/iluwatar/eda/framework/EventDispatcher.java index 1d0fab9d5..da29f770e 100644 --- a/event-driven-architecture/src/main/java/com/iluwatar/eda/framework/EventDispatcher.java +++ b/event-driven-architecture/src/main/java/com/iluwatar/eda/framework/EventDispatcher.java @@ -43,12 +43,9 @@ public class EventDispatcher { * Links an {@link Event} to a specific {@link Handler}. * * @param eventType The {@link Event} to be registered - * @param handler The {@link Handler} that will be handling the {@link Event} + * @param handler The {@link Handler} that will be handling the {@link Event} */ - public void registerHandler( - Class eventType, - Handler handler - ) { + public void registerHandler(Class eventType, Handler handler) { handlers.put(eventType, handler); } @@ -64,5 +61,4 @@ public class EventDispatcher { handler.onEvent(event); } } - } diff --git a/event-driven-architecture/src/main/java/com/iluwatar/eda/handler/UserCreatedEventHandler.java b/event-driven-architecture/src/main/java/com/iluwatar/eda/handler/UserCreatedEventHandler.java index 22d5fdaa4..25f2354b5 100644 --- a/event-driven-architecture/src/main/java/com/iluwatar/eda/handler/UserCreatedEventHandler.java +++ b/event-driven-architecture/src/main/java/com/iluwatar/eda/handler/UserCreatedEventHandler.java @@ -28,9 +28,7 @@ import com.iluwatar.eda.event.UserCreatedEvent; import com.iluwatar.eda.framework.Handler; import lombok.extern.slf4j.Slf4j; -/** - * Handles the {@link UserCreatedEvent} message. - */ +/** Handles the {@link UserCreatedEvent} message. */ @Slf4j public class UserCreatedEventHandler implements Handler { @@ -38,5 +36,4 @@ public class UserCreatedEventHandler implements Handler { public void onEvent(UserCreatedEvent event) { LOGGER.info("User '{}' has been Created!", event.getUser().username()); } - } diff --git a/event-driven-architecture/src/main/java/com/iluwatar/eda/handler/UserUpdatedEventHandler.java b/event-driven-architecture/src/main/java/com/iluwatar/eda/handler/UserUpdatedEventHandler.java index 016b52570..9947af484 100644 --- a/event-driven-architecture/src/main/java/com/iluwatar/eda/handler/UserUpdatedEventHandler.java +++ b/event-driven-architecture/src/main/java/com/iluwatar/eda/handler/UserUpdatedEventHandler.java @@ -28,9 +28,7 @@ import com.iluwatar.eda.event.UserUpdatedEvent; import com.iluwatar.eda.framework.Handler; import lombok.extern.slf4j.Slf4j; -/** - * Handles the {@link UserUpdatedEvent} message. - */ +/** Handles the {@link UserUpdatedEvent} message. */ @Slf4j public class UserUpdatedEventHandler implements Handler { diff --git a/event-driven-architecture/src/main/java/com/iluwatar/eda/model/User.java b/event-driven-architecture/src/main/java/com/iluwatar/eda/model/User.java index b255cfa98..2b9e17693 100644 --- a/event-driven-architecture/src/main/java/com/iluwatar/eda/model/User.java +++ b/event-driven-architecture/src/main/java/com/iluwatar/eda/model/User.java @@ -26,8 +26,6 @@ package com.iluwatar.eda.model; import com.iluwatar.eda.event.UserCreatedEvent; import com.iluwatar.eda.event.UserUpdatedEvent; -import lombok.Getter; -import lombok.RequiredArgsConstructor; /** * This {@link User} class is a basic pojo used to demonstrate user data sent along with the {@link diff --git a/event-driven-architecture/src/test/java/com/iluwatar/eda/AppTest.java b/event-driven-architecture/src/test/java/com/iluwatar/eda/AppTest.java index 17f3bddaa..52e08eb9a 100644 --- a/event-driven-architecture/src/test/java/com/iluwatar/eda/AppTest.java +++ b/event-driven-architecture/src/test/java/com/iluwatar/eda/AppTest.java @@ -24,24 +24,21 @@ */ package com.iluwatar.eda; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -/** - * Tests that Event Driven Architecture example runs without errors. - */ +import org.junit.jupiter.api.Test; + +/** Tests that Event Driven Architecture example runs without errors. */ class AppTest { /** * Issue: Add at least one assertion to this test case. - *

- * Solution: Inserted assertion to check whether the execution of the main method in {@link App#main(String[])} - * throws an exception. + * + *

Solution: Inserted assertion to check whether the execution of the main method in {@link + * App#main(String[])} throws an exception. */ - @Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/event-driven-architecture/src/test/java/com/iluwatar/eda/event/UserCreatedEventTest.java b/event-driven-architecture/src/test/java/com/iluwatar/eda/event/UserCreatedEventTest.java index 88ba805a4..d3254255e 100644 --- a/event-driven-architecture/src/test/java/com/iluwatar/eda/event/UserCreatedEventTest.java +++ b/event-driven-architecture/src/test/java/com/iluwatar/eda/event/UserCreatedEventTest.java @@ -29,9 +29,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import com.iluwatar.eda.model.User; import org.junit.jupiter.api.Test; -/** - * {@link UserCreatedEventTest} tests and verifies {@link AbstractEvent} behaviour. - */ +/** {@link UserCreatedEventTest} tests and verifies {@link AbstractEvent} behaviour. */ class UserCreatedEventTest { /** diff --git a/event-driven-architecture/src/test/java/com/iluwatar/eda/framework/EventDispatcherTest.java b/event-driven-architecture/src/test/java/com/iluwatar/eda/framework/EventDispatcherTest.java index b4cae33ab..f92fde927 100644 --- a/event-driven-architecture/src/test/java/com/iluwatar/eda/framework/EventDispatcherTest.java +++ b/event-driven-architecture/src/test/java/com/iluwatar/eda/framework/EventDispatcherTest.java @@ -34,9 +34,7 @@ import com.iluwatar.eda.handler.UserUpdatedEventHandler; import com.iluwatar.eda.model.User; import org.junit.jupiter.api.Test; -/** - * Event Dispatcher unit tests to assert and verify correct event dispatcher behaviour - */ +/** Event Dispatcher unit tests to assert and verify correct event dispatcher behaviour */ class EventDispatcherTest { /** @@ -57,15 +55,14 @@ class EventDispatcherTest { var userCreatedEvent = new UserCreatedEvent(user); var userUpdatedEvent = new UserUpdatedEvent(user); - //fire a userCreatedEvent and verify that userCreatedEventHandler has been invoked. + // fire a userCreatedEvent and verify that userCreatedEventHandler has been invoked. dispatcher.dispatch(userCreatedEvent); verify(userCreatedEventHandler).onEvent(userCreatedEvent); verify(dispatcher).dispatch(userCreatedEvent); - //fire a userCreatedEvent and verify that userUpdatedEventHandler has been invoked. + // fire a userCreatedEvent and verify that userUpdatedEventHandler has been invoked. dispatcher.dispatch(userUpdatedEvent); verify(userUpdatedEventHandler).onEvent(userUpdatedEvent); verify(dispatcher).dispatch(userUpdatedEvent); } - } diff --git a/event-queue/pom.xml b/event-queue/pom.xml index 3f2d1de62..4b7566df4 100644 --- a/event-queue/pom.xml +++ b/event-queue/pom.xml @@ -34,6 +34,14 @@ event-queue + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/event-queue/src/main/java/com/iluwatar/event/queue/App.java b/event-queue/src/main/java/com/iluwatar/event/queue/App.java index 283884fea..3ea957a5a 100644 --- a/event-queue/src/main/java/com/iluwatar/event/queue/App.java +++ b/event-queue/src/main/java/com/iluwatar/event/queue/App.java @@ -47,11 +47,11 @@ public class App { * Program entry point. * * @param args command line args - * @throws IOException when there is a problem with the audio file loading + * @throws IOException when there is a problem with the audio file loading * @throws UnsupportedAudioFileException when the loaded audio file is unsupported */ - public static void main(String[] args) throws UnsupportedAudioFileException, IOException, - InterruptedException { + public static void main(String[] args) + throws UnsupportedAudioFileException, IOException, InterruptedException { var audio = Audio.getInstance(); audio.playSound(audio.getAudioStream("./etc/Bass-Drum-1.wav"), -10.0f); audio.playSound(audio.getAudioStream("./etc/Closed-Hi-Hat-1.wav"), -8.0f); diff --git a/event-queue/src/main/java/com/iluwatar/event/queue/Audio.java b/event-queue/src/main/java/com/iluwatar/event/queue/Audio.java index e18322947..02bee71b8 100644 --- a/event-queue/src/main/java/com/iluwatar/event/queue/Audio.java +++ b/event-queue/src/main/java/com/iluwatar/event/queue/Audio.java @@ -33,10 +33,7 @@ import javax.sound.sampled.UnsupportedAudioFileException; import lombok.Getter; import lombok.extern.slf4j.Slf4j; -/** - * This class implements the Event Queue pattern. - * - */ +/** This class implements the Event Queue pattern. */ @Slf4j public class Audio { private static final Audio INSTANCE = new Audio(); @@ -49,21 +46,16 @@ public class Audio { private volatile Thread updateThread = null; - @Getter - private final PlayMessage[] pendingAudio = new PlayMessage[MAX_PENDING]; + @Getter private final PlayMessage[] pendingAudio = new PlayMessage[MAX_PENDING]; // Visible only for testing purposes - Audio() { - - } + Audio() {} public static Audio getInstance() { return INSTANCE; } - /** - * This method stops the Update Method's thread and waits till service stops. - */ + /** This method stops the Update Method's thread and waits till service stops. */ public synchronized void stopService() throws InterruptedException { if (updateThread != null) { updateThread.interrupt(); @@ -82,23 +74,23 @@ public class Audio { } /** - * Starts the thread for the Update Method pattern if it was not started previously. Also, when the - * thread is ready initializes the indexes of the queue + * Starts the thread for the Update Method pattern if it was not started previously. Also, when + * the thread is ready initializes the indexes of the queue */ public void init() { if (updateThread == null) { - updateThread = new Thread(() -> { - while (!Thread.currentThread().isInterrupted()) { - update(); - } - }); + updateThread = + new Thread( + () -> { + while (!Thread.currentThread().isInterrupted()) { + update(); + } + }); } startThread(); } - /** - * This is a synchronized thread starter. - */ + /** This is a synchronized thread starter. */ private synchronized void startThread() { if (!updateThread.isAlive()) { updateThread.start(); @@ -130,9 +122,7 @@ public class Audio { tailIndex = (tailIndex + 1) % MAX_PENDING; } - /** - * This method uses the Update Method pattern. It takes the audio from the queue and plays it - */ + /** This method uses the Update Method pattern. It takes the audio from the queue and plays it */ private void update() { // If there are no pending requests, do nothing. if (headIndex == tailIndex) { @@ -159,7 +149,7 @@ public class Audio { * @param filePath is the path of the audio file * @return AudioInputStream * @throws UnsupportedAudioFileException when the audio file is not supported - * @throws IOException when the file is not readable + * @throws IOException when the file is not readable */ public AudioInputStream getAudioStream(String filePath) throws UnsupportedAudioFileException, IOException { diff --git a/event-queue/src/main/java/com/iluwatar/event/queue/PlayMessage.java b/event-queue/src/main/java/com/iluwatar/event/queue/PlayMessage.java index 0769ee36d..60f328d79 100644 --- a/event-queue/src/main/java/com/iluwatar/event/queue/PlayMessage.java +++ b/event-queue/src/main/java/com/iluwatar/event/queue/PlayMessage.java @@ -29,17 +29,12 @@ import lombok.AllArgsConstructor; import lombok.Getter; import lombok.Setter; -/** - * The Event Queue's queue will store the instances of this class. - * - */ +/** The Event Queue's queue will store the instances of this class. */ @Getter @AllArgsConstructor public class PlayMessage { private final AudioInputStream stream; - @Setter - private float volume; - + @Setter private float volume; } diff --git a/event-queue/src/test/java/com/iluwatar/event/queue/AudioTest.java b/event-queue/src/test/java/com/iluwatar/event/queue/AudioTest.java index 5112be9da..4f2abbdac 100644 --- a/event-queue/src/test/java/com/iluwatar/event/queue/AudioTest.java +++ b/event-queue/src/test/java/com/iluwatar/event/queue/AudioTest.java @@ -32,11 +32,7 @@ import javax.sound.sampled.UnsupportedAudioFileException; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; - -/** - * Testing the Audio service of the Queue - * - */ +/** Testing the Audio service of the Queue */ class AudioTest { private Audio audio; @@ -48,7 +44,8 @@ class AudioTest { /** * Test here that the playSound method works correctly - * @throws UnsupportedAudioFileException when the audio file is not supported + * + * @throws UnsupportedAudioFileException when the audio file is not supported * @throws IOException when the file is not readable * @throws InterruptedException when the test is interrupted externally */ @@ -67,7 +64,8 @@ class AudioTest { /** * Test here that the Queue - * @throws UnsupportedAudioFileException when the audio file is not supported + * + * @throws UnsupportedAudioFileException when the audio file is not supported * @throws IOException when the file is not readable * @throws InterruptedException when the test is interrupted externally */ @@ -86,5 +84,4 @@ class AudioTest { // test that service is finished assertFalse(audio.isServiceRunning()); } - } diff --git a/event-sourcing/pom.xml b/event-sourcing/pom.xml index b42952070..72d257df3 100644 --- a/event-sourcing/pom.xml +++ b/event-sourcing/pom.xml @@ -34,6 +34,14 @@ event-sourcing + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/event-sourcing/src/main/java/com/iluwatar/event/sourcing/app/App.java b/event-sourcing/src/main/java/com/iluwatar/event/sourcing/app/App.java index 20c4151b5..a625e9ace 100644 --- a/event-sourcing/src/main/java/com/iluwatar/event/sourcing/app/App.java +++ b/event-sourcing/src/main/java/com/iluwatar/event/sourcing/app/App.java @@ -53,13 +53,10 @@ import lombok.extern.slf4j.Slf4j; @Slf4j public class App { - /** - * The constant ACCOUNT OF DAENERYS. - */ + /** The constant ACCOUNT OF DAENERYS. */ public static final int ACCOUNT_OF_DAENERYS = 1; - /** - * The constant ACCOUNT OF JON. - */ + + /** The constant ACCOUNT OF JON. */ public static final int ACCOUNT_OF_JON = 2; /** @@ -76,23 +73,24 @@ public class App { LOGGER.info("Creating the accounts............"); - eventProcessor.process(new AccountCreateEvent( - 0, new Date().getTime(), ACCOUNT_OF_DAENERYS, "Daenerys Targaryen")); + eventProcessor.process( + new AccountCreateEvent(0, new Date().getTime(), ACCOUNT_OF_DAENERYS, "Daenerys Targaryen")); - eventProcessor.process(new AccountCreateEvent( - 1, new Date().getTime(), ACCOUNT_OF_JON, "Jon Snow")); + eventProcessor.process( + new AccountCreateEvent(1, new Date().getTime(), ACCOUNT_OF_JON, "Jon Snow")); LOGGER.info("Do some money operations............"); - eventProcessor.process(new MoneyDepositEvent( - 2, new Date().getTime(), ACCOUNT_OF_DAENERYS, new BigDecimal("100000"))); + eventProcessor.process( + new MoneyDepositEvent( + 2, new Date().getTime(), ACCOUNT_OF_DAENERYS, new BigDecimal("100000"))); - eventProcessor.process(new MoneyDepositEvent( - 3, new Date().getTime(), ACCOUNT_OF_JON, new BigDecimal("100"))); + eventProcessor.process( + new MoneyDepositEvent(3, new Date().getTime(), ACCOUNT_OF_JON, new BigDecimal("100"))); - eventProcessor.process(new MoneyTransferEvent( - 4, new Date().getTime(), new BigDecimal("10000"), ACCOUNT_OF_DAENERYS, - ACCOUNT_OF_JON)); + eventProcessor.process( + new MoneyTransferEvent( + 4, new Date().getTime(), new BigDecimal("10000"), ACCOUNT_OF_DAENERYS, ACCOUNT_OF_JON)); LOGGER.info("...............State:............"); LOGGER.info(AccountAggregate.getAccount(ACCOUNT_OF_DAENERYS).toString()); diff --git a/event-sourcing/src/main/java/com/iluwatar/event/sourcing/domain/Account.java b/event-sourcing/src/main/java/com/iluwatar/event/sourcing/domain/Account.java index 177348be8..89f4219d7 100644 --- a/event-sourcing/src/main/java/com/iluwatar/event/sourcing/domain/Account.java +++ b/event-sourcing/src/main/java/com/iluwatar/event/sourcing/domain/Account.java @@ -68,9 +68,13 @@ public class Account { @Override public String toString() { return "Account{" - + "accountNo=" + accountNo - + ", owner='" + owner + '\'' - + ", money=" + money + + "accountNo=" + + accountNo + + ", owner='" + + owner + + '\'' + + ", money=" + + money + '}'; } @@ -111,7 +115,6 @@ public class Account { handleDeposit(moneyDepositEvent.getMoney(), moneyDepositEvent.isRealTime()); } - /** * Handles the AccountCreateEvent. * @@ -141,6 +144,4 @@ public class Account { public void handleTransferToEvent(MoneyTransferEvent moneyTransferEvent) { handleDeposit(moneyTransferEvent.getMoney(), moneyTransferEvent.isRealTime()); } - - } diff --git a/event-sourcing/src/main/java/com/iluwatar/event/sourcing/event/AccountCreateEvent.java b/event-sourcing/src/main/java/com/iluwatar/event/sourcing/event/AccountCreateEvent.java index f3f4e78e6..087752cbf 100644 --- a/event-sourcing/src/main/java/com/iluwatar/event/sourcing/event/AccountCreateEvent.java +++ b/event-sourcing/src/main/java/com/iluwatar/event/sourcing/event/AccountCreateEvent.java @@ -46,15 +46,17 @@ public class AccountCreateEvent extends DomainEvent { /** * Instantiates a new Account created event. * - * @param sequenceId the sequence id + * @param sequenceId the sequence id * @param createdTime the created time - * @param accountNo the account no - * @param owner the owner + * @param accountNo the account no + * @param owner the owner */ @JsonCreator - public AccountCreateEvent(@JsonProperty("sequenceId") long sequenceId, + public AccountCreateEvent( + @JsonProperty("sequenceId") long sequenceId, @JsonProperty("createdTime") long createdTime, - @JsonProperty("accountNo") int accountNo, @JsonProperty("owner") String owner) { + @JsonProperty("accountNo") int accountNo, + @JsonProperty("owner") String owner) { super(sequenceId, createdTime, "AccountCreateEvent"); this.accountNo = accountNo; this.owner = owner; diff --git a/event-sourcing/src/main/java/com/iluwatar/event/sourcing/event/DomainEvent.java b/event-sourcing/src/main/java/com/iluwatar/event/sourcing/event/DomainEvent.java index 139ddd576..f39ebda43 100644 --- a/event-sourcing/src/main/java/com/iluwatar/event/sourcing/event/DomainEvent.java +++ b/event-sourcing/src/main/java/com/iluwatar/event/sourcing/event/DomainEvent.java @@ -44,9 +44,6 @@ public abstract class DomainEvent implements Serializable { private final String eventClassName; private boolean realTime = true; - /** - * Process. - */ + /** Process. */ public abstract void process(); - } diff --git a/event-sourcing/src/main/java/com/iluwatar/event/sourcing/event/MoneyDepositEvent.java b/event-sourcing/src/main/java/com/iluwatar/event/sourcing/event/MoneyDepositEvent.java index 07e88bc0e..4f80ec6b6 100644 --- a/event-sourcing/src/main/java/com/iluwatar/event/sourcing/event/MoneyDepositEvent.java +++ b/event-sourcing/src/main/java/com/iluwatar/event/sourcing/event/MoneyDepositEvent.java @@ -47,15 +47,17 @@ public class MoneyDepositEvent extends DomainEvent { /** * Instantiates a new Money deposit event. * - * @param sequenceId the sequence id + * @param sequenceId the sequence id * @param createdTime the created time - * @param accountNo the account no - * @param money the money + * @param accountNo the account no + * @param money the money */ @JsonCreator - public MoneyDepositEvent(@JsonProperty("sequenceId") long sequenceId, + public MoneyDepositEvent( + @JsonProperty("sequenceId") long sequenceId, @JsonProperty("createdTime") long createdTime, - @JsonProperty("accountNo") int accountNo, @JsonProperty("money") BigDecimal money) { + @JsonProperty("accountNo") int accountNo, + @JsonProperty("money") BigDecimal money) { super(sequenceId, createdTime, "MoneyDepositEvent"); this.money = money; this.accountNo = accountNo; @@ -63,8 +65,9 @@ public class MoneyDepositEvent extends DomainEvent { @Override public void process() { - var account = Optional.ofNullable(AccountAggregate.getAccount(accountNo)) - .orElseThrow(() -> new RuntimeException("Account not found")); + var account = + Optional.ofNullable(AccountAggregate.getAccount(accountNo)) + .orElseThrow(() -> new RuntimeException("Account not found")); account.handleEvent(this); } } diff --git a/event-sourcing/src/main/java/com/iluwatar/event/sourcing/event/MoneyTransferEvent.java b/event-sourcing/src/main/java/com/iluwatar/event/sourcing/event/MoneyTransferEvent.java index 3b4fa1ed1..e6e257dde 100644 --- a/event-sourcing/src/main/java/com/iluwatar/event/sourcing/event/MoneyTransferEvent.java +++ b/event-sourcing/src/main/java/com/iluwatar/event/sourcing/event/MoneyTransferEvent.java @@ -48,16 +48,18 @@ public class MoneyTransferEvent extends DomainEvent { /** * Instantiates a new Money transfer event. * - * @param sequenceId the sequence id - * @param createdTime the created time - * @param money the money + * @param sequenceId the sequence id + * @param createdTime the created time + * @param money the money * @param accountNoFrom the account no from - * @param accountNoTo the account no to + * @param accountNoTo the account no to */ @JsonCreator - public MoneyTransferEvent(@JsonProperty("sequenceId") long sequenceId, + public MoneyTransferEvent( + @JsonProperty("sequenceId") long sequenceId, @JsonProperty("createdTime") long createdTime, - @JsonProperty("money") BigDecimal money, @JsonProperty("accountNoFrom") int accountNoFrom, + @JsonProperty("money") BigDecimal money, + @JsonProperty("accountNoFrom") int accountNoFrom, @JsonProperty("accountNoTo") int accountNoTo) { super(sequenceId, createdTime, "MoneyTransferEvent"); this.money = money; @@ -67,10 +69,12 @@ public class MoneyTransferEvent extends DomainEvent { @Override public void process() { - var accountFrom = Optional.ofNullable(AccountAggregate.getAccount(accountNoFrom)) - .orElseThrow(() -> new RuntimeException("Account not found " + accountNoFrom)); - var accountTo = Optional.ofNullable(AccountAggregate.getAccount(accountNoTo)) - .orElseThrow(() -> new RuntimeException("Account not found " + accountNoTo)); + var accountFrom = + Optional.ofNullable(AccountAggregate.getAccount(accountNoFrom)) + .orElseThrow(() -> new RuntimeException("Account not found " + accountNoFrom)); + var accountTo = + Optional.ofNullable(AccountAggregate.getAccount(accountNoTo)) + .orElseThrow(() -> new RuntimeException("Account not found " + accountNoTo)); accountFrom.handleTransferFromEvent(this); accountTo.handleTransferToEvent(this); } diff --git a/event-sourcing/src/main/java/com/iluwatar/event/sourcing/processor/DomainEventProcessor.java b/event-sourcing/src/main/java/com/iluwatar/event/sourcing/processor/DomainEventProcessor.java index cdfe44e33..6b0658b40 100644 --- a/event-sourcing/src/main/java/com/iluwatar/event/sourcing/processor/DomainEventProcessor.java +++ b/event-sourcing/src/main/java/com/iluwatar/event/sourcing/processor/DomainEventProcessor.java @@ -50,16 +50,12 @@ public class DomainEventProcessor { eventJournal.write(domainEvent); } - /** - * Reset. - */ + /** Reset. */ public void reset() { eventJournal.reset(); } - /** - * Recover. - */ + /** Recover. */ public void recover() { DomainEvent domainEvent; while ((domainEvent = eventJournal.readNext()) != null) { diff --git a/event-sourcing/src/main/java/com/iluwatar/event/sourcing/processor/EventJournal.java b/event-sourcing/src/main/java/com/iluwatar/event/sourcing/processor/EventJournal.java index 5c78da1d8..3b4cdfd3e 100644 --- a/event-sourcing/src/main/java/com/iluwatar/event/sourcing/processor/EventJournal.java +++ b/event-sourcing/src/main/java/com/iluwatar/event/sourcing/processor/EventJournal.java @@ -28,9 +28,7 @@ import com.iluwatar.event.sourcing.event.DomainEvent; import java.io.File; import lombok.extern.slf4j.Slf4j; -/** - * Base class for Journaling implementations. - */ +/** Base class for Journaling implementations. */ @Slf4j public abstract class EventJournal { @@ -43,9 +41,7 @@ public abstract class EventJournal { */ abstract void write(DomainEvent domainEvent); - /** - * Reset. - */ + /** Reset. */ void reset() { if (file.delete()) { LOGGER.info("File cleared successfully............"); diff --git a/event-sourcing/src/main/java/com/iluwatar/event/sourcing/processor/JsonFileJournal.java b/event-sourcing/src/main/java/com/iluwatar/event/sourcing/processor/JsonFileJournal.java index cfde566dc..106dbf95e 100644 --- a/event-sourcing/src/main/java/com/iluwatar/event/sourcing/processor/JsonFileJournal.java +++ b/event-sourcing/src/main/java/com/iluwatar/event/sourcing/processor/JsonFileJournal.java @@ -53,14 +53,13 @@ public class JsonFileJournal extends EventJournal { private final List events = new ArrayList<>(); private int index = 0; - /** - * Instantiates a new Json file journal. - */ + /** Instantiates a new Json file journal. */ public JsonFileJournal() { file = new File("Journal.json"); if (file.exists()) { - try (var input = new BufferedReader( - new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8))) { + try (var input = + new BufferedReader( + new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8))) { String line; while ((line = input.readLine()) != null) { events.add(line); @@ -73,7 +72,6 @@ public class JsonFileJournal extends EventJournal { } } - /** * Write. * @@ -82,8 +80,9 @@ public class JsonFileJournal extends EventJournal { @Override public void write(DomainEvent domainEvent) { var mapper = new ObjectMapper(); - try (var output = new BufferedWriter( - new OutputStreamWriter(new FileOutputStream(file, true), StandardCharsets.UTF_8))) { + try (var output = + new BufferedWriter( + new OutputStreamWriter(new FileOutputStream(file, true), StandardCharsets.UTF_8))) { var eventString = mapper.writeValueAsString(domainEvent); output.write(eventString + "\r\n"); } catch (IOException e) { @@ -91,7 +90,6 @@ public class JsonFileJournal extends EventJournal { } } - /** * Read the next domain event. * @@ -109,12 +107,13 @@ public class JsonFileJournal extends EventJournal { try { var jsonElement = mapper.readTree(event); var eventClassName = jsonElement.get("eventClassName").asText(); - domainEvent = switch (eventClassName) { - case "AccountCreateEvent" -> mapper.treeToValue(jsonElement, AccountCreateEvent.class); - case "MoneyDepositEvent" -> mapper.treeToValue(jsonElement, MoneyDepositEvent.class); - case "MoneyTransferEvent" -> mapper.treeToValue(jsonElement, MoneyTransferEvent.class); - default -> throw new RuntimeException("Journal Event not recognized"); - }; + domainEvent = + switch (eventClassName) { + case "AccountCreateEvent" -> mapper.treeToValue(jsonElement, AccountCreateEvent.class); + case "MoneyDepositEvent" -> mapper.treeToValue(jsonElement, MoneyDepositEvent.class); + case "MoneyTransferEvent" -> mapper.treeToValue(jsonElement, MoneyTransferEvent.class); + default -> throw new RuntimeException("Journal Event not recognized"); + }; } catch (JsonProcessingException jsonProcessingException) { throw new RuntimeException("Failed to convert JSON"); } diff --git a/event-sourcing/src/main/java/com/iluwatar/event/sourcing/state/AccountAggregate.java b/event-sourcing/src/main/java/com/iluwatar/event/sourcing/state/AccountAggregate.java index 4948fcd30..80253036f 100644 --- a/event-sourcing/src/main/java/com/iluwatar/event/sourcing/state/AccountAggregate.java +++ b/event-sourcing/src/main/java/com/iluwatar/event/sourcing/state/AccountAggregate.java @@ -38,8 +38,7 @@ public class AccountAggregate { private static Map accounts = new HashMap<>(); - private AccountAggregate() { - } + private AccountAggregate() {} /** * Put account. @@ -57,15 +56,10 @@ public class AccountAggregate { * @return the copy of the account or null if not found */ public static Account getAccount(int accountNo) { - return Optional.of(accountNo) - .map(accounts::get) - .map(Account::copy) - .orElse(null); + return Optional.of(accountNo).map(accounts::get).map(Account::copy).orElse(null); } - /** - * Reset state. - */ + /** Reset state. */ public static void resetState() { accounts = new HashMap<>(); } diff --git a/event-sourcing/src/test/java/IntegrationTest.java b/event-sourcing/src/test/java/IntegrationTest.java index c737bd0da..89c7a77fe 100644 --- a/event-sourcing/src/test/java/IntegrationTest.java +++ b/event-sourcing/src/test/java/IntegrationTest.java @@ -40,46 +40,41 @@ import org.junit.jupiter.api.Test; /** * Integration Test for Event-Sourcing state recovery - *

- * Created by Serdar Hamzaogullari on 19.08.2017. + * + *

Created by Serdar Hamzaogullari on 19.08.2017. */ class IntegrationTest { - /** - * The Domain event processor. - */ + /** The Domain event processor. */ private DomainEventProcessor eventProcessor; - /** - * Initialize. - */ + /** Initialize. */ @BeforeEach void initialize() { eventProcessor = new DomainEventProcessor(new JsonFileJournal()); } - /** - * Test state recovery. - */ + /** Test state recovery. */ @Test void testStateRecovery() { eventProcessor.reset(); - eventProcessor.process(new AccountCreateEvent( - 0, new Date().getTime(), ACCOUNT_OF_DAENERYS, "Daenerys Targaryen")); + eventProcessor.process( + new AccountCreateEvent(0, new Date().getTime(), ACCOUNT_OF_DAENERYS, "Daenerys Targaryen")); - eventProcessor.process(new AccountCreateEvent( - 1, new Date().getTime(), ACCOUNT_OF_JON, "Jon Snow")); + eventProcessor.process( + new AccountCreateEvent(1, new Date().getTime(), ACCOUNT_OF_JON, "Jon Snow")); - eventProcessor.process(new MoneyDepositEvent( - 2, new Date().getTime(), ACCOUNT_OF_DAENERYS, new BigDecimal("100000"))); + eventProcessor.process( + new MoneyDepositEvent( + 2, new Date().getTime(), ACCOUNT_OF_DAENERYS, new BigDecimal("100000"))); - eventProcessor.process(new MoneyDepositEvent( - 3, new Date().getTime(), ACCOUNT_OF_JON, new BigDecimal("100"))); + eventProcessor.process( + new MoneyDepositEvent(3, new Date().getTime(), ACCOUNT_OF_JON, new BigDecimal("100"))); - eventProcessor.process(new MoneyTransferEvent( - 4, new Date().getTime(), new BigDecimal("10000"), ACCOUNT_OF_DAENERYS, - ACCOUNT_OF_JON)); + eventProcessor.process( + new MoneyTransferEvent( + 4, new Date().getTime(), new BigDecimal("10000"), ACCOUNT_OF_DAENERYS, ACCOUNT_OF_JON)); var accountOfDaenerysBeforeShotDown = AccountAggregate.getAccount(ACCOUNT_OF_DAENERYS); var accountOfJonBeforeShotDown = AccountAggregate.getAccount(ACCOUNT_OF_JON); @@ -92,9 +87,8 @@ class IntegrationTest { var accountOfDaenerysAfterShotDown = AccountAggregate.getAccount(ACCOUNT_OF_DAENERYS); var accountOfJonAfterShotDown = AccountAggregate.getAccount(ACCOUNT_OF_JON); - assertEquals(accountOfDaenerysBeforeShotDown.getMoney(), - accountOfDaenerysAfterShotDown.getMoney()); + assertEquals( + accountOfDaenerysBeforeShotDown.getMoney(), accountOfDaenerysAfterShotDown.getMoney()); assertEquals(accountOfJonBeforeShotDown.getMoney(), accountOfJonAfterShotDown.getMoney()); } - } diff --git a/execute-around/pom.xml b/execute-around/pom.xml index d5e01d31c..2ed0d0858 100644 --- a/execute-around/pom.xml +++ b/execute-around/pom.xml @@ -34,6 +34,14 @@ execute-around + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine @@ -42,6 +50,7 @@ org.junit.jupiter junit-jupiter-migrationsupport + 5.11.4 test diff --git a/execute-around/src/main/java/com/iluwatar/execute/around/App.java b/execute-around/src/main/java/com/iluwatar/execute/around/App.java index 9291fd0ea..9dc88fbfd 100644 --- a/execute-around/src/main/java/com/iluwatar/execute/around/App.java +++ b/execute-around/src/main/java/com/iluwatar/execute/around/App.java @@ -30,20 +30,18 @@ import java.util.Scanner; import lombok.extern.slf4j.Slf4j; /** - * The Execute Around idiom specifies executable code before and after a method. Typically, - * the idiom is used when the API has methods to be executed in pairs, such as resource + * The Execute Around idiom specifies executable code before and after a method. Typically, the + * idiom is used when the API has methods to be executed in pairs, such as resource * allocation/deallocation or lock acquisition/release. * - *

In this example, we have {@link SimpleFileWriter} class that opens and closes the file for - * the user. The user specifies only what to do with the file by providing the {@link - * FileWriterAction} implementation. + *

In this example, we have {@link SimpleFileWriter} class that opens and closes the file for the + * user. The user specifies only what to do with the file by providing the {@link FileWriterAction} + * implementation. */ @Slf4j public class App { - /** - * Program entry point. - */ + /** Program entry point. */ public static void main(String[] args) throws IOException { // create the file writer and execute the custom action diff --git a/execute-around/src/main/java/com/iluwatar/execute/around/FileWriterAction.java b/execute-around/src/main/java/com/iluwatar/execute/around/FileWriterAction.java index 5585bc4fa..0627177a3 100644 --- a/execute-around/src/main/java/com/iluwatar/execute/around/FileWriterAction.java +++ b/execute-around/src/main/java/com/iluwatar/execute/around/FileWriterAction.java @@ -27,12 +27,9 @@ package com.iluwatar.execute.around; import java.io.FileWriter; import java.io.IOException; -/** - * Interface for specifying what to do with the file resource. - */ +/** Interface for specifying what to do with the file resource. */ @FunctionalInterface public interface FileWriterAction { void writeFile(FileWriter writer) throws IOException; - } diff --git a/execute-around/src/main/java/com/iluwatar/execute/around/SimpleFileWriter.java b/execute-around/src/main/java/com/iluwatar/execute/around/SimpleFileWriter.java index 66c844aa4..d3bd54d4e 100644 --- a/execute-around/src/main/java/com/iluwatar/execute/around/SimpleFileWriter.java +++ b/execute-around/src/main/java/com/iluwatar/execute/around/SimpleFileWriter.java @@ -35,9 +35,7 @@ import lombok.extern.slf4j.Slf4j; @Slf4j public class SimpleFileWriter { - /** - * Constructor. - */ + /** Constructor. */ public SimpleFileWriter(String filename, FileWriterAction action) throws IOException { LOGGER.info("Opening the file"); try (var writer = new FileWriter(filename)) { diff --git a/execute-around/src/test/java/com/iluwatar/execute/around/AppTest.java b/execute-around/src/test/java/com/iluwatar/execute/around/AppTest.java index 8df0c9939..1e06beb12 100644 --- a/execute-around/src/test/java/com/iluwatar/execute/around/AppTest.java +++ b/execute-around/src/test/java/com/iluwatar/execute/around/AppTest.java @@ -31,14 +31,12 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -/** - * Tests execute-around example. - */ +/** Tests execute-around example. */ class AppTest { @Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } @BeforeEach diff --git a/execute-around/src/test/java/com/iluwatar/execute/around/SimpleFileWriterTest.java b/execute-around/src/test/java/com/iluwatar/execute/around/SimpleFileWriterTest.java index 6c0dfcd54..60c4ecb6b 100644 --- a/execute-around/src/test/java/com/iluwatar/execute/around/SimpleFileWriterTest.java +++ b/execute-around/src/test/java/com/iluwatar/execute/around/SimpleFileWriterTest.java @@ -38,15 +38,11 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.migrationsupport.rules.EnableRuleMigrationSupport; import org.junit.rules.TemporaryFolder; -/** - * SimpleFileWriterTest - * - */ +/** SimpleFileWriterTest */ @EnableRuleMigrationSupport class SimpleFileWriterTest { - @Rule - public final TemporaryFolder testFolder = new TemporaryFolder(); + @Rule public final TemporaryFolder testFolder = new TemporaryFolder(); @Test void testWriterNotNull() throws Exception { @@ -74,12 +70,19 @@ class SimpleFileWriterTest { assertTrue(Files.lines(temporaryFile.toPath()).allMatch(testMessage::equals)); } - @Test @SneakyThrows void testRipplesIoExceptionOccurredWhileWriting() { var message = "Some error"; final var temporaryFile = this.testFolder.newFile(); - assertThrows(IOException.class, () -> new SimpleFileWriter(temporaryFile.getPath(), writer -> {throw new IOException("error");}), message); + assertThrows( + IOException.class, + () -> + new SimpleFileWriter( + temporaryFile.getPath(), + writer -> { + throw new IOException("error"); + }), + message); } -} \ No newline at end of file +} diff --git a/extension-objects/pom.xml b/extension-objects/pom.xml index 4e3d1e981..92297162f 100644 --- a/extension-objects/pom.xml +++ b/extension-objects/pom.xml @@ -34,6 +34,14 @@ 4.0.0 extension-objects + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/extension-objects/src/main/java/App.java b/extension-objects/src/main/java/App.java index dd67b2e1e..db48032f1 100644 --- a/extension-objects/src/main/java/App.java +++ b/extension-objects/src/main/java/App.java @@ -46,16 +46,15 @@ public class App { */ public static void main(String[] args) { - //Create 3 different units + // Create 3 different units var soldierUnit = new SoldierUnit("SoldierUnit1"); var sergeantUnit = new SergeantUnit("SergeantUnit1"); var commanderUnit = new CommanderUnit("CommanderUnit1"); - //check for each unit to have an extension + // check for each unit to have an extension checkExtensionsForUnit(soldierUnit); checkExtensionsForUnit(sergeantUnit); checkExtensionsForUnit(commanderUnit); - } private static void checkExtensionsForUnit(Unit unit) { diff --git a/extension-objects/src/main/java/abstractextensions/CommanderExtension.java b/extension-objects/src/main/java/abstractextensions/CommanderExtension.java index d366069b1..bcad9db94 100644 --- a/extension-objects/src/main/java/abstractextensions/CommanderExtension.java +++ b/extension-objects/src/main/java/abstractextensions/CommanderExtension.java @@ -24,9 +24,7 @@ */ package abstractextensions; -/** - * Interface with their method. - */ +/** Interface with their method. */ public interface CommanderExtension extends UnitExtension { void commanderReady(); diff --git a/extension-objects/src/main/java/abstractextensions/SergeantExtension.java b/extension-objects/src/main/java/abstractextensions/SergeantExtension.java index 0cb04dc70..7eea21d0c 100644 --- a/extension-objects/src/main/java/abstractextensions/SergeantExtension.java +++ b/extension-objects/src/main/java/abstractextensions/SergeantExtension.java @@ -24,9 +24,7 @@ */ package abstractextensions; -/** - * Interface with their method. - */ +/** Interface with their method. */ public interface SergeantExtension extends UnitExtension { void sergeantReady(); diff --git a/extension-objects/src/main/java/abstractextensions/SoldierExtension.java b/extension-objects/src/main/java/abstractextensions/SoldierExtension.java index 98e182de3..579e3c1d0 100644 --- a/extension-objects/src/main/java/abstractextensions/SoldierExtension.java +++ b/extension-objects/src/main/java/abstractextensions/SoldierExtension.java @@ -24,9 +24,7 @@ */ package abstractextensions; -/** - * Interface with their method. - */ +/** Interface with their method. */ public interface SoldierExtension extends UnitExtension { void soldierReady(); } diff --git a/extension-objects/src/main/java/abstractextensions/UnitExtension.java b/extension-objects/src/main/java/abstractextensions/UnitExtension.java index 8a82f0f0b..d79868d54 100644 --- a/extension-objects/src/main/java/abstractextensions/UnitExtension.java +++ b/extension-objects/src/main/java/abstractextensions/UnitExtension.java @@ -24,8 +24,5 @@ */ package abstractextensions; -/** - * Other Extensions will extend this interface. - */ -public interface UnitExtension { -} +/** Other Extensions will extend this interface. */ +public interface UnitExtension {} diff --git a/extension-objects/src/main/java/concreteextensions/Commander.java b/extension-objects/src/main/java/concreteextensions/Commander.java index a2ffff941..0716d2e9b 100644 --- a/extension-objects/src/main/java/concreteextensions/Commander.java +++ b/extension-objects/src/main/java/concreteextensions/Commander.java @@ -25,14 +25,10 @@ package concreteextensions; import abstractextensions.CommanderExtension; -import lombok.Getter; -import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import units.CommanderUnit; -/** - * Class defining Commander. - */ +/** Class defining Commander. */ @Slf4j public record Commander(CommanderUnit unit) implements CommanderExtension { @@ -40,5 +36,4 @@ public record Commander(CommanderUnit unit) implements CommanderExtension { public void commanderReady() { LOGGER.info("[Commander] " + unit.getName() + " is ready!"); } - } diff --git a/extension-objects/src/main/java/concreteextensions/Sergeant.java b/extension-objects/src/main/java/concreteextensions/Sergeant.java index 716bd4a1a..fb8f815c8 100644 --- a/extension-objects/src/main/java/concreteextensions/Sergeant.java +++ b/extension-objects/src/main/java/concreteextensions/Sergeant.java @@ -25,14 +25,10 @@ package concreteextensions; import abstractextensions.SergeantExtension; -import lombok.Getter; -import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import units.SergeantUnit; -/** - * Class defining Sergeant. - */ +/** Class defining Sergeant. */ @Slf4j public record Sergeant(SergeantUnit unit) implements SergeantExtension { @@ -40,5 +36,4 @@ public record Sergeant(SergeantUnit unit) implements SergeantExtension { public void sergeantReady() { LOGGER.info("[Sergeant] " + unit.getName() + " is ready!"); } - } diff --git a/extension-objects/src/main/java/concreteextensions/Soldier.java b/extension-objects/src/main/java/concreteextensions/Soldier.java index cbd5d2a1a..dd2338a53 100644 --- a/extension-objects/src/main/java/concreteextensions/Soldier.java +++ b/extension-objects/src/main/java/concreteextensions/Soldier.java @@ -25,14 +25,10 @@ package concreteextensions; import abstractextensions.SoldierExtension; -import lombok.Getter; -import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import units.SoldierUnit; -/** - * Class defining Soldier. - */ +/** Class defining Soldier. */ @Slf4j public record Soldier(SoldierUnit unit) implements SoldierExtension { @@ -40,5 +36,4 @@ public record Soldier(SoldierUnit unit) implements SoldierExtension { public void soldierReady() { LOGGER.info("[Soldier] " + unit.getName() + " is ready!"); } - } diff --git a/extension-objects/src/main/java/units/CommanderUnit.java b/extension-objects/src/main/java/units/CommanderUnit.java index cf62aaec8..94e92807f 100644 --- a/extension-objects/src/main/java/units/CommanderUnit.java +++ b/extension-objects/src/main/java/units/CommanderUnit.java @@ -28,9 +28,7 @@ import abstractextensions.UnitExtension; import concreteextensions.Commander; import java.util.Optional; -/** - * Class defining CommanderUnit. - */ +/** Class defining CommanderUnit. */ public class CommanderUnit extends Unit { public CommanderUnit(String name) { diff --git a/extension-objects/src/main/java/units/SergeantUnit.java b/extension-objects/src/main/java/units/SergeantUnit.java index 7645a7495..ae882d929 100644 --- a/extension-objects/src/main/java/units/SergeantUnit.java +++ b/extension-objects/src/main/java/units/SergeantUnit.java @@ -28,9 +28,7 @@ import abstractextensions.UnitExtension; import concreteextensions.Sergeant; import java.util.Optional; -/** - * Class defining SergeantUnit. - */ +/** Class defining SergeantUnit. */ public class SergeantUnit extends Unit { public SergeantUnit(String name) { diff --git a/extension-objects/src/main/java/units/SoldierUnit.java b/extension-objects/src/main/java/units/SoldierUnit.java index e82e9fac4..b1db8930e 100644 --- a/extension-objects/src/main/java/units/SoldierUnit.java +++ b/extension-objects/src/main/java/units/SoldierUnit.java @@ -28,9 +28,7 @@ import abstractextensions.UnitExtension; import concreteextensions.Soldier; import java.util.Optional; -/** - * Class defining SoldierUnit. - */ +/** Class defining SoldierUnit. */ public class SoldierUnit extends Unit { public SoldierUnit(String name) { diff --git a/extension-objects/src/main/java/units/Unit.java b/extension-objects/src/main/java/units/Unit.java index 1bb3a8dac..195777182 100644 --- a/extension-objects/src/main/java/units/Unit.java +++ b/extension-objects/src/main/java/units/Unit.java @@ -28,9 +28,7 @@ import abstractextensions.UnitExtension; import lombok.Getter; import lombok.Setter; -/** - * Class defining Unit, other units will extend this class. - */ +/** Class defining Unit, other units will extend this class. */ @Setter @Getter public class Unit { diff --git a/extension-objects/src/test/java/AppTest.java b/extension-objects/src/test/java/AppTest.java index 92db1702a..c80e472b4 100644 --- a/extension-objects/src/test/java/AppTest.java +++ b/extension-objects/src/test/java/AppTest.java @@ -22,18 +22,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -/** - * Created by Srdjan on 03-May-17. - */ +import org.junit.jupiter.api.Test; + +/** Created by Srdjan on 03-May-17. */ class AppTest { @Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } - -} \ No newline at end of file +} diff --git a/extension-objects/src/test/java/concreteextensions/CommanderTest.java b/extension-objects/src/test/java/concreteextensions/CommanderTest.java index 74b668d5e..5271d7ea7 100644 --- a/extension-objects/src/test/java/concreteextensions/CommanderTest.java +++ b/extension-objects/src/test/java/concreteextensions/CommanderTest.java @@ -24,20 +24,18 @@ */ package concreteextensions; +import static org.junit.jupiter.api.Assertions.assertEquals; + import ch.qos.logback.classic.Level; import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.read.ListAppender; +import java.util.List; import org.junit.jupiter.api.Test; import org.slf4j.LoggerFactory; import units.CommanderUnit; -import java.util.List; -import static org.junit.jupiter.api.Assertions.assertEquals; - -/** - * CommanderTest - */ +/** CommanderTest */ class CommanderTest { @Test @@ -54,9 +52,8 @@ class CommanderTest { commander.commanderReady(); List logsList = listAppender.list; - assertEquals("[Commander] " + commander.unit().getName() + " is ready!", logsList.get(0) - .getMessage()); - assertEquals(Level.INFO, logsList.get(0) - .getLevel()); + assertEquals( + "[Commander] " + commander.unit().getName() + " is ready!", logsList.get(0).getMessage()); + assertEquals(Level.INFO, logsList.get(0).getLevel()); } } diff --git a/extension-objects/src/test/java/concreteextensions/SergeantTest.java b/extension-objects/src/test/java/concreteextensions/SergeantTest.java index 13f2f8812..83b2cb46d 100644 --- a/extension-objects/src/test/java/concreteextensions/SergeantTest.java +++ b/extension-objects/src/test/java/concreteextensions/SergeantTest.java @@ -24,20 +24,18 @@ */ package concreteextensions; +import static org.junit.jupiter.api.Assertions.assertEquals; + import ch.qos.logback.classic.Level; import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.read.ListAppender; +import java.util.List; import org.junit.jupiter.api.Test; import org.slf4j.LoggerFactory; import units.SergeantUnit; -import java.util.List; -import static org.junit.jupiter.api.Assertions.assertEquals; - -/** - * Created by Srdjan on 03-May-17. - */ +/** Created by Srdjan on 03-May-17. */ class SergeantTest { @Test @@ -54,10 +52,8 @@ class SergeantTest { sergeant.sergeantReady(); List logsList = listAppender.list; - assertEquals("[Sergeant] " + sergeant.unit().getName() + " is ready!", logsList.get(0) - .getMessage()); - assertEquals(Level.INFO, logsList.get(0) - .getLevel()); + assertEquals( + "[Sergeant] " + sergeant.unit().getName() + " is ready!", logsList.get(0).getMessage()); + assertEquals(Level.INFO, logsList.get(0).getLevel()); } - -} \ No newline at end of file +} diff --git a/extension-objects/src/test/java/concreteextensions/SoldierTest.java b/extension-objects/src/test/java/concreteextensions/SoldierTest.java index d5ebcca70..da3490c2b 100644 --- a/extension-objects/src/test/java/concreteextensions/SoldierTest.java +++ b/extension-objects/src/test/java/concreteextensions/SoldierTest.java @@ -24,21 +24,18 @@ */ package concreteextensions; +import static org.junit.jupiter.api.Assertions.assertEquals; + import ch.qos.logback.classic.Level; import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.read.ListAppender; +import java.util.List; import org.junit.jupiter.api.Test; import org.slf4j.LoggerFactory; import units.SoldierUnit; -import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -/** - * Created by Srdjan on 03-May-17. - */ +/** Created by Srdjan on 03-May-17. */ class SoldierTest { @Test @@ -55,10 +52,8 @@ class SoldierTest { soldier.soldierReady(); List logsList = listAppender.list; - assertEquals("[Soldier] " + soldier.unit().getName() + " is ready!", logsList.get(0) - .getMessage()); - assertEquals(Level.INFO, logsList.get(0) - .getLevel()); + assertEquals( + "[Soldier] " + soldier.unit().getName() + " is ready!", logsList.get(0).getMessage()); + assertEquals(Level.INFO, logsList.get(0).getLevel()); } - -} \ No newline at end of file +} diff --git a/extension-objects/src/test/java/units/CommanderUnitTest.java b/extension-objects/src/test/java/units/CommanderUnitTest.java index 52e343d5c..1b4793e66 100644 --- a/extension-objects/src/test/java/units/CommanderUnitTest.java +++ b/extension-objects/src/test/java/units/CommanderUnitTest.java @@ -29,9 +29,7 @@ import static org.junit.jupiter.api.Assertions.assertNull; import org.junit.jupiter.api.Test; -/** - * Created by Srdjan on 03-May-17. - */ +/** Created by Srdjan on 03-May-17. */ class CommanderUnitTest { @Test @@ -42,5 +40,4 @@ class CommanderUnitTest { assertNull(unit.getUnitExtension("SergeantExtension")); assertNotNull(unit.getUnitExtension("CommanderExtension")); } - -} \ No newline at end of file +} diff --git a/extension-objects/src/test/java/units/SergeantUnitTest.java b/extension-objects/src/test/java/units/SergeantUnitTest.java index 59255f3b8..b211483b1 100644 --- a/extension-objects/src/test/java/units/SergeantUnitTest.java +++ b/extension-objects/src/test/java/units/SergeantUnitTest.java @@ -29,9 +29,7 @@ import static org.junit.jupiter.api.Assertions.assertNull; import org.junit.jupiter.api.Test; -/** - * Created by Srdjan on 03-May-17. - */ +/** Created by Srdjan on 03-May-17. */ class SergeantUnitTest { @Test @@ -42,5 +40,4 @@ class SergeantUnitTest { assertNotNull(unit.getUnitExtension("SergeantExtension")); assertNull(unit.getUnitExtension("CommanderExtension")); } - -} \ No newline at end of file +} diff --git a/extension-objects/src/test/java/units/SoldierUnitTest.java b/extension-objects/src/test/java/units/SoldierUnitTest.java index c32e74117..4a3ff803e 100644 --- a/extension-objects/src/test/java/units/SoldierUnitTest.java +++ b/extension-objects/src/test/java/units/SoldierUnitTest.java @@ -29,9 +29,7 @@ import static org.junit.jupiter.api.Assertions.assertNull; import org.junit.jupiter.api.Test; -/** - * Created by Srdjan on 03-May-17. - */ +/** Created by Srdjan on 03-May-17. */ class SoldierUnitTest { @Test @@ -42,5 +40,4 @@ class SoldierUnitTest { assertNull(unit.getUnitExtension("SergeantExtension")); assertNull(unit.getUnitExtension("CommanderExtension")); } - -} \ No newline at end of file +} diff --git a/extension-objects/src/test/java/units/UnitTest.java b/extension-objects/src/test/java/units/UnitTest.java index 2ec0bcf52..9cd0d29d7 100644 --- a/extension-objects/src/test/java/units/UnitTest.java +++ b/extension-objects/src/test/java/units/UnitTest.java @@ -29,9 +29,7 @@ import static org.junit.jupiter.api.Assertions.assertNull; import org.junit.jupiter.api.Test; -/** - * Created by Srdjan on 03-May-17. - */ +/** Created by Srdjan on 03-May-17. */ class UnitTest { @Test @@ -44,11 +42,9 @@ class UnitTest { unit.setName(newName); assertEquals(newName, unit.getName()); - assertNull(unit.getUnitExtension("")); assertNull(unit.getUnitExtension("SoldierExtension")); assertNull(unit.getUnitExtension("SergeantExtension")); assertNull(unit.getUnitExtension("CommanderExtension")); } - -} \ No newline at end of file +} diff --git a/facade/pom.xml b/facade/pom.xml index c61e03e16..916a3b0c4 100644 --- a/facade/pom.xml +++ b/facade/pom.xml @@ -34,6 +34,14 @@ facade + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/facade/src/main/java/com/iluwatar/facade/DwarvenCartOperator.java b/facade/src/main/java/com/iluwatar/facade/DwarvenCartOperator.java index 82ec4ef3a..9b077b242 100644 --- a/facade/src/main/java/com/iluwatar/facade/DwarvenCartOperator.java +++ b/facade/src/main/java/com/iluwatar/facade/DwarvenCartOperator.java @@ -1,44 +1,42 @@ -/* - * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). - * - * The MIT License - * Copyright © 2014-2022 Ilkka Seppälä - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package com.iluwatar.facade; - -import lombok.extern.slf4j.Slf4j; - -/** - * DwarvenCartOperator is one of the goldmine subsystems. - */ -@Slf4j -public class DwarvenCartOperator extends DwarvenMineWorker { - - @Override - public void work() { - LOGGER.info("{} moves gold chunks out of the mine.", name()); - } - - @Override - public String name() { - return "Dwarf cart operator"; - } -} +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.facade; + +import lombok.extern.slf4j.Slf4j; + +/** DwarvenCartOperator is one of the goldmine subsystems. */ +@Slf4j +public class DwarvenCartOperator extends DwarvenMineWorker { + + @Override + public void work() { + LOGGER.info("{} moves gold chunks out of the mine.", name()); + } + + @Override + public String name() { + return "Dwarf cart operator"; + } +} diff --git a/facade/src/main/java/com/iluwatar/facade/DwarvenGoldDigger.java b/facade/src/main/java/com/iluwatar/facade/DwarvenGoldDigger.java index 2f95c015b..29cdc7424 100644 --- a/facade/src/main/java/com/iluwatar/facade/DwarvenGoldDigger.java +++ b/facade/src/main/java/com/iluwatar/facade/DwarvenGoldDigger.java @@ -1,44 +1,42 @@ -/* - * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). - * - * The MIT License - * Copyright © 2014-2022 Ilkka Seppälä - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package com.iluwatar.facade; - -import lombok.extern.slf4j.Slf4j; - -/** - * DwarvenGoldDigger is one of the goldmine subsystems. - */ -@Slf4j -public class DwarvenGoldDigger extends DwarvenMineWorker { - - @Override - public void work() { - LOGGER.info("{} digs for gold.", name()); - } - - @Override - public String name() { - return "Dwarf gold digger"; - } -} +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.facade; + +import lombok.extern.slf4j.Slf4j; + +/** DwarvenGoldDigger is one of the goldmine subsystems. */ +@Slf4j +public class DwarvenGoldDigger extends DwarvenMineWorker { + + @Override + public void work() { + LOGGER.info("{} digs for gold.", name()); + } + + @Override + public String name() { + return "Dwarf gold digger"; + } +} diff --git a/facade/src/main/java/com/iluwatar/facade/DwarvenGoldmineFacade.java b/facade/src/main/java/com/iluwatar/facade/DwarvenGoldmineFacade.java index 28c1a58a9..3e4151674 100644 --- a/facade/src/main/java/com/iluwatar/facade/DwarvenGoldmineFacade.java +++ b/facade/src/main/java/com/iluwatar/facade/DwarvenGoldmineFacade.java @@ -1,69 +1,62 @@ -/* - * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). - * - * The MIT License - * Copyright © 2014-2022 Ilkka Seppälä - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package com.iluwatar.facade; - -import java.util.Collection; -import java.util.List; - -/** - * DwarvenGoldmineFacade provides a single interface through which users can operate the - * subsystems. - * - *

This makes the goldmine easier to operate and cuts the dependencies from the goldmine user to - * the subsystems. - */ -public class DwarvenGoldmineFacade { - - private final List workers; - - /** - * Constructor. - */ - public DwarvenGoldmineFacade() { - workers = List.of( - new DwarvenGoldDigger(), - new DwarvenCartOperator(), - new DwarvenTunnelDigger()); - } - - public void startNewDay() { - makeActions(workers, DwarvenMineWorker.Action.WAKE_UP, DwarvenMineWorker.Action.GO_TO_MINE); - } - - public void digOutGold() { - makeActions(workers, DwarvenMineWorker.Action.WORK); - } - - public void endDay() { - makeActions(workers, DwarvenMineWorker.Action.GO_HOME, DwarvenMineWorker.Action.GO_TO_SLEEP); - } - - private static void makeActions( - Collection workers, - DwarvenMineWorker.Action... actions - ) { - workers.forEach(worker -> worker.action(actions)); - } -} +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.facade; + +import java.util.Collection; +import java.util.List; + +/** + * DwarvenGoldmineFacade provides a single interface through which users can operate the subsystems. + * + *

This makes the goldmine easier to operate and cuts the dependencies from the goldmine user to + * the subsystems. + */ +public class DwarvenGoldmineFacade { + + private final List workers; + + /** Constructor. */ + public DwarvenGoldmineFacade() { + workers = + List.of(new DwarvenGoldDigger(), new DwarvenCartOperator(), new DwarvenTunnelDigger()); + } + + public void startNewDay() { + makeActions(workers, DwarvenMineWorker.Action.WAKE_UP, DwarvenMineWorker.Action.GO_TO_MINE); + } + + public void digOutGold() { + makeActions(workers, DwarvenMineWorker.Action.WORK); + } + + public void endDay() { + makeActions(workers, DwarvenMineWorker.Action.GO_HOME, DwarvenMineWorker.Action.GO_TO_SLEEP); + } + + private static void makeActions( + Collection workers, DwarvenMineWorker.Action... actions) { + workers.forEach(worker -> worker.action(actions)); + } +} diff --git a/facade/src/main/java/com/iluwatar/facade/DwarvenMineWorker.java b/facade/src/main/java/com/iluwatar/facade/DwarvenMineWorker.java index e0c50a206..08af7cc2c 100644 --- a/facade/src/main/java/com/iluwatar/facade/DwarvenMineWorker.java +++ b/facade/src/main/java/com/iluwatar/facade/DwarvenMineWorker.java @@ -1,77 +1,77 @@ -/* - * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). - * - * The MIT License - * Copyright © 2014-2022 Ilkka Seppälä - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package com.iluwatar.facade; - -import java.util.Arrays; -import lombok.extern.slf4j.Slf4j; - -/** - * DwarvenMineWorker is one of the goldmine subsystems. - */ -@Slf4j -public abstract class DwarvenMineWorker { - - public void goToSleep() { - LOGGER.info("{} goes to sleep.", name()); - } - - public void wakeUp() { - LOGGER.info("{} wakes up.", name()); - } - - public void goHome() { - LOGGER.info("{} goes home.", name()); - } - - public void goToMine() { - LOGGER.info("{} goes to the mine.", name()); - } - - private void action(Action action) { - switch (action) { - case GO_TO_SLEEP -> goToSleep(); - case WAKE_UP -> wakeUp(); - case GO_HOME -> goHome(); - case GO_TO_MINE -> goToMine(); - case WORK -> work(); - default -> LOGGER.info("Undefined action"); - } - } - - /** - * Perform actions. - */ - public void action(Action... actions) { - Arrays.stream(actions).forEach(this::action); - } - - public abstract void work(); - - public abstract String name(); - - enum Action { - GO_TO_SLEEP, WAKE_UP, GO_HOME, GO_TO_MINE, WORK - } -} +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.facade; + +import java.util.Arrays; +import lombok.extern.slf4j.Slf4j; + +/** DwarvenMineWorker is one of the goldmine subsystems. */ +@Slf4j +public abstract class DwarvenMineWorker { + + public void goToSleep() { + LOGGER.info("{} goes to sleep.", name()); + } + + public void wakeUp() { + LOGGER.info("{} wakes up.", name()); + } + + public void goHome() { + LOGGER.info("{} goes home.", name()); + } + + public void goToMine() { + LOGGER.info("{} goes to the mine.", name()); + } + + private void action(Action action) { + switch (action) { + case GO_TO_SLEEP -> goToSleep(); + case WAKE_UP -> wakeUp(); + case GO_HOME -> goHome(); + case GO_TO_MINE -> goToMine(); + case WORK -> work(); + default -> LOGGER.info("Undefined action"); + } + } + + /** Perform actions. */ + public void action(Action... actions) { + Arrays.stream(actions).forEach(this::action); + } + + public abstract void work(); + + public abstract String name(); + + enum Action { + GO_TO_SLEEP, + WAKE_UP, + GO_HOME, + GO_TO_MINE, + WORK + } +} diff --git a/facade/src/main/java/com/iluwatar/facade/DwarvenTunnelDigger.java b/facade/src/main/java/com/iluwatar/facade/DwarvenTunnelDigger.java index b496b0ebd..4a8fa5a89 100644 --- a/facade/src/main/java/com/iluwatar/facade/DwarvenTunnelDigger.java +++ b/facade/src/main/java/com/iluwatar/facade/DwarvenTunnelDigger.java @@ -1,44 +1,42 @@ -/* - * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). - * - * The MIT License - * Copyright © 2014-2022 Ilkka Seppälä - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package com.iluwatar.facade; - -import lombok.extern.slf4j.Slf4j; - -/** - * DwarvenTunnelDigger is one of the goldmine subsystems. - */ -@Slf4j -public class DwarvenTunnelDigger extends DwarvenMineWorker { - - @Override - public void work() { - LOGGER.info("{} creates another promising tunnel.", name()); - } - - @Override - public String name() { - return "Dwarven tunnel digger"; - } -} +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.facade; + +import lombok.extern.slf4j.Slf4j; + +/** DwarvenTunnelDigger is one of the goldmine subsystems. */ +@Slf4j +public class DwarvenTunnelDigger extends DwarvenMineWorker { + + @Override + public void work() { + LOGGER.info("{} creates another promising tunnel.", name()); + } + + @Override + public String name() { + return "Dwarven tunnel digger"; + } +} diff --git a/facade/src/test/java/com/iluwatar/facade/AppTest.java b/facade/src/test/java/com/iluwatar/facade/AppTest.java index 38c4b9b78..41d6d2a94 100644 --- a/facade/src/test/java/com/iluwatar/facade/AppTest.java +++ b/facade/src/test/java/com/iluwatar/facade/AppTest.java @@ -24,17 +24,15 @@ */ package com.iluwatar.facade; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -/** - * Application test - */ +import org.junit.jupiter.api.Test; + +/** Application test */ class AppTest { @Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/facade/src/test/java/com/iluwatar/facade/DwarvenGoldmineFacadeTest.java b/facade/src/test/java/com/iluwatar/facade/DwarvenGoldmineFacadeTest.java index 63b59fb1c..55baf907d 100644 --- a/facade/src/test/java/com/iluwatar/facade/DwarvenGoldmineFacadeTest.java +++ b/facade/src/test/java/com/iluwatar/facade/DwarvenGoldmineFacadeTest.java @@ -37,10 +37,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.slf4j.LoggerFactory; -/** - * DwarvenGoldmineFacadeTest - * - */ +/** DwarvenGoldmineFacadeTest */ class DwarvenGoldmineFacadeTest { private InMemoryAppender appender; @@ -59,8 +56,8 @@ class DwarvenGoldmineFacadeTest { * Test a complete day cycle in the gold mine by executing all three different steps: {@link * DwarvenGoldmineFacade#startNewDay()}, {@link DwarvenGoldmineFacade#digOutGold()} and {@link * DwarvenGoldmineFacade#endDay()}. - *

- * See if the workers are doing what's expected from them on each step. + * + *

See if the workers are doing what's expected from them on each step. */ @Test void testFullWorkDay() { @@ -127,11 +124,7 @@ class DwarvenGoldmineFacadeTest { } public boolean logContains(String message) { - return log.stream() - .map(ILoggingEvent::getFormattedMessage) - .anyMatch(message::equals); + return log.stream().map(ILoggingEvent::getFormattedMessage).anyMatch(message::equals); } } - - } diff --git a/factory-kit/pom.xml b/factory-kit/pom.xml index 0edb889ea..729ea8c6b 100644 --- a/factory-kit/pom.xml +++ b/factory-kit/pom.xml @@ -34,6 +34,14 @@ factory-kit + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/factory-kit/src/main/java/com/iluwatar/factorykit/App.java b/factory-kit/src/main/java/com/iluwatar/factorykit/App.java index 416b3d39b..e545c313e 100644 --- a/factory-kit/src/main/java/com/iluwatar/factorykit/App.java +++ b/factory-kit/src/main/java/com/iluwatar/factorykit/App.java @@ -35,9 +35,9 @@ import lombok.extern.slf4j.Slf4j; *

In the given example {@link WeaponFactory} represents the factory kit, that contains four * {@link Builder}s for creating new objects of the classes implementing {@link Weapon} interface. * - *

Each of them can be called with {@link WeaponFactory#create(WeaponType)} method, with - * an input representing an instance of {@link WeaponType} that needs to be mapped explicitly with - * desired class type in the factory instance. + *

Each of them can be called with {@link WeaponFactory#create(WeaponType)} method, with an input + * representing an instance of {@link WeaponType} that needs to be mapped explicitly with desired + * class type in the factory instance. */ @Slf4j public class App { @@ -48,12 +48,14 @@ public class App { * @param args command line args */ public static void main(String[] args) { - var factory = WeaponFactory.factory(builder -> { - builder.add(WeaponType.SWORD, Sword::new); - builder.add(WeaponType.AXE, Axe::new); - builder.add(WeaponType.SPEAR, Spear::new); - builder.add(WeaponType.BOW, Bow::new); - }); + var factory = + WeaponFactory.factory( + builder -> { + builder.add(WeaponType.SWORD, Sword::new); + builder.add(WeaponType.AXE, Axe::new); + builder.add(WeaponType.SPEAR, Spear::new); + builder.add(WeaponType.BOW, Bow::new); + }); var list = new ArrayList(); list.add(factory.create(WeaponType.AXE)); list.add(factory.create(WeaponType.SPEAR)); 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 d8de7ffe2..583fa44a5 100644 --- a/factory-kit/src/main/java/com/iluwatar/factorykit/Axe.java +++ b/factory-kit/src/main/java/com/iluwatar/factorykit/Axe.java @@ -24,9 +24,7 @@ */ package com.iluwatar.factorykit; -/** - * Class representing Axe. - */ +/** 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 bd1644b78..f052db810 100644 --- a/factory-kit/src/main/java/com/iluwatar/factorykit/Bow.java +++ b/factory-kit/src/main/java/com/iluwatar/factorykit/Bow.java @@ -24,9 +24,7 @@ */ package com.iluwatar.factorykit; -/** - * Class representing Bows. - */ +/** Class representing Bows. */ public class Bow implements Weapon { @Override public String toString() { diff --git a/factory-kit/src/main/java/com/iluwatar/factorykit/Builder.java b/factory-kit/src/main/java/com/iluwatar/factorykit/Builder.java index 927f2b631..541932e8c 100644 --- a/factory-kit/src/main/java/com/iluwatar/factorykit/Builder.java +++ b/factory-kit/src/main/java/com/iluwatar/factorykit/Builder.java @@ -26,9 +26,7 @@ package com.iluwatar.factorykit; import java.util.function.Supplier; -/** - * Functional interface that allows adding builder with name to the factory. - */ +/** Functional interface that allows adding builder with name to the factory. */ public interface Builder { void add(WeaponType name, Supplier supplier); } 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 ad9b682a5..9dfd97a07 100644 --- a/factory-kit/src/main/java/com/iluwatar/factorykit/Spear.java +++ b/factory-kit/src/main/java/com/iluwatar/factorykit/Spear.java @@ -24,9 +24,7 @@ */ package com.iluwatar.factorykit; -/** - * Class representing Spear. - */ +/** 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 2aa49ce58..7f0320a3b 100644 --- a/factory-kit/src/main/java/com/iluwatar/factorykit/Sword.java +++ b/factory-kit/src/main/java/com/iluwatar/factorykit/Sword.java @@ -24,9 +24,7 @@ */ package com.iluwatar.factorykit; -/** - * Class representing Swords. - */ +/** Class representing Swords. */ public class Sword implements Weapon { @Override public String toString() { diff --git a/factory-kit/src/main/java/com/iluwatar/factorykit/Weapon.java b/factory-kit/src/main/java/com/iluwatar/factorykit/Weapon.java index e02da7484..8501fd59f 100644 --- a/factory-kit/src/main/java/com/iluwatar/factorykit/Weapon.java +++ b/factory-kit/src/main/java/com/iluwatar/factorykit/Weapon.java @@ -24,8 +24,5 @@ */ package com.iluwatar.factorykit; -/** - * Interface representing weapon. - */ -public interface Weapon { -} +/** Interface representing weapon. */ +public interface Weapon {} diff --git a/factory-kit/src/main/java/com/iluwatar/factorykit/WeaponFactory.java b/factory-kit/src/main/java/com/iluwatar/factorykit/WeaponFactory.java index 997ac8fad..74bf0623b 100644 --- a/factory-kit/src/main/java/com/iluwatar/factorykit/WeaponFactory.java +++ b/factory-kit/src/main/java/com/iluwatar/factorykit/WeaponFactory.java @@ -29,11 +29,11 @@ import java.util.function.Consumer; import java.util.function.Supplier; /** - * Functional interface, an example of the factory-kit design pattern. - *
Instance created locally gives an opportunity to strictly define - * which objects types the instance of a factory will be able to create. - *
Factory is a placeholder for {@link Builder}s - * with {@link WeaponFactory#create(WeaponType)} method to initialize new objects. + * Functional interface, an example of the factory-kit design pattern.
+ * Instance created locally gives an opportunity to strictly define which objects types the instance + * of a factory will be able to create.
+ * Factory is a placeholder for {@link Builder}s with {@link WeaponFactory#create(WeaponType)} + * method to initialize new objects. */ public interface WeaponFactory { diff --git a/factory-kit/src/main/java/com/iluwatar/factorykit/WeaponType.java b/factory-kit/src/main/java/com/iluwatar/factorykit/WeaponType.java index 4d292f461..eee7e1136 100644 --- a/factory-kit/src/main/java/com/iluwatar/factorykit/WeaponType.java +++ b/factory-kit/src/main/java/com/iluwatar/factorykit/WeaponType.java @@ -24,9 +24,7 @@ */ package com.iluwatar.factorykit; -/** - * Enumerates {@link Weapon} types. - */ +/** Enumerates {@link Weapon} types. */ public enum WeaponType { SWORD, AXE, 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 781b3f4da..afd4f6404 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 @@ -24,19 +24,16 @@ */ package com.iluwatar.factorykit.app; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + import com.iluwatar.factorykit.App; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; - -/** - * Application Test Entrypoint - */ +/** Application Test Entrypoint */ class AppTest { @Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } } - 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 152ce2bd0..02862a5d8 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 @@ -35,20 +35,20 @@ import com.iluwatar.factorykit.WeaponType; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -/** - * Test Factory Kit Pattern - */ +/** Test Factory Kit Pattern */ class FactoryKitTest { private WeaponFactory factory; @BeforeEach void init() { - factory = WeaponFactory.factory(builder -> { - builder.add(WeaponType.SPEAR, Spear::new); - builder.add(WeaponType.AXE, Axe::new); - builder.add(WeaponType.SWORD, Sword::new); - }); + factory = + WeaponFactory.factory( + builder -> { + builder.add(WeaponType.SPEAR, Spear::new); + builder.add(WeaponType.AXE, Axe::new); + builder.add(WeaponType.SWORD, Sword::new); + }); } /** @@ -71,7 +71,6 @@ class FactoryKitTest { verifyWeapon(weapon, Axe.class); } - /** * Testing {@link WeaponFactory} to produce a SWORD asserting that the Weapon is an instance of * {@link Sword} @@ -86,7 +85,7 @@ class FactoryKitTest { * This method asserts that the weapon object that is passed is an instance of the clazz * * @param weapon weapon object which is to be verified - * @param clazz expected class of the weapon + * @param clazz expected class of the weapon */ private void verifyWeapon(Weapon weapon, Class clazz) { assertTrue(clazz.isInstance(weapon), "Weapon must be an object of: " + clazz.getName()); diff --git a/factory-method/pom.xml b/factory-method/pom.xml index ea8e842c5..bdcfcea3c 100644 --- a/factory-method/pom.xml +++ b/factory-method/pom.xml @@ -34,6 +34,14 @@ factory-method + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/factory-method/src/main/java/com/iluwatar/factory/method/App.java b/factory-method/src/main/java/com/iluwatar/factory/method/App.java index 5ca71f45a..2094d2d69 100644 --- a/factory-method/src/main/java/com/iluwatar/factory/method/App.java +++ b/factory-method/src/main/java/com/iluwatar/factory/method/App.java @@ -34,10 +34,9 @@ import lombok.extern.slf4j.Slf4j; * derived classes—rather than by calling a constructor. * *

In this Factory Method example we have an interface ({@link Blacksmith}) with a method for - * creating objects ({@link Blacksmith#manufactureWeapon}). The concrete subclasses ( - * {@link OrcBlacksmith}, {@link ElfBlacksmith}) then override the method to produce objects of - * their liking. - * + * creating objects ({@link Blacksmith#manufactureWeapon}). The concrete subclasses ( {@link + * OrcBlacksmith}, {@link ElfBlacksmith}) then override the method to produce objects of their + * liking. */ @Slf4j public class App { @@ -46,6 +45,7 @@ public class App { /** * Program entry point. + * * @param args command line args */ public static void main(String[] args) { diff --git a/factory-method/src/main/java/com/iluwatar/factory/method/Blacksmith.java b/factory-method/src/main/java/com/iluwatar/factory/method/Blacksmith.java index 15fb24b65..b027763ed 100644 --- a/factory-method/src/main/java/com/iluwatar/factory/method/Blacksmith.java +++ b/factory-method/src/main/java/com/iluwatar/factory/method/Blacksmith.java @@ -24,11 +24,8 @@ */ package com.iluwatar.factory.method; -/** - * The interface containing method for producing objects. - */ +/** The interface containing method for producing objects. */ public interface Blacksmith { Weapon manufactureWeapon(WeaponType weaponType); - } diff --git a/factory-method/src/main/java/com/iluwatar/factory/method/ElfBlacksmith.java b/factory-method/src/main/java/com/iluwatar/factory/method/ElfBlacksmith.java index 411663ad1..881b82a6a 100644 --- a/factory-method/src/main/java/com/iluwatar/factory/method/ElfBlacksmith.java +++ b/factory-method/src/main/java/com/iluwatar/factory/method/ElfBlacksmith.java @@ -28,9 +28,7 @@ import java.util.Arrays; import java.util.EnumMap; import java.util.Map; -/** - * Concrete subclass for creating new objects. - */ +/** Concrete subclass for creating new objects. */ public class ElfBlacksmith implements Blacksmith { private static final Map ELFARSENAL; diff --git a/factory-method/src/main/java/com/iluwatar/factory/method/ElfWeapon.java b/factory-method/src/main/java/com/iluwatar/factory/method/ElfWeapon.java index e055132e2..58b188e29 100644 --- a/factory-method/src/main/java/com/iluwatar/factory/method/ElfWeapon.java +++ b/factory-method/src/main/java/com/iluwatar/factory/method/ElfWeapon.java @@ -24,12 +24,7 @@ */ package com.iluwatar.factory.method; -import lombok.Getter; -import lombok.RequiredArgsConstructor; - -/** - * ElfWeapon. - */ +/** ElfWeapon. */ public record ElfWeapon(WeaponType weaponType) implements Weapon { @Override diff --git a/factory-method/src/main/java/com/iluwatar/factory/method/OrcBlacksmith.java b/factory-method/src/main/java/com/iluwatar/factory/method/OrcBlacksmith.java index 4d856bba5..6657b66a4 100644 --- a/factory-method/src/main/java/com/iluwatar/factory/method/OrcBlacksmith.java +++ b/factory-method/src/main/java/com/iluwatar/factory/method/OrcBlacksmith.java @@ -28,9 +28,7 @@ import java.util.Arrays; import java.util.EnumMap; import java.util.Map; -/** - * Concrete subclass for creating new objects. - */ +/** Concrete subclass for creating new objects. */ public class OrcBlacksmith implements Blacksmith { private static final Map ORCARSENAL; diff --git a/factory-method/src/main/java/com/iluwatar/factory/method/OrcWeapon.java b/factory-method/src/main/java/com/iluwatar/factory/method/OrcWeapon.java index 8446b9099..c7bf473ce 100644 --- a/factory-method/src/main/java/com/iluwatar/factory/method/OrcWeapon.java +++ b/factory-method/src/main/java/com/iluwatar/factory/method/OrcWeapon.java @@ -24,12 +24,7 @@ */ package com.iluwatar.factory.method; -import lombok.Getter; -import lombok.RequiredArgsConstructor; - -/** - * OrcWeapon. - */ +/** OrcWeapon. */ public record OrcWeapon(WeaponType weaponType) implements Weapon { @Override diff --git a/factory-method/src/main/java/com/iluwatar/factory/method/Weapon.java b/factory-method/src/main/java/com/iluwatar/factory/method/Weapon.java index 97f8cb1d7..0d5f12e48 100644 --- a/factory-method/src/main/java/com/iluwatar/factory/method/Weapon.java +++ b/factory-method/src/main/java/com/iluwatar/factory/method/Weapon.java @@ -24,11 +24,8 @@ */ package com.iluwatar.factory.method; -/** - * Weapon interface. - */ +/** Weapon interface. */ public interface Weapon { WeaponType weaponType(); - } diff --git a/factory-method/src/main/java/com/iluwatar/factory/method/WeaponType.java b/factory-method/src/main/java/com/iluwatar/factory/method/WeaponType.java index 156afae55..e1ab11a1f 100644 --- a/factory-method/src/main/java/com/iluwatar/factory/method/WeaponType.java +++ b/factory-method/src/main/java/com/iluwatar/factory/method/WeaponType.java @@ -26,12 +26,9 @@ package com.iluwatar.factory.method; import lombok.RequiredArgsConstructor; -/** - * WeaponType enumeration. - */ +/** WeaponType enumeration. */ @RequiredArgsConstructor public enum WeaponType { - SHORT_SWORD("short sword"), SPEAR("spear"), AXE("axe"), diff --git a/factory-method/src/test/java/com/iluwatar/factory/method/AppTest.java b/factory-method/src/test/java/com/iluwatar/factory/method/AppTest.java index cd597444b..88fe6f6d7 100644 --- a/factory-method/src/test/java/com/iluwatar/factory/method/AppTest.java +++ b/factory-method/src/test/java/com/iluwatar/factory/method/AppTest.java @@ -24,17 +24,15 @@ */ package com.iluwatar.factory.method; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -/** - * Tests that Factory Method example runs without errors. - */ +import org.junit.jupiter.api.Test; + +/** Tests that Factory Method example runs without errors. */ class AppTest { @Test void shouldExecuteWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/factory-method/src/test/java/com/iluwatar/factory/method/FactoryMethodTest.java b/factory-method/src/test/java/com/iluwatar/factory/method/FactoryMethodTest.java index 25b15836e..7cd4dbeb2 100644 --- a/factory-method/src/test/java/com/iluwatar/factory/method/FactoryMethodTest.java +++ b/factory-method/src/test/java/com/iluwatar/factory/method/FactoryMethodTest.java @@ -36,10 +36,8 @@ import org.junit.jupiter.api.Test; * and implemented by child classes, or implemented in a base class and optionally overridden by * derived classes—rather than by calling a constructor. * - *

Factory produces the object of its liking. - * The weapon {@link Weapon} manufactured by the blacksmith depends on the kind of factory - * implementation it is referring to. - *

+ *

Factory produces the object of its liking. The weapon {@link Weapon} manufactured by the + * blacksmith depends on the kind of factory implementation it is referring to. */ class FactoryMethodTest { @@ -91,13 +89,15 @@ class FactoryMethodTest { * This method asserts that the weapon object that is passed is an instance of the clazz and the * weapon is of type expectedWeaponType. * - * @param weapon weapon object which is to be verified + * @param weapon weapon object which is to be verified * @param expectedWeaponType expected WeaponType of the weapon - * @param clazz expected class of the weapon + * @param clazz expected class of the weapon */ private void verifyWeapon(Weapon weapon, WeaponType expectedWeaponType, Class clazz) { assertTrue(clazz.isInstance(weapon), "Weapon must be an object of: " + clazz.getName()); - assertEquals(expectedWeaponType, weapon - .weaponType(), "Weapon must be of weaponType: " + expectedWeaponType); + assertEquals( + expectedWeaponType, + weapon.weaponType(), + "Weapon must be of weaponType: " + expectedWeaponType); } } diff --git a/factory/pom.xml b/factory/pom.xml index 5468af6cd..7280d8b6d 100644 --- a/factory/pom.xml +++ b/factory/pom.xml @@ -34,6 +34,14 @@ factory + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/factory/src/main/java/com/iluwatar/factory/App.java b/factory/src/main/java/com/iluwatar/factory/App.java index d1f3313b4..ce9f205b0 100644 --- a/factory/src/main/java/com/iluwatar/factory/App.java +++ b/factory/src/main/java/com/iluwatar/factory/App.java @@ -27,20 +27,17 @@ package com.iluwatar.factory; import lombok.extern.slf4j.Slf4j; /** - * Factory is an object for creating other objects. It provides a static method to - * create and return objects of varying classes, in order to hide the implementation logic - * and makes client code focus on usage rather than objects initialization and management. + * Factory is an object for creating other objects. It provides a static method to create and return + * objects of varying classes, in order to hide the implementation logic and makes client code focus + * on usage rather than objects initialization and management. * *

In this example an alchemist manufactures coins. CoinFactory is the factory class, and it * provides a static method to create different types of coins. */ - @Slf4j public class App { - /** - * Program main entry point. - */ + /** Program main entry point. */ public static void main(String[] args) { LOGGER.info("The alchemist begins his work."); var coin1 = CoinFactory.getCoin(CoinType.COPPER); diff --git a/factory/src/main/java/com/iluwatar/factory/Coin.java b/factory/src/main/java/com/iluwatar/factory/Coin.java index 4adef8ea7..b8824222e 100644 --- a/factory/src/main/java/com/iluwatar/factory/Coin.java +++ b/factory/src/main/java/com/iluwatar/factory/Coin.java @@ -24,11 +24,8 @@ */ package com.iluwatar.factory; -/** - * Coin interface. - */ +/** Coin interface. */ public interface Coin { String getDescription(); - } diff --git a/factory/src/main/java/com/iluwatar/factory/CoinFactory.java b/factory/src/main/java/com/iluwatar/factory/CoinFactory.java index 212bef4b9..8940e3ade 100644 --- a/factory/src/main/java/com/iluwatar/factory/CoinFactory.java +++ b/factory/src/main/java/com/iluwatar/factory/CoinFactory.java @@ -24,14 +24,10 @@ */ package com.iluwatar.factory; -/** - * Factory of coins. - */ +/** Factory of coins. */ public class CoinFactory { - /** - * Factory method takes as a parameter the coin type and calls the appropriate class. - */ + /** Factory method takes as a parameter the coin type and calls the appropriate class. */ public static Coin getCoin(CoinType type) { return type.getConstructor().get(); } diff --git a/factory/src/main/java/com/iluwatar/factory/CoinType.java b/factory/src/main/java/com/iluwatar/factory/CoinType.java index 069bd4586..de1583bf9 100644 --- a/factory/src/main/java/com/iluwatar/factory/CoinType.java +++ b/factory/src/main/java/com/iluwatar/factory/CoinType.java @@ -28,13 +28,10 @@ import java.util.function.Supplier; import lombok.Getter; import lombok.RequiredArgsConstructor; -/** - * Enumeration for different types of coins. - */ +/** Enumeration for different types of coins. */ @RequiredArgsConstructor @Getter public enum CoinType { - COPPER(CopperCoin::new), GOLD(GoldCoin::new); diff --git a/factory/src/main/java/com/iluwatar/factory/CopperCoin.java b/factory/src/main/java/com/iluwatar/factory/CopperCoin.java index b4c586468..fa6f3f2d8 100644 --- a/factory/src/main/java/com/iluwatar/factory/CopperCoin.java +++ b/factory/src/main/java/com/iluwatar/factory/CopperCoin.java @@ -24,9 +24,7 @@ */ package com.iluwatar.factory; -/** - * CopperCoin implementation. - */ +/** CopperCoin implementation. */ public class CopperCoin implements Coin { static final String DESCRIPTION = "This is a copper coin."; diff --git a/factory/src/main/java/com/iluwatar/factory/GoldCoin.java b/factory/src/main/java/com/iluwatar/factory/GoldCoin.java index 4e693a4d3..b5e1aef1a 100644 --- a/factory/src/main/java/com/iluwatar/factory/GoldCoin.java +++ b/factory/src/main/java/com/iluwatar/factory/GoldCoin.java @@ -24,9 +24,7 @@ */ package com.iluwatar.factory; -/** - * GoldCoin implementation. - */ +/** GoldCoin implementation. */ public class GoldCoin implements Coin { static final String DESCRIPTION = "This is a gold coin."; diff --git a/factory/src/test/java/com/iluwatar/factory/AppTest.java b/factory/src/test/java/com/iluwatar/factory/AppTest.java index 544a9bc46..702481525 100644 --- a/factory/src/test/java/com/iluwatar/factory/AppTest.java +++ b/factory/src/test/java/com/iluwatar/factory/AppTest.java @@ -32,7 +32,6 @@ class AppTest { @Test void shouldExecuteWithoutExceptions() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } - } diff --git a/fanout-fanin/pom.xml b/fanout-fanin/pom.xml index 2cc2c117f..1052918ee 100644 --- a/fanout-fanin/pom.xml +++ b/fanout-fanin/pom.xml @@ -34,6 +34,14 @@ 4.0.0 fanout-fanin + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/fanout-fanin/src/main/java/com/iluwatar/fanout/fanin/App.java b/fanout-fanin/src/main/java/com/iluwatar/fanout/fanin/App.java index 83f51f647..7a34c2214 100644 --- a/fanout-fanin/src/main/java/com/iluwatar/fanout/fanin/App.java +++ b/fanout-fanin/src/main/java/com/iluwatar/fanout/fanin/App.java @@ -28,8 +28,6 @@ import java.util.Arrays; import java.util.List; import lombok.extern.slf4j.Slf4j; - - /** * FanOut/FanIn pattern is a concurrency pattern that refers to executing multiple instances of the * activity function concurrently. The "fan out" part is essentially splitting the data into diff --git a/fanout-fanin/src/main/java/com/iluwatar/fanout/fanin/Consumer.java b/fanout-fanin/src/main/java/com/iluwatar/fanout/fanin/Consumer.java index 90b7c6385..95b7c663a 100644 --- a/fanout-fanin/src/main/java/com/iluwatar/fanout/fanin/Consumer.java +++ b/fanout-fanin/src/main/java/com/iluwatar/fanout/fanin/Consumer.java @@ -27,8 +27,6 @@ package com.iluwatar.fanout.fanin; import java.util.concurrent.atomic.AtomicLong; import lombok.Getter; - - /** * Consumer or callback class that will be called every time a request is complete This will * aggregate individual result to form a final result. diff --git a/fanout-fanin/src/main/java/com/iluwatar/fanout/fanin/FanOutFanIn.java b/fanout-fanin/src/main/java/com/iluwatar/fanout/fanin/FanOutFanIn.java index e75f0d22b..9239e03f4 100644 --- a/fanout-fanin/src/main/java/com/iluwatar/fanout/fanin/FanOutFanIn.java +++ b/fanout-fanin/src/main/java/com/iluwatar/fanout/fanin/FanOutFanIn.java @@ -38,6 +38,7 @@ public class FanOutFanIn { /** * the main fanOutFanIn function or orchestrator function. + * * @param requests List of numbers that need to be squared and summed up * @param consumer Takes in the squared number from {@link SquareNumberRequest} and sums it up * @return Aggregated sum of all squared numbers. diff --git a/fanout-fanin/src/main/java/com/iluwatar/fanout/fanin/SquareNumberRequest.java b/fanout-fanin/src/main/java/com/iluwatar/fanout/fanin/SquareNumberRequest.java index e41c33683..7f12e8420 100644 --- a/fanout-fanin/src/main/java/com/iluwatar/fanout/fanin/SquareNumberRequest.java +++ b/fanout-fanin/src/main/java/com/iluwatar/fanout/fanin/SquareNumberRequest.java @@ -41,8 +41,9 @@ public class SquareNumberRequest { /** * Squares the number with a little timeout to give impression of long-running process that return * at different times. + * * @param consumer callback class that takes the result after the delay. - * */ + */ public void delayedSquaring(final Consumer consumer) { var minTimeOut = 5000L; diff --git a/fanout-fanin/src/test/java/com/iluwatar/fanout/fanin/AppTest.java b/fanout-fanin/src/test/java/com/iluwatar/fanout/fanin/AppTest.java index 3f2bee396..0fe64096f 100644 --- a/fanout-fanin/src/test/java/com/iluwatar/fanout/fanin/AppTest.java +++ b/fanout-fanin/src/test/java/com/iluwatar/fanout/fanin/AppTest.java @@ -24,14 +24,14 @@ */ package com.iluwatar.fanout.fanin; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import org.junit.jupiter.api.Test; + class AppTest { - @Test - void shouldLaunchApp() { - assertDoesNotThrow(() -> App.main(new String[]{})); - } + @Test + void shouldLaunchApp() { + assertDoesNotThrow(() -> App.main(new String[] {})); + } } diff --git a/fanout-fanin/src/test/java/com/iluwatar/fanout/fanin/FanOutFanInTest.java b/fanout-fanin/src/test/java/com/iluwatar/fanout/fanin/FanOutFanInTest.java index bd31108b7..55260c36a 100644 --- a/fanout-fanin/src/test/java/com/iluwatar/fanout/fanin/FanOutFanInTest.java +++ b/fanout-fanin/src/test/java/com/iluwatar/fanout/fanin/FanOutFanInTest.java @@ -24,10 +24,10 @@ */ package com.iluwatar.fanout.fanin; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.List; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; class FanOutFanInTest { diff --git a/feature-toggle/pom.xml b/feature-toggle/pom.xml index 8a60b4876..c21080827 100644 --- a/feature-toggle/pom.xml +++ b/feature-toggle/pom.xml @@ -34,6 +34,14 @@ 4.0.0 feature-toggle + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/feature-toggle/src/main/java/com/iluwatar/featuretoggle/App.java b/feature-toggle/src/main/java/com/iluwatar/featuretoggle/App.java index 93a953005..30c729dd8 100644 --- a/feature-toggle/src/main/java/com/iluwatar/featuretoggle/App.java +++ b/feature-toggle/src/main/java/com/iluwatar/featuretoggle/App.java @@ -94,7 +94,8 @@ public class App { // Demonstrates the TieredFeatureToggleVersion setup with // two users: one on the free tier and the other on the paid tier. When the // Service#getWelcomeMessage(User) method is called with the paid user, the welcome - // message includes their username. In contrast, calling the same service with the free tier user results + // message includes their username. In contrast, calling the same service with the free tier + // user results // in a more generic welcome message without the username. var service2 = new TieredFeatureToggleVersion(); diff --git a/feature-toggle/src/main/java/com/iluwatar/featuretoggle/pattern/Service.java b/feature-toggle/src/main/java/com/iluwatar/featuretoggle/pattern/Service.java index 4dcc45b13..7c8287622 100644 --- a/feature-toggle/src/main/java/com/iluwatar/featuretoggle/pattern/Service.java +++ b/feature-toggle/src/main/java/com/iluwatar/featuretoggle/pattern/Service.java @@ -28,8 +28,8 @@ import com.iluwatar.featuretoggle.user.User; /** * Simple interfaces to allow the calling of the method to generate the welcome message for a given - * user. While there is a helper method to gather the status of the feature toggle. In some - * cases there is no need for the {@link Service#isEnhanced()} in {@link + * user. While there is a helper method to gather the status of the feature toggle. In some cases + * there is no need for the {@link Service#isEnhanced()} in {@link * com.iluwatar.featuretoggle.pattern.tieredversion.TieredFeatureToggleVersion} where the toggle is * determined by the actual {@link User}. * @@ -53,5 +53,4 @@ public interface Service { * @return Boolean {@code true} if enhanced. */ boolean isEnhanced(); - } diff --git a/feature-toggle/src/main/java/com/iluwatar/featuretoggle/pattern/propertiesversion/PropertiesFeatureToggleVersion.java b/feature-toggle/src/main/java/com/iluwatar/featuretoggle/pattern/propertiesversion/PropertiesFeatureToggleVersion.java index b3484cec2..cfc2ab56b 100644 --- a/feature-toggle/src/main/java/com/iluwatar/featuretoggle/pattern/propertiesversion/PropertiesFeatureToggleVersion.java +++ b/feature-toggle/src/main/java/com/iluwatar/featuretoggle/pattern/propertiesversion/PropertiesFeatureToggleVersion.java @@ -46,8 +46,8 @@ import lombok.Getter; public class PropertiesFeatureToggleVersion implements Service { /** - * True if the welcome message to be returned is the enhanced venison or not. For - * this service it will see the value of the boolean that was set in the constructor {@link + * True if the welcome message to be returned is the enhanced venison or not. For this service it + * will see the value of the boolean that was set in the constructor {@link * PropertiesFeatureToggleVersion#PropertiesFeatureToggleVersion(Properties)} */ private final boolean enhanced; @@ -80,9 +80,9 @@ public class PropertiesFeatureToggleVersion implements Service { * passed {@link User}. However, if disabled then a generic version fo the message is returned. * * @param user the {@link User} to be displayed in the message if the enhanced version is enabled - * see {@link PropertiesFeatureToggleVersion#isEnhanced()}. If the enhanced version is - * enabled, then the message will be personalised with the name of the passed {@link - * User}. However, if disabled then a generic version fo the message is returned. + * see {@link PropertiesFeatureToggleVersion#isEnhanced()}. If the enhanced version is + * enabled, then the message will be personalised with the name of the passed {@link User}. + * However, if disabled then a generic version fo the message is returned. * @return Resulting welcome message. * @see User */ diff --git a/feature-toggle/src/main/java/com/iluwatar/featuretoggle/pattern/tieredversion/TieredFeatureToggleVersion.java b/feature-toggle/src/main/java/com/iluwatar/featuretoggle/pattern/tieredversion/TieredFeatureToggleVersion.java index 420783485..f5342da01 100644 --- a/feature-toggle/src/main/java/com/iluwatar/featuretoggle/pattern/tieredversion/TieredFeatureToggleVersion.java +++ b/feature-toggle/src/main/java/com/iluwatar/featuretoggle/pattern/tieredversion/TieredFeatureToggleVersion.java @@ -30,9 +30,9 @@ import com.iluwatar.featuretoggle.user.UserGroup; /** * This example of the Feature Toggle pattern shows how it could be implemented based on a {@link - * User}. Therefore, showing its use within a tiered application where the paying users get access to - * different content or better versions of features. So in this instance a {@link User} is passed in - * and if they are found to be on the {@link UserGroup#isPaid(User)} they are welcomed with a + * User}. Therefore, showing its use within a tiered application where the paying users get access + * to different content or better versions of features. So in this instance a {@link User} is passed + * in and if they are found to be on the {@link UserGroup#isPaid(User)} they are welcomed with a * personalised message. While the other is more generic. However, this pattern is limited to simple * examples such as the one below. * @@ -49,8 +49,8 @@ public class TieredFeatureToggleVersion implements Service { * the enhanced version of the welcome message will be returned where the username is displayed. * * @param user the {@link User} to generate the welcome message for, different messages are - * displayed if the user is in the {@link UserGroup#isPaid(User)} or {@link - * UserGroup#freeGroup} + * displayed if the user is in the {@link UserGroup#isPaid(User)} or {@link + * UserGroup#freeGroup} * @return Resulting welcome message. * @see User * @see UserGroup @@ -75,5 +75,4 @@ public class TieredFeatureToggleVersion implements Service { public boolean isEnhanced() { return true; } - } 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 f659134fb..52badacab 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 @@ -33,9 +33,7 @@ import com.iluwatar.featuretoggle.user.User; import java.util.Properties; import org.junit.jupiter.api.Test; -/** - * Test Properties Toggle - */ +/** Test Properties Toggle */ class PropertiesFeatureToggleVersionTest { @Test @@ -45,11 +43,13 @@ class PropertiesFeatureToggleVersionTest { @Test void testNonBooleanProperty() { - assertThrows(IllegalArgumentException.class, () -> { - final var properties = new Properties(); - properties.setProperty("enhancedWelcome", "Something"); - new PropertiesFeatureToggleVersion(properties); - }); + assertThrows( + IllegalArgumentException.class, + () -> { + final var properties = new Properties(); + properties.setProperty("enhancedWelcome", "Something"); + new PropertiesFeatureToggleVersion(properties); + }); } @Test @@ -59,7 +59,8 @@ class PropertiesFeatureToggleVersionTest { var service = new PropertiesFeatureToggleVersion(properties); assertTrue(service.isEnhanced()); final var welcomeMessage = service.getWelcomeMessage(new User("Jamie No Code")); - assertEquals("Welcome Jamie No Code. You're using the enhanced welcome message.", welcomeMessage); + assertEquals( + "Welcome Jamie No Code. You're using the enhanced welcome message.", welcomeMessage); } @Test diff --git a/feature-toggle/src/test/java/com/iluwatar/featuretoggle/pattern/tieredversion/TieredFeatureToggleVersionTest.java b/feature-toggle/src/test/java/com/iluwatar/featuretoggle/pattern/tieredversion/TieredFeatureToggleVersionTest.java index 7eb03b833..67314f404 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 @@ -33,9 +33,7 @@ import com.iluwatar.featuretoggle.user.UserGroup; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -/** - * Test Tiered Feature Toggle - */ +/** Test Tiered Feature Toggle */ class TieredFeatureToggleVersionTest { final User paidUser = new User("Jamie Coder"); 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 07d0bc88f..b9bfb0bef 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 @@ -30,9 +30,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; -/** - * Test User Group specific feature - */ +/** Test User Group specific feature */ class UserGroupTest { @Test diff --git a/filterer/pom.xml b/filterer/pom.xml index 23f0093f9..a0d438394 100644 --- a/filterer/pom.xml +++ b/filterer/pom.xml @@ -34,9 +34,17 @@ 4.0.0 filterer + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter - junit-jupiter-api + junit-jupiter-engine test diff --git a/filterer/src/main/java/com/iluwatar/filterer/App.java b/filterer/src/main/java/com/iluwatar/filterer/App.java index 30a04d46e..c64dce891 100644 --- a/filterer/src/main/java/com/iluwatar/filterer/App.java +++ b/filterer/src/main/java/com/iluwatar/filterer/App.java @@ -39,10 +39,10 @@ import lombok.extern.slf4j.Slf4j; /** * This demo class represent how {@link com.iluwatar.filterer.domain.Filterer} pattern is used to * filter container-like objects to return filtered versions of themselves. The container like - * objects are systems that are aware of threats that they can be vulnerable to. We would like - * to have a way to create copy of different system objects but with filtered threats. - * The thing is to keep it simple if we add new subtype of {@link Threat} - * (for example {@link ProbableThreat}) - we still need to be able to filter by its properties. + * objects are systems that are aware of threats that they can be vulnerable to. We would like to + * have a way to create copy of different system objects but with filtered threats. The thing is to + * keep it simple if we add new subtype of {@link Threat} (for example {@link ProbableThreat}) - we + * still need to be able to filter by its properties. */ @Slf4j public class App { @@ -55,8 +55,8 @@ public class App { /** * Demonstrates how to filter {@link com.iluwatar.filterer.threat.ProbabilisticThreatAwareSystem} * based on probability property. The @{@link com.iluwatar.filterer.domain.Filterer#by(Predicate)} - * method is able to use {@link com.iluwatar.filterer.threat.ProbableThreat} - * as predicate argument. + * method is able to use {@link com.iluwatar.filterer.threat.ProbableThreat} as predicate + * argument. */ private static void filteringSimpleProbableThreats() { LOGGER.info("### Filtering ProbabilisticThreatAwareSystem by probability ###"); @@ -69,20 +69,22 @@ public class App { var probabilisticThreatAwareSystem = new SimpleProbabilisticThreatAwareSystem("Sys-1", probableThreats); - LOGGER.info("Filtering ProbabilisticThreatAwareSystem. Initial : " - + probabilisticThreatAwareSystem); + LOGGER.info( + "Filtering ProbabilisticThreatAwareSystem. Initial : " + probabilisticThreatAwareSystem); - //Filtering using filterer - var filteredThreatAwareSystem = probabilisticThreatAwareSystem.filtered() - .by(probableThreat -> Double.compare(probableThreat.probability(), 0.99) == 0); + // Filtering using filterer + var filteredThreatAwareSystem = + probabilisticThreatAwareSystem + .filtered() + .by(probableThreat -> Double.compare(probableThreat.probability(), 0.99) == 0); LOGGER.info("Filtered by probability = 0.99 : " + filteredThreatAwareSystem); } /** - * Demonstrates how to filter {@link ThreatAwareSystem} based on startingOffset property - * of {@link SimpleThreat}. The @{@link com.iluwatar.filterer.domain.Filterer#by(Predicate)} - * method is able to use {@link Threat} as predicate argument. + * Demonstrates how to filter {@link ThreatAwareSystem} based on startingOffset property of {@link + * SimpleThreat}. The @{@link com.iluwatar.filterer.domain.Filterer#by(Predicate)} method is able + * to use {@link Threat} as predicate argument. */ private static void filteringSimpleThreats() { LOGGER.info("### Filtering ThreatAwareSystem by ThreatType ###"); @@ -95,11 +97,10 @@ public class App { LOGGER.info("Filtering ThreatAwareSystem. Initial : " + threatAwareSystem); - //Filtering using Filterer - var rootkitThreatAwareSystem = threatAwareSystem.filtered() - .by(threat -> threat.type() == ThreatType.ROOTKIT); + // Filtering using Filterer + var rootkitThreatAwareSystem = + threatAwareSystem.filtered().by(threat -> threat.type() == ThreatType.ROOTKIT); LOGGER.info("Filtered by threatType = ROOTKIT : " + rootkitThreatAwareSystem); } - } diff --git a/filterer/src/main/java/com/iluwatar/filterer/domain/Filterer.java b/filterer/src/main/java/com/iluwatar/filterer/domain/Filterer.java index 091db7071..58da1a7e5 100644 --- a/filterer/src/main/java/com/iluwatar/filterer/domain/Filterer.java +++ b/filterer/src/main/java/com/iluwatar/filterer/domain/Filterer.java @@ -28,10 +28,11 @@ import java.util.function.Predicate; /** * Filterer helper interface. + * * @param type of the container-like object. * @param type of the elements contained within this container-like object. */ @FunctionalInterface public interface Filterer { G by(Predicate predicate); -} \ No newline at end of file +} diff --git a/filterer/src/main/java/com/iluwatar/filterer/threat/ProbabilisticThreatAwareSystem.java b/filterer/src/main/java/com/iluwatar/filterer/threat/ProbabilisticThreatAwareSystem.java index 21609207b..a63728d74 100644 --- a/filterer/src/main/java/com/iluwatar/filterer/threat/ProbabilisticThreatAwareSystem.java +++ b/filterer/src/main/java/com/iluwatar/filterer/threat/ProbabilisticThreatAwareSystem.java @@ -27,13 +27,12 @@ package com.iluwatar.filterer.threat; import com.iluwatar.filterer.domain.Filterer; import java.util.List; -/** - * Represents system that is aware of its threats with given probability of their occurrence. - */ +/** Represents system that is aware of its threats with given probability of their occurrence. */ public interface ProbabilisticThreatAwareSystem extends ThreatAwareSystem { /** * {@inheritDoc} + * * @return {@link ProbableThreat} */ @Override @@ -41,9 +40,9 @@ public interface ProbabilisticThreatAwareSystem extends ThreatAwareSystem { /** * {@inheritDoc} + * * @return {@link Filterer} */ @Override Filterer filtered(); } - diff --git a/filterer/src/main/java/com/iluwatar/filterer/threat/ProbableThreat.java b/filterer/src/main/java/com/iluwatar/filterer/threat/ProbableThreat.java index fc4efce51..8562136b5 100644 --- a/filterer/src/main/java/com/iluwatar/filterer/threat/ProbableThreat.java +++ b/filterer/src/main/java/com/iluwatar/filterer/threat/ProbableThreat.java @@ -24,13 +24,12 @@ */ package com.iluwatar.filterer.threat; -/** - * Represents threat that might be a threat with given probability. - */ +/** Represents threat that might be a threat with given probability. */ public interface ProbableThreat extends Threat { /** * Returns probability of occurrence of given threat. + * * @return probability of occurrence of given threat. */ double probability(); -} \ No newline at end of file +} diff --git a/filterer/src/main/java/com/iluwatar/filterer/threat/SimpleProbabilisticThreatAwareSystem.java b/filterer/src/main/java/com/iluwatar/filterer/threat/SimpleProbabilisticThreatAwareSystem.java index e9161b9f4..0584a031b 100644 --- a/filterer/src/main/java/com/iluwatar/filterer/threat/SimpleProbabilisticThreatAwareSystem.java +++ b/filterer/src/main/java/com/iluwatar/filterer/threat/SimpleProbabilisticThreatAwareSystem.java @@ -31,9 +31,7 @@ import lombok.EqualsAndHashCode; import lombok.RequiredArgsConstructor; import lombok.ToString; -/** - * {@inheritDoc} - */ +/** {@inheritDoc} */ @ToString @EqualsAndHashCode @RequiredArgsConstructor @@ -42,25 +40,19 @@ public class SimpleProbabilisticThreatAwareSystem implements ProbabilisticThreat private final String systemId; private final List threats; - /** - * {@inheritDoc} - */ + /** {@inheritDoc} */ @Override public String systemId() { return systemId; } - /** - * {@inheritDoc} - */ + /** {@inheritDoc} */ @Override public List threats() { return threats; } - /** - * {@inheritDoc} - */ + /** {@inheritDoc} */ @Override public Filterer filtered() { return this::filteredGroup; @@ -71,11 +63,7 @@ public class SimpleProbabilisticThreatAwareSystem implements ProbabilisticThreat return new SimpleProbabilisticThreatAwareSystem(this.systemId, filteredItems(predicate)); } - private List filteredItems( - final Predicate predicate) { - return this.threats.stream() - .filter(predicate) - .toList(); + private List filteredItems(final Predicate predicate) { + return this.threats.stream().filter(predicate).toList(); } - } diff --git a/filterer/src/main/java/com/iluwatar/filterer/threat/SimpleProbableThreat.java b/filterer/src/main/java/com/iluwatar/filterer/threat/SimpleProbableThreat.java index bd8997de3..044e02471 100644 --- a/filterer/src/main/java/com/iluwatar/filterer/threat/SimpleProbableThreat.java +++ b/filterer/src/main/java/com/iluwatar/filterer/threat/SimpleProbableThreat.java @@ -26,23 +26,19 @@ package com.iluwatar.filterer.threat; import lombok.EqualsAndHashCode; -/** - * {@inheritDoc} - */ +/** {@inheritDoc} */ @EqualsAndHashCode(callSuper = false) public class SimpleProbableThreat extends SimpleThreat implements ProbableThreat { private final double probability; - public SimpleProbableThreat(final String name, final int id, final ThreatType threatType, - final double probability) { + public SimpleProbableThreat( + final String name, final int id, final ThreatType threatType, final double probability) { super(threatType, id, name); this.probability = probability; } - /** - * {@inheritDoc} - */ + /** {@inheritDoc} */ @Override public double probability() { return probability; @@ -50,9 +46,6 @@ public class SimpleProbableThreat extends SimpleThreat implements ProbableThreat @Override public String toString() { - return "SimpleProbableThreat{" - + "probability=" + probability - + "} " - + super.toString(); + return "SimpleProbableThreat{" + "probability=" + probability + "} " + super.toString(); } } diff --git a/filterer/src/main/java/com/iluwatar/filterer/threat/SimpleThreat.java b/filterer/src/main/java/com/iluwatar/filterer/threat/SimpleThreat.java index 6285bddc9..034c6970b 100644 --- a/filterer/src/main/java/com/iluwatar/filterer/threat/SimpleThreat.java +++ b/filterer/src/main/java/com/iluwatar/filterer/threat/SimpleThreat.java @@ -28,9 +28,7 @@ import lombok.EqualsAndHashCode; import lombok.RequiredArgsConstructor; import lombok.ToString; -/** - * Represents a simple threat. - */ +/** Represents a simple threat. */ @ToString @EqualsAndHashCode @RequiredArgsConstructor @@ -40,28 +38,21 @@ public class SimpleThreat implements Threat { private final int id; private final String name; - /** - * {@inheritDoc} - */ + /** {@inheritDoc} */ @Override public String name() { return name; } - /** - * {@inheritDoc} - */ + /** {@inheritDoc} */ @Override public int id() { return id; } - /** - * {@inheritDoc} - */ + /** {@inheritDoc} */ @Override public ThreatType type() { return threatType; } - } diff --git a/filterer/src/main/java/com/iluwatar/filterer/threat/SimpleThreatAwareSystem.java b/filterer/src/main/java/com/iluwatar/filterer/threat/SimpleThreatAwareSystem.java index 93304b647..c547afe8f 100644 --- a/filterer/src/main/java/com/iluwatar/filterer/threat/SimpleThreatAwareSystem.java +++ b/filterer/src/main/java/com/iluwatar/filterer/threat/SimpleThreatAwareSystem.java @@ -32,9 +32,7 @@ import lombok.EqualsAndHashCode; import lombok.RequiredArgsConstructor; import lombok.ToString; -/** - * {@inheritDoc} - */ +/** {@inheritDoc} */ @ToString @EqualsAndHashCode @RequiredArgsConstructor @@ -43,25 +41,19 @@ public class SimpleThreatAwareSystem implements ThreatAwareSystem { private final String systemId; private final List issues; - /** - * {@inheritDoc} - */ + /** {@inheritDoc} */ @Override public String systemId() { return systemId; } - /** - * {@inheritDoc} - */ + /** {@inheritDoc} */ @Override public List threats() { return new ArrayList<>(issues); } - /** - * {@inheritDoc} - */ + /** {@inheritDoc} */ @Override public Filterer filtered() { return this::filteredGroup; @@ -72,8 +64,6 @@ public class SimpleThreatAwareSystem implements ThreatAwareSystem { } private List filteredItems(Predicate predicate) { - return this.issues.stream() - .filter(predicate).toList(); + return this.issues.stream().filter(predicate).toList(); } - } diff --git a/filterer/src/main/java/com/iluwatar/filterer/threat/Threat.java b/filterer/src/main/java/com/iluwatar/filterer/threat/Threat.java index f8aff1c84..1a138956d 100644 --- a/filterer/src/main/java/com/iluwatar/filterer/threat/Threat.java +++ b/filterer/src/main/java/com/iluwatar/filterer/threat/Threat.java @@ -24,9 +24,7 @@ */ package com.iluwatar.filterer.threat; -/** - * Represents a threat that can be detected in given system. - */ +/** Represents a threat that can be detected in given system. */ public interface Threat { /** * Returns name of the threat. @@ -44,6 +42,7 @@ public interface Threat { /** * Returns threat type. + * * @return {@link ThreatType} */ ThreatType type(); diff --git a/filterer/src/main/java/com/iluwatar/filterer/threat/ThreatAwareSystem.java b/filterer/src/main/java/com/iluwatar/filterer/threat/ThreatAwareSystem.java index c0de663d3..49ef8560f 100644 --- a/filterer/src/main/java/com/iluwatar/filterer/threat/ThreatAwareSystem.java +++ b/filterer/src/main/java/com/iluwatar/filterer/threat/ThreatAwareSystem.java @@ -27,9 +27,7 @@ package com.iluwatar.filterer.threat; import com.iluwatar.filterer.domain.Filterer; import java.util.List; -/** - * Represents system that is aware of threats that are present in it. - */ +/** Represents system that is aware of threats that are present in it. */ public interface ThreatAwareSystem { /** @@ -41,15 +39,16 @@ public interface ThreatAwareSystem { /** * Returns list of threats for this system. + * * @return list of threats for this system. */ List threats(); /** - * Returns the instance of {@link Filterer} helper interface that allows to covariantly - * specify lower bound for predicate that we want to filter by. + * Returns the instance of {@link Filterer} helper interface that allows to covariantly specify + * lower bound for predicate that we want to filter by. + * * @return an instance of {@link Filterer} helper interface. */ Filterer, T> filtered(); - } diff --git a/filterer/src/main/java/com/iluwatar/filterer/threat/ThreatType.java b/filterer/src/main/java/com/iluwatar/filterer/threat/ThreatType.java index 72293ce13..30dcaefa1 100644 --- a/filterer/src/main/java/com/iluwatar/filterer/threat/ThreatType.java +++ b/filterer/src/main/java/com/iluwatar/filterer/threat/ThreatType.java @@ -24,9 +24,7 @@ */ package com.iluwatar.filterer.threat; -/** - * Enum class representing Threat types. - */ +/** Enum class representing Threat types. */ public enum ThreatType { TROJAN, WORM, diff --git a/filterer/src/test/java/com/iluwatar/filterer/AppTest.java b/filterer/src/test/java/com/iluwatar/filterer/AppTest.java index 7885feefd..a35f03ea5 100644 --- a/filterer/src/test/java/com/iluwatar/filterer/AppTest.java +++ b/filterer/src/test/java/com/iluwatar/filterer/AppTest.java @@ -32,6 +32,6 @@ class AppTest { @Test void shouldLaunchApp() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } -} \ No newline at end of file +} diff --git a/filterer/src/test/java/com/iluwatar/filterer/threat/SimpleProbabilisticThreatAwareSystemTest.java b/filterer/src/test/java/com/iluwatar/filterer/threat/SimpleProbabilisticThreatAwareSystemTest.java index bf5a3ed39..3705009f1 100644 --- a/filterer/src/test/java/com/iluwatar/filterer/threat/SimpleProbabilisticThreatAwareSystemTest.java +++ b/filterer/src/test/java/com/iluwatar/filterer/threat/SimpleProbabilisticThreatAwareSystemTest.java @@ -33,7 +33,7 @@ class SimpleProbabilisticThreatAwareSystemTest { @Test void shouldFilterByProbability() { - //given + // given var trojan = new SimpleProbableThreat("Troyan-ArcBomb", 1, ThreatType.TROJAN, 0.99); var rootkit = new SimpleProbableThreat("Rootkit-System", 2, ThreatType.ROOTKIT, 0.8); List probableThreats = List.of(trojan, rootkit); @@ -41,12 +41,14 @@ class SimpleProbabilisticThreatAwareSystemTest { var simpleProbabilisticThreatAwareSystem = new SimpleProbabilisticThreatAwareSystem("System-1", probableThreats); - //when - var filtered = simpleProbabilisticThreatAwareSystem.filtered() - .by(probableThreat -> Double.compare(probableThreat.probability(), 0.99) == 0); + // when + var filtered = + simpleProbabilisticThreatAwareSystem + .filtered() + .by(probableThreat -> Double.compare(probableThreat.probability(), 0.99) == 0); - //then + // then assertEquals(filtered.threats().size(), 1); assertEquals(filtered.threats().get(0), trojan); } -} \ No newline at end of file +} diff --git a/filterer/src/test/java/com/iluwatar/filterer/threat/SimpleThreatAwareSystemTest.java b/filterer/src/test/java/com/iluwatar/filterer/threat/SimpleThreatAwareSystemTest.java index cc0d696f1..d763edbf3 100644 --- a/filterer/src/test/java/com/iluwatar/filterer/threat/SimpleThreatAwareSystemTest.java +++ b/filterer/src/test/java/com/iluwatar/filterer/threat/SimpleThreatAwareSystemTest.java @@ -32,18 +32,18 @@ import org.junit.jupiter.api.Test; class SimpleThreatAwareSystemTest { @Test void shouldFilterByThreatType() { - //given + // given var rootkit = new SimpleThreat(ThreatType.ROOTKIT, 1, "Simple-Rootkit"); var trojan = new SimpleThreat(ThreatType.TROJAN, 2, "Simple-Trojan"); List threats = List.of(rootkit, trojan); var threatAwareSystem = new SimpleThreatAwareSystem("System-1", threats); - //when - var rootkitThreatAwareSystem = threatAwareSystem.filtered() - .by(threat -> threat.type() == ThreatType.ROOTKIT); + // when + var rootkitThreatAwareSystem = + threatAwareSystem.filtered().by(threat -> threat.type() == ThreatType.ROOTKIT); - //then + // then assertEquals(rootkitThreatAwareSystem.threats().size(), 1); assertEquals(rootkitThreatAwareSystem.threats().get(0), rootkit); } diff --git a/fluent-interface/pom.xml b/fluent-interface/pom.xml index 94aa25999..005fa9f7b 100644 --- a/fluent-interface/pom.xml +++ b/fluent-interface/pom.xml @@ -34,6 +34,14 @@ 4.0.0 fluent-interface + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/fluent-interface/src/main/java/com/iluwatar/fluentinterface/app/App.java b/fluent-interface/src/main/java/com/iluwatar/fluentinterface/app/App.java index b51f5839a..a36bef68b 100644 --- a/fluent-interface/src/main/java/com/iluwatar/fluentinterface/app/App.java +++ b/fluent-interface/src/main/java/com/iluwatar/fluentinterface/app/App.java @@ -47,57 +47,46 @@ import lombok.extern.slf4j.Slf4j; @Slf4j public class App { - /** - * Program entry point. - */ + /** Program entry point. */ public static void main(String[] args) { var integerList = List.of(1, -61, 14, -22, 18, -87, 6, 64, -82, 26, -98, 97, 45, 23, 2, -68); prettyPrint("The initial list contains: ", integerList); - var firstFiveNegatives = SimpleFluentIterable - .fromCopyOf(integerList) - .filter(negatives()) - .first(3) - .asList(); + var firstFiveNegatives = + SimpleFluentIterable.fromCopyOf(integerList).filter(negatives()).first(3).asList(); prettyPrint("The first three negative values are: ", firstFiveNegatives); - - var lastTwoPositives = SimpleFluentIterable - .fromCopyOf(integerList) - .filter(positives()) - .last(2) - .asList(); + var lastTwoPositives = + SimpleFluentIterable.fromCopyOf(integerList).filter(positives()).last(2).asList(); prettyPrint("The last two positive values are: ", lastTwoPositives); - SimpleFluentIterable - .fromCopyOf(integerList) + SimpleFluentIterable.fromCopyOf(integerList) .filter(number -> number % 2 == 0) .first() .ifPresent(evenNumber -> LOGGER.info("The first even number is: {}", evenNumber)); - - var transformedList = SimpleFluentIterable - .fromCopyOf(integerList) - .filter(negatives()) - .map(transformToString()) - .asList(); + var transformedList = + SimpleFluentIterable.fromCopyOf(integerList) + .filter(negatives()) + .map(transformToString()) + .asList(); prettyPrint("A string-mapped list of negative numbers contains: ", transformedList); + var lastTwoOfFirstFourStringMapped = + LazyFluentIterable.from(integerList) + .filter(positives()) + .first(4) + .last(2) + .map(number -> "String[" + number + "]") + .asList(); + prettyPrint( + "The lazy list contains the last two of the first four positive numbers " + + "mapped to Strings: ", + lastTwoOfFirstFourStringMapped); - var lastTwoOfFirstFourStringMapped = LazyFluentIterable - .from(integerList) - .filter(positives()) - .first(4) - .last(2) - .map(number -> "String[" + number + "]") - .asList(); - prettyPrint("The lazy list contains the last two of the first four positive numbers " - + "mapped to Strings: ", lastTwoOfFirstFourStringMapped); - - LazyFluentIterable - .from(integerList) + LazyFluentIterable.from(integerList) .filter(negatives()) .first(2) .last() @@ -120,10 +109,7 @@ public class App { prettyPrint(", ", prefix, iterable); } - private static void prettyPrint( - String delimiter, String prefix, - Iterable iterable - ) { + private static void prettyPrint(String delimiter, String prefix, Iterable iterable) { var joiner = new StringJoiner(delimiter, prefix, "."); iterable.forEach(e -> joiner.add(e.toString())); LOGGER.info(joiner.toString()); diff --git a/fluent-interface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/FluentIterable.java b/fluent-interface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/FluentIterable.java index d97289e78..2ab128afa 100644 --- a/fluent-interface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/FluentIterable.java +++ b/fluent-interface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/FluentIterable.java @@ -44,7 +44,7 @@ public interface FluentIterable extends Iterable { * the predicate. * * @param predicate the condition to test with for the filtering. If the test is negative, the - * tested object is removed by the iterator. + * tested object is removed by the iterator. * @return a filtered FluentIterable */ FluentIterable filter(Predicate predicate); @@ -82,7 +82,7 @@ public interface FluentIterable extends Iterable { * Transforms this FluentIterable into a new one containing objects of the type T. * * @param function a function that transforms an instance of E into an instance of T - * @param the target type of the transformation + * @param the target type of the transformation * @return a new FluentIterable of the new type */ FluentIterable map(Function function); @@ -98,7 +98,7 @@ public interface FluentIterable extends Iterable { * Utility method that iterates over iterable and adds the contents to a list. * * @param iterable the iterable to collect - * @param the type of the objects to iterate + * @param the type of the objects to iterate * @return a list with all objects of the given iterator */ static List copyToList(Iterable iterable) { diff --git a/fluent-interface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/lazy/DecoratingIterator.java b/fluent-interface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/lazy/DecoratingIterator.java index aaf00b935..12a0304a8 100644 --- a/fluent-interface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/lazy/DecoratingIterator.java +++ b/fluent-interface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/lazy/DecoratingIterator.java @@ -38,9 +38,7 @@ public abstract class DecoratingIterator implements Iterator { private E next; - /** - * Creates an iterator that decorates the given iterator. - */ + /** Creates an iterator that decorates the given iterator. */ public DecoratingIterator(Iterator fromIterator) { this.fromIterator = fromIterator; } diff --git a/fluent-interface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/lazy/LazyFluentIterable.java b/fluent-interface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/lazy/LazyFluentIterable.java index f624179e0..971ac9a02 100644 --- a/fluent-interface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/lazy/LazyFluentIterable.java +++ b/fluent-interface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/lazy/LazyFluentIterable.java @@ -44,9 +44,7 @@ public class LazyFluentIterable implements FluentIterable { private final Iterable iterable; - /** - * This constructor can be used to implement anonymous subclasses of the LazyFluentIterable. - */ + /** This constructor can be used to implement anonymous subclasses of the LazyFluentIterable. */ protected LazyFluentIterable() { iterable = this; } @@ -56,7 +54,7 @@ public class LazyFluentIterable implements FluentIterable { * the predicate. * * @param predicate the condition to test with for the filtering. If the test is negative, the - * tested object is removed by the iterator. + * tested object is removed by the iterator. * @return a new FluentIterable object that decorates the source iterable */ @Override @@ -183,7 +181,7 @@ public class LazyFluentIterable implements FluentIterable { * Transforms this FluentIterable into a new one containing objects of the type T. * * @param function a function that transforms an instance of E into an instance of T - * @param the target type of the transformation + * @param the target type of the transformation * @return a new FluentIterable of the new type */ @Override @@ -236,5 +234,4 @@ public class LazyFluentIterable implements FluentIterable { public static FluentIterable from(Iterable iterable) { return new LazyFluentIterable<>(iterable); } - } diff --git a/fluent-interface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/simple/SimpleFluentIterable.java b/fluent-interface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/simple/SimpleFluentIterable.java index b3c912f1f..a44cfb44c 100644 --- a/fluent-interface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/simple/SimpleFluentIterable.java +++ b/fluent-interface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/simple/SimpleFluentIterable.java @@ -51,7 +51,7 @@ public class SimpleFluentIterable implements FluentIterable { * the predicate. * * @param predicate the condition to test with for the filtering. If the test is negative, the - * tested object is removed by the iterator. + * tested object is removed by the iterator. * @return the same FluentIterable with a filtered collection */ @Override @@ -139,7 +139,7 @@ public class SimpleFluentIterable implements FluentIterable { * Transforms this FluentIterable into a new one containing objects of the type T. * * @param function a function that transforms an instance of E into an instance of T - * @param the target type of the transformation + * @param the target type of the transformation * @return a new FluentIterable of the new type */ @Override @@ -183,7 +183,6 @@ public class SimpleFluentIterable implements FluentIterable { iterable.forEach(action); } - @Override public Spliterator spliterator() { return iterable.spliterator(); diff --git a/fluent-interface/src/test/java/com/iluwatar/fluentinterface/app/AppTest.java b/fluent-interface/src/test/java/com/iluwatar/fluentinterface/app/AppTest.java index d637923dc..003e4a12c 100644 --- a/fluent-interface/src/test/java/com/iluwatar/fluentinterface/app/AppTest.java +++ b/fluent-interface/src/test/java/com/iluwatar/fluentinterface/app/AppTest.java @@ -24,17 +24,15 @@ */ package com.iluwatar.fluentinterface.app; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -/** - * Application Test Entry - */ +import org.junit.jupiter.api.Test; + +/** Application Test Entry */ class AppTest { @Test void shouldExecuteWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/fluent-interface/src/test/java/com/iluwatar/fluentinterface/fluentiterable/FluentIterableTest.java b/fluent-interface/src/test/java/com/iluwatar/fluentinterface/fluentiterable/FluentIterableTest.java index e1e0b6291..d85b64109 100644 --- a/fluent-interface/src/test/java/com/iluwatar/fluentinterface/fluentiterable/FluentIterableTest.java +++ b/fluent-interface/src/test/java/com/iluwatar/fluentinterface/fluentiterable/FluentIterableTest.java @@ -38,10 +38,7 @@ import java.util.List; import java.util.function.Consumer; import org.junit.jupiter.api.Test; -/** - * FluentIterableTest - * - */ +/** FluentIterableTest */ public abstract class FluentIterableTest { /** @@ -72,9 +69,7 @@ public abstract class FluentIterableTest { @Test void testFirstCount() { final var integers = List.of(1, 2, 3, 10, 9, 8); - final var first4 = createFluentIterable(integers) - .first(4) - .asList(); + final var first4 = createFluentIterable(integers).first(4).asList(); assertNotNull(first4); assertEquals(4, first4.size()); @@ -88,9 +83,7 @@ public abstract class FluentIterableTest { @Test void testFirstCountLessItems() { final var integers = List.of(1, 2, 3); - final var first4 = createFluentIterable(integers) - .first(4) - .asList(); + final var first4 = createFluentIterable(integers).first(4).asList(); assertNotNull(first4); assertEquals(3, first4.size()); @@ -120,9 +113,7 @@ public abstract class FluentIterableTest { @Test void testLastCount() { final var integers = List.of(1, 2, 3, 10, 9, 8); - final var last4 = createFluentIterable(integers) - .last(4) - .asList(); + final var last4 = createFluentIterable(integers).last(4).asList(); assertNotNull(last4); assertEquals(4, last4.size()); @@ -135,9 +126,7 @@ public abstract class FluentIterableTest { @Test void testLastCountLessItems() { final var integers = List.of(1, 2, 3); - final var last4 = createFluentIterable(integers) - .last(4) - .asList(); + final var last4 = createFluentIterable(integers).last(4).asList(); assertNotNull(last4); assertEquals(3, last4.size()); @@ -150,9 +139,7 @@ public abstract class FluentIterableTest { @Test void testFilter() { final var integers = List.of(1, 2, 3, 10, 9, 8); - final var evenItems = createFluentIterable(integers) - .filter(i -> i % 2 == 0) - .asList(); + final var evenItems = createFluentIterable(integers).filter(i -> i % 2 == 0).asList(); assertNotNull(evenItems); assertEquals(3, evenItems.size()); @@ -164,9 +151,7 @@ public abstract class FluentIterableTest { @Test void testMap() { final var integers = List.of(1, 2, 3); - final var longs = createFluentIterable(integers) - .map(Integer::longValue) - .asList(); + final var longs = createFluentIterable(integers).map(Integer::longValue).asList(); assertNotNull(longs); assertEquals(integers.size(), longs.size()); @@ -186,7 +171,6 @@ public abstract class FluentIterableTest { verify(consumer, times(1)).accept(2); verify(consumer, times(1)).accept(3); verifyNoMoreInteractions(consumer); - } @Test @@ -195,5 +179,4 @@ public abstract class FluentIterableTest { final var split = createFluentIterable(integers).spliterator(); assertNotNull(split); } - -} \ No newline at end of file +} diff --git a/fluent-interface/src/test/java/com/iluwatar/fluentinterface/fluentiterable/lazy/LazyFluentIterableTest.java b/fluent-interface/src/test/java/com/iluwatar/fluentinterface/fluentiterable/lazy/LazyFluentIterableTest.java index e0f3dcd4d..2db7ef534 100644 --- a/fluent-interface/src/test/java/com/iluwatar/fluentinterface/fluentiterable/lazy/LazyFluentIterableTest.java +++ b/fluent-interface/src/test/java/com/iluwatar/fluentinterface/fluentiterable/lazy/LazyFluentIterableTest.java @@ -27,15 +27,11 @@ package com.iluwatar.fluentinterface.fluentiterable.lazy; import com.iluwatar.fluentinterface.fluentiterable.FluentIterable; import com.iluwatar.fluentinterface.fluentiterable.FluentIterableTest; -/** - * LazyFluentIterableTest - * - */ +/** LazyFluentIterableTest */ class LazyFluentIterableTest extends FluentIterableTest { @Override protected FluentIterable createFluentIterable(Iterable integers) { return LazyFluentIterable.from(integers); } - } diff --git a/fluent-interface/src/test/java/com/iluwatar/fluentinterface/fluentiterable/simple/SimpleFluentIterableTest.java b/fluent-interface/src/test/java/com/iluwatar/fluentinterface/fluentiterable/simple/SimpleFluentIterableTest.java index 5903d1af1..5b1cc374d 100644 --- a/fluent-interface/src/test/java/com/iluwatar/fluentinterface/fluentiterable/simple/SimpleFluentIterableTest.java +++ b/fluent-interface/src/test/java/com/iluwatar/fluentinterface/fluentiterable/simple/SimpleFluentIterableTest.java @@ -27,15 +27,11 @@ package com.iluwatar.fluentinterface.fluentiterable.simple; import com.iluwatar.fluentinterface.fluentiterable.FluentIterable; import com.iluwatar.fluentinterface.fluentiterable.FluentIterableTest; -/** - * SimpleFluentIterableTest - * - */ +/** SimpleFluentIterableTest */ class SimpleFluentIterableTest extends FluentIterableTest { @Override protected FluentIterable createFluentIterable(Iterable integers) { return SimpleFluentIterable.fromCopyOf(integers); } - } diff --git a/flux/pom.xml b/flux/pom.xml index 2b8588884..f0259126d 100644 --- a/flux/pom.xml +++ b/flux/pom.xml @@ -34,6 +34,14 @@ flux + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/flux/src/main/java/com/iluwatar/flux/action/Action.java b/flux/src/main/java/com/iluwatar/flux/action/Action.java index e493d04df..cf59d5ad9 100644 --- a/flux/src/main/java/com/iluwatar/flux/action/Action.java +++ b/flux/src/main/java/com/iluwatar/flux/action/Action.java @@ -27,13 +27,10 @@ package com.iluwatar.flux.action; import lombok.Getter; import lombok.RequiredArgsConstructor; -/** - * Action is the data payload dispatched to the stores when something happens. - */ +/** Action is the data payload dispatched to the stores when something happens. */ @RequiredArgsConstructor @Getter public abstract class Action { private final ActionType type; - } diff --git a/flux/src/main/java/com/iluwatar/flux/action/ActionType.java b/flux/src/main/java/com/iluwatar/flux/action/ActionType.java index a8206972e..9665959d0 100644 --- a/flux/src/main/java/com/iluwatar/flux/action/ActionType.java +++ b/flux/src/main/java/com/iluwatar/flux/action/ActionType.java @@ -24,12 +24,8 @@ */ package com.iluwatar.flux.action; -/** - * Types of actions. - */ +/** Types of actions. */ public enum ActionType { - MENU_ITEM_SELECTED, CONTENT_CHANGED - } diff --git a/flux/src/main/java/com/iluwatar/flux/action/Content.java b/flux/src/main/java/com/iluwatar/flux/action/Content.java index d17aed00a..124e8f9ed 100644 --- a/flux/src/main/java/com/iluwatar/flux/action/Content.java +++ b/flux/src/main/java/com/iluwatar/flux/action/Content.java @@ -26,12 +26,9 @@ package com.iluwatar.flux.action; import lombok.RequiredArgsConstructor; -/** - * Content items. - */ +/** Content items. */ @RequiredArgsConstructor public enum Content { - PRODUCTS("Products - This page lists the company's products."), COMPANY("Company - This page displays information about the company."); diff --git a/flux/src/main/java/com/iluwatar/flux/action/ContentAction.java b/flux/src/main/java/com/iluwatar/flux/action/ContentAction.java index 67afc3f2f..fb3020dfa 100644 --- a/flux/src/main/java/com/iluwatar/flux/action/ContentAction.java +++ b/flux/src/main/java/com/iluwatar/flux/action/ContentAction.java @@ -26,13 +26,10 @@ package com.iluwatar.flux.action; import lombok.Getter; -/** - * ContentAction is a concrete action. - */ +/** ContentAction is a concrete action. */ public class ContentAction extends Action { - @Getter - private final Content content; + @Getter private final Content content; public ContentAction(Content content) { super(ActionType.CONTENT_CHANGED); diff --git a/flux/src/main/java/com/iluwatar/flux/action/MenuAction.java b/flux/src/main/java/com/iluwatar/flux/action/MenuAction.java index 5ad3ca43b..81e52213d 100644 --- a/flux/src/main/java/com/iluwatar/flux/action/MenuAction.java +++ b/flux/src/main/java/com/iluwatar/flux/action/MenuAction.java @@ -24,16 +24,12 @@ */ package com.iluwatar.flux.action; - import lombok.Getter; -/** - * MenuAction is a concrete action. - */ +/** MenuAction is a concrete action. */ public class MenuAction extends Action { - @Getter - private final MenuItem menuItem; + @Getter private final MenuItem menuItem; public MenuAction(MenuItem menuItem) { super(ActionType.MENU_ITEM_SELECTED); diff --git a/flux/src/main/java/com/iluwatar/flux/action/MenuItem.java b/flux/src/main/java/com/iluwatar/flux/action/MenuItem.java index 70aabe566..cc8087077 100644 --- a/flux/src/main/java/com/iluwatar/flux/action/MenuItem.java +++ b/flux/src/main/java/com/iluwatar/flux/action/MenuItem.java @@ -24,12 +24,11 @@ */ package com.iluwatar.flux.action; -/** - * Menu items. - */ +/** Menu items. */ public enum MenuItem { - - HOME("Home"), PRODUCTS("Products"), COMPANY("Company"); + HOME("Home"), + PRODUCTS("Products"), + COMPANY("Company"); private final String title; diff --git a/flux/src/main/java/com/iluwatar/flux/dispatcher/Dispatcher.java b/flux/src/main/java/com/iluwatar/flux/dispatcher/Dispatcher.java index 47a656e89..ca087dd42 100644 --- a/flux/src/main/java/com/iluwatar/flux/dispatcher/Dispatcher.java +++ b/flux/src/main/java/com/iluwatar/flux/dispatcher/Dispatcher.java @@ -34,26 +34,20 @@ import java.util.LinkedList; import java.util.List; import lombok.Getter; -/** - * Dispatcher sends Actions to registered Stores. - */ +/** Dispatcher sends Actions to registered Stores. */ public final class Dispatcher { - @Getter - private static Dispatcher instance = new Dispatcher(); + @Getter private static Dispatcher instance = new Dispatcher(); private final List stores = new LinkedList<>(); - private Dispatcher() { - } + private Dispatcher() {} public void registerStore(Store store) { stores.add(store); } - /** - * Menu item selected handler. - */ + /** Menu item selected handler. */ public void menuItemSelected(MenuItem menuItem) { dispatchAction(new MenuAction(menuItem)); if (menuItem == MenuItem.COMPANY) { diff --git a/flux/src/main/java/com/iluwatar/flux/store/ContentStore.java b/flux/src/main/java/com/iluwatar/flux/store/ContentStore.java index 9a2e7bd9b..b26146d52 100644 --- a/flux/src/main/java/com/iluwatar/flux/store/ContentStore.java +++ b/flux/src/main/java/com/iluwatar/flux/store/ContentStore.java @@ -30,13 +30,10 @@ import com.iluwatar.flux.action.Content; import com.iluwatar.flux.action.ContentAction; import lombok.Getter; -/** - * ContentStore is a concrete store. - */ +/** ContentStore is a concrete store. */ public class ContentStore extends Store { - @Getter - private Content content = Content.PRODUCTS; + @Getter private Content content = Content.PRODUCTS; @Override public void onAction(Action action) { diff --git a/flux/src/main/java/com/iluwatar/flux/store/MenuStore.java b/flux/src/main/java/com/iluwatar/flux/store/MenuStore.java index 9a0732f0e..c0d8d8255 100644 --- a/flux/src/main/java/com/iluwatar/flux/store/MenuStore.java +++ b/flux/src/main/java/com/iluwatar/flux/store/MenuStore.java @@ -30,13 +30,10 @@ import com.iluwatar.flux.action.MenuAction; import com.iluwatar.flux.action.MenuItem; import lombok.Getter; -/** - * MenuStore is a concrete store. - */ +/** MenuStore is a concrete store. */ public class MenuStore extends Store { - @Getter - private MenuItem selected = MenuItem.HOME; + @Getter private MenuItem selected = MenuItem.HOME; @Override public void onAction(Action action) { diff --git a/flux/src/main/java/com/iluwatar/flux/store/Store.java b/flux/src/main/java/com/iluwatar/flux/store/Store.java index 313635bd6..879ae65d2 100644 --- a/flux/src/main/java/com/iluwatar/flux/store/Store.java +++ b/flux/src/main/java/com/iluwatar/flux/store/Store.java @@ -29,9 +29,7 @@ import com.iluwatar.flux.view.View; import java.util.LinkedList; import java.util.List; -/** - * Store is a data model. - */ +/** Store is a data model. */ public abstract class Store { private final List views = new LinkedList<>(); diff --git a/flux/src/main/java/com/iluwatar/flux/view/ContentView.java b/flux/src/main/java/com/iluwatar/flux/view/ContentView.java index 7f01daadb..66befdf78 100644 --- a/flux/src/main/java/com/iluwatar/flux/view/ContentView.java +++ b/flux/src/main/java/com/iluwatar/flux/view/ContentView.java @@ -29,9 +29,7 @@ import com.iluwatar.flux.store.ContentStore; import com.iluwatar.flux.store.Store; import lombok.extern.slf4j.Slf4j; -/** - * ContentView is a concrete view. - */ +/** ContentView is a concrete view. */ @Slf4j public class ContentView implements View { diff --git a/flux/src/main/java/com/iluwatar/flux/view/MenuView.java b/flux/src/main/java/com/iluwatar/flux/view/MenuView.java index 378c9ed50..74ae5192b 100644 --- a/flux/src/main/java/com/iluwatar/flux/view/MenuView.java +++ b/flux/src/main/java/com/iluwatar/flux/view/MenuView.java @@ -30,9 +30,7 @@ import com.iluwatar.flux.store.MenuStore; import com.iluwatar.flux.store.Store; import lombok.extern.slf4j.Slf4j; -/** - * MenuView is a concrete view. - */ +/** MenuView is a concrete view. */ @Slf4j public class MenuView implements View { diff --git a/flux/src/main/java/com/iluwatar/flux/view/View.java b/flux/src/main/java/com/iluwatar/flux/view/View.java index 6e6a7cd59..b31b20c18 100644 --- a/flux/src/main/java/com/iluwatar/flux/view/View.java +++ b/flux/src/main/java/com/iluwatar/flux/view/View.java @@ -26,9 +26,7 @@ package com.iluwatar.flux.view; import com.iluwatar.flux.store.Store; -/** - * Views define the representation of data. - */ +/** Views define the representation of data. */ public interface View { void storeChanged(Store store); diff --git a/flux/src/test/java/com/iluwatar/flux/action/ContentTest.java b/flux/src/test/java/com/iluwatar/flux/action/ContentTest.java index 5e58e166f..8263468c9 100644 --- a/flux/src/test/java/com/iluwatar/flux/action/ContentTest.java +++ b/flux/src/test/java/com/iluwatar/flux/action/ContentTest.java @@ -29,10 +29,7 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import org.junit.jupiter.api.Test; -/** - * ContentTest - * - */ +/** ContentTest */ class ContentTest { @Test @@ -43,5 +40,4 @@ class ContentTest { assertFalse(toString.trim().isEmpty()); } } - } diff --git a/flux/src/test/java/com/iluwatar/flux/action/MenuItemTest.java b/flux/src/test/java/com/iluwatar/flux/action/MenuItemTest.java index f0e2d4690..bf012abee 100644 --- a/flux/src/test/java/com/iluwatar/flux/action/MenuItemTest.java +++ b/flux/src/test/java/com/iluwatar/flux/action/MenuItemTest.java @@ -29,10 +29,7 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import org.junit.jupiter.api.Test; -/** - * MenuItemTest - * - */ +/** MenuItemTest */ class MenuItemTest { @Test @@ -43,5 +40,4 @@ class MenuItemTest { assertFalse(toString.trim().isEmpty()); } } - } diff --git a/flux/src/test/java/com/iluwatar/flux/app/AppTest.java b/flux/src/test/java/com/iluwatar/flux/app/AppTest.java index 0fc0049fc..c594a1efb 100644 --- a/flux/src/test/java/com/iluwatar/flux/app/AppTest.java +++ b/flux/src/test/java/com/iluwatar/flux/app/AppTest.java @@ -24,17 +24,15 @@ */ package com.iluwatar.flux.app; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -/** - * Application test - */ +import org.junit.jupiter.api.Test; + +/** Application test */ class AppTest { @Test void shouldExecuteWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/flux/src/test/java/com/iluwatar/flux/dispatcher/DispatcherTest.java b/flux/src/test/java/com/iluwatar/flux/dispatcher/DispatcherTest.java index 8cb3e92ef..b45de5992 100644 --- a/flux/src/test/java/com/iluwatar/flux/dispatcher/DispatcherTest.java +++ b/flux/src/test/java/com/iluwatar/flux/dispatcher/DispatcherTest.java @@ -43,10 +43,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; -/** - * DispatcherTest - * - */ +/** DispatcherTest */ class DispatcherTest { /** @@ -85,28 +82,37 @@ class DispatcherTest { verifyNoMoreInteractions(store); final var actions = actionCaptor.getAllValues(); - final var menuActions = actions.stream() - .filter(a -> a.getType().equals(ActionType.MENU_ITEM_SELECTED)) - .map(a -> (MenuAction) a) - .toList(); + final var menuActions = + actions.stream() + .filter(a -> a.getType().equals(ActionType.MENU_ITEM_SELECTED)) + .map(a -> (MenuAction) a) + .toList(); - final var contentActions = actions.stream() - .filter(a -> a.getType().equals(ActionType.CONTENT_CHANGED)) - .map(a -> (ContentAction) a) - .toList(); + final var contentActions = + actions.stream() + .filter(a -> a.getType().equals(ActionType.CONTENT_CHANGED)) + .map(a -> (ContentAction) a) + .toList(); assertEquals(2, menuActions.size()); - assertEquals(1, menuActions.stream().map(MenuAction::getMenuItem).filter(MenuItem.HOME::equals) - .count()); - assertEquals(1, menuActions.stream().map(MenuAction::getMenuItem) - .filter(MenuItem.COMPANY::equals).count()); + assertEquals( + 1, menuActions.stream().map(MenuAction::getMenuItem).filter(MenuItem.HOME::equals).count()); + assertEquals( + 1, + menuActions.stream().map(MenuAction::getMenuItem).filter(MenuItem.COMPANY::equals).count()); assertEquals(2, contentActions.size()); - assertEquals(1, contentActions.stream().map(ContentAction::getContent) - .filter(Content.PRODUCTS::equals).count()); - assertEquals(1, contentActions.stream().map(ContentAction::getContent) - .filter(Content.COMPANY::equals).count()); - + assertEquals( + 1, + contentActions.stream() + .map(ContentAction::getContent) + .filter(Content.PRODUCTS::equals) + .count()); + assertEquals( + 1, + contentActions.stream() + .map(ContentAction::getContent) + .filter(Content.COMPANY::equals) + .count()); } - } diff --git a/flux/src/test/java/com/iluwatar/flux/store/ContentStoreTest.java b/flux/src/test/java/com/iluwatar/flux/store/ContentStoreTest.java index 0297899f0..6d6270ddb 100644 --- a/flux/src/test/java/com/iluwatar/flux/store/ContentStoreTest.java +++ b/flux/src/test/java/com/iluwatar/flux/store/ContentStoreTest.java @@ -38,10 +38,7 @@ import com.iluwatar.flux.action.MenuItem; import com.iluwatar.flux.view.View; import org.junit.jupiter.api.Test; -/** - * ContentStoreTest - * - */ +/** ContentStoreTest */ class ContentStoreTest { @Test @@ -62,7 +59,5 @@ class ContentStoreTest { verify(view, times(1)).storeChanged(eq(contentStore)); verifyNoMoreInteractions(view); assertEquals(Content.COMPANY, contentStore.getContent()); - } - } diff --git a/flux/src/test/java/com/iluwatar/flux/store/MenuStoreTest.java b/flux/src/test/java/com/iluwatar/flux/store/MenuStoreTest.java index d39394e96..368307602 100644 --- a/flux/src/test/java/com/iluwatar/flux/store/MenuStoreTest.java +++ b/flux/src/test/java/com/iluwatar/flux/store/MenuStoreTest.java @@ -38,10 +38,7 @@ import com.iluwatar.flux.action.MenuItem; import com.iluwatar.flux.view.View; import org.junit.jupiter.api.Test; -/** - * MenuStoreTest - * - */ +/** MenuStoreTest */ class MenuStoreTest { @Test @@ -62,7 +59,5 @@ class MenuStoreTest { verify(view, times(1)).storeChanged(eq(menuStore)); verifyNoMoreInteractions(view); assertEquals(MenuItem.PRODUCTS, menuStore.getSelected()); - } - } diff --git a/flux/src/test/java/com/iluwatar/flux/view/ContentViewTest.java b/flux/src/test/java/com/iluwatar/flux/view/ContentViewTest.java index 619b8d202..a6b91a95b 100644 --- a/flux/src/test/java/com/iluwatar/flux/view/ContentViewTest.java +++ b/flux/src/test/java/com/iluwatar/flux/view/ContentViewTest.java @@ -34,10 +34,7 @@ import com.iluwatar.flux.action.Content; import com.iluwatar.flux.store.ContentStore; import org.junit.jupiter.api.Test; -/** - * ContentViewTest - * - */ +/** ContentViewTest */ class ContentViewTest { @Test @@ -51,5 +48,4 @@ class ContentViewTest { verify(store, times(1)).getContent(); verifyNoMoreInteractions(store); } - } diff --git a/flux/src/test/java/com/iluwatar/flux/view/MenuViewTest.java b/flux/src/test/java/com/iluwatar/flux/view/MenuViewTest.java index 8b3f6cc60..8fda7e47a 100644 --- a/flux/src/test/java/com/iluwatar/flux/view/MenuViewTest.java +++ b/flux/src/test/java/com/iluwatar/flux/view/MenuViewTest.java @@ -38,10 +38,7 @@ import com.iluwatar.flux.store.MenuStore; import com.iluwatar.flux.store.Store; import org.junit.jupiter.api.Test; -/** - * MenuViewTest - * - */ +/** MenuViewTest */ class MenuViewTest { @Test @@ -66,7 +63,5 @@ class MenuViewTest { // We should receive a menu click action and a content changed action verify(store, times(2)).onAction(any(Action.class)); - } - } diff --git a/flyweight/pom.xml b/flyweight/pom.xml index 9f3a9672c..26bc01369 100644 --- a/flyweight/pom.xml +++ b/flyweight/pom.xml @@ -34,6 +34,14 @@ flyweight + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/flyweight/src/main/java/com/iluwatar/flyweight/AlchemistShop.java b/flyweight/src/main/java/com/iluwatar/flyweight/AlchemistShop.java index 05e1a48b4..42ce63c8e 100644 --- a/flyweight/src/main/java/com/iluwatar/flyweight/AlchemistShop.java +++ b/flyweight/src/main/java/com/iluwatar/flyweight/AlchemistShop.java @@ -27,37 +27,33 @@ package com.iluwatar.flyweight; import java.util.List; import lombok.extern.slf4j.Slf4j; -/** - * AlchemistShop holds potions on its shelves. It uses PotionFactory to provide the potions. - */ +/** AlchemistShop holds potions on its shelves. It uses PotionFactory to provide the potions. */ @Slf4j public class AlchemistShop { private final List topShelf; private final List bottomShelf; - /** - * Constructor. - */ + /** Constructor. */ public AlchemistShop() { var factory = new PotionFactory(); - topShelf = List.of( - factory.createPotion(PotionType.INVISIBILITY), - factory.createPotion(PotionType.INVISIBILITY), - factory.createPotion(PotionType.STRENGTH), - factory.createPotion(PotionType.HEALING), - factory.createPotion(PotionType.INVISIBILITY), - factory.createPotion(PotionType.STRENGTH), - factory.createPotion(PotionType.HEALING), - factory.createPotion(PotionType.HEALING) - ); - bottomShelf = List.of( - factory.createPotion(PotionType.POISON), - factory.createPotion(PotionType.POISON), - factory.createPotion(PotionType.POISON), - factory.createPotion(PotionType.HOLY_WATER), - factory.createPotion(PotionType.HOLY_WATER) - ); + topShelf = + List.of( + factory.createPotion(PotionType.INVISIBILITY), + factory.createPotion(PotionType.INVISIBILITY), + factory.createPotion(PotionType.STRENGTH), + factory.createPotion(PotionType.HEALING), + factory.createPotion(PotionType.INVISIBILITY), + factory.createPotion(PotionType.STRENGTH), + factory.createPotion(PotionType.HEALING), + factory.createPotion(PotionType.HEALING)); + bottomShelf = + List.of( + factory.createPotion(PotionType.POISON), + factory.createPotion(PotionType.POISON), + factory.createPotion(PotionType.POISON), + factory.createPotion(PotionType.HOLY_WATER), + factory.createPotion(PotionType.HOLY_WATER)); } /** @@ -78,9 +74,7 @@ public class AlchemistShop { return List.copyOf(this.bottomShelf); } - /** - * Drink all the potions. - */ + /** Drink all the potions. */ public void drinkPotions() { LOGGER.info("Drinking top shelf potions"); topShelf.forEach(Potion::drink); diff --git a/flyweight/src/main/java/com/iluwatar/flyweight/HealingPotion.java b/flyweight/src/main/java/com/iluwatar/flyweight/HealingPotion.java index 9c63e4a8d..9fb66df96 100644 --- a/flyweight/src/main/java/com/iluwatar/flyweight/HealingPotion.java +++ b/flyweight/src/main/java/com/iluwatar/flyweight/HealingPotion.java @@ -26,9 +26,7 @@ package com.iluwatar.flyweight; import lombok.extern.slf4j.Slf4j; -/** - * HealingPotion. - */ +/** HealingPotion. */ @Slf4j public class HealingPotion implements Potion { diff --git a/flyweight/src/main/java/com/iluwatar/flyweight/HolyWaterPotion.java b/flyweight/src/main/java/com/iluwatar/flyweight/HolyWaterPotion.java index 47d1cd4af..73822c8bf 100644 --- a/flyweight/src/main/java/com/iluwatar/flyweight/HolyWaterPotion.java +++ b/flyweight/src/main/java/com/iluwatar/flyweight/HolyWaterPotion.java @@ -26,9 +26,7 @@ package com.iluwatar.flyweight; import lombok.extern.slf4j.Slf4j; -/** - * HolyWaterPotion. - */ +/** HolyWaterPotion. */ @Slf4j public class HolyWaterPotion implements Potion { diff --git a/flyweight/src/main/java/com/iluwatar/flyweight/InvisibilityPotion.java b/flyweight/src/main/java/com/iluwatar/flyweight/InvisibilityPotion.java index 09a3d83a2..1e5ada3cc 100644 --- a/flyweight/src/main/java/com/iluwatar/flyweight/InvisibilityPotion.java +++ b/flyweight/src/main/java/com/iluwatar/flyweight/InvisibilityPotion.java @@ -26,9 +26,7 @@ package com.iluwatar.flyweight; import lombok.extern.slf4j.Slf4j; -/** - * InvisibilityPotion. - */ +/** InvisibilityPotion. */ @Slf4j public class InvisibilityPotion implements Potion { diff --git a/flyweight/src/main/java/com/iluwatar/flyweight/PoisonPotion.java b/flyweight/src/main/java/com/iluwatar/flyweight/PoisonPotion.java index 8123053f8..a25bfc6fc 100644 --- a/flyweight/src/main/java/com/iluwatar/flyweight/PoisonPotion.java +++ b/flyweight/src/main/java/com/iluwatar/flyweight/PoisonPotion.java @@ -26,9 +26,7 @@ package com.iluwatar.flyweight; import lombok.extern.slf4j.Slf4j; -/** - * PoisonPotion. - */ +/** PoisonPotion. */ @Slf4j public class PoisonPotion implements Potion { diff --git a/flyweight/src/main/java/com/iluwatar/flyweight/Potion.java b/flyweight/src/main/java/com/iluwatar/flyweight/Potion.java index edbf07789..fa1af252b 100644 --- a/flyweight/src/main/java/com/iluwatar/flyweight/Potion.java +++ b/flyweight/src/main/java/com/iluwatar/flyweight/Potion.java @@ -1,33 +1,31 @@ -/* - * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). - * - * The MIT License - * Copyright © 2014-2022 Ilkka Seppälä - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package com.iluwatar.flyweight; - -/** - * Interface for Potions. - */ -public interface Potion { - - void drink(); -} +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.flyweight; + +/** Interface for Potions. */ +public interface Potion { + + void drink(); +} diff --git a/flyweight/src/main/java/com/iluwatar/flyweight/PotionFactory.java b/flyweight/src/main/java/com/iluwatar/flyweight/PotionFactory.java index 582cf8b90..2ac4e58a1 100644 --- a/flyweight/src/main/java/com/iluwatar/flyweight/PotionFactory.java +++ b/flyweight/src/main/java/com/iluwatar/flyweight/PotionFactory.java @@ -1,61 +1,60 @@ -/* - * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). - * - * The MIT License - * Copyright © 2014-2022 Ilkka Seppälä - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package com.iluwatar.flyweight; - -import java.util.EnumMap; -import java.util.Map; - -/** - * PotionFactory is the Flyweight in this example. It minimizes memory use by sharing object - * instances. It holds a map of potion instances and new potions are created only when none of the - * type already exists. - */ -public class PotionFactory { - - private final Map potions; - - public PotionFactory() { - potions = new EnumMap<>(PotionType.class); - } - - Potion createPotion(PotionType type) { - var potion = potions.get(type); - if (potion == null) { - switch (type) { - case HEALING -> potion = new HealingPotion(); - case HOLY_WATER -> potion = new HolyWaterPotion(); - case INVISIBILITY -> potion = new InvisibilityPotion(); - case POISON -> potion = new PoisonPotion(); - case STRENGTH -> potion = new StrengthPotion(); - default -> { - } - } - if (potion != null) { - potions.put(type, potion); - } - } - return potion; - } -} +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.flyweight; + +import java.util.EnumMap; +import java.util.Map; + +/** + * PotionFactory is the Flyweight in this example. It minimizes memory use by sharing object + * instances. It holds a map of potion instances and new potions are created only when none of the + * type already exists. + */ +public class PotionFactory { + + private final Map potions; + + public PotionFactory() { + potions = new EnumMap<>(PotionType.class); + } + + Potion createPotion(PotionType type) { + var potion = potions.get(type); + if (potion == null) { + switch (type) { + case HEALING -> potion = new HealingPotion(); + case HOLY_WATER -> potion = new HolyWaterPotion(); + case INVISIBILITY -> potion = new InvisibilityPotion(); + case POISON -> potion = new PoisonPotion(); + case STRENGTH -> potion = new StrengthPotion(); + default -> {} + } + if (potion != null) { + potions.put(type, potion); + } + } + return potion; + } +} diff --git a/flyweight/src/main/java/com/iluwatar/flyweight/PotionType.java b/flyweight/src/main/java/com/iluwatar/flyweight/PotionType.java index b45fd2268..da73c1f1c 100644 --- a/flyweight/src/main/java/com/iluwatar/flyweight/PotionType.java +++ b/flyweight/src/main/java/com/iluwatar/flyweight/PotionType.java @@ -1,33 +1,34 @@ -/* - * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). - * - * The MIT License - * Copyright © 2014-2022 Ilkka Seppälä - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package com.iluwatar.flyweight; - -/** - * Enumeration for potion types. - */ -public enum PotionType { - - HEALING, INVISIBILITY, STRENGTH, HOLY_WATER, POISON -} +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.flyweight; + +/** Enumeration for potion types. */ +public enum PotionType { + HEALING, + INVISIBILITY, + STRENGTH, + HOLY_WATER, + POISON +} diff --git a/flyweight/src/main/java/com/iluwatar/flyweight/StrengthPotion.java b/flyweight/src/main/java/com/iluwatar/flyweight/StrengthPotion.java index 22dfa24ed..57a880b9f 100644 --- a/flyweight/src/main/java/com/iluwatar/flyweight/StrengthPotion.java +++ b/flyweight/src/main/java/com/iluwatar/flyweight/StrengthPotion.java @@ -26,9 +26,7 @@ package com.iluwatar.flyweight; import lombok.extern.slf4j.Slf4j; -/** - * StrengthPotion. - */ +/** StrengthPotion. */ @Slf4j public class StrengthPotion implements Potion { diff --git a/flyweight/src/test/java/com/iluwatar/flyweight/AlchemistShopTest.java b/flyweight/src/test/java/com/iluwatar/flyweight/AlchemistShopTest.java index f5580184e..b5aff254a 100644 --- a/flyweight/src/test/java/com/iluwatar/flyweight/AlchemistShopTest.java +++ b/flyweight/src/test/java/com/iluwatar/flyweight/AlchemistShopTest.java @@ -31,10 +31,7 @@ import java.util.ArrayList; import java.util.HashSet; import org.junit.jupiter.api.Test; -/** - * AlchemistShopTest - * - */ +/** AlchemistShopTest */ class AlchemistShopTest { @Test diff --git a/flyweight/src/test/java/com/iluwatar/flyweight/AppTest.java b/flyweight/src/test/java/com/iluwatar/flyweight/AppTest.java index 59ef84b3d..d2960fb15 100644 --- a/flyweight/src/test/java/com/iluwatar/flyweight/AppTest.java +++ b/flyweight/src/test/java/com/iluwatar/flyweight/AppTest.java @@ -24,17 +24,15 @@ */ package com.iluwatar.flyweight; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -/** - * Application test - */ +import org.junit.jupiter.api.Test; + +/** Application test */ class AppTest { @Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/front-controller/pom.xml b/front-controller/pom.xml index c9eac51ba..66495f891 100644 --- a/front-controller/pom.xml +++ b/front-controller/pom.xml @@ -34,6 +34,14 @@ front-controller + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine @@ -42,6 +50,7 @@ org.junit.jupiter junit-jupiter-params + 5.11.4 test diff --git a/front-controller/src/main/java/com/iluwatar/front/controller/ApplicationException.java b/front-controller/src/main/java/com/iluwatar/front/controller/ApplicationException.java index 6ba13a46f..2016c9d4d 100644 --- a/front-controller/src/main/java/com/iluwatar/front/controller/ApplicationException.java +++ b/front-controller/src/main/java/com/iluwatar/front/controller/ApplicationException.java @@ -26,13 +26,10 @@ package com.iluwatar.front.controller; import java.io.Serial; -/** - * Custom exception type. - */ +/** Custom exception type. */ public class ApplicationException extends RuntimeException { - @Serial - private static final long serialVersionUID = 1L; + @Serial private static final long serialVersionUID = 1L; public ApplicationException(Throwable cause) { super(cause); diff --git a/front-controller/src/main/java/com/iluwatar/front/controller/ArcherCommand.java b/front-controller/src/main/java/com/iluwatar/front/controller/ArcherCommand.java index ec3a120c0..a062e3405 100644 --- a/front-controller/src/main/java/com/iluwatar/front/controller/ArcherCommand.java +++ b/front-controller/src/main/java/com/iluwatar/front/controller/ArcherCommand.java @@ -24,9 +24,7 @@ */ package com.iluwatar.front.controller; -/** - * Command for archers. - */ +/** Command for archers. */ public class ArcherCommand implements Command { @Override diff --git a/front-controller/src/main/java/com/iluwatar/front/controller/ArcherView.java b/front-controller/src/main/java/com/iluwatar/front/controller/ArcherView.java index 9b7d96d9d..794ecccb3 100644 --- a/front-controller/src/main/java/com/iluwatar/front/controller/ArcherView.java +++ b/front-controller/src/main/java/com/iluwatar/front/controller/ArcherView.java @@ -26,9 +26,7 @@ package com.iluwatar.front.controller; import lombok.extern.slf4j.Slf4j; -/** - * View for archers. - */ +/** View for archers. */ @Slf4j public class ArcherView implements View { diff --git a/front-controller/src/main/java/com/iluwatar/front/controller/CatapultCommand.java b/front-controller/src/main/java/com/iluwatar/front/controller/CatapultCommand.java index 6d9c63dc3..6d032f999 100644 --- a/front-controller/src/main/java/com/iluwatar/front/controller/CatapultCommand.java +++ b/front-controller/src/main/java/com/iluwatar/front/controller/CatapultCommand.java @@ -24,9 +24,7 @@ */ package com.iluwatar.front.controller; -/** - * Command for catapults. - */ +/** Command for catapults. */ public class CatapultCommand implements Command { @Override diff --git a/front-controller/src/main/java/com/iluwatar/front/controller/CatapultView.java b/front-controller/src/main/java/com/iluwatar/front/controller/CatapultView.java index 59c56c5dd..68a02460a 100644 --- a/front-controller/src/main/java/com/iluwatar/front/controller/CatapultView.java +++ b/front-controller/src/main/java/com/iluwatar/front/controller/CatapultView.java @@ -26,9 +26,7 @@ package com.iluwatar.front.controller; import lombok.extern.slf4j.Slf4j; -/** - * View for catapults. - */ +/** View for catapults. */ @Slf4j public class CatapultView implements View { diff --git a/front-controller/src/main/java/com/iluwatar/front/controller/Command.java b/front-controller/src/main/java/com/iluwatar/front/controller/Command.java index 65e3359fe..a55b97848 100644 --- a/front-controller/src/main/java/com/iluwatar/front/controller/Command.java +++ b/front-controller/src/main/java/com/iluwatar/front/controller/Command.java @@ -24,9 +24,7 @@ */ package com.iluwatar.front.controller; -/** - * Commands are the intermediary between requests and views. - */ +/** Commands are the intermediary between requests and views. */ public interface Command { void process(); diff --git a/front-controller/src/main/java/com/iluwatar/front/controller/Dispatcher.java b/front-controller/src/main/java/com/iluwatar/front/controller/Dispatcher.java index 8b9644ab8..5b9da51b0 100644 --- a/front-controller/src/main/java/com/iluwatar/front/controller/Dispatcher.java +++ b/front-controller/src/main/java/com/iluwatar/front/controller/Dispatcher.java @@ -69,4 +69,4 @@ public class Dispatcher { return UnknownCommand.class; } } -} \ No newline at end of file +} diff --git a/front-controller/src/main/java/com/iluwatar/front/controller/ErrorView.java b/front-controller/src/main/java/com/iluwatar/front/controller/ErrorView.java index 54e711905..3e1a1d1b8 100644 --- a/front-controller/src/main/java/com/iluwatar/front/controller/ErrorView.java +++ b/front-controller/src/main/java/com/iluwatar/front/controller/ErrorView.java @@ -26,9 +26,7 @@ package com.iluwatar.front.controller; import lombok.extern.slf4j.Slf4j; -/** - * View for errors. - */ +/** View for errors. */ @Slf4j public class ErrorView implements View { diff --git a/front-controller/src/main/java/com/iluwatar/front/controller/FrontController.java b/front-controller/src/main/java/com/iluwatar/front/controller/FrontController.java index bc8b4e344..293cedba4 100644 --- a/front-controller/src/main/java/com/iluwatar/front/controller/FrontController.java +++ b/front-controller/src/main/java/com/iluwatar/front/controller/FrontController.java @@ -25,9 +25,9 @@ package com.iluwatar.front.controller; /** - * The FrontController is responsible for handling all incoming requests. It delegates - * the processing of requests to the Dispatcher, which then determines the appropriate - * command and view to render the correct response. + * The FrontController is responsible for handling all incoming requests. It delegates the + * processing of requests to the Dispatcher, which then determines the appropriate command and view + * to render the correct response. */ public class FrontController { diff --git a/front-controller/src/main/java/com/iluwatar/front/controller/UnknownCommand.java b/front-controller/src/main/java/com/iluwatar/front/controller/UnknownCommand.java index 1cb7060b2..56d2b60a1 100644 --- a/front-controller/src/main/java/com/iluwatar/front/controller/UnknownCommand.java +++ b/front-controller/src/main/java/com/iluwatar/front/controller/UnknownCommand.java @@ -24,9 +24,7 @@ */ package com.iluwatar.front.controller; -/** - * Default command in case the mapping is not successful. - */ +/** Default command in case the mapping is not successful. */ public class UnknownCommand implements Command { @Override diff --git a/front-controller/src/main/java/com/iluwatar/front/controller/View.java b/front-controller/src/main/java/com/iluwatar/front/controller/View.java index 187ceeb7c..cc741b9e6 100644 --- a/front-controller/src/main/java/com/iluwatar/front/controller/View.java +++ b/front-controller/src/main/java/com/iluwatar/front/controller/View.java @@ -24,9 +24,7 @@ */ package com.iluwatar.front.controller; -/** - * Views are the representations rendered for the user. - */ +/** Views are the representations rendered for the user. */ public interface View { void display(); diff --git a/front-controller/src/test/java/com/iluwatar/front/controller/AppTest.java b/front-controller/src/test/java/com/iluwatar/front/controller/AppTest.java index ad2abda46..287398cc5 100644 --- a/front-controller/src/test/java/com/iluwatar/front/controller/AppTest.java +++ b/front-controller/src/test/java/com/iluwatar/front/controller/AppTest.java @@ -24,17 +24,15 @@ */ package com.iluwatar.front.controller; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -/** - * Application test - */ +import org.junit.jupiter.api.Test; + +/** Application test */ class AppTest { @Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/front-controller/src/test/java/com/iluwatar/front/controller/ApplicationExceptionTest.java b/front-controller/src/test/java/com/iluwatar/front/controller/ApplicationExceptionTest.java index 38dea3316..91e071f8b 100644 --- a/front-controller/src/test/java/com/iluwatar/front/controller/ApplicationExceptionTest.java +++ b/front-controller/src/test/java/com/iluwatar/front/controller/ApplicationExceptionTest.java @@ -28,10 +28,7 @@ import static org.junit.jupiter.api.Assertions.assertSame; import org.junit.jupiter.api.Test; -/** - * ApplicationExceptionTest - * - */ +/** ApplicationExceptionTest */ class ApplicationExceptionTest { @Test @@ -39,5 +36,4 @@ class ApplicationExceptionTest { final var cause = new Exception(); assertSame(cause, new ApplicationException(cause).getCause()); } - -} \ No newline at end of file +} diff --git a/front-controller/src/test/java/com/iluwatar/front/controller/CommandTest.java b/front-controller/src/test/java/com/iluwatar/front/controller/CommandTest.java index 8232b2b76..7f7a3d390 100644 --- a/front-controller/src/test/java/com/iluwatar/front/controller/CommandTest.java +++ b/front-controller/src/test/java/com/iluwatar/front/controller/CommandTest.java @@ -33,10 +33,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; -/** - * CommandTest - * - */ +/** CommandTest */ class CommandTest { private InMemoryAppender appender; @@ -53,14 +50,13 @@ class CommandTest { static List dataProvider() { return List.of( - new Object[]{"Archer", "Displaying archers"}, - new Object[]{"Catapult", "Displaying catapults"}, - new Object[]{"NonExistentCommand", "Error 500"} - ); + new Object[] {"Archer", "Displaying archers"}, + new Object[] {"Catapult", "Displaying catapults"}, + new Object[] {"NonExistentCommand", "Error 500"}); } /** - * @param request The request that's been tested + * @param request The request that's been tested * @param displayMessage The expected display message */ @ParameterizedTest @@ -72,5 +68,4 @@ class CommandTest { assertEquals(displayMessage, appender.getLastMessage()); assertEquals(1, appender.getLogSize()); } - } diff --git a/front-controller/src/test/java/com/iluwatar/front/controller/DispatcherTest.java b/front-controller/src/test/java/com/iluwatar/front/controller/DispatcherTest.java index c60aa899d..64c611c49 100644 --- a/front-controller/src/test/java/com/iluwatar/front/controller/DispatcherTest.java +++ b/front-controller/src/test/java/com/iluwatar/front/controller/DispatcherTest.java @@ -24,12 +24,12 @@ */ package com.iluwatar.front.controller; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.*; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + class DispatcherTest { private Dispatcher dispatcher; diff --git a/front-controller/src/test/java/com/iluwatar/front/controller/FrontControllerTest.java b/front-controller/src/test/java/com/iluwatar/front/controller/FrontControllerTest.java index 1b5519db2..b4163aef4 100644 --- a/front-controller/src/test/java/com/iluwatar/front/controller/FrontControllerTest.java +++ b/front-controller/src/test/java/com/iluwatar/front/controller/FrontControllerTest.java @@ -33,10 +33,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; -/** - * FrontControllerTest - * - */ +/** FrontControllerTest */ class FrontControllerTest { private InMemoryAppender appender; @@ -53,14 +50,13 @@ class FrontControllerTest { static List dataProvider() { return List.of( - new Object[]{new ArcherCommand(), "Displaying archers"}, - new Object[]{new CatapultCommand(), "Displaying catapults"}, - new Object[]{new UnknownCommand(), "Error 500"} - ); + new Object[] {new ArcherCommand(), "Displaying archers"}, + new Object[] {new CatapultCommand(), "Displaying catapults"}, + new Object[] {new UnknownCommand(), "Error 500"}); } /** - * @param command The command that's been tested + * @param command The command that's been tested * @param displayMessage The expected display message */ @ParameterizedTest @@ -71,5 +67,4 @@ class FrontControllerTest { assertEquals(displayMessage, appender.getLastMessage()); assertEquals(1, appender.getLogSize()); } - } diff --git a/front-controller/src/test/java/com/iluwatar/front/controller/ViewTest.java b/front-controller/src/test/java/com/iluwatar/front/controller/ViewTest.java index d95c0bbff..09cd1e21e 100644 --- a/front-controller/src/test/java/com/iluwatar/front/controller/ViewTest.java +++ b/front-controller/src/test/java/com/iluwatar/front/controller/ViewTest.java @@ -33,10 +33,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; -/** - * ViewTest - * - */ +/** ViewTest */ class ViewTest { private InMemoryAppender appender; @@ -53,14 +50,13 @@ class ViewTest { static List dataProvider() { return List.of( - new Object[]{new ArcherView(), "Displaying archers"}, - new Object[]{new CatapultView(), "Displaying catapults"}, - new Object[]{new ErrorView(), "Error 500"} - ); + new Object[] {new ArcherView(), "Displaying archers"}, + new Object[] {new CatapultView(), "Displaying catapults"}, + new Object[] {new ErrorView(), "Error 500"}); } /** - * @param view The view that's been tested + * @param view The view that's been tested * @param displayMessage The expected display message */ @ParameterizedTest @@ -71,5 +67,4 @@ class ViewTest { assertEquals(displayMessage, appender.getLastMessage()); assertEquals(1, appender.getLogSize()); } - } 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 ca0a5ccbf..86268d4c3 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 @@ -27,13 +27,11 @@ package com.iluwatar.front.controller.utils; import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.AppenderBase; -import org.slf4j.LoggerFactory; import java.util.LinkedList; import java.util.List; +import org.slf4j.LoggerFactory; -/** - * InMemory Log Appender Util. - */ +/** InMemory Log Appender Util. */ public class InMemoryAppender extends AppenderBase { private final List log = new LinkedList<>(); diff --git a/function-composition/pom.xml b/function-composition/pom.xml index da803b723..abf504b29 100644 --- a/function-composition/pom.xml +++ b/function-composition/pom.xml @@ -35,13 +35,16 @@ function-composition - org.junit.jupiter - junit-jupiter-engine - test + org.slf4j + slf4j-api - junit - junit + ch.qos.logback + logback-classic + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/function-composition/src/main/java/com/iluwatar/function/composition/App.java b/function-composition/src/main/java/com/iluwatar/function/composition/App.java index da55135bd..206d8fe1c 100644 --- a/function-composition/src/main/java/com/iluwatar/function/composition/App.java +++ b/function-composition/src/main/java/com/iluwatar/function/composition/App.java @@ -27,9 +27,7 @@ package com.iluwatar.function.composition; import java.util.function.Function; import org.slf4j.LoggerFactory; -/** - * Main application class to demonstrate the use of function composition. - */ +/** Main application class to demonstrate the use of function composition. */ public class App { /** @@ -42,7 +40,8 @@ public class App { Function timesTwo = x -> x * 2; Function square = x -> x * x; - Function composedFunction = FunctionComposer.composeFunctions(timesTwo, square); + Function composedFunction = + FunctionComposer.composeFunctions(timesTwo, square); int result = composedFunction.apply(3); logger.info("Result of composing 'timesTwo' and 'square' functions applied to 3 is: " + result); diff --git a/function-composition/src/main/java/com/iluwatar/function/composition/FunctionComposer.java b/function-composition/src/main/java/com/iluwatar/function/composition/FunctionComposer.java index 725903f9c..9438b8550 100644 --- a/function-composition/src/main/java/com/iluwatar/function/composition/FunctionComposer.java +++ b/function-composition/src/main/java/com/iluwatar/function/composition/FunctionComposer.java @@ -27,20 +27,21 @@ package com.iluwatar.function.composition; import java.util.function.Function; /** - * Class for composing functions using the Function Composition pattern. - * Provides a static method to compose two functions using the 'andThen' method. + * Class for composing functions using the Function Composition pattern. Provides a static method to + * compose two functions using the 'andThen' method. */ public class FunctionComposer { /** - * Composes two functions where the output of the first function becomes - * the input of the second function. + * Composes two functions where the output of the first function becomes the input of the second + * function. * * @param f1 the first function to apply * @param f2 the second function to apply after the first * @return a composed function that applies f1 and then f2 */ - public static Function composeFunctions(Function f1, Function f2) { + public static Function composeFunctions( + Function f1, Function f2) { return f1.andThen(f2); } } diff --git a/function-composition/src/test/java/com/iluwatar/function/composition/AppTest.java b/function-composition/src/test/java/com/iluwatar/function/composition/AppTest.java index 82d543568..f1640675c 100644 --- a/function-composition/src/test/java/com/iluwatar/function/composition/AppTest.java +++ b/function-composition/src/test/java/com/iluwatar/function/composition/AppTest.java @@ -24,17 +24,15 @@ */ package com.iluwatar.function.composition; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -/** - * Application test - */ +import org.junit.jupiter.api.Test; + +/** Application test */ class AppTest { @Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/function-composition/src/test/java/com/iluwatar/function/composition/FunctionComposerTest.java b/function-composition/src/test/java/com/iluwatar/function/composition/FunctionComposerTest.java index af8950252..451fb787b 100644 --- a/function-composition/src/test/java/com/iluwatar/function/composition/FunctionComposerTest.java +++ b/function-composition/src/test/java/com/iluwatar/function/composition/FunctionComposerTest.java @@ -24,79 +24,73 @@ */ package com.iluwatar.function.composition; -import static org.junit.Assert.assertEquals; -import org.junit.Test; -import java.util.function.Function; +import static org.junit.jupiter.api.Assertions.assertEquals; -/** - * Test class for FunctionComposer. - */ +import java.util.function.Function; +import org.junit.jupiter.api.Test; + +/** Test class for FunctionComposer. */ public class FunctionComposerTest { - /** - * Tests the composition of two functions. - */ + /** Tests the composition of two functions. */ @Test - public void testComposeFunctions() { + void testComposeFunctions() { Function timesTwo = x -> x * 2; Function square = x -> x * x; Function composed = FunctionComposer.composeFunctions(timesTwo, square); - assertEquals("Expected output of composed functions is 36", 36, (int) composed.apply(3)); + assertEquals(36, composed.apply(3), "Expected output of composed functions is 36"); } - /** - * Tests function composition with identity function. - */ + /** Tests function composition with identity function. */ @Test - public void testComposeWithIdentity() { + void testComposeWithIdentity() { Function identity = Function.identity(); Function timesThree = x -> x * 3; - Function composedLeft = FunctionComposer.composeFunctions(identity, timesThree); - Function composedRight = FunctionComposer.composeFunctions(timesThree, identity); + Function composedLeft = + FunctionComposer.composeFunctions(identity, timesThree); + Function composedRight = + FunctionComposer.composeFunctions(timesThree, identity); - assertEquals("Composition with identity on the left should be the same", 9, (int) composedLeft.apply(3)); - assertEquals("Composition with identity on the right should be the same", 9, (int) composedRight.apply(3)); + assertEquals( + 9, composedLeft.apply(3), "Composition with identity on the left should be the same"); + assertEquals( + 9, composedRight.apply(3), "Composition with identity on the right should be the same"); } - /** - * Tests function composition resulting in zero. - */ + /** Tests function composition resulting in zero. */ @Test - public void testComposeToZero() { + void testComposeToZero() { Function multiply = x -> x * 10; Function toZero = x -> 0; Function composed = FunctionComposer.composeFunctions(multiply, toZero); - assertEquals("Expected output of function composition leading to zero is 0", 0, (int) composed.apply(5)); + assertEquals( + 0, composed.apply(5), "Expected output of function composition leading to zero is 0"); } - /** - * Tests the composition with a negative function. - */ + /** Tests the composition with a negative function. */ @Test - public void testComposeNegative() { + void testComposeNegative() { Function negate = x -> -x; Function square = x -> x * x; Function composed = FunctionComposer.composeFunctions(negate, square); - assertEquals("Expected square of negative number to be positive", 9, (int) composed.apply(3)); + assertEquals(9, composed.apply(3), "Expected square of negative number to be positive"); } - /** - * Tests the composition of functions that cancel each other out. - */ + /** Tests the composition of functions that cancel each other out. */ @Test - public void testComposeInverseFunctions() { + void testComposeInverseFunctions() { Function timesTwo = x -> x * 2; Function half = x -> x / 2; Function composed = FunctionComposer.composeFunctions(timesTwo, half); - assertEquals("Expect the functions to cancel each other out", 5, (int) composed.apply(5)); + assertEquals(5, composed.apply(5), "Expect the functions to cancel each other out"); } } diff --git a/game-loop/pom.xml b/game-loop/pom.xml index af782d4ce..1ef70a650 100644 --- a/game-loop/pom.xml +++ b/game-loop/pom.xml @@ -34,6 +34,14 @@ 4.0.0 game-loop + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/game-loop/src/main/java/com/iluwatar/gameloop/App.java b/game-loop/src/main/java/com/iluwatar/gameloop/App.java index f01937396..76ed426e6 100644 --- a/game-loop/src/main/java/com/iluwatar/gameloop/App.java +++ b/game-loop/src/main/java/com/iluwatar/gameloop/App.java @@ -27,20 +27,19 @@ package com.iluwatar.gameloop; import lombok.extern.slf4j.Slf4j; /** - * A game loop runs continuously during gameplay. Each turn of the loop, it processes - * user input without blocking, updates the game state, and renders the game. It tracks - * the passage of time to control the rate of gameplay. + * A game loop runs continuously during gameplay. Each turn of the loop, it processes user input + * without blocking, updates the game state, and renders the game. It tracks the passage of time to + * control the rate of gameplay. */ @Slf4j public class App { - /** - * Each type of game loop will run for 2 seconds. - */ + /** Each type of game loop will run for 2 seconds. */ private static final int GAME_LOOP_DURATION_TIME = 2000; /** * Program entry point. + * * @param args runtime arguments */ public static void main(String[] args) { @@ -71,5 +70,4 @@ public class App { LOGGER.error(e.getMessage()); } } - } diff --git a/game-loop/src/main/java/com/iluwatar/gameloop/Bullet.java b/game-loop/src/main/java/com/iluwatar/gameloop/Bullet.java index 90484b2d0..00b1a8b77 100644 --- a/game-loop/src/main/java/com/iluwatar/gameloop/Bullet.java +++ b/game-loop/src/main/java/com/iluwatar/gameloop/Bullet.java @@ -27,14 +27,10 @@ package com.iluwatar.gameloop; import lombok.Getter; import lombok.Setter; -/** - * Bullet object class. - */ +/** Bullet object class. */ public class Bullet { - @Getter - @Setter - private float position; + @Getter @Setter private float position; public Bullet() { position = 0.0f; diff --git a/game-loop/src/main/java/com/iluwatar/gameloop/FixedStepGameLoop.java b/game-loop/src/main/java/com/iluwatar/gameloop/FixedStepGameLoop.java index 3f775a9d2..58c4e0dfd 100644 --- a/game-loop/src/main/java/com/iluwatar/gameloop/FixedStepGameLoop.java +++ b/game-loop/src/main/java/com/iluwatar/gameloop/FixedStepGameLoop.java @@ -25,15 +25,13 @@ package com.iluwatar.gameloop; /** - * For fixed-step game loop, a certain amount of real time has elapsed since the - * last turn of the game loop. This is how much game time need to be simulated for - * the game’s “now” to catch up with the player’s. + * For fixed-step game loop, a certain amount of real time has elapsed since the last turn of the + * game loop. This is how much game time need to be simulated for the game’s “now” to catch up with + * the player’s. */ public class FixedStepGameLoop extends GameLoop { - /** - * 20 ms per frame = 50 FPS. - */ + /** 20 ms per frame = 50 FPS. */ private static final long MS_PER_FRAME = 20; @Override diff --git a/game-loop/src/main/java/com/iluwatar/gameloop/FrameBasedGameLoop.java b/game-loop/src/main/java/com/iluwatar/gameloop/FrameBasedGameLoop.java index 12117e3b1..a60eaf547 100644 --- a/game-loop/src/main/java/com/iluwatar/gameloop/FrameBasedGameLoop.java +++ b/game-loop/src/main/java/com/iluwatar/gameloop/FrameBasedGameLoop.java @@ -25,12 +25,11 @@ package com.iluwatar.gameloop; /** - * Frame-based game loop is the easiest implementation. The loop always keeps spinning - * for the following three processes: processInput, update and render. The problem with - * it is you have no control over how fast the game runs. On a fast machine, that loop - * will spin so fast users won’t be able to see what’s going on. On a slow machine, the - * game will crawl. If you have a part of the game that’s content-heavy or does more AI - * or physics, the game will actually play slower there. + * Frame-based game loop is the easiest implementation. The loop always keeps spinning for the + * following three processes: processInput, update and render. The problem with it is you have no + * control over how fast the game runs. On a fast machine, that loop will spin so fast users won’t + * be able to see what’s going on. On a slow machine, the game will crawl. If you have a part of the + * game that’s content-heavy or does more AI or physics, the game will actually play slower there. */ public class FrameBasedGameLoop extends GameLoop { @@ -44,11 +43,10 @@ public class FrameBasedGameLoop extends GameLoop { } /** - * Each time when update() is invoked, a new frame is created, and the bullet will be - * moved 0.5f away from the current position. + * Each time when update() is invoked, a new frame is created, and the bullet will be moved 0.5f + * away from the current position. */ protected void update() { controller.moveBullet(0.5f); } - } diff --git a/game-loop/src/main/java/com/iluwatar/gameloop/GameController.java b/game-loop/src/main/java/com/iluwatar/gameloop/GameController.java index 1ed2304ec..872aa8e8c 100644 --- a/game-loop/src/main/java/com/iluwatar/gameloop/GameController.java +++ b/game-loop/src/main/java/com/iluwatar/gameloop/GameController.java @@ -25,16 +25,14 @@ package com.iluwatar.gameloop; /** - * Update and render objects in the game. Here we add a Bullet object to the - * game system to show how the game loop works. + * Update and render objects in the game. Here we add a Bullet object to the game system to show how + * the game loop works. */ public class GameController { protected final Bullet bullet; - /** - * Initialize Bullet instance. - */ + /** Initialize Bullet instance. */ public GameController() { bullet = new Bullet(); } @@ -57,6 +55,4 @@ public class GameController { public float getBulletPosition() { return bullet.getPosition(); } - } - diff --git a/game-loop/src/main/java/com/iluwatar/gameloop/GameLoop.java b/game-loop/src/main/java/com/iluwatar/gameloop/GameLoop.java index 6ad8c2c52..0dcdb21f2 100644 --- a/game-loop/src/main/java/com/iluwatar/gameloop/GameLoop.java +++ b/game-loop/src/main/java/com/iluwatar/gameloop/GameLoop.java @@ -28,9 +28,7 @@ import java.security.SecureRandom; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -/** - * Abstract class for GameLoop implementation class. - */ +/** Abstract class for GameLoop implementation class. */ public abstract class GameLoop { protected final Logger logger = LoggerFactory.getLogger(this.getClass()); @@ -39,26 +37,20 @@ public abstract class GameLoop { protected final GameController controller; - /** - * Initialize game status to be stopped. - */ + /** Initialize game status to be stopped. */ protected GameLoop() { controller = new GameController(); status = GameStatus.STOPPED; } - /** - * Run game loop. - */ + /** Run game loop. */ public void run() { status = GameStatus.RUNNING; Thread gameThread = new Thread(this::processGameLoop); gameThread.start(); } - /** - * Stop game loop. - */ + /** Stop game loop. */ public void stop() { status = GameStatus.STOPPED; } @@ -73,9 +65,8 @@ public abstract class GameLoop { } /** - * Handle any user input that has happened since the last call. In order to - * simulate the situation in real-life game, here we add a random time lag. - * The time lag ranges from 50 ms to 250 ms. + * Handle any user input that has happened since the last call. In order to simulate the situation + * in real-life game, here we add a random time lag. The time lag ranges from 50 ms to 250 ms. */ protected void processInput() { try { @@ -88,18 +79,12 @@ public abstract class GameLoop { } } - /** - * Render game frames to screen. Here we print bullet position to simulate - * this process. - */ + /** Render game frames to screen. Here we print bullet position to simulate this process. */ protected void render() { var position = controller.getBulletPosition(); logger.info("Current bullet position: {}", position); } - /** - * execute game loop logic. - */ + /** execute game loop logic. */ protected abstract void processGameLoop(); - } diff --git a/game-loop/src/main/java/com/iluwatar/gameloop/GameStatus.java b/game-loop/src/main/java/com/iluwatar/gameloop/GameStatus.java index 8fb198c51..316bb83d9 100644 --- a/game-loop/src/main/java/com/iluwatar/gameloop/GameStatus.java +++ b/game-loop/src/main/java/com/iluwatar/gameloop/GameStatus.java @@ -24,11 +24,8 @@ */ package com.iluwatar.gameloop; -/** - * Enum class for game status. - */ +/** Enum class for game status. */ public enum GameStatus { - - RUNNING, STOPPED - + RUNNING, + STOPPED } diff --git a/game-loop/src/main/java/com/iluwatar/gameloop/VariableStepGameLoop.java b/game-loop/src/main/java/com/iluwatar/gameloop/VariableStepGameLoop.java index 98644224a..9c7c0f348 100644 --- a/game-loop/src/main/java/com/iluwatar/gameloop/VariableStepGameLoop.java +++ b/game-loop/src/main/java/com/iluwatar/gameloop/VariableStepGameLoop.java @@ -25,10 +25,9 @@ package com.iluwatar.gameloop; /** - * The variable-step game loop chooses a time step to advance based on how much - * real time passed since the last frame. The longer the frame takes, the bigger - * steps the game takes. It always keeps up with real time because it will take - * bigger and bigger steps to get there. + * The variable-step game loop chooses a time step to advance based on how much real time passed + * since the last frame. The longer the frame takes, the bigger steps the game takes. It always + * keeps up with real time because it will take bigger and bigger steps to get there. */ public class VariableStepGameLoop extends GameLoop { @@ -48,5 +47,4 @@ public class VariableStepGameLoop extends GameLoop { protected void update(Long elapsedTime) { controller.moveBullet(0.5f * elapsedTime / 1000); } - } diff --git a/game-loop/src/test/java/com/iluwatar/gameloop/AppTest.java b/game-loop/src/test/java/com/iluwatar/gameloop/AppTest.java index 72997b744..956503037 100644 --- a/game-loop/src/test/java/com/iluwatar/gameloop/AppTest.java +++ b/game-loop/src/test/java/com/iluwatar/gameloop/AppTest.java @@ -28,14 +28,11 @@ import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import org.junit.jupiter.api.Test; -/** - * App unit test class. - */ +/** App unit test class. */ class AppTest { @Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } - } diff --git a/game-loop/src/test/java/com/iluwatar/gameloop/FixedStepGameLoopTest.java b/game-loop/src/test/java/com/iluwatar/gameloop/FixedStepGameLoopTest.java index 8cd00f286..fdcd8a1e3 100644 --- a/game-loop/src/test/java/com/iluwatar/gameloop/FixedStepGameLoopTest.java +++ b/game-loop/src/test/java/com/iluwatar/gameloop/FixedStepGameLoopTest.java @@ -26,13 +26,11 @@ package com.iluwatar.gameloop; import static org.junit.jupiter.api.Assertions.assertEquals; -import org.junit.jupiter.api.Test; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -/** - * FixedStepGameLoop unit test class. - */ +/** FixedStepGameLoop unit test class. */ class FixedStepGameLoopTest { private FixedStepGameLoop gameLoop; @@ -52,5 +50,4 @@ class FixedStepGameLoopTest { gameLoop.update(); assertEquals(0.01f, gameLoop.controller.getBulletPosition(), 0); } - } diff --git a/game-loop/src/test/java/com/iluwatar/gameloop/FrameBasedGameLoopTest.java b/game-loop/src/test/java/com/iluwatar/gameloop/FrameBasedGameLoopTest.java index fb93a3f0f..ea2f80646 100644 --- a/game-loop/src/test/java/com/iluwatar/gameloop/FrameBasedGameLoopTest.java +++ b/game-loop/src/test/java/com/iluwatar/gameloop/FrameBasedGameLoopTest.java @@ -30,9 +30,7 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -/** - * FrameBasedGameLoop unit test class. - */ +/** FrameBasedGameLoop unit test class. */ class FrameBasedGameLoopTest { private FrameBasedGameLoop gameLoop; diff --git a/game-loop/src/test/java/com/iluwatar/gameloop/GameControllerTest.java b/game-loop/src/test/java/com/iluwatar/gameloop/GameControllerTest.java index a8eef3431..c5855a88e 100644 --- a/game-loop/src/test/java/com/iluwatar/gameloop/GameControllerTest.java +++ b/game-loop/src/test/java/com/iluwatar/gameloop/GameControllerTest.java @@ -54,5 +54,4 @@ class GameControllerTest { void testGetBulletPosition() { assertEquals(controller.bullet.getPosition(), controller.getBulletPosition(), 0); } - } diff --git a/game-loop/src/test/java/com/iluwatar/gameloop/GameLoopTest.java b/game-loop/src/test/java/com/iluwatar/gameloop/GameLoopTest.java index 210892e6a..c7dddd372 100644 --- a/game-loop/src/test/java/com/iluwatar/gameloop/GameLoopTest.java +++ b/game-loop/src/test/java/com/iluwatar/gameloop/GameLoopTest.java @@ -24,30 +24,28 @@ */ package com.iluwatar.gameloop; +import static org.junit.jupiter.api.Assertions.assertFalse; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; -import static org.junit.jupiter.api.Assertions.assertFalse; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -/** - * GameLoop unit test class. - */ +/** GameLoop unit test class. */ class GameLoopTest { private GameLoop gameLoop; - /** - * Create mock implementation of GameLoop. - */ + /** Create mock implementation of GameLoop. */ @BeforeEach void setup() { - gameLoop = new GameLoop() { - @Override - protected void processGameLoop() { - throw new UnsupportedOperationException("Not supported yet."); - } - }; + gameLoop = + new GameLoop() { + @Override + protected void processGameLoop() { + throw new UnsupportedOperationException("Not supported yet."); + } + }; } @AfterEach diff --git a/game-loop/src/test/java/com/iluwatar/gameloop/VariableStepGameLoopTest.java b/game-loop/src/test/java/com/iluwatar/gameloop/VariableStepGameLoopTest.java index 4c04eec0a..b528c145c 100644 --- a/game-loop/src/test/java/com/iluwatar/gameloop/VariableStepGameLoopTest.java +++ b/game-loop/src/test/java/com/iluwatar/gameloop/VariableStepGameLoopTest.java @@ -29,9 +29,7 @@ import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -/** - * VariableStepGameLoop unit test class. - */ +/** VariableStepGameLoop unit test class. */ class VariableStepGameLoopTest { private VariableStepGameLoop gameLoop; diff --git a/gateway/pom.xml b/gateway/pom.xml index 88c15cd58..4fbde9cce 100644 --- a/gateway/pom.xml +++ b/gateway/pom.xml @@ -36,13 +36,16 @@ gateway - org.junit.jupiter - junit-jupiter-engine - test + org.slf4j + slf4j-api - junit - junit + ch.qos.logback + logback-classic + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/gateway/src/main/java/com/iluwatar/gateway/App.java b/gateway/src/main/java/com/iluwatar/gateway/App.java index 811cd4f7c..5034748b2 100644 --- a/gateway/src/main/java/com/iluwatar/gateway/App.java +++ b/gateway/src/main/java/com/iluwatar/gateway/App.java @@ -27,21 +27,21 @@ package com.iluwatar.gateway; import lombok.extern.slf4j.Slf4j; /** - * the Gateway design pattern is a structural design pattern that provides a unified interface to a set of - * interfaces in a subsystem. It involves creating a Gateway interface that serves as a common entry point for - * interacting with various services, and concrete implementations of this interface for different external services. + * the Gateway design pattern is a structural design pattern that provides a unified interface to a + * set of interfaces in a subsystem. It involves creating a Gateway interface that serves as a + * common entry point for interacting with various services, and concrete implementations of this + * interface for different external services. * - *

In this example, GateFactory is the factory class, and it provides a method to create different kinds of external - * services. ExternalServiceA, B, and C are virtual implementations of the external services. Each service provides its - * own implementation of the execute() method. The Gateway interface is the common interface for all external services. - * The App class serves as the main entry point for the application implementing the Gateway design pattern. Through - * the Gateway interface, the App class could call each service with much less complexity. + *

In this example, GateFactory is the factory class, and it provides a method to create + * different kinds of external services. ExternalServiceA, B, and C are virtual implementations of + * the external services. Each service provides its own implementation of the execute() method. The + * Gateway interface is the common interface for all external services. The App class serves as the + * main entry point for the application implementing the Gateway design pattern. Through the Gateway + * interface, the App class could call each service with much less complexity. */ @Slf4j public class App { - /** - * Simulate an application calling external services. - */ + /** Simulate an application calling external services. */ public static void main(String[] args) throws Exception { GatewayFactory gatewayFactory = new GatewayFactory(); diff --git a/gateway/src/main/java/com/iluwatar/gateway/ExternalServiceA.java b/gateway/src/main/java/com/iluwatar/gateway/ExternalServiceA.java index 5b90536ca..892dc5d7b 100644 --- a/gateway/src/main/java/com/iluwatar/gateway/ExternalServiceA.java +++ b/gateway/src/main/java/com/iluwatar/gateway/ExternalServiceA.java @@ -24,12 +24,9 @@ */ package com.iluwatar.gateway; - import lombok.extern.slf4j.Slf4j; -/** -* ExternalServiceA is one of external services. -*/ +/** ExternalServiceA is one of external services. */ @Slf4j class ExternalServiceA implements Gateway { @Override diff --git a/gateway/src/main/java/com/iluwatar/gateway/ExternalServiceB.java b/gateway/src/main/java/com/iluwatar/gateway/ExternalServiceB.java index 153cfc5b2..dcd931ffb 100644 --- a/gateway/src/main/java/com/iluwatar/gateway/ExternalServiceB.java +++ b/gateway/src/main/java/com/iluwatar/gateway/ExternalServiceB.java @@ -24,12 +24,9 @@ */ package com.iluwatar.gateway; - import lombok.extern.slf4j.Slf4j; -/** -* ExternalServiceB is one of external services. -*/ +/** ExternalServiceB is one of external services. */ @Slf4j class ExternalServiceB implements Gateway { @Override @@ -39,4 +36,3 @@ class ExternalServiceB implements Gateway { Thread.sleep(1000); } } - diff --git a/gateway/src/main/java/com/iluwatar/gateway/ExternalServiceC.java b/gateway/src/main/java/com/iluwatar/gateway/ExternalServiceC.java index 6b0239f94..b01d79e37 100644 --- a/gateway/src/main/java/com/iluwatar/gateway/ExternalServiceC.java +++ b/gateway/src/main/java/com/iluwatar/gateway/ExternalServiceC.java @@ -24,12 +24,9 @@ */ package com.iluwatar.gateway; - import lombok.extern.slf4j.Slf4j; -/** -* ExternalServiceC is one of external services. -*/ +/** ExternalServiceC is one of external services. */ @Slf4j class ExternalServiceC implements Gateway { @Override diff --git a/gateway/src/main/java/com/iluwatar/gateway/Gateway.java b/gateway/src/main/java/com/iluwatar/gateway/Gateway.java index 40dc473d5..36627681c 100644 --- a/gateway/src/main/java/com/iluwatar/gateway/Gateway.java +++ b/gateway/src/main/java/com/iluwatar/gateway/Gateway.java @@ -24,9 +24,7 @@ */ package com.iluwatar.gateway; -/** - * Service interface. - */ +/** Service interface. */ interface Gateway { void execute() throws Exception; -} \ No newline at end of file +} diff --git a/gateway/src/main/java/com/iluwatar/gateway/GatewayFactory.java b/gateway/src/main/java/com/iluwatar/gateway/GatewayFactory.java index 0f8c12ede..2501e5f72 100644 --- a/gateway/src/main/java/com/iluwatar/gateway/GatewayFactory.java +++ b/gateway/src/main/java/com/iluwatar/gateway/GatewayFactory.java @@ -28,8 +28,9 @@ import java.util.HashMap; import java.util.Map; /** - * The "GatewayFactory" class is responsible for providing different external services in this Gateway design pattern - * example. It allows clients to register and retrieve specific gateways based on unique keys. + * The "GatewayFactory" class is responsible for providing different external services in this + * Gateway design pattern example. It allows clients to register and retrieve specific gateways + * based on unique keys. */ public class GatewayFactory { private Map gateways = new HashMap<>(); diff --git a/gateway/src/test/java/com/iluwatar/gateway/AppTest.java b/gateway/src/test/java/com/iluwatar/gateway/AppTest.java index 76dc45e53..0776926ed 100644 --- a/gateway/src/test/java/com/iluwatar/gateway/AppTest.java +++ b/gateway/src/test/java/com/iluwatar/gateway/AppTest.java @@ -24,86 +24,88 @@ */ package com.iluwatar.gateway; -import org.junit.Before; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.*; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import java.util.concurrent.*; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class AppTest { - private GatewayFactory gatewayFactory; - private ExecutorService executorService; - @Before - public void setUp() { - gatewayFactory = new GatewayFactory(); - executorService = Executors.newFixedThreadPool(2); - gatewayFactory.registerGateway("ServiceA", new ExternalServiceA()); - gatewayFactory.registerGateway("ServiceB", new ExternalServiceB()); - gatewayFactory.registerGateway("ServiceC", new ExternalServiceC()); - } + private GatewayFactory gatewayFactory; + private ExecutorService executorService; - @Test - public void testServiceAExecution() throws InterruptedException, ExecutionException { - // Test Service A execution - Future serviceAFuture = executorService.submit(() -> { - try { + @BeforeEach + void setUp() { + gatewayFactory = new GatewayFactory(); + executorService = Executors.newFixedThreadPool(2); + gatewayFactory.registerGateway("ServiceA", new ExternalServiceA()); + gatewayFactory.registerGateway("ServiceB", new ExternalServiceB()); + gatewayFactory.registerGateway("ServiceC", new ExternalServiceC()); + } + + @Test + void testServiceAExecution() throws InterruptedException, ExecutionException { + // Test Service A execution + Future serviceAFuture = + executorService.submit( + () -> { + try { Gateway serviceA = gatewayFactory.getGateway("ServiceA"); serviceA.execute(); - } catch (Exception e) { + } catch (Exception e) { fail("Service A should not throw an exception."); - } - }); + } + }); - // Wait for Service A to complete - serviceAFuture.get(); - } + // Wait for Service A to complete + serviceAFuture.get(); + } - @Test - public void testServiceCExecutionWithException() throws InterruptedException, ExecutionException { - // Test Service B execution with an exception - Future serviceBFuture = executorService.submit(() -> { - try { + @Test + void testServiceCExecutionWithException() throws InterruptedException, ExecutionException { + // Test Service B execution with an exception + Future serviceBFuture = + executorService.submit( + () -> { + try { Gateway serviceB = gatewayFactory.getGateway("ServiceB"); serviceB.execute(); - } catch (Exception e) { + } catch (Exception e) { fail("Service B should not throw an exception."); - } - }); + } + }); - // Wait for Service B to complete - serviceBFuture.get(); - } + // Wait for Service B to complete + serviceBFuture.get(); + } - @Test - public void testServiceCExecution() throws InterruptedException, ExecutionException { - // Test Service C execution - Future serviceCFuture = executorService.submit(() -> { - try { + @Test + void testServiceCExecution() throws InterruptedException, ExecutionException { + // Test Service C execution + Future serviceCFuture = + executorService.submit( + () -> { + try { Gateway serviceC = gatewayFactory.getGateway("ServiceC"); serviceC.execute(); - } catch (Exception e) { + } catch (Exception e) { fail("Service C should not throw an exception."); - } - }); + } + }); - // Wait for Service C to complete - serviceCFuture.get(); - } + // Wait for Service C to complete + serviceCFuture.get(); + } - @Test - public void testServiceCError() { - try { - ExternalServiceC serviceC = (ExternalServiceC) gatewayFactory.getGateway("ServiceC"); - serviceC.error(); - fail("Service C should throw an exception."); - } catch (Exception e) { - assertEquals("Service C encountered an error", e.getMessage()); - } + @Test + void testServiceCError() { + try { + ExternalServiceC serviceC = (ExternalServiceC) gatewayFactory.getGateway("ServiceC"); + serviceC.error(); + fail("Service C should throw an exception."); + } catch (Exception e) { + assertEquals("Service C encountered an error", e.getMessage()); } + } } diff --git a/gateway/src/test/java/com/iluwatar/gateway/ServiceFactoryTest.java b/gateway/src/test/java/com/iluwatar/gateway/ServiceFactoryTest.java index c2d118cc1..f5e216cb2 100644 --- a/gateway/src/test/java/com/iluwatar/gateway/ServiceFactoryTest.java +++ b/gateway/src/test/java/com/iluwatar/gateway/ServiceFactoryTest.java @@ -24,70 +24,69 @@ */ package com.iluwatar.gateway; +import static org.junit.jupiter.api.Assertions.*; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; +import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicBoolean; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class ServiceFactoryTest { - private GatewayFactory gatewayFactory; - private ExecutorService executorService; - @Before - public void setUp() { - gatewayFactory = new GatewayFactory(); - executorService = Executors.newFixedThreadPool(2); - gatewayFactory.registerGateway("ServiceA", new ExternalServiceA()); - gatewayFactory.registerGateway("ServiceB", new ExternalServiceB()); - gatewayFactory.registerGateway("ServiceC", new ExternalServiceC()); + private GatewayFactory gatewayFactory; + private ExecutorService executorService; + + @BeforeEach + void setUp() { + gatewayFactory = new GatewayFactory(); + executorService = Executors.newFixedThreadPool(2); + gatewayFactory.registerGateway("ServiceA", new ExternalServiceA()); + gatewayFactory.registerGateway("ServiceB", new ExternalServiceB()); + gatewayFactory.registerGateway("ServiceC", new ExternalServiceC()); + } + + @Test + void testGatewayFactoryRegistrationAndRetrieval() { + Gateway serviceA = gatewayFactory.getGateway("ServiceA"); + Gateway serviceB = gatewayFactory.getGateway("ServiceB"); + Gateway serviceC = gatewayFactory.getGateway("ServiceC"); + + // Check if the retrieved instances match their expected types + assertTrue( + serviceA instanceof ExternalServiceA, "ServiceA should be an instance of ExternalServiceA"); + assertTrue( + serviceB instanceof ExternalServiceB, "ServiceB should be an instance of ExternalServiceB"); + assertTrue( + serviceC instanceof ExternalServiceC, "ServiceC should be an instance of ExternalServiceC"); + } + + @Test + void testGatewayFactoryRegistrationWithNonExistingKey() { + Gateway nonExistingService = gatewayFactory.getGateway("NonExistingService"); + assertNull(nonExistingService); + } + + @Test + void testGatewayFactoryConcurrency() throws InterruptedException { + int numThreads = 10; + CountDownLatch latch = new CountDownLatch(numThreads); + AtomicBoolean failed = new AtomicBoolean(false); + + for (int i = 0; i < numThreads; i++) { + executorService.submit( + () -> { + try { + Gateway serviceA = gatewayFactory.getGateway("ServiceA"); + serviceA.execute(); + } catch (Exception e) { + failed.set(true); + } finally { + latch.countDown(); + } + }); } - @Test - public void testGatewayFactoryRegistrationAndRetrieval() { - Gateway serviceA = gatewayFactory.getGateway("ServiceA"); - Gateway serviceB = gatewayFactory.getGateway("ServiceB"); - Gateway serviceC = gatewayFactory.getGateway("ServiceC"); - - // Check if the retrieved instances match their expected types - assertTrue("ServiceA should be an instance of ExternalServiceA", serviceA instanceof ExternalServiceA); - assertTrue("ServiceB should be an instance of ExternalServiceB", serviceB instanceof ExternalServiceB); - assertTrue("ServiceC should be an instance of ExternalServiceC", serviceC instanceof ExternalServiceC); - } - - @Test - public void testGatewayFactoryRegistrationWithNonExistingKey() { - Gateway nonExistingService = gatewayFactory.getGateway("NonExistingService"); - assertNull(nonExistingService); - } - - @Test - public void testGatewayFactoryConcurrency() throws InterruptedException { - int numThreads = 10; - CountDownLatch latch = new CountDownLatch(numThreads); - AtomicBoolean failed = new AtomicBoolean(false); - - for (int i = 0; i < numThreads; i++) { - executorService.submit(() -> { - try { - Gateway serviceA = gatewayFactory.getGateway("ServiceA"); - serviceA.execute(); - } catch (Exception e) { - failed.set(true); - } finally { - latch.countDown(); - } - }); - } - - latch.await(); - assertFalse("This should not fail", failed.get()); - } + latch.await(); + assertFalse(failed.get(), "This should not fail"); + } } diff --git a/guarded-suspension/pom.xml b/guarded-suspension/pom.xml index 2e4fdec92..099bfe1e4 100644 --- a/guarded-suspension/pom.xml +++ b/guarded-suspension/pom.xml @@ -35,6 +35,14 @@ jar guarded-suspension + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/guarded-suspension/src/main/java/com/iluwatar/guarded/suspension/App.java b/guarded-suspension/src/main/java/com/iluwatar/guarded/suspension/App.java index 8503751d5..5c6b7e054 100644 --- a/guarded-suspension/src/main/java/com/iluwatar/guarded/suspension/App.java +++ b/guarded-suspension/src/main/java/com/iluwatar/guarded/suspension/App.java @@ -30,14 +30,13 @@ import lombok.extern.slf4j.Slf4j; /** * Guarded-suspension is a concurrent design pattern for handling situation when to execute some - * action we need condition to be satisfied. - * The implementation utilizes a GuardedQueue, which features two primary methods: `get` and `put`. - * The key condition governing these operations is that elements cannot be retrieved (`get`) from - * an empty queue. When a thread attempts to retrieve an element under this condition, it triggers - * the invocation of the `wait` method from the Object class, causing the thread to pause. - * Conversely, when an element is added (`put`) to the queue by another thread, it invokes the - * `notify` method. This notifies the waiting thread that it can now successfully retrieve an - * element from the queue. + * action we need condition to be satisfied. The implementation utilizes a GuardedQueue, which + * features two primary methods: `get` and `put`. The key condition governing these operations is + * that elements cannot be retrieved (`get`) from an empty queue. When a thread attempts to retrieve + * an element under this condition, it triggers the invocation of the `wait` method from the Object + * class, causing the thread to pause. Conversely, when an element is added (`put`) to the queue by + * another thread, it invokes the `notify` method. This notifies the waiting thread that it can now + * successfully retrieve an element from the queue. */ @Slf4j public class App { @@ -50,7 +49,7 @@ public class App { var guardedQueue = new GuardedQueue(); var executorService = Executors.newFixedThreadPool(3); - //here we create first thread which is supposed to get from guardedQueue + // here we create first thread which is supposed to get from guardedQueue executorService.execute(guardedQueue::get); // here we wait two seconds to show that the thread which is trying 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 c53868b32..346e7193a 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 @@ -33,7 +33,8 @@ import lombok.extern.slf4j.Slf4j; * 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/ + * @see http://java-design-patterns.com/patterns/guarded-suspension/ */ @Slf4j public class GuardedQueue { 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 a88e96968..edbcf5145 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 @@ -31,9 +31,7 @@ import java.util.concurrent.TimeUnit; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.Test; -/** - * Test for Guarded Queue. - */ +/** Test for Guarded Queue. */ @Slf4j class GuardedQueueTest { private volatile Integer value; @@ -59,5 +57,4 @@ class GuardedQueueTest { g.put(12); assertEquals(Integer.valueOf(12), g.get()); } - } diff --git a/half-sync-half-async/pom.xml b/half-sync-half-async/pom.xml index 28cbf2023..33d6803db 100644 --- a/half-sync-half-async/pom.xml +++ b/half-sync-half-async/pom.xml @@ -34,6 +34,14 @@ half-sync-half-async + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/half-sync-half-async/src/main/java/com/iluwatar/halfsynchalfasync/App.java b/half-sync-half-async/src/main/java/com/iluwatar/halfsynchalfasync/App.java index 5d2c31290..1a8baafbc 100644 --- a/half-sync-half-async/src/main/java/com/iluwatar/halfsynchalfasync/App.java +++ b/half-sync-half-async/src/main/java/com/iluwatar/halfsynchalfasync/App.java @@ -43,13 +43,14 @@ import lombok.extern.slf4j.Slf4j; * *

APPLICABILITY
* UNIX network subsystems - In operating systems network operations are carried out asynchronously - * with help of hardware level interrupts.
CORBA - At the asynchronous layer one thread is - * associated with each socket that is connected to the client. Thread blocks waiting for CORBA - * requests from the client. On receiving request it is inserted in the queuing layer which is then - * picked up by synchronous layer which processes the request and sends response back to the - * client.
Android AsyncTask framework - Framework provides a way to execute long-running - * blocking calls, such as downloading a file, in background threads so that the UI thread remains - * free to respond to user inputs.
+ * with help of hardware level interrupts.
+ * CORBA - At the asynchronous layer one thread is associated with each socket that is connected to + * the client. Thread blocks waiting for CORBA requests from the client. On receiving request it is + * inserted in the queuing layer which is then picked up by synchronous layer which processes the + * request and sends response back to the client.
+ * Android AsyncTask framework - Framework provides a way to execute long-running blocking calls, + * such as downloading a file, in background threads so that the UI thread remains free to respond + * to user inputs.
* *

IMPLEMENTATION
* The main method creates an asynchronous service which does not block the main thread while the @@ -90,9 +91,7 @@ public class App { service.close(); } - /** - * ArithmeticSumTask. - */ + /** ArithmeticSumTask. */ static class ArithmeticSumTask implements AsyncTask { private final long numberOfElements; diff --git a/half-sync-half-async/src/main/java/com/iluwatar/halfsynchalfasync/AsynchronousService.java b/half-sync-half-async/src/main/java/com/iluwatar/halfsynchalfasync/AsynchronousService.java index c7aaa1651..ca31b0d8b 100644 --- a/half-sync-half-async/src/main/java/com/iluwatar/halfsynchalfasync/AsynchronousService.java +++ b/half-sync-half-async/src/main/java/com/iluwatar/halfsynchalfasync/AsynchronousService.java @@ -58,7 +58,6 @@ public class AsynchronousService { service = new ThreadPoolExecutor(10, 10, 10, TimeUnit.SECONDS, workQueue); } - /** * A non-blocking method which performs the task provided in background and returns immediately. * @@ -79,30 +78,29 @@ public class AsynchronousService { return; } - service.submit(new FutureTask<>(task) { - @Override - protected void done() { - super.done(); - try { - /* - * called in context of background thread. There is other variant possible where result is - * posted back and sits in the queue of caller thread which then picks it up for - * processing. An example of such a system is Android OS, where the UI elements can only - * be updated using UI thread. So result must be posted back in UI thread. - */ - task.onPostCall(get()); - } catch (InterruptedException e) { - // should not occur - } catch (ExecutionException e) { - task.onError(e.getCause()); - } - } - }); + service.submit( + new FutureTask<>(task) { + @Override + protected void done() { + super.done(); + try { + /* + * called in context of background thread. There is other variant possible where result is + * posted back and sits in the queue of caller thread which then picks it up for + * processing. An example of such a system is Android OS, where the UI elements can only + * be updated using UI thread. So result must be posted back in UI thread. + */ + task.onPostCall(get()); + } catch (InterruptedException e) { + // should not occur + } catch (ExecutionException e) { + task.onError(e.getCause()); + } + } + }); } - /** - * Stops the pool of workers. This is a blocking call to wait for all tasks to be completed. - */ + /** Stops the pool of workers. This is a blocking call to wait for all tasks to be completed. */ public void close() { service.shutdown(); try { diff --git a/half-sync-half-async/src/test/java/com/iluwatar/halfsynchalfasync/AppTest.java b/half-sync-half-async/src/test/java/com/iluwatar/halfsynchalfasync/AppTest.java index d445a155c..a871c81cb 100644 --- a/half-sync-half-async/src/test/java/com/iluwatar/halfsynchalfasync/AppTest.java +++ b/half-sync-half-async/src/test/java/com/iluwatar/halfsynchalfasync/AppTest.java @@ -24,13 +24,11 @@ */ package com.iluwatar.halfsynchalfasync; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -/** - * Application test - */ +import org.junit.jupiter.api.Test; + +/** Application test */ class AppTest { @Test diff --git a/half-sync-half-async/src/test/java/com/iluwatar/halfsynchalfasync/AsynchronousServiceTest.java b/half-sync-half-async/src/test/java/com/iluwatar/halfsynchalfasync/AsynchronousServiceTest.java index b9060c42a..1360f7daa 100644 --- a/half-sync-half-async/src/test/java/com/iluwatar/halfsynchalfasync/AsynchronousServiceTest.java +++ b/half-sync-half-async/src/test/java/com/iluwatar/halfsynchalfasync/AsynchronousServiceTest.java @@ -39,10 +39,7 @@ import java.util.concurrent.LinkedBlockingQueue; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -/** - * AsynchronousServiceTest - * - */ +/** AsynchronousServiceTest */ class AsynchronousServiceTest { private AsynchronousService service; private AsyncTask task; @@ -99,5 +96,4 @@ class AsynchronousServiceTest { verifyNoMoreInteractions(task); } - -} \ No newline at end of file +} diff --git a/health-check/pom.xml b/health-check/pom.xml index b96b07a3b..203503ad0 100644 --- a/health-check/pom.xml +++ b/health-check/pom.xml @@ -36,43 +36,38 @@ health-check - - - - org.springframework.boot - spring-boot-dependencies - pom - 3.2.3 - import - - - org.hibernate - hibernate-core - 6.4.4.Final - - - - + + org.springframework.boot + spring-boot-starter + org.springframework.boot spring-boot-starter-web - jakarta.xml.bind - jakarta.xml.bind-api + org.springframework.boot + spring-boot-starter-test + test - org.springframework.boot spring-boot-starter-actuator - - org.springframework.boot spring-boot-starter-data-jpa + + org.hibernate + hibernate-core + 6.4.4.Final + + + jakarta.xml.bind + jakarta.xml.bind-api + 4.0.2 + @@ -85,21 +80,7 @@ org.springframework.retry spring-retry - - - - - - org.junit.jupiter - junit-jupiter-engine - test - - - - - org.mockito - mockito-core - test + 2.0.11 @@ -120,6 +101,7 @@ io.rest-assured rest-assured + 5.5.1 test diff --git a/health-check/src/main/java/com/iluwatar/health/check/App.java b/health-check/src/main/java/com/iluwatar/health/check/App.java index ae2845225..8f8faed9f 100644 --- a/health-check/src/main/java/com/iluwatar/health/check/App.java +++ b/health-check/src/main/java/com/iluwatar/health/check/App.java @@ -36,7 +36,6 @@ import org.springframework.scheduling.annotation.EnableScheduling; * their availability and responsiveness. For more information about health checks and their role in * microservice architectures, please refer to: [Microservices Health Checks * API]('https://microservices.io/patterns/observability/health-check-api.html'). - * */ @EnableCaching @EnableScheduling diff --git a/health-check/src/main/java/com/iluwatar/health/check/AsynchronousHealthChecker.java b/health-check/src/main/java/com/iluwatar/health/check/AsynchronousHealthChecker.java index 5cf015db8..50433d48a 100644 --- a/health-check/src/main/java/com/iluwatar/health/check/AsynchronousHealthChecker.java +++ b/health-check/src/main/java/com/iluwatar/health/check/AsynchronousHealthChecker.java @@ -37,10 +37,7 @@ import lombok.extern.slf4j.Slf4j; import org.springframework.boot.actuate.health.Health; import org.springframework.stereotype.Component; -/** - * An asynchronous health checker component that executes health checks in a separate thread. - * - */ +/** An asynchronous health checker component that executes health checks in a separate thread. */ @Slf4j @Component @RequiredArgsConstructor diff --git a/health-check/src/main/java/com/iluwatar/health/check/CpuHealthIndicator.java b/health-check/src/main/java/com/iluwatar/health/check/CpuHealthIndicator.java index c224a01b6..451b1263b 100644 --- a/health-check/src/main/java/com/iluwatar/health/check/CpuHealthIndicator.java +++ b/health-check/src/main/java/com/iluwatar/health/check/CpuHealthIndicator.java @@ -38,10 +38,7 @@ import org.springframework.boot.actuate.health.Health; import org.springframework.boot.actuate.health.HealthIndicator; import org.springframework.stereotype.Component; -/** - * A health indicator that checks the health of the system's CPU. - * - */ +/** A health indicator that checks the health of the system's CPU. */ @Getter @Setter @Slf4j @@ -136,4 +133,4 @@ public class CpuHealthIndicator implements HealthIndicator { return Health.up().withDetails(details).build(); } } -} \ No newline at end of file +} diff --git a/health-check/src/main/java/com/iluwatar/health/check/CustomHealthIndicator.java b/health-check/src/main/java/com/iluwatar/health/check/CustomHealthIndicator.java index ccdf14624..54f2efe04 100644 --- a/health-check/src/main/java/com/iluwatar/health/check/CustomHealthIndicator.java +++ b/health-check/src/main/java/com/iluwatar/health/check/CustomHealthIndicator.java @@ -40,7 +40,6 @@ import org.springframework.stereotype.Component; /** * A custom health indicator that periodically checks the health of a database and caches the * result. It leverages an asynchronous health checker to perform the health checks. - * */ @Slf4j @Component diff --git a/health-check/src/main/java/com/iluwatar/health/check/DatabaseTransactionHealthIndicator.java b/health-check/src/main/java/com/iluwatar/health/check/DatabaseTransactionHealthIndicator.java index 3f5b33798..81658a27c 100644 --- a/health-check/src/main/java/com/iluwatar/health/check/DatabaseTransactionHealthIndicator.java +++ b/health-check/src/main/java/com/iluwatar/health/check/DatabaseTransactionHealthIndicator.java @@ -41,7 +41,6 @@ import org.springframework.stereotype.Component; * test transaction using a retry mechanism. If the transaction succeeds after multiple attempts, * the health indicator returns {@link Health#up()} and logs a success message. If all retry * attempts fail, the health indicator returns {@link Health#down()} and logs an error message. - * */ @Slf4j @Component diff --git a/health-check/src/main/java/com/iluwatar/health/check/GarbageCollectionHealthIndicator.java b/health-check/src/main/java/com/iluwatar/health/check/GarbageCollectionHealthIndicator.java index 460165275..0790f0407 100644 --- a/health-check/src/main/java/com/iluwatar/health/check/GarbageCollectionHealthIndicator.java +++ b/health-check/src/main/java/com/iluwatar/health/check/GarbageCollectionHealthIndicator.java @@ -44,7 +44,6 @@ import org.springframework.stereotype.Component; * reports the health status accordingly. It gathers information about the collection count, * collection time, memory pool name, and garbage collector algorithm for each garbage collector and * presents the details in a structured manner. - * */ @Slf4j @Component diff --git a/health-check/src/main/java/com/iluwatar/health/check/HealthCheck.java b/health-check/src/main/java/com/iluwatar/health/check/HealthCheck.java index 46b0505c3..6223acde0 100644 --- a/health-check/src/main/java/com/iluwatar/health/check/HealthCheck.java +++ b/health-check/src/main/java/com/iluwatar/health/check/HealthCheck.java @@ -34,7 +34,6 @@ import lombok.Data; /** * An entity class that represents a health check record in the database. This class is used to * persist the results of health checks performed by the `DatabaseTransactionHealthIndicator`. - * */ @Entity @Data diff --git a/health-check/src/main/java/com/iluwatar/health/check/HealthCheckRepository.java b/health-check/src/main/java/com/iluwatar/health/check/HealthCheckRepository.java index 83ac27792..d5016323a 100644 --- a/health-check/src/main/java/com/iluwatar/health/check/HealthCheckRepository.java +++ b/health-check/src/main/java/com/iluwatar/health/check/HealthCheckRepository.java @@ -33,7 +33,6 @@ import org.springframework.stereotype.Repository; /** * A repository class for managing health check records in the database. This class provides methods * for checking the health of the database connection and performing test transactions. - * */ @Slf4j @Repository diff --git a/health-check/src/main/java/com/iluwatar/health/check/MemoryHealthIndicator.java b/health-check/src/main/java/com/iluwatar/health/check/MemoryHealthIndicator.java index b69fd9d74..08d82dd4a 100644 --- a/health-check/src/main/java/com/iluwatar/health/check/MemoryHealthIndicator.java +++ b/health-check/src/main/java/com/iluwatar/health/check/MemoryHealthIndicator.java @@ -41,7 +41,6 @@ import org.springframework.stereotype.Component; * A custom health indicator that checks the memory usage of the application and reports the health * status accordingly. It uses an asynchronous health checker to perform the health check and a * configurable memory usage threshold to determine the health status. - * */ @Slf4j @Component diff --git a/health-check/src/main/java/com/iluwatar/health/check/RetryConfig.java b/health-check/src/main/java/com/iluwatar/health/check/RetryConfig.java index f05c1eb91..026a4dd11 100644 --- a/health-check/src/main/java/com/iluwatar/health/check/RetryConfig.java +++ b/health-check/src/main/java/com/iluwatar/health/check/RetryConfig.java @@ -32,10 +32,7 @@ import org.springframework.retry.policy.SimpleRetryPolicy; import org.springframework.retry.support.RetryTemplate; import org.springframework.stereotype.Component; -/** - * Configuration class for retry policies used in health check operations. - * - */ +/** Configuration class for retry policies used in health check operations. */ @Configuration @Component public class RetryConfig { diff --git a/health-check/src/test/java/AsynchronousHealthCheckerTest.java b/health-check/src/test/java/AsynchronousHealthCheckerTest.java index 52751c41b..2241f1989 100644 --- a/health-check/src/test/java/AsynchronousHealthCheckerTest.java +++ b/health-check/src/test/java/AsynchronousHealthCheckerTest.java @@ -45,10 +45,7 @@ import org.slf4j.LoggerFactory; import org.springframework.boot.actuate.health.Health; import org.springframework.boot.actuate.health.Status; -/** - * Tests for {@link AsynchronousHealthChecker}. - * - */ +/** Tests for {@link AsynchronousHealthChecker}. */ @Slf4j class AsynchronousHealthCheckerTest { diff --git a/health-check/src/test/java/CpuHealthIndicatorTest.java b/health-check/src/test/java/CpuHealthIndicatorTest.java index 8391dde33..c59f3fea7 100644 --- a/health-check/src/test/java/CpuHealthIndicatorTest.java +++ b/health-check/src/test/java/CpuHealthIndicatorTest.java @@ -34,10 +34,7 @@ import org.mockito.Mockito; import org.springframework.boot.actuate.health.Health; import org.springframework.boot.actuate.health.Status; -/** - * Test class for the {@link CpuHealthIndicator} class. - * - */ +/** Test class for the {@link CpuHealthIndicator} class. */ class CpuHealthIndicatorTest { /** The CPU health indicator to be tested. */ diff --git a/health-check/src/test/java/CustomHealthIndicatorTest.java b/health-check/src/test/java/CustomHealthIndicatorTest.java index 1acb0e536..1c48861aa 100644 --- a/health-check/src/test/java/CustomHealthIndicatorTest.java +++ b/health-check/src/test/java/CustomHealthIndicatorTest.java @@ -47,10 +47,7 @@ import org.springframework.cache.concurrent.ConcurrentMapCacheManager; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -/** - * Tests class< for {@link CustomHealthIndicator}. * - * - */ +/** Tests class< for {@link CustomHealthIndicator}. * */ class CustomHealthIndicatorTest { /** Mocked AsynchronousHealthChecker instance. */ diff --git a/health-check/src/test/java/DatabaseTransactionHealthIndicatorTest.java b/health-check/src/test/java/DatabaseTransactionHealthIndicatorTest.java index 0d7dfc2e9..c396770d1 100644 --- a/health-check/src/test/java/DatabaseTransactionHealthIndicatorTest.java +++ b/health-check/src/test/java/DatabaseTransactionHealthIndicatorTest.java @@ -43,10 +43,7 @@ import org.springframework.boot.actuate.health.Health; import org.springframework.boot.actuate.health.Status; import org.springframework.retry.support.RetryTemplate; -/** - * Unit tests for the {@link DatabaseTransactionHealthIndicator} class. - * - */ +/** Unit tests for the {@link DatabaseTransactionHealthIndicator} class. */ class DatabaseTransactionHealthIndicatorTest { /** Timeout value in seconds for the health check. */ diff --git a/health-check/src/test/java/GarbageCollectionHealthIndicatorTest.java b/health-check/src/test/java/GarbageCollectionHealthIndicatorTest.java index a0c914e2b..6f3068b03 100644 --- a/health-check/src/test/java/GarbageCollectionHealthIndicatorTest.java +++ b/health-check/src/test/java/GarbageCollectionHealthIndicatorTest.java @@ -40,10 +40,7 @@ import org.mockito.MockitoAnnotations; import org.springframework.boot.actuate.health.Health; import org.springframework.boot.actuate.health.Status; -/** - * Test class for {@link GarbageCollectionHealthIndicator}. - * - */ +/** Test class for {@link GarbageCollectionHealthIndicator}. */ class GarbageCollectionHealthIndicatorTest { /** Mocked garbage collector MXBean. */ diff --git a/health-check/src/test/java/HealthCheckRepositoryTest.java b/health-check/src/test/java/HealthCheckRepositoryTest.java index 7942535c4..8a630299d 100644 --- a/health-check/src/test/java/HealthCheckRepositoryTest.java +++ b/health-check/src/test/java/HealthCheckRepositoryTest.java @@ -35,10 +35,7 @@ import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; -/** - * Tests class for {@link HealthCheckRepository}. - * - */ +/** Tests class for {@link HealthCheckRepository}. */ @ExtendWith(MockitoExtension.class) class HealthCheckRepositoryTest { diff --git a/health-check/src/test/java/HealthEndpointIntegrationTest.java b/health-check/src/test/java/HealthEndpointIntegrationTest.java index da8dfaeca..0d0a3d8f8 100644 --- a/health-check/src/test/java/HealthEndpointIntegrationTest.java +++ b/health-check/src/test/java/HealthEndpointIntegrationTest.java @@ -48,7 +48,6 @@ import org.springframework.http.HttpStatus; * {"status":"DOWN","components":{"cpu":{"status":"DOWN","details":{"processCpuLoad":"100.00%", * * "availableProcessors":2,"systemCpuLoad":"100.00%","loadAverage":1.97,"timestamp":"2023-11-09T08:34:15.974557865Z", * * "error":"High system CPU load"}}} * - * */ @Slf4j @SpringBootTest( diff --git a/health-check/src/test/java/MemoryHealthIndicatorTest.java b/health-check/src/test/java/MemoryHealthIndicatorTest.java index 13676af65..8b8da1613 100644 --- a/health-check/src/test/java/MemoryHealthIndicatorTest.java +++ b/health-check/src/test/java/MemoryHealthIndicatorTest.java @@ -41,10 +41,7 @@ import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.boot.actuate.health.Health; import org.springframework.boot.actuate.health.Status; -/** - * Unit tests for {@link MemoryHealthIndicator}. - * - */ +/** Unit tests for {@link MemoryHealthIndicator}. */ @ExtendWith(MockitoExtension.class) class MemoryHealthIndicatorTest { diff --git a/health-check/src/test/java/RetryConfigTest.java b/health-check/src/test/java/RetryConfigTest.java index 4341aeef9..947616e45 100644 --- a/health-check/src/test/java/RetryConfigTest.java +++ b/health-check/src/test/java/RetryConfigTest.java @@ -32,10 +32,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.retry.support.RetryTemplate; -/** - * Unit tests for the {@link RetryConfig} class. - * - */ +/** Unit tests for the {@link RetryConfig} class. */ @SpringBootTest(classes = RetryConfig.class) class RetryConfigTest { diff --git a/hexagonal-architecture/pom.xml b/hexagonal-architecture/pom.xml index d79a7c124..3f19bfa95 100644 --- a/hexagonal-architecture/pom.xml +++ b/hexagonal-architecture/pom.xml @@ -34,6 +34,14 @@ hexagonal-architecture + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/App.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/App.java index 13b173a6a..b2ea0e635 100644 --- a/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/App.java +++ b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/App.java @@ -58,9 +58,7 @@ import com.iluwatar.hexagonal.sampledata.SampleData; */ public class App { - /** - * Program entry point. - */ + /** Program entry point. */ public static void main(String[] args) { var injector = Guice.createInjector(new LotteryTestingModule()); diff --git a/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/administration/ConsoleAdministration.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/administration/ConsoleAdministration.java index 718758483..80c47e3d1 100644 --- a/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/administration/ConsoleAdministration.java +++ b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/administration/ConsoleAdministration.java @@ -33,15 +33,11 @@ import com.iluwatar.hexagonal.sampledata.SampleData; import java.util.Scanner; import lombok.extern.slf4j.Slf4j; -/** - * Console interface for lottery administration. - */ +/** Console interface for lottery administration. */ @Slf4j public class ConsoleAdministration { - /** - * Program entry point. - */ + /** Program entry point. */ public static void main(String[] args) { MongoConnectionPropertiesLoader.load(); var injector = Guice.createInjector(new LotteryModule()); diff --git a/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/administration/ConsoleAdministrationSrv.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/administration/ConsoleAdministrationSrv.java index 44eefccc3..f361ede46 100644 --- a/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/administration/ConsoleAdministrationSrv.java +++ b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/administration/ConsoleAdministrationSrv.java @@ -24,23 +24,15 @@ */ package com.iluwatar.hexagonal.administration; -/** - * Console interface for lottery administration. - */ +/** Console interface for lottery administration. */ public interface ConsoleAdministrationSrv { - /** - * Get all submitted tickets. - */ + /** Get all submitted tickets. */ void getAllSubmittedTickets(); - /** - * Draw lottery numbers. - */ + /** Draw lottery numbers. */ void performLottery(); - /** - * Begin new lottery round. - */ + /** Begin new lottery round. */ void resetLottery(); } diff --git a/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/administration/ConsoleAdministrationSrvImpl.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/administration/ConsoleAdministrationSrvImpl.java index 8808f507c..02612ff83 100644 --- a/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/administration/ConsoleAdministrationSrvImpl.java +++ b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/administration/ConsoleAdministrationSrvImpl.java @@ -27,16 +27,12 @@ package com.iluwatar.hexagonal.administration; import com.iluwatar.hexagonal.domain.LotteryAdministration; import org.slf4j.Logger; -/** - * Console implementation for lottery administration. - */ +/** Console implementation for lottery administration. */ public class ConsoleAdministrationSrvImpl implements ConsoleAdministrationSrv { private final LotteryAdministration administration; private final Logger logger; - /** - * Constructor. - */ + /** Constructor. */ public ConsoleAdministrationSrvImpl(LotteryAdministration administration, Logger logger) { this.administration = administration; this.logger = logger; @@ -44,7 +40,8 @@ public class ConsoleAdministrationSrvImpl implements ConsoleAdministrationSrv { @Override public void getAllSubmittedTickets() { - administration.getAllSubmittedTickets() + administration + .getAllSubmittedTickets() .forEach((k, v) -> logger.info("Key: {}, Value: {}", k, v)); } diff --git a/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/banking/InMemoryBank.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/banking/InMemoryBank.java index f1754a65f..421d5c32d 100644 --- a/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/banking/InMemoryBank.java +++ b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/banking/InMemoryBank.java @@ -28,16 +28,14 @@ import com.iluwatar.hexagonal.domain.LotteryConstants; import java.util.HashMap; import java.util.Map; -/** - * Banking implementation. - */ +/** Banking implementation. */ public class InMemoryBank implements WireTransfers { private static final Map accounts = new HashMap<>(); static { - accounts - .put(LotteryConstants.SERVICE_BANK_ACCOUNT, LotteryConstants.SERVICE_BANK_ACCOUNT_BALANCE); + accounts.put( + LotteryConstants.SERVICE_BANK_ACCOUNT, LotteryConstants.SERVICE_BANK_ACCOUNT_BALANCE); } @Override diff --git a/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/banking/MongoBank.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/banking/MongoBank.java index 23f1cc8fc..c7af46931 100644 --- a/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/banking/MongoBank.java +++ b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/banking/MongoBank.java @@ -32,51 +32,39 @@ import java.util.ArrayList; import lombok.Getter; import org.bson.Document; -/** - * Mongo based banking adapter. - */ +/** Mongo based banking adapter. */ public class MongoBank implements WireTransfers { private static final String DEFAULT_DB = "lotteryDB"; private static final String DEFAULT_ACCOUNTS_COLLECTION = "accounts"; - @Getter - private MongoClient mongoClient; - @Getter - private MongoDatabase database; - @Getter - private MongoCollection accountsCollection; + @Getter private MongoClient mongoClient; + @Getter private MongoDatabase database; + @Getter private MongoCollection accountsCollection; - /** - * Constructor. - */ + /** Constructor. */ public MongoBank() { connect(); } - /** - * Constructor accepting parameters. - */ + /** Constructor accepting parameters. */ public MongoBank(String dbName, String accountsCollectionName) { connect(dbName, accountsCollectionName); } - /** - * Connect to database with default parameters. - */ + /** Connect to database with default parameters. */ public void connect() { connect(DEFAULT_DB, DEFAULT_ACCOUNTS_COLLECTION); } - /** - * Connect to database with given parameters. - */ + /** Connect to database with given parameters. */ public void connect(String dbName, String accountsCollectionName) { if (mongoClient != null) { mongoClient.close(); } - mongoClient = new MongoClient(System.getProperty("mongo-host"), - Integer.parseInt(System.getProperty("mongo-port"))); + mongoClient = + new MongoClient( + System.getProperty("mongo-host"), Integer.parseInt(System.getProperty("mongo-port"))); database = mongoClient.getDatabase(dbName); accountsCollection = database.getCollection(accountsCollectionName); } diff --git a/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/banking/WireTransfers.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/banking/WireTransfers.java index d88827d8f..f89814209 100644 --- a/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/banking/WireTransfers.java +++ b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/banking/WireTransfers.java @@ -24,24 +24,15 @@ */ package com.iluwatar.hexagonal.banking; -/** - * Interface to bank accounts. - */ +/** Interface to bank accounts. */ public interface WireTransfers { - /** - * Set amount of funds for bank account. - */ + /** Set amount of funds for bank account. */ void setFunds(String bankAccount, int amount); - /** - * Get amount of funds for bank account. - */ + /** Get amount of funds for bank account. */ int getFunds(String bankAccount); - /** - * Transfer funds from one bank account to another. - */ + /** Transfer funds from one bank account to another. */ boolean transferFunds(int amount, String sourceBackAccount, String destinationBankAccount); - } diff --git a/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/database/InMemoryTicketRepository.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/database/InMemoryTicketRepository.java index 8c0aa1d74..5805e80aa 100644 --- a/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/database/InMemoryTicketRepository.java +++ b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/database/InMemoryTicketRepository.java @@ -30,9 +30,7 @@ import java.util.HashMap; import java.util.Map; import java.util.Optional; -/** - * Mock database for lottery tickets. - */ +/** Mock database for lottery tickets. */ public class InMemoryTicketRepository implements LotteryTicketRepository { private static final Map tickets = new HashMap<>(); diff --git a/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/database/LotteryTicketRepository.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/database/LotteryTicketRepository.java index 6302b6dd6..29ca16af7 100644 --- a/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/database/LotteryTicketRepository.java +++ b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/database/LotteryTicketRepository.java @@ -29,29 +29,18 @@ import com.iluwatar.hexagonal.domain.LotteryTicketId; import java.util.Map; import java.util.Optional; -/** - * Interface for accessing lottery tickets in database. - */ +/** Interface for accessing lottery tickets in database. */ public interface LotteryTicketRepository { - /** - * Find lottery ticket by id. - */ + /** Find lottery ticket by id. */ Optional findById(LotteryTicketId id); - /** - * Save lottery ticket. - */ + /** Save lottery ticket. */ Optional save(LotteryTicket ticket); - /** - * Get all lottery tickets. - */ + /** Get all lottery tickets. */ Map findAll(); - /** - * Delete all lottery tickets. - */ + /** Delete all lottery tickets. */ void deleteAll(); - } diff --git a/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/database/MongoTicketRepository.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/database/MongoTicketRepository.java index 9817a14a7..ecb26c9c4 100644 --- a/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/database/MongoTicketRepository.java +++ b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/database/MongoTicketRepository.java @@ -40,9 +40,7 @@ import java.util.stream.Collectors; import lombok.Getter; import org.bson.Document; -/** - * Mongo lottery ticket database. - */ +/** Mongo lottery ticket database. */ public class MongoTicketRepository implements LotteryTicketRepository { private static final String DEFAULT_DB = "lotteryDB"; @@ -52,43 +50,33 @@ public class MongoTicketRepository implements LotteryTicketRepository { private MongoClient mongoClient; private MongoDatabase database; - @Getter - private MongoCollection ticketsCollection; - @Getter - private MongoCollection countersCollection; + @Getter private MongoCollection ticketsCollection; + @Getter private MongoCollection countersCollection; - /** - * Constructor. - */ + /** Constructor. */ public MongoTicketRepository() { connect(); } - /** - * Constructor accepting parameters. - */ - public MongoTicketRepository(String dbName, String ticketsCollectionName, - String countersCollectionName) { + /** Constructor accepting parameters. */ + public MongoTicketRepository( + String dbName, String ticketsCollectionName, String countersCollectionName) { connect(dbName, ticketsCollectionName, countersCollectionName); } - /** - * Connect to database with default parameters. - */ + /** Connect to database with default parameters. */ public void connect() { connect(DEFAULT_DB, DEFAULT_TICKETS_COLLECTION, DEFAULT_COUNTERS_COLLECTION); } - /** - * Connect to database with given parameters. - */ - public void connect(String dbName, String ticketsCollectionName, - String countersCollectionName) { + /** Connect to database with given parameters. */ + public void connect(String dbName, String ticketsCollectionName, String countersCollectionName) { if (mongoClient != null) { mongoClient.close(); } - mongoClient = new MongoClient(System.getProperty("mongo-host"), - Integer.parseInt(System.getProperty("mongo-port"))); + mongoClient = + new MongoClient( + System.getProperty("mongo-host"), Integer.parseInt(System.getProperty("mongo-port"))); database = mongoClient.getDatabase(dbName); ticketsCollection = database.getCollection(ticketsCollectionName); countersCollection = database.getCollection(countersCollectionName); @@ -140,10 +128,7 @@ public class MongoTicketRepository implements LotteryTicketRepository { @Override public Map findAll() { - return ticketsCollection - .find(new Document()) - .into(new ArrayList<>()) - .stream() + return ticketsCollection.find(new Document()).into(new ArrayList<>()).stream() .map(this::docToTicket) .collect(Collectors.toMap(LotteryTicket::id, Function.identity())); } @@ -154,11 +139,12 @@ public class MongoTicketRepository implements LotteryTicketRepository { } private LotteryTicket docToTicket(Document doc) { - var playerDetails = new PlayerDetails(doc.getString("email"), doc.getString("bank"), - doc.getString("phone")); - var numbers = Arrays.stream(doc.getString("numbers").split(",")) - .map(Integer::parseInt) - .collect(Collectors.toSet()); + var playerDetails = + new PlayerDetails(doc.getString("email"), doc.getString("bank"), doc.getString("phone")); + var numbers = + Arrays.stream(doc.getString("numbers").split(",")) + .map(Integer::parseInt) + .collect(Collectors.toSet()); var lotteryNumbers = LotteryNumbers.create(numbers); var ticketId = new LotteryTicketId(doc.getInteger(TICKET_ID)); return new LotteryTicket(ticketId, playerDetails, lotteryNumbers); diff --git a/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/domain/LotteryAdministration.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/domain/LotteryAdministration.java index e21b028cc..28cf0fbbd 100644 --- a/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/domain/LotteryAdministration.java +++ b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/domain/LotteryAdministration.java @@ -33,36 +33,30 @@ import com.iluwatar.hexagonal.database.LotteryTicketRepository; import com.iluwatar.hexagonal.eventlog.LotteryEventLog; import java.util.Map; -/** - * Lottery administration implementation. - */ +/** Lottery administration implementation. */ public class LotteryAdministration { private final LotteryTicketRepository repository; private final LotteryEventLog notifications; private final WireTransfers wireTransfers; - /** - * Constructor. - */ + /** Constructor. */ @Inject - public LotteryAdministration(LotteryTicketRepository repository, LotteryEventLog notifications, - WireTransfers wireTransfers) { + public LotteryAdministration( + LotteryTicketRepository repository, + LotteryEventLog notifications, + WireTransfers wireTransfers) { this.repository = repository; this.notifications = notifications; this.wireTransfers = wireTransfers; } - /** - * Get all the lottery tickets submitted for lottery. - */ + /** Get all the lottery tickets submitted for lottery. */ public Map getAllSubmittedTickets() { return repository.findAll(); } - /** - * Draw lottery numbers. - */ + /** Draw lottery numbers. */ public LotteryNumbers performLottery() { var numbers = LotteryNumbers.createRandom(); var tickets = getAllSubmittedTickets(); @@ -84,9 +78,7 @@ public class LotteryAdministration { return numbers; } - /** - * Begin new lottery round. - */ + /** Begin new lottery round. */ public void resetLottery() { repository.deleteAll(); } diff --git a/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/domain/LotteryConstants.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/domain/LotteryConstants.java index 2001d57ac..21dcbc2d4 100644 --- a/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/domain/LotteryConstants.java +++ b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/domain/LotteryConstants.java @@ -24,18 +24,14 @@ */ package com.iluwatar.hexagonal.domain; -/** - * Lottery domain constants. - */ +/** Lottery domain constants. */ public class LotteryConstants { - private LotteryConstants() { - } + private LotteryConstants() {} public static final int PRIZE_AMOUNT = 100000; public static final String SERVICE_BANK_ACCOUNT = "123-123"; public static final int TICKET_PRIZE = 3; public static final int SERVICE_BANK_ACCOUNT_BALANCE = 150000; public static final int PLAYER_MAX_BALANCE = 100; - } diff --git a/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/domain/LotteryNumbers.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/domain/LotteryNumbers.java index 83836046d..3319251f4 100644 --- a/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/domain/LotteryNumbers.java +++ b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/domain/LotteryNumbers.java @@ -47,17 +47,13 @@ public class LotteryNumbers { public static final int MAX_NUMBER = 20; public static final int NUM_NUMBERS = 4; - /** - * Constructor. Creates random lottery numbers. - */ + /** Constructor. Creates random lottery numbers. */ private LotteryNumbers() { numbers = new HashSet<>(); generateRandomNumbers(); } - /** - * Constructor. Uses given numbers. - */ + /** Constructor. Uses given numbers. */ private LotteryNumbers(Set givenNumbers) { numbers = new HashSet<>(); numbers.addAll(givenNumbers); @@ -99,9 +95,7 @@ public class LotteryNumbers { return Joiner.on(',').join(numbers); } - /** - * Generates 4 unique random numbers between 1-20 into numbers set. - */ + /** Generates 4 unique random numbers between 1-20 into numbers set. */ private void generateRandomNumbers() { numbers.clear(); var generator = new RandomNumberGenerator(MIN_NUMBER, MAX_NUMBER); @@ -111,9 +105,7 @@ public class LotteryNumbers { } } - /** - * Helper class for generating random numbers. - */ + /** Helper class for generating random numbers. */ private static class RandomNumberGenerator { private final PrimitiveIterator.OfInt randomIterator; @@ -138,5 +130,4 @@ public class LotteryNumbers { return randomIterator.nextInt(); } } - } diff --git a/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/domain/LotteryService.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/domain/LotteryService.java index 8b6521498..38d33ab95 100644 --- a/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/domain/LotteryService.java +++ b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/domain/LotteryService.java @@ -33,29 +33,25 @@ import com.iluwatar.hexagonal.database.LotteryTicketRepository; import com.iluwatar.hexagonal.eventlog.LotteryEventLog; import java.util.Optional; -/** - * Implementation for lottery service. - */ +/** Implementation for lottery service. */ public class LotteryService { private final LotteryTicketRepository repository; private final LotteryEventLog notifications; private final WireTransfers wireTransfers; - /** - * Constructor. - */ + /** Constructor. */ @Inject - public LotteryService(LotteryTicketRepository repository, LotteryEventLog notifications, - WireTransfers wireTransfers) { + public LotteryService( + LotteryTicketRepository repository, + LotteryEventLog notifications, + WireTransfers wireTransfers) { this.repository = repository; this.notifications = notifications; this.wireTransfers = wireTransfers; } - /** - * Submit lottery ticket to participate in the lottery. - */ + /** Submit lottery ticket to participate in the lottery. */ public Optional submitTicket(LotteryTicket ticket) { var playerDetails = ticket.playerDetails(); var playerAccount = playerDetails.bankAccount(); @@ -71,13 +67,9 @@ public class LotteryService { return optional; } - /** - * Check if lottery ticket has won. - */ + /** Check if lottery ticket has won. */ public LotteryTicketCheckResult checkTicketForPrize( - LotteryTicketId id, - LotteryNumbers winningNumbers - ) { + LotteryTicketId id, LotteryNumbers winningNumbers) { return LotteryUtils.checkTicketForPrize(repository, id, winningNumbers); } } diff --git a/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicket.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicket.java index bc031f660..0b895f816 100644 --- a/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicket.java +++ b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicket.java @@ -24,10 +24,9 @@ */ package com.iluwatar.hexagonal.domain; -/** - * Immutable value object representing lottery ticket. - */ -public record LotteryTicket(LotteryTicketId id, PlayerDetails playerDetails, LotteryNumbers lotteryNumbers) { +/** Immutable value object representing lottery ticket. */ +public record LotteryTicket( + LotteryTicketId id, PlayerDetails playerDetails, LotteryNumbers lotteryNumbers) { @Override public int hashCode() { diff --git a/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicketCheckResult.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicketCheckResult.java index 7b1290e23..ff0245f30 100644 --- a/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicketCheckResult.java +++ b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicketCheckResult.java @@ -28,17 +28,13 @@ import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.RequiredArgsConstructor; -/** - * Represents lottery ticket check result. - */ +/** Represents lottery ticket check result. */ @Getter @EqualsAndHashCode @RequiredArgsConstructor public class LotteryTicketCheckResult { - /** - * Enumeration of Type of Outcomes of a Lottery. - */ + /** Enumeration of Type of Outcomes of a Lottery. */ public enum CheckResult { WIN_PRIZE, NO_PRIZE, @@ -48,12 +44,9 @@ public class LotteryTicketCheckResult { private final CheckResult result; private final int prizeAmount; - /** - * Constructor. - */ + /** Constructor. */ public LotteryTicketCheckResult(CheckResult result) { this.result = result; prizeAmount = 0; } - } diff --git a/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicketId.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicketId.java index f53c992e1..4bd1074fb 100644 --- a/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicketId.java +++ b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicketId.java @@ -29,9 +29,7 @@ import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.RequiredArgsConstructor; -/** - * Lottery ticked id. - */ +/** Lottery ticked id. */ @Getter @EqualsAndHashCode @RequiredArgsConstructor @@ -48,5 +46,4 @@ public class LotteryTicketId { public String toString() { return String.format("%d", id); } - } diff --git a/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/domain/LotteryUtils.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/domain/LotteryUtils.java index d14c7ce48..5e4ed138c 100644 --- a/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/domain/LotteryUtils.java +++ b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/domain/LotteryUtils.java @@ -27,22 +27,14 @@ package com.iluwatar.hexagonal.domain; import com.iluwatar.hexagonal.database.LotteryTicketRepository; import com.iluwatar.hexagonal.domain.LotteryTicketCheckResult.CheckResult; -/** - * Lottery utilities. - */ +/** Lottery utilities. */ public class LotteryUtils { - private LotteryUtils() { - } + private LotteryUtils() {} - /** - * Checks if lottery ticket has won. - */ + /** Checks if lottery ticket has won. */ public static LotteryTicketCheckResult checkTicketForPrize( - LotteryTicketRepository repository, - LotteryTicketId id, - LotteryNumbers winningNumbers - ) { + LotteryTicketRepository repository, LotteryTicketId id, LotteryNumbers winningNumbers) { var optional = repository.findById(id); if (optional.isPresent()) { if (optional.get().lotteryNumbers().equals(winningNumbers)) { diff --git a/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/domain/PlayerDetails.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/domain/PlayerDetails.java index fe638ae32..5fa3a3145 100644 --- a/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/domain/PlayerDetails.java +++ b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/domain/PlayerDetails.java @@ -24,7 +24,5 @@ */ package com.iluwatar.hexagonal.domain; -/** - * Immutable value object containing lottery player details. - */ +/** Immutable value object containing lottery player details. */ public record PlayerDetails(String email, String bankAccount, String phoneNumber) {} diff --git a/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/eventlog/LotteryEventLog.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/eventlog/LotteryEventLog.java index b33ec322f..6cea51b6b 100644 --- a/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/eventlog/LotteryEventLog.java +++ b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/eventlog/LotteryEventLog.java @@ -26,34 +26,21 @@ package com.iluwatar.hexagonal.eventlog; import com.iluwatar.hexagonal.domain.PlayerDetails; -/** - * Event log for lottery events. - */ +/** Event log for lottery events. */ public interface LotteryEventLog { - /** - * lottery ticket submitted. - */ + /** lottery ticket submitted. */ void ticketSubmitted(PlayerDetails details); - /** - * error submitting lottery ticket. - */ + /** error submitting lottery ticket. */ void ticketSubmitError(PlayerDetails details); - /** - * lottery ticket did not win. - */ + /** lottery ticket did not win. */ void ticketDidNotWin(PlayerDetails details); - /** - * lottery ticket won. - */ + /** lottery ticket won. */ void ticketWon(PlayerDetails details, int prizeAmount); - /** - * error paying the prize. - */ + /** error paying the prize. */ void prizeError(PlayerDetails details, int prizeAmount); - } diff --git a/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/eventlog/MongoEventLog.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/eventlog/MongoEventLog.java index bc3c621e9..47120d3d7 100644 --- a/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/eventlog/MongoEventLog.java +++ b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/eventlog/MongoEventLog.java @@ -31,9 +31,7 @@ import com.mongodb.client.MongoDatabase; import lombok.Getter; import org.bson.Document; -/** - * Mongo based event log. - */ +/** Mongo based event log. */ public class MongoEventLog implements LotteryEventLog { private static final String DEFAULT_DB = "lotteryDB"; @@ -42,45 +40,35 @@ public class MongoEventLog implements LotteryEventLog { private static final String PHONE = "phone"; public static final String MESSAGE = "message"; - @Getter - private MongoClient mongoClient; - @Getter - private MongoDatabase database; - @Getter - private MongoCollection eventsCollection; + @Getter private MongoClient mongoClient; + @Getter private MongoDatabase database; + @Getter private MongoCollection eventsCollection; private final StdOutEventLog stdOutEventLog = new StdOutEventLog(); - /** - * Constructor. - */ + /** Constructor. */ public MongoEventLog() { connect(); } - /** - * Constructor accepting parameters. - */ + /** Constructor accepting parameters. */ public MongoEventLog(String dbName, String eventsCollectionName) { connect(dbName, eventsCollectionName); } - /** - * Connect to database with default parameters. - */ + /** Connect to database with default parameters. */ public void connect() { connect(DEFAULT_DB, DEFAULT_EVENTS_COLLECTION); } - /** - * Connect to database with given parameters. - */ + /** Connect to database with given parameters. */ public void connect(String dbName, String eventsCollectionName) { if (mongoClient != null) { mongoClient.close(); } - mongoClient = new MongoClient(System.getProperty("mongo-host"), - Integer.parseInt(System.getProperty("mongo-port"))); + mongoClient = + new MongoClient( + System.getProperty("mongo-host"), Integer.parseInt(System.getProperty("mongo-port"))); database = mongoClient.getDatabase(dbName); eventsCollection = database.getCollection(eventsCollectionName); } @@ -90,8 +78,8 @@ public class MongoEventLog implements LotteryEventLog { var document = new Document(EMAIL, details.email()); document.put(PHONE, details.phoneNumber()); document.put("bank", details.bankAccount()); - document - .put(MESSAGE, "Lottery ticket was submitted and bank account was charged for 3 credits."); + document.put( + MESSAGE, "Lottery ticket was submitted and bank account was charged for 3 credits."); eventsCollection.insertOne(document); stdOutEventLog.ticketSubmitted(details); } @@ -121,9 +109,10 @@ public class MongoEventLog implements LotteryEventLog { var document = new Document(EMAIL, details.email()); document.put(PHONE, details.phoneNumber()); document.put("bank", details.bankAccount()); - document.put(MESSAGE, String - .format("Lottery ticket won! The bank account was deposited with %d credits.", - prizeAmount)); + document.put( + MESSAGE, + String.format( + "Lottery ticket won! The bank account was deposited with %d credits.", prizeAmount)); eventsCollection.insertOne(document); stdOutEventLog.ticketWon(details, prizeAmount); } @@ -133,8 +122,10 @@ public class MongoEventLog implements LotteryEventLog { var document = new Document(EMAIL, details.email()); document.put(PHONE, details.phoneNumber()); document.put("bank", details.bankAccount()); - document.put(MESSAGE, String - .format("Lottery ticket won! Unfortunately the bank credit transfer of %d failed.", + document.put( + MESSAGE, + String.format( + "Lottery ticket won! Unfortunately the bank credit transfer of %d failed.", prizeAmount)); eventsCollection.insertOne(document); stdOutEventLog.prizeError(details, prizeAmount); diff --git a/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/eventlog/StdOutEventLog.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/eventlog/StdOutEventLog.java index d57645115..1ddd93d59 100644 --- a/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/eventlog/StdOutEventLog.java +++ b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/eventlog/StdOutEventLog.java @@ -27,39 +27,47 @@ package com.iluwatar.hexagonal.eventlog; import com.iluwatar.hexagonal.domain.PlayerDetails; import lombok.extern.slf4j.Slf4j; -/** - * Standard output event log. - */ +/** Standard output event log. */ @Slf4j public class StdOutEventLog implements LotteryEventLog { @Override public void ticketSubmitted(PlayerDetails details) { - LOGGER.info("Lottery ticket for {} was submitted. Bank account {} was charged for 3 credits.", - details.email(), details.bankAccount()); + LOGGER.info( + "Lottery ticket for {} was submitted. Bank account {} was charged for 3 credits.", + details.email(), + details.bankAccount()); } @Override public void ticketDidNotWin(PlayerDetails details) { - LOGGER.info("Lottery ticket for {} was checked and unfortunately did not win this time.", + LOGGER.info( + "Lottery ticket for {} was checked and unfortunately did not win this time.", details.email()); } @Override public void ticketWon(PlayerDetails details, int prizeAmount) { - LOGGER.info("Lottery ticket for {} has won! The bank account {} was deposited with {} credits.", - details.email(), details.bankAccount(), prizeAmount); + LOGGER.info( + "Lottery ticket for {} has won! The bank account {} was deposited with {} credits.", + details.email(), + details.bankAccount(), + prizeAmount); } @Override public void prizeError(PlayerDetails details, int prizeAmount) { - LOGGER.error("Lottery ticket for {} has won! Unfortunately the bank credit transfer of" - + " {} failed.", details.email(), prizeAmount); + LOGGER.error( + "Lottery ticket for {} has won! Unfortunately the bank credit transfer of" + " {} failed.", + details.email(), + prizeAmount); } @Override public void ticketSubmitError(PlayerDetails details) { - LOGGER.error("Lottery ticket for {} could not be submitted because the credit transfer" - + " of 3 credits failed.", details.email()); + LOGGER.error( + "Lottery ticket for {} could not be submitted because the credit transfer" + + " of 3 credits failed.", + details.email()); } } diff --git a/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/module/LotteryModule.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/module/LotteryModule.java index 1f1d16d4e..c45117bc6 100644 --- a/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/module/LotteryModule.java +++ b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/module/LotteryModule.java @@ -32,9 +32,7 @@ import com.iluwatar.hexagonal.database.MongoTicketRepository; import com.iluwatar.hexagonal.eventlog.LotteryEventLog; import com.iluwatar.hexagonal.eventlog.MongoEventLog; -/** - * Guice module for binding production dependencies. - */ +/** Guice module for binding production dependencies. */ public class LotteryModule extends AbstractModule { @Override protected void configure() { diff --git a/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/module/LotteryTestingModule.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/module/LotteryTestingModule.java index 1e67f60a7..1ed43183b 100644 --- a/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/module/LotteryTestingModule.java +++ b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/module/LotteryTestingModule.java @@ -32,9 +32,7 @@ import com.iluwatar.hexagonal.database.LotteryTicketRepository; import com.iluwatar.hexagonal.eventlog.LotteryEventLog; import com.iluwatar.hexagonal.eventlog.StdOutEventLog; -/** - * Guice module for testing dependencies. - */ +/** Guice module for testing dependencies. */ public class LotteryTestingModule extends AbstractModule { @Override protected void configure() { diff --git a/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/mongo/MongoConnectionPropertiesLoader.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/mongo/MongoConnectionPropertiesLoader.java index 40261090e..5a9057989 100644 --- a/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/mongo/MongoConnectionPropertiesLoader.java +++ b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/mongo/MongoConnectionPropertiesLoader.java @@ -28,18 +28,14 @@ import java.io.FileInputStream; import java.util.Properties; import lombok.extern.slf4j.Slf4j; -/** - * Mongo connection properties loader. - */ +/** Mongo connection properties loader. */ @Slf4j public class MongoConnectionPropertiesLoader { private static final String DEFAULT_HOST = "localhost"; private static final int DEFAULT_PORT = 27017; - /** - * Try to load connection properties from file. Fall back to default connection properties. - */ + /** Try to load connection properties from file. Fall back to default connection properties. */ public static void load() { var host = DEFAULT_HOST; var port = DEFAULT_PORT; diff --git a/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/sampledata/SampleData.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/sampledata/SampleData.java index 2dc191604..7d0bb4136 100644 --- a/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/sampledata/SampleData.java +++ b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/sampledata/SampleData.java @@ -36,56 +36,54 @@ import java.util.AbstractMap.SimpleEntry; import java.util.List; import java.util.stream.Collectors; -/** - * Utilities for creating sample lottery tickets. - */ +/** Utilities for creating sample lottery tickets. */ public class SampleData { private static final List PLAYERS; private static final SecureRandom RANDOM = new SecureRandom(); static { - PLAYERS = List.of( - new PlayerDetails("john@google.com", "312-342", "+3242434242"), - new PlayerDetails("mary@google.com", "234-987", "+23452346"), - new PlayerDetails("steve@google.com", "833-836", "+63457543"), - new PlayerDetails("wayne@google.com", "319-826", "+24626"), - new PlayerDetails("johnie@google.com", "983-322", "+3635635"), - new PlayerDetails("andy@google.com", "934-734", "+0898245"), - new PlayerDetails("richard@google.com", "536-738", "+09845325"), - new PlayerDetails("kevin@google.com", "453-936", "+2423532"), - new PlayerDetails("arnold@google.com", "114-988", "+5646346524"), - new PlayerDetails("ian@google.com", "663-765", "+928394235"), - new PlayerDetails("robin@google.com", "334-763", "+35448"), - new PlayerDetails("ted@google.com", "735-964", "+98752345"), - new PlayerDetails("larry@google.com", "734-853", "+043842423"), - new PlayerDetails("calvin@google.com", "334-746", "+73294135"), - new PlayerDetails("jacob@google.com", "444-766", "+358042354"), - new PlayerDetails("edwin@google.com", "895-345", "+9752435"), - new PlayerDetails("mary@google.com", "760-009", "+34203542"), - new PlayerDetails("lolita@google.com", "425-907", "+9872342"), - new PlayerDetails("bruno@google.com", "023-638", "+673824122"), - new PlayerDetails("peter@google.com", "335-886", "+5432503945"), - new PlayerDetails("warren@google.com", "225-946", "+9872341324"), - new PlayerDetails("monica@google.com", "265-748", "+134124"), - new PlayerDetails("ollie@google.com", "190-045", "+34453452"), - new PlayerDetails("yngwie@google.com", "241-465", "+9897641231"), - new PlayerDetails("lars@google.com", "746-936", "+42345298345"), - new PlayerDetails("bobbie@google.com", "946-384", "+79831742"), - new PlayerDetails("tyron@google.com", "310-992", "+0498837412"), - new PlayerDetails("tyrell@google.com", "032-045", "+67834134"), - new PlayerDetails("nadja@google.com", "000-346", "+498723"), - new PlayerDetails("wendy@google.com", "994-989", "+987324454"), - new PlayerDetails("luke@google.com", "546-634", "+987642435"), - new PlayerDetails("bjorn@google.com", "342-874", "+7834325"), - new PlayerDetails("lisa@google.com", "024-653", "+980742154"), - new PlayerDetails("anton@google.com", "834-935", "+876423145"), - new PlayerDetails("bruce@google.com", "284-936", "+09843212345"), - new PlayerDetails("ray@google.com", "843-073", "+678324123"), - new PlayerDetails("ron@google.com", "637-738", "+09842354"), - new PlayerDetails("xavier@google.com", "143-947", "+375245"), - new PlayerDetails("harriet@google.com", "842-404", "+131243252") - ); + PLAYERS = + List.of( + new PlayerDetails("john@google.com", "312-342", "+3242434242"), + new PlayerDetails("mary@google.com", "234-987", "+23452346"), + new PlayerDetails("steve@google.com", "833-836", "+63457543"), + new PlayerDetails("wayne@google.com", "319-826", "+24626"), + new PlayerDetails("johnie@google.com", "983-322", "+3635635"), + new PlayerDetails("andy@google.com", "934-734", "+0898245"), + new PlayerDetails("richard@google.com", "536-738", "+09845325"), + new PlayerDetails("kevin@google.com", "453-936", "+2423532"), + new PlayerDetails("arnold@google.com", "114-988", "+5646346524"), + new PlayerDetails("ian@google.com", "663-765", "+928394235"), + new PlayerDetails("robin@google.com", "334-763", "+35448"), + new PlayerDetails("ted@google.com", "735-964", "+98752345"), + new PlayerDetails("larry@google.com", "734-853", "+043842423"), + new PlayerDetails("calvin@google.com", "334-746", "+73294135"), + new PlayerDetails("jacob@google.com", "444-766", "+358042354"), + new PlayerDetails("edwin@google.com", "895-345", "+9752435"), + new PlayerDetails("mary@google.com", "760-009", "+34203542"), + new PlayerDetails("lolita@google.com", "425-907", "+9872342"), + new PlayerDetails("bruno@google.com", "023-638", "+673824122"), + new PlayerDetails("peter@google.com", "335-886", "+5432503945"), + new PlayerDetails("warren@google.com", "225-946", "+9872341324"), + new PlayerDetails("monica@google.com", "265-748", "+134124"), + new PlayerDetails("ollie@google.com", "190-045", "+34453452"), + new PlayerDetails("yngwie@google.com", "241-465", "+9897641231"), + new PlayerDetails("lars@google.com", "746-936", "+42345298345"), + new PlayerDetails("bobbie@google.com", "946-384", "+79831742"), + new PlayerDetails("tyron@google.com", "310-992", "+0498837412"), + new PlayerDetails("tyrell@google.com", "032-045", "+67834134"), + new PlayerDetails("nadja@google.com", "000-346", "+498723"), + new PlayerDetails("wendy@google.com", "994-989", "+987324454"), + new PlayerDetails("luke@google.com", "546-634", "+987642435"), + new PlayerDetails("bjorn@google.com", "342-874", "+7834325"), + new PlayerDetails("lisa@google.com", "024-653", "+980742154"), + new PlayerDetails("anton@google.com", "834-935", "+876423145"), + new PlayerDetails("bruce@google.com", "284-936", "+09843212345"), + new PlayerDetails("ray@google.com", "843-073", "+678324123"), + new PlayerDetails("ron@google.com", "637-738", "+09842354"), + new PlayerDetails("xavier@google.com", "143-947", "+375245"), + new PlayerDetails("harriet@google.com", "842-404", "+131243252")); var wireTransfers = new InMemoryBank(); PLAYERS.stream() .map(PlayerDetails::bankAccount) @@ -94,9 +92,7 @@ public class SampleData { .forEach(wireTransfers::setFunds); } - /** - * Inserts lottery tickets into the database based on the sample data. - */ + /** Inserts lottery tickets into the database based on the sample data. */ public static void submitTickets(LotteryService lotteryService, int numTickets) { for (var i = 0; i < numTickets; i++) { var randomPlayerDetails = getRandomPlayerDetails(); diff --git a/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/service/ConsoleLottery.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/service/ConsoleLottery.java index b273a828f..8832b71a5 100644 --- a/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/service/ConsoleLottery.java +++ b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/service/ConsoleLottery.java @@ -32,15 +32,11 @@ import com.iluwatar.hexagonal.mongo.MongoConnectionPropertiesLoader; import java.util.Scanner; import lombok.extern.slf4j.Slf4j; -/** - * Console interface for lottery players. - */ +/** Console interface for lottery players. */ @Slf4j public class ConsoleLottery { - /** - * Program entry point. - */ + /** Program entry point. */ public static void main(String[] args) { MongoConnectionPropertiesLoader.load(); var injector = Guice.createInjector(new LotteryModule()); diff --git a/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/service/LotteryConsoleService.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/service/LotteryConsoleService.java index baa244564..39fbb08c3 100644 --- a/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/service/LotteryConsoleService.java +++ b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/service/LotteryConsoleService.java @@ -28,28 +28,17 @@ import com.iluwatar.hexagonal.banking.WireTransfers; import com.iluwatar.hexagonal.domain.LotteryService; import java.util.Scanner; - -/** - * Console interface for lottery service. - */ +/** Console interface for lottery service. */ public interface LotteryConsoleService { void checkTicket(LotteryService service, Scanner scanner); - /** - * Submit lottery ticket to participate in the lottery. - */ + /** Submit lottery ticket to participate in the lottery. */ void submitTicket(LotteryService service, Scanner scanner); - /** - * Add funds to lottery account. - */ + /** Add funds to lottery account. */ void addFundsToLotteryAccount(WireTransfers bank, Scanner scanner); - - /** - * Recovery funds from lottery account. - */ + /** Recovery funds from lottery account. */ void queryLotteryAccountFunds(WireTransfers bank, Scanner scanner); - } diff --git a/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/service/LotteryConsoleServiceImpl.java b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/service/LotteryConsoleServiceImpl.java index 44f8bea09..dbdd16f79 100644 --- a/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/service/LotteryConsoleServiceImpl.java +++ b/hexagonal-architecture/src/main/java/com/iluwatar/hexagonal/service/LotteryConsoleServiceImpl.java @@ -36,16 +36,12 @@ import java.util.Scanner; import java.util.stream.Collectors; import org.slf4j.Logger; -/** - * Console implementation for lottery console service. - */ +/** Console implementation for lottery console service. */ public class LotteryConsoleServiceImpl implements LotteryConsoleService { private final Logger logger; - /** - * Constructor. - */ + /** Constructor. */ public LotteryConsoleServiceImpl(Logger logger) { this.logger = logger; } @@ -57,10 +53,11 @@ public class LotteryConsoleServiceImpl implements LotteryConsoleService { logger.info("Give the 4 comma separated winning numbers?"); var numbers = readString(scanner); try { - var winningNumbers = Arrays.stream(numbers.split(",")) - .map(Integer::parseInt) - .limit(4) - .collect(Collectors.toSet()); + var winningNumbers = + Arrays.stream(numbers.split(",")) + .map(Integer::parseInt) + .limit(4) + .collect(Collectors.toSet()); final var lotteryTicketId = new LotteryTicketId(Integer.parseInt(id)); final var lotteryNumbers = LotteryNumbers.create(winningNumbers); @@ -90,15 +87,15 @@ public class LotteryConsoleServiceImpl implements LotteryConsoleService { logger.info("Give 4 comma separated lottery numbers?"); var numbers = readString(scanner); try { - var chosen = Arrays.stream(numbers.split(",")) - .map(Integer::parseInt) - .collect(Collectors.toSet()); + var chosen = + Arrays.stream(numbers.split(",")).map(Integer::parseInt).collect(Collectors.toSet()); var lotteryNumbers = LotteryNumbers.create(chosen); var lotteryTicket = new LotteryTicket(new LotteryTicketId(), details, lotteryNumbers); - service.submitTicket(lotteryTicket).ifPresentOrElse( - (id) -> logger.info("Submitted lottery ticket with id: {}", id), - () -> logger.info("Failed submitting lottery ticket - please try again.") - ); + service + .submitTicket(lotteryTicket) + .ifPresentOrElse( + (id) -> logger.info("Submitted lottery ticket with id: {}", id), + () -> logger.info("Failed submitting lottery ticket - please try again.")); } catch (Exception e) { logger.info("Failed submitting lottery ticket - please try again."); } diff --git a/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/AppTest.java b/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/AppTest.java index 1d8152b83..1022ccb09 100644 --- a/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/AppTest.java +++ b/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/AppTest.java @@ -24,18 +24,15 @@ */ package com.iluwatar.hexagonal; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -/** - * Unit test for simple App. - */ +import org.junit.jupiter.api.Test; + +/** Unit test for simple App. */ class AppTest { @Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); - + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/banking/InMemoryBankTest.java b/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/banking/InMemoryBankTest.java index 740dea788..4e3c1fac7 100644 --- a/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/banking/InMemoryBankTest.java +++ b/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/banking/InMemoryBankTest.java @@ -29,9 +29,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; -/** - * Tests for banking - */ +/** Tests for banking */ class InMemoryBankTest { private final WireTransfers bank = new InMemoryBank(); diff --git a/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/banking/MongoBankTest.java b/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/banking/MongoBankTest.java index 7e5dc39bf..8253ac7cb 100644 --- a/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/banking/MongoBankTest.java +++ b/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/banking/MongoBankTest.java @@ -39,9 +39,7 @@ import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -/** - * Tests for Mongo banking adapter - */ +/** Tests for Mongo banking adapter */ class MongoBankTest { private static final String TEST_DB = "lotteryDBTest"; @@ -56,8 +54,6 @@ class MongoBankTest { private static ServerAddress serverAddress; - - @BeforeAll static void setUp() { mongodProcess = Mongod.instance().start(Version.Main.V7_0); @@ -73,7 +69,6 @@ class MongoBankTest { mongodProcess.close(); } - @BeforeEach void init() { System.setProperty("mongo-host", serverAddress.getHost()); @@ -97,4 +92,4 @@ class MongoBankTest { assertEquals(1, mongoBank.getFunds("000-000")); assertEquals(9, mongoBank.getFunds("111-111")); } -} \ No newline at end of file +} diff --git a/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/database/InMemoryTicketRepositoryTest.java b/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/database/InMemoryTicketRepositoryTest.java index 6fa1d5a3e..5d9017033 100644 --- a/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/database/InMemoryTicketRepositoryTest.java +++ b/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/database/InMemoryTicketRepositoryTest.java @@ -31,9 +31,7 @@ import com.iluwatar.hexagonal.test.LotteryTestUtils; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -/** - * Tests for {@link LotteryTicketRepository} - */ +/** Tests for {@link LotteryTicketRepository} */ class InMemoryTicketRepositoryTest { private final LotteryTicketRepository repository = new InMemoryTicketRepository(); diff --git a/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/database/MongoTicketRepositoryTest.java b/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/database/MongoTicketRepositoryTest.java index ee8329bd9..0a45adcac 100644 --- a/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/database/MongoTicketRepositoryTest.java +++ b/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/database/MongoTicketRepositoryTest.java @@ -37,9 +37,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; -/** - * Tests for Mongo based ticket repository - */ +/** Tests for Mongo based ticket repository */ @Disabled class MongoTicketRepositoryTest { @@ -52,12 +50,13 @@ class MongoTicketRepositoryTest { @BeforeEach void init() { MongoConnectionPropertiesLoader.load(); - var mongoClient = new MongoClient(System.getProperty("mongo-host"), - Integer.parseInt(System.getProperty("mongo-port"))); + var mongoClient = + new MongoClient( + System.getProperty("mongo-host"), Integer.parseInt(System.getProperty("mongo-port"))); mongoClient.dropDatabase(TEST_DB); mongoClient.close(); - repository = new MongoTicketRepository(TEST_DB, TEST_TICKETS_COLLECTION, - TEST_COUNTERS_COLLECTION); + repository = + new MongoTicketRepository(TEST_DB, TEST_TICKETS_COLLECTION, TEST_COUNTERS_COLLECTION); } @Test diff --git a/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/domain/LotteryNumbersTest.java b/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/domain/LotteryNumbersTest.java index f2690fb39..0aa740690 100644 --- a/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/domain/LotteryNumbersTest.java +++ b/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/domain/LotteryNumbersTest.java @@ -32,9 +32,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Set; import org.junit.jupiter.api.Test; -/** - * Unit tests for {@link LotteryNumbers} - */ +/** Unit tests for {@link LotteryNumbers} */ class LotteryNumbersTest { @Test diff --git a/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/domain/LotteryTest.java b/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/domain/LotteryTest.java index d7f4e951d..c71f88788 100644 --- a/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/domain/LotteryTest.java +++ b/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/domain/LotteryTest.java @@ -39,18 +39,13 @@ import java.util.Set; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -/** - * Test the lottery system - */ +/** Test the lottery system */ class LotteryTest { private final Injector injector; - @Inject - private LotteryAdministration administration; - @Inject - private LotteryService service; - @Inject - private WireTransfers wireTransfers; + @Inject private LotteryAdministration administration; + @Inject private LotteryService service; + @Inject private WireTransfers wireTransfers; LotteryTest() { this.injector = Guice.createInjector(new LotteryTestingModule()); @@ -70,14 +65,20 @@ class LotteryTest { assertEquals(0, administration.getAllSubmittedTickets().size()); // players submit the lottery tickets - var ticket1 = service.submitTicket(LotteryTestUtils.createLotteryTicket("cvt@bbb.com", - "123-12312", "+32425255", Set.of(1, 2, 3, 4))); + var ticket1 = + service.submitTicket( + LotteryTestUtils.createLotteryTicket( + "cvt@bbb.com", "123-12312", "+32425255", Set.of(1, 2, 3, 4))); assertTrue(ticket1.isPresent()); - var ticket2 = service.submitTicket(LotteryTestUtils.createLotteryTicket("ant@bac.com", - "123-12312", "+32423455", Set.of(11, 12, 13, 14))); + var ticket2 = + service.submitTicket( + LotteryTestUtils.createLotteryTicket( + "ant@bac.com", "123-12312", "+32423455", Set.of(11, 12, 13, 14))); assertTrue(ticket2.isPresent()); - var ticket3 = service.submitTicket(LotteryTestUtils.createLotteryTicket("arg@boo.com", - "123-12312", "+32421255", Set.of(6, 8, 13, 19))); + var ticket3 = + service.submitTicket( + LotteryTestUtils.createLotteryTicket( + "arg@boo.com", "123-12312", "+32421255", Set.of(6, 8, 13, 19))); assertTrue(ticket3.isPresent()); assertEquals(3, administration.getAllSubmittedTickets().size()); @@ -85,8 +86,10 @@ class LotteryTest { var winningNumbers = administration.performLottery(); // cheat a bit for testing sake, use winning numbers to submit another ticket - var ticket4 = service.submitTicket(LotteryTestUtils.createLotteryTicket("lucky@orb.com", - "123-12312", "+12421255", winningNumbers.getNumbers())); + var ticket4 = + service.submitTicket( + LotteryTestUtils.createLotteryTicket( + "lucky@orb.com", "123-12312", "+12421255", winningNumbers.getNumbers())); assertTrue(ticket4.isPresent()); assertEquals(4, administration.getAllSubmittedTickets().size()); diff --git a/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketCheckResultTest.java b/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketCheckResultTest.java index 6e11a95b0..05af100dc 100644 --- a/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketCheckResultTest.java +++ b/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketCheckResultTest.java @@ -30,9 +30,7 @@ import static org.junit.jupiter.api.Assertions.assertNotEquals; import com.iluwatar.hexagonal.domain.LotteryTicketCheckResult.CheckResult; import org.junit.jupiter.api.Test; -/** - * Unit tests for {@link LotteryTicketCheckResult} - */ +/** Unit tests for {@link LotteryTicketCheckResult} */ class LotteryTicketCheckResultTest { @Test diff --git a/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketIdTest.java b/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketIdTest.java index 8456e7742..cde988eaa 100644 --- a/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketIdTest.java +++ b/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketIdTest.java @@ -29,9 +29,7 @@ import static org.junit.jupiter.api.Assertions.assertNotEquals; import org.junit.jupiter.api.Test; -/** - * Tests for lottery ticket id - */ +/** Tests for lottery ticket id */ class LotteryTicketIdTest { @Test diff --git a/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketTest.java b/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketTest.java index ce316b347..9b8e400c8 100644 --- a/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketTest.java +++ b/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketTest.java @@ -30,9 +30,7 @@ import static org.junit.jupiter.api.Assertions.assertNotEquals; import java.util.Set; import org.junit.jupiter.api.Test; -/** - * Test Lottery Tickets for equality - */ +/** Test Lottery Tickets for equality */ class LotteryTicketTest { @Test diff --git a/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/domain/PlayerDetailsTest.java b/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/domain/PlayerDetailsTest.java index 732a4b14c..266f90779 100644 --- a/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/domain/PlayerDetailsTest.java +++ b/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/domain/PlayerDetailsTest.java @@ -29,9 +29,7 @@ import static org.junit.jupiter.api.Assertions.assertNotEquals; import org.junit.jupiter.api.Test; -/** - * Unit tests for {@link PlayerDetails} - */ +/** Unit tests for {@link PlayerDetails} */ class PlayerDetailsTest { @Test diff --git a/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/eventlog/MongoEventLogTest.java b/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/eventlog/MongoEventLogTest.java index 3216ac7eb..0227d9a6d 100644 --- a/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/eventlog/MongoEventLogTest.java +++ b/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/eventlog/MongoEventLogTest.java @@ -33,9 +33,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; -/** - * Tests for Mongo event log - */ +/** Tests for Mongo event log */ @Disabled class MongoEventLogTest { @@ -47,8 +45,9 @@ class MongoEventLogTest { @BeforeEach void init() { MongoConnectionPropertiesLoader.load(); - var mongoClient = new MongoClient(System.getProperty("mongo-host"), - Integer.parseInt(System.getProperty("mongo-port"))); + var mongoClient = + new MongoClient( + System.getProperty("mongo-host"), Integer.parseInt(System.getProperty("mongo-port"))); mongoClient.dropDatabase(TEST_DB); mongoClient.close(); mongoEventLog = new MongoEventLog(TEST_DB, TEST_EVENTS_COLLECTION); diff --git a/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/test/LotteryTestUtils.java b/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/test/LotteryTestUtils.java index 3b6babaa1..3002879ba 100644 --- a/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/test/LotteryTestUtils.java +++ b/hexagonal-architecture/src/test/java/com/iluwatar/hexagonal/test/LotteryTestUtils.java @@ -30,9 +30,7 @@ import com.iluwatar.hexagonal.domain.LotteryTicketId; import com.iluwatar.hexagonal.domain.PlayerDetails; import java.util.Set; -/** - * Utilities for lottery tests - */ +/** Utilities for lottery tests */ public class LotteryTestUtils { /** @@ -45,8 +43,8 @@ public class LotteryTestUtils { /** * @return lottery ticket */ - public static LotteryTicket createLotteryTicket(String email, String account, String phone, - Set givenNumbers) { + public static LotteryTicket createLotteryTicket( + String email, String account, String phone, Set givenNumbers) { var details = new PlayerDetails(email, account, phone); var numbers = LotteryNumbers.create(givenNumbers); return new LotteryTicket(new LotteryTicketId(), details, numbers); diff --git a/identity-map/pom.xml b/identity-map/pom.xml index 5125e1130..cf151c1ff 100644 --- a/identity-map/pom.xml +++ b/identity-map/pom.xml @@ -37,13 +37,16 @@ identity-map - org.junit.jupiter - junit-jupiter-api - test + org.slf4j + slf4j-api - junit - junit + ch.qos.logback + logback-classic + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/identity-map/src/main/java/com/iluwatar/identitymap/App.java b/identity-map/src/main/java/com/iluwatar/identitymap/App.java index 2625531df..e3538f4b3 100644 --- a/identity-map/src/main/java/com/iluwatar/identitymap/App.java +++ b/identity-map/src/main/java/com/iluwatar/identitymap/App.java @@ -27,12 +27,12 @@ package com.iluwatar.identitymap; import lombok.extern.slf4j.Slf4j; /** - * The basic idea behind the Identity Map is to have a series of maps containing objects that have been pulled from the database. - * The below example demonstrates the identity map pattern by creating a sample DB. - * Since only 1 DB has been created we only have 1 map corresponding to it for the purpose of this demo. - * When you load an object from the database, you first check the map. - * If there’s an object in it that corresponds to the one you’re loading, you return it. If not, you go to the database, - * putting the objects on the map for future reference as you load them. + * The basic idea behind the Identity Map is to have a series of maps containing objects that have + * been pulled from the database. The below example demonstrates the identity map pattern by + * creating a sample DB. Since only 1 DB has been created we only have 1 map corresponding to it for + * the purpose of this demo. When you load an object from the database, you first check the map. If + * there’s an object in it that corresponds to the one you’re loading, you return it. If not, you go + * to the database, putting the objects on the map for future reference as you load them. */ @Slf4j public class App { diff --git a/identity-map/src/main/java/com/iluwatar/identitymap/IdNotFoundException.java b/identity-map/src/main/java/com/iluwatar/identitymap/IdNotFoundException.java index 18ed4cc9f..9a0210854 100644 --- a/identity-map/src/main/java/com/iluwatar/identitymap/IdNotFoundException.java +++ b/identity-map/src/main/java/com/iluwatar/identitymap/IdNotFoundException.java @@ -24,9 +24,7 @@ */ package com.iluwatar.identitymap; -/** - * Using Runtime Exception to control the flow in case Person Id doesn't exist. - */ +/** Using Runtime Exception to control the flow in case Person Id doesn't exist. */ public class IdNotFoundException extends RuntimeException { public IdNotFoundException(final String message) { super(message); diff --git a/identity-map/src/main/java/com/iluwatar/identitymap/IdentityMap.java b/identity-map/src/main/java/com/iluwatar/identitymap/IdentityMap.java index 633dff35d..7543cfb0b 100644 --- a/identity-map/src/main/java/com/iluwatar/identitymap/IdentityMap.java +++ b/identity-map/src/main/java/com/iluwatar/identitymap/IdentityMap.java @@ -30,20 +30,20 @@ import lombok.Getter; import lombok.extern.slf4j.Slf4j; /** - * This class stores the map into which we will be caching records after loading them from a DataBase. - * Stores the records as a Hash Map with the personNationalIDs as keys. + * This class stores the map into which we will be caching records after loading them from a + * DataBase. Stores the records as a Hash Map with the personNationalIDs as keys. */ @Slf4j @Getter public class IdentityMap { private Map personMap = new HashMap<>(); - /** - * Add person to the map. - */ + + /** Add person to the map. */ public void addPerson(Person person) { if (!personMap.containsKey(person.getPersonNationalId())) { personMap.put(person.getPersonNationalId(), person); - } else { // Ensure that addPerson does not update a record. This situation will never arise in our implementation. Added only for testing purposes. + } else { // Ensure that addPerson does not update a record. This situation will never arise in + // our implementation. Added only for testing purposes. LOGGER.info("Key already in Map"); } } @@ -63,14 +63,11 @@ public class IdentityMap { return person; } - /** - * Get the size of the map. - */ + /** Get the size of the map. */ public int size() { if (personMap == null) { return 0; } return personMap.size(); } - } diff --git a/identity-map/src/main/java/com/iluwatar/identitymap/Person.java b/identity-map/src/main/java/com/iluwatar/identitymap/Person.java index e3e7b8729..bc14bff50 100644 --- a/identity-map/src/main/java/com/iluwatar/identitymap/Person.java +++ b/identity-map/src/main/java/com/iluwatar/identitymap/Person.java @@ -31,28 +31,27 @@ import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; -/** - * Person definition. - */ +/** Person definition. */ @EqualsAndHashCode(onlyExplicitlyIncluded = true) @Getter @Setter @AllArgsConstructor public final class Person implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial private static final long serialVersionUID = 1L; - @EqualsAndHashCode.Include - private int personNationalId; + @EqualsAndHashCode.Include private int personNationalId; private String name; private long phoneNum; @Override public String toString() { - return "Person ID is : " + personNationalId + " ; Person Name is : " + name + " ; Phone Number is :" + phoneNum; - + return "Person ID is : " + + personNationalId + + " ; Person Name is : " + + name + + " ; Phone Number is :" + + phoneNum; } - } diff --git a/identity-map/src/main/java/com/iluwatar/identitymap/PersonDbSimulator.java b/identity-map/src/main/java/com/iluwatar/identitymap/PersonDbSimulator.java index 7cee5e06a..8a2d7481d 100644 --- a/identity-map/src/main/java/com/iluwatar/identitymap/PersonDbSimulator.java +++ b/identity-map/src/main/java/com/iluwatar/identitymap/PersonDbSimulator.java @@ -24,9 +24,7 @@ */ package com.iluwatar.identitymap; -/** - * Simulator interface for Person DB. - */ +/** Simulator interface for Person DB. */ public interface PersonDbSimulator { Person find(int personNationalId); @@ -35,5 +33,4 @@ public interface PersonDbSimulator { void update(Person person); void delete(int personNationalId); - } diff --git a/identity-map/src/main/java/com/iluwatar/identitymap/PersonDbSimulatorImplementation.java b/identity-map/src/main/java/com/iluwatar/identitymap/PersonDbSimulatorImplementation.java index 22abb44f2..e6c4be3eb 100644 --- a/identity-map/src/main/java/com/iluwatar/identitymap/PersonDbSimulatorImplementation.java +++ b/identity-map/src/main/java/com/iluwatar/identitymap/PersonDbSimulatorImplementation.java @@ -30,26 +30,26 @@ import java.util.Optional; import lombok.extern.slf4j.Slf4j; /** - * This is a sample database implementation. The database is in the form of an arraylist which stores records of - * different persons. The personNationalId acts as the primary key for a record. - * Operations : - * -> find (look for object with a particular ID) - * -> insert (insert record for a new person into the database) - * -> update (update the record of a person). To do this, create a new person instance with the same ID as the record you - * want to update. Then call this method with that person as an argument. - * -> delete (delete the record for a particular ID) + * This is a sample database implementation. The database is in the form of an arraylist which + * stores records of different persons. The personNationalId acts as the primary key for a record. + * Operations : -> find (look for object with a particular ID) -> insert (insert record for a new + * person into the database) -> update (update the record of a person). To do this, create a new + * person instance with the same ID as the record you want to update. Then call this method with + * that person as an argument. -> delete (delete the record for a particular ID) */ @Slf4j public class PersonDbSimulatorImplementation implements PersonDbSimulator { - //This simulates a table in the database. To extend logic to multiple tables just add more lists to the implementation. + // This simulates a table in the database. To extend logic to multiple tables just add more lists + // to the implementation. private List personList = new ArrayList<>(); static final String NOT_IN_DATA_BASE = " not in DataBase"; static final String ID_STR = "ID : "; @Override public Person find(int personNationalId) throws IdNotFoundException { - Optional elem = personList.stream().filter(p -> p.getPersonNationalId() == personNationalId).findFirst(); + Optional elem = + personList.stream().filter(p -> p.getPersonNationalId() == personNationalId).findFirst(); if (elem.isEmpty()) { throw new IdNotFoundException(ID_STR + personNationalId + NOT_IN_DATA_BASE); } @@ -59,7 +59,10 @@ public class PersonDbSimulatorImplementation implements PersonDbSimulator { @Override public void insert(Person person) { - Optional elem = personList.stream().filter(p -> p.getPersonNationalId() == person.getPersonNationalId()).findFirst(); + Optional elem = + personList.stream() + .filter(p -> p.getPersonNationalId() == person.getPersonNationalId()) + .findFirst(); if (elem.isPresent()) { LOGGER.info("Record already exists."); return; @@ -69,7 +72,10 @@ public class PersonDbSimulatorImplementation implements PersonDbSimulator { @Override public void update(Person person) throws IdNotFoundException { - Optional elem = personList.stream().filter(p -> p.getPersonNationalId() == person.getPersonNationalId()).findFirst(); + Optional elem = + personList.stream() + .filter(p -> p.getPersonNationalId() == person.getPersonNationalId()) + .findFirst(); if (elem.isPresent()) { elem.get().setName(person.getName()); elem.get().setPhoneNum(person.getPhoneNum()); @@ -85,7 +91,8 @@ public class PersonDbSimulatorImplementation implements PersonDbSimulator { * @param id : personNationalId for person whose record is to be deleted. */ public void delete(int id) throws IdNotFoundException { - Optional elem = personList.stream().filter(p -> p.getPersonNationalId() == id).findFirst(); + Optional elem = + personList.stream().filter(p -> p.getPersonNationalId() == id).findFirst(); if (elem.isPresent()) { personList.remove(elem.get()); LOGGER.info("Record deleted successfully."); @@ -94,14 +101,11 @@ public class PersonDbSimulatorImplementation implements PersonDbSimulator { throw new IdNotFoundException(ID_STR + id + NOT_IN_DATA_BASE); } - /** - * Return the size of the database. - */ + /** Return the size of the database. */ public int size() { if (personList == null) { return 0; } return personList.size(); } - } diff --git a/identity-map/src/main/java/com/iluwatar/identitymap/PersonFinder.java b/identity-map/src/main/java/com/iluwatar/identitymap/PersonFinder.java index d358e24e4..35cbcf84e 100644 --- a/identity-map/src/main/java/com/iluwatar/identitymap/PersonFinder.java +++ b/identity-map/src/main/java/com/iluwatar/identitymap/PersonFinder.java @@ -29,11 +29,11 @@ import lombok.Setter; import lombok.extern.slf4j.Slf4j; /** - * Any object of this class stores a DataBase and an Identity Map. When we try to look for a key we first check if - * it has been cached in the Identity Map and return it if it is indeed in the map. - * If that is not the case then go to the DataBase, get the record, store it in the - * Identity Map and then return the record. Now if we look for the record again we will find it in the table itself which - * will make lookup faster. + * Any object of this class stores a DataBase and an Identity Map. When we try to look for a key we + * first check if it has been cached in the Identity Map and return it if it is indeed in the map. + * If that is not the case then go to the DataBase, get the record, store it in the Identity Map and + * then return the record. Now if we look for the record again we will find it in the table itself + * which will make lookup faster. */ @Slf4j @Getter @@ -43,6 +43,7 @@ public class PersonFinder { // Access to the Identity Map private IdentityMap identityMap = new IdentityMap(); private PersonDbSimulatorImplementation db = new PersonDbSimulatorImplementation(); + /** * get person corresponding to input ID. * diff --git a/identity-map/src/test/java/com/iluwatar/identitymap/AppTest.java b/identity-map/src/test/java/com/iluwatar/identitymap/AppTest.java index b946a44a6..8ef0e78d6 100644 --- a/identity-map/src/test/java/com/iluwatar/identitymap/AppTest.java +++ b/identity-map/src/test/java/com/iluwatar/identitymap/AppTest.java @@ -23,13 +23,14 @@ * THE SOFTWARE. */ package com.iluwatar.identitymap; -import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; - class AppTest { +import org.junit.jupiter.api.Test; + +class AppTest { @Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/identity-map/src/test/java/com/iluwatar/identitymap/IdentityMapTest.java b/identity-map/src/test/java/com/iluwatar/identitymap/IdentityMapTest.java index 74bbe3d41..98289e6d5 100644 --- a/identity-map/src/test/java/com/iluwatar/identitymap/IdentityMapTest.java +++ b/identity-map/src/test/java/com/iluwatar/identitymap/IdentityMapTest.java @@ -29,7 +29,7 @@ import org.junit.jupiter.api.Test; class IdentityMapTest { @Test - void addToMap(){ + void addToMap() { // new instance of an identity map(not connected to any DB here) IdentityMap idMap = new IdentityMap(); // Dummy person instances @@ -46,10 +46,12 @@ class IdentityMapTest { idMap.addPerson(person4); idMap.addPerson(person5); // Test no duplicate in our Map. - Assertions.assertEquals(4,idMap.size(),"Size of the map is incorrect"); + Assertions.assertEquals(4, idMap.size(), "Size of the map is incorrect"); // Test record not updated by add method. - Assertions.assertEquals(27304159,idMap.getPerson(11).getPhoneNum(),"Incorrect return value for phone number"); + Assertions.assertEquals( + 27304159, idMap.getPerson(11).getPhoneNum(), "Incorrect return value for phone number"); } + @Test void testGetFromMap() { // new instance of an identity map(not connected to any DB here) @@ -67,8 +69,8 @@ class IdentityMapTest { idMap.addPerson(person4); idMap.addPerson(person5); // Test for dummy persons in the map - Assertions.assertEquals(person1,idMap.getPerson(11),"Incorrect person record returned"); - Assertions.assertEquals(person4,idMap.getPerson(44),"Incorrect person record returned"); + Assertions.assertEquals(person1, idMap.getPerson(11), "Incorrect person record returned"); + Assertions.assertEquals(person4, idMap.getPerson(44), "Incorrect person record returned"); // Test for person with given id not in map Assertions.assertNull(idMap.getPerson(1), "Incorrect person record returned"); } diff --git a/identity-map/src/test/java/com/iluwatar/identitymap/PersonDbSimulatorImplementationTest.java b/identity-map/src/test/java/com/iluwatar/identitymap/PersonDbSimulatorImplementationTest.java index 6823f3919..7861cb2f6 100644 --- a/identity-map/src/test/java/com/iluwatar/identitymap/PersonDbSimulatorImplementationTest.java +++ b/identity-map/src/test/java/com/iluwatar/identitymap/PersonDbSimulatorImplementationTest.java @@ -29,10 +29,10 @@ import org.junit.jupiter.api.Test; class PersonDbSimulatorImplementationTest { @Test - void testInsert(){ + void testInsert() { // DataBase initialization. PersonDbSimulatorImplementation db = new PersonDbSimulatorImplementation(); - Assertions.assertEquals(0,db.size(),"Size of null database should be 0"); + Assertions.assertEquals(0, db.size(), "Size of null database should be 0"); // Dummy persons. Person person1 = new Person(1, "Thomas", 27304159); Person person2 = new Person(2, "John", 42273631); @@ -41,71 +41,77 @@ class PersonDbSimulatorImplementationTest { db.insert(person2); db.insert(person3); // Test size after insertion. - Assertions.assertEquals(3,db.size(),"Incorrect size for database."); + Assertions.assertEquals(3, db.size(), "Incorrect size for database."); Person person4 = new Person(4, "Finn", 20499078); Person person5 = new Person(5, "Michael", 40599078); db.insert(person4); db.insert(person5); // Test size after more insertions. - Assertions.assertEquals(5,db.size(),"Incorrect size for database."); - Person person5duplicate = new Person(5,"Kevin",89589122); + Assertions.assertEquals(5, db.size(), "Incorrect size for database."); + Person person5duplicate = new Person(5, "Kevin", 89589122); db.insert(person5duplicate); // Test size after attempt to insert record with duplicate key. - Assertions.assertEquals(5,db.size(),"Incorrect size for data base"); + Assertions.assertEquals(5, db.size(), "Incorrect size for data base"); } + @Test - void findNotInDb(){ + void findNotInDb() { PersonDbSimulatorImplementation db = new PersonDbSimulatorImplementation(); Person person1 = new Person(1, "Thomas", 27304159); Person person2 = new Person(2, "John", 42273631); db.insert(person1); db.insert(person2); // Test if IdNotFoundException is thrown where expected. - Assertions.assertThrows(IdNotFoundException.class,()->db.find(3)); + Assertions.assertThrows(IdNotFoundException.class, () -> db.find(3)); } + @Test - void findInDb(){ + void findInDb() { PersonDbSimulatorImplementation db = new PersonDbSimulatorImplementation(); Person person1 = new Person(1, "Thomas", 27304159); Person person2 = new Person(2, "John", 42273631); db.insert(person1); db.insert(person2); - Assertions.assertEquals(person2,db.find(2),"Record that was found was incorrect."); + Assertions.assertEquals(person2, db.find(2), "Record that was found was incorrect."); } + @Test - void updateNotInDb(){ + void updateNotInDb() { PersonDbSimulatorImplementation db = new PersonDbSimulatorImplementation(); Person person1 = new Person(1, "Thomas", 27304159); Person person2 = new Person(2, "John", 42273631); db.insert(person1); db.insert(person2); - Person person3 = new Person(3,"Micheal",25671234); + Person person3 = new Person(3, "Micheal", 25671234); // Test if IdNotFoundException is thrown when person with ID 3 is not in DB. - Assertions.assertThrows(IdNotFoundException.class,()->db.update(person3)); + Assertions.assertThrows(IdNotFoundException.class, () -> db.update(person3)); } + @Test - void updateInDb(){ + void updateInDb() { PersonDbSimulatorImplementation db = new PersonDbSimulatorImplementation(); Person person1 = new Person(1, "Thomas", 27304159); Person person2 = new Person(2, "John", 42273631); db.insert(person1); db.insert(person2); - Person person = new Person(2,"Thomas",42273690); + Person person = new Person(2, "Thomas", 42273690); db.update(person); - Assertions.assertEquals(person,db.find(2),"Incorrect update."); + Assertions.assertEquals(person, db.find(2), "Incorrect update."); } + @Test - void deleteNotInDb(){ + void deleteNotInDb() { PersonDbSimulatorImplementation db = new PersonDbSimulatorImplementation(); Person person1 = new Person(1, "Thomas", 27304159); Person person2 = new Person(2, "John", 42273631); db.insert(person1); db.insert(person2); // Test if IdNotFoundException is thrown when person with this ID not in DB. - Assertions.assertThrows(IdNotFoundException.class,()->db.delete(3)); + Assertions.assertThrows(IdNotFoundException.class, () -> db.delete(3)); } + @Test - void deleteInDb(){ + void deleteInDb() { PersonDbSimulatorImplementation db = new PersonDbSimulatorImplementation(); Person person1 = new Person(1, "Thomas", 27304159); Person person2 = new Person(2, "John", 42273631); @@ -114,9 +120,8 @@ class PersonDbSimulatorImplementationTest { // delete the record. db.delete(1); // test size of database after deletion. - Assertions.assertEquals(1,db.size(),"Size after deletion is incorrect."); + Assertions.assertEquals(1, db.size(), "Size after deletion is incorrect."); // try to find deleted record in db. - Assertions.assertThrows(IdNotFoundException.class,()->db.find(1)); + Assertions.assertThrows(IdNotFoundException.class, () -> db.find(1)); } - } diff --git a/identity-map/src/test/java/com/iluwatar/identitymap/PersonFinderTest.java b/identity-map/src/test/java/com/iluwatar/identitymap/PersonFinderTest.java index 88f706048..9257a3b0a 100644 --- a/identity-map/src/test/java/com/iluwatar/identitymap/PersonFinderTest.java +++ b/identity-map/src/test/java/com/iluwatar/identitymap/PersonFinderTest.java @@ -29,7 +29,7 @@ import org.junit.jupiter.api.Test; class PersonFinderTest { @Test - void personFoundInDB(){ + void personFoundInDB() { // personFinderInstance PersonFinder personFinder = new PersonFinder(); // init database for our personFinder @@ -48,14 +48,20 @@ class PersonFinderTest { db.insert(person5); personFinder.setDb(db); - Assertions.assertEquals(person1,personFinder.getPerson(1),"Find person returns incorrect record."); - Assertions.assertEquals(person3,personFinder.getPerson(3),"Find person returns incorrect record."); - Assertions.assertEquals(person2,personFinder.getPerson(2),"Find person returns incorrect record."); - Assertions.assertEquals(person5,personFinder.getPerson(5),"Find person returns incorrect record."); - Assertions.assertEquals(person4,personFinder.getPerson(4),"Find person returns incorrect record."); + Assertions.assertEquals( + person1, personFinder.getPerson(1), "Find person returns incorrect record."); + Assertions.assertEquals( + person3, personFinder.getPerson(3), "Find person returns incorrect record."); + Assertions.assertEquals( + person2, personFinder.getPerson(2), "Find person returns incorrect record."); + Assertions.assertEquals( + person5, personFinder.getPerson(5), "Find person returns incorrect record."); + Assertions.assertEquals( + person4, personFinder.getPerson(4), "Find person returns incorrect record."); } + @Test - void personFoundInIdMap(){ + void personFoundInIdMap() { // personFinderInstance PersonFinder personFinder = new PersonFinder(); // init database for our personFinder @@ -76,19 +82,20 @@ class PersonFinderTest { // Assure key is not in the ID map. Assertions.assertFalse(personFinder.getIdentityMap().getPersonMap().containsKey(3)); // Assure key is in the database. - Assertions.assertEquals(person3,personFinder.getPerson(3),"Finder returns incorrect record."); + Assertions.assertEquals(person3, personFinder.getPerson(3), "Finder returns incorrect record."); // Assure that the record for this key is cached in the Map now. Assertions.assertTrue(personFinder.getIdentityMap().getPersonMap().containsKey(3)); // Find the record again. This time it will be found in the map. - Assertions.assertEquals(person3,personFinder.getPerson(3),"Finder returns incorrect record."); + Assertions.assertEquals(person3, personFinder.getPerson(3), "Finder returns incorrect record."); } + @Test - void personNotFoundInDB(){ + void personNotFoundInDB() { PersonFinder personFinder = new PersonFinder(); // init database for our personFinder PersonDbSimulatorImplementation db = new PersonDbSimulatorImplementation(); personFinder.setDb(db); - Assertions.assertThrows(IdNotFoundException.class,()->personFinder.getPerson(1)); + Assertions.assertThrows(IdNotFoundException.class, () -> personFinder.getPerson(1)); // Dummy persons Person person1 = new Person(1, "John", 27304159); Person person2 = new Person(2, "Thomas", 42273631); @@ -102,11 +109,10 @@ class PersonFinderTest { db.insert(person5); personFinder.setDb(db); // Assure that the database has been updated. - Assertions.assertEquals(person4,personFinder.getPerson(4),"Find returns incorrect record"); + Assertions.assertEquals(person4, personFinder.getPerson(4), "Find returns incorrect record"); // Assure key is in DB now. - Assertions.assertDoesNotThrow(()->personFinder.getPerson(1)); + Assertions.assertDoesNotThrow(() -> personFinder.getPerson(1)); // Assure key not in DB. - Assertions.assertThrows(IdNotFoundException.class,()->personFinder.getPerson(6)); - + Assertions.assertThrows(IdNotFoundException.class, () -> personFinder.getPerson(6)); } } diff --git a/identity-map/src/test/java/com/iluwatar/identitymap/PersonTest.java b/identity-map/src/test/java/com/iluwatar/identitymap/PersonTest.java index 7c491bf59..8199daaa2 100644 --- a/identity-map/src/test/java/com/iluwatar/identitymap/PersonTest.java +++ b/identity-map/src/test/java/com/iluwatar/identitymap/PersonTest.java @@ -29,15 +29,15 @@ import org.junit.jupiter.api.Test; class PersonTest { @Test - void testEquality(){ + void testEquality() { // dummy persons. - Person person1 = new Person(1,"Harry",989950022); - Person person2 = new Person(2,"Kane",989920011); - Assertions.assertNotEquals(person1,person2,"Incorrect equality condition"); + Person person1 = new Person(1, "Harry", 989950022); + Person person2 = new Person(2, "Kane", 989920011); + Assertions.assertNotEquals(person1, person2, "Incorrect equality condition"); // person with duplicate nationalID. - Person person3 = new Person(2,"John",789012211); + Person person3 = new Person(2, "John", 789012211); // If nationalID is equal then persons are equal(even if name or phoneNum are different). // This situation will never arise in this implementation. Only for testing. - Assertions.assertEquals(person2,person3,"Incorrect inequality condition"); + Assertions.assertEquals(person2, person3, "Incorrect inequality condition"); } } diff --git a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/AbstractFilter.java b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/AbstractFilter.java index 697287325..7803ef878 100644 --- a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/AbstractFilter.java +++ b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/AbstractFilter.java @@ -24,15 +24,12 @@ */ package com.iluwatar.intercepting.filter; -/** - * Base class for order processing filters. Handles chain management. - */ +/** Base class for order processing filters. Handles chain management. */ public abstract class AbstractFilter implements Filter { private Filter next; - public AbstractFilter() { - } + public AbstractFilter() {} public AbstractFilter(Filter next) { this.next = next; diff --git a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/AddressFilter.java b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/AddressFilter.java index 9e08ea008..0f8aeeb55 100644 --- a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/AddressFilter.java +++ b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/AddressFilter.java @@ -27,7 +27,6 @@ package com.iluwatar.intercepting.filter; /** * Concrete implementation of filter This filter is responsible for checking/filtering the input in * the address field. - * */ public class AddressFilter extends AbstractFilter { diff --git a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/App.java b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/App.java index 454cc8800..53559ede1 100644 --- a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/App.java +++ b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/App.java @@ -44,7 +44,6 @@ package com.iluwatar.intercepting.filter; * *

In this example we check whether the order request is valid through pre-processing done via * {@link Filter}. Each field has its own corresponding {@link Filter}. - * */ public class App { diff --git a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Client.java b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Client.java index ea3d3a728..96f2e2acd 100644 --- a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Client.java +++ b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Client.java @@ -45,12 +45,10 @@ import javax.swing.WindowConstants; * *

This is where {@link Filter}s come to play as the client pre-processes the request before * being displayed in the {@link Target}. - * */ public class Client extends JFrame { // NOSONAR - @Serial - private static final long serialVersionUID = 1L; + @Serial private static final long serialVersionUID = 1L; private transient FilterManager filterManager; private final JLabel jl; @@ -59,9 +57,7 @@ public class Client extends JFrame { // NOSONAR private final JButton clearButton; private final JButton processButton; - /** - * Constructor. - */ + /** Constructor. */ public Client() { super("Client System"); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); @@ -100,10 +96,11 @@ public class Client extends JFrame { // NOSONAR panel.add(clearButton); panel.add(processButton); - clearButton.addActionListener(e -> { - Arrays.stream(jtAreas).forEach(i -> i.setText("")); - Arrays.stream(jtFields).forEach(i -> i.setText("")); - }); + clearButton.addActionListener( + e -> { + Arrays.stream(jtAreas).forEach(i -> i.setText("")); + Arrays.stream(jtFields).forEach(i -> i.setText("")); + }); processButton.addActionListener(this::actionPerformed); diff --git a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/ContactFilter.java b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/ContactFilter.java index 96f3f5582..14b491444 100644 --- a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/ContactFilter.java +++ b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/ContactFilter.java @@ -28,7 +28,6 @@ package com.iluwatar.intercepting.filter; * Concrete implementation of filter This filter checks for the contact field in which it checks if * the input consist of numbers and it also checks if the input follows the length constraint (11 * digits). - * */ public class ContactFilter extends AbstractFilter { @@ -36,7 +35,8 @@ public class ContactFilter extends AbstractFilter { public String execute(Order order) { var result = super.execute(order); var contactNumber = order.getContactNumber(); - if (contactNumber == null || contactNumber.matches(".*[^\\d]+.*") + if (contactNumber == null + || contactNumber.matches(".*[^\\d]+.*") || contactNumber.length() != 11) { return result + "Invalid contact number! "; } else { diff --git a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/DepositFilter.java b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/DepositFilter.java index b56abb9f3..2c13d831e 100644 --- a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/DepositFilter.java +++ b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/DepositFilter.java @@ -24,10 +24,7 @@ */ package com.iluwatar.intercepting.filter; -/** - * Concrete implementation of filter This checks for the deposit code. - * - */ +/** Concrete implementation of filter This checks for the deposit code. */ public class DepositFilter extends AbstractFilter { @Override diff --git a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Filter.java b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Filter.java index 82c36144e..fcadf86a7 100644 --- a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Filter.java +++ b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Filter.java @@ -27,27 +27,18 @@ package com.iluwatar.intercepting.filter; /** * Filters perform certain tasks prior or after execution of request by request handler. In this * case, before the request is handled by the target, the request undergoes through each Filter - * */ public interface Filter { - /** - * Execute order processing filter. - */ + /** Execute order processing filter. */ String execute(Order order); - /** - * Set next filter in chain after this. - */ + /** Set next filter in chain after this. */ void setNext(Filter filter); - /** - * Get next filter in chain after this. - */ + /** Get next filter in chain after this. */ Filter getNext(); - /** - * Get last filter in the chain. - */ + /** Get last filter in the chain. */ Filter getLast(); } diff --git a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/FilterChain.java b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/FilterChain.java index bf71d23c6..1fc27095a 100644 --- a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/FilterChain.java +++ b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/FilterChain.java @@ -24,19 +24,12 @@ */ package com.iluwatar.intercepting.filter; - -/** - * Filter Chain carries multiple filters and help to execute them in defined order on target. - * - */ +/** Filter Chain carries multiple filters and help to execute them in defined order on target. */ public class FilterChain { private Filter chain; - - /** - * Adds filter. - */ + /** Adds filter. */ public void addFilter(Filter filter) { if (chain == null) { chain = filter; @@ -45,9 +38,7 @@ public class FilterChain { } } - /** - * Execute filter chain. - */ + /** Execute filter chain. */ public String execute(Order order) { if (chain != null) { return chain.execute(order); diff --git a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/FilterManager.java b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/FilterManager.java index 62f20d905..93303dd9a 100644 --- a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/FilterManager.java +++ b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/FilterManager.java @@ -24,10 +24,7 @@ */ package com.iluwatar.intercepting.filter; -/** - * Filter Manager manages the filters and {@link FilterChain}. - * - */ +/** Filter Manager manages the filters and {@link FilterChain}. */ public class FilterManager { private final FilterChain filterChain; diff --git a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/NameFilter.java b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/NameFilter.java index aed8346ab..19f80a4ee 100644 --- a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/NameFilter.java +++ b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/NameFilter.java @@ -27,7 +27,6 @@ package com.iluwatar.intercepting.filter; /** * Concrete implementation of filter. This filter checks if the input in the Name field is valid. * (alphanumeric) - * */ public class NameFilter extends AbstractFilter { diff --git a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Order.java b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Order.java index 778c9d403..576b26a4c 100644 --- a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Order.java +++ b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Order.java @@ -27,12 +27,9 @@ package com.iluwatar.intercepting.filter; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; -import lombok.RequiredArgsConstructor; import lombok.Setter; -/** - * Order class carries the order data. - */ +/** Order class carries the order data. */ @Getter @Setter @NoArgsConstructor diff --git a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/OrderFilter.java b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/OrderFilter.java index 131359461..f3eed5f1a 100644 --- a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/OrderFilter.java +++ b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/OrderFilter.java @@ -24,10 +24,7 @@ */ package com.iluwatar.intercepting.filter; -/** - * Concrete implementation of filter. This checks for the order field. - * - */ +/** Concrete implementation of filter. This checks for the order field. */ public class OrderFilter extends AbstractFilter { @Override diff --git a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Target.java b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Target.java index b228a332f..92b76745e 100644 --- a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Target.java +++ b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Target.java @@ -39,28 +39,23 @@ import javax.swing.SwingUtilities; import javax.swing.WindowConstants; import javax.swing.table.DefaultTableModel; -/** - * This is where the requests are displayed after being validated by filters. - * - */ -public class Target extends JFrame { //NOSONAR +/** This is where the requests are displayed after being validated by filters. */ +public class Target extends JFrame { // NOSONAR - @Serial - private static final long serialVersionUID = 1L; + @Serial private static final long serialVersionUID = 1L; private final JTable jt; private final DefaultTableModel dtm; private final JButton del; - /** - * Constructor. - */ + /** Constructor. */ public Target() { super("Order System"); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); setSize(640, 480); - dtm = new DefaultTableModel( - new Object[]{"Name", "Contact Number", "Address", "Deposit Number", "Order"}, 0); + dtm = + new DefaultTableModel( + new Object[] {"Name", "Contact Number", "Address", "Deposit Number", "Order"}, 0); jt = new JTable(dtm); del = new JButton("Delete"); setup(); @@ -85,7 +80,7 @@ public class Target extends JFrame { //NOSONAR } public void execute(String[] request) { - dtm.addRow(new Object[]{request[0], request[1], request[2], request[3], request[4]}); + dtm.addRow(new Object[] {request[0], request[1], request[2], request[3], request[4]}); } class TargetListener implements ActionListener { diff --git a/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/AppTest.java b/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/AppTest.java index 78d4d0bdd..27e5aaba2 100644 --- a/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/AppTest.java +++ b/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/AppTest.java @@ -24,17 +24,15 @@ */ package com.iluwatar.intercepting.filter; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -/** - * Application test. - */ +import org.junit.jupiter.api.Test; + +/** Application test. */ class AppTest { @Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/FilterManagerTest.java b/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/FilterManagerTest.java index 74c86e204..969386c82 100644 --- a/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/FilterManagerTest.java +++ b/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/FilterManagerTest.java @@ -34,10 +34,7 @@ import static org.mockito.Mockito.when; import org.junit.jupiter.api.Test; -/** - * FilterManagerTest - * - */ +/** FilterManagerTest */ class FilterManagerTest { @Test @@ -66,4 +63,4 @@ class FilterManagerTest { verify(filter, times(1)).execute(any(Order.class)); verifyNoMoreInteractions(target, filter, order); } -} \ No newline at end of file +} diff --git a/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/FilterTest.java b/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/FilterTest.java index 8377a88d2..60b12a930 100644 --- a/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/FilterTest.java +++ b/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/FilterTest.java @@ -33,10 +33,7 @@ import java.util.List; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; -/** - * FilterTest - * - */ +/** FilterTest */ class FilterTest { private static final Order PERFECT_ORDER = @@ -49,41 +46,36 @@ class FilterTest { static List getTestData() { return List.of( - new Object[]{new NameFilter(), PERFECT_ORDER, ""}, - new Object[]{new NameFilter(), WRONG_NAME, "Invalid name!"}, - new Object[]{new NameFilter(), WRONG_CONTACT, ""}, - new Object[]{new NameFilter(), WRONG_ADDRESS, ""}, - new Object[]{new NameFilter(), WRONG_DEPOSIT, ""}, - new Object[]{new NameFilter(), WRONG_ORDER, ""}, - - new Object[]{new ContactFilter(), PERFECT_ORDER, ""}, - new Object[]{new ContactFilter(), WRONG_NAME, ""}, - new Object[]{new ContactFilter(), WRONG_CONTACT, "Invalid contact number!"}, - new Object[]{new ContactFilter(), WRONG_ADDRESS, ""}, - new Object[]{new ContactFilter(), WRONG_DEPOSIT, ""}, - new Object[]{new ContactFilter(), WRONG_ORDER, ""}, - - new Object[]{new AddressFilter(), PERFECT_ORDER, ""}, - new Object[]{new AddressFilter(), WRONG_NAME, ""}, - new Object[]{new AddressFilter(), WRONG_CONTACT, ""}, - new Object[]{new AddressFilter(), WRONG_ADDRESS, "Invalid address!"}, - new Object[]{new AddressFilter(), WRONG_DEPOSIT, ""}, - new Object[]{new AddressFilter(), WRONG_ORDER, ""}, - - new Object[]{new DepositFilter(), PERFECT_ORDER, ""}, - new Object[]{new DepositFilter(), WRONG_NAME, ""}, - new Object[]{new DepositFilter(), WRONG_CONTACT, ""}, - new Object[]{new DepositFilter(), WRONG_ADDRESS, ""}, - new Object[]{new DepositFilter(), WRONG_DEPOSIT, "Invalid deposit number!"}, - new Object[]{new DepositFilter(), WRONG_ORDER, ""}, - - new Object[]{new OrderFilter(), PERFECT_ORDER, ""}, - new Object[]{new OrderFilter(), WRONG_NAME, ""}, - new Object[]{new OrderFilter(), WRONG_CONTACT, ""}, - new Object[]{new OrderFilter(), WRONG_ADDRESS, ""}, - new Object[]{new OrderFilter(), WRONG_DEPOSIT, ""}, - new Object[]{new OrderFilter(), WRONG_ORDER, "Invalid order!"} - ); + new Object[] {new NameFilter(), PERFECT_ORDER, ""}, + new Object[] {new NameFilter(), WRONG_NAME, "Invalid name!"}, + new Object[] {new NameFilter(), WRONG_CONTACT, ""}, + new Object[] {new NameFilter(), WRONG_ADDRESS, ""}, + new Object[] {new NameFilter(), WRONG_DEPOSIT, ""}, + new Object[] {new NameFilter(), WRONG_ORDER, ""}, + new Object[] {new ContactFilter(), PERFECT_ORDER, ""}, + new Object[] {new ContactFilter(), WRONG_NAME, ""}, + new Object[] {new ContactFilter(), WRONG_CONTACT, "Invalid contact number!"}, + new Object[] {new ContactFilter(), WRONG_ADDRESS, ""}, + new Object[] {new ContactFilter(), WRONG_DEPOSIT, ""}, + new Object[] {new ContactFilter(), WRONG_ORDER, ""}, + new Object[] {new AddressFilter(), PERFECT_ORDER, ""}, + new Object[] {new AddressFilter(), WRONG_NAME, ""}, + new Object[] {new AddressFilter(), WRONG_CONTACT, ""}, + new Object[] {new AddressFilter(), WRONG_ADDRESS, "Invalid address!"}, + new Object[] {new AddressFilter(), WRONG_DEPOSIT, ""}, + new Object[] {new AddressFilter(), WRONG_ORDER, ""}, + new Object[] {new DepositFilter(), PERFECT_ORDER, ""}, + new Object[] {new DepositFilter(), WRONG_NAME, ""}, + new Object[] {new DepositFilter(), WRONG_CONTACT, ""}, + new Object[] {new DepositFilter(), WRONG_ADDRESS, ""}, + new Object[] {new DepositFilter(), WRONG_DEPOSIT, "Invalid deposit number!"}, + new Object[] {new DepositFilter(), WRONG_ORDER, ""}, + new Object[] {new OrderFilter(), PERFECT_ORDER, ""}, + new Object[] {new OrderFilter(), WRONG_NAME, ""}, + new Object[] {new OrderFilter(), WRONG_CONTACT, ""}, + new Object[] {new OrderFilter(), WRONG_ADDRESS, ""}, + new Object[] {new OrderFilter(), WRONG_DEPOSIT, ""}, + new Object[] {new OrderFilter(), WRONG_ORDER, "Invalid order!"}); } @ParameterizedTest @@ -100,5 +92,4 @@ class FilterTest { assertNull(filter.getNext()); assertSame(filter, filter.getLast()); } - } diff --git a/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/OrderTest.java b/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/OrderTest.java index ffa282fcb..3cb6ed3c8 100644 --- a/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/OrderTest.java +++ b/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/OrderTest.java @@ -28,10 +28,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; -/** - * OrderTest - * - */ +/** OrderTest */ class OrderTest { private static final String EXPECTED_VALUE = "test"; @@ -70,5 +67,4 @@ class OrderTest { order.setOrderItem(EXPECTED_VALUE); assertEquals(EXPECTED_VALUE, order.getOrderItem()); } - } diff --git a/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/TargetTest.java b/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/TargetTest.java index a1164f74c..c202020f7 100644 --- a/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/TargetTest.java +++ b/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/TargetTest.java @@ -29,17 +29,14 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; -/** - * TargetTest - * - */ +/** TargetTest */ class TargetTest { - - @Test - void testSetup(){ - final var target = new Target(); - assertEquals(target.getSize().getWidth(), Double.valueOf(640)); - assertEquals(target.getSize().getHeight(), Double.valueOf(480)); - assertTrue(target.isVisible()); - } + + @Test + void testSetup() { + final var target = new Target(); + assertEquals(target.getSize().getWidth(), Double.valueOf(640)); + assertEquals(target.getSize().getHeight(), Double.valueOf(480)); + assertTrue(target.isVisible()); + } } diff --git a/interpreter/pom.xml b/interpreter/pom.xml index 9f2129424..86c45ce22 100644 --- a/interpreter/pom.xml +++ b/interpreter/pom.xml @@ -34,6 +34,14 @@ interpreter + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/interpreter/src/main/java/com/iluwatar/interpreter/App.java b/interpreter/src/main/java/com/iluwatar/interpreter/App.java index df4dd1ec4..7f0c0b244 100644 --- a/interpreter/src/main/java/com/iluwatar/interpreter/App.java +++ b/interpreter/src/main/java/com/iluwatar/interpreter/App.java @@ -38,13 +38,13 @@ import lombok.extern.slf4j.Slf4j; * *

Expressions can be evaluated using prefix, infix or postfix notations This sample uses * postfix, where operator comes after the operands. - * */ @Slf4j public class App { /** * Program entry point. + * * @param args program arguments */ public static void main(String[] args) { @@ -64,8 +64,10 @@ public class App { // the stack var rightExpression = stack.pop(); var leftExpression = stack.pop(); - LOGGER.info("popped from stack left: {} right: {}", - leftExpression.interpret(), rightExpression.interpret()); + LOGGER.info( + "popped from stack left: {} right: {}", + leftExpression.interpret(), + rightExpression.interpret()); var operator = getOperatorInstance(s, leftExpression, rightExpression); LOGGER.info("operator: {}", operator); var result = operator.interpret(); @@ -86,6 +88,7 @@ public class App { /** * Checks whether the input parameter is an operator. + * * @param s input string * @return true if the input parameter is an operator */ @@ -95,6 +98,7 @@ public class App { /** * Returns correct expression based on the parameters. + * * @param s input string * @param left expression * @param right expression diff --git a/interpreter/src/main/java/com/iluwatar/interpreter/Expression.java b/interpreter/src/main/java/com/iluwatar/interpreter/Expression.java index a5f364d36..44b4ea278 100644 --- a/interpreter/src/main/java/com/iluwatar/interpreter/Expression.java +++ b/interpreter/src/main/java/com/iluwatar/interpreter/Expression.java @@ -24,9 +24,7 @@ */ package com.iluwatar.interpreter; -/** - * Expression. - */ +/** Expression. */ public abstract class Expression { public abstract int interpret(); diff --git a/interpreter/src/main/java/com/iluwatar/interpreter/MinusExpression.java b/interpreter/src/main/java/com/iluwatar/interpreter/MinusExpression.java index 12738add6..c6d7f5581 100644 --- a/interpreter/src/main/java/com/iluwatar/interpreter/MinusExpression.java +++ b/interpreter/src/main/java/com/iluwatar/interpreter/MinusExpression.java @@ -24,9 +24,7 @@ */ package com.iluwatar.interpreter; -/** - * MinusExpression. - */ +/** MinusExpression. */ public class MinusExpression extends Expression { private final Expression leftExpression; @@ -46,5 +44,4 @@ public class MinusExpression extends Expression { public String toString() { return "-"; } - } diff --git a/interpreter/src/main/java/com/iluwatar/interpreter/MultiplyExpression.java b/interpreter/src/main/java/com/iluwatar/interpreter/MultiplyExpression.java index d3803526d..a5c1efe4f 100644 --- a/interpreter/src/main/java/com/iluwatar/interpreter/MultiplyExpression.java +++ b/interpreter/src/main/java/com/iluwatar/interpreter/MultiplyExpression.java @@ -24,9 +24,7 @@ */ package com.iluwatar.interpreter; -/** - * MultiplyExpression. - */ +/** MultiplyExpression. */ public class MultiplyExpression extends Expression { private final Expression leftExpression; @@ -46,5 +44,4 @@ public class MultiplyExpression extends Expression { public String toString() { return "*"; } - } diff --git a/interpreter/src/main/java/com/iluwatar/interpreter/NumberExpression.java b/interpreter/src/main/java/com/iluwatar/interpreter/NumberExpression.java index 49f8c39ef..31a632c34 100644 --- a/interpreter/src/main/java/com/iluwatar/interpreter/NumberExpression.java +++ b/interpreter/src/main/java/com/iluwatar/interpreter/NumberExpression.java @@ -24,9 +24,7 @@ */ package com.iluwatar.interpreter; -/** - * NumberExpression. - */ +/** NumberExpression. */ public class NumberExpression extends Expression { private final int number; diff --git a/interpreter/src/main/java/com/iluwatar/interpreter/PlusExpression.java b/interpreter/src/main/java/com/iluwatar/interpreter/PlusExpression.java index 2fbea275a..4109f397d 100644 --- a/interpreter/src/main/java/com/iluwatar/interpreter/PlusExpression.java +++ b/interpreter/src/main/java/com/iluwatar/interpreter/PlusExpression.java @@ -24,9 +24,7 @@ */ package com.iluwatar.interpreter; -/** - * PlusExpression. - */ +/** PlusExpression. */ public class PlusExpression extends Expression { private final Expression leftExpression; diff --git a/interpreter/src/test/java/com/iluwatar/interpreter/AppTest.java b/interpreter/src/test/java/com/iluwatar/interpreter/AppTest.java index 56acffee5..4c72970c9 100644 --- a/interpreter/src/test/java/com/iluwatar/interpreter/AppTest.java +++ b/interpreter/src/test/java/com/iluwatar/interpreter/AppTest.java @@ -24,17 +24,15 @@ */ package com.iluwatar.interpreter; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -/** - * Application test - */ +import org.junit.jupiter.api.Test; + +/** Application test */ class AppTest { @Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/interpreter/src/test/java/com/iluwatar/interpreter/ExpressionTest.java b/interpreter/src/test/java/com/iluwatar/interpreter/ExpressionTest.java index a84e8a4c7..80d76416e 100644 --- a/interpreter/src/test/java/com/iluwatar/interpreter/ExpressionTest.java +++ b/interpreter/src/test/java/com/iluwatar/interpreter/ExpressionTest.java @@ -54,19 +54,15 @@ public abstract class ExpressionTest { final var testData = new ArrayList(); for (var i = -10; i < 10; i++) { for (var j = -10; j < 10; j++) { - testData.add(Arguments.of( - new NumberExpression(i), - new NumberExpression(j), - resultCalc.applyAsInt(i, j) - )); + testData.add( + Arguments.of( + new NumberExpression(i), new NumberExpression(j), resultCalc.applyAsInt(i, j))); } } return testData.stream(); } - /** - * The expected {@link E#toString()} response - */ + /** The expected {@link E#toString()} response */ private final String expectedToString; /** @@ -78,11 +74,11 @@ public abstract class ExpressionTest { * Create a new test instance with the given parameters and expected results * * @param expectedToString The expected {@link E#toString()} response - * @param factory Factory, used to create a new test object instance + * @param factory Factory, used to create a new test object instance */ - ExpressionTest(final String expectedToString, - final BiFunction factory - ) { + ExpressionTest( + final String expectedToString, + final BiFunction factory) { this.expectedToString = expectedToString; this.factory = factory; } @@ -94,9 +90,7 @@ public abstract class ExpressionTest { */ public abstract Stream expressionProvider(); - /** - * Verify if the expression calculates the correct result when calling {@link E#interpret()} - */ + /** Verify if the expression calculates the correct result when calling {@link E#interpret()} */ @ParameterizedTest @MethodSource("expressionProvider") void testInterpret(NumberExpression first, NumberExpression second, int result) { @@ -105,9 +99,7 @@ public abstract class ExpressionTest { assertEquals(result, expression.interpret()); } - /** - * Verify if the expression has the expected {@link E#toString()} value - */ + /** Verify if the expression has the expected {@link E#toString()} value */ @ParameterizedTest @MethodSource("expressionProvider") void testToString(NumberExpression first, NumberExpression second) { diff --git a/interpreter/src/test/java/com/iluwatar/interpreter/MinusExpressionTest.java b/interpreter/src/test/java/com/iluwatar/interpreter/MinusExpressionTest.java index 1ae8337d5..d773a8970 100644 --- a/interpreter/src/test/java/com/iluwatar/interpreter/MinusExpressionTest.java +++ b/interpreter/src/test/java/com/iluwatar/interpreter/MinusExpressionTest.java @@ -27,10 +27,7 @@ package com.iluwatar.interpreter; import java.util.stream.Stream; import org.junit.jupiter.params.provider.Arguments; -/** - * MinusExpressionTest - * - */ +/** MinusExpressionTest */ class MinusExpressionTest extends ExpressionTest { /** @@ -43,11 +40,8 @@ class MinusExpressionTest extends ExpressionTest { return prepareParameters((f, s) -> f - s); } - /** - * Create a new test instance using the given test parameters and expected result - */ + /** Create a new test instance using the given test parameters and expected result */ public MinusExpressionTest() { super("-", MinusExpression::new); } - -} \ No newline at end of file +} diff --git a/interpreter/src/test/java/com/iluwatar/interpreter/MultiplyExpressionTest.java b/interpreter/src/test/java/com/iluwatar/interpreter/MultiplyExpressionTest.java index c04bf705b..6d73341a3 100644 --- a/interpreter/src/test/java/com/iluwatar/interpreter/MultiplyExpressionTest.java +++ b/interpreter/src/test/java/com/iluwatar/interpreter/MultiplyExpressionTest.java @@ -27,10 +27,7 @@ package com.iluwatar.interpreter; import java.util.stream.Stream; import org.junit.jupiter.params.provider.Arguments; -/** - * MultiplyExpressionTest - * - */ +/** MultiplyExpressionTest */ class MultiplyExpressionTest extends ExpressionTest { /** @@ -43,11 +40,8 @@ class MultiplyExpressionTest extends ExpressionTest { return prepareParameters((f, s) -> f * s); } - /** - * Create a new test instance using the given test parameters and expected result - */ + /** Create a new test instance using the given test parameters and expected result */ public MultiplyExpressionTest() { super("*", MultiplyExpression::new); } - -} \ No newline at end of file +} diff --git a/interpreter/src/test/java/com/iluwatar/interpreter/NumberExpressionTest.java b/interpreter/src/test/java/com/iluwatar/interpreter/NumberExpressionTest.java index 459cf71e2..9d917c03a 100644 --- a/interpreter/src/test/java/com/iluwatar/interpreter/NumberExpressionTest.java +++ b/interpreter/src/test/java/com/iluwatar/interpreter/NumberExpressionTest.java @@ -31,10 +31,7 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; -/** - * NumberExpressionTest - * - */ +/** NumberExpressionTest */ class NumberExpressionTest extends ExpressionTest { /** @@ -47,9 +44,7 @@ class NumberExpressionTest extends ExpressionTest { return prepareParameters((f, s) -> f); } - /** - * Create a new test instance using the given test parameters and expected result - */ + /** Create a new test instance using the given test parameters and expected result */ public NumberExpressionTest() { super("number", (f, s) -> f); } @@ -65,5 +60,4 @@ class NumberExpressionTest extends ExpressionTest { final var numberExpression = new NumberExpression(testStringValue); assertEquals(expectedValue, numberExpression.interpret()); } - -} \ No newline at end of file +} diff --git a/interpreter/src/test/java/com/iluwatar/interpreter/PlusExpressionTest.java b/interpreter/src/test/java/com/iluwatar/interpreter/PlusExpressionTest.java index 3dc04a06c..a93f27c84 100644 --- a/interpreter/src/test/java/com/iluwatar/interpreter/PlusExpressionTest.java +++ b/interpreter/src/test/java/com/iluwatar/interpreter/PlusExpressionTest.java @@ -27,10 +27,7 @@ package com.iluwatar.interpreter; import java.util.stream.Stream; import org.junit.jupiter.params.provider.Arguments; -/** - * PlusExpressionTest - * - */ +/** PlusExpressionTest */ class PlusExpressionTest extends ExpressionTest { /** @@ -43,11 +40,8 @@ class PlusExpressionTest extends ExpressionTest { return prepareParameters(Integer::sum); } - /** - * Create a new test instance using the given test parameters and expected result - */ + /** Create a new test instance using the given test parameters and expected result */ public PlusExpressionTest() { super("+", PlusExpression::new); } - -} \ No newline at end of file +} diff --git a/iterator/pom.xml b/iterator/pom.xml index 4afb9278c..4578eed1b 100644 --- a/iterator/pom.xml +++ b/iterator/pom.xml @@ -34,6 +34,14 @@ iterator + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/iterator/src/main/java/com/iluwatar/iterator/bst/BstIterator.java b/iterator/src/main/java/com/iluwatar/iterator/bst/BstIterator.java index 8796a7939..a027a2862 100644 --- a/iterator/src/main/java/com/iluwatar/iterator/bst/BstIterator.java +++ b/iterator/src/main/java/com/iluwatar/iterator/bst/BstIterator.java @@ -33,7 +33,7 @@ import java.util.NoSuchElementException; * expect to retrieve TreeNodes according to the Integer's natural ordering (1, 2, 3...) * * @param This Iterator has been implemented with generic typing to allow for TreeNodes of - * different value types + * different value types */ public class BstIterator> implements Iterator> { @@ -83,5 +83,4 @@ public class BstIterator> implements Iterator> { private final T val; - @Getter - @Setter - private TreeNode left; + @Getter @Setter private TreeNode left; - @Getter - @Setter - private TreeNode right; + @Getter @Setter private TreeNode right; /** * Creates a TreeNode with a given value, and null children. @@ -129,5 +125,4 @@ public class TreeNode> { public String toString() { return val.toString(); } - } diff --git a/iterator/src/main/java/com/iluwatar/iterator/list/Item.java b/iterator/src/main/java/com/iluwatar/iterator/list/Item.java index 776258ecf..0188078a1 100644 --- a/iterator/src/main/java/com/iluwatar/iterator/list/Item.java +++ b/iterator/src/main/java/com/iluwatar/iterator/list/Item.java @@ -28,15 +28,11 @@ import lombok.AllArgsConstructor; import lombok.Getter; import lombok.Setter; -/** - * Item. - */ +/** Item. */ @AllArgsConstructor public class Item { - @Getter - @Setter - private ItemType type; + @Getter @Setter private ItemType type; private final String name; @Override diff --git a/iterator/src/main/java/com/iluwatar/iterator/list/ItemType.java b/iterator/src/main/java/com/iluwatar/iterator/list/ItemType.java index 1325cd365..2655a7aa0 100644 --- a/iterator/src/main/java/com/iluwatar/iterator/list/ItemType.java +++ b/iterator/src/main/java/com/iluwatar/iterator/list/ItemType.java @@ -24,11 +24,10 @@ */ package com.iluwatar.iterator.list; -/** - * ItemType enumeration. - */ +/** ItemType enumeration. */ public enum ItemType { - - ANY, WEAPON, RING, POTION - + ANY, + WEAPON, + RING, + POTION } diff --git a/iterator/src/main/java/com/iluwatar/iterator/list/TreasureChest.java b/iterator/src/main/java/com/iluwatar/iterator/list/TreasureChest.java index 2a0472dcb..1eb3905a7 100644 --- a/iterator/src/main/java/com/iluwatar/iterator/list/TreasureChest.java +++ b/iterator/src/main/java/com/iluwatar/iterator/list/TreasureChest.java @@ -28,39 +28,33 @@ import com.iluwatar.iterator.Iterator; import java.util.ArrayList; import java.util.List; -/** - * TreasureChest, the collection class. - */ +/** TreasureChest, the collection class. */ public class TreasureChest { private final List items; - /** - * Constructor. - */ + /** Constructor. */ public TreasureChest() { - items = List.of( - new Item(ItemType.POTION, "Potion of courage"), - new Item(ItemType.RING, "Ring of shadows"), - new Item(ItemType.POTION, "Potion of wisdom"), - new Item(ItemType.POTION, "Potion of blood"), - new Item(ItemType.WEAPON, "Sword of silver +1"), - new Item(ItemType.POTION, "Potion of rust"), - new Item(ItemType.POTION, "Potion of healing"), - new Item(ItemType.RING, "Ring of armor"), - new Item(ItemType.WEAPON, "Steel halberd"), - new Item(ItemType.WEAPON, "Dagger of poison")); + items = + List.of( + new Item(ItemType.POTION, "Potion of courage"), + new Item(ItemType.RING, "Ring of shadows"), + new Item(ItemType.POTION, "Potion of wisdom"), + new Item(ItemType.POTION, "Potion of blood"), + new Item(ItemType.WEAPON, "Sword of silver +1"), + new Item(ItemType.POTION, "Potion of rust"), + new Item(ItemType.POTION, "Potion of healing"), + new Item(ItemType.RING, "Ring of armor"), + new Item(ItemType.WEAPON, "Steel halberd"), + new Item(ItemType.WEAPON, "Dagger of poison")); } public Iterator iterator(ItemType itemType) { return new TreasureChestItemIterator(this, itemType); } - /** - * Get all items. - */ + /** Get all items. */ public List getItems() { return new ArrayList<>(items); } - } diff --git a/iterator/src/main/java/com/iluwatar/iterator/list/TreasureChestItemIterator.java b/iterator/src/main/java/com/iluwatar/iterator/list/TreasureChestItemIterator.java index 25f6e1434..51c33f931 100644 --- a/iterator/src/main/java/com/iluwatar/iterator/list/TreasureChestItemIterator.java +++ b/iterator/src/main/java/com/iluwatar/iterator/list/TreasureChestItemIterator.java @@ -26,18 +26,14 @@ package com.iluwatar.iterator.list; import com.iluwatar.iterator.Iterator; -/** - * TreasureChestItemIterator. - */ +/** TreasureChestItemIterator. */ public class TreasureChestItemIterator implements Iterator { private final TreasureChest chest; private int idx; private final ItemType type; - /** - * Constructor. - */ + /** Constructor. */ public TreasureChestItemIterator(TreasureChest chest, ItemType type) { this.chest = chest; this.type = type; diff --git a/iterator/src/test/java/com/iluwatar/iterator/AppTest.java b/iterator/src/test/java/com/iluwatar/iterator/AppTest.java index da2ed3c67..13766bbc9 100644 --- a/iterator/src/test/java/com/iluwatar/iterator/AppTest.java +++ b/iterator/src/test/java/com/iluwatar/iterator/AppTest.java @@ -24,17 +24,15 @@ */ package com.iluwatar.iterator; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -/** - * Application Test - */ +import org.junit.jupiter.api.Test; + +/** Application Test */ class AppTest { @Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } -} \ No newline at end of file +} diff --git a/iterator/src/test/java/com/iluwatar/iterator/bst/BstIteratorTest.java b/iterator/src/test/java/com/iluwatar/iterator/bst/BstIteratorTest.java index 2014aadc8..a075ce75f 100644 --- a/iterator/src/test/java/com/iluwatar/iterator/bst/BstIteratorTest.java +++ b/iterator/src/test/java/com/iluwatar/iterator/bst/BstIteratorTest.java @@ -56,7 +56,9 @@ class BstIteratorTest { @Test void nextForEmptyTree() { var iter = new BstIterator<>(emptyRoot); - assertThrows(NoSuchElementException.class, iter::next, + assertThrows( + NoSuchElementException.class, + iter::next, "next() should throw an IllegalStateException if hasNext() is false."); } @@ -100,5 +102,4 @@ class BstIteratorTest { assertEquals(Integer.valueOf(7), iter.next().getVal(), "Sixth Node is 7."); assertFalse(iter.hasNext(), "Iterator hasNext() should be false, end of tree."); } - } diff --git a/iterator/src/test/java/com/iluwatar/iterator/list/TreasureChestTest.java b/iterator/src/test/java/com/iluwatar/iterator/list/TreasureChestTest.java index c7c54a8cb..3c298180d 100644 --- a/iterator/src/test/java/com/iluwatar/iterator/list/TreasureChestTest.java +++ b/iterator/src/test/java/com/iluwatar/iterator/list/TreasureChestTest.java @@ -32,10 +32,7 @@ import java.util.List; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; -/** - * TreasureChestTest - * - */ +/** TreasureChestTest */ class TreasureChestTest { /** @@ -45,17 +42,16 @@ class TreasureChestTest { */ public static List dataProvider() { return List.of( - new Object[]{new Item(ItemType.POTION, "Potion of courage")}, - new Object[]{new Item(ItemType.RING, "Ring of shadows")}, - new Object[]{new Item(ItemType.POTION, "Potion of wisdom")}, - new Object[]{new Item(ItemType.POTION, "Potion of blood")}, - new Object[]{new Item(ItemType.WEAPON, "Sword of silver +1")}, - new Object[]{new Item(ItemType.POTION, "Potion of rust")}, - new Object[]{new Item(ItemType.POTION, "Potion of healing")}, - new Object[]{new Item(ItemType.RING, "Ring of armor")}, - new Object[]{new Item(ItemType.WEAPON, "Steel halberd")}, - new Object[]{new Item(ItemType.WEAPON, "Dagger of poison")} - ); + new Object[] {new Item(ItemType.POTION, "Potion of courage")}, + new Object[] {new Item(ItemType.RING, "Ring of shadows")}, + new Object[] {new Item(ItemType.POTION, "Potion of wisdom")}, + new Object[] {new Item(ItemType.POTION, "Potion of blood")}, + new Object[] {new Item(ItemType.WEAPON, "Sword of silver +1")}, + new Object[] {new Item(ItemType.POTION, "Potion of rust")}, + new Object[] {new Item(ItemType.POTION, "Potion of healing")}, + new Object[] {new Item(ItemType.RING, "Ring of armor")}, + new Object[] {new Item(ItemType.WEAPON, "Steel halberd")}, + new Object[] {new Item(ItemType.WEAPON, "Dagger of poison")}); } /** @@ -82,7 +78,6 @@ class TreasureChestTest { } fail("Expected to find item [" + expectedItem + "] using iterator, but we didn't."); - } /** @@ -109,7 +104,5 @@ class TreasureChestTest { } fail("Expected to find item [" + expectedItem + "] in the item list, but we didn't."); - } - -} \ No newline at end of file +} diff --git a/layered-architecture/pom.xml b/layered-architecture/pom.xml index 07ca0bdef..c91fc733e 100644 --- a/layered-architecture/pom.xml +++ b/layered-architecture/pom.xml @@ -38,18 +38,6 @@ layers layers - - - - org.springframework.boot - spring-boot-dependencies - pom - 3.2.4 - import - - - - org.springframework.boot @@ -59,17 +47,11 @@ org.springframework.boot spring-boot-starter-data-jpa - com.h2database h2 runtime - - org.projectlombok - lombok - true - org.springframework.boot spring-boot-starter-test @@ -80,16 +62,19 @@ - org.springframework.boot - spring-boot-maven-plugin - - - - org.projectlombok - lombok - - - + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.layers.Runner + + + + + diff --git a/layered-architecture/src/main/java/com/iluwatar/layers/Runner.java b/layered-architecture/src/main/java/com/iluwatar/layers/Runner.java index 5e9d28758..4c4fb6837 100644 --- a/layered-architecture/src/main/java/com/iluwatar/layers/Runner.java +++ b/layered-architecture/src/main/java/com/iluwatar/layers/Runner.java @@ -35,18 +35,18 @@ import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.domain.EntityScan; import org.springframework.context.annotation.ComponentScan; -import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.stereotype.Component; import service.CakeBakingService; import view.CakeViewImpl; /** - * The Runner class is the entry point of the application. - * It implements CommandLineRunner, which means it will execute the run method after the application context is loaded. + * The Runner class is the entry point of the application. It implements CommandLineRunner, which + * means it will execute the run method after the application context is loaded. * - *

The Runner class is responsible for initializing the cake baking service with sample data and creating a view to render the cakes. - * It uses the CakeBakingService to save new layers and toppings and to bake new cakes. - * It also handles exceptions that might occur during the cake baking process.

+ *

The Runner class is responsible for initializing the cake baking service with sample data and + * creating a view to render the cakes. It uses the CakeBakingService to save new layers and + * toppings and to bake new cakes. It also handles exceptions that might occur during the cake + * baking process. */ @EntityScan(basePackages = "entity") @ComponentScan(basePackages = {"com.iluwatar.layers", "service", "dto", "exception", "view", "dao"}) @@ -63,7 +63,7 @@ public class Runner implements CommandLineRunner { @Override public void run(String... args) { - //initialize sample data + // initialize sample data initializeData(); // create view and render it var cakeView = new CakeViewImpl(cakeBakingService); @@ -74,9 +74,7 @@ public class Runner implements CommandLineRunner { SpringApplication.run(Runner.class, args); } - /** - * Initializes the example data. - */ + /** Initializes the example data. */ private void initializeData() { cakeBakingService.saveNewLayer(new CakeLayerInfo("chocolate", 1200)); cakeBakingService.saveNewLayer(new CakeLayerInfo("banana", 900)); @@ -88,17 +86,25 @@ public class Runner implements CommandLineRunner { cakeBakingService.saveNewTopping(new CakeToppingInfo("candies", 350)); cakeBakingService.saveNewTopping(new CakeToppingInfo("cherry", 350)); - var cake1 = new CakeInfo(new CakeToppingInfo("candies", 0), - List.of(new CakeLayerInfo("chocolate", 0), new CakeLayerInfo("banana", 0), - new CakeLayerInfo(STRAWBERRY, 0))); + var cake1 = + new CakeInfo( + new CakeToppingInfo("candies", 0), + List.of( + new CakeLayerInfo("chocolate", 0), + new CakeLayerInfo("banana", 0), + new CakeLayerInfo(STRAWBERRY, 0))); try { cakeBakingService.bakeNewCake(cake1); } catch (CakeBakingException e) { LOGGER.error("Cake baking exception", e); } - var cake2 = new CakeInfo(new CakeToppingInfo("cherry", 0), - List.of(new CakeLayerInfo("vanilla", 0), new CakeLayerInfo("lemon", 0), - new CakeLayerInfo(STRAWBERRY, 0))); + var cake2 = + new CakeInfo( + new CakeToppingInfo("cherry", 0), + List.of( + new CakeLayerInfo("vanilla", 0), + new CakeLayerInfo("lemon", 0), + new CakeLayerInfo(STRAWBERRY, 0))); try { cakeBakingService.bakeNewCake(cake2); } catch (CakeBakingException e) { diff --git a/layered-architecture/src/main/java/com/iluwatar/layers/app/LayersApp.java b/layered-architecture/src/main/java/com/iluwatar/layers/app/LayersApp.java index 58828b6ea..2870366e0 100644 --- a/layered-architecture/src/main/java/com/iluwatar/layers/app/LayersApp.java +++ b/layered-architecture/src/main/java/com/iluwatar/layers/app/LayersApp.java @@ -33,8 +33,8 @@ import org.springframework.data.jpa.repository.config.EnableJpaRepositories; /** * The Layers pattern is a structural design pattern that organizes system architecture into * distinct layers, each with a specific responsibility and abstraction level. This separation - * allows for increased modularity, facilitating independent development, maintenance, and reuse - * of each layer. Commonly, layers interact with each other through well-defined interfaces, with + * allows for increased modularity, facilitating independent development, maintenance, and reuse of + * each layer. Commonly, layers interact with each other through well-defined interfaces, with * higher layers (more abstract) depending on lower layers (more concrete), but not vice versa, * promoting a clear hierarchy and separation of concerns. */ @@ -46,7 +46,5 @@ public class LayersApp { public static void main(String[] args) { SpringApplication.run(LayersApp.class, args); - } - } diff --git a/layered-architecture/src/main/java/dao/CakeDao.java b/layered-architecture/src/main/java/dao/CakeDao.java index 06d74bace..aae92a175 100644 --- a/layered-architecture/src/main/java/dao/CakeDao.java +++ b/layered-architecture/src/main/java/dao/CakeDao.java @@ -28,8 +28,6 @@ import entity.Cake; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; -/** - * CRUD repository for cakes. - */ +/** CRUD repository for cakes. */ @Repository public interface CakeDao extends JpaRepository {} diff --git a/layered-architecture/src/main/java/dao/CakeLayerDao.java b/layered-architecture/src/main/java/dao/CakeLayerDao.java index 90a523f16..0e4415ce4 100644 --- a/layered-architecture/src/main/java/dao/CakeLayerDao.java +++ b/layered-architecture/src/main/java/dao/CakeLayerDao.java @@ -28,10 +28,6 @@ import entity.CakeLayer; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; -/** - * CRUD repository for cake layers. - */ +/** CRUD repository for cake layers. */ @Repository -public interface CakeLayerDao extends JpaRepository { - -} +public interface CakeLayerDao extends JpaRepository {} diff --git a/layered-architecture/src/main/java/dao/CakeToppingDao.java b/layered-architecture/src/main/java/dao/CakeToppingDao.java index 0d0c8836d..bc7b4a56f 100644 --- a/layered-architecture/src/main/java/dao/CakeToppingDao.java +++ b/layered-architecture/src/main/java/dao/CakeToppingDao.java @@ -24,16 +24,10 @@ */ package dao; - - import entity.CakeTopping; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; -/** - * CRUD repository cake toppings. - */ +/** CRUD repository cake toppings. */ @Repository -public interface CakeToppingDao extends JpaRepository { - -} +public interface CakeToppingDao extends JpaRepository {} diff --git a/layered-architecture/src/main/java/dto/CakeInfo.java b/layered-architecture/src/main/java/dto/CakeInfo.java index 0bda58239..475c99448 100644 --- a/layered-architecture/src/main/java/dto/CakeInfo.java +++ b/layered-architecture/src/main/java/dto/CakeInfo.java @@ -27,36 +27,28 @@ package dto; import java.util.List; -/** - * DTO for cakes. - */ +/** DTO for cakes. */ public class CakeInfo { public final Long id; public final CakeToppingInfo cakeToppingInfo; public final List cakeLayerInfos; - /** - * Constructor. - */ + /** Constructor. */ public CakeInfo(Long id, CakeToppingInfo cakeToppingInfo, List cakeLayerInfos) { this.id = id; this.cakeToppingInfo = cakeToppingInfo; this.cakeLayerInfos = cakeLayerInfos; } - /** - * Constructor. - */ + /** Constructor. */ public CakeInfo(CakeToppingInfo cakeToppingInfo, List cakeLayerInfos) { this.id = null; this.cakeToppingInfo = cakeToppingInfo; this.cakeLayerInfos = cakeLayerInfos; } - /** - * Calculate calories. - */ + /** Calculate calories. */ public int calculateTotalCalories() { var total = cakeToppingInfo != null ? cakeToppingInfo.calories : 0; total += cakeLayerInfos.stream().mapToInt(c -> c.calories).sum(); @@ -65,7 +57,8 @@ public class CakeInfo { @Override public String toString() { - return String.format("CakeInfo id=%d topping=%s layers=%s totalCalories=%d", id, - cakeToppingInfo, cakeLayerInfos, calculateTotalCalories()); + return String.format( + "CakeInfo id=%d topping=%s layers=%s totalCalories=%d", + id, cakeToppingInfo, cakeLayerInfos, calculateTotalCalories()); } } diff --git a/layered-architecture/src/main/java/dto/CakeLayerInfo.java b/layered-architecture/src/main/java/dto/CakeLayerInfo.java index 6689b8746..e7e464e2d 100644 --- a/layered-architecture/src/main/java/dto/CakeLayerInfo.java +++ b/layered-architecture/src/main/java/dto/CakeLayerInfo.java @@ -25,27 +25,21 @@ package dto; -/** - * DTO for cake layers. - */ +/** DTO for cake layers. */ public class CakeLayerInfo { public final Long id; public final String name; public final int calories; - /** - * Constructor. - */ + /** Constructor. */ public CakeLayerInfo(Long id, String name, int calories) { this.id = id; this.name = name; this.calories = calories; } - /** - * Constructor. - */ + /** Constructor. */ public CakeLayerInfo(String name, int calories) { this.id = null; this.name = name; diff --git a/layered-architecture/src/main/java/dto/CakeToppingInfo.java b/layered-architecture/src/main/java/dto/CakeToppingInfo.java index a36572086..9c48d869c 100644 --- a/layered-architecture/src/main/java/dto/CakeToppingInfo.java +++ b/layered-architecture/src/main/java/dto/CakeToppingInfo.java @@ -25,27 +25,21 @@ package dto; -/** - * DTO for cake toppings. - */ +/** DTO for cake toppings. */ public class CakeToppingInfo { public final Long id; public final String name; public final int calories; - /** - * Constructor. - */ + /** Constructor. */ public CakeToppingInfo(Long id, String name, int calories) { this.id = id; this.name = name; this.calories = calories; } - /** - * Constructor. - */ + /** Constructor. */ public CakeToppingInfo(String name, int calories) { this.id = null; this.name = name; @@ -54,7 +48,6 @@ public class CakeToppingInfo { @Override public String toString() { - return String.format("CakeToppingInfo id=%d name=%s calories=%d", id, name, - calories); + return String.format("CakeToppingInfo id=%d name=%s calories=%d", id, name, calories); } } diff --git a/layered-architecture/src/main/java/entity/Cake.java b/layered-architecture/src/main/java/entity/Cake.java index 92dcc5ecf..58a8af659 100644 --- a/layered-architecture/src/main/java/entity/Cake.java +++ b/layered-architecture/src/main/java/entity/Cake.java @@ -37,17 +37,13 @@ import java.util.Set; import lombok.Getter; import lombok.Setter; -/** - * Cake entity. - */ +/** Cake entity. */ @Entity @Getter @Setter public class Cake { - @Id - @GeneratedValue - private Long id; + @Id @GeneratedValue private Long id; @OneToOne(cascade = CascadeType.REMOVE) private CakeTopping topping; diff --git a/layered-architecture/src/main/java/entity/CakeLayer.java b/layered-architecture/src/main/java/entity/CakeLayer.java index ad517317c..798ecbd17 100644 --- a/layered-architecture/src/main/java/entity/CakeLayer.java +++ b/layered-architecture/src/main/java/entity/CakeLayer.java @@ -25,7 +25,6 @@ package entity; - import jakarta.persistence.CascadeType; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; @@ -38,9 +37,7 @@ import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; -/** - * CakeLayer entity. - */ +/** CakeLayer entity. */ @Entity @Getter @Setter @@ -50,9 +47,7 @@ import lombok.Setter; @EqualsAndHashCode public class CakeLayer { - @Id - @GeneratedValue - private Long id; + @Id @GeneratedValue private Long id; private String name; diff --git a/layered-architecture/src/main/java/entity/CakeTopping.java b/layered-architecture/src/main/java/entity/CakeTopping.java index 997dc6ddb..8b1c5f38b 100644 --- a/layered-architecture/src/main/java/entity/CakeTopping.java +++ b/layered-architecture/src/main/java/entity/CakeTopping.java @@ -25,7 +25,6 @@ package entity; - import jakarta.persistence.CascadeType; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; @@ -38,9 +37,7 @@ import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; -/** - * CakeTopping entity. - */ +/** CakeTopping entity. */ @Entity @Getter @Setter @@ -50,9 +47,7 @@ import lombok.Setter; @EqualsAndHashCode public class CakeTopping { - @Id - @GeneratedValue - private Long id; + @Id @GeneratedValue private Long id; private String name; @@ -70,5 +65,4 @@ public class CakeTopping { public String toString() { return String.format("id=%s name=%s calories=%d", id, name, calories); } - } diff --git a/layered-architecture/src/main/java/exception/CakeBakingException.java b/layered-architecture/src/main/java/exception/CakeBakingException.java index 0af1e28cd..13af2b550 100644 --- a/layered-architecture/src/main/java/exception/CakeBakingException.java +++ b/layered-architecture/src/main/java/exception/CakeBakingException.java @@ -28,17 +28,13 @@ package exception; import java.io.Serial; import org.springframework.stereotype.Component; -/** - * Custom exception used in cake baking. - */ +/** Custom exception used in cake baking. */ @Component public class CakeBakingException extends Exception { - @Serial - private static final long serialVersionUID = 1L; + @Serial private static final long serialVersionUID = 1L; - public CakeBakingException() { - } + public CakeBakingException() {} public CakeBakingException(String message) { super(message); diff --git a/layered-architecture/src/main/java/service/CakeBakingService.java b/layered-architecture/src/main/java/service/CakeBakingService.java index 8ab5dd3a8..be34797d6 100644 --- a/layered-architecture/src/main/java/service/CakeBakingService.java +++ b/layered-architecture/src/main/java/service/CakeBakingService.java @@ -32,40 +32,26 @@ import exception.CakeBakingException; import java.util.List; import org.springframework.stereotype.Service; -/** - * Service for cake baking operations. - */ +/** Service for cake baking operations. */ @Service public interface CakeBakingService { - /** - * Bakes new cake according to parameters. - */ + /** Bakes new cake according to parameters. */ void bakeNewCake(CakeInfo cakeInfo) throws CakeBakingException; - /** - * Get all cakes. - */ + /** Get all cakes. */ List getAllCakes(); - /** - * Store new cake topping. - */ + /** Store new cake topping. */ void saveNewTopping(CakeToppingInfo toppingInfo); - /** - * Get available cake toppings. - */ + /** Get available cake toppings. */ List getAvailableToppings(); - /** - * Add new cake layer. - */ + /** Add new cake layer. */ void saveNewLayer(CakeLayerInfo layerInfo); - /** - * Get available cake layers. - */ + /** Get available cake layers. */ List getAvailableLayers(); void deleteAllCakes(); @@ -73,5 +59,4 @@ public interface CakeBakingService { void deleteAllLayers(); void deleteAllToppings(); - } diff --git a/layered-architecture/src/main/java/service/CakeBakingServiceImpl.java b/layered-architecture/src/main/java/service/CakeBakingServiceImpl.java index 2161c3ef7..6af2123d9 100644 --- a/layered-architecture/src/main/java/service/CakeBakingServiceImpl.java +++ b/layered-architecture/src/main/java/service/CakeBakingServiceImpl.java @@ -43,9 +43,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -/** - * Implementation of CakeBakingService. - */ +/** Implementation of CakeBakingService. */ @Service @Transactional public class CakeBakingServiceImpl implements CakeBakingService { @@ -62,8 +60,8 @@ public class CakeBakingServiceImpl implements CakeBakingService { * @param cakeToppingDao the DAO for cake topping-related operations */ @Autowired - public CakeBakingServiceImpl(CakeDao cakeDao, CakeLayerDao cakeLayerDao, - CakeToppingDao cakeToppingDao) { + public CakeBakingServiceImpl( + CakeDao cakeDao, CakeLayerDao cakeLayerDao, CakeToppingDao cakeToppingDao) { this.cakeDao = cakeDao; this.cakeLayerDao = cakeLayerDao; this.cakeToppingDao = cakeToppingDao; @@ -73,7 +71,8 @@ public class CakeBakingServiceImpl implements CakeBakingService { public void bakeNewCake(CakeInfo cakeInfo) throws CakeBakingException { var allToppings = getAvailableToppingEntities(); var matchingToppings = - allToppings.stream().filter(t -> t.getName().equals(cakeInfo.cakeToppingInfo.name)) + allToppings.stream() + .filter(t -> t.getName().equals(cakeInfo.cakeToppingInfo.name)) .toList(); if (matchingToppings.isEmpty()) { throw new CakeBakingException( @@ -184,7 +183,9 @@ public class CakeBakingServiceImpl implements CakeBakingService { List result = new ArrayList<>(); for (Cake cake : cakeDao.findAll()) { var cakeToppingInfo = - new CakeToppingInfo(cake.getTopping().getId(), cake.getTopping().getName(), + new CakeToppingInfo( + cake.getTopping().getId(), + cake.getTopping().getName(), cake.getTopping().getCalories()); List cakeLayerInfos = new ArrayList<>(); for (var layer : cake.getLayers()) { diff --git a/layered-architecture/src/main/java/view/CakeViewImpl.java b/layered-architecture/src/main/java/view/CakeViewImpl.java index edb9ebffe..a01d1c160 100644 --- a/layered-architecture/src/main/java/view/CakeViewImpl.java +++ b/layered-architecture/src/main/java/view/CakeViewImpl.java @@ -29,9 +29,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import service.CakeBakingService; -/** - * View implementation for displaying cakes. - */ +/** View implementation for displaying cakes. */ public class CakeViewImpl implements View { private final CakeBakingService cakeBakingService; diff --git a/layered-architecture/src/main/java/view/View.java b/layered-architecture/src/main/java/view/View.java index f8ff8b535..78403c601 100644 --- a/layered-architecture/src/main/java/view/View.java +++ b/layered-architecture/src/main/java/view/View.java @@ -25,11 +25,8 @@ package view; -/** - * View interface. - */ +/** View interface. */ public interface View { void render(); - } diff --git a/layered-architecture/src/test/java/com/iluwatar/layers/app/LayersAppTests.java b/layered-architecture/src/test/java/com/iluwatar/layers/app/LayersAppTests.java index da361e3f0..e51bca34d 100644 --- a/layered-architecture/src/test/java/com/iluwatar/layers/app/LayersAppTests.java +++ b/layered-architecture/src/test/java/com/iluwatar/layers/app/LayersAppTests.java @@ -45,5 +45,4 @@ class LayersAppTests { void contextLoads() { assertNotNull(applicationContext); } - } diff --git a/layered-architecture/src/test/java/com/iluwatar/layers/entity/CakeTest.java b/layered-architecture/src/test/java/com/iluwatar/layers/entity/CakeTest.java index a59986c6c..eea31e935 100644 --- a/layered-architecture/src/test/java/com/iluwatar/layers/entity/CakeTest.java +++ b/layered-architecture/src/test/java/com/iluwatar/layers/entity/CakeTest.java @@ -38,9 +38,9 @@ import java.util.Set; import org.junit.jupiter.api.Test; /** - * This class contains unit tests for the Cake class. - * It tests the functionality of setting and getting the id, topping, and layers of a Cake object. - * It also tests the functionality of adding a layer to a Cake object and converting a Cake object to a string. + * This class contains unit tests for the Cake class. It tests the functionality of setting and + * getting the id, topping, and layers of a Cake object. It also tests the functionality of adding a + * layer to a Cake object and converting a Cake object to a string. */ class CakeTest { @@ -70,8 +70,11 @@ class CakeTest { assertNotNull(cake.getLayers()); assertTrue(cake.getLayers().isEmpty()); - final var expectedLayers = Set.of(new CakeLayer("layer1", 1000), new CakeLayer("layer2", 2000), - new CakeLayer("layer3", 3000)); + final var expectedLayers = + Set.of( + new CakeLayer("layer1", 1000), + new CakeLayer("layer2", 2000), + new CakeLayer("layer3", 3000)); cake.setLayers(expectedLayers); assertEquals(expectedLayers, cake.getLayers()); } @@ -112,10 +115,9 @@ class CakeTest { cake.setTopping(topping); cake.addLayer(layer); - final var expected = "id=1234 topping=id=2345 name=topping calories=20 " - + "layers=[id=3456 name=layer calories=100]"; + final var expected = + "id=1234 topping=id=2345 name=topping calories=20 " + + "layers=[id=3456 name=layer calories=100]"; assertEquals(expected, cake.toString()); - } - } diff --git a/layered-architecture/src/test/java/com/iluwatar/layers/exception/CakeBakingExceptionTest.java b/layered-architecture/src/test/java/com/iluwatar/layers/exception/CakeBakingExceptionTest.java index 5939abe74..9acb49d2a 100644 --- a/layered-architecture/src/test/java/com/iluwatar/layers/exception/CakeBakingExceptionTest.java +++ b/layered-architecture/src/test/java/com/iluwatar/layers/exception/CakeBakingExceptionTest.java @@ -32,17 +32,15 @@ import exception.CakeBakingException; import org.junit.jupiter.api.Test; /** - * Tests for the {@link CakeBakingException} class. - * This class contains unit tests to verify the correct functionality - * of the {@code CakeBakingException} class constructors, including the default constructor - * and the constructor that accepts a message parameter. + * Tests for the {@link CakeBakingException} class. This class contains unit tests to verify the + * correct functionality of the {@code CakeBakingException} class constructors, including the + * default constructor and the constructor that accepts a message parameter. */ class CakeBakingExceptionTest { /** - * Tests the default constructor of {@link CakeBakingException}. - * Ensures that an exception created with the default constructor has - * {@code null} as its message and cause. + * Tests the default constructor of {@link CakeBakingException}. Ensures that an exception created + * with the default constructor has {@code null} as its message and cause. */ @Test void testConstructor() { @@ -52,18 +50,20 @@ class CakeBakingExceptionTest { } /** - * Tests the constructor of {@link CakeBakingException} that accepts a message. - * Ensures that an exception created with this constructor correctly stores the provided message - * and has {@code null} as its cause. + * Tests the constructor of {@link CakeBakingException} that accepts a message. Ensures that an + * exception created with this constructor correctly stores the provided message and has {@code + * null} as its cause. */ @Test void testConstructorWithMessage() { final var expectedMessage = "message"; final var exception = new CakeBakingException(expectedMessage); - assertEquals(expectedMessage, exception.getMessage(), + assertEquals( + expectedMessage, + exception.getMessage(), "The stored message should match the expected message."); - assertNull(exception.getCause(), + assertNull( + exception.getCause(), "The cause should be null when an exception is created with only a message."); } - } diff --git a/layered-architecture/src/test/java/com/iluwatar/layers/service/CakeBakingServiceImplTest.java b/layered-architecture/src/test/java/com/iluwatar/layers/service/CakeBakingServiceImplTest.java index cd0edb48c..a14c00760 100644 --- a/layered-architecture/src/test/java/com/iluwatar/layers/service/CakeBakingServiceImplTest.java +++ b/layered-architecture/src/test/java/com/iluwatar/layers/service/CakeBakingServiceImplTest.java @@ -44,10 +44,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import service.CakeBakingServiceImpl; -/** - * Constructs a new instance of CakeBakingServiceImplTest. - * - */ +/** Constructs a new instance of CakeBakingServiceImplTest. */ @SpringBootTest(classes = LayersApp.class) class CakeBakingServiceImplTest { @@ -65,7 +62,6 @@ class CakeBakingServiceImplTest { cakeBakingService.deleteAllToppings(); } - @Test void testLayers() { final var initialLayers = cakeBakingService.getAvailableLayers(); @@ -84,7 +80,6 @@ class CakeBakingServiceImplTest { assertNotNull(layer.toString()); assertTrue(layer.calories > 0); } - } @Test @@ -105,7 +100,6 @@ class CakeBakingServiceImplTest { assertNotNull(topping.toString()); assertTrue(topping.calories > 0); } - } @Test @@ -141,7 +135,6 @@ class CakeBakingServiceImplTest { assertFalse(cakeInfo.cakeLayerInfos.isEmpty()); assertTrue(cakeInfo.calculateTotalCalories() > 0); } - } @Test @@ -152,7 +145,8 @@ class CakeBakingServiceImplTest { cakeBakingService.saveNewLayer(layer2); final var missingTopping = new CakeToppingInfo("Topping1", 1000); - assertThrows(CakeBakingException.class, + assertThrows( + CakeBakingException.class, () -> cakeBakingService.bakeNewCake(new CakeInfo(missingTopping, List.of(layer1, layer2)))); } @@ -169,7 +163,8 @@ class CakeBakingServiceImplTest { cakeBakingService.saveNewLayer(layer1); final var missingLayer = new CakeLayerInfo("Layer2", 2000); - assertThrows(CakeBakingException.class, + assertThrows( + CakeBakingException.class, () -> cakeBakingService.bakeNewCake(new CakeInfo(topping1, List.of(layer1, missingLayer)))); } @@ -190,8 +185,10 @@ class CakeBakingServiceImplTest { cakeBakingService.saveNewLayer(layer2); cakeBakingService.bakeNewCake(new CakeInfo(topping1, List.of(layer1, layer2))); - assertThrows(CakeBakingException.class, () -> cakeBakingService.bakeNewCake( - new CakeInfo(topping2, Collections.singletonList(layer2)))); + assertThrows( + CakeBakingException.class, + () -> + cakeBakingService.bakeNewCake( + new CakeInfo(topping2, Collections.singletonList(layer2)))); } - } diff --git a/layered-architecture/src/test/java/com/iluwatar/layers/view/CakeViewImplTest.java b/layered-architecture/src/test/java/com/iluwatar/layers/view/CakeViewImplTest.java index 1d7546a59..2e3b1ae59 100644 --- a/layered-architecture/src/test/java/com/iluwatar/layers/view/CakeViewImplTest.java +++ b/layered-architecture/src/test/java/com/iluwatar/layers/view/CakeViewImplTest.java @@ -45,9 +45,9 @@ import service.CakeBakingService; import view.CakeViewImpl; /** - * This class contains unit tests for the CakeViewImpl class. - * It tests the functionality of rendering cakes using the CakeViewImpl class. - * It also tests the logging functionality of the CakeViewImpl class. + * This class contains unit tests for the CakeViewImpl class. It tests the functionality of + * rendering cakes using the CakeViewImpl class. It also tests the logging functionality of the + * CakeViewImpl class. */ class CakeViewImplTest { @@ -63,14 +63,15 @@ class CakeViewImplTest { appender.stop(); } - /** - * Verify if the cake view renders the expected result. - */ + /** Verify if the cake view renders the expected result. */ @Test void testRender() { - final var layers = List.of(new CakeLayerInfo("layer1", 1000), new CakeLayerInfo("layer2", 2000), - new CakeLayerInfo("layer3", 3000)); + final var layers = + List.of( + new CakeLayerInfo("layer1", 1000), + new CakeLayerInfo("layer2", 2000), + new CakeLayerInfo("layer3", 3000)); final var cake = new CakeInfo(new CakeToppingInfo("topping", 1000), layers); final var cakes = List.of(cake); @@ -84,7 +85,6 @@ class CakeViewImplTest { cakeView.render(); assertEquals(cake.toString(), appender.getLastMessage()); - } private static class InMemoryAppender extends AppenderBase { @@ -109,5 +109,4 @@ class CakeViewImplTest { return log.size(); } } - } diff --git a/lazy-loading/pom.xml b/lazy-loading/pom.xml index 8d777fc76..9b2061c2c 100644 --- a/lazy-loading/pom.xml +++ b/lazy-loading/pom.xml @@ -34,6 +34,14 @@ lazy-loading + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/lazy-loading/src/main/java/com/iluwatar/lazy/loading/Heavy.java b/lazy-loading/src/main/java/com/iluwatar/lazy/loading/Heavy.java index 31f90b68f..0c96768b6 100644 --- a/lazy-loading/src/main/java/com/iluwatar/lazy/loading/Heavy.java +++ b/lazy-loading/src/main/java/com/iluwatar/lazy/loading/Heavy.java @@ -26,15 +26,11 @@ package com.iluwatar.lazy.loading; import lombok.extern.slf4j.Slf4j; -/** - * Heavy objects are expensive to create. - */ +/** Heavy objects are expensive to create. */ @Slf4j public class Heavy { - /** - * Constructor. - */ + /** Constructor. */ public Heavy() { LOGGER.info("Creating Heavy ..."); try { diff --git a/lazy-loading/src/main/java/com/iluwatar/lazy/loading/HolderNaive.java b/lazy-loading/src/main/java/com/iluwatar/lazy/loading/HolderNaive.java index 054ab6bcc..55281a7e6 100644 --- a/lazy-loading/src/main/java/com/iluwatar/lazy/loading/HolderNaive.java +++ b/lazy-loading/src/main/java/com/iluwatar/lazy/loading/HolderNaive.java @@ -26,24 +26,18 @@ package com.iluwatar.lazy.loading; import lombok.extern.slf4j.Slf4j; -/** - * Simple implementation of the lazy loading idiom. However, this is not thread safe. - */ +/** Simple implementation of the lazy loading idiom. However, this is not thread safe. */ @Slf4j public class HolderNaive { private Heavy heavy; - /** - * Constructor. - */ + /** Constructor. */ public HolderNaive() { LOGGER.info("HolderNaive created"); } - /** - * Get heavy object. - */ + /** Get heavy object. */ public Heavy getHeavy() { if (heavy == null) { heavy = new Heavy(); diff --git a/lazy-loading/src/main/java/com/iluwatar/lazy/loading/HolderThreadSafe.java b/lazy-loading/src/main/java/com/iluwatar/lazy/loading/HolderThreadSafe.java index cb0f7a2a8..f698a0579 100644 --- a/lazy-loading/src/main/java/com/iluwatar/lazy/loading/HolderThreadSafe.java +++ b/lazy-loading/src/main/java/com/iluwatar/lazy/loading/HolderThreadSafe.java @@ -35,16 +35,12 @@ public class HolderThreadSafe { private Heavy heavy; - /** - * Constructor. - */ + /** Constructor. */ public HolderThreadSafe() { LOGGER.info("HolderThreadSafe created"); } - /** - * Get heavy object. - */ + /** Get heavy object. */ public synchronized Heavy getHeavy() { if (heavy == null) { heavy = new Heavy(); diff --git a/lazy-loading/src/test/java/com/iluwatar/lazy/loading/AbstractHolderTest.java b/lazy-loading/src/test/java/com/iluwatar/lazy/loading/AbstractHolderTest.java index 5c15a529f..72cdd9e47 100644 --- a/lazy-loading/src/test/java/com/iluwatar/lazy/loading/AbstractHolderTest.java +++ b/lazy-loading/src/test/java/com/iluwatar/lazy/loading/AbstractHolderTest.java @@ -32,10 +32,7 @@ import static org.junit.jupiter.api.Assertions.assertTimeout; import org.junit.jupiter.api.Test; -/** - * AbstractHolderTest - * - */ +/** AbstractHolderTest */ public abstract class AbstractHolderTest { /** @@ -57,12 +54,13 @@ public abstract class AbstractHolderTest { */ @Test void testGetHeavy() { - assertTimeout(ofMillis(3000), () -> { - assertNull(getInternalHeavyValue()); - assertNotNull(getHeavy()); - assertNotNull(getInternalHeavyValue()); - assertSame(getHeavy(), getInternalHeavyValue()); - }); + assertTimeout( + ofMillis(3000), + () -> { + assertNull(getInternalHeavyValue()); + assertNotNull(getHeavy()); + assertNotNull(getInternalHeavyValue()); + assertSame(getHeavy(), getInternalHeavyValue()); + }); } - } diff --git a/lazy-loading/src/test/java/com/iluwatar/lazy/loading/AppTest.java b/lazy-loading/src/test/java/com/iluwatar/lazy/loading/AppTest.java index 3b45c27c0..3f3e5b28a 100644 --- a/lazy-loading/src/test/java/com/iluwatar/lazy/loading/AppTest.java +++ b/lazy-loading/src/test/java/com/iluwatar/lazy/loading/AppTest.java @@ -24,19 +24,15 @@ */ package com.iluwatar.lazy.loading; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -/** - * - * Application test - * - */ +import org.junit.jupiter.api.Test; + +/** Application test */ class AppTest { @Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/lazy-loading/src/test/java/com/iluwatar/lazy/loading/HolderNaiveTest.java b/lazy-loading/src/test/java/com/iluwatar/lazy/loading/HolderNaiveTest.java index 52e79a3a1..e165c4a9b 100644 --- a/lazy-loading/src/test/java/com/iluwatar/lazy/loading/HolderNaiveTest.java +++ b/lazy-loading/src/test/java/com/iluwatar/lazy/loading/HolderNaiveTest.java @@ -24,10 +24,7 @@ */ package com.iluwatar.lazy.loading; -/** - * HolderNaiveTest - * - */ +/** HolderNaiveTest */ class HolderNaiveTest extends AbstractHolderTest { private final HolderNaive holder = new HolderNaive(); @@ -43,5 +40,4 @@ class HolderNaiveTest extends AbstractHolderTest { Heavy getHeavy() { return holder.getHeavy(); } - -} \ No newline at end of file +} diff --git a/lazy-loading/src/test/java/com/iluwatar/lazy/loading/HolderThreadSafeTest.java b/lazy-loading/src/test/java/com/iluwatar/lazy/loading/HolderThreadSafeTest.java index a879c9352..e6c8efb4b 100644 --- a/lazy-loading/src/test/java/com/iluwatar/lazy/loading/HolderThreadSafeTest.java +++ b/lazy-loading/src/test/java/com/iluwatar/lazy/loading/HolderThreadSafeTest.java @@ -24,10 +24,7 @@ */ package com.iluwatar.lazy.loading; -/** - * HolderThreadSafeTest - * - */ +/** HolderThreadSafeTest */ class HolderThreadSafeTest extends AbstractHolderTest { private final HolderThreadSafe holder = new HolderThreadSafe(); @@ -43,5 +40,4 @@ class HolderThreadSafeTest extends AbstractHolderTest { Heavy getHeavy() { return this.holder.getHeavy(); } - -} \ No newline at end of file +} diff --git a/lazy-loading/src/test/java/com/iluwatar/lazy/loading/Java8HolderTest.java b/lazy-loading/src/test/java/com/iluwatar/lazy/loading/Java8HolderTest.java index a702cacca..41c1d4886 100644 --- a/lazy-loading/src/test/java/com/iluwatar/lazy/loading/Java8HolderTest.java +++ b/lazy-loading/src/test/java/com/iluwatar/lazy/loading/Java8HolderTest.java @@ -26,15 +26,11 @@ package com.iluwatar.lazy.loading; import java.util.function.Supplier; -/** - * Java8HolderTest - * - */ +/** Java8HolderTest */ class Java8HolderTest extends AbstractHolderTest { private final Java8Holder holder = new Java8Holder(); - @Override Heavy getInternalHeavyValue() throws Exception { final var holderField = Java8Holder.class.getDeclaredField("heavy"); @@ -58,5 +54,4 @@ class Java8HolderTest extends AbstractHolderTest { Heavy getHeavy() { return holder.getHeavy(); } - -} \ No newline at end of file +} diff --git a/leader-election/pom.xml b/leader-election/pom.xml index 8cef07548..fbe1edbea 100644 --- a/leader-election/pom.xml +++ b/leader-election/pom.xml @@ -34,6 +34,14 @@ leader-election + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/leader-election/src/main/java/com/iluwatar/leaderelection/AbstractInstance.java b/leader-election/src/main/java/com/iluwatar/leaderelection/AbstractInstance.java index 531c9869e..398d0baf3 100644 --- a/leader-election/src/main/java/com/iluwatar/leaderelection/AbstractInstance.java +++ b/leader-election/src/main/java/com/iluwatar/leaderelection/AbstractInstance.java @@ -28,9 +28,7 @@ import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import lombok.extern.slf4j.Slf4j; -/** - * Abstract class of all the instance implementation classes. - */ +/** Abstract class of all the instance implementation classes. */ @Slf4j public abstract class AbstractInstance implements Instance, Runnable { @@ -43,9 +41,7 @@ public abstract class AbstractInstance implements Instance, Runnable { protected int leaderId; protected boolean alive; - /** - * Constructor of BullyInstance. - */ + /** Constructor of BullyInstance. */ public AbstractInstance(MessageManager messageManager, int localId, int leaderId) { this.messageManager = messageManager; this.messageQueue = new ConcurrentLinkedQueue<>(); @@ -54,9 +50,7 @@ public abstract class AbstractInstance implements Instance, Runnable { this.alive = true; } - /** - * The instance will execute the message in its message queue periodically once it is alive. - */ + /** The instance will execute the message in its message queue periodically once it is alive. */ @Override @SuppressWarnings("squid:S2189") public void run() { @@ -129,8 +123,7 @@ public abstract class AbstractInstance implements Instance, Runnable { LOGGER.info(INSTANCE + localId + " - Heartbeat Invoke Message handling..."); handleHeartbeatInvokeMessage(); } - default -> { - } + default -> {} } } @@ -149,5 +142,4 @@ public abstract class AbstractInstance implements Instance, Runnable { protected abstract void handleHeartbeatMessage(Message message); protected abstract void handleHeartbeatInvokeMessage(); - } diff --git a/leader-election/src/main/java/com/iluwatar/leaderelection/AbstractMessageManager.java b/leader-election/src/main/java/com/iluwatar/leaderelection/AbstractMessageManager.java index 934f2f83b..d613182e5 100644 --- a/leader-election/src/main/java/com/iluwatar/leaderelection/AbstractMessageManager.java +++ b/leader-election/src/main/java/com/iluwatar/leaderelection/AbstractMessageManager.java @@ -26,19 +26,13 @@ package com.iluwatar.leaderelection; import java.util.Map; -/** - * Abstract class of all the message manager classes. - */ +/** Abstract class of all the message manager classes. */ public abstract class AbstractMessageManager implements MessageManager { - /** - * Contain all the instances in the system. Key is its ID, and value is the instance itself. - */ + /** Contain all the instances in the system. Key is its ID, and value is the instance itself. */ protected Map instanceMap; - /** - * Constructor of AbstractMessageManager. - */ + /** Constructor of AbstractMessageManager. */ public AbstractMessageManager(Map instanceMap) { this.instanceMap = instanceMap; } @@ -50,18 +44,18 @@ public abstract class AbstractMessageManager implements MessageManager { */ protected Instance findNextInstance(int currentId) { Instance result = null; - var candidateList = instanceMap.keySet() - .stream() - .filter((i) -> i > currentId && instanceMap.get(i).isAlive()) - .sorted() - .toList(); + var candidateList = + instanceMap.keySet().stream() + .filter((i) -> i > currentId && instanceMap.get(i).isAlive()) + .sorted() + .toList(); if (candidateList.isEmpty()) { - var index = instanceMap.keySet() - .stream() - .filter((i) -> instanceMap.get(i).isAlive()) - .sorted() - .toList() - .get(0); + var index = + instanceMap.keySet().stream() + .filter((i) -> instanceMap.get(i).isAlive()) + .sorted() + .toList() + .get(0); result = instanceMap.get(index); } else { var index = candidateList.get(0); @@ -69,5 +63,4 @@ public abstract class AbstractMessageManager implements MessageManager { } return result; } - } diff --git a/leader-election/src/main/java/com/iluwatar/leaderelection/Instance.java b/leader-election/src/main/java/com/iluwatar/leaderelection/Instance.java index 08f76dfea..a2a16f0f6 100644 --- a/leader-election/src/main/java/com/iluwatar/leaderelection/Instance.java +++ b/leader-election/src/main/java/com/iluwatar/leaderelection/Instance.java @@ -24,9 +24,7 @@ */ package com.iluwatar.leaderelection; -/** - * Instance interface. - */ +/** Instance interface. */ public interface Instance { /** @@ -49,5 +47,4 @@ public interface Instance { * @param message Message sent by other instances */ void onMessage(Message message); - } diff --git a/leader-election/src/main/java/com/iluwatar/leaderelection/Message.java b/leader-election/src/main/java/com/iluwatar/leaderelection/Message.java index 6984481a6..af3788e95 100644 --- a/leader-election/src/main/java/com/iluwatar/leaderelection/Message.java +++ b/leader-election/src/main/java/com/iluwatar/leaderelection/Message.java @@ -30,9 +30,7 @@ import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; -/** - * Message used to transport data between instances. - */ +/** Message used to transport data between instances. */ @Setter @Getter @EqualsAndHashCode @@ -42,5 +40,4 @@ public class Message { private MessageType type; private String content; - } diff --git a/leader-election/src/main/java/com/iluwatar/leaderelection/MessageManager.java b/leader-election/src/main/java/com/iluwatar/leaderelection/MessageManager.java index 58006dc00..96a030421 100644 --- a/leader-election/src/main/java/com/iluwatar/leaderelection/MessageManager.java +++ b/leader-election/src/main/java/com/iluwatar/leaderelection/MessageManager.java @@ -24,9 +24,7 @@ */ package com.iluwatar.leaderelection; -/** - * MessageManager interface. - */ +/** MessageManager interface. */ public interface MessageManager { /** @@ -41,7 +39,7 @@ public interface MessageManager { * Send election message to other instances. * * @param currentId Instance ID of which sends this message. - * @param content Election message content. + * @param content Election message content. * @return {@code true} if the message is accepted by the target instances. */ boolean sendElectionMessage(int currentId, String content); @@ -50,7 +48,7 @@ public interface MessageManager { * Send new leader notification message to other instances. * * @param currentId Instance ID of which sends this message. - * @param leaderId Leader message content. + * @param leaderId Leader message content. * @return {@code true} if the message is accepted by the target instances. */ boolean sendLeaderMessage(int currentId, int leaderId); @@ -61,5 +59,4 @@ public interface MessageManager { * @param currentId Instance ID of which sends this message. */ void sendHeartbeatInvokeMessage(int currentId); - } diff --git a/leader-election/src/main/java/com/iluwatar/leaderelection/MessageType.java b/leader-election/src/main/java/com/iluwatar/leaderelection/MessageType.java index 9f3d3ea86..d2d06cc21 100644 --- a/leader-election/src/main/java/com/iluwatar/leaderelection/MessageType.java +++ b/leader-election/src/main/java/com/iluwatar/leaderelection/MessageType.java @@ -24,40 +24,24 @@ */ package com.iluwatar.leaderelection; -/** - * Message Type enum. - */ +/** Message Type enum. */ public enum MessageType { - /** - * Start the election. The content of the message stores ID(s) of the candidate instance(s). - */ + /** Start the election. The content of the message stores ID(s) of the candidate instance(s). */ ELECTION, - /** - * Nodify the new leader. The content of the message should be the leader ID. - */ + /** Nodify the new leader. The content of the message should be the leader ID. */ LEADER, - /** - * Check health of current leader instance. - */ + /** Check health of current leader instance. */ HEARTBEAT, - /** - * Inform target instance to start election. - */ + /** Inform target instance to start election. */ ELECTION_INVOKE, - /** - * Inform target instance to notify all the other instance that it is the new leader. - */ + /** Inform target instance to notify all the other instance that it is the new leader. */ LEADER_INVOKE, - /** - * Inform target instance to start heartbeat. - */ + /** Inform target instance to start heartbeat. */ HEARTBEAT_INVOKE - } - diff --git a/leader-election/src/main/java/com/iluwatar/leaderelection/bully/BullyApp.java b/leader-election/src/main/java/com/iluwatar/leaderelection/bully/BullyApp.java index 51f9ec0a8..700d8ac6e 100644 --- a/leader-election/src/main/java/com/iluwatar/leaderelection/bully/BullyApp.java +++ b/leader-election/src/main/java/com/iluwatar/leaderelection/bully/BullyApp.java @@ -37,9 +37,7 @@ import java.util.Map; */ public class BullyApp { - /** - * Program entry point. - */ + /** Program entry point. */ public static void main(String[] args) { Map instanceMap = new HashMap<>(); diff --git a/leader-election/src/main/java/com/iluwatar/leaderelection/bully/BullyInstance.java b/leader-election/src/main/java/com/iluwatar/leaderelection/bully/BullyInstance.java index 1162ae37d..3ee9629d4 100644 --- a/leader-election/src/main/java/com/iluwatar/leaderelection/bully/BullyInstance.java +++ b/leader-election/src/main/java/com/iluwatar/leaderelection/bully/BullyInstance.java @@ -42,9 +42,7 @@ import lombok.extern.slf4j.Slf4j; public class BullyInstance extends AbstractInstance { private static final String INSTANCE = "Instance "; - /** - * Constructor of BullyInstance. - */ + /** Constructor of BullyInstance. */ public BullyInstance(MessageManager messageManager, int localId, int leaderId) { super(messageManager, localId, leaderId); } @@ -95,9 +93,7 @@ public class BullyInstance extends AbstractInstance { } } - /** - * Process leader message. Update local leader information. - */ + /** Process leader message. Update local leader information. */ @Override protected void handleLeaderMessage(Message message) { leaderId = Integer.parseInt(message.getContent()); diff --git a/leader-election/src/main/java/com/iluwatar/leaderelection/bully/BullyMessageManager.java b/leader-election/src/main/java/com/iluwatar/leaderelection/bully/BullyMessageManager.java index 7a189c87c..e3bd158ed 100644 --- a/leader-election/src/main/java/com/iluwatar/leaderelection/bully/BullyMessageManager.java +++ b/leader-election/src/main/java/com/iluwatar/leaderelection/bully/BullyMessageManager.java @@ -31,14 +31,10 @@ import com.iluwatar.leaderelection.MessageType; import java.util.List; import java.util.Map; -/** - * Implementation of BullyMessageManager. - */ +/** Implementation of BullyMessageManager. */ public class BullyMessageManager extends AbstractMessageManager { - /** - * Constructor of BullyMessageManager. - */ + /** Constructor of BullyMessageManager. */ public BullyMessageManager(Map instanceMap) { super(instanceMap); } @@ -59,7 +55,7 @@ public class BullyMessageManager extends AbstractMessageManager { * Send election message to all the instances with smaller ID. * * @param currentId Instance ID of which sends this message. - * @param content Election message content. + * @param content Election message content. * @return {@code true} if no alive instance has smaller ID, so that the election is accepted. */ @Override @@ -78,14 +74,13 @@ public class BullyMessageManager extends AbstractMessageManager { * Send leader message to all the instances to notify the new leader. * * @param currentId Instance ID of which sends this message. - * @param leaderId Leader message content. + * @param leaderId Leader message content. * @return {@code true} if the message is accepted. */ @Override public boolean sendLeaderMessage(int currentId, int leaderId) { var leaderMessage = new Message(MessageType.LEADER, String.valueOf(leaderId)); - instanceMap.keySet() - .stream() + instanceMap.keySet().stream() .filter((i) -> i != currentId) .forEach((i) -> instanceMap.get(i).onMessage(leaderMessage)); return false; @@ -110,10 +105,8 @@ public class BullyMessageManager extends AbstractMessageManager { * @return ID list of all the candidate instance. */ private List findElectionCandidateInstanceList(int currentId) { - return instanceMap.keySet() - .stream() + return instanceMap.keySet().stream() .filter((i) -> i < currentId && instanceMap.get(i).isAlive()) .toList(); } - } diff --git a/leader-election/src/main/java/com/iluwatar/leaderelection/ring/RingApp.java b/leader-election/src/main/java/com/iluwatar/leaderelection/ring/RingApp.java index feb3b9709..f72e37b01 100644 --- a/leader-election/src/main/java/com/iluwatar/leaderelection/ring/RingApp.java +++ b/leader-election/src/main/java/com/iluwatar/leaderelection/ring/RingApp.java @@ -37,9 +37,7 @@ import java.util.Map; */ public class RingApp { - /** - * Program entry point. - */ + /** Program entry point. */ public static void main(String[] args) { Map instanceMap = new HashMap<>(); diff --git a/leader-election/src/main/java/com/iluwatar/leaderelection/ring/RingInstance.java b/leader-election/src/main/java/com/iluwatar/leaderelection/ring/RingInstance.java index e19a882ef..d4a8f0d38 100644 --- a/leader-election/src/main/java/com/iluwatar/leaderelection/ring/RingInstance.java +++ b/leader-election/src/main/java/com/iluwatar/leaderelection/ring/RingInstance.java @@ -45,9 +45,7 @@ import lombok.extern.slf4j.Slf4j; public class RingInstance extends AbstractInstance { private static final String INSTANCE = "Instance "; - /** - * Constructor of RingInstance. - */ + /** Constructor of RingInstance. */ public RingInstance(MessageManager messageManager, int localId, int leaderId) { super(messageManager, localId, leaderId); } @@ -76,18 +74,16 @@ public class RingInstance extends AbstractInstance { /** * Process election message. If the local ID is contained in the ID list, the instance will select - * the alive instance with the smallest ID to be the new leader, and send the leader inform message. - * If not, it will add its local ID to the list and send the message to the next instance in the - * ring. + * the alive instance with the smallest ID to be the new leader, and send the leader inform + * message. If not, it will add its local ID to the list and send the message to the next instance + * in the ring. */ @Override protected void handleElectionMessage(Message message) { var content = message.getContent(); LOGGER.info(INSTANCE + localId + " - Election Message: " + content); - var candidateList = Arrays.stream(content.trim().split(",")) - .map(Integer::valueOf) - .sorted() - .toList(); + var candidateList = + Arrays.stream(content.trim().split(",")).map(Integer::valueOf).sorted().toList(); if (candidateList.contains(localId)) { var newLeaderId = candidateList.get(0); LOGGER.info(INSTANCE + localId + " - New leader should be " + newLeaderId + "."); @@ -115,9 +111,7 @@ public class RingInstance extends AbstractInstance { } } - /** - * Not used in Ring instance. - */ + /** Not used in Ring instance. */ @Override protected void handleLeaderInvokeMessage() { // Not used in Ring instance. @@ -132,5 +126,4 @@ public class RingInstance extends AbstractInstance { protected void handleElectionInvokeMessage() { // Not used in Ring instance. } - } diff --git a/leader-election/src/main/java/com/iluwatar/leaderelection/ring/RingMessageManager.java b/leader-election/src/main/java/com/iluwatar/leaderelection/ring/RingMessageManager.java index 98a1b571d..7a055cf10 100644 --- a/leader-election/src/main/java/com/iluwatar/leaderelection/ring/RingMessageManager.java +++ b/leader-election/src/main/java/com/iluwatar/leaderelection/ring/RingMessageManager.java @@ -30,14 +30,10 @@ import com.iluwatar.leaderelection.Message; import com.iluwatar.leaderelection.MessageType; import java.util.Map; -/** - * Implementation of RingMessageManager. - */ +/** Implementation of RingMessageManager. */ public class RingMessageManager extends AbstractMessageManager { - /** - * Constructor of RingMessageManager. - */ + /** Constructor of RingMessageManager. */ public RingMessageManager(Map instanceMap) { super(instanceMap); } @@ -58,8 +54,8 @@ public class RingMessageManager extends AbstractMessageManager { * Send election message to the next instance. * * @param currentId currentID - * @param content list contains all the IDs of instances which have received this election - * message. + * @param content list contains all the IDs of instances which have received this election + * message. * @return {@code true} if the election message is accepted by the target instance. */ @Override @@ -74,7 +70,7 @@ public class RingMessageManager extends AbstractMessageManager { * Send leader message to the next instance. * * @param currentId Instance ID of which sends this message. - * @param leaderId Leader message content. + * @param leaderId Leader message content. * @return {@code true} if the leader message is accepted by the target instance. */ @Override @@ -96,5 +92,4 @@ public class RingMessageManager extends AbstractMessageManager { var heartbeatInvokeMessage = new Message(MessageType.HEARTBEAT_INVOKE, ""); nextInstance.onMessage(heartbeatInvokeMessage); } - } diff --git a/leader-election/src/test/java/com/iluwatar/leaderelection/MessageTest.java b/leader-election/src/test/java/com/iluwatar/leaderelection/MessageTest.java index d54dcabd7..f8a4d1869 100644 --- a/leader-election/src/test/java/com/iluwatar/leaderelection/MessageTest.java +++ b/leader-election/src/test/java/com/iluwatar/leaderelection/MessageTest.java @@ -28,9 +28,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; -/** - * Message test case. - */ +/** Message test case. */ class MessageTest { @Test @@ -45,5 +43,4 @@ class MessageTest { var message = new Message(MessageType.HEARTBEAT, content); assertEquals(content, message.getContent()); } - } diff --git a/leader-election/src/test/java/com/iluwatar/leaderelection/bully/BullyAppTest.java b/leader-election/src/test/java/com/iluwatar/leaderelection/bully/BullyAppTest.java index b4da68fee..32ba40c38 100644 --- a/leader-election/src/test/java/com/iluwatar/leaderelection/bully/BullyAppTest.java +++ b/leader-election/src/test/java/com/iluwatar/leaderelection/bully/BullyAppTest.java @@ -24,18 +24,15 @@ */ package com.iluwatar.leaderelection.bully; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -/** - * BullyApp unit test. - */ +import org.junit.jupiter.api.Test; + +/** BullyApp unit test. */ class BullyAppTest { @Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> BullyApp.main(new String[]{})); + assertDoesNotThrow(() -> BullyApp.main(new String[] {})); } - } diff --git a/leader-election/src/test/java/com/iluwatar/leaderelection/bully/BullyMessageManagerTest.java b/leader-election/src/test/java/com/iluwatar/leaderelection/bully/BullyMessageManagerTest.java index 8c3cfbf72..f1453202a 100644 --- a/leader-election/src/test/java/com/iluwatar/leaderelection/bully/BullyMessageManagerTest.java +++ b/leader-election/src/test/java/com/iluwatar/leaderelection/bully/BullyMessageManagerTest.java @@ -37,9 +37,7 @@ import java.util.Map; import java.util.Queue; import org.junit.jupiter.api.Test; -/** - * BullyMessageManager unit test. - */ +/** BullyMessageManager unit test. */ class BullyMessageManagerTest { @Test @@ -57,7 +55,8 @@ class BullyMessageManagerTest { var instance2 = new BullyInstance(null, 1, 2); var instance3 = new BullyInstance(null, 1, 3); var instance4 = new BullyInstance(null, 1, 4); - Map instanceMap = Map.of(1, instance1, 2, instance2, 3, instance3, 4, instance4); + Map instanceMap = + Map.of(1, instance1, 2, instance2, 3, instance3, 4, instance4); instance1.setAlive(false); var messageManager = new BullyMessageManager(instanceMap); var result = messageManager.sendElectionMessage(3, "3"); @@ -81,7 +80,8 @@ class BullyMessageManagerTest { var instance2 = new BullyInstance(null, 1, 2); var instance3 = new BullyInstance(null, 1, 3); var instance4 = new BullyInstance(null, 1, 4); - Map instanceMap = Map.of(1, instance1, 2, instance2, 3, instance3, 4, instance4); + Map instanceMap = + Map.of(1, instance1, 2, instance2, 3, instance3, 4, instance4); instance1.setAlive(false); var messageManager = new BullyMessageManager(instanceMap); var result = messageManager.sendElectionMessage(2, "2"); @@ -95,7 +95,8 @@ class BullyMessageManagerTest { var instance2 = new BullyInstance(null, 1, 2); var instance3 = new BullyInstance(null, 1, 3); var instance4 = new BullyInstance(null, 1, 4); - Map instanceMap = Map.of(1, instance1, 2, instance2, 3, instance3, 4, instance4); + Map instanceMap = + Map.of(1, instance1, 2, instance2, 3, instance3, 4, instance4); instance1.setAlive(false); var messageManager = new BullyMessageManager(instanceMap); messageManager.sendLeaderMessage(2, 2); @@ -132,6 +133,4 @@ class BullyMessageManagerTest { fail("Error to access private field."); } } - - } diff --git a/leader-election/src/test/java/com/iluwatar/leaderelection/bully/BullyinstanceTest.java b/leader-election/src/test/java/com/iluwatar/leaderelection/bully/BullyinstanceTest.java index e036b05a5..31dbad14b 100644 --- a/leader-election/src/test/java/com/iluwatar/leaderelection/bully/BullyinstanceTest.java +++ b/leader-election/src/test/java/com/iluwatar/leaderelection/bully/BullyinstanceTest.java @@ -34,9 +34,7 @@ import com.iluwatar.leaderelection.MessageType; import java.util.Queue; import org.junit.jupiter.api.Test; -/** - * BullyInstance unit test. - */ +/** BullyInstance unit test. */ class BullyinstanceTest { @Test @@ -52,7 +50,6 @@ class BullyinstanceTest { } catch (IllegalAccessException | NoSuchFieldException e) { fail("fail to access messasge queue."); } - } @Test @@ -75,5 +72,4 @@ class BullyinstanceTest { bullyInstance.setAlive(false); assertFalse(bullyInstance.isAlive()); } - } diff --git a/leader-election/src/test/java/com/iluwatar/leaderelection/ring/RingAppTest.java b/leader-election/src/test/java/com/iluwatar/leaderelection/ring/RingAppTest.java index 207b6ff24..839e481f4 100644 --- a/leader-election/src/test/java/com/iluwatar/leaderelection/ring/RingAppTest.java +++ b/leader-election/src/test/java/com/iluwatar/leaderelection/ring/RingAppTest.java @@ -24,18 +24,15 @@ */ package com.iluwatar.leaderelection.ring; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -/** - * RingApp unit test. - */ +import org.junit.jupiter.api.Test; + +/** RingApp unit test. */ class RingAppTest { @Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> RingApp.main(new String[]{})); + assertDoesNotThrow(() -> RingApp.main(new String[] {})); } - } diff --git a/leader-election/src/test/java/com/iluwatar/leaderelection/ring/RingInstanceTest.java b/leader-election/src/test/java/com/iluwatar/leaderelection/ring/RingInstanceTest.java index 2c0634d71..140432e54 100644 --- a/leader-election/src/test/java/com/iluwatar/leaderelection/ring/RingInstanceTest.java +++ b/leader-election/src/test/java/com/iluwatar/leaderelection/ring/RingInstanceTest.java @@ -34,9 +34,7 @@ import com.iluwatar.leaderelection.MessageType; import java.util.Queue; import org.junit.jupiter.api.Test; -/** - * RingInstance unit test. - */ +/** RingInstance unit test. */ class RingInstanceTest { @Test diff --git a/leader-election/src/test/java/com/iluwatar/leaderelection/ring/RingMessageManagerTest.java b/leader-election/src/test/java/com/iluwatar/leaderelection/ring/RingMessageManagerTest.java index 4dc842658..ed13e4fb4 100644 --- a/leader-election/src/test/java/com/iluwatar/leaderelection/ring/RingMessageManagerTest.java +++ b/leader-election/src/test/java/com/iluwatar/leaderelection/ring/RingMessageManagerTest.java @@ -36,9 +36,7 @@ import java.util.Map; import java.util.Queue; import org.junit.jupiter.api.Test; -/** - * RingMessageManager unit test. - */ +/** RingMessageManager unit test. */ class RingMessageManagerTest { @Test @@ -112,5 +110,4 @@ class RingMessageManagerTest { fail("Error to access private field."); } } - } diff --git a/leader-followers/pom.xml b/leader-followers/pom.xml index d77cd8035..12152cd3f 100644 --- a/leader-followers/pom.xml +++ b/leader-followers/pom.xml @@ -34,10 +34,37 @@ leader-followers + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.leaderfollowers.App + + + + + + + + diff --git a/leader-followers/src/main/java/com/iluwatar/leaderfollowers/App.java b/leader-followers/src/main/java/com/iluwatar/leaderfollowers/App.java index ffd17bf24..826a7bbb1 100644 --- a/leader-followers/src/main/java/com/iluwatar/leaderfollowers/App.java +++ b/leader-followers/src/main/java/com/iluwatar/leaderfollowers/App.java @@ -39,27 +39,23 @@ import java.util.concurrent.TimeUnit; * work. {@link TaskSet} basically acts as the source of input events for the {@link Worker}, who * are spawned and controlled by the {@link WorkCenter} . When {@link Task} arrives then the leader * takes the work and calls the {@link TaskHandler}. It also calls the {@link WorkCenter} to - * promotes one of the followers to be the new leader, who can then process the next work and so - * on. + * promotes one of the followers to be the new leader, who can then process the next work and so on. * - *

The pros for this pattern are: - * It enhances CPU cache affinity and eliminates unbound allocation and data buffer sharing between - * threads by reading the request into buffer space allocated on the stack of the leader or by using - * the Thread-Specific Storage pattern [22] to allocate memory. It minimizes locking overhead by not - * exchanging data between threads, thereby reducing thread synchronization. In bound handle/thread - * associations, the leader thread dispatches the event based on the I/O handle. It can minimize - * priority inversion because no extra queuing is introduced in the server. It does not require a - * context switch to handle each event, reducing the event dispatching latency. Note that promoting - * a follower thread to fulfill the leader role requires a context switch. Programming simplicity: - * The Leader/Followers pattern simplifies the programming of concurrency models where multiple - * threads can receive requests, process responses, and de-multiplex connections using a shared - * handle set. + *

The pros for this pattern are: It enhances CPU cache affinity and eliminates unbound + * allocation and data buffer sharing between threads by reading the request into buffer space + * allocated on the stack of the leader or by using the Thread-Specific Storage pattern [22] to + * allocate memory. It minimizes locking overhead by not exchanging data between threads, thereby + * reducing thread synchronization. In bound handle/thread associations, the leader thread + * dispatches the event based on the I/O handle. It can minimize priority inversion because no extra + * queuing is introduced in the server. It does not require a context switch to handle each event, + * reducing the event dispatching latency. Note that promoting a follower thread to fulfill the + * leader role requires a context switch. Programming simplicity: The Leader/Followers pattern + * simplifies the programming of concurrency models where multiple threads can receive requests, + * process responses, and de-multiplex connections using a shared handle set. */ public class App { - /** - * The main method for the leader followers pattern. - */ + /** The main method for the leader followers pattern. */ public static void main(String[] args) throws InterruptedException { var taskSet = new TaskSet(); var taskHandler = new TaskHandler(); @@ -68,9 +64,7 @@ public class App { execute(workCenter, taskSet); } - /** - * Start the work, dispatch tasks and stop the thread pool at last. - */ + /** Start the work, dispatch tasks and stop the thread pool at last. */ private static void execute(WorkCenter workCenter, TaskSet taskSet) throws InterruptedException { var workers = workCenter.getWorkers(); var exec = Executors.newFixedThreadPool(workers.size()); @@ -81,9 +75,7 @@ public class App { exec.shutdownNow(); } - /** - * Add tasks. - */ + /** Add tasks. */ private static void addTasks(TaskSet taskSet) throws InterruptedException { var rand = new SecureRandom(); for (var i = 0; i < 5; i++) { diff --git a/leader-followers/src/main/java/com/iluwatar/leaderfollowers/Task.java b/leader-followers/src/main/java/com/iluwatar/leaderfollowers/Task.java index e5a405f43..29374b931 100644 --- a/leader-followers/src/main/java/com/iluwatar/leaderfollowers/Task.java +++ b/leader-followers/src/main/java/com/iluwatar/leaderfollowers/Task.java @@ -27,17 +27,12 @@ package com.iluwatar.leaderfollowers; import lombok.Getter; import lombok.Setter; -/** - * A unit of work to be processed by the Workers. - */ +/** A unit of work to be processed by the Workers. */ public class Task { - @Getter - private final int time; + @Getter private final int time; - @Getter - @Setter - private boolean finished; + @Getter @Setter private boolean finished; public Task(int time) { this.time = time; diff --git a/leader-followers/src/main/java/com/iluwatar/leaderfollowers/TaskHandler.java b/leader-followers/src/main/java/com/iluwatar/leaderfollowers/TaskHandler.java index 60c102b65..8689ce442 100644 --- a/leader-followers/src/main/java/com/iluwatar/leaderfollowers/TaskHandler.java +++ b/leader-followers/src/main/java/com/iluwatar/leaderfollowers/TaskHandler.java @@ -26,15 +26,11 @@ package com.iluwatar.leaderfollowers; import lombok.extern.slf4j.Slf4j; -/** - * The TaskHandler is used by the {@link Worker} to process the newly arrived task. - */ +/** The TaskHandler is used by the {@link Worker} to process the newly arrived task. */ @Slf4j public class TaskHandler { - /** - * This interface handles one task at a time. - */ + /** This interface handles one task at a time. */ public void handleTask(Task task) throws InterruptedException { var time = task.getTime(); Thread.sleep(time); diff --git a/leader-followers/src/main/java/com/iluwatar/leaderfollowers/TaskSet.java b/leader-followers/src/main/java/com/iluwatar/leaderfollowers/TaskSet.java index 0c0ce4f30..c54037024 100644 --- a/leader-followers/src/main/java/com/iluwatar/leaderfollowers/TaskSet.java +++ b/leader-followers/src/main/java/com/iluwatar/leaderfollowers/TaskSet.java @@ -27,9 +27,7 @@ package com.iluwatar.leaderfollowers; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; -/** - * A TaskSet is a collection of the tasks, the leader receives task from here. - */ +/** A TaskSet is a collection of the tasks, the leader receives task from here. */ public class TaskSet { private final BlockingQueue queue = new ArrayBlockingQueue<>(100); diff --git a/leader-followers/src/main/java/com/iluwatar/leaderfollowers/WorkCenter.java b/leader-followers/src/main/java/com/iluwatar/leaderfollowers/WorkCenter.java index bc5796e30..c2fd32f3a 100644 --- a/leader-followers/src/main/java/com/iluwatar/leaderfollowers/WorkCenter.java +++ b/leader-followers/src/main/java/com/iluwatar/leaderfollowers/WorkCenter.java @@ -35,13 +35,10 @@ import lombok.Getter; */ public class WorkCenter { - @Getter - private Worker leader; + @Getter private Worker leader; private final List workers = new CopyOnWriteArrayList<>(); - /** - * Create workers and set leader. - */ + /** Create workers and set leader. */ public void createWorkers(int numberOfWorkers, TaskSet taskSet, TaskHandler taskHandler) { for (var id = 1; id <= numberOfWorkers; id++) { var worker = new Worker(id, this, taskSet, taskHandler); @@ -58,9 +55,7 @@ public class WorkCenter { workers.remove(worker); } - /** - * Promote a leader. - */ + /** Promote a leader. */ public void promoteLeader() { Worker leader = null; if (!workers.isEmpty()) { diff --git a/leader-followers/src/main/java/com/iluwatar/leaderfollowers/Worker.java b/leader-followers/src/main/java/com/iluwatar/leaderfollowers/Worker.java index 5ad463a4a..b079bc616 100644 --- a/leader-followers/src/main/java/com/iluwatar/leaderfollowers/Worker.java +++ b/leader-followers/src/main/java/com/iluwatar/leaderfollowers/Worker.java @@ -27,22 +27,17 @@ package com.iluwatar.leaderfollowers; import lombok.EqualsAndHashCode; import lombok.extern.slf4j.Slf4j; -/** - * Worker class that takes work from work center. - */ +/** Worker class that takes work from work center. */ @EqualsAndHashCode(onlyExplicitlyIncluded = true) @Slf4j public class Worker implements Runnable { - @EqualsAndHashCode.Include - private final long id; + @EqualsAndHashCode.Include private final long id; private final WorkCenter workCenter; private final TaskSet taskSet; private final TaskHandler taskHandler; - /** - * Constructor to create a worker which will take work from the work center. - */ + /** Constructor to create a worker which will take work from the work center. */ public Worker(long id, WorkCenter workCenter, TaskSet taskSet, TaskHandler taskHandler) { super(); this.id = id; @@ -83,5 +78,4 @@ public class Worker implements Runnable { } } } - } diff --git a/leader-followers/src/test/java/com/iluwatar/leaderfollowers/AppTest.java b/leader-followers/src/test/java/com/iluwatar/leaderfollowers/AppTest.java index acd39e735..dd8779141 100644 --- a/leader-followers/src/test/java/com/iluwatar/leaderfollowers/AppTest.java +++ b/leader-followers/src/test/java/com/iluwatar/leaderfollowers/AppTest.java @@ -28,14 +28,11 @@ import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import org.junit.jupiter.api.Test; -/** - * Application test - */ +/** Application test */ class AppTest { @Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } - } diff --git a/leader-followers/src/test/java/com/iluwatar/leaderfollowers/TaskHandlerTest.java b/leader-followers/src/test/java/com/iluwatar/leaderfollowers/TaskHandlerTest.java index 2d92e2e6b..a52aa9f79 100644 --- a/leader-followers/src/test/java/com/iluwatar/leaderfollowers/TaskHandlerTest.java +++ b/leader-followers/src/test/java/com/iluwatar/leaderfollowers/TaskHandlerTest.java @@ -28,9 +28,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; -/** - * Tests for TaskHandler - */ +/** Tests for TaskHandler */ class TaskHandlerTest { @Test @@ -40,5 +38,4 @@ class TaskHandlerTest { taskHandler.handleTask(handle); assertTrue(handle.isFinished()); } - } diff --git a/leader-followers/src/test/java/com/iluwatar/leaderfollowers/TaskSetTest.java b/leader-followers/src/test/java/com/iluwatar/leaderfollowers/TaskSetTest.java index 63559a938..8b55ba418 100644 --- a/leader-followers/src/test/java/com/iluwatar/leaderfollowers/TaskSetTest.java +++ b/leader-followers/src/test/java/com/iluwatar/leaderfollowers/TaskSetTest.java @@ -28,9 +28,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; -/** - * Tests for TaskSet - */ +/** Tests for TaskSet */ class TaskSetTest { @Test @@ -48,5 +46,4 @@ class TaskSetTest { assertEquals(100, task.getTime()); assertEquals(0, taskSet.getSize()); } - } diff --git a/leader-followers/src/test/java/com/iluwatar/leaderfollowers/WorkCenterTest.java b/leader-followers/src/test/java/com/iluwatar/leaderfollowers/WorkCenterTest.java index f37d7526e..425edc576 100644 --- a/leader-followers/src/test/java/com/iluwatar/leaderfollowers/WorkCenterTest.java +++ b/leader-followers/src/test/java/com/iluwatar/leaderfollowers/WorkCenterTest.java @@ -29,9 +29,7 @@ import static org.junit.jupiter.api.Assertions.assertNull; import org.junit.jupiter.api.Test; -/** - * Tests for WorkCenter - */ +/** Tests for WorkCenter */ class WorkCenterTest { @Test diff --git a/lockable-object/pom.xml b/lockable-object/pom.xml index 432cd5b1b..a96ec972e 100644 --- a/lockable-object/pom.xml +++ b/lockable-object/pom.xml @@ -34,6 +34,14 @@ lockable-object + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/lockable-object/src/main/java/com/iluwatar/lockableobject/App.java b/lockable-object/src/main/java/com/iluwatar/lockableobject/App.java index 2199e2d8d..1c05f7d33 100644 --- a/lockable-object/src/main/java/com/iluwatar/lockableobject/App.java +++ b/lockable-object/src/main/java/com/iluwatar/lockableobject/App.java @@ -43,11 +43,10 @@ import lombok.extern.slf4j.Slf4j; * *

In this example, we create a new Lockable object with the SwordOfAragorn implementation of it. * Afterward we create 6 Creatures with the Elf, Orc and Human implementations and assign them each - * to a Fiend object and the Sword is the target object. Because there is only one Sword, and it uses - * the Lockable Object pattern, only one creature can hold the sword at a given time. When the sword - * is locked, any other alive Fiends will try to lock, which will result in a race to lock the + * to a Fiend object and the Sword is the target object. Because there is only one Sword, and it + * uses the Lockable Object pattern, only one creature can hold the sword at a given time. When the + * sword is locked, any other alive Fiends will try to lock, which will result in a race to lock the * sword. - * */ @Slf4j public class App implements Runnable { diff --git a/lockable-object/src/main/java/com/iluwatar/lockableobject/LockingException.java b/lockable-object/src/main/java/com/iluwatar/lockableobject/LockingException.java index 8d9038f53..dd1d2b8f7 100644 --- a/lockable-object/src/main/java/com/iluwatar/lockableobject/LockingException.java +++ b/lockable-object/src/main/java/com/iluwatar/lockableobject/LockingException.java @@ -26,16 +26,12 @@ package com.iluwatar.lockableobject; import java.io.Serial; -/** - * An exception regarding the locking process of a Lockable object. - */ +/** An exception regarding the locking process of a Lockable object. */ public class LockingException extends RuntimeException { - @Serial - private static final long serialVersionUID = 8556381044865867037L; + @Serial private static final long serialVersionUID = 8556381044865867037L; public LockingException(String message) { super(message); } - } diff --git a/lockable-object/src/main/java/com/iluwatar/lockableobject/SwordOfAragorn.java b/lockable-object/src/main/java/com/iluwatar/lockableobject/SwordOfAragorn.java index 85a5d7df5..8e05ea6e6 100644 --- a/lockable-object/src/main/java/com/iluwatar/lockableobject/SwordOfAragorn.java +++ b/lockable-object/src/main/java/com/iluwatar/lockableobject/SwordOfAragorn.java @@ -29,8 +29,8 @@ import lombok.NonNull; import lombok.extern.slf4j.Slf4j; /** - * An implementation of a Lockable object. This is the Sword of Aragorn and every creature wants - * to possess it! + * An implementation of a Lockable object. This is the Sword of Aragorn and every creature wants to + * possess it! */ @Slf4j public class SwordOfAragorn implements Lockable { diff --git a/lockable-object/src/main/java/com/iluwatar/lockableobject/domain/Creature.java b/lockable-object/src/main/java/com/iluwatar/lockableobject/domain/Creature.java index 4380e7755..05b6db001 100644 --- a/lockable-object/src/main/java/com/iluwatar/lockableobject/domain/Creature.java +++ b/lockable-object/src/main/java/com/iluwatar/lockableobject/domain/Creature.java @@ -109,5 +109,4 @@ public abstract class Creature { public synchronized boolean isAlive() { return getHealth() > 0; } - } diff --git a/lockable-object/src/main/java/com/iluwatar/lockableobject/domain/CreatureStats.java b/lockable-object/src/main/java/com/iluwatar/lockableobject/domain/CreatureStats.java index 1d2a4040f..7996a0269 100644 --- a/lockable-object/src/main/java/com/iluwatar/lockableobject/domain/CreatureStats.java +++ b/lockable-object/src/main/java/com/iluwatar/lockableobject/domain/CreatureStats.java @@ -35,8 +35,7 @@ public enum CreatureStats { HUMAN_HEALTH(60), HUMAN_DAMAGE(60); - @Getter - final int value; + @Getter final int value; CreatureStats(int value) { this.value = value; diff --git a/lockable-object/src/test/java/com/iluwatar/lockableobject/CreatureTest.java b/lockable-object/src/test/java/com/iluwatar/lockableobject/CreatureTest.java index f2fec0531..de7fc3678 100644 --- a/lockable-object/src/test/java/com/iluwatar/lockableobject/CreatureTest.java +++ b/lockable-object/src/test/java/com/iluwatar/lockableobject/CreatureTest.java @@ -97,7 +97,7 @@ class CreatureTest { } @Test - void invalidDamageTest(){ + void invalidDamageTest() { Assertions.assertThrows(IllegalArgumentException.class, () -> elf.hit(-50)); } } diff --git a/lockable-object/src/test/java/com/iluwatar/lockableobject/ExceptionsTest.java b/lockable-object/src/test/java/com/iluwatar/lockableobject/ExceptionsTest.java index 614ed9655..26a97853e 100644 --- a/lockable-object/src/test/java/com/iluwatar/lockableobject/ExceptionsTest.java +++ b/lockable-object/src/test/java/com/iluwatar/lockableobject/ExceptionsTest.java @@ -32,12 +32,11 @@ class ExceptionsTest { private static final String MSG = "test"; @Test - void testException(){ + void testException() { Exception e; - try{ + try { throw new LockingException(MSG); - } - catch(LockingException ex){ + } catch (LockingException ex) { e = ex; } Assertions.assertEquals(MSG, e.getMessage()); diff --git a/lockable-object/src/test/java/com/iluwatar/lockableobject/FeindTest.java b/lockable-object/src/test/java/com/iluwatar/lockableobject/FeindTest.java index 70b864a1c..cedaf65b0 100644 --- a/lockable-object/src/test/java/com/iluwatar/lockableobject/FeindTest.java +++ b/lockable-object/src/test/java/com/iluwatar/lockableobject/FeindTest.java @@ -39,14 +39,14 @@ class FeindTest { private Lockable sword; @BeforeEach - void init(){ + void init() { elf = new Elf("Nagdil"); orc = new Orc("Ghandar"); sword = new SwordOfAragorn(); } @Test - void nullTests(){ + void nullTests() { Assertions.assertThrows(NullPointerException.class, () -> new Feind(null, null)); Assertions.assertThrows(NullPointerException.class, () -> new Feind(elf, null)); Assertions.assertThrows(NullPointerException.class, () -> new Feind(null, sword)); @@ -67,5 +67,4 @@ class FeindTest { sword.unlock(elf.isAlive() ? elf : orc); Assertions.assertNull(sword.getLocker()); } - } diff --git a/lockable-object/src/test/java/com/iluwatar/lockableobject/SubCreaturesTests.java b/lockable-object/src/test/java/com/iluwatar/lockableobject/SubCreaturesTests.java index 766069b89..b6db85685 100644 --- a/lockable-object/src/test/java/com/iluwatar/lockableobject/SubCreaturesTests.java +++ b/lockable-object/src/test/java/com/iluwatar/lockableobject/SubCreaturesTests.java @@ -34,7 +34,7 @@ import org.junit.jupiter.api.Test; class SubCreaturesTests { @Test - void statsTest(){ + void statsTest() { var elf = new Elf("Limbar"); var orc = new Orc("Dargal"); var human = new Human("Jerry"); diff --git a/lockable-object/src/test/java/com/iluwatar/lockableobject/TheSwordOfAragornTest.java b/lockable-object/src/test/java/com/iluwatar/lockableobject/TheSwordOfAragornTest.java index e4b604e70..4c40f806b 100644 --- a/lockable-object/src/test/java/com/iluwatar/lockableobject/TheSwordOfAragornTest.java +++ b/lockable-object/src/test/java/com/iluwatar/lockableobject/TheSwordOfAragornTest.java @@ -43,7 +43,7 @@ class TheSwordOfAragornTest { } @Test - void invalidLockerTest(){ + void invalidLockerTest() { var sword = new SwordOfAragorn(); Assertions.assertThrows(NullPointerException.class, () -> sword.lock(null)); Assertions.assertThrows(NullPointerException.class, () -> sword.unlock(null)); diff --git a/map-reduce/src/main/java/com/iluwatar/Main.java b/map-reduce/src/main/java/com/iluwatar/Main.java index cdbc809ae..98e638123 100644 --- a/map-reduce/src/main/java/com/iluwatar/Main.java +++ b/map-reduce/src/main/java/com/iluwatar/Main.java @@ -30,26 +30,24 @@ import java.util.Map; import java.util.logging.Logger; /** - * The Main class serves as the entry point for executing the MapReduce program. - * It processes a list of text inputs, applies the MapReduce pattern, and prints the results. + * The Main class serves as the entry point for executing the MapReduce program. It processes a list + * of text inputs, applies the MapReduce pattern, and prints the results. */ public class Main { private static final Logger logger = Logger.getLogger(Main.class.getName()); + /** * The main method initiates the MapReduce process and displays the word count results. * * @param args Command-line arguments (not used). */ public static void main(String[] args) { - List inputs = Arrays.asList( - "Hello world hello", - "MapReduce is fun", - "Hello from the other side", - "Hello world" - ); + List inputs = + Arrays.asList( + "Hello world hello", "MapReduce is fun", "Hello from the other side", "Hello world"); List> result = MapReduce.mapReduce(inputs); for (Map.Entry entry : result) { logger.info(entry.getKey() + ": " + entry.getValue()); } } -} \ No newline at end of file +} diff --git a/map-reduce/src/main/java/com/iluwatar/MapReduce.java b/map-reduce/src/main/java/com/iluwatar/MapReduce.java index 86964d5db..49b6f0a1d 100644 --- a/map-reduce/src/main/java/com/iluwatar/MapReduce.java +++ b/map-reduce/src/main/java/com/iluwatar/MapReduce.java @@ -29,13 +29,15 @@ import java.util.List; import java.util.Map; /** - * The MapReduce class orchestrates the MapReduce process, - * calling the Mapper, Shuffler, and Reducer components. + * The MapReduce class orchestrates the MapReduce process, calling the Mapper, Shuffler, and Reducer + * components. */ public class MapReduce { private MapReduce() { - throw new UnsupportedOperationException("MapReduce is a utility class and cannot be instantiated."); + throw new UnsupportedOperationException( + "MapReduce is a utility class and cannot be instantiated."); } + /** * Executes the MapReduce process on the given list of input strings. * diff --git a/map-reduce/src/main/java/com/iluwatar/Mapper.java b/map-reduce/src/main/java/com/iluwatar/Mapper.java index 5a21a73f0..c048c5e4a 100644 --- a/map-reduce/src/main/java/com/iluwatar/Mapper.java +++ b/map-reduce/src/main/java/com/iluwatar/Mapper.java @@ -27,15 +27,16 @@ package com.iluwatar; import java.util.HashMap; import java.util.Map; - /** - * The Mapper class is responsible for processing an input string - * and generating a map of word occurrences. + * The Mapper class is responsible for processing an input string and generating a map of word + * occurrences. */ public class Mapper { private Mapper() { - throw new UnsupportedOperationException("Mapper is a utility class and cannot be instantiated."); + throw new UnsupportedOperationException( + "Mapper is a utility class and cannot be instantiated."); } + /** * Splits a given input string into words and counts their occurrences. * diff --git a/map-reduce/src/main/java/com/iluwatar/Reducer.java b/map-reduce/src/main/java/com/iluwatar/Reducer.java index 6bd9f5f10..fbfc8d09d 100644 --- a/map-reduce/src/main/java/com/iluwatar/Reducer.java +++ b/map-reduce/src/main/java/com/iluwatar/Reducer.java @@ -30,13 +30,13 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -/** - * The Reducer class is responsible for aggregating word counts from the shuffled data. - */ +/** The Reducer class is responsible for aggregating word counts from the shuffled data. */ public class Reducer { private Reducer() { - throw new UnsupportedOperationException("Reducer is a utility class and cannot be instantiated."); + throw new UnsupportedOperationException( + "Reducer is a utility class and cannot be instantiated."); } + /** * Sums the occurrences of each word and sorts the results in descending order. * diff --git a/map-reduce/src/main/java/com/iluwatar/Shuffler.java b/map-reduce/src/main/java/com/iluwatar/Shuffler.java index 7eacee034..cf58bc901 100644 --- a/map-reduce/src/main/java/com/iluwatar/Shuffler.java +++ b/map-reduce/src/main/java/com/iluwatar/Shuffler.java @@ -29,14 +29,14 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -/** - * The Shuffler class is responsible for grouping word occurrences from multiple mappers. - */ +/** The Shuffler class is responsible for grouping word occurrences from multiple mappers. */ public class Shuffler { private Shuffler() { - throw new UnsupportedOperationException("Shuffler is a utility class and cannot be instantiated."); + throw new UnsupportedOperationException( + "Shuffler is a utility class and cannot be instantiated."); } + /** * Merges multiple word count maps into a single grouped map. * diff --git a/map-reduce/src/test/java/com/iluwatar/MapReduceTest.java b/map-reduce/src/test/java/com/iluwatar/MapReduceTest.java index 86dbeff5c..6abaa2142 100644 --- a/map-reduce/src/test/java/com/iluwatar/MapReduceTest.java +++ b/map-reduce/src/test/java/com/iluwatar/MapReduceTest.java @@ -24,24 +24,21 @@ */ package com.iluwatar; -import org.junit.jupiter.api.Test; -import java.util.*; - import static org.junit.jupiter.api.Assertions.*; +import java.util.*; +import org.junit.jupiter.api.Test; + class MapReduceTest { @Test void testMapReduce() { - List inputs = Arrays.asList( - "Hello world hello", - "MapReduce is fun", - "Hello from the other side" - ); + List inputs = + Arrays.asList("Hello world hello", "MapReduce is fun", "Hello from the other side"); List> result = MapReduce.mapReduce(inputs); - assertEquals("hello", result.get(0).getKey()); // hello = 3 + assertEquals("hello", result.get(0).getKey()); // hello = 3 assertEquals(3, result.get(0).getValue()); assertEquals(1, result.get(1).getValue()); } diff --git a/map-reduce/src/test/java/com/iluwatar/MapperTest.java b/map-reduce/src/test/java/com/iluwatar/MapperTest.java index d8011c984..7ebd48407 100644 --- a/map-reduce/src/test/java/com/iluwatar/MapperTest.java +++ b/map-reduce/src/test/java/com/iluwatar/MapperTest.java @@ -24,10 +24,11 @@ */ package com.iluwatar; -import org.junit.jupiter.api.Test; -import java.util.Map; import static org.junit.jupiter.api.Assertions.*; +import java.util.Map; +import org.junit.jupiter.api.Test; + class MapperTest { @Test diff --git a/map-reduce/src/test/java/com/iluwatar/ReducerTest.java b/map-reduce/src/test/java/com/iluwatar/ReducerTest.java index ab4490b9e..903b3828c 100644 --- a/map-reduce/src/test/java/com/iluwatar/ReducerTest.java +++ b/map-reduce/src/test/java/com/iluwatar/ReducerTest.java @@ -24,11 +24,11 @@ */ package com.iluwatar; -import org.junit.jupiter.api.Test; -import java.util.*; - import static org.junit.jupiter.api.Assertions.*; +import java.util.*; +import org.junit.jupiter.api.Test; + class ReducerTest { @Test diff --git a/map-reduce/src/test/java/com/iluwatar/ShufflerTest.java b/map-reduce/src/test/java/com/iluwatar/ShufflerTest.java index cda651c59..3362f7ea2 100644 --- a/map-reduce/src/test/java/com/iluwatar/ShufflerTest.java +++ b/map-reduce/src/test/java/com/iluwatar/ShufflerTest.java @@ -24,19 +24,17 @@ */ package com.iluwatar; -import org.junit.jupiter.api.Test; -import java.util.*; - import static org.junit.jupiter.api.Assertions.*; +import java.util.*; +import org.junit.jupiter.api.Test; + class ShufflerTest { @Test void testShuffleAndSort() { - List> mappedData = Arrays.asList( - Map.of("hello", 1, "world", 2), - Map.of("hello", 2, "java", 1) - ); + List> mappedData = + Arrays.asList(Map.of("hello", 1, "world", 2), Map.of("hello", 2, "java", 1)); Map> grouped = Shuffler.shuffleAndSort(mappedData); diff --git a/marker-interface/pom.xml b/marker-interface/pom.xml index 43ee4bf78..f564d6756 100644 --- a/marker-interface/pom.xml +++ b/marker-interface/pom.xml @@ -34,6 +34,14 @@ 4.0.0 marker-interface + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine @@ -42,6 +50,7 @@ org.hamcrest hamcrest-core + 3.0 test diff --git a/marker-interface/src/main/java/App.java b/marker-interface/src/main/java/App.java index 1d4a0dc97..c1f36664b 100644 --- a/marker-interface/src/main/java/App.java +++ b/marker-interface/src/main/java/App.java @@ -66,4 +66,3 @@ public class App { } } } - diff --git a/marker-interface/src/main/java/Guard.java b/marker-interface/src/main/java/Guard.java index 8852e8302..469ee2e77 100644 --- a/marker-interface/src/main/java/Guard.java +++ b/marker-interface/src/main/java/Guard.java @@ -24,9 +24,7 @@ */ import lombok.extern.slf4j.Slf4j; -/** - * Class defining Guard. - */ +/** Class defining Guard. */ @Slf4j public class Guard implements Permission { diff --git a/marker-interface/src/main/java/Permission.java b/marker-interface/src/main/java/Permission.java index 21f751f72..bdaf18375 100644 --- a/marker-interface/src/main/java/Permission.java +++ b/marker-interface/src/main/java/Permission.java @@ -22,8 +22,5 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -/** - * Interface without any methods Marker interface is based on that assumption. - */ -public interface Permission { -} +/** Interface without any methods Marker interface is based on that assumption. */ +public interface Permission {} diff --git a/marker-interface/src/main/java/Thief.java b/marker-interface/src/main/java/Thief.java index d412d3fa0..ae6bec874 100644 --- a/marker-interface/src/main/java/Thief.java +++ b/marker-interface/src/main/java/Thief.java @@ -24,9 +24,7 @@ */ import lombok.extern.slf4j.Slf4j; -/** - * Class defining Thief. - */ +/** Class defining Thief. */ @Slf4j public class Thief { diff --git a/marker-interface/src/test/java/AppTest.java b/marker-interface/src/test/java/AppTest.java index 1d7048320..4600eed4a 100644 --- a/marker-interface/src/test/java/AppTest.java +++ b/marker-interface/src/test/java/AppTest.java @@ -22,17 +22,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -/** - * Application test - */ +import org.junit.jupiter.api.Test; + +/** Application test */ class AppTest { @Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/marker-interface/src/test/java/GuardTest.java b/marker-interface/src/test/java/GuardTest.java index 9470689bc..7ae34f63d 100644 --- a/marker-interface/src/test/java/GuardTest.java +++ b/marker-interface/src/test/java/GuardTest.java @@ -27,9 +27,7 @@ import static org.hamcrest.MatcherAssert.assertThat; import org.junit.jupiter.api.Test; -/** - * Guard test - */ +/** Guard test */ class GuardTest { @Test @@ -37,4 +35,4 @@ class GuardTest { var guard = new Guard(); assertThat(guard, instanceOf(Permission.class)); } -} \ No newline at end of file +} diff --git a/marker-interface/src/test/java/ThiefTest.java b/marker-interface/src/test/java/ThiefTest.java index 91f312930..130dd12fc 100644 --- a/marker-interface/src/test/java/ThiefTest.java +++ b/marker-interface/src/test/java/ThiefTest.java @@ -28,13 +28,11 @@ import static org.hamcrest.MatcherAssert.assertThat; import org.junit.jupiter.api.Test; -/** - * Thief test - */ +/** Thief test */ class ThiefTest { @Test void testThief() { var thief = new Thief(); assertThat(thief, not(instanceOf(Permission.class))); } -} \ No newline at end of file +} diff --git a/master-worker/pom.xml b/master-worker/pom.xml index 2661fea40..630fbb6f5 100644 --- a/master-worker/pom.xml +++ b/master-worker/pom.xml @@ -34,6 +34,14 @@ master-worker + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/master-worker/src/main/java/com/iluwatar/masterworker/App.java b/master-worker/src/main/java/com/iluwatar/masterworker/App.java index 483729f72..fbe31eca8 100644 --- a/master-worker/src/main/java/com/iluwatar/masterworker/App.java +++ b/master-worker/src/main/java/com/iluwatar/masterworker/App.java @@ -33,13 +33,14 @@ import com.iluwatar.masterworker.system.systemworkers.Worker; import lombok.extern.slf4j.Slf4j; /** - *

The Master-Worker pattern is used when the problem at hand can be solved by + * The Master-Worker pattern is used when the problem at hand can be solved by * dividing into multiple parts which need to go through the same computation and may need to be * aggregated to get final result. Parallel processing is performed using a system consisting of a * master and some number of workers, where a master divides the work among the workers, gets the * result back from them and assimilates all the results to give final result. The only * communication is between the master and the worker - none of the workers communicate among one - * another and the user only communicates with the master to get required job done.

+ * another and the user only communicates with the master to get required job done. + * *

In our example, we have generic abstract classes {@link MasterWorker}, {@link Master} and * {@link Worker} which have to be extended by the classes which will perform the specific job at * hand (in this case finding transpose of matrix, done by {@link ArrayTransposeMasterWorker}, @@ -52,9 +53,8 @@ import lombok.extern.slf4j.Slf4j; * result. We also have 2 abstract classes {@link Input} and {@link Result}, which contain the input * data and result data respectively. The Input class also has an abstract method divideData which * defines how the data is to be divided into segments. These classes are extended by {@link - * ArrayInput} and {@link ArrayResult}.

+ * ArrayInput} and {@link ArrayResult}. */ - @Slf4j public class App { @@ -63,7 +63,6 @@ public class App { * * @param args command line args */ - public static void main(String[] args) { var mw = new ArrayTransposeMasterWorker(); var rows = 10; @@ -78,5 +77,4 @@ public class App { LOGGER.info("Please enter non-zero input"); } } - } diff --git a/master-worker/src/main/java/com/iluwatar/masterworker/ArrayInput.java b/master-worker/src/main/java/com/iluwatar/masterworker/ArrayInput.java index 84e7aef20..3d492aa08 100644 --- a/master-worker/src/main/java/com/iluwatar/masterworker/ArrayInput.java +++ b/master-worker/src/main/java/com/iluwatar/masterworker/ArrayInput.java @@ -28,10 +28,7 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; -/** - * Class ArrayInput extends abstract class {@link Input} and contains data of type int[][]. - */ - +/** Class ArrayInput extends abstract class {@link Input} and contains data of type int[][]. */ public class ArrayInput extends Input { public ArrayInput(int[][] data) { @@ -39,13 +36,13 @@ public class ArrayInput extends Input { } static int[] makeDivisions(int[][] data, int num) { - var initialDivision = data.length / num; //equally dividing + var initialDivision = data.length / num; // equally dividing var divisions = new int[num]; Arrays.fill(divisions, initialDivision); if (initialDivision * num != data.length) { var extra = data.length - initialDivision * num; var l = 0; - //equally dividing extra among all parts + // equally dividing extra among all parts while (extra > 0) { divisions[l] = divisions[l] + 1; extra--; @@ -66,7 +63,7 @@ public class ArrayInput extends Input { } else { var divisions = makeDivisions(this.data, num); var result = new ArrayList>(num); - var rowsDone = 0; //number of rows divided so far + var rowsDone = 0; // number of rows divided so far for (var i = 0; i < num; i++) { var rows = divisions[i]; if (rows != 0) { @@ -76,7 +73,7 @@ public class ArrayInput extends Input { var dividedInput = new ArrayInput(divided); result.add(dividedInput); } else { - break; //rest of divisions will also be 0 + break; // rest of divisions will also be 0 } } return result; diff --git a/master-worker/src/main/java/com/iluwatar/masterworker/ArrayResult.java b/master-worker/src/main/java/com/iluwatar/masterworker/ArrayResult.java index a81fd6c3d..fa99b5ce6 100644 --- a/master-worker/src/main/java/com/iluwatar/masterworker/ArrayResult.java +++ b/master-worker/src/main/java/com/iluwatar/masterworker/ArrayResult.java @@ -24,10 +24,7 @@ */ package com.iluwatar.masterworker; -/** - * Class ArrayResult extends abstract class {@link Result} and contains data of type int[][]. - */ - +/** Class ArrayResult extends abstract class {@link Result} and contains data of type int[][]. */ public class ArrayResult extends Result { public ArrayResult(int[][] data) { diff --git a/master-worker/src/main/java/com/iluwatar/masterworker/ArrayUtilityMethods.java b/master-worker/src/main/java/com/iluwatar/masterworker/ArrayUtilityMethods.java index 865c6f229..8d3e9e790 100644 --- a/master-worker/src/main/java/com/iluwatar/masterworker/ArrayUtilityMethods.java +++ b/master-worker/src/main/java/com/iluwatar/masterworker/ArrayUtilityMethods.java @@ -27,10 +27,7 @@ package com.iluwatar.masterworker; import java.security.SecureRandom; import lombok.extern.slf4j.Slf4j; -/** - * Class ArrayUtilityMethods has some utility methods for matrices and arrays. - */ - +/** Class ArrayUtilityMethods has some utility methods for matrices and arrays. */ @Slf4j public class ArrayUtilityMethods { @@ -40,9 +37,8 @@ public class ArrayUtilityMethods { * Method arraysSame compares 2 arrays @param a1 and @param a2 and @return whether their values * are equal (boolean). */ - public static boolean arraysSame(int[] a1, int[] a2) { - //compares if 2 arrays have the same value + // compares if 2 arrays have the same value if (a1.length != a2.length) { return false; } else { @@ -63,7 +59,6 @@ public class ArrayUtilityMethods { * Method matricesSame compares 2 matrices @param m1 and @param m2 and @return whether their * values are equal (boolean). */ - public static boolean matricesSame(int[][] m1, int[][] m2) { if (m1.length != m2.length) { return false; @@ -90,19 +85,16 @@ public class ArrayUtilityMethods { var matrix = new int[rows][columns]; for (var i = 0; i < rows; i++) { for (var j = 0; j < columns; j++) { - //filling cells in matrix + // filling cells in matrix matrix[i][j] = RANDOM.nextInt(10); } } return matrix; } - /** - * Method printMatrix prints input matrix @param matrix. - */ - + /** Method printMatrix prints input matrix @param matrix. */ public static void printMatrix(int[][] matrix) { - //prints out int[][] + // prints out int[][] for (var ints : matrix) { for (var j = 0; j < matrix[0].length; j++) { LOGGER.info(ints[j] + " "); @@ -110,5 +102,4 @@ public class ArrayUtilityMethods { LOGGER.info(""); } } - } diff --git a/master-worker/src/main/java/com/iluwatar/masterworker/Input.java b/master-worker/src/main/java/com/iluwatar/masterworker/Input.java index 6dd46865b..4e7c73d86 100644 --- a/master-worker/src/main/java/com/iluwatar/masterworker/Input.java +++ b/master-worker/src/main/java/com/iluwatar/masterworker/Input.java @@ -32,7 +32,6 @@ import java.util.List; * * @param T will be type of data. */ - public abstract class Input { public final T data; diff --git a/master-worker/src/main/java/com/iluwatar/masterworker/Result.java b/master-worker/src/main/java/com/iluwatar/masterworker/Result.java index 61450d656..cc0bd4682 100644 --- a/master-worker/src/main/java/com/iluwatar/masterworker/Result.java +++ b/master-worker/src/main/java/com/iluwatar/masterworker/Result.java @@ -29,7 +29,6 @@ package com.iluwatar.masterworker; * * @param T will be type of data. */ - public abstract class Result { public final T data; diff --git a/master-worker/src/main/java/com/iluwatar/masterworker/system/ArrayTransposeMasterWorker.java b/master-worker/src/main/java/com/iluwatar/masterworker/system/ArrayTransposeMasterWorker.java index dcbd47a3f..0ebef7dd8 100644 --- a/master-worker/src/main/java/com/iluwatar/masterworker/system/ArrayTransposeMasterWorker.java +++ b/master-worker/src/main/java/com/iluwatar/masterworker/system/ArrayTransposeMasterWorker.java @@ -31,7 +31,6 @@ import com.iluwatar.masterworker.system.systemmaster.Master; * Class ArrayTransposeMasterWorker extends abstract class {@link MasterWorker} and specifically * solves the problem of finding transpose of input array. */ - public class ArrayTransposeMasterWorker extends MasterWorker { public ArrayTransposeMasterWorker() { diff --git a/master-worker/src/main/java/com/iluwatar/masterworker/system/MasterWorker.java b/master-worker/src/main/java/com/iluwatar/masterworker/system/MasterWorker.java index 8027161b8..5f785ebff 100644 --- a/master-worker/src/main/java/com/iluwatar/masterworker/system/MasterWorker.java +++ b/master-worker/src/main/java/com/iluwatar/masterworker/system/MasterWorker.java @@ -28,10 +28,7 @@ import com.iluwatar.masterworker.Input; import com.iluwatar.masterworker.Result; import com.iluwatar.masterworker.system.systemmaster.Master; -/** - * The abstract MasterWorker class which contains reference to master. - */ - +/** The abstract MasterWorker class which contains reference to master. */ public abstract class MasterWorker { private final Master master; @@ -46,4 +43,3 @@ public abstract class MasterWorker { return this.master.getFinalResult(); } } - diff --git a/master-worker/src/main/java/com/iluwatar/masterworker/system/systemmaster/ArrayTransposeMaster.java b/master-worker/src/main/java/com/iluwatar/masterworker/system/systemmaster/ArrayTransposeMaster.java index da3e6c5d2..50ee1c2b1 100644 --- a/master-worker/src/main/java/com/iluwatar/masterworker/system/systemmaster/ArrayTransposeMaster.java +++ b/master-worker/src/main/java/com/iluwatar/masterworker/system/systemmaster/ArrayTransposeMaster.java @@ -35,7 +35,6 @@ import java.util.stream.IntStream; * Class ArrayTransposeMaster extends abstract class {@link Master} and contains definition of * aggregateData, which will obtain final result from all data obtained and for setWorkers. */ - public class ArrayTransposeMaster extends Master { public ArrayTransposeMaster(int numOfWorkers) { super(numOfWorkers); @@ -43,7 +42,7 @@ public class ArrayTransposeMaster extends Master { @Override ArrayList setWorkers(int num) { - //i+1 will be id + // i+1 will be id return IntStream.range(0, num) .mapToObj(i -> new ArrayTransposeWorker(this, i + 1)) .collect(Collectors.toCollection(() -> new ArrayList<>(num))); @@ -60,20 +59,19 @@ public class ArrayTransposeMaster extends Master { columns += ((ArrayResult) elements.nextElement()).data[0].length; } var resultData = new int[rows][columns]; - var columnsDone = 0; //columns aggregated so far + var columnsDone = 0; // columns aggregated so far var workers = this.getWorkers(); for (var i = 0; i < this.getExpectedNumResults(); i++) { - //result obtained from ith worker + // result obtained from ith worker var worker = workers.get(i); var workerId = worker.getWorkerId(); var work = ((ArrayResult) allResultData.get(workerId)).data; for (var m = 0; m < work.length; m++) { - //m = row number, n = columns number + // m = row number, n = columns number System.arraycopy(work[m], 0, resultData[m], columnsDone, work[0].length); } columnsDone += work[0].length; } return new ArrayResult(resultData); } - } diff --git a/master-worker/src/main/java/com/iluwatar/masterworker/system/systemmaster/Master.java b/master-worker/src/main/java/com/iluwatar/masterworker/system/systemmaster/Master.java index 800b63f71..791de82c9 100644 --- a/master-worker/src/main/java/com/iluwatar/masterworker/system/systemmaster/Master.java +++ b/master-worker/src/main/java/com/iluwatar/masterworker/system/systemmaster/Master.java @@ -37,14 +37,12 @@ import lombok.Getter; * number of results), allResultData (hashtable of results obtained from workers, mapped by their * ids) and finalResult (aggregated from allResultData). */ - public abstract class Master { private final int numOfWorkers; private final List workers; private final Hashtable> allResultData; private int expectedNumResults; - @Getter - private Result finalResult; + @Getter private Result finalResult; Master(int numOfWorkers) { this.numOfWorkers = numOfWorkers; @@ -77,7 +75,7 @@ public abstract class Master { if (dividedInput != null) { this.expectedNumResults = dividedInput.size(); for (var i = 0; i < this.expectedNumResults; i++) { - //ith division given to ith worker in this.workers + // ith division given to ith worker in this.workers this.workers.get(i).setReceivedData(this, dividedInput.get(i)); this.workers.get(i).start(); } @@ -99,7 +97,7 @@ public abstract class Master { private void collectResult(Result data, int workerId) { this.allResultData.put(workerId, data); if (this.allResultData.size() == this.expectedNumResults) { - //all data received + // all data received this.finalResult = aggregateData(); } } diff --git a/master-worker/src/main/java/com/iluwatar/masterworker/system/systemworkers/ArrayTransposeWorker.java b/master-worker/src/main/java/com/iluwatar/masterworker/system/systemworkers/ArrayTransposeWorker.java index 110a15a1a..0d83fd3eb 100644 --- a/master-worker/src/main/java/com/iluwatar/masterworker/system/systemworkers/ArrayTransposeWorker.java +++ b/master-worker/src/main/java/com/iluwatar/masterworker/system/systemworkers/ArrayTransposeWorker.java @@ -32,7 +32,6 @@ import com.iluwatar.masterworker.system.systemmaster.Master; * Class ArrayTransposeWorker extends abstract class {@link Worker} and defines method * executeOperation(), to be performed on data received from master. */ - public class ArrayTransposeWorker extends Worker { public ArrayTransposeWorker(Master master, int id) { @@ -41,14 +40,14 @@ public class ArrayTransposeWorker extends Worker { @Override ArrayResult executeOperation() { - //number of rows in result matrix is equal to number of columns in input matrix and vice versa + // number of rows in result matrix is equal to number of columns in input matrix and vice versa var arrayInput = (ArrayInput) this.getReceivedData(); final var rows = arrayInput.data[0].length; final var cols = arrayInput.data.length; var resultData = new int[rows][cols]; for (var i = 0; i < cols; i++) { for (var j = 0; j < rows; j++) { - //flipping element positions along diagonal + // flipping element positions along diagonal resultData[j][i] = arrayInput.data[i][j]; } } diff --git a/master-worker/src/main/java/com/iluwatar/masterworker/system/systemworkers/Worker.java b/master-worker/src/main/java/com/iluwatar/masterworker/system/systemworkers/Worker.java index a276fc540..0f154c195 100644 --- a/master-worker/src/main/java/com/iluwatar/masterworker/system/systemworkers/Worker.java +++ b/master-worker/src/main/java/com/iluwatar/masterworker/system/systemworkers/Worker.java @@ -33,11 +33,9 @@ import lombok.Getter; * The abstract Worker class which extends Thread class to enable parallel processing. Contains * fields master(holding reference to master), workerId (unique id) and receivedData(from master). */ - public abstract class Worker extends Thread { private final Master master; - @Getter - private final int workerId; + @Getter private final int workerId; private Input receivedData; Worker(Master master, int id) { @@ -61,7 +59,7 @@ public abstract class Worker extends Thread { this.master.receiveData(data, this); } - public void run() { //from Thread class + public void run() { // from Thread class var work = executeOperation(); sendToMaster(work); } diff --git a/master-worker/src/test/java/com/iluwatar/masterworker/ArrayInputTest.java b/master-worker/src/test/java/com/iluwatar/masterworker/ArrayInputTest.java index 2f259573e..30cee36ce 100644 --- a/master-worker/src/test/java/com/iluwatar/masterworker/ArrayInputTest.java +++ b/master-worker/src/test/java/com/iluwatar/masterworker/ArrayInputTest.java @@ -30,10 +30,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Random; import org.junit.jupiter.api.Test; -/** - * Testing divideData method in {@link ArrayInput} class. - */ - +/** Testing divideData method in {@link ArrayInput} class. */ class ArrayInputTest { @Test @@ -49,14 +46,14 @@ class ArrayInputTest { } var i = new ArrayInput(inputMatrix); var table = i.divideData(4); - var division1 = new int[][]{inputMatrix[0], inputMatrix[1], inputMatrix[2]}; - var division2 = new int[][]{inputMatrix[3], inputMatrix[4], inputMatrix[5]}; - var division3 = new int[][]{inputMatrix[6], inputMatrix[7]}; - var division4 = new int[][]{inputMatrix[8], inputMatrix[9]}; - assertTrue(matricesSame(table.get(0).data, division1) - && matricesSame(table.get(1).data, division2) - && matricesSame(table.get(2).data, division3) - && matricesSame(table.get(3).data, division4)); + var division1 = new int[][] {inputMatrix[0], inputMatrix[1], inputMatrix[2]}; + var division2 = new int[][] {inputMatrix[3], inputMatrix[4], inputMatrix[5]}; + var division3 = new int[][] {inputMatrix[6], inputMatrix[7]}; + var division4 = new int[][] {inputMatrix[8], inputMatrix[9]}; + assertTrue( + matricesSame(table.get(0).data, division1) + && matricesSame(table.get(1).data, division2) + && matricesSame(table.get(2).data, division3) + && matricesSame(table.get(3).data, division4)); } - } diff --git a/master-worker/src/test/java/com/iluwatar/masterworker/ArrayUtilityMethodsTest.java b/master-worker/src/test/java/com/iluwatar/masterworker/ArrayUtilityMethodsTest.java index 2e2a1bc54..2c3cbaa75 100644 --- a/master-worker/src/test/java/com/iluwatar/masterworker/ArrayUtilityMethodsTest.java +++ b/master-worker/src/test/java/com/iluwatar/masterworker/ArrayUtilityMethodsTest.java @@ -28,24 +28,20 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; -/** - * Testing utility methods in {@link ArrayUtilityMethods} class. - */ - +/** Testing utility methods in {@link ArrayUtilityMethods} class. */ class ArrayUtilityMethodsTest { @Test void arraysSameTest() { - var arr1 = new int[]{1, 4, 2, 6}; - var arr2 = new int[]{1, 4, 2, 6}; + var arr1 = new int[] {1, 4, 2, 6}; + var arr2 = new int[] {1, 4, 2, 6}; assertTrue(ArrayUtilityMethods.arraysSame(arr1, arr2)); } @Test void matricesSameTest() { - var matrix1 = new int[][]{{1, 4, 2, 6}, {5, 8, 6, 7}}; - var matrix2 = new int[][]{{1, 4, 2, 6}, {5, 8, 6, 7}}; + var matrix1 = new int[][] {{1, 4, 2, 6}, {5, 8, 6, 7}}; + var matrix2 = new int[][] {{1, 4, 2, 6}, {5, 8, 6, 7}}; assertTrue(ArrayUtilityMethods.matricesSame(matrix1, matrix2)); } - } diff --git a/master-worker/src/test/java/com/iluwatar/masterworker/system/ArrayTransposeMasterWorkerTest.java b/master-worker/src/test/java/com/iluwatar/masterworker/system/ArrayTransposeMasterWorkerTest.java index d8a014b61..9d037ada0 100644 --- a/master-worker/src/test/java/com/iluwatar/masterworker/system/ArrayTransposeMasterWorkerTest.java +++ b/master-worker/src/test/java/com/iluwatar/masterworker/system/ArrayTransposeMasterWorkerTest.java @@ -31,29 +31,28 @@ import com.iluwatar.masterworker.ArrayResult; import com.iluwatar.masterworker.ArrayUtilityMethods; import org.junit.jupiter.api.Test; -/** - * Testing getResult method in {@link ArrayTransposeMasterWorker} class. - */ - +/** Testing getResult method in {@link ArrayTransposeMasterWorker} class. */ class ArrayTransposeMasterWorkerTest { @Test void getResultTest() { var atmw = new ArrayTransposeMasterWorker(); - var matrix = new int[][]{ - {1, 2, 3, 4, 5}, - {1, 2, 3, 4, 5}, - {1, 2, 3, 4, 5}, - {1, 2, 3, 4, 5}, - {1, 2, 3, 4, 5} - }; - var matrixTranspose = new int[][]{ - {1, 1, 1, 1, 1}, - {2, 2, 2, 2, 2}, - {3, 3, 3, 3, 3}, - {4, 4, 4, 4, 4}, - {5, 5, 5, 5, 5} - }; + var matrix = + new int[][] { + {1, 2, 3, 4, 5}, + {1, 2, 3, 4, 5}, + {1, 2, 3, 4, 5}, + {1, 2, 3, 4, 5}, + {1, 2, 3, 4, 5} + }; + var matrixTranspose = + new int[][] { + {1, 1, 1, 1, 1}, + {2, 2, 2, 2, 2}, + {3, 3, 3, 3, 3}, + {4, 4, 4, 4, 4}, + {5, 5, 5, 5, 5} + }; var i = new ArrayInput(matrix); var r = (ArrayResult) atmw.getResult(i); assertTrue(ArrayUtilityMethods.matricesSame(r.data, matrixTranspose)); diff --git a/master-worker/src/test/java/com/iluwatar/masterworker/system/systemworkers/ArrayTransposeWorkerTest.java b/master-worker/src/test/java/com/iluwatar/masterworker/system/systemworkers/ArrayTransposeWorkerTest.java index a6deb3a83..b1fedbd97 100644 --- a/master-worker/src/test/java/com/iluwatar/masterworker/system/systemworkers/ArrayTransposeWorkerTest.java +++ b/master-worker/src/test/java/com/iluwatar/masterworker/system/systemworkers/ArrayTransposeWorkerTest.java @@ -31,22 +31,18 @@ import com.iluwatar.masterworker.ArrayUtilityMethods; import com.iluwatar.masterworker.system.systemmaster.ArrayTransposeMaster; import org.junit.jupiter.api.Test; -/** - * Testing executeOperation method in {@link ArrayTransposeWorker} class. - */ - +/** Testing executeOperation method in {@link ArrayTransposeWorker} class. */ class ArrayTransposeWorkerTest { @Test void executeOperationTest() { var atm = new ArrayTransposeMaster(1); var atw = new ArrayTransposeWorker(atm, 1); - var matrix = new int[][]{{2, 4}, {3, 5}}; - var matrixTranspose = new int[][]{{2, 3}, {4, 5}}; + var matrix = new int[][] {{2, 4}, {3, 5}}; + var matrixTranspose = new int[][] {{2, 3}, {4, 5}}; var i = new ArrayInput(matrix); atw.setReceivedData(atm, i); var r = atw.executeOperation(); assertTrue(ArrayUtilityMethods.matricesSame(r.data, matrixTranspose)); } - } diff --git a/mediator/pom.xml b/mediator/pom.xml index 6fa9bbaf4..737f81883 100644 --- a/mediator/pom.xml +++ b/mediator/pom.xml @@ -34,6 +34,14 @@ mediator + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/mediator/src/main/java/com/iluwatar/mediator/Action.java b/mediator/src/main/java/com/iluwatar/mediator/Action.java index 61f70f0e6..d61873e69 100644 --- a/mediator/src/main/java/com/iluwatar/mediator/Action.java +++ b/mediator/src/main/java/com/iluwatar/mediator/Action.java @@ -26,9 +26,7 @@ package com.iluwatar.mediator; import lombok.Getter; -/** - * Action enumeration. - */ +/** Action enumeration. */ public enum Action { HUNT("hunted a rabbit", "arrives for dinner"), TALE("tells a tale", "comes to listen"), @@ -37,8 +35,7 @@ public enum Action { NONE("", ""); private final String title; - @Getter - private final String description; + @Getter private final String description; Action(String title, String description) { this.title = title; diff --git a/mediator/src/main/java/com/iluwatar/mediator/App.java b/mediator/src/main/java/com/iluwatar/mediator/App.java index c5e4c64cd..aaab69f4d 100644 --- a/mediator/src/main/java/com/iluwatar/mediator/App.java +++ b/mediator/src/main/java/com/iluwatar/mediator/App.java @@ -41,9 +41,8 @@ package com.iluwatar.mediator; * the mediator. This reduces the dependencies between communicating objects, thereby lowering the * coupling. * - *

In this example the mediator encapsulates how a set of objects ({@link PartyMember}) - * interact. Instead of referring to each other directly they use the mediator ({@link Party}) - * interface. + *

In this example the mediator encapsulates how a set of objects ({@link PartyMember}) interact. + * Instead of referring to each other directly they use the mediator ({@link Party}) interface. */ public class App { diff --git a/mediator/src/main/java/com/iluwatar/mediator/Hobbit.java b/mediator/src/main/java/com/iluwatar/mediator/Hobbit.java index effe0dd15..c0b5fc967 100644 --- a/mediator/src/main/java/com/iluwatar/mediator/Hobbit.java +++ b/mediator/src/main/java/com/iluwatar/mediator/Hobbit.java @@ -1,37 +1,34 @@ -/* - * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). - * - * The MIT License - * Copyright © 2014-2022 Ilkka Seppälä - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package com.iluwatar.mediator; - -/** - * Hobbit party member. - */ -public class Hobbit extends PartyMemberBase { - - @Override - public String toString() { - return "Hobbit"; - } - -} +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.mediator; + +/** Hobbit party member. */ +public class Hobbit extends PartyMemberBase { + + @Override + public String toString() { + return "Hobbit"; + } +} diff --git a/mediator/src/main/java/com/iluwatar/mediator/Hunter.java b/mediator/src/main/java/com/iluwatar/mediator/Hunter.java index 783cd1aa9..ddf0c2810 100644 --- a/mediator/src/main/java/com/iluwatar/mediator/Hunter.java +++ b/mediator/src/main/java/com/iluwatar/mediator/Hunter.java @@ -1,36 +1,34 @@ -/* - * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). - * - * The MIT License - * Copyright © 2014-2022 Ilkka Seppälä - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package com.iluwatar.mediator; - -/** - * Hunter party member. - */ -public class Hunter extends PartyMemberBase { - - @Override - public String toString() { - return "Hunter"; - } -} +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.mediator; + +/** Hunter party member. */ +public class Hunter extends PartyMemberBase { + + @Override + public String toString() { + return "Hunter"; + } +} diff --git a/mediator/src/main/java/com/iluwatar/mediator/Party.java b/mediator/src/main/java/com/iluwatar/mediator/Party.java index 387f4809f..b7c87f162 100644 --- a/mediator/src/main/java/com/iluwatar/mediator/Party.java +++ b/mediator/src/main/java/com/iluwatar/mediator/Party.java @@ -1,36 +1,33 @@ -/* - * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). - * - * The MIT License - * Copyright © 2014-2022 Ilkka Seppälä - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package com.iluwatar.mediator; - -/** - * Party interface. - */ -public interface Party { - - void addMember(PartyMember member); - - void act(PartyMember actor, Action action); - -} +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.mediator; + +/** Party interface. */ +public interface Party { + + void addMember(PartyMember member); + + void act(PartyMember actor, Action action); +} diff --git a/mediator/src/main/java/com/iluwatar/mediator/PartyImpl.java b/mediator/src/main/java/com/iluwatar/mediator/PartyImpl.java index c61e39faf..92e37506f 100644 --- a/mediator/src/main/java/com/iluwatar/mediator/PartyImpl.java +++ b/mediator/src/main/java/com/iluwatar/mediator/PartyImpl.java @@ -1,55 +1,53 @@ -/* - * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). - * - * The MIT License - * Copyright © 2014-2022 Ilkka Seppälä - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package com.iluwatar.mediator; - -import java.util.ArrayList; -import java.util.List; - -/** - * Party implementation. - */ -public class PartyImpl implements Party { - - private final List members; - - public PartyImpl() { - members = new ArrayList<>(); - } - - @Override - public void act(PartyMember actor, Action action) { - for (var member : members) { - if (!member.equals(actor)) { - member.partyAction(action); - } - } - } - - @Override - public void addMember(PartyMember member) { - members.add(member); - member.joinedParty(this); - } -} +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.mediator; + +import java.util.ArrayList; +import java.util.List; + +/** Party implementation. */ +public class PartyImpl implements Party { + + private final List members; + + public PartyImpl() { + members = new ArrayList<>(); + } + + @Override + public void act(PartyMember actor, Action action) { + for (var member : members) { + if (!member.equals(actor)) { + member.partyAction(action); + } + } + } + + @Override + public void addMember(PartyMember member) { + members.add(member); + member.joinedParty(this); + } +} diff --git a/mediator/src/main/java/com/iluwatar/mediator/PartyMember.java b/mediator/src/main/java/com/iluwatar/mediator/PartyMember.java index dc1aec4e4..4fad4e85b 100644 --- a/mediator/src/main/java/com/iluwatar/mediator/PartyMember.java +++ b/mediator/src/main/java/com/iluwatar/mediator/PartyMember.java @@ -24,9 +24,7 @@ */ package com.iluwatar.mediator; -/** - * Interface for party members interacting with {@link Party}. - */ +/** Interface for party members interacting with {@link Party}. */ public interface PartyMember { void joinedParty(Party party); diff --git a/mediator/src/main/java/com/iluwatar/mediator/PartyMemberBase.java b/mediator/src/main/java/com/iluwatar/mediator/PartyMemberBase.java index 21909cd3c..8a67b8f59 100644 --- a/mediator/src/main/java/com/iluwatar/mediator/PartyMemberBase.java +++ b/mediator/src/main/java/com/iluwatar/mediator/PartyMemberBase.java @@ -1,59 +1,56 @@ -/* - * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). - * - * The MIT License - * Copyright © 2014-2022 Ilkka Seppälä - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package com.iluwatar.mediator; - -import lombok.extern.slf4j.Slf4j; - -/** - * Abstract base class for party members. - */ -@Slf4j -public abstract class PartyMemberBase implements PartyMember { - - protected Party party; - - @Override - public void joinedParty(Party party) { - LOGGER.info("{} joins the party", this); - this.party = party; - } - - @Override - public void partyAction(Action action) { - LOGGER.info("{} {}", this, action.getDescription()); - } - - @Override - public void act(Action action) { - if (party != null) { - LOGGER.info("{} {}", this, action); - party.act(this, action); - } - } - - @Override - public abstract String toString(); - -} +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.mediator; + +import lombok.extern.slf4j.Slf4j; + +/** Abstract base class for party members. */ +@Slf4j +public abstract class PartyMemberBase implements PartyMember { + + protected Party party; + + @Override + public void joinedParty(Party party) { + LOGGER.info("{} joins the party", this); + this.party = party; + } + + @Override + public void partyAction(Action action) { + LOGGER.info("{} {}", this, action.getDescription()); + } + + @Override + public void act(Action action) { + if (party != null) { + LOGGER.info("{} {}", this, action); + party.act(this, action); + } + } + + @Override + public abstract String toString(); +} diff --git a/mediator/src/main/java/com/iluwatar/mediator/Rogue.java b/mediator/src/main/java/com/iluwatar/mediator/Rogue.java index 2724b46e8..5edeff28f 100644 --- a/mediator/src/main/java/com/iluwatar/mediator/Rogue.java +++ b/mediator/src/main/java/com/iluwatar/mediator/Rogue.java @@ -1,37 +1,34 @@ -/* - * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). - * - * The MIT License - * Copyright © 2014-2022 Ilkka Seppälä - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package com.iluwatar.mediator; - -/** - * Rogue party member. - */ -public class Rogue extends PartyMemberBase { - - @Override - public String toString() { - return "Rogue"; - } - -} +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.mediator; + +/** Rogue party member. */ +public class Rogue extends PartyMemberBase { + + @Override + public String toString() { + return "Rogue"; + } +} diff --git a/mediator/src/main/java/com/iluwatar/mediator/Wizard.java b/mediator/src/main/java/com/iluwatar/mediator/Wizard.java index d43b95e39..126766ea9 100644 --- a/mediator/src/main/java/com/iluwatar/mediator/Wizard.java +++ b/mediator/src/main/java/com/iluwatar/mediator/Wizard.java @@ -1,37 +1,34 @@ -/* - * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). - * - * The MIT License - * Copyright © 2014-2022 Ilkka Seppälä - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package com.iluwatar.mediator; - -/** - * Wizard party member. - */ -public class Wizard extends PartyMemberBase { - - @Override - public String toString() { - return "Wizard"; - } - -} +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.mediator; + +/** Wizard party member. */ +public class Wizard extends PartyMemberBase { + + @Override + public String toString() { + return "Wizard"; + } +} diff --git a/mediator/src/test/java/com/iluwatar/mediator/AppTest.java b/mediator/src/test/java/com/iluwatar/mediator/AppTest.java index 47d2727cc..85be64afe 100644 --- a/mediator/src/test/java/com/iluwatar/mediator/AppTest.java +++ b/mediator/src/test/java/com/iluwatar/mediator/AppTest.java @@ -24,17 +24,15 @@ */ package com.iluwatar.mediator; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -/** - * Application test - */ +import org.junit.jupiter.api.Test; + +/** Application test */ class AppTest { @Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/mediator/src/test/java/com/iluwatar/mediator/PartyImplTest.java b/mediator/src/test/java/com/iluwatar/mediator/PartyImplTest.java index ce892303a..7353bc83b 100644 --- a/mediator/src/test/java/com/iluwatar/mediator/PartyImplTest.java +++ b/mediator/src/test/java/com/iluwatar/mediator/PartyImplTest.java @@ -30,10 +30,7 @@ import static org.mockito.Mockito.verifyNoMoreInteractions; import org.junit.jupiter.api.Test; -/** - * PartyImplTest - * - */ +/** PartyImplTest */ class PartyImplTest { /** @@ -58,5 +55,4 @@ class PartyImplTest { verifyNoMoreInteractions(partyMember1, partyMember2); } - } diff --git a/mediator/src/test/java/com/iluwatar/mediator/PartyMemberTest.java b/mediator/src/test/java/com/iluwatar/mediator/PartyMemberTest.java index 144175ca0..46be9593a 100644 --- a/mediator/src/test/java/com/iluwatar/mediator/PartyMemberTest.java +++ b/mediator/src/test/java/com/iluwatar/mediator/PartyMemberTest.java @@ -42,10 +42,7 @@ import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import org.slf4j.LoggerFactory; -/** - * PartyMemberTest - * - */ +/** PartyMemberTest */ class PartyMemberTest { static Stream dataProvider() { @@ -53,8 +50,7 @@ class PartyMemberTest { Arguments.of((Supplier) Hobbit::new), Arguments.of((Supplier) Hunter::new), Arguments.of((Supplier) Rogue::new), - Arguments.of((Supplier) Wizard::new) - ); + Arguments.of((Supplier) Wizard::new)); } private InMemoryAppender appender; @@ -69,9 +65,7 @@ class PartyMemberTest { appender.stop(); } - /** - * Verify if a party action triggers the correct output to the std-Out - */ + /** Verify if a party action triggers the correct output to the std-Out */ @ParameterizedTest @MethodSource("dataProvider") void testPartyAction(Supplier memberSupplier) { @@ -85,9 +79,7 @@ class PartyMemberTest { assertEquals(Action.values().length, appender.getLogSize()); } - /** - * Verify if a member action triggers the expected interactions with the party class - */ + /** Verify if a member action triggers the expected interactions with the party class */ @ParameterizedTest @MethodSource("dataProvider") void testAct(Supplier memberSupplier) { @@ -109,9 +101,7 @@ class PartyMemberTest { assertEquals(Action.values().length + 1, appender.getLogSize()); } - /** - * Verify if {@link PartyMemberBase#toString()} generate the expected output - */ + /** Verify if {@link PartyMemberBase#toString()} generate the expected output */ @ParameterizedTest @MethodSource("dataProvider") void testToString(Supplier memberSupplier) { @@ -141,6 +131,4 @@ class PartyMemberTest { return log.get(log.size() - 1).getFormattedMessage(); } } - - } diff --git a/memento/pom.xml b/memento/pom.xml index 6f4314d54..6ec5ca5d0 100644 --- a/memento/pom.xml +++ b/memento/pom.xml @@ -34,6 +34,14 @@ memento + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/memento/src/main/java/com/iluwatar/memento/App.java b/memento/src/main/java/com/iluwatar/memento/App.java index effc83d3f..d47bc20db 100644 --- a/memento/src/main/java/com/iluwatar/memento/App.java +++ b/memento/src/main/java/com/iluwatar/memento/App.java @@ -47,9 +47,7 @@ import lombok.extern.slf4j.Slf4j; @Slf4j public class App { - /** - * Program entry point. - */ + /** Program entry point. */ public static void main(String[] args) { var states = new Stack(); diff --git a/memento/src/main/java/com/iluwatar/memento/Star.java b/memento/src/main/java/com/iluwatar/memento/Star.java index deccb8595..8f806b1e1 100644 --- a/memento/src/main/java/com/iluwatar/memento/Star.java +++ b/memento/src/main/java/com/iluwatar/memento/Star.java @@ -27,27 +27,21 @@ package com.iluwatar.memento; import lombok.Getter; import lombok.Setter; -/** - * Star uses "mementos" to store and restore state. - */ +/** Star uses "mementos" to store and restore state. */ public class Star { private StarType type; private int ageYears; private int massTons; - /** - * Constructor. - */ + /** Constructor. */ public Star(StarType startType, int startAge, int startMass) { this.type = startType; this.ageYears = startAge; this.massTons = startMass; } - /** - * Makes time pass for the star. - */ + /** Makes time pass for the star. */ public void timePasses() { ageYears *= 2; massTons *= 8; @@ -60,8 +54,7 @@ public class Star { ageYears *= 2; massTons = 0; } - default -> { - } + default -> {} } } @@ -85,9 +78,7 @@ public class Star { return String.format("%s age: %d years mass: %d tons", type.toString(), ageYears, massTons); } - /** - * StarMemento implementation. - */ + /** StarMemento implementation. */ @Getter @Setter private static class StarMementoInternal implements StarMemento { diff --git a/memento/src/main/java/com/iluwatar/memento/StarMemento.java b/memento/src/main/java/com/iluwatar/memento/StarMemento.java index 3a355a1ea..b0214ad1a 100644 --- a/memento/src/main/java/com/iluwatar/memento/StarMemento.java +++ b/memento/src/main/java/com/iluwatar/memento/StarMemento.java @@ -1,32 +1,28 @@ -/* - * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). - * - * The MIT License - * Copyright © 2014-2022 Ilkka Seppälä - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package com.iluwatar.memento; - -/** - * External interface to memento. - */ -public interface StarMemento { - -} +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.memento; + +/** External interface to memento. */ +public interface StarMemento {} diff --git a/memento/src/main/java/com/iluwatar/memento/StarType.java b/memento/src/main/java/com/iluwatar/memento/StarType.java index 69bc9b9be..41e1659ef 100644 --- a/memento/src/main/java/com/iluwatar/memento/StarType.java +++ b/memento/src/main/java/com/iluwatar/memento/StarType.java @@ -24,9 +24,7 @@ */ package com.iluwatar.memento; -/** - * StarType enumeration. - */ +/** StarType enumeration. */ public enum StarType { SUN("sun"), RED_GIANT("red giant"), diff --git a/memento/src/test/java/com/iluwatar/memento/AppTest.java b/memento/src/test/java/com/iluwatar/memento/AppTest.java index b175f57ef..ad7ea0019 100644 --- a/memento/src/test/java/com/iluwatar/memento/AppTest.java +++ b/memento/src/test/java/com/iluwatar/memento/AppTest.java @@ -24,17 +24,15 @@ */ package com.iluwatar.memento; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -/** - * Application test - */ +import org.junit.jupiter.api.Test; + +/** Application test */ class AppTest { @Test void shouldExecuteWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/memento/src/test/java/com/iluwatar/memento/StarTest.java b/memento/src/test/java/com/iluwatar/memento/StarTest.java index 9a52e83cb..4411efaab 100644 --- a/memento/src/test/java/com/iluwatar/memento/StarTest.java +++ b/memento/src/test/java/com/iluwatar/memento/StarTest.java @@ -28,15 +28,10 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; -/** - * StarTest - * - */ +/** StarTest */ class StarTest { - /** - * Verify the stages of a dying sun, without going back in time - */ + /** Verify the stages of a dying sun, without going back in time */ @Test void testTimePasses() { final var star = new Star(StarType.SUN, 1, 2); @@ -61,9 +56,7 @@ class StarTest { assertEquals("dead star age: 256 years mass: 0 tons", star.toString()); } - /** - * Verify some stage of a dying sun, but go back in time to test the memento - */ + /** Verify some stage of a dying sun, but go back in time to test the memento */ @Test void testSetMemento() { final var star = new Star(StarType.SUN, 1, 2); @@ -92,7 +85,5 @@ class StarTest { star.setMemento(firstMemento); assertEquals("sun age: 1 years mass: 2 tons", star.toString()); - } - } diff --git a/metadata-mapping/pom.xml b/metadata-mapping/pom.xml index a50180806..7aa802d7f 100644 --- a/metadata-mapping/pom.xml +++ b/metadata-mapping/pom.xml @@ -37,6 +37,14 @@ metadata-mapping + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine @@ -45,14 +53,17 @@ org.hibernate hibernate-core + 6.6.11.Final javax.xml.bind jaxb-api + 2.4.0-b180830.0359 org.glassfish.jaxb jaxb-runtime + 4.0.5 com.h2database diff --git a/metadata-mapping/src/main/java/com/iluwatar/metamapping/App.java b/metadata-mapping/src/main/java/com/iluwatar/metamapping/App.java index 8d4d7ee83..6b5624ac5 100644 --- a/metadata-mapping/src/main/java/com/iluwatar/metamapping/App.java +++ b/metadata-mapping/src/main/java/com/iluwatar/metamapping/App.java @@ -32,20 +32,17 @@ import lombok.extern.slf4j.Slf4j; import org.hibernate.service.ServiceRegistry; /** - * Metadata Mapping specifies the mapping - * between classes and tables so that - * we could treat a table of any database like a Java class. + * Metadata Mapping specifies the mapping between classes and tables so that we could treat a table + * of any database like a Java class. + * + *

With hibernate, we achieve list/create/update/delete/get operations: 1)Create the H2 Database + * in {@link DatabaseUtil}. 2)Hibernate resolve hibernate.cfg.xml and generate service like + * save/list/get/delete. For learning metadata mapping pattern, we go deeper into Hibernate here: + * a)read properties from hibernate.cfg.xml and mapping from *.hbm.xml b)create session factory to + * generate session interacting with database c)generate session with factory pattern d)create query + * object or use basic api with session, hibernate will convert all query to database query + * according to metadata 3)We encapsulate hibernate service in {@link UserService} for our use. * - *

With hibernate, we achieve list/create/update/delete/get operations: - * 1)Create the H2 Database in {@link DatabaseUtil}. - * 2)Hibernate resolve hibernate.cfg.xml and generate service like save/list/get/delete. - * For learning metadata mapping pattern, we go deeper into Hibernate here: - * a)read properties from hibernate.cfg.xml and mapping from *.hbm.xml - * b)create session factory to generate session interacting with database - * c)generate session with factory pattern - * d)create query object or use basic api with session, - * hibernate will convert all query to database query according to metadata - * 3)We encapsulate hibernate service in {@link UserService} for our use. * @see org.hibernate.cfg.Configuration#configure(String) * @see org.hibernate.cfg.Configuration#buildSessionFactory(ServiceRegistry) * @see org.hibernate.internal.SessionFactoryImpl#openSession() @@ -92,4 +89,4 @@ public class App { final var user3 = new User("WangWu", "ww123"); return List.of(user1, user2, user3); } -} \ No newline at end of file +} diff --git a/metadata-mapping/src/main/java/com/iluwatar/metamapping/model/User.java b/metadata-mapping/src/main/java/com/iluwatar/metamapping/model/User.java index 73a7009f6..7d2275234 100644 --- a/metadata-mapping/src/main/java/com/iluwatar/metamapping/model/User.java +++ b/metadata-mapping/src/main/java/com/iluwatar/metamapping/model/User.java @@ -28,9 +28,7 @@ import lombok.Getter; import lombok.Setter; import lombok.ToString; -/** - * User Entity. - */ +/** User Entity. */ @Setter @Getter @ToString @@ -43,6 +41,7 @@ public class User { /** * Get a user. + * * @param username user name * @param password user password */ @@ -50,4 +49,4 @@ public class User { this.username = username; this.password = password; } -} \ No newline at end of file +} diff --git a/metadata-mapping/src/main/java/com/iluwatar/metamapping/service/UserService.java b/metadata-mapping/src/main/java/com/iluwatar/metamapping/service/UserService.java index cd731f8d0..e1943a6a9 100644 --- a/metadata-mapping/src/main/java/com/iluwatar/metamapping/service/UserService.java +++ b/metadata-mapping/src/main/java/com/iluwatar/metamapping/service/UserService.java @@ -32,15 +32,14 @@ import lombok.extern.slf4j.Slf4j; import org.hibernate.HibernateException; import org.hibernate.SessionFactory; -/** - * Service layer for user. - */ +/** Service layer for user. */ @Slf4j public class UserService { private static final SessionFactory factory = HibernateUtil.getSessionFactory(); /** * List all users. + * * @return list of users */ public List listUser() { @@ -61,6 +60,7 @@ public class UserService { /** * Add a user. + * * @param user user entity * @return user id */ @@ -80,6 +80,7 @@ public class UserService { /** * Update user. + * * @param id user id * @param user new user entity */ @@ -97,6 +98,7 @@ public class UserService { /** * Delete user. + * * @param id user id */ public void deleteUser(Integer id) { @@ -113,6 +115,7 @@ public class UserService { /** * Get user. + * * @param id user id * @return deleted user */ @@ -129,10 +132,8 @@ public class UserService { return user; } - /** - * Close hibernate. - */ + /** Close hibernate. */ public void close() { HibernateUtil.shutdown(); } -} \ No newline at end of file +} diff --git a/metadata-mapping/src/main/java/com/iluwatar/metamapping/utils/DatabaseUtil.java b/metadata-mapping/src/main/java/com/iluwatar/metamapping/utils/DatabaseUtil.java index 5f5dddcbc..9c3c8469d 100644 --- a/metadata-mapping/src/main/java/com/iluwatar/metamapping/utils/DatabaseUtil.java +++ b/metadata-mapping/src/main/java/com/iluwatar/metamapping/utils/DatabaseUtil.java @@ -28,13 +28,12 @@ import java.sql.SQLException; import lombok.extern.slf4j.Slf4j; import org.h2.jdbcx.JdbcDataSource; -/** - * Create h2 database. - */ +/** Create h2 database. */ @Slf4j public class DatabaseUtil { private static final String DB_URL = "jdbc:h2:mem:metamapping"; - private static final String CREATE_SCHEMA_SQL = """ + private static final String CREATE_SCHEMA_SQL = + """ DROP TABLE IF EXISTS `user_account`;CREATE TABLE `user_account` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(255) NOT NULL, @@ -42,9 +41,7 @@ public class DatabaseUtil { PRIMARY KEY (`id`) );"""; - /** - * Hide constructor. - */ + /** Hide constructor. */ private DatabaseUtil() {} static { @@ -57,4 +54,4 @@ public class DatabaseUtil { LOGGER.error("unable to create h2 data source", e); } } -} \ No newline at end of file +} diff --git a/metadata-mapping/src/main/java/com/iluwatar/metamapping/utils/HibernateUtil.java b/metadata-mapping/src/main/java/com/iluwatar/metamapping/utils/HibernateUtil.java index 68d8b4485..54c0b3c36 100644 --- a/metadata-mapping/src/main/java/com/iluwatar/metamapping/utils/HibernateUtil.java +++ b/metadata-mapping/src/main/java/com/iluwatar/metamapping/utils/HibernateUtil.java @@ -29,22 +29,18 @@ import lombok.extern.slf4j.Slf4j; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; -/** - * Manage hibernate. - */ +/** Manage hibernate. */ @Slf4j public class HibernateUtil { - @Getter - private static final SessionFactory sessionFactory = buildSessionFactory(); + @Getter private static final SessionFactory sessionFactory = buildSessionFactory(); - /** - * Hide constructor. - */ + /** Hide constructor. */ private HibernateUtil() {} /** * Build session factory. + * * @return session factory */ private static SessionFactory buildSessionFactory() { @@ -52,12 +48,9 @@ public class HibernateUtil { return new Configuration().configure().buildSessionFactory(); } - /** - * Close session factory. - */ + /** Close session factory. */ public static void shutdown() { // Close caches and connection pools getSessionFactory().close(); } - -} \ No newline at end of file +} diff --git a/metadata-mapping/src/test/java/com/iluwatar/metamapping/AppTest.java b/metadata-mapping/src/test/java/com/iluwatar/metamapping/AppTest.java index 37ba2e09f..2b159b526 100644 --- a/metadata-mapping/src/test/java/com/iluwatar/metamapping/AppTest.java +++ b/metadata-mapping/src/test/java/com/iluwatar/metamapping/AppTest.java @@ -24,20 +24,18 @@ */ package com.iluwatar.metamapping; -import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -/** - * Tests that metadata mapping example runs without errors. - */ +import org.junit.jupiter.api.Test; + +/** Tests that metadata mapping example runs without errors. */ class AppTest { /** - * Issue: Add at least one assertion to this test case. - * Solution: Inserted assertion to check whether the execution of the main method in {@link App#main(String[])} - * throws an exception. + * Issue: Add at least one assertion to this test case. Solution: Inserted assertion to check + * whether the execution of the main method in {@link App#main(String[])} throws an exception. */ @Test void shouldExecuteMetaMappingWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/microservices-aggregrator/aggregator-service/pom.xml b/microservices-aggregrator/aggregator-service/pom.xml index e0f7c2a07..fe8382691 100644 --- a/microservices-aggregrator/aggregator-service/pom.xml +++ b/microservices-aggregrator/aggregator-service/pom.xml @@ -38,6 +38,7 @@ org.springframework spring-webmvc + 6.2.5 org.springframework.boot diff --git a/microservices-aggregrator/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/Aggregator.java b/microservices-aggregrator/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/Aggregator.java index 2e429bf08..0fd19e7ef 100644 --- a/microservices-aggregrator/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/Aggregator.java +++ b/microservices-aggregrator/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/Aggregator.java @@ -37,11 +37,9 @@ import org.springframework.web.bind.annotation.RestController; @RestController public class Aggregator { - @Resource - private ProductInformationClient informationClient; + @Resource private ProductInformationClient informationClient; - @Resource - private ProductInventoryClient inventoryClient; + @Resource private ProductInventoryClient inventoryClient; /** * Retrieves product data. @@ -55,13 +53,12 @@ public class Aggregator { var productTitle = informationClient.getProductTitle(); var productInventory = inventoryClient.getProductInventories(); - //Fallback to error message + // Fallback to error message product.setTitle(requireNonNullElse(productTitle, "Error: Fetching Product Title Failed")); - //Fallback to default error inventory + // Fallback to default error inventory product.setProductInventories(requireNonNullElse(productInventory, -1)); return product; } - } diff --git a/microservices-aggregrator/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/App.java b/microservices-aggregrator/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/App.java index 95f7c587d..26424eb9c 100644 --- a/microservices-aggregrator/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/App.java +++ b/microservices-aggregrator/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/App.java @@ -27,9 +27,7 @@ package com.iluwatar.aggregator.microservices; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -/** - * Spring Boot EntryPoint Class. - */ +/** Spring Boot EntryPoint Class. */ @SpringBootApplication public class App { diff --git a/microservices-aggregrator/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/Product.java b/microservices-aggregrator/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/Product.java index 56dc0155f..66626d814 100644 --- a/microservices-aggregrator/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/Product.java +++ b/microservices-aggregrator/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/Product.java @@ -27,22 +27,14 @@ package com.iluwatar.aggregator.microservices; import lombok.Getter; import lombok.Setter; -/** - * Encapsulates all the data for a Product that clients will request. - */ +/** Encapsulates all the data for a Product that clients will request. */ @Getter @Setter public class Product { - /** - * The title of the product. - */ + /** The title of the product. */ private String title; - - /** - * The inventories of the product. - */ + /** The inventories of the product. */ private int productInventories; - } diff --git a/microservices-aggregrator/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInformationClient.java b/microservices-aggregrator/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInformationClient.java index 1260e4e30..d183656ed 100644 --- a/microservices-aggregrator/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInformationClient.java +++ b/microservices-aggregrator/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInformationClient.java @@ -24,11 +24,8 @@ */ package com.iluwatar.aggregator.microservices; -/** - * Interface for the Information micro-service. - */ +/** Interface for the Information micro-service. */ public interface ProductInformationClient { String getProductTitle(); - } diff --git a/microservices-aggregrator/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInformationClientImpl.java b/microservices-aggregrator/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInformationClientImpl.java index a41627cb3..2bda000b3 100644 --- a/microservices-aggregrator/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInformationClientImpl.java +++ b/microservices-aggregrator/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInformationClientImpl.java @@ -32,19 +32,18 @@ import java.net.http.HttpResponse; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; -/** - * An adapter to communicate with information micro-service. - */ +/** An adapter to communicate with information micro-service. */ @Slf4j @Component public class ProductInformationClientImpl implements ProductInformationClient { @Override public String getProductTitle() { - var request = HttpRequest.newBuilder() - .GET() - .uri(URI.create("http://localhost:51515/information")) - .build(); + var request = + HttpRequest.newBuilder() + .GET() + .uri(URI.create("http://localhost:51515/information")) + .build(); var client = HttpClient.newHttpClient(); try { var httpResponse = client.send(request, HttpResponse.BodyHandlers.ofString()); diff --git a/microservices-aggregrator/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInventoryClient.java b/microservices-aggregrator/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInventoryClient.java index 4e0ffe2ed..02ebac873 100644 --- a/microservices-aggregrator/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInventoryClient.java +++ b/microservices-aggregrator/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInventoryClient.java @@ -24,9 +24,7 @@ */ package com.iluwatar.aggregator.microservices; -/** - * Interface to Inventory micro-service. - */ +/** Interface to Inventory micro-service. */ public interface ProductInventoryClient { Integer getProductInventories(); diff --git a/microservices-aggregrator/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInventoryClientImpl.java b/microservices-aggregrator/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInventoryClientImpl.java index 7549693d0..d5a918e46 100644 --- a/microservices-aggregrator/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInventoryClientImpl.java +++ b/microservices-aggregrator/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInventoryClientImpl.java @@ -32,9 +32,7 @@ import java.net.http.HttpResponse; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; -/** - * An adapter to communicate with inventory micro-service. - */ +/** An adapter to communicate with inventory micro-service. */ @Slf4j @Component public class ProductInventoryClientImpl implements ProductInventoryClient { @@ -43,10 +41,11 @@ public class ProductInventoryClientImpl implements ProductInventoryClient { public Integer getProductInventories() { var response = ""; - var request = HttpRequest.newBuilder() - .GET() - .uri(URI.create("http://localhost:51516/inventories")) - .build(); + var request = + HttpRequest.newBuilder() + .GET() + .uri(URI.create("http://localhost:51516/inventories")) + .build(); var client = HttpClient.newHttpClient(); try { var httpResponse = client.send(request, HttpResponse.BodyHandlers.ofString()); diff --git a/microservices-aggregrator/aggregator-service/src/test/java/com/iluwatar/aggregator/microservices/AggregatorTest.java b/microservices-aggregrator/aggregator-service/src/test/java/com/iluwatar/aggregator/microservices/AggregatorTest.java index 2ac246d9f..914e15dad 100644 --- a/microservices-aggregrator/aggregator-service/src/test/java/com/iluwatar/aggregator/microservices/AggregatorTest.java +++ b/microservices-aggregrator/aggregator-service/src/test/java/com/iluwatar/aggregator/microservices/AggregatorTest.java @@ -24,37 +24,30 @@ */ package com.iluwatar.aggregator.microservices; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.when; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.Mockito.when; - -/** - * Test Aggregation of domain objects - */ +/** Test Aggregation of domain objects */ class AggregatorTest { - @InjectMocks - private Aggregator aggregator; + @InjectMocks private Aggregator aggregator; - @Mock - private ProductInformationClient informationClient; + @Mock private ProductInformationClient informationClient; - @Mock - private ProductInventoryClient inventoryClient; + @Mock private ProductInventoryClient inventoryClient; @BeforeEach void setup() { MockitoAnnotations.openMocks(this); } - /** - * Tests getting the data for a desktop client - */ + /** Tests getting the data for a desktop client */ @Test void testGetProduct() { var title = "The Product Title."; @@ -68,5 +61,4 @@ class AggregatorTest { assertEquals(title, testProduct.getTitle()); assertEquals(inventories, testProduct.getProductInventories()); } - } diff --git a/microservices-aggregrator/information-microservice/pom.xml b/microservices-aggregrator/information-microservice/pom.xml index 69e588bd5..5b27df625 100644 --- a/microservices-aggregrator/information-microservice/pom.xml +++ b/microservices-aggregrator/information-microservice/pom.xml @@ -38,6 +38,7 @@ org.springframework spring-webmvc + 6.2.5 org.springframework.boot diff --git a/microservices-aggregrator/information-microservice/src/main/java/com/iluwatar/information/microservice/InformationApplication.java b/microservices-aggregrator/information-microservice/src/main/java/com/iluwatar/information/microservice/InformationApplication.java index 6c4905340..68ff8856e 100644 --- a/microservices-aggregrator/information-microservice/src/main/java/com/iluwatar/information/microservice/InformationApplication.java +++ b/microservices-aggregrator/information-microservice/src/main/java/com/iluwatar/information/microservice/InformationApplication.java @@ -27,9 +27,7 @@ package com.iluwatar.information.microservice; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -/** - * Inventory Application starts container (Spring Boot) and exposes the Inventory micro-service. - */ +/** Inventory Application starts container (Spring Boot) and exposes the Inventory micro-service. */ @SpringBootApplication public class InformationApplication { diff --git a/microservices-aggregrator/information-microservice/src/main/java/com/iluwatar/information/microservice/InformationController.java b/microservices-aggregrator/information-microservice/src/main/java/com/iluwatar/information/microservice/InformationController.java index 88d11e5f4..cc826e497 100644 --- a/microservices-aggregrator/information-microservice/src/main/java/com/iluwatar/information/microservice/InformationController.java +++ b/microservices-aggregrator/information-microservice/src/main/java/com/iluwatar/information/microservice/InformationController.java @@ -27,9 +27,7 @@ package com.iluwatar.information.microservice; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; -/** - * Controller providing endpoints to retrieve information about products. - */ +/** Controller providing endpoints to retrieve information about products. */ @RestController public class InformationController { diff --git a/microservices-aggregrator/information-microservice/src/test/java/com/iluwatar/information/microservice/InformationControllerTest.java b/microservices-aggregrator/information-microservice/src/test/java/com/iluwatar/information/microservice/InformationControllerTest.java index d85e1ce0c..3f344d9d8 100644 --- a/microservices-aggregrator/information-microservice/src/test/java/com/iluwatar/information/microservice/InformationControllerTest.java +++ b/microservices-aggregrator/information-microservice/src/test/java/com/iluwatar/information/microservice/InformationControllerTest.java @@ -24,13 +24,11 @@ */ package com.iluwatar.information.microservice; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; -/** - * Test for Information Rest Controller - */ +import org.junit.jupiter.api.Test; + +/** Test for Information Rest Controller */ class InformationControllerTest { @Test @@ -39,5 +37,4 @@ class InformationControllerTest { var title = infoController.getProductTitle(); assertEquals("The Product Title.", title); } - } diff --git a/microservices-aggregrator/inventory-microservice/pom.xml b/microservices-aggregrator/inventory-microservice/pom.xml index 4d563a2a1..64203b09e 100644 --- a/microservices-aggregrator/inventory-microservice/pom.xml +++ b/microservices-aggregrator/inventory-microservice/pom.xml @@ -38,6 +38,7 @@ org.springframework spring-webmvc + 6.2.5 org.springframework.boot diff --git a/microservices-aggregrator/inventory-microservice/src/main/java/com/iluwatar/inventory/microservice/InventoryApplication.java b/microservices-aggregrator/inventory-microservice/src/main/java/com/iluwatar/inventory/microservice/InventoryApplication.java index 7d1762655..5627c37c9 100644 --- a/microservices-aggregrator/inventory-microservice/src/main/java/com/iluwatar/inventory/microservice/InventoryApplication.java +++ b/microservices-aggregrator/inventory-microservice/src/main/java/com/iluwatar/inventory/microservice/InventoryApplication.java @@ -27,14 +27,11 @@ package com.iluwatar.inventory.microservice; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -/** - * Inventory Application starts container (Spring Boot) and exposes the Inventory micro-service. - */ +/** Inventory Application starts container (Spring Boot) and exposes the Inventory micro-service. */ @SpringBootApplication public class InventoryApplication { public static void main(String[] args) { SpringApplication.run(InventoryApplication.class, args); } - } diff --git a/microservices-aggregrator/inventory-microservice/src/main/java/com/iluwatar/inventory/microservice/InventoryController.java b/microservices-aggregrator/inventory-microservice/src/main/java/com/iluwatar/inventory/microservice/InventoryController.java index 374da55c6..bf5abd510 100644 --- a/microservices-aggregrator/inventory-microservice/src/main/java/com/iluwatar/inventory/microservice/InventoryController.java +++ b/microservices-aggregrator/inventory-microservice/src/main/java/com/iluwatar/inventory/microservice/InventoryController.java @@ -27,9 +27,7 @@ package com.iluwatar.inventory.microservice; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; -/** - * Controller providing endpoints to retrieve product inventories. - */ +/** Controller providing endpoints to retrieve product inventories. */ @RestController public class InventoryController { @@ -42,5 +40,4 @@ public class InventoryController { public int getProductInventories() { return 5; } - } diff --git a/microservices-aggregrator/inventory-microservice/src/test/java/com/iluwatar/inventory/microservice/InventoryControllerTest.java b/microservices-aggregrator/inventory-microservice/src/test/java/com/iluwatar/inventory/microservice/InventoryControllerTest.java index 1bb692042..27b41594d 100644 --- a/microservices-aggregrator/inventory-microservice/src/test/java/com/iluwatar/inventory/microservice/InventoryControllerTest.java +++ b/microservices-aggregrator/inventory-microservice/src/test/java/com/iluwatar/inventory/microservice/InventoryControllerTest.java @@ -24,13 +24,11 @@ */ package com.iluwatar.inventory.microservice; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; -/** - * Test Inventory Rest Controller - */ +import org.junit.jupiter.api.Test; + +/** Test Inventory Rest Controller */ class InventoryControllerTest { @Test diff --git a/microservices-aggregrator/pom.xml b/microservices-aggregrator/pom.xml index 1463af072..bf1edb1c8 100644 --- a/microservices-aggregrator/pom.xml +++ b/microservices-aggregrator/pom.xml @@ -34,17 +34,6 @@ 4.0.0 microservices-aggregrator pom - - - - org.springframework.boot - spring-boot-dependencies - pom - 3.2.4 - import - - - information-microservice aggregator-service diff --git a/microservices-api-gateway/api-gateway-service/pom.xml b/microservices-api-gateway/api-gateway-service/pom.xml index f1133ec3c..b84bebe6f 100644 --- a/microservices-api-gateway/api-gateway-service/pom.xml +++ b/microservices-api-gateway/api-gateway-service/pom.xml @@ -38,6 +38,7 @@ org.springframework spring-webmvc + 6.2.5 org.springframework.boot diff --git a/microservices-api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/ApiGateway.java b/microservices-api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/ApiGateway.java index b7ab7b404..c41105097 100644 --- a/microservices-api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/ApiGateway.java +++ b/microservices-api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/ApiGateway.java @@ -34,11 +34,9 @@ import org.springframework.web.bind.annotation.RestController; @RestController public class ApiGateway { - @Resource - private ImageClient imageClient; + @Resource private ImageClient imageClient; - @Resource - private PriceClient priceClient; + @Resource private PriceClient priceClient; /** * Retrieves product information that desktop clients need. diff --git a/microservices-api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/App.java b/microservices-api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/App.java index 9ccf8696a..4754ba0a5 100644 --- a/microservices-api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/App.java +++ b/microservices-api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/App.java @@ -36,14 +36,14 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; * sometime in the future) or if the location (host and port) of a microservice changes, then every * client that makes use of those microservices must be updated. * - *

The intent of the API Gateway pattern is to alleviate some of these issues. In the API - * Gateway pattern, an additional entity (the API Gateway) is placed between the client and the + *

The intent of the API Gateway pattern is to alleviate some of these issues. In the API Gateway + * pattern, an additional entity (the API Gateway) is placed between the client and the * microservices. The job of the API Gateway is to aggregate the calls to the microservices. Rather * than the client calling each microservice individually, the client calls the API Gateway a single * time. The API Gateway then calls each of the microservices that the client needs. * - *

This implementation shows what the API Gateway pattern could look like for an e-commerce - * site. The {@link ApiGateway} makes calls to the Image and Price microservices using the {@link + *

This implementation shows what the API Gateway pattern could look like for an e-commerce site. + * The {@link ApiGateway} makes calls to the Image and Price microservices using the {@link * ImageClientImpl} and {@link PriceClientImpl} respectively. Customers viewing the site on a * desktop device can see both price information and an image of a product, so the {@link * ApiGateway} calls both of the microservices and aggregates the data in the {@link DesktopProduct} diff --git a/microservices-api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/DesktopProduct.java b/microservices-api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/DesktopProduct.java index 85917dc1c..40cc795fd 100644 --- a/microservices-api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/DesktopProduct.java +++ b/microservices-api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/DesktopProduct.java @@ -27,21 +27,14 @@ package com.iluwatar.api.gateway; import lombok.Getter; import lombok.Setter; -/** - * Encapsulates all of the information that a desktop client needs to display a product. - */ +/** Encapsulates all of the information that a desktop client needs to display a product. */ @Getter @Setter public class DesktopProduct { - /** - * The price of the product. - */ + /** The price of the product. */ private String price; - /** - * The path to the image of the product. - */ + /** The path to the image of the product. */ private String imagePath; - } diff --git a/microservices-api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/ImageClient.java b/microservices-api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/ImageClient.java index 742502714..9f7e08c89 100644 --- a/microservices-api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/ImageClient.java +++ b/microservices-api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/ImageClient.java @@ -24,9 +24,7 @@ */ package com.iluwatar.api.gateway; -/** - * An interface used to communicate with the Image microservice. - */ +/** An interface used to communicate with the Image microservice. */ public interface ImageClient { String getImagePath(); } diff --git a/microservices-api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/ImageClientImpl.java b/microservices-api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/ImageClientImpl.java index 86008b74a..4e618b2aa 100644 --- a/microservices-api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/ImageClientImpl.java +++ b/microservices-api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/ImageClientImpl.java @@ -33,9 +33,7 @@ import java.net.http.HttpResponse.BodyHandlers; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; -/** - * An adapter to communicate with the Image microservice. - */ +/** An adapter to communicate with the Image microservice. */ @Slf4j @Component public class ImageClientImpl implements ImageClient { @@ -48,10 +46,8 @@ public class ImageClientImpl implements ImageClient { @Override public String getImagePath() { var httpClient = HttpClient.newHttpClient(); - var httpGet = HttpRequest.newBuilder() - .GET() - .uri(URI.create("http://localhost:50005/image-path")) - .build(); + var httpGet = + HttpRequest.newBuilder().GET().uri(URI.create("http://localhost:50005/image-path")).build(); try { LOGGER.info("Sending request to fetch image path"); diff --git a/microservices-api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/MobileProduct.java b/microservices-api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/MobileProduct.java index f621da1a5..ed42248ea 100644 --- a/microservices-api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/MobileProduct.java +++ b/microservices-api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/MobileProduct.java @@ -27,14 +27,10 @@ package com.iluwatar.api.gateway; import lombok.Getter; import lombok.Setter; -/** - * Encapsulates all of the information that mobile client needs to display a product. - */ +/** Encapsulates all of the information that mobile client needs to display a product. */ @Getter @Setter public class MobileProduct { - /** - * The price of the product. - */ + /** The price of the product. */ private String price; } diff --git a/microservices-api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/PriceClient.java b/microservices-api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/PriceClient.java index 5294dbd6d..003fa478b 100644 --- a/microservices-api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/PriceClient.java +++ b/microservices-api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/PriceClient.java @@ -24,9 +24,7 @@ */ package com.iluwatar.api.gateway; -/** - * An interface used to communicate with the Price microservice. - */ +/** An interface used to communicate with the Price microservice. */ public interface PriceClient { String getPrice(); } diff --git a/microservices-api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/PriceClientImpl.java b/microservices-api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/PriceClientImpl.java index b94bdb4a1..47fb0617d 100644 --- a/microservices-api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/PriceClientImpl.java +++ b/microservices-api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/PriceClientImpl.java @@ -33,10 +33,7 @@ import java.net.http.HttpResponse.BodyHandlers; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; - -/** - * An adapter to communicate with the Price microservice. - */ +/** An adapter to communicate with the Price microservice. */ @Slf4j @Component public class PriceClientImpl implements PriceClient { @@ -49,10 +46,8 @@ public class PriceClientImpl implements PriceClient { @Override public String getPrice() { var httpClient = HttpClient.newHttpClient(); - var httpGet = HttpRequest.newBuilder() - .GET() - .uri(URI.create("http://localhost:50006/price")) - .build(); + var httpGet = + HttpRequest.newBuilder().GET().uri(URI.create("http://localhost:50006/price")).build(); try { LOGGER.info("Sending request to fetch price info"); diff --git a/microservices-api-gateway/api-gateway-service/src/test/java/com/iluwatar/api/gateway/ApiGatewayTest.java b/microservices-api-gateway/api-gateway-service/src/test/java/com/iluwatar/api/gateway/ApiGatewayTest.java index 0f1fa938e..f177512f5 100644 --- a/microservices-api-gateway/api-gateway-service/src/test/java/com/iluwatar/api/gateway/ApiGatewayTest.java +++ b/microservices-api-gateway/api-gateway-service/src/test/java/com/iluwatar/api/gateway/ApiGatewayTest.java @@ -33,28 +33,21 @@ import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; -/** - * Test API Gateway Pattern - */ +/** Test API Gateway Pattern */ class ApiGatewayTest { - @InjectMocks - private ApiGateway apiGateway; + @InjectMocks private ApiGateway apiGateway; - @Mock - private ImageClient imageClient; + @Mock private ImageClient imageClient; - @Mock - private PriceClient priceClient; + @Mock private PriceClient priceClient; @BeforeEach void setup() { MockitoAnnotations.openMocks(this); } - /** - * Tests getting the data for a desktop client - */ + /** Tests getting the data for a desktop client */ @Test void testGetProductDesktop() { var imagePath = "/product-image.png"; @@ -68,9 +61,7 @@ class ApiGatewayTest { assertEquals(imagePath, desktopProduct.getImagePath()); } - /** - * Tests getting the data for a mobile client - */ + /** Tests getting the data for a mobile client */ @Test void testGetProductMobile() { var price = "20"; diff --git a/microservices-api-gateway/image-microservice/pom.xml b/microservices-api-gateway/image-microservice/pom.xml index 7f27eb515..7c08fe2ec 100644 --- a/microservices-api-gateway/image-microservice/pom.xml +++ b/microservices-api-gateway/image-microservice/pom.xml @@ -38,6 +38,7 @@ org.springframework spring-webmvc + 6.2.5 org.springframework.boot diff --git a/microservices-api-gateway/image-microservice/src/main/java/com/iluwatar/image/microservice/ImageController.java b/microservices-api-gateway/image-microservice/src/main/java/com/iluwatar/image/microservice/ImageController.java index 0594a4fa9..a737f0b8d 100644 --- a/microservices-api-gateway/image-microservice/src/main/java/com/iluwatar/image/microservice/ImageController.java +++ b/microservices-api-gateway/image-microservice/src/main/java/com/iluwatar/image/microservice/ImageController.java @@ -28,10 +28,7 @@ import lombok.extern.slf4j.Slf4j; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; - -/** - * Exposes the Image microservice's endpoints. - */ +/** Exposes the Image microservice's endpoints. */ @Slf4j @RestController public class ImageController { diff --git a/microservices-api-gateway/image-microservice/src/test/java/com/iluwatar/image/microservice/ImageControllerTest.java b/microservices-api-gateway/image-microservice/src/test/java/com/iluwatar/image/microservice/ImageControllerTest.java index bfb0af75a..f2ff0c747 100644 --- a/microservices-api-gateway/image-microservice/src/test/java/com/iluwatar/image/microservice/ImageControllerTest.java +++ b/microservices-api-gateway/image-microservice/src/test/java/com/iluwatar/image/microservice/ImageControllerTest.java @@ -24,13 +24,11 @@ */ package com.iluwatar.image.microservice; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; -/** - * Test for Image Rest Controller - */ +import org.junit.jupiter.api.Test; + +/** Test for Image Rest Controller */ class ImageControllerTest { @Test diff --git a/microservices-api-gateway/pom.xml b/microservices-api-gateway/pom.xml index 762295876..18022d957 100644 --- a/microservices-api-gateway/pom.xml +++ b/microservices-api-gateway/pom.xml @@ -34,17 +34,6 @@ 4.0.0 microservices-api-gateway pom - - - - org.springframework.boot - spring-boot-dependencies - pom - 3.2.4 - import - - - image-microservice price-microservice diff --git a/microservices-api-gateway/price-microservice/pom.xml b/microservices-api-gateway/price-microservice/pom.xml index 6dedbd398..8e95948af 100644 --- a/microservices-api-gateway/price-microservice/pom.xml +++ b/microservices-api-gateway/price-microservice/pom.xml @@ -38,6 +38,7 @@ org.springframework spring-webmvc + 6.2.5 org.springframework.boot diff --git a/microservices-api-gateway/price-microservice/src/main/java/com/iluwatar/price/microservice/PriceController.java b/microservices-api-gateway/price-microservice/src/main/java/com/iluwatar/price/microservice/PriceController.java index 9b922a502..695d3aadb 100644 --- a/microservices-api-gateway/price-microservice/src/main/java/com/iluwatar/price/microservice/PriceController.java +++ b/microservices-api-gateway/price-microservice/src/main/java/com/iluwatar/price/microservice/PriceController.java @@ -28,10 +28,7 @@ import lombok.RequiredArgsConstructor; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; - -/** - * Exposes the Price microservice's endpoints. - */ +/** Exposes the Price microservice's endpoints. */ @RestController @RequiredArgsConstructor public class PriceController { diff --git a/microservices-api-gateway/price-microservice/src/main/java/com/iluwatar/price/microservice/PriceService.java b/microservices-api-gateway/price-microservice/src/main/java/com/iluwatar/price/microservice/PriceService.java index 1d09c5311..253bab4e5 100644 --- a/microservices-api-gateway/price-microservice/src/main/java/com/iluwatar/price/microservice/PriceService.java +++ b/microservices-api-gateway/price-microservice/src/main/java/com/iluwatar/price/microservice/PriceService.java @@ -24,9 +24,7 @@ */ package com.iluwatar.price.microservice; -/** - * Service to get a product's price. - */ +/** Service to get a product's price. */ public interface PriceService { /** diff --git a/microservices-api-gateway/price-microservice/src/main/java/com/iluwatar/price/microservice/PriceServiceImpl.java b/microservices-api-gateway/price-microservice/src/main/java/com/iluwatar/price/microservice/PriceServiceImpl.java index c4b8aa105..1338313fe 100644 --- a/microservices-api-gateway/price-microservice/src/main/java/com/iluwatar/price/microservice/PriceServiceImpl.java +++ b/microservices-api-gateway/price-microservice/src/main/java/com/iluwatar/price/microservice/PriceServiceImpl.java @@ -27,16 +27,12 @@ package com.iluwatar.price.microservice; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; -/** - * {@inheritDoc} - */ +/** {@inheritDoc} */ @Service @Slf4j public class PriceServiceImpl implements PriceService { - /** - * {@inheritDoc} - */ + /** {@inheritDoc} */ @Override public String getPrice() { LOGGER.info("Successfully found price info"); diff --git a/microservices-api-gateway/price-microservice/src/test/java/com/iluwatar/price/microservice/PriceControllerTest.java b/microservices-api-gateway/price-microservice/src/test/java/com/iluwatar/price/microservice/PriceControllerTest.java index 91c9b36be..eeaa0c28d 100644 --- a/microservices-api-gateway/price-microservice/src/test/java/com/iluwatar/price/microservice/PriceControllerTest.java +++ b/microservices-api-gateway/price-microservice/src/test/java/com/iluwatar/price/microservice/PriceControllerTest.java @@ -24,13 +24,11 @@ */ package com.iluwatar.price.microservice; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; -/** - * Test for Price Rest Controller - */ +import org.junit.jupiter.api.Test; + +/** Test for Price Rest Controller */ class PriceControllerTest { @Test diff --git a/microservices-api-gateway/price-microservice/src/test/java/com/iluwatar/price/microservice/PriceServiceTest.java b/microservices-api-gateway/price-microservice/src/test/java/com/iluwatar/price/microservice/PriceServiceTest.java index c6e87e7c7..830ac7d18 100644 --- a/microservices-api-gateway/price-microservice/src/test/java/com/iluwatar/price/microservice/PriceServiceTest.java +++ b/microservices-api-gateway/price-microservice/src/test/java/com/iluwatar/price/microservice/PriceServiceTest.java @@ -24,13 +24,11 @@ */ package com.iluwatar.price.microservice; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; -/** - * Test for Price Service - */ +import org.junit.jupiter.api.Test; + +/** Test for Price Service */ class PriceServiceTest { @Test diff --git a/microservices-client-side-ui-composition/pom.xml b/microservices-client-side-ui-composition/pom.xml index b30a86007..2d5644a14 100644 --- a/microservices-client-side-ui-composition/pom.xml +++ b/microservices-client-side-ui-composition/pom.xml @@ -39,6 +39,14 @@ microservices-client-side-ui-composition + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/microservices-client-side-ui-composition/src/main/java/com/iluwatar/clientsideuicomposition/ApiGateway.java b/microservices-client-side-ui-composition/src/main/java/com/iluwatar/clientsideuicomposition/ApiGateway.java index 5103d455a..6fc1cc643 100644 --- a/microservices-client-side-ui-composition/src/main/java/com/iluwatar/clientsideuicomposition/ApiGateway.java +++ b/microservices-client-side-ui-composition/src/main/java/com/iluwatar/clientsideuicomposition/ApiGateway.java @@ -28,9 +28,8 @@ import java.util.HashMap; import java.util.Map; /** - * ApiGateway class acts as a dynamic routing mechanism that forwards client - * requests to the appropriate frontend components based on dynamically - * registered routes. + * ApiGateway class acts as a dynamic routing mechanism that forwards client requests to the + * appropriate frontend components based on dynamically registered routes. * *

This allows for flexible, runtime-defined routing without hardcoding specific paths. */ @@ -43,7 +42,7 @@ public class ApiGateway { /** * Registers a route dynamically at runtime. * - * @param path the path to access the component (e.g., "/products") + * @param path the path to access the component (e.g., "/products") * @param component the frontend component to be accessed at the given path */ public void registerRoute(String path, FrontendComponent component) { @@ -53,14 +52,14 @@ public class ApiGateway { /** * Handles a client request by routing it to the appropriate frontend component. * - *

This method dynamically handles parameters passed with the request, which - * allows the frontend components to respond based on those parameters. + *

This method dynamically handles parameters passed with the request, which allows the + * frontend components to respond based on those parameters. * - * @param path the path for which the request is made (e.g., "/products", "/cart") - * @param params a map of parameters that might influence the data fetching logic - * (e.g., filters, userId, categories, etc.) - * @return the data fetched from the appropriate component or "404 Not Found" - * if the path is not registered + * @param path the path for which the request is made (e.g., "/products", "/cart") + * @param params a map of parameters that might influence the data fetching logic (e.g., filters, + * userId, categories, etc.) + * @return the data fetched from the appropriate component or "404 Not Found" if the path is not + * registered */ public String handleRequest(String path, Map params) { if (routes.containsKey(path)) { diff --git a/microservices-client-side-ui-composition/src/main/java/com/iluwatar/clientsideuicomposition/CartFrontend.java b/microservices-client-side-ui-composition/src/main/java/com/iluwatar/clientsideuicomposition/CartFrontend.java index f068a8fe9..d2916408b 100644 --- a/microservices-client-side-ui-composition/src/main/java/com/iluwatar/clientsideuicomposition/CartFrontend.java +++ b/microservices-client-side-ui-composition/src/main/java/com/iluwatar/clientsideuicomposition/CartFrontend.java @@ -27,18 +27,16 @@ package com.iluwatar.clientsideuicomposition; import java.util.Map; /** - * CartFrontend is a concrete implementation of FrontendComponent - * that simulates fetching shopping cart data based on the user. + * CartFrontend is a concrete implementation of FrontendComponent that simulates fetching shopping + * cart data based on the user. */ public class CartFrontend extends FrontendComponent { /** - * Fetches the current state of the shopping cart based on dynamic parameters - * like user ID. + * Fetches the current state of the shopping cart based on dynamic parameters like user ID. * * @param params parameters that influence the cart data, e.g., "userId" - * @return a string representing the items in the shopping cart for a given - * user + * @return a string representing the items in the shopping cart for a given user */ @Override protected String getData(Map params) { diff --git a/microservices-client-side-ui-composition/src/main/java/com/iluwatar/clientsideuicomposition/ClientSideIntegrator.java b/microservices-client-side-ui-composition/src/main/java/com/iluwatar/clientsideuicomposition/ClientSideIntegrator.java index 9265a4ba3..ca99747a7 100644 --- a/microservices-client-side-ui-composition/src/main/java/com/iluwatar/clientsideuicomposition/ClientSideIntegrator.java +++ b/microservices-client-side-ui-composition/src/main/java/com/iluwatar/clientsideuicomposition/ClientSideIntegrator.java @@ -28,9 +28,8 @@ import java.util.Map; import lombok.extern.slf4j.Slf4j; /** - * ClientSideIntegrator class simulates the client-side integration layer that - * dynamically assembles various frontend components into a cohesive user - * interface. + * ClientSideIntegrator class simulates the client-side integration layer that dynamically assembles + * various frontend components into a cohesive user interface. */ @Slf4j public class ClientSideIntegrator { @@ -38,19 +37,17 @@ public class ClientSideIntegrator { private final ApiGateway apiGateway; /** - * Constructor that accepts an instance of ApiGateway to handle dynamic - * routing. + * Constructor that accepts an instance of ApiGateway to handle dynamic routing. * - * @param apiGateway the gateway that routes requests to different frontend - * components + * @param apiGateway the gateway that routes requests to different frontend components */ public ClientSideIntegrator(ApiGateway apiGateway) { this.apiGateway = apiGateway; } /** - * Composes the user interface dynamically by fetching data from different - * frontend components based on provided parameters. + * Composes the user interface dynamically by fetching data from different frontend components + * based on provided parameters. * * @param path the route of the frontend component * @param params a map of dynamic parameters to influence the data fetching diff --git a/microservices-client-side-ui-composition/src/main/java/com/iluwatar/clientsideuicomposition/FrontendComponent.java b/microservices-client-side-ui-composition/src/main/java/com/iluwatar/clientsideuicomposition/FrontendComponent.java index 1602e3482..70399c318 100644 --- a/microservices-client-side-ui-composition/src/main/java/com/iluwatar/clientsideuicomposition/FrontendComponent.java +++ b/microservices-client-side-ui-composition/src/main/java/com/iluwatar/clientsideuicomposition/FrontendComponent.java @@ -28,16 +28,16 @@ import java.util.Map; import java.util.Random; /** - * FrontendComponent is an abstract class representing an independent frontend - * component that fetches data dynamically based on the provided parameters. + * FrontendComponent is an abstract class representing an independent frontend component that + * fetches data dynamically based on the provided parameters. */ public abstract class FrontendComponent { public static final Random random = new Random(); /** - * Simulates asynchronous data fetching by introducing a random delay and - * then fetching the data based on dynamic input. + * Simulates asynchronous data fetching by introducing a random delay and then fetching the data + * based on dynamic input. * * @param params a map of parameters that may affect the data fetching logic * @return the data fetched by the frontend component @@ -54,8 +54,7 @@ public abstract class FrontendComponent { } /** - * Abstract method to be implemented by subclasses to return data based on - * parameters. + * Abstract method to be implemented by subclasses to return data based on parameters. * * @param params a map of parameters that may affect the data fetching logic * @return the data for this specific component diff --git a/microservices-client-side-ui-composition/src/main/java/com/iluwatar/clientsideuicomposition/ProductFrontend.java b/microservices-client-side-ui-composition/src/main/java/com/iluwatar/clientsideuicomposition/ProductFrontend.java index a3c4026fc..157f2aef3 100644 --- a/microservices-client-side-ui-composition/src/main/java/com/iluwatar/clientsideuicomposition/ProductFrontend.java +++ b/microservices-client-side-ui-composition/src/main/java/com/iluwatar/clientsideuicomposition/ProductFrontend.java @@ -27,8 +27,8 @@ package com.iluwatar.clientsideuicomposition; import java.util.Map; /** - * ProductFrontend is a concrete implementation of FrontendComponent - * that simulates fetching dynamic product data. + * ProductFrontend is a concrete implementation of FrontendComponent that simulates fetching dynamic + * product data. */ public class ProductFrontend extends FrontendComponent { @@ -41,8 +41,6 @@ public class ProductFrontend extends FrontendComponent { @Override protected String getData(Map params) { String category = params.getOrDefault("category", "all"); - return "Product List for category '" - + category - + "': [Product 1, Product 2, Product 3]"; + return "Product List for category '" + category + "': [Product 1, Product 2, Product 3]"; } } diff --git a/microservices-client-side-ui-composition/src/test/java/com/iluwatar/clientsideuicomposition/ClientSideCompositionTest.java b/microservices-client-side-ui-composition/src/test/java/com/iluwatar/clientsideuicomposition/ClientSideCompositionTest.java index b005d33b1..be5aef2f7 100644 --- a/microservices-client-side-ui-composition/src/test/java/com/iluwatar/clientsideuicomposition/ClientSideCompositionTest.java +++ b/microservices-client-side-ui-composition/src/test/java/com/iluwatar/clientsideuicomposition/ClientSideCompositionTest.java @@ -24,21 +24,19 @@ */ package com.iluwatar.clientsideuicomposition; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.HashMap; import java.util.Map; - -import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.Test; /** - * ClientSideCompositionTest contains unit tests to validate dynamic route registration and UI composition. + * ClientSideCompositionTest contains unit tests to validate dynamic route registration and UI + * composition. */ class ClientSideCompositionTest { - /** - * Tests dynamic registration of frontend components and dynamic composition of UI. - */ + /** Tests dynamic registration of frontend components and dynamic composition of UI. */ @Test void testClientSideUIComposition() { // Create API Gateway and dynamically register frontend components diff --git a/microservices-distributed-tracing/order-microservice/src/main/java/com/iluwatar/order/microservice/Main.java b/microservices-distributed-tracing/order-microservice/src/main/java/com/iluwatar/order/microservice/Main.java index 2b4d3f41f..b6b6da79f 100644 --- a/microservices-distributed-tracing/order-microservice/src/main/java/com/iluwatar/order/microservice/Main.java +++ b/microservices-distributed-tracing/order-microservice/src/main/java/com/iluwatar/order/microservice/Main.java @@ -52,10 +52,9 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; * {@code docker run -d -p 9411:9411 --name zipkin openzipkin/zipkin } * * - *

Start Zipkin with the command above. Once Zipkin is running, you can - * access the Zipkin UI at `...` - * to view the tracing logs and analyze the request flows across your microservices. - * + *

Start Zipkin with the command above. Once Zipkin is running, you can access the Zipkin UI at + * `...` to view the tracing logs and analyze the request flows + * across your microservices. * *

To place an order and generate tracing data, you can use the following curl command: * @@ -65,7 +64,6 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; * *

This command sends a POST request to create an order, which will trigger interactions with the * payment and product microservices, generating tracing logs that can be viewed in Zipkin. - * */ @SpringBootApplication public class Main { diff --git a/microservices-distributed-tracing/order-microservice/src/main/java/com/iluwatar/order/microservice/OrderController.java b/microservices-distributed-tracing/order-microservice/src/main/java/com/iluwatar/order/microservice/OrderController.java index 5f50e1f25..a7c67868c 100644 --- a/microservices-distributed-tracing/order-microservice/src/main/java/com/iluwatar/order/microservice/OrderController.java +++ b/microservices-distributed-tracing/order-microservice/src/main/java/com/iluwatar/order/microservice/OrderController.java @@ -30,9 +30,7 @@ import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; -/** - * This controller handles order processing by calling necessary microservices. - */ +/** This controller handles order processing by calling necessary microservices. */ @Slf4j @RestController public class OrderController { diff --git a/microservices-distributed-tracing/order-microservice/src/main/java/com/iluwatar/order/microservice/OrderService.java b/microservices-distributed-tracing/order-microservice/src/main/java/com/iluwatar/order/microservice/OrderService.java index 046fc9fff..b4be09309 100644 --- a/microservices-distributed-tracing/order-microservice/src/main/java/com/iluwatar/order/microservice/OrderService.java +++ b/microservices-distributed-tracing/order-microservice/src/main/java/com/iluwatar/order/microservice/OrderService.java @@ -31,9 +31,7 @@ import org.springframework.stereotype.Service; import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.ResourceAccessException; -/** - * Service to handle order processing logic. - */ +/** Service to handle order processing logic. */ @Slf4j @Service public class OrderService { @@ -50,9 +48,8 @@ public class OrderService { } /** - * Processes an order by calling - * {@link OrderService#validateProduct()} and - * {@link OrderService#processPayment()}. + * Processes an order by calling {@link OrderService#validateProduct()} and {@link + * OrderService#processPayment()}. * * @return A string indicating whether the order was processed successfully or failed. */ @@ -70,10 +67,11 @@ public class OrderService { */ Boolean validateProduct() { try { - ResponseEntity productValidationResult = restTemplateBuilder - .build() - .postForEntity("http://localhost:30302/product/validate", "validating product", - Boolean.class); + ResponseEntity productValidationResult = + restTemplateBuilder + .build() + .postForEntity( + "http://localhost:30302/product/validate", "validating product", Boolean.class); LOGGER.info("Product validation result: {}", productValidationResult.getBody()); return productValidationResult.getBody(); } catch (ResourceAccessException | HttpClientErrorException e) { @@ -89,10 +87,11 @@ public class OrderService { */ Boolean processPayment() { try { - ResponseEntity paymentProcessResult = restTemplateBuilder - .build() - .postForEntity("http://localhost:30301/payment/process", "processing payment", - Boolean.class); + ResponseEntity paymentProcessResult = + restTemplateBuilder + .build() + .postForEntity( + "http://localhost:30301/payment/process", "processing payment", Boolean.class); LOGGER.info("Payment processing result: {}", paymentProcessResult.getBody()); return paymentProcessResult.getBody(); } catch (ResourceAccessException | HttpClientErrorException e) { diff --git a/microservices-distributed-tracing/order-microservice/src/test/java/com/iluwatar/order/microservice/MainTest.java b/microservices-distributed-tracing/order-microservice/src/test/java/com/iluwatar/order/microservice/MainTest.java index 369690947..97f9295ff 100644 --- a/microservices-distributed-tracing/order-microservice/src/test/java/com/iluwatar/order/microservice/MainTest.java +++ b/microservices-distributed-tracing/order-microservice/src/test/java/com/iluwatar/order/microservice/MainTest.java @@ -28,12 +28,10 @@ import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import org.junit.jupiter.api.Test; -/** - * Application test - */ +/** Application test */ class MainTest { @Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> Main.main(new String[]{})); + assertDoesNotThrow(() -> Main.main(new String[] {})); } } diff --git a/microservices-distributed-tracing/order-microservice/src/test/java/com/iluwatar/order/microservice/OrderControllerTest.java b/microservices-distributed-tracing/order-microservice/src/test/java/com/iluwatar/order/microservice/OrderControllerTest.java index f6a593943..7760129f8 100644 --- a/microservices-distributed-tracing/order-microservice/src/test/java/com/iluwatar/order/microservice/OrderControllerTest.java +++ b/microservices-distributed-tracing/order-microservice/src/test/java/com/iluwatar/order/microservice/OrderControllerTest.java @@ -1,27 +1,31 @@ -package com.iluwatar.order.microservice;/* - * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). - * - * The MIT License - * Copyright © 2014-2022 Ilkka Seppälä - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ +package com.iluwatar.order.microservice; /* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.when; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.InjectMocks; @@ -29,28 +33,19 @@ import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.http.ResponseEntity; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.Mockito.when; - -/** - * OrderControllerTest class to test the OrderController. - */ +/** OrderControllerTest class to test the OrderController. */ class OrderControllerTest { - @InjectMocks - private OrderController orderController; + @InjectMocks private OrderController orderController; - @Mock - private OrderService orderService; + @Mock private OrderService orderService; @BeforeEach void setup() { MockitoAnnotations.openMocks(this); } - /** - * Test to process the order successfully. - */ + /** Test to process the order successfully. */ @Test void processOrderShouldReturnSuccessStatus() { // Arrange @@ -61,9 +56,7 @@ class OrderControllerTest { assertEquals("Order processed successfully", response.getBody()); } - /** - * Test to process the order with failure. - */ + /** Test to process the order with failure. */ @Test void ProcessOrderShouldReturnFailureStatusWhen() { // Arrange diff --git a/microservices-distributed-tracing/order-microservice/src/test/java/com/iluwatar/order/microservice/OrderServiceTest.java b/microservices-distributed-tracing/order-microservice/src/test/java/com/iluwatar/order/microservice/OrderServiceTest.java index c331c5abb..10a3fcacb 100644 --- a/microservices-distributed-tracing/order-microservice/src/test/java/com/iluwatar/order/microservice/OrderServiceTest.java +++ b/microservices-distributed-tracing/order-microservice/src/test/java/com/iluwatar/order/microservice/OrderServiceTest.java @@ -36,23 +36,18 @@ import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.http.ResponseEntity; -import org.springframework.web.client.RestTemplate; import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.ResourceAccessException; +import org.springframework.web.client.RestTemplate; -/** - * OrderServiceTest class to test the OrderService. - */ +/** OrderServiceTest class to test the OrderService. */ class OrderServiceTest { - @InjectMocks - private OrderService orderService; + @InjectMocks private OrderService orderService; - @Mock - private RestTemplateBuilder restTemplateBuilder; + @Mock private RestTemplateBuilder restTemplateBuilder; - @Mock - private RestTemplate restTemplate; + @Mock private RestTemplate restTemplate; @BeforeEach void setup() { @@ -60,15 +55,15 @@ class OrderServiceTest { when(restTemplateBuilder.build()).thenReturn(restTemplate); } - /** - * Test to process the order successfully. - */ + /** Test to process the order successfully. */ @Test void testProcessOrder_Success() { // Arrange - when(restTemplate.postForEntity(eq("http://localhost:30302/product/validate"), anyString(), eq(Boolean.class))) + when(restTemplate.postForEntity( + eq("http://localhost:30302/product/validate"), anyString(), eq(Boolean.class))) .thenReturn(ResponseEntity.ok(true)); - when(restTemplate.postForEntity(eq("http://localhost:30301/payment/process"), anyString(), eq(Boolean.class))) + when(restTemplate.postForEntity( + eq("http://localhost:30301/payment/process"), anyString(), eq(Boolean.class))) .thenReturn(ResponseEntity.ok(true)); // Act String result = orderService.processOrder(); @@ -76,13 +71,12 @@ class OrderServiceTest { assertEquals("Order processed successfully", result); } - /** - * Test to process the order with failure caused by product validation failure. - */ + /** Test to process the order with failure caused by product validation failure. */ @Test void testProcessOrder_FailureWithProductValidationFailure() { // Arrange - when(restTemplate.postForEntity(eq("http://localhost:30302/product/validate"), anyString(), eq(Boolean.class))) + when(restTemplate.postForEntity( + eq("http://localhost:30302/product/validate"), anyString(), eq(Boolean.class))) .thenReturn(ResponseEntity.ok(false)); // Act String result = orderService.processOrder(); @@ -90,15 +84,15 @@ class OrderServiceTest { assertEquals("Order processing failed", result); } - /** - * Test to process the order with failure caused by payment processing failure. - */ + /** Test to process the order with failure caused by payment processing failure. */ @Test void testProcessOrder_FailureWithPaymentProcessingFailure() { // Arrange - when(restTemplate.postForEntity(eq("http://localhost:30302/product/validate"), anyString(), eq(Boolean.class))) + when(restTemplate.postForEntity( + eq("http://localhost:30302/product/validate"), anyString(), eq(Boolean.class))) .thenReturn(ResponseEntity.ok(true)); - when(restTemplate.postForEntity(eq("http://localhost:30301/payment/process"), anyString(), eq(Boolean.class))) + when(restTemplate.postForEntity( + eq("http://localhost:30301/payment/process"), anyString(), eq(Boolean.class))) .thenReturn(ResponseEntity.ok(false)); // Act String result = orderService.processOrder(); @@ -106,13 +100,12 @@ class OrderServiceTest { assertEquals("Order processing failed", result); } - /** - * Test to validate the product. - */ + /** Test to validate the product. */ @Test void testValidateProduct() { // Arrange - when(restTemplate.postForEntity(eq("http://localhost:30302/product/validate"), anyString(), eq(Boolean.class))) + when(restTemplate.postForEntity( + eq("http://localhost:30302/product/validate"), anyString(), eq(Boolean.class))) .thenReturn(ResponseEntity.ok(true)); // Act Boolean result = orderService.validateProduct(); @@ -120,13 +113,12 @@ class OrderServiceTest { assertEquals(true, result); } - /** - * Test to process the payment. - */ + /** Test to process the payment. */ @Test void testProcessPayment() { // Arrange - when(restTemplate.postForEntity(eq("http://localhost:30301/payment/process"), anyString(), eq(Boolean.class))) + when(restTemplate.postForEntity( + eq("http://localhost:30301/payment/process"), anyString(), eq(Boolean.class))) .thenReturn(ResponseEntity.ok(true)); // Act Boolean result = orderService.processPayment(); @@ -134,13 +126,12 @@ class OrderServiceTest { assertEquals(true, result); } - /** - * Test to validate the product with ResourceAccessException. - */ + /** Test to validate the product with ResourceAccessException. */ @Test void testValidateProduct_ResourceAccessException() { // Arrange - when(restTemplate.postForEntity(eq("http://localhost:30302/product/validate"), anyString(), eq(Boolean.class))) + when(restTemplate.postForEntity( + eq("http://localhost:30302/product/validate"), anyString(), eq(Boolean.class))) .thenThrow(new ResourceAccessException("Service unavailable")); // Act Boolean result = orderService.validateProduct(); @@ -148,27 +139,27 @@ class OrderServiceTest { assertEquals(false, result); } - /** - * Test to validate the product with HttpClientErrorException. - */ + /** Test to validate the product with HttpClientErrorException. */ @Test void testValidateProduct_HttpClientErrorException() { // Arrange - when(restTemplate.postForEntity(eq("http://localhost:30302/product/validate"), anyString(), eq(Boolean.class))) - .thenThrow(new HttpClientErrorException(org.springframework.http.HttpStatus.BAD_REQUEST, "Bad request")); + when(restTemplate.postForEntity( + eq("http://localhost:30302/product/validate"), anyString(), eq(Boolean.class))) + .thenThrow( + new HttpClientErrorException( + org.springframework.http.HttpStatus.BAD_REQUEST, "Bad request")); // Act Boolean result = orderService.validateProduct(); // Assert assertEquals(false, result); } - /** - * Test to process the payment with ResourceAccessException. - */ + /** Test to process the payment with ResourceAccessException. */ @Test void testProcessPayment_ResourceAccessException() { // Arrange - when(restTemplate.postForEntity(eq("http://localhost:30301/payment/process"), anyString(), eq(Boolean.class))) + when(restTemplate.postForEntity( + eq("http://localhost:30301/payment/process"), anyString(), eq(Boolean.class))) .thenThrow(new ResourceAccessException("Service unavailable")); // Act Boolean result = orderService.processPayment(); @@ -176,14 +167,15 @@ class OrderServiceTest { assertEquals(false, result); } - /** - * Test to process the payment with HttpClientErrorException. - */ + /** Test to process the payment with HttpClientErrorException. */ @Test void testProcessPayment_HttpClientErrorException() { // Arrange - when(restTemplate.postForEntity(eq("http://localhost:30301/payment/process"), anyString(), eq(Boolean.class))) - .thenThrow(new HttpClientErrorException(org.springframework.http.HttpStatus.BAD_REQUEST, "Bad request")); + when(restTemplate.postForEntity( + eq("http://localhost:30301/payment/process"), anyString(), eq(Boolean.class))) + .thenThrow( + new HttpClientErrorException( + org.springframework.http.HttpStatus.BAD_REQUEST, "Bad request")); // Act Boolean result = orderService.processPayment(); // Assert diff --git a/microservices-distributed-tracing/payment-microservice/src/main/java/com/iluwatar/payment/microservice/Main.java b/microservices-distributed-tracing/payment-microservice/src/main/java/com/iluwatar/payment/microservice/Main.java index e41f1c01b..506096f4e 100644 --- a/microservices-distributed-tracing/payment-microservice/src/main/java/com/iluwatar/payment/microservice/Main.java +++ b/microservices-distributed-tracing/payment-microservice/src/main/java/com/iluwatar/payment/microservice/Main.java @@ -41,10 +41,9 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; * journey. * *

This implementation demonstrates distributed tracing in a microservices architecture for an - * e-commerce platform. When a customer places an order, the OrderService interacts with - * both the PaymentService to process the payment and the ProductService to check the - * product inventory. Tracing logs are generated for each interaction, and these logs can be - * visualized using Zipkin. + * e-commerce platform. When a customer places an order, the OrderService interacts with both the + * PaymentService to process the payment and the ProductService to check the product inventory. + * Tracing logs are generated for each interaction, and these logs can be visualized using Zipkin. * *

To run Zipkin and view the tracing logs, you can use the following Docker command: * @@ -52,9 +51,9 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; * {@code docker run -d -p 9411:9411 --name zipkin openzipkin/zipkin } * * - *

Start Zipkin with the command above. Once Zipkin is running, you can - * access the Zipkin UI at http://localhost:9411 - * to view the tracing logs and analyze the request flows across your microservices. + *

Start Zipkin with the command above. Once Zipkin is running, you can access the Zipkin UI at + * http://localhost:9411 to view the tracing logs and analyze + * the request flows across your microservices. * *

To place an order and generate tracing data, you can use the following curl command: * @@ -64,7 +63,6 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; * *

This command sends a POST request to create an order, which will trigger interactions with the * payment and product microservices, generating tracing logs that can be viewed in Zipkin. - * */ @SpringBootApplication public class Main { diff --git a/microservices-distributed-tracing/payment-microservice/src/main/java/com/iluwatar/payment/microservice/PaymentController.java b/microservices-distributed-tracing/payment-microservice/src/main/java/com/iluwatar/payment/microservice/PaymentController.java index 2662589a0..834c88c07 100644 --- a/microservices-distributed-tracing/payment-microservice/src/main/java/com/iluwatar/payment/microservice/PaymentController.java +++ b/microservices-distributed-tracing/payment-microservice/src/main/java/com/iluwatar/payment/microservice/PaymentController.java @@ -30,9 +30,7 @@ import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; -/** - * Controller for handling payment processing requests. - */ +/** Controller for handling payment processing requests. */ @Slf4j @RestController public class PaymentController { diff --git a/microservices-distributed-tracing/payment-microservice/src/test/java/com/iluwatar/payment/microservice/MainTest.java b/microservices-distributed-tracing/payment-microservice/src/test/java/com/iluwatar/payment/microservice/MainTest.java index b8b3b6e56..2b500440e 100644 --- a/microservices-distributed-tracing/payment-microservice/src/test/java/com/iluwatar/payment/microservice/MainTest.java +++ b/microservices-distributed-tracing/payment-microservice/src/test/java/com/iluwatar/payment/microservice/MainTest.java @@ -24,16 +24,14 @@ */ package com.iluwatar.payment.microservice; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -/** - * Application Context loads test - */ +import org.junit.jupiter.api.Test; + +/** Application Context loads test */ class MainTest { @Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> Main.main(new String[]{})); + assertDoesNotThrow(() -> Main.main(new String[] {})); } } diff --git a/microservices-distributed-tracing/payment-microservice/src/test/java/com/iluwatar/payment/microservice/ProductControllerTest.java b/microservices-distributed-tracing/payment-microservice/src/test/java/com/iluwatar/payment/microservice/ProductControllerTest.java index 4b32d7662..7fbbf2c1a 100644 --- a/microservices-distributed-tracing/payment-microservice/src/test/java/com/iluwatar/payment/microservice/ProductControllerTest.java +++ b/microservices-distributed-tracing/payment-microservice/src/test/java/com/iluwatar/payment/microservice/ProductControllerTest.java @@ -24,15 +24,13 @@ */ package com.iluwatar.payment.microservice; +import static org.junit.jupiter.api.Assertions.assertEquals; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.http.ResponseEntity; -import static org.junit.jupiter.api.Assertions.assertEquals; - -/** - * Payment controller test. - */ +/** Payment controller test. */ class ProductControllerTest { private PaymentController paymentController; @@ -41,9 +39,8 @@ class ProductControllerTest { void setUp() { paymentController = new PaymentController(); } - /** - * Test to process the payment. - */ + + /** Test to process the payment. */ @Test void testValidateProduct() { // Arrange @@ -54,9 +51,7 @@ class ProductControllerTest { assertEquals(ResponseEntity.ok(true), response); } - /** - * Test to process the payment with null request. - */ + /** Test to process the payment with null request. */ @Test void testValidateProductWithNullRequest() { // Arrange diff --git a/microservices-distributed-tracing/pom.xml b/microservices-distributed-tracing/pom.xml index 72eded678..1957766d6 100644 --- a/microservices-distributed-tracing/pom.xml +++ b/microservices-distributed-tracing/pom.xml @@ -34,17 +34,6 @@ 4.0.0 microservices-distributed-tracing pom - - - - org.springframework.boot - spring-boot-dependencies - pom - 3.3.1 - import - - - org.springframework.boot @@ -57,11 +46,13 @@ io.micrometer micrometer-tracing-bridge-brave + 1.4.4 compile io.zipkin.reporter2 zipkin-reporter-brave + 3.5.0 org.junit.jupiter diff --git a/microservices-distributed-tracing/product-microservice/src/main/java/com/iluwatar/product/microservice/microservice/Main.java b/microservices-distributed-tracing/product-microservice/src/main/java/com/iluwatar/product/microservice/microservice/Main.java index 93b2a8383..91e41631c 100644 --- a/microservices-distributed-tracing/product-microservice/src/main/java/com/iluwatar/product/microservice/microservice/Main.java +++ b/microservices-distributed-tracing/product-microservice/src/main/java/com/iluwatar/product/microservice/microservice/Main.java @@ -41,10 +41,9 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; * journey. * *

This implementation demonstrates distributed tracing in a microservices architecture for an - * e-commerce platform. When a customer places an order, the OrderService interacts with - * both the PaymentService to process the payment and the ProductService to check the - * product inventory. Tracing logs are generated for each interaction, and these logs can be - * visualized using Zipkin. + * e-commerce platform. When a customer places an order, the OrderService interacts with both the + * PaymentService to process the payment and the ProductService to check the product inventory. + * Tracing logs are generated for each interaction, and these logs can be visualized using Zipkin. * *

To run Zipkin and view the tracing logs, you can use the following Docker command: * @@ -52,9 +51,9 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; * {@code docker run -d -p 9411:9411 --name zipkin openzipkin/zipkin } * * - *

Start Zipkin with the command above. Once Zipkin is running, you can - * access the Zipkin UI at http://localhost:9411 - * to view the tracing logs and analyze the request flows across your microservices. + *

Start Zipkin with the command above. Once Zipkin is running, you can access the Zipkin UI at + * http://localhost:9411 to view the tracing logs and analyze + * the request flows across your microservices. * *

To place an order and generate tracing data, you can use the following curl command: * @@ -64,7 +63,6 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; * *

This command sends a POST request to create an order, which will trigger interactions with the * payment and product microservices, generating tracing logs that can be viewed in Zipkin. - * */ @SpringBootApplication public class Main { diff --git a/microservices-distributed-tracing/product-microservice/src/main/java/com/iluwatar/product/microservice/microservice/ProductController.java b/microservices-distributed-tracing/product-microservice/src/main/java/com/iluwatar/product/microservice/microservice/ProductController.java index c9972e5b2..cc4b21475 100644 --- a/microservices-distributed-tracing/product-microservice/src/main/java/com/iluwatar/product/microservice/microservice/ProductController.java +++ b/microservices-distributed-tracing/product-microservice/src/main/java/com/iluwatar/product/microservice/microservice/ProductController.java @@ -30,9 +30,7 @@ import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; -/** - * Controller for handling product validation requests. - */ +/** Controller for handling product validation requests. */ @Slf4j @RestController public class ProductController { diff --git a/microservices-distributed-tracing/product-microservice/src/test/java/com/iluwatar/product/microservice/MainTest.java b/microservices-distributed-tracing/product-microservice/src/test/java/com/iluwatar/product/microservice/MainTest.java index f7c6b8800..1534943ab 100644 --- a/microservices-distributed-tracing/product-microservice/src/test/java/com/iluwatar/product/microservice/MainTest.java +++ b/microservices-distributed-tracing/product-microservice/src/test/java/com/iluwatar/product/microservice/MainTest.java @@ -24,17 +24,15 @@ */ package com.iluwatar.product.microservice; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + import com.iluwatar.product.microservice.microservice.Main; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; - -/** - * Application test - */ +/** Application test */ class MainTest { @Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> Main.main(new String[]{})); + assertDoesNotThrow(() -> Main.main(new String[] {})); } } diff --git a/microservices-distributed-tracing/product-microservice/src/test/java/com/iluwatar/product/microservice/ProductControllerTest.java b/microservices-distributed-tracing/product-microservice/src/test/java/com/iluwatar/product/microservice/ProductControllerTest.java index 139cae40b..517a1b20b 100644 --- a/microservices-distributed-tracing/product-microservice/src/test/java/com/iluwatar/product/microservice/ProductControllerTest.java +++ b/microservices-distributed-tracing/product-microservice/src/test/java/com/iluwatar/product/microservice/ProductControllerTest.java @@ -24,14 +24,13 @@ */ package com.iluwatar.product.microservice; +import static org.junit.jupiter.api.Assertions.assertEquals; + import com.iluwatar.product.microservice.microservice.ProductController; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.http.ResponseEntity; -import static org.junit.jupiter.api.Assertions.assertEquals; - - class ProductControllerTest { private ProductController productController; @@ -41,9 +40,7 @@ class ProductControllerTest { productController = new ProductController(); } - /** - * Test to validate the product. - */ + /** Test to validate the product. */ @Test void testValidateProduct() { // Arrange @@ -54,9 +51,7 @@ class ProductControllerTest { assertEquals(ResponseEntity.ok(true), response); } - /** - * Test to validate the product with null request. - */ + /** Test to validate the product with null request. */ @Test void testValidateProductWithNullRequest() { // Arrange diff --git a/microservices-idempotent-consumer/pom.xml b/microservices-idempotent-consumer/pom.xml index 453e4a1ec..665be3abe 100644 --- a/microservices-idempotent-consumer/pom.xml +++ b/microservices-idempotent-consumer/pom.xml @@ -36,22 +36,6 @@ microservices-idempotent-consumer - - - - org.springframework.boot - spring-boot-dependencies - pom - 3.2.3 - import - - - org.hibernate - hibernate-core - 6.4.4.Final - - - @@ -89,6 +73,12 @@ runtime + + org.hibernate + hibernate-core + 6.4.4.Final + + diff --git a/microservices-idempotent-consumer/src/main/java/com/iluwatar/idempotentconsumer/App.java b/microservices-idempotent-consumer/src/main/java/com/iluwatar/idempotentconsumer/App.java index 4fcc28016..fe099eab4 100644 --- a/microservices-idempotent-consumer/src/main/java/com/iluwatar/idempotentconsumer/App.java +++ b/microservices-idempotent-consumer/src/main/java/com/iluwatar/idempotentconsumer/App.java @@ -32,13 +32,14 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; /** - * The main entry point for the idempotent-consumer application. - * This application demonstrates the use of the Idempotent Consumer - * pattern which ensures that a message is processed exactly once - * in scenarios where the same message can be delivered multiple times. + * The main entry point for the idempotent-consumer application. This application demonstrates the + * use of the Idempotent Consumer pattern which ensures that a message is processed exactly once in + * scenarios where the same message can be delivered multiple times. * * @see Idempotence (Wikipedia) - * @see Idempotent Consumer Pattern (Apache Camel) + * @see Idempotent + * Consumer Pattern (Apache Camel) */ @SpringBootApplication @Slf4j @@ -46,9 +47,9 @@ public class App { public static void main(String[] args) { SpringApplication.run(App.class, args); } + /** - * The starting point of the CommandLineRunner - * where the main program is run. + * The starting point of the CommandLineRunner where the main program is run. * * @param requestService idempotent request service * @param requestRepository request jpa repository @@ -59,7 +60,8 @@ public class App { Request req = requestService.create(UUID.randomUUID()); requestService.create(req.getUuid()); requestService.create(req.getUuid()); - LOGGER.info("Nb of requests : {}", requestRepository.count()); // 1, processRequest is idempotent + LOGGER.info( + "Nb of requests : {}", requestRepository.count()); // 1, processRequest is idempotent req = requestService.start(req.getUuid()); try { req = requestService.start(req.getUuid()); @@ -71,4 +73,3 @@ public class App { }; } } - diff --git a/microservices-idempotent-consumer/src/main/java/com/iluwatar/idempotentconsumer/InvalidNextStateException.java b/microservices-idempotent-consumer/src/main/java/com/iluwatar/idempotentconsumer/InvalidNextStateException.java index c29e913aa..e280d37a8 100644 --- a/microservices-idempotent-consumer/src/main/java/com/iluwatar/idempotentconsumer/InvalidNextStateException.java +++ b/microservices-idempotent-consumer/src/main/java/com/iluwatar/idempotentconsumer/InvalidNextStateException.java @@ -25,9 +25,9 @@ package com.iluwatar.idempotentconsumer; /** - * This exception is thrown when an invalid transition is attempted in the Statemachine - * for the request status. This can occur when attempting to move to a state that is not valid - * from the current state. + * This exception is thrown when an invalid transition is attempted in the Statemachine for the + * request status. This can occur when attempting to move to a state that is not valid from the + * current state. */ public class InvalidNextStateException extends RuntimeException { public InvalidNextStateException(String s) { diff --git a/microservices-idempotent-consumer/src/main/java/com/iluwatar/idempotentconsumer/Request.java b/microservices-idempotent-consumer/src/main/java/com/iluwatar/idempotentconsumer/Request.java index 29f5d6fba..dfd68346b 100644 --- a/microservices-idempotent-consumer/src/main/java/com/iluwatar/idempotentconsumer/Request.java +++ b/microservices-idempotent-consumer/src/main/java/com/iluwatar/idempotentconsumer/Request.java @@ -31,8 +31,8 @@ import lombok.Data; import lombok.NoArgsConstructor; /** - * The {@code Request} class represents a request with a unique UUID and a status. - * The status of a request can be one of four values: PENDING, STARTED, COMPLETED, or INERROR. + * The {@code Request} class represents a request with a unique UUID and a status. The status of a + * request can be one of four values: PENDING, STARTED, COMPLETED, or INERROR. */ @Entity @NoArgsConstructor @@ -44,8 +44,7 @@ public class Request { COMPLETED } - @Id - private UUID uuid; + @Id private UUID uuid; private Status status; public Request(UUID uuid) { diff --git a/microservices-idempotent-consumer/src/main/java/com/iluwatar/idempotentconsumer/RequestNotFoundException.java b/microservices-idempotent-consumer/src/main/java/com/iluwatar/idempotentconsumer/RequestNotFoundException.java index 5294298d6..aedc94ef7 100644 --- a/microservices-idempotent-consumer/src/main/java/com/iluwatar/idempotentconsumer/RequestNotFoundException.java +++ b/microservices-idempotent-consumer/src/main/java/com/iluwatar/idempotentconsumer/RequestNotFoundException.java @@ -28,9 +28,8 @@ import java.util.UUID; /** * This class extends the RuntimeException class to handle scenarios where a Request is not found. - * It is intended to be used where you would like to have a custom exception that signals that a requested object or action - * was not found in the system, based on the UUID of the request. - * + * It is intended to be used where you would like to have a custom exception that signals that a + * requested object or action was not found in the system, based on the UUID of the request. */ public class RequestNotFoundException extends RuntimeException { RequestNotFoundException(UUID uuid) { diff --git a/microservices-idempotent-consumer/src/main/java/com/iluwatar/idempotentconsumer/RequestRepository.java b/microservices-idempotent-consumer/src/main/java/com/iluwatar/idempotentconsumer/RequestRepository.java index 0d8d3744b..e0b273e9f 100644 --- a/microservices-idempotent-consumer/src/main/java/com/iluwatar/idempotentconsumer/RequestRepository.java +++ b/microservices-idempotent-consumer/src/main/java/com/iluwatar/idempotentconsumer/RequestRepository.java @@ -29,12 +29,11 @@ import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; /** - * This is a repository interface for the "Request" entity. It extends the JpaRepository interface from Spring Data JPA. - * JpaRepository comes with many operations out of the box, including standard CRUD operations. - * With JpaRepository, we are also able to leverage the power of Spring Data's query methods. - * The UUID parameter in JpaRepository refers to the type of the ID in the "Request" entity. - * + * This is a repository interface for the "Request" entity. It extends the JpaRepository interface + * from Spring Data JPA. JpaRepository comes with many operations out of the box, including standard + * CRUD operations. With JpaRepository, we are also able to leverage the power of Spring Data's + * query methods. The UUID parameter in JpaRepository refers to the type of the ID in the "Request" + * entity. */ @Repository -public interface RequestRepository extends JpaRepository { -} +public interface RequestRepository extends JpaRepository {} diff --git a/microservices-idempotent-consumer/src/main/java/com/iluwatar/idempotentconsumer/RequestService.java b/microservices-idempotent-consumer/src/main/java/com/iluwatar/idempotentconsumer/RequestService.java index 066e52e66..796053330 100644 --- a/microservices-idempotent-consumer/src/main/java/com/iluwatar/idempotentconsumer/RequestService.java +++ b/microservices-idempotent-consumer/src/main/java/com/iluwatar/idempotentconsumer/RequestService.java @@ -29,24 +29,23 @@ import java.util.UUID; import org.springframework.stereotype.Service; /** - * This service is responsible for handling request operations including - * creation, start, and completion of requests. + * This service is responsible for handling request operations including creation, start, and + * completion of requests. */ @Service public class RequestService { RequestRepository requestRepository; RequestStateMachine requestStateMachine; - public RequestService(RequestRepository requestRepository, - RequestStateMachine requestStateMachine) { + public RequestService( + RequestRepository requestRepository, RequestStateMachine requestStateMachine) { this.requestRepository = requestRepository; this.requestStateMachine = requestStateMachine; } /** - * Creates a new Request or returns an existing one by it's UUID. - * This operation is idempotent: performing it once or several times - * successively leads to an equivalent result. + * Creates a new Request or returns an existing one by it's UUID. This operation is idempotent: + * performing it once or several times successively leads to an equivalent result. * * @param uuid The unique identifier for the Request. * @return Return existing Request or save and return a new Request. diff --git a/microservices-idempotent-consumer/src/main/java/com/iluwatar/idempotentconsumer/RequestStateMachine.java b/microservices-idempotent-consumer/src/main/java/com/iluwatar/idempotentconsumer/RequestStateMachine.java index 5861276ca..a67affdf1 100644 --- a/microservices-idempotent-consumer/src/main/java/com/iluwatar/idempotentconsumer/RequestStateMachine.java +++ b/microservices-idempotent-consumer/src/main/java/com/iluwatar/idempotentconsumer/RequestStateMachine.java @@ -27,8 +27,8 @@ package com.iluwatar.idempotentconsumer; import org.springframework.stereotype.Component; /** - * This class represents a state machine for managing request transitions. - * It supports transitions to the statuses: PENDING, STARTED, and COMPLETED. + * This class represents a state machine for managing request transitions. It supports transitions + * to the statuses: PENDING, STARTED, and COMPLETED. */ @Component public class RequestStateMachine { @@ -36,8 +36,10 @@ public class RequestStateMachine { /** * Provides the next possible state of the request based on the current and next status. * - * @param req The actual request object. This object MUST NOT be null and SHOULD have a valid status. - * @param nextStatus Represents the next status that the request could transition to. MUST NOT be null. + * @param req The actual request object. This object MUST NOT be null and SHOULD have a valid + * status. + * @param nextStatus Represents the next status that the request could transition to. MUST NOT be + * null. * @return A new Request object with updated status if the transition is valid. * @throws InvalidNextStateException If an invalid state transition is attempted. */ diff --git a/microservices-idempotent-consumer/src/test/java/com/iluwatar/idempotentconsumer/AppTest.java b/microservices-idempotent-consumer/src/test/java/com/iluwatar/idempotentconsumer/AppTest.java index b72f5bffa..457febeda 100644 --- a/microservices-idempotent-consumer/src/test/java/com/iluwatar/idempotentconsumer/AppTest.java +++ b/microservices-idempotent-consumer/src/test/java/com/iluwatar/idempotentconsumer/AppTest.java @@ -24,21 +24,18 @@ */ package com.iluwatar.idempotentconsumer; -import org.junit.jupiter.api.Test; -import org.mockito.Mockito; -import org.springframework.boot.CommandLineRunner; - -import java.util.UUID; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -/** - * Application test - */ +import java.util.UUID; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; +import org.springframework.boot.CommandLineRunner; + +/** Application test */ class AppTest { @Test @@ -67,4 +64,4 @@ class AppTest { verify(requestService, times(1)).complete(any()); verify(requestRepository, times(1)).count(); } -} \ No newline at end of file +} diff --git a/microservices-idempotent-consumer/src/test/java/com/iluwatar/idempotentconsumer/RequestServiceTests.java b/microservices-idempotent-consumer/src/test/java/com/iluwatar/idempotentconsumer/RequestServiceTests.java index 1d5eebd34..f883709a9 100644 --- a/microservices-idempotent-consumer/src/test/java/com/iluwatar/idempotentconsumer/RequestServiceTests.java +++ b/microservices-idempotent-consumer/src/test/java/com/iluwatar/idempotentconsumer/RequestServiceTests.java @@ -42,9 +42,9 @@ import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) class RequestServiceTests { private RequestService requestService; - @Mock - private RequestRepository requestRepository; + @Mock private RequestRepository requestRepository; private RequestStateMachine requestStateMachine; + @BeforeEach void setUp() { requestStateMachine = new RequestStateMachine(); @@ -61,6 +61,7 @@ class RequestServiceTests { verify(requestRepository, times(1)).findById(uuid); verify(requestRepository, times(1)).save(any()); } + @Test void createRequest_whenExists() { UUID uuid = UUID.randomUUID(); @@ -75,7 +76,7 @@ class RequestServiceTests { void startRequest_whenNotExists_shouldThrowError() { UUID uuid = UUID.randomUUID(); when(requestRepository.findById(any())).thenReturn(Optional.empty()); - assertThrows(RequestNotFoundException.class, ()->requestService.start(uuid)); + assertThrows(RequestNotFoundException.class, () -> requestService.start(uuid)); verify(requestRepository, times(1)).findById(uuid); verify(requestRepository, times(0)).save(any()); } @@ -97,7 +98,7 @@ class RequestServiceTests { UUID uuid = UUID.randomUUID(); Request requestStarted = new Request(uuid, Request.Status.STARTED); when(requestRepository.findById(any())).thenReturn(Optional.of(requestStarted)); - assertThrows(InvalidNextStateException.class, ()->requestService.start(uuid)); + assertThrows(InvalidNextStateException.class, () -> requestService.start(uuid)); verify(requestRepository, times(1)).findById(uuid); verify(requestRepository, times(0)).save(any()); } @@ -107,7 +108,7 @@ class RequestServiceTests { UUID uuid = UUID.randomUUID(); Request requestStarted = new Request(uuid, Request.Status.COMPLETED); when(requestRepository.findById(any())).thenReturn(Optional.of(requestStarted)); - assertThrows(InvalidNextStateException.class, ()->requestService.start(uuid)); + assertThrows(InvalidNextStateException.class, () -> requestService.start(uuid)); verify(requestRepository, times(1)).findById(uuid); verify(requestRepository, times(0)).save(any()); } @@ -123,6 +124,7 @@ class RequestServiceTests { verify(requestRepository, times(1)).findById(uuid); verify(requestRepository, times(1)).save(completedEntity); } + @Test void completeRequest_whenNotInprogress() { UUID uuid = UUID.randomUUID(); @@ -132,4 +134,4 @@ class RequestServiceTests { verify(requestRepository, times(1)).findById(uuid); verify(requestRepository, times(0)).save(any()); } -} \ No newline at end of file +} diff --git a/microservices-idempotent-consumer/src/test/java/com/iluwatar/idempotentconsumer/RequestStateMachineTests.java b/microservices-idempotent-consumer/src/test/java/com/iluwatar/idempotentconsumer/RequestStateMachineTests.java index 083cff7ad..62837cbf5 100644 --- a/microservices-idempotent-consumer/src/test/java/com/iluwatar/idempotentconsumer/RequestStateMachineTests.java +++ b/microservices-idempotent-consumer/src/test/java/com/iluwatar/idempotentconsumer/RequestStateMachineTests.java @@ -24,13 +24,13 @@ */ package com.iluwatar.idempotentconsumer; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import java.util.UUID; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; +import java.util.UUID; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + class RequestStateMachineTests { private RequestStateMachine requestStateMachine; @@ -41,43 +41,56 @@ class RequestStateMachineTests { @Test void transitionPendingToStarted() { - Request startedRequest = requestStateMachine.next(new Request(UUID.randomUUID(), Request.Status.PENDING), - Request.Status.STARTED); + Request startedRequest = + requestStateMachine.next( + new Request(UUID.randomUUID(), Request.Status.PENDING), Request.Status.STARTED); assertEquals(Request.Status.STARTED, startedRequest.getStatus()); } @Test void transitionAnyToPending_shouldThrowError() { - assertThrows(InvalidNextStateException.class, - () -> requestStateMachine.next(new Request(UUID.randomUUID(), Request.Status.PENDING), - Request.Status.PENDING)); - assertThrows(InvalidNextStateException.class, - () -> requestStateMachine.next(new Request(UUID.randomUUID(), Request.Status.STARTED), - Request.Status.PENDING)); - assertThrows(InvalidNextStateException.class, - () -> requestStateMachine.next(new Request(UUID.randomUUID(), Request.Status.COMPLETED), - Request.Status.PENDING)); + assertThrows( + InvalidNextStateException.class, + () -> + requestStateMachine.next( + new Request(UUID.randomUUID(), Request.Status.PENDING), Request.Status.PENDING)); + assertThrows( + InvalidNextStateException.class, + () -> + requestStateMachine.next( + new Request(UUID.randomUUID(), Request.Status.STARTED), Request.Status.PENDING)); + assertThrows( + InvalidNextStateException.class, + () -> + requestStateMachine.next( + new Request(UUID.randomUUID(), Request.Status.COMPLETED), Request.Status.PENDING)); } @Test void transitionCompletedToAny_shouldThrowError() { - assertThrows(InvalidNextStateException.class, - () -> requestStateMachine.next(new Request(UUID.randomUUID(), Request.Status.COMPLETED), - Request.Status.PENDING)); - assertThrows(InvalidNextStateException.class, - () -> requestStateMachine.next(new Request(UUID.randomUUID(), Request.Status.COMPLETED), - Request.Status.STARTED)); - assertThrows(InvalidNextStateException.class, - () -> requestStateMachine.next(new Request(UUID.randomUUID(), Request.Status.COMPLETED), - Request.Status.COMPLETED)); + assertThrows( + InvalidNextStateException.class, + () -> + requestStateMachine.next( + new Request(UUID.randomUUID(), Request.Status.COMPLETED), Request.Status.PENDING)); + assertThrows( + InvalidNextStateException.class, + () -> + requestStateMachine.next( + new Request(UUID.randomUUID(), Request.Status.COMPLETED), Request.Status.STARTED)); + assertThrows( + InvalidNextStateException.class, + () -> + requestStateMachine.next( + new Request(UUID.randomUUID(), Request.Status.COMPLETED), + Request.Status.COMPLETED)); } @Test void transitionStartedToCompleted() { - Request completedRequest = requestStateMachine.next(new Request(UUID.randomUUID(), Request.Status.STARTED), - Request.Status.COMPLETED); + Request completedRequest = + requestStateMachine.next( + new Request(UUID.randomUUID(), Request.Status.STARTED), Request.Status.COMPLETED); assertEquals(Request.Status.COMPLETED, completedRequest.getStatus()); } - - -} \ No newline at end of file +} diff --git a/microservices-log-aggregation/pom.xml b/microservices-log-aggregation/pom.xml index b10760e37..fd5548661 100644 --- a/microservices-log-aggregation/pom.xml +++ b/microservices-log-aggregation/pom.xml @@ -38,6 +38,14 @@ microservices-log-aggregation + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine @@ -46,13 +54,27 @@ org.mockito mockito-junit-jupiter + 5.16.1 test - - 17 - 17 - UTF-8 - - + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.logaggregation.App + + + + + + + + diff --git a/microservices-log-aggregation/src/main/java/com/iluwatar/logaggregation/CentralLogStore.java b/microservices-log-aggregation/src/main/java/com/iluwatar/logaggregation/CentralLogStore.java index 327279161..3f525fa9e 100644 --- a/microservices-log-aggregation/src/main/java/com/iluwatar/logaggregation/CentralLogStore.java +++ b/microservices-log-aggregation/src/main/java/com/iluwatar/logaggregation/CentralLogStore.java @@ -28,9 +28,9 @@ import java.util.concurrent.ConcurrentLinkedQueue; import lombok.extern.slf4j.Slf4j; /** - * A centralized store for logs. It collects logs from various services and stores them. - * This class is thread-safe, ensuring that logs from different services are safely stored - * concurrently without data races. + * A centralized store for logs. It collects logs from various services and stores them. This class + * is thread-safe, ensuring that logs from different services are safely stored concurrently without + * data races. */ @Slf4j public class CentralLogStore { @@ -50,9 +50,7 @@ public class CentralLogStore { logs.offer(logEntry); } - /** - * Displays all logs currently stored in the central log store. - */ + /** Displays all logs currently stored in the central log store. */ public void displayLogs() { LOGGER.info("----- Centralized Logs -----"); for (LogEntry logEntry : logs) { diff --git a/microservices-log-aggregation/src/main/java/com/iluwatar/logaggregation/LogAggregator.java b/microservices-log-aggregation/src/main/java/com/iluwatar/logaggregation/LogAggregator.java index 37417e212..0acdc9fed 100644 --- a/microservices-log-aggregation/src/main/java/com/iluwatar/logaggregation/LogAggregator.java +++ b/microservices-log-aggregation/src/main/java/com/iluwatar/logaggregation/LogAggregator.java @@ -32,11 +32,10 @@ import java.util.concurrent.atomic.AtomicInteger; import lombok.extern.slf4j.Slf4j; /** - * Responsible for collecting and buffering logs from different services. - * Once the logs reach a certain threshold or after a certain time interval, - * they are flushed to the central log store. This class ensures logs are collected - * and processed asynchronously and efficiently, providing both an immediate collection - * and periodic flushing. + * Responsible for collecting and buffering logs from different services. Once the logs reach a + * certain threshold or after a certain time interval, they are flushed to the central log store. + * This class ensures logs are collected and processed asynchronously and efficiently, providing + * both an immediate collection and periodic flushing. */ @Slf4j public class LogAggregator { @@ -84,8 +83,7 @@ public class LogAggregator { } /** - * Stops the log aggregator service and flushes any remaining logs to - * the central log store. + * Stops the log aggregator service and flushes any remaining logs to the central log store. * * @throws InterruptedException If any thread has interrupted the current thread. */ @@ -106,15 +104,16 @@ public class LogAggregator { } private void startBufferFlusher() { - executorService.execute(() -> { - while (!Thread.currentThread().isInterrupted()) { - try { - Thread.sleep(5000); // Flush every 5 seconds. - flushBuffer(); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - } - } - }); + executorService.execute( + () -> { + while (!Thread.currentThread().isInterrupted()) { + try { + Thread.sleep(5000); // Flush every 5 seconds. + flushBuffer(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + }); } } diff --git a/microservices-log-aggregation/src/main/java/com/iluwatar/logaggregation/LogEntry.java b/microservices-log-aggregation/src/main/java/com/iluwatar/logaggregation/LogEntry.java index 1dd467293..93fe30d7c 100644 --- a/microservices-log-aggregation/src/main/java/com/iluwatar/logaggregation/LogEntry.java +++ b/microservices-log-aggregation/src/main/java/com/iluwatar/logaggregation/LogEntry.java @@ -29,8 +29,8 @@ import lombok.AllArgsConstructor; import lombok.Data; /** - * Represents a single log entry, capturing essential details like the service name, - * log level, message, and the timestamp when the log was generated. + * Represents a single log entry, capturing essential details like the service name, log level, + * message, and the timestamp when the log was generated. */ @Data @AllArgsConstructor diff --git a/microservices-log-aggregation/src/main/java/com/iluwatar/logaggregation/LogLevel.java b/microservices-log-aggregation/src/main/java/com/iluwatar/logaggregation/LogLevel.java index 8d90dbe95..da6c69afb 100644 --- a/microservices-log-aggregation/src/main/java/com/iluwatar/logaggregation/LogLevel.java +++ b/microservices-log-aggregation/src/main/java/com/iluwatar/logaggregation/LogLevel.java @@ -25,14 +25,17 @@ package com.iluwatar.logaggregation; /** - * Enum representing different log levels. - * Defines the severity of a log message, helping in filtering and prioritization. + * Enum representing different log levels. Defines the severity of a log message, helping in + * filtering and prioritization. + * *

    - *
  • DEBUG: Detailed information, typically of interest only when diagnosing problems.
  • - *
  • INFO: Confirmation that things are working as expected.
  • - *
  • ERROR: Indicates a problem that needs attention.
  • + *
  • DEBUG: Detailed information, typically of interest only when diagnosing problems. + *
  • INFO: Confirmation that things are working as expected. + *
  • ERROR: Indicates a problem that needs attention. *
*/ public enum LogLevel { - DEBUG, INFO, ERROR + DEBUG, + INFO, + ERROR } diff --git a/microservices-log-aggregation/src/main/java/com/iluwatar/logaggregation/LogProducer.java b/microservices-log-aggregation/src/main/java/com/iluwatar/logaggregation/LogProducer.java index a586588bc..a1d3f4c71 100644 --- a/microservices-log-aggregation/src/main/java/com/iluwatar/logaggregation/LogProducer.java +++ b/microservices-log-aggregation/src/main/java/com/iluwatar/logaggregation/LogProducer.java @@ -29,9 +29,9 @@ import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; /** - * Represents a service that produces logs. - * The logs are generated based on certain activities or events within the service. - * Once a log is generated, it's passed on to the aggregator for further processing. + * Represents a service that produces logs. The logs are generated based on certain activities or + * events within the service. Once a log is generated, it's passed on to the aggregator for further + * processing. */ @AllArgsConstructor @Slf4j diff --git a/microservices-log-aggregation/src/test/java/com/iluwatar/logaggregation/LogAggregatorTest.java b/microservices-log-aggregation/src/test/java/com/iluwatar/logaggregation/LogAggregatorTest.java index 6c385f35c..219bb4c48 100644 --- a/microservices-log-aggregation/src/test/java/com/iluwatar/logaggregation/LogAggregatorTest.java +++ b/microservices-log-aggregation/src/test/java/com/iluwatar/logaggregation/LogAggregatorTest.java @@ -38,8 +38,7 @@ import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) class LogAggregatorTest { - @Mock - private CentralLogStore centralLogStore; + @Mock private CentralLogStore centralLogStore; private LogAggregator logAggregator; @BeforeEach diff --git a/model-view-controller/pom.xml b/model-view-controller/pom.xml index 78072af44..807596459 100644 --- a/model-view-controller/pom.xml +++ b/model-view-controller/pom.xml @@ -34,6 +34,14 @@ model-view-controller + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Fatigue.java b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Fatigue.java index 00cced240..a4a3c69cb 100644 --- a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Fatigue.java +++ b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Fatigue.java @@ -26,9 +26,7 @@ package com.iluwatar.model.view.controller; import lombok.AllArgsConstructor; -/** - * Fatigue enumeration. - */ +/** Fatigue enumeration. */ @AllArgsConstructor public enum Fatigue { ALERT("alert"), @@ -37,7 +35,6 @@ public enum Fatigue { private final String title; - @Override public String toString() { return title; diff --git a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantController.java b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantController.java index 35881fbff..5fb8f1aca 100644 --- a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantController.java +++ b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantController.java @@ -24,9 +24,7 @@ */ package com.iluwatar.model.view.controller; -/** - * GiantController can update the giant data and redraw it using the view. - */ +/** GiantController can update the giant data and redraw it using the view. */ public class GiantController { private final GiantModel giant; diff --git a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantModel.java b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantModel.java index 3de47cdcb..8be7e6e4e 100644 --- a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantModel.java +++ b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantModel.java @@ -30,9 +30,7 @@ import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; -/** - * GiantModel contains the giant data. - */ +/** GiantModel contains the giant data. */ @Getter @Setter @Builder @@ -44,7 +42,6 @@ public class GiantModel { private Fatigue fatigue; private Nourishment nourishment; - @Override public String toString() { return String.format("The giant looks %s, %s and %s.", health, fatigue, nourishment); diff --git a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantView.java b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantView.java index b73204d1d..a9696d898 100644 --- a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantView.java +++ b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantView.java @@ -26,9 +26,7 @@ package com.iluwatar.model.view.controller; import lombok.extern.slf4j.Slf4j; -/** - * GiantView displays the giant. - */ +/** GiantView displays the giant. */ @Slf4j public class GiantView { diff --git a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Health.java b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Health.java index 0f54f5cd3..7fba2f54f 100644 --- a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Health.java +++ b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Health.java @@ -26,9 +26,7 @@ package com.iluwatar.model.view.controller; import lombok.AllArgsConstructor; -/** - * Health enumeration. - */ +/** Health enumeration. */ @AllArgsConstructor public enum Health { HEALTHY("healthy"), @@ -37,7 +35,6 @@ public enum Health { private final String title; - @Override public String toString() { return title; diff --git a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Nourishment.java b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Nourishment.java index f08a9c5bc..d385588bb 100644 --- a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Nourishment.java +++ b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Nourishment.java @@ -26,9 +26,7 @@ package com.iluwatar.model.view.controller; import lombok.AllArgsConstructor; -/** - * Nourishment enumeration. - */ +/** Nourishment enumeration. */ @AllArgsConstructor public enum Nourishment { SATURATED("saturated"), @@ -37,7 +35,6 @@ public enum Nourishment { private final String title; - @Override public String toString() { return title; diff --git a/model-view-controller/src/test/java/com/iluwatar/model/view/controller/AppTest.java b/model-view-controller/src/test/java/com/iluwatar/model/view/controller/AppTest.java index 8b44e47d2..b435b3930 100644 --- a/model-view-controller/src/test/java/com/iluwatar/model/view/controller/AppTest.java +++ b/model-view-controller/src/test/java/com/iluwatar/model/view/controller/AppTest.java @@ -24,17 +24,15 @@ */ package com.iluwatar.model.view.controller; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -/** - * Application test - */ +import org.junit.jupiter.api.Test; + +/** Application test */ class AppTest { @Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/model-view-controller/src/test/java/com/iluwatar/model/view/controller/GiantControllerTest.java b/model-view-controller/src/test/java/com/iluwatar/model/view/controller/GiantControllerTest.java index 1cacb52c3..9dc9f2807 100644 --- a/model-view-controller/src/test/java/com/iluwatar/model/view/controller/GiantControllerTest.java +++ b/model-view-controller/src/test/java/com/iluwatar/model/view/controller/GiantControllerTest.java @@ -30,15 +30,10 @@ import static org.mockito.Mockito.verifyNoMoreInteractions; import org.junit.jupiter.api.Test; -/** - * GiantControllerTest - * - */ +/** GiantControllerTest */ class GiantControllerTest { - /** - * Verify if the controller passes the health level through to the model and vice versa - */ + /** Verify if the controller passes the health level through to the model and vice versa */ @Test void testSetHealth() { final var model = mock(GiantModel.class); @@ -60,9 +55,7 @@ class GiantControllerTest { verifyNoMoreInteractions(model, view); } - /** - * Verify if the controller passes the fatigue level through to the model and vice versa - */ + /** Verify if the controller passes the fatigue level through to the model and vice versa */ @Test void testSetFatigue() { final var model = mock(GiantModel.class); @@ -84,9 +77,7 @@ class GiantControllerTest { verifyNoMoreInteractions(model, view); } - /** - * Verify if the controller passes the nourishment level through to the model and vice versa - */ + /** Verify if the controller passes the nourishment level through to the model and vice versa */ @Test void testSetNourishment() { final var model = mock(GiantModel.class); @@ -121,5 +112,4 @@ class GiantControllerTest { verifyNoMoreInteractions(model, view); } - -} \ No newline at end of file +} diff --git a/model-view-controller/src/test/java/com/iluwatar/model/view/controller/GiantModelTest.java b/model-view-controller/src/test/java/com/iluwatar/model/view/controller/GiantModelTest.java index f87a71267..ed9eefc4e 100644 --- a/model-view-controller/src/test/java/com/iluwatar/model/view/controller/GiantModelTest.java +++ b/model-view-controller/src/test/java/com/iluwatar/model/view/controller/GiantModelTest.java @@ -28,15 +28,10 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; -/** - * GiantModelTest - * - */ +/** GiantModelTest */ class GiantModelTest { - /** - * Verify if the health value is set properly though the constructor and setter - */ + /** Verify if the health value is set properly though the constructor and setter */ @Test void testSetHealth() { final var model = new GiantModel(Health.HEALTHY, Fatigue.ALERT, Nourishment.SATURATED); @@ -49,9 +44,7 @@ class GiantModelTest { } } - /** - * Verify if the fatigue level is set properly though the constructor and setter - */ + /** Verify if the fatigue level is set properly though the constructor and setter */ @Test void testSetFatigue() { final var model = new GiantModel(Health.HEALTHY, Fatigue.ALERT, Nourishment.SATURATED); @@ -64,9 +57,7 @@ class GiantModelTest { } } - /** - * Verify if the nourishment level is set properly though the constructor and setter - */ + /** Verify if the nourishment level is set properly though the constructor and setter */ @Test void testSetNourishment() { final var model = new GiantModel(Health.HEALTHY, Fatigue.ALERT, Nourishment.SATURATED); @@ -78,5 +69,4 @@ class GiantModelTest { assertEquals(String.format(messageFormat, nourishment), model.toString()); } } - } 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 b38452b61..da2032b7f 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 @@ -37,10 +37,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.slf4j.LoggerFactory; -/** - * GiantViewTest - * - */ +/** GiantViewTest */ class GiantViewTest { private InMemoryAppender appender; @@ -70,9 +67,7 @@ class GiantViewTest { assertEquals(1, appender.getLogSize()); } - /** - * Logging Appender Implementation - */ + /** Logging Appender Implementation */ public static class InMemoryAppender extends AppenderBase { private final List log = new LinkedList<>(); diff --git a/model-view-intent/pom.xml b/model-view-intent/pom.xml index 9ca57f881..048acd199 100644 --- a/model-view-intent/pom.xml +++ b/model-view-intent/pom.xml @@ -34,6 +34,14 @@ model-view-intent + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/model-view-intent/src/main/java/com/iluwatar/model/view/intent/App.java b/model-view-intent/src/main/java/com/iluwatar/model/view/intent/App.java index 7d17f7104..4bb699cf2 100644 --- a/model-view-intent/src/main/java/com/iluwatar/model/view/intent/App.java +++ b/model-view-intent/src/main/java/com/iluwatar/model/view/intent/App.java @@ -25,23 +25,17 @@ package com.iluwatar.model.view.intent; /** - * Model-View-Intent is a pattern for implementing user interfaces. - * Its main advantage over MVVM which it closely mirrors is a - * minimal public api with which user events can be exposed to the ViewModel. - * In case of the MVI every event is exposed by using a single method - * with 1 argument which implements UserEvent interface. - * Specific parameters can be expressed as its parameters. In this case, - * we'll be using MVI to implement a simple calculator - * with +, -, /, * operations and the ability to set the variable. - * It's important to note, that every user action happens through the + * Model-View-Intent is a pattern for implementing user interfaces. Its main advantage over MVVM + * which it closely mirrors is a minimal public api with which user events can be exposed to the + * ViewModel. In case of the MVI every event is exposed by using a single method with 1 argument + * which implements UserEvent interface. Specific parameters can be expressed as its parameters. In + * this case, we'll be using MVI to implement a simple calculator with +, -, /, * operations and the + * ability to set the variable. It's important to note, that every user action happens through the * view, we never interact with the ViewModel directly. */ public final class App { - - /** - * To avoid magic value lint error. - */ + /** To avoid magic value lint error. */ private static final double RANDOM_VARIABLE = 10.0; /** @@ -61,10 +55,10 @@ public final class App { // add calculator variable to output -> calculator output = 10.0 view.add(); - view.displayTotal(); // display output + view.displayTotal(); // display output variable1 = 2.0; - view.setVariable(variable1); // calculator variable = 2.0 + view.setVariable(variable1); // calculator variable = 2.0 // subtract calculator variable from output -> calculator output = 8 view.subtract(); @@ -77,9 +71,6 @@ public final class App { view.displayTotal(); } - /** - * Avoid default constructor lint error. - */ - private App() { - } + /** Avoid default constructor lint error. */ + private App() {} } diff --git a/model-view-intent/src/main/java/com/iluwatar/model/view/intent/CalculatorModel.java b/model-view-intent/src/main/java/com/iluwatar/model/view/intent/CalculatorModel.java index 4d513ebe7..3ef9c9934 100644 --- a/model-view-intent/src/main/java/com/iluwatar/model/view/intent/CalculatorModel.java +++ b/model-view-intent/src/main/java/com/iluwatar/model/view/intent/CalculatorModel.java @@ -27,21 +27,13 @@ package com.iluwatar.model.view.intent; import lombok.Data; import lombok.Getter; -/** - * Current state of calculator. - */ +/** Current state of calculator. */ @Data public class CalculatorModel { - /** - * Current calculator variable used for operations. - **/ - @Getter - private final Double variable; + /** Current calculator variable used for operations. */ + @Getter private final Double variable; - /** - * Current calculator output -> is affected by operations. - **/ - @Getter - private final Double output; + /** Current calculator output -> is affected by operations. */ + @Getter private final Double output; } diff --git a/model-view-intent/src/main/java/com/iluwatar/model/view/intent/CalculatorView.java b/model-view-intent/src/main/java/com/iluwatar/model/view/intent/CalculatorView.java index 13de1cbb4..a5ceb587d 100644 --- a/model-view-intent/src/main/java/com/iluwatar/model/view/intent/CalculatorView.java +++ b/model-view-intent/src/main/java/com/iluwatar/model/view/intent/CalculatorView.java @@ -34,55 +34,38 @@ import lombok.Getter; import lombok.extern.slf4j.Slf4j; /** - * Exposes changes to the state of calculator - * to {@link CalculatorViewModel} through - * {@link com.iluwatar.model.view.intent.actions.CalculatorAction} - * and displays its updated {@link CalculatorModel}. + * Exposes changes to the state of calculator to {@link CalculatorViewModel} through {@link + * com.iluwatar.model.view.intent.actions.CalculatorAction} and displays its updated {@link + * CalculatorModel}. */ @Slf4j @Data public class CalculatorView { - /** - * View model param handling the operations. - */ - @Getter - private final CalculatorViewModel viewModel; + /** View model param handling the operations. */ + @Getter private final CalculatorViewModel viewModel; - /** - * Display current view model output with logger. - */ + /** Display current view model output with logger. */ void displayTotal() { - LOGGER.info( - "Total value = {}", - viewModel.getCalculatorModel().getOutput().toString() - ); + LOGGER.info("Total value = {}", viewModel.getCalculatorModel().getOutput().toString()); } - /** - * Handle addition action. - */ + /** Handle addition action. */ void add() { viewModel.handleAction(new AdditionCalculatorAction()); } - /** - * Handle subtraction action. - */ + /** Handle subtraction action. */ void subtract() { viewModel.handleAction(new SubtractionCalculatorAction()); } - /** - * Handle multiplication action. - */ + /** Handle multiplication action. */ void multiply() { viewModel.handleAction(new MultiplicationCalculatorAction()); } - /** - * Handle division action. - */ + /** Handle division action. */ void divide() { viewModel.handleAction(new DivisionCalculatorAction()); } diff --git a/model-view-intent/src/main/java/com/iluwatar/model/view/intent/CalculatorViewModel.java b/model-view-intent/src/main/java/com/iluwatar/model/view/intent/CalculatorViewModel.java index fc5d182ad..9c1fee801 100644 --- a/model-view-intent/src/main/java/com/iluwatar/model/view/intent/CalculatorViewModel.java +++ b/model-view-intent/src/main/java/com/iluwatar/model/view/intent/CalculatorViewModel.java @@ -32,16 +32,12 @@ import com.iluwatar.model.view.intent.actions.SetVariableCalculatorAction; import com.iluwatar.model.view.intent.actions.SubtractionCalculatorAction; /** - * Handle transformations to {@link CalculatorModel} - * based on intercepted {@link CalculatorAction}. + * Handle transformations to {@link CalculatorModel} based on intercepted {@link CalculatorAction}. */ public final class CalculatorViewModel { - /** - * Current calculator model (can be changed). - */ - private CalculatorModel model = - new CalculatorModel(0.0, 0.0); + /** Current calculator model (can be changed). */ + private CalculatorModel model = new CalculatorModel(0.0, 0.0); /** * Handle calculator action. @@ -55,8 +51,7 @@ public final class CalculatorViewModel { case MultiplicationCalculatorAction.MULTIPLICATION -> multiply(); case DivisionCalculatorAction.DIVISION -> divide(); case SetVariableCalculatorAction.SET_VARIABLE -> { - SetVariableCalculatorAction setVariableAction = - (SetVariableCalculatorAction) action; + SetVariableCalculatorAction setVariableAction = (SetVariableCalculatorAction) action; setVariable(setVariableAction.getVariable()); } default -> throw new IllegalArgumentException("Unknown tag"); @@ -78,49 +73,26 @@ public final class CalculatorViewModel { * @param variable -> value of new calculator model variable. */ private void setVariable(final Double variable) { - model = new CalculatorModel( - variable, - model.getOutput() - ); + model = new CalculatorModel(variable, model.getOutput()); } - /** - * Add variable to model output. - */ + /** Add variable to model output. */ private void add() { - model = new CalculatorModel( - model.getVariable(), - model.getOutput() + model.getVariable() - ); + model = new CalculatorModel(model.getVariable(), model.getOutput() + model.getVariable()); } - /** - * Subtract variable from model output. - */ + /** Subtract variable from model output. */ private void subtract() { - model = new CalculatorModel( - model.getVariable(), - model.getOutput() - model.getVariable() - ); + model = new CalculatorModel(model.getVariable(), model.getOutput() - model.getVariable()); } - /** - * Multiply model output by variable. - */ + /** Multiply model output by variable. */ private void multiply() { - model = new CalculatorModel( - model.getVariable(), - model.getOutput() * model.getVariable() - ); + model = new CalculatorModel(model.getVariable(), model.getOutput() * model.getVariable()); } - /** - * Divide model output by variable. - */ + /** Divide model output by variable. */ private void divide() { - model = new CalculatorModel( - model.getVariable(), - model.getOutput() / model.getVariable() - ); + model = new CalculatorModel(model.getVariable(), model.getOutput() / model.getVariable()); } -} \ No newline at end of file +} diff --git a/model-view-intent/src/main/java/com/iluwatar/model/view/intent/actions/AdditionCalculatorAction.java b/model-view-intent/src/main/java/com/iluwatar/model/view/intent/actions/AdditionCalculatorAction.java index a93308e7f..21aca2a54 100644 --- a/model-view-intent/src/main/java/com/iluwatar/model/view/intent/actions/AdditionCalculatorAction.java +++ b/model-view-intent/src/main/java/com/iluwatar/model/view/intent/actions/AdditionCalculatorAction.java @@ -24,20 +24,14 @@ */ package com.iluwatar.model.view.intent.actions; -/** - * Addition {@link CalculatorAction}. - * */ +/** Addition {@link CalculatorAction}. */ public class AdditionCalculatorAction implements CalculatorAction { - /** - * Subclass tag. - * */ + /** Subclass tag. */ public static final String ADDITION = "ADDITION"; - /** - * Makes checking subclass type trivial. - * */ + /** Makes checking subclass type trivial. */ @Override public String tag() { return ADDITION; } -} \ No newline at end of file +} diff --git a/model-view-intent/src/main/java/com/iluwatar/model/view/intent/actions/CalculatorAction.java b/model-view-intent/src/main/java/com/iluwatar/model/view/intent/actions/CalculatorAction.java index 18b7c8463..b9566dc53 100644 --- a/model-view-intent/src/main/java/com/iluwatar/model/view/intent/actions/CalculatorAction.java +++ b/model-view-intent/src/main/java/com/iluwatar/model/view/intent/actions/CalculatorAction.java @@ -24,16 +24,13 @@ */ package com.iluwatar.model.view.intent.actions; -/** - * Defines what outside interactions can be consumed by view model. - * */ +/** Defines what outside interactions can be consumed by view model. */ public interface CalculatorAction { /** * Makes identifying action trivial. * * @return subclass tag. - * */ + */ String tag(); } - diff --git a/model-view-intent/src/main/java/com/iluwatar/model/view/intent/actions/DivisionCalculatorAction.java b/model-view-intent/src/main/java/com/iluwatar/model/view/intent/actions/DivisionCalculatorAction.java index 7622e4f2f..28e2ad362 100644 --- a/model-view-intent/src/main/java/com/iluwatar/model/view/intent/actions/DivisionCalculatorAction.java +++ b/model-view-intent/src/main/java/com/iluwatar/model/view/intent/actions/DivisionCalculatorAction.java @@ -24,20 +24,14 @@ */ package com.iluwatar.model.view.intent.actions; -/** - * Division {@link CalculatorAction}. - * */ +/** Division {@link CalculatorAction}. */ public class DivisionCalculatorAction implements CalculatorAction { - /** - * Subclass tag. - * */ + /** Subclass tag. */ public static final String DIVISION = "DIVISION"; - /** - * Makes checking subclass type trivial. - * */ + /** Makes checking subclass type trivial. */ @Override public String tag() { return DIVISION; } -} \ No newline at end of file +} diff --git a/model-view-intent/src/main/java/com/iluwatar/model/view/intent/actions/MultiplicationCalculatorAction.java b/model-view-intent/src/main/java/com/iluwatar/model/view/intent/actions/MultiplicationCalculatorAction.java index a163bd5d6..9c5bcd044 100644 --- a/model-view-intent/src/main/java/com/iluwatar/model/view/intent/actions/MultiplicationCalculatorAction.java +++ b/model-view-intent/src/main/java/com/iluwatar/model/view/intent/actions/MultiplicationCalculatorAction.java @@ -24,20 +24,14 @@ */ package com.iluwatar.model.view.intent.actions; -/** - * Multiplication {@link CalculatorAction}. - * */ +/** Multiplication {@link CalculatorAction}. */ public class MultiplicationCalculatorAction implements CalculatorAction { - /** - * Subclass tag. - * */ + /** Subclass tag. */ public static final String MULTIPLICATION = "MULTIPLICATION"; - /** - * Makes checking subclass type trivial. - * */ + /** Makes checking subclass type trivial. */ @Override public String tag() { return MULTIPLICATION; } -} \ No newline at end of file +} diff --git a/model-view-intent/src/main/java/com/iluwatar/model/view/intent/actions/SetVariableCalculatorAction.java b/model-view-intent/src/main/java/com/iluwatar/model/view/intent/actions/SetVariableCalculatorAction.java index c178d5400..ce438e22a 100644 --- a/model-view-intent/src/main/java/com/iluwatar/model/view/intent/actions/SetVariableCalculatorAction.java +++ b/model-view-intent/src/main/java/com/iluwatar/model/view/intent/actions/SetVariableCalculatorAction.java @@ -27,28 +27,19 @@ package com.iluwatar.model.view.intent.actions; import lombok.Data; import lombok.Getter; -/** - * SetVariable {@link CalculatorAction}. - */ +/** SetVariable {@link CalculatorAction}. */ @Data public final class SetVariableCalculatorAction implements CalculatorAction { - /** - * Subclass tag. - */ + /** Subclass tag. */ public static final String SET_VARIABLE = "SET_VARIABLE"; - /** - * Used by {@link com.iluwatar.model.view.intent.CalculatorViewModel}. - */ - @Getter - private final Double variable; + /** Used by {@link com.iluwatar.model.view.intent.CalculatorViewModel}. */ + @Getter private final Double variable; - /** - * Makes checking subclass type trivial. - */ + /** Makes checking subclass type trivial. */ @Override public String tag() { return SET_VARIABLE; } -} \ No newline at end of file +} diff --git a/model-view-intent/src/main/java/com/iluwatar/model/view/intent/actions/SubtractionCalculatorAction.java b/model-view-intent/src/main/java/com/iluwatar/model/view/intent/actions/SubtractionCalculatorAction.java index 68c576ed1..4a20d32a1 100644 --- a/model-view-intent/src/main/java/com/iluwatar/model/view/intent/actions/SubtractionCalculatorAction.java +++ b/model-view-intent/src/main/java/com/iluwatar/model/view/intent/actions/SubtractionCalculatorAction.java @@ -24,20 +24,14 @@ */ package com.iluwatar.model.view.intent.actions; -/** - * Subtraction {@link CalculatorAction}. - * */ +/** Subtraction {@link CalculatorAction}. */ public class SubtractionCalculatorAction implements CalculatorAction { - /** - * Subclass tag. - * */ + /** Subclass tag. */ public static final String SUBTRACTION = "SUBTRACTION"; - /** - * Makes checking subclass type trivial. - * */ + /** Makes checking subclass type trivial. */ @Override public String tag() { return SUBTRACTION; } -} \ No newline at end of file +} diff --git a/model-view-intent/src/main/java/com/iluwatar/model/view/intent/actions/package-info.java b/model-view-intent/src/main/java/com/iluwatar/model/view/intent/actions/package-info.java index 1e0b6da49..062fc309d 100644 --- a/model-view-intent/src/main/java/com/iluwatar/model/view/intent/actions/package-info.java +++ b/model-view-intent/src/main/java/com/iluwatar/model/view/intent/actions/package-info.java @@ -23,8 +23,7 @@ * THE SOFTWARE. */ /** - * Handle actions for {@link com.iluwatar.model.view.intent.CalculatorModel} - * defined by {@link com.iluwatar.model.view.intent.actions.CalculatorAction}. + * Handle actions for {@link com.iluwatar.model.view.intent.CalculatorModel} defined by {@link + * com.iluwatar.model.view.intent.actions.CalculatorAction}. */ - package com.iluwatar.model.view.intent.actions; diff --git a/model-view-intent/src/main/java/com/iluwatar/model/view/intent/package-info.java b/model-view-intent/src/main/java/com/iluwatar/model/view/intent/package-info.java index 7b00c1d1a..654eb228b 100644 --- a/model-view-intent/src/main/java/com/iluwatar/model/view/intent/package-info.java +++ b/model-view-intent/src/main/java/com/iluwatar/model/view/intent/package-info.java @@ -22,9 +22,5 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -/** - * Define Model, View and ViewModel. - * Use them in {@link com.iluwatar.model.view.intent.App} - */ - +/** Define Model, View and ViewModel. Use them in {@link com.iluwatar.model.view.intent.App} */ package com.iluwatar.model.view.intent; diff --git a/model-view-intent/src/test/java/com/iluwatar/model/view/intent/AppTest.java b/model-view-intent/src/test/java/com/iluwatar/model/view/intent/AppTest.java index 6adc84c64..b28ad3cab 100644 --- a/model-view-intent/src/test/java/com/iluwatar/model/view/intent/AppTest.java +++ b/model-view-intent/src/test/java/com/iluwatar/model/view/intent/AppTest.java @@ -24,17 +24,15 @@ */ package com.iluwatar.model.view.intent; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -/** - * Application test - */ +import org.junit.jupiter.api.Test; + +/** Application test */ class AppTest { @Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/model-view-intent/src/test/java/com/iluwatar/model/view/intent/CalculatorViewModelTest.java b/model-view-intent/src/test/java/com/iluwatar/model/view/intent/CalculatorViewModelTest.java index 453def145..492c965fe 100644 --- a/model-view-intent/src/test/java/com/iluwatar/model/view/intent/CalculatorViewModelTest.java +++ b/model-view-intent/src/test/java/com/iluwatar/model/view/intent/CalculatorViewModelTest.java @@ -24,12 +24,12 @@ */ package com.iluwatar.model.view.intent; +import static org.junit.jupiter.api.Assertions.assertEquals; + import com.iluwatar.model.view.intent.actions.*; -import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; class CalculatorViewModelTest { @@ -50,9 +50,7 @@ class CalculatorViewModelTest { @Test void testSetVariable() { - List actions = List.of( - new SetVariableCalculatorAction(10.0) - ); + List actions = List.of(new SetVariableCalculatorAction(10.0)); CalculatorModel model = modelAfterExecutingActions(actions); assertEquals(10.0, model.getVariable()); assertEquals(0, model.getOutput()); @@ -60,13 +58,13 @@ class CalculatorViewModelTest { @Test void testAddition() { - List actions = List.of( - new SetVariableCalculatorAction(2.0), - new AdditionCalculatorAction(), - new AdditionCalculatorAction(), - new SetVariableCalculatorAction(7.0), - new AdditionCalculatorAction() - ); + List actions = + List.of( + new SetVariableCalculatorAction(2.0), + new AdditionCalculatorAction(), + new AdditionCalculatorAction(), + new SetVariableCalculatorAction(7.0), + new AdditionCalculatorAction()); CalculatorModel model = modelAfterExecutingActions(actions); assertEquals(7.0, model.getVariable()); assertEquals(11.0, model.getOutput()); @@ -74,12 +72,12 @@ class CalculatorViewModelTest { @Test void testSubtraction() { - List actions = List.of( - new SetVariableCalculatorAction(2.0), - new AdditionCalculatorAction(), - new AdditionCalculatorAction(), - new SubtractionCalculatorAction() - ); + List actions = + List.of( + new SetVariableCalculatorAction(2.0), + new AdditionCalculatorAction(), + new AdditionCalculatorAction(), + new SubtractionCalculatorAction()); CalculatorModel model = modelAfterExecutingActions(actions); assertEquals(2.0, model.getVariable()); assertEquals(2.0, model.getOutput()); @@ -87,12 +85,12 @@ class CalculatorViewModelTest { @Test void testMultiplication() { - List actions = List.of( - new SetVariableCalculatorAction(2.0), - new AdditionCalculatorAction(), - new AdditionCalculatorAction(), - new MultiplicationCalculatorAction() - ); + List actions = + List.of( + new SetVariableCalculatorAction(2.0), + new AdditionCalculatorAction(), + new AdditionCalculatorAction(), + new MultiplicationCalculatorAction()); CalculatorModel model = modelAfterExecutingActions(actions); assertEquals(2.0, model.getVariable()); assertEquals(8.0, model.getOutput()); @@ -100,15 +98,15 @@ class CalculatorViewModelTest { @Test void testDivision() { - List actions = List.of( - new SetVariableCalculatorAction(2.0), - new AdditionCalculatorAction(), - new AdditionCalculatorAction(), - new SetVariableCalculatorAction(2.0), - new DivisionCalculatorAction() - ); + List actions = + List.of( + new SetVariableCalculatorAction(2.0), + new AdditionCalculatorAction(), + new AdditionCalculatorAction(), + new SetVariableCalculatorAction(2.0), + new DivisionCalculatorAction()); CalculatorModel model = modelAfterExecutingActions(actions); assertEquals(2.0, model.getVariable()); assertEquals(2.0, model.getOutput()); } -} \ No newline at end of file +} diff --git a/model-view-presenter/pom.xml b/model-view-presenter/pom.xml index ab49c8f2f..9dcd55f61 100644 --- a/model-view-presenter/pom.xml +++ b/model-view-presenter/pom.xml @@ -36,6 +36,14 @@ model-view-presenter http://maven.apache.org + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/App.java b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/App.java index 7bee50111..45f772560 100644 --- a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/App.java +++ b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/App.java @@ -34,8 +34,8 @@ package com.iluwatar.model.view.presenter; * FileSelectorJframe} is the GUI and the {@link FileSelectorPresenter} is responsible to respond to * users' actions. * - *

Finally, please notice the wiring between the Presenter and the View and between the - * Presenter and the Model. + *

Finally, please notice the wiring between the Presenter and the View and between the Presenter + * and the Model. */ public class App { 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 871cbedd2..b2678c811 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 @@ -43,27 +43,18 @@ import org.slf4j.LoggerFactory; @Getter public class FileLoader implements Serializable { - /** - * Generated serial version UID. - */ - @Serial - private static final long serialVersionUID = -4745803872902019069L; + /** Generated serial version UID. */ + @Serial private static final long serialVersionUID = -4745803872902019069L; private static final Logger LOGGER = LoggerFactory.getLogger(FileLoader.class); - /** - * Indicates if the file is loaded or not. - */ + /** Indicates if the file is loaded or not. */ private boolean loaded; - /** - * The name of the file that we want to load. - */ + /** The name of the file that we want to load. */ private String fileName; - /** - * Loads the data of the file specified. - */ + /** Loads the data of the file specified. */ public String loadData() { var dataFileName = this.fileName; try (var br = new BufferedReader(new FileReader(dataFileName))) { diff --git a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorJframe.java b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorJframe.java index fa7f3cdaf..1680e5455 100644 --- a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorJframe.java +++ b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorJframe.java @@ -45,45 +45,28 @@ import javax.swing.JTextField; */ public class FileSelectorJframe extends JFrame implements FileSelectorView, ActionListener { - /** - * Default serial version ID. - */ - @Serial - private static final long serialVersionUID = 1L; + /** Default serial version ID. */ + @Serial private static final long serialVersionUID = 1L; - /** - * The "OK" button for loading the file. - */ + /** The "OK" button for loading the file. */ private final JButton ok; - /** - * The cancel button. - */ + /** The cancel button. */ private final JButton cancel; - /** - * The text field for giving the name of the file that we want to open. - */ + /** The text field for giving the name of the file that we want to open. */ private final JTextField input; - /** - * A text area that will keep the contents of the file opened. - */ + /** A text area that will keep the contents of the file opened. */ private final JTextArea area; - /** - * The Presenter component that the frame will interact with. - */ + /** The Presenter component that the frame will interact with. */ private FileSelectorPresenter presenter; - /** - * The name of the file that we want to read it's contents. - */ + /** The name of the file that we want to read it's contents. */ private String fileName; - /** - * Constructor. - */ + /** Constructor. */ public FileSelectorJframe() { super("File Loader"); this.setDefaultCloseOperation(EXIT_ON_CLOSE); diff --git a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorPresenter.java b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorPresenter.java index 170c0f1ce..3c15408bd 100644 --- a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorPresenter.java +++ b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorPresenter.java @@ -35,20 +35,13 @@ import java.io.Serializable; */ public class FileSelectorPresenter implements Serializable { - /** - * Generated serial version UID. - */ - @Serial - private static final long serialVersionUID = 1210314339075855074L; + /** Generated serial version UID. */ + @Serial private static final long serialVersionUID = 1210314339075855074L; - /** - * The View component that the presenter interacts with. - */ + /** The View component that the presenter interacts with. */ private final FileSelectorView view; - /** - * The Model component that the presenter interacts with. - */ + /** The Model component that the presenter interacts with. */ private FileLoader loader; /** @@ -69,24 +62,18 @@ public class FileSelectorPresenter implements Serializable { this.loader = loader; } - /** - * Starts the presenter. - */ + /** Starts the presenter. */ public void start() { view.setPresenter(this); view.open(); } - /** - * An "event" that fires when the name of the file to be loaded changes. - */ + /** An "event" that fires when the name of the file to be loaded changes. */ public void fileNameChanged() { loader.setFileName(view.getFileName()); } - /** - * Ok button handler. - */ + /** Ok button handler. */ public void confirmed() { if (loader.getFileName() == null || loader.getFileName().isEmpty()) { view.showMessage("Please give the name of the file first!"); @@ -101,9 +88,7 @@ public class FileSelectorPresenter implements Serializable { } } - /** - * Cancels the file loading process. - */ + /** Cancels the file loading process. */ public void cancelled() { view.close(); } diff --git a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorStub.java b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorStub.java index ed09627a2..3eda80eb2 100644 --- a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorStub.java +++ b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorStub.java @@ -36,34 +36,22 @@ package com.iluwatar.model.view.presenter; */ public class FileSelectorStub implements FileSelectorView { - /** - * Indicates whether or not the view is opened. - */ + /** Indicates whether or not the view is opened. */ private boolean opened; - /** - * The presenter Component. - */ + /** The presenter Component. */ private FileSelectorPresenter presenter; - /** - * The current name of the file. - */ + /** The current name of the file. */ private String name; - /** - * Indicates the number of messages that were "displayed" to the user. - */ + /** Indicates the number of messages that were "displayed" to the user. */ private int numOfMessageSent; - /** - * Indicates if the data of the file where displayed or not. - */ + /** Indicates if the data of the file where displayed or not. */ private boolean dataDisplayed; - /** - * Constructor. - */ + /** Constructor. */ public FileSelectorStub() { this.opened = false; this.presenter = null; @@ -117,9 +105,7 @@ public class FileSelectorStub implements FileSelectorView { this.dataDisplayed = true; } - /** - * Returns the number of messages that were displayed to the user. - */ + /** Returns the number of messages that were displayed to the user. */ public int getMessagesSent() { return this.numOfMessageSent; } diff --git a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorView.java b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorView.java index b2d916ac1..9a0b86a0b 100644 --- a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorView.java +++ b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorView.java @@ -32,14 +32,10 @@ import java.io.Serializable; */ public interface FileSelectorView extends Serializable { - /** - * Opens the view. - */ + /** Opens the view. */ void open(); - /** - * Closes the view. - */ + /** Closes the view. */ void close(); /** diff --git a/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/AppTest.java b/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/AppTest.java index 785795189..91c7e8dbd 100644 --- a/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/AppTest.java +++ b/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/AppTest.java @@ -24,18 +24,15 @@ */ package com.iluwatar.model.view.presenter; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -/** - * Application test - */ +import org.junit.jupiter.api.Test; + +/** Application test */ class AppTest { @Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } - } diff --git a/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/FileLoaderTest.java b/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/FileLoaderTest.java index 8edf9b40b..b12877d35 100644 --- a/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/FileLoaderTest.java +++ b/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/FileLoaderTest.java @@ -28,10 +28,7 @@ import static org.junit.jupiter.api.Assertions.assertNull; import org.junit.jupiter.api.Test; -/** - * FileLoaderTest - * - */ +/** FileLoaderTest */ class FileLoaderTest { @Test @@ -40,5 +37,4 @@ class FileLoaderTest { fileLoader.setFileName("non-existing-file"); assertNull(fileLoader.loadData()); } - -} \ No newline at end of file +} diff --git a/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/FileSelectorJframeTest.java b/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/FileSelectorJframeTest.java index 66107ebb5..47b10737d 100644 --- a/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/FileSelectorJframeTest.java +++ b/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/FileSelectorJframeTest.java @@ -27,25 +27,19 @@ package com.iluwatar.model.view.presenter; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import java.awt.event.ActionEvent; - import org.junit.jupiter.api.Test; -/** - * FileSelectorJframeTest - * - */ +/** FileSelectorJframeTest */ class FileSelectorJframeTest { - - /** - * Tests if the jframe action event is triggered without any exception. - */ - @Test - void testActionEvent() { - assertDoesNotThrow(() ->{ - FileSelectorJframe jFrame = new FileSelectorJframe(); - ActionEvent action = new ActionEvent("dummy", 1, "dummy"); - jFrame.actionPerformed(action); - }); - } + /** Tests if the jframe action event is triggered without any exception. */ + @Test + void testActionEvent() { + assertDoesNotThrow( + () -> { + FileSelectorJframe jFrame = new FileSelectorJframe(); + ActionEvent action = new ActionEvent("dummy", 1, "dummy"); + jFrame.actionPerformed(action); + }); + } } diff --git a/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/FileSelectorPresenterTest.java b/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/FileSelectorPresenterTest.java index b9a31253b..dca646c20 100644 --- a/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/FileSelectorPresenterTest.java +++ b/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/FileSelectorPresenterTest.java @@ -38,24 +38,16 @@ import org.junit.jupiter.api.Test; */ class FileSelectorPresenterTest { - /** - * The Presenter component. - */ + /** The Presenter component. */ private FileSelectorPresenter presenter; - /** - * The View component, implemented this time as a Stub!!! - */ + /** The View component, implemented this time as a Stub!!! */ private FileSelectorStub stub; - /** - * The Model component. - */ + /** The Model component. */ private FileLoader loader; - /** - * Initializes the components of the test case. - */ + /** Initializes the components of the test case. */ @BeforeEach void setUp() { this.stub = new FileSelectorStub(); @@ -64,9 +56,7 @@ class FileSelectorPresenterTest { presenter.setLoader(loader); } - /** - * Tests if the Presenter was successfully connected with the View. - */ + /** Tests if the Presenter was successfully connected with the View. */ @Test void wiring() { presenter.start(); @@ -75,9 +65,7 @@ class FileSelectorPresenterTest { assertTrue(stub.isOpened()); } - /** - * Tests if the name of the file changes. - */ + /** Tests if the name of the file changes. */ @Test void updateFileNameToLoader() { var expectedFile = "Stamatis"; @@ -105,9 +93,7 @@ class FileSelectorPresenterTest { assertEquals(1, stub.getMessagesSent()); } - /** - * Tests if we receive a confirmation when we attempt to open a file that it doesn't exist. - */ + /** Tests if we receive a confirmation when we attempt to open a file that it doesn't exist. */ @Test void fileConfirmationWhenFileDoesNotExist() { stub.setFileName("RandomName.txt"); @@ -120,9 +106,7 @@ class FileSelectorPresenterTest { assertEquals(1, stub.getMessagesSent()); } - /** - * Tests if we can open the file, when it exists. - */ + /** Tests if we can open the file, when it exists. */ @Test void fileConfirmationWhenFileExists() { stub.setFileName("etc/data/test.txt"); @@ -134,9 +118,7 @@ class FileSelectorPresenterTest { assertTrue(stub.dataDisplayed()); } - /** - * Tests if the view closes after cancellation. - */ + /** Tests if the view closes after cancellation. */ @Test void cancellation() { presenter.start(); @@ -155,5 +137,4 @@ class FileSelectorPresenterTest { assertFalse(loader.isLoaded()); assertFalse(stub.dataDisplayed()); } - } diff --git a/model-view-viewmodel/src/main/java/com/iluwatar/model/view/viewmodel/Book.java b/model-view-viewmodel/src/main/java/com/iluwatar/model/view/viewmodel/Book.java index 27f679402..e7f8f0358 100644 --- a/model-view-viewmodel/src/main/java/com/iluwatar/model/view/viewmodel/Book.java +++ b/model-view-viewmodel/src/main/java/com/iluwatar/model/view/viewmodel/Book.java @@ -27,9 +27,7 @@ package com.iluwatar.model.view.viewmodel; import lombok.AllArgsConstructor; import lombok.Data; -/** - * Book class. - */ +/** Book class. */ @AllArgsConstructor @Data public class Book { @@ -37,5 +35,4 @@ public class Book { private String name; private String author; private String description; - } diff --git a/model-view-viewmodel/src/main/java/com/iluwatar/model/view/viewmodel/BookService.java b/model-view-viewmodel/src/main/java/com/iluwatar/model/view/viewmodel/BookService.java index b5f19b7c0..34bb25c07 100644 --- a/model-view-viewmodel/src/main/java/com/iluwatar/model/view/viewmodel/BookService.java +++ b/model-view-viewmodel/src/main/java/com/iluwatar/model/view/viewmodel/BookService.java @@ -27,9 +27,7 @@ package com.iluwatar.model.view.viewmodel; import java.util.List; -/** - * Class representing a service to load books. - */ +/** Class representing a service to load books. */ public interface BookService { /* List all books * @return all books diff --git a/model-view-viewmodel/src/main/java/com/iluwatar/model/view/viewmodel/BookServiceImpl.java b/model-view-viewmodel/src/main/java/com/iluwatar/model/view/viewmodel/BookServiceImpl.java index a407b1e8f..7d7257fcc 100644 --- a/model-view-viewmodel/src/main/java/com/iluwatar/model/view/viewmodel/BookServiceImpl.java +++ b/model-view-viewmodel/src/main/java/com/iluwatar/model/view/viewmodel/BookServiceImpl.java @@ -27,39 +27,44 @@ package com.iluwatar.model.view.viewmodel; import java.util.ArrayList; import java.util.List; -/** - * Class that actually implement the books to load. - */ +/** Class that actually implement the books to load. */ public class BookServiceImpl implements BookService { private List designPatternBooks = new ArrayList<>(); - /** Initializes Book Data. - * To be used and passed along in load method - * In this case, list design pattern books are initialized to be loaded. - */ + /** + * Initializes Book Data. To be used and passed along in load method In this case, list design + * pattern books are initialized to be loaded. + */ public BookServiceImpl() { - designPatternBooks.add(new Book( - "Head First Design Patterns: A Brain-Friendly Guide", - "Eric Freeman, Bert Bates, Kathy Sierra, Elisabeth Robson", - "Head First Design Patterns Description")); - designPatternBooks.add(new Book( - "Design Patterns: Elements of Reusable Object-Oriented Software", - "Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides", - "Design Patterns Description")); - designPatternBooks.add(new Book( - "Patterns of Enterprise Application Architecture", "Martin Fowler", - "Patterns of Enterprise Application Architecture Description")); - designPatternBooks.add(new Book( - "Design Patterns Explained", "Alan Shalloway, James Trott", - "Design Patterns Explained Description")); - designPatternBooks.add(new Book( - "Applying UML and Patterns: An Introduction to " - + "Object-Oriented Analysis and Design and Iterative Development", - "Craig Larman", "Applying UML and Patterns Description")); + designPatternBooks.add( + new Book( + "Head First Design Patterns: A Brain-Friendly Guide", + "Eric Freeman, Bert Bates, Kathy Sierra, Elisabeth Robson", + "Head First Design Patterns Description")); + designPatternBooks.add( + new Book( + "Design Patterns: Elements of Reusable Object-Oriented Software", + "Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides", + "Design Patterns Description")); + designPatternBooks.add( + new Book( + "Patterns of Enterprise Application Architecture", + "Martin Fowler", + "Patterns of Enterprise Application Architecture Description")); + designPatternBooks.add( + new Book( + "Design Patterns Explained", + "Alan Shalloway, James Trott", + "Design Patterns Explained Description")); + designPatternBooks.add( + new Book( + "Applying UML and Patterns: An Introduction to " + + "Object-Oriented Analysis and Design and Iterative Development", + "Craig Larman", + "Applying UML and Patterns Description")); } public List load() { return designPatternBooks; } - } diff --git a/model-view-viewmodel/src/main/java/com/iluwatar/model/view/viewmodel/BookViewModel.java b/model-view-viewmodel/src/main/java/com/iluwatar/model/view/viewmodel/BookViewModel.java index e00cb623f..7eb81d1f0 100644 --- a/model-view-viewmodel/src/main/java/com/iluwatar/model/view/viewmodel/BookViewModel.java +++ b/model-view-viewmodel/src/main/java/com/iluwatar/model/view/viewmodel/BookViewModel.java @@ -26,22 +26,17 @@ package com.iluwatar.model.view.viewmodel; import java.util.List; import lombok.Getter; -import lombok.Setter; import org.zkoss.bind.annotation.Command; import org.zkoss.bind.annotation.NotifyChange; import org.zkoss.zk.ui.select.annotation.WireVariable; -/** - * BookViewModel class. - */ +/** BookViewModel class. */ public class BookViewModel { - - @WireVariable - private List bookList; - @Getter - private Book selectedBook; + + @WireVariable private List bookList; + @Getter private Book selectedBook; private BookService bookService = new BookServiceImpl(); - + @NotifyChange("selectedBook") public void setSelectedBook(Book selectedBook) { this.selectedBook = selectedBook; @@ -50,11 +45,11 @@ public class BookViewModel { public List getBookList() { return bookService.load(); } - - /** Deleting a book. - * When event is triggered on click of Delete button, - * this method will be notified with the selected entry that will be referenced - * and used to delete the selected book from the list of books. + + /** + * Deleting a book. When event is triggered on click of Delete button, this method will be + * notified with the selected entry that will be referenced and used to delete the selected book + * from the list of books. */ @Command @NotifyChange({"selectedBook", "bookList"}) @@ -64,5 +59,4 @@ public class BookViewModel { selectedBook = null; } } - } diff --git a/model-view-viewmodel/src/test/java/com/iluwatar/model/view/viewmodel/BookTest.java b/model-view-viewmodel/src/test/java/com/iluwatar/model/view/viewmodel/BookTest.java index bec79d011..71f3d8a51 100644 --- a/model-view-viewmodel/src/test/java/com/iluwatar/model/view/viewmodel/BookTest.java +++ b/model-view-viewmodel/src/test/java/com/iluwatar/model/view/viewmodel/BookTest.java @@ -30,6 +30,7 @@ import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -41,27 +42,33 @@ class BookTest { List testBookList; Book testBookTwo; Book testBookThree; - + @BeforeEach void setUp() { bvm = new BookViewModel(); - testBook = new Book("Head First Design Patterns: A Brain-Friendly Guide", - "Eric Freeman, Bert Bates, Kathy Sierra, Elisabeth Robson", - "Head First Design Patterns Description"); + testBook = + new Book( + "Head First Design Patterns: A Brain-Friendly Guide", + "Eric Freeman, Bert Bates, Kathy Sierra, Elisabeth Robson", + "Head First Design Patterns Description"); testBookList = bvm.getBookList(); - testBookTwo = new Book("Head First Design Patterns: A Brain-Friendly Guide", - "Eric Freeman, Bert Bates, Kathy Sierra, Elisabeth Robson", - "Head First Design Patterns Description"); - testBookThree = new Book("Design Patterns: Elements of Reusable Object-Oriented Software", + testBookTwo = + new Book( + "Head First Design Patterns: A Brain-Friendly Guide", + "Eric Freeman, Bert Bates, Kathy Sierra, Elisabeth Robson", + "Head First Design Patterns Description"); + testBookThree = + new Book( + "Design Patterns: Elements of Reusable Object-Oriented Software", "Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides", "Design Patterns Description"); } @Test void testBookModel() { - assertNotNull(testBook); + assertNotNull(testBook); } - + @Test void testEquals() { assertEquals(testBook, testBookTwo); @@ -72,13 +79,13 @@ class BookTest { assertEquals(testBook.toString(), testBookTwo.toString()); assertNotEquals(testBook.toString(), testBookThree.toString()); } - + @Test void testHashCode() { assertTrue(testBook.equals(testBookTwo) && testBookTwo.equals(testBook)); assertEquals(testBook.hashCode(), testBookTwo.hashCode()); } - + @Test void testLoadData() { assertNotNull(testBookList); @@ -87,7 +94,7 @@ class BookTest { @Test void testSelectedData() { - bvm.setSelectedBook(testBook); + bvm.setSelectedBook(testBook); assertNotNull(bvm.getSelectedBook()); assertEquals(testBook.toString(), bvm.getSelectedBook().toString()); assertTrue(true, bvm.getSelectedBook().toString()); @@ -102,5 +109,4 @@ class BookTest { assertNull(bvm.getSelectedBook()); assertFalse(testBookList.get(0).toString().contains("Head First Design Patterns")); } - -} \ No newline at end of file +} diff --git a/monad/pom.xml b/monad/pom.xml index e48e6538b..7837b60c8 100644 --- a/monad/pom.xml +++ b/monad/pom.xml @@ -34,6 +34,14 @@ monad + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/monad/src/main/java/com/iluwatar/monad/App.java b/monad/src/main/java/com/iluwatar/monad/App.java index 7ee04f1b8..56e1c59da 100644 --- a/monad/src/main/java/com/iluwatar/monad/App.java +++ b/monad/src/main/java/com/iluwatar/monad/App.java @@ -1,63 +1,66 @@ -/* - * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). - * - * The MIT License - * Copyright © 2014-2022 Ilkka Seppälä - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package com.iluwatar.monad; - -import java.util.Objects; -import java.util.function.Function; -import java.util.function.Predicate; -import lombok.extern.slf4j.Slf4j; - -/** - * The Monad pattern defines a monad structure, that enables chaining operations in pipelines and - * processing data step by step. Formally, monad consists of a type constructor M and two - * operations: - *
bind - that takes monadic object and a function from plain object to the - * monadic value and returns monadic value. - *
return - that takes plain type object and returns this object wrapped in a monadic value. - * - *

In the given example, the Monad pattern is represented as a {@link Validator} that takes an - * instance of a plain object with {@link Validator#of(Object)} and validates it {@link - * Validator#validate(Function, Predicate, String)} against given predicates. - * - *

As a validation result {@link Validator#get()} either returns valid object - * or throws {@link IllegalStateException} with list of exceptions collected during validation. - */ -@Slf4j -public class App { - - /** - * Program entry point. - * - * @param args command line args - */ - public static void main(String[] args) { - var user = new User("user", 24, Sex.FEMALE, "foobar.com"); - LOGGER.info(Validator.of(user).validate(User::name, Objects::nonNull, "name is null") - .validate(User::name, name -> !name.isEmpty(), "name is empty") - .validate(User::email, email -> !email.contains("@"), "email doesn't contains '@'") - .validate(User::age, age -> age > 20 && age < 30, "age isn't between...").get() - .toString()); - } -} +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.monad; + +import java.util.Objects; +import java.util.function.Function; +import java.util.function.Predicate; +import lombok.extern.slf4j.Slf4j; + +/** + * The Monad pattern defines a monad structure, that enables chaining operations in pipelines and + * processing data step by step. Formally, monad consists of a type constructor M and two + * operations:
+ * bind - that takes monadic object and a function from plain object to the monadic value and + * returns monadic value.
+ * return - that takes plain type object and returns this object wrapped in a monadic value. + * + *

In the given example, the Monad pattern is represented as a {@link Validator} that takes an + * instance of a plain object with {@link Validator#of(Object)} and validates it {@link + * Validator#validate(Function, Predicate, String)} against given predicates. + * + *

As a validation result {@link Validator#get()} either returns valid object or throws {@link + * IllegalStateException} with list of exceptions collected during validation. + */ +@Slf4j +public class App { + + /** + * Program entry point. + * + * @param args command line args + */ + public static void main(String[] args) { + var user = new User("user", 24, Sex.FEMALE, "foobar.com"); + LOGGER.info( + Validator.of(user) + .validate(User::name, Objects::nonNull, "name is null") + .validate(User::name, name -> !name.isEmpty(), "name is empty") + .validate(User::email, email -> !email.contains("@"), "email doesn't contains '@'") + .validate(User::age, age -> age > 20 && age < 30, "age isn't between...") + .get() + .toString()); + } +} diff --git a/monad/src/main/java/com/iluwatar/monad/Sex.java b/monad/src/main/java/com/iluwatar/monad/Sex.java index 5979187a5..7a5189f53 100644 --- a/monad/src/main/java/com/iluwatar/monad/Sex.java +++ b/monad/src/main/java/com/iluwatar/monad/Sex.java @@ -1,32 +1,31 @@ -/* - * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). - * - * The MIT License - * Copyright © 2014-2022 Ilkka Seppälä - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package com.iluwatar.monad; - -/** - * Enumeration of Types of Sex. - */ -public enum Sex { - MALE, FEMALE -} +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.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 089279a8d..dd419a36d 100644 --- a/monad/src/main/java/com/iluwatar/monad/User.java +++ b/monad/src/main/java/com/iluwatar/monad/User.java @@ -27,11 +27,9 @@ package com.iluwatar.monad; /** * Record class. * - * @param name - name - * @param age - age - * @param sex - sex + * @param name - name + * @param age - age + * @param sex - sex * @param email - email address */ -public record User(String name, int age, Sex sex, String email) { -} - +public record User(String name, int age, Sex sex, String email) {} diff --git a/monad/src/main/java/com/iluwatar/monad/Validator.java b/monad/src/main/java/com/iluwatar/monad/Validator.java index 757343e75..0aef2f67c 100644 --- a/monad/src/main/java/com/iluwatar/monad/Validator.java +++ b/monad/src/main/java/com/iluwatar/monad/Validator.java @@ -1,121 +1,116 @@ -/* - * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). - * - * The MIT License - * Copyright © 2014-2022 Ilkka Seppälä - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package com.iluwatar.monad; - -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; -import java.util.function.Function; -import java.util.function.Predicate; - -/** - * Class representing Monad design pattern. Monad is a way of chaining operations on the given - * object together step by step. In Validator each step results in either success or failure - * indicator, giving a way of receiving each of them easily and finally getting validated object or - * list of exceptions. - * - * @param Placeholder for an object. - */ -public class Validator { - /** - * Object that is validated. - */ - private final T obj; - - /** - * List of exception thrown during validation. - */ - private final List exceptions = new ArrayList<>(); - - /** - * Creates a monadic value of given object. - * - * @param obj object to be validated - */ - private Validator(T obj) { - this.obj = obj; - } - - /** - * Creates validator against given object. - * - * @param t object to be validated - * @param object's type - * @return new instance of a validator - */ - public static Validator of(T t) { - return new Validator<>(Objects.requireNonNull(t)); - } - - /** - * Checks if the validation is successful. - * - * @param validation one argument boolean-valued function that represents one step of validation. - * Adds exception to main validation exception list when single step validation - * ends with failure. - * @param message error message when object is invalid - * @return this - */ - public Validator validate(Predicate validation, String message) { - if (!validation.test(obj)) { - exceptions.add(new IllegalStateException(message)); - } - return this; - } - - /** - * Extension for the {@link Validator#validate(Predicate, String)} method, dedicated for objects, - * that need to be projected before requested validation. - * - * @param projection function that gets an objects, and returns projection representing element to - * be validated. - * @param validation see {@link Validator#validate(Predicate, String)} - * @param message see {@link Validator#validate(Predicate, String)} - * @param see {@link Validator#validate(Predicate, String)} - * @return this - */ - public Validator validate( - Function projection, - Predicate validation, - String message - ) { - return validate(projection.andThen(validation::test)::apply, message); - } - - /** - * Receives validated object or throws exception when invalid. - * - * @return object that was validated - * @throws IllegalStateException when any validation step results with failure - */ - public T get() throws IllegalStateException { - if (exceptions.isEmpty()) { - return obj; - } - var e = new IllegalStateException(); - exceptions.forEach(e::addSuppressed); - throw e; - } -} +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.monad; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.function.Function; +import java.util.function.Predicate; + +/** + * Class representing Monad design pattern. Monad is a way of chaining operations on the given + * object together step by step. In Validator each step results in either success or failure + * indicator, giving a way of receiving each of them easily and finally getting validated object or + * list of exceptions. + * + * @param Placeholder for an object. + */ +public class Validator { + /** Object that is validated. */ + private final T obj; + + /** List of exception thrown during validation. */ + private final List exceptions = new ArrayList<>(); + + /** + * Creates a monadic value of given object. + * + * @param obj object to be validated + */ + private Validator(T obj) { + this.obj = obj; + } + + /** + * Creates validator against given object. + * + * @param t object to be validated + * @param object's type + * @return new instance of a validator + */ + public static Validator of(T t) { + return new Validator<>(Objects.requireNonNull(t)); + } + + /** + * Checks if the validation is successful. + * + * @param validation one argument boolean-valued function that represents one step of validation. + * Adds exception to main validation exception list when single step validation ends with + * failure. + * @param message error message when object is invalid + * @return this + */ + public Validator validate(Predicate validation, String message) { + if (!validation.test(obj)) { + exceptions.add(new IllegalStateException(message)); + } + return this; + } + + /** + * Extension for the {@link Validator#validate(Predicate, String)} method, dedicated for objects, + * that need to be projected before requested validation. + * + * @param projection function that gets an objects, and returns projection representing element to + * be validated. + * @param validation see {@link Validator#validate(Predicate, String)} + * @param message see {@link Validator#validate(Predicate, String)} + * @param see {@link Validator#validate(Predicate, String)} + * @return this + */ + public Validator validate( + Function projection, + Predicate validation, + String message) { + return validate(projection.andThen(validation::test)::apply, message); + } + + /** + * Receives validated object or throws exception when invalid. + * + * @return object that was validated + * @throws IllegalStateException when any validation step results with failure + */ + public T get() throws IllegalStateException { + if (exceptions.isEmpty()) { + return obj; + } + var e = new IllegalStateException(); + exceptions.forEach(e::addSuppressed); + throw e; + } +} diff --git a/monad/src/test/java/com/iluwatar/monad/AppTest.java b/monad/src/test/java/com/iluwatar/monad/AppTest.java index 864ede813..9320d4b1c 100644 --- a/monad/src/test/java/com/iluwatar/monad/AppTest.java +++ b/monad/src/test/java/com/iluwatar/monad/AppTest.java @@ -28,15 +28,11 @@ import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import org.junit.jupiter.api.Test; -/** - * Application Test - */ - +/** Application Test */ class AppTest { @Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } - } diff --git a/monad/src/test/java/com/iluwatar/monad/MonadTest.java b/monad/src/test/java/com/iluwatar/monad/MonadTest.java index 1eed42b12..589164884 100644 --- a/monad/src/test/java/com/iluwatar/monad/MonadTest.java +++ b/monad/src/test/java/com/iluwatar/monad/MonadTest.java @@ -30,9 +30,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.Objects; import org.junit.jupiter.api.Test; -/** - * Test for Monad Pattern - */ +/** Test for Monad Pattern */ class MonadTest { @Test @@ -40,10 +38,8 @@ class MonadTest { var tom = new User(null, 21, Sex.MALE, "tom@foo.bar"); assertThrows( IllegalStateException.class, - () -> Validator.of(tom) - .validate(User::name, Objects::nonNull, "name cannot be null") - .get() - ); + () -> + Validator.of(tom).validate(User::name, Objects::nonNull, "name cannot be null").get()); } @Test @@ -51,22 +47,23 @@ class MonadTest { var john = new User("John", 17, Sex.MALE, "john@qwe.bar"); assertThrows( IllegalStateException.class, - () -> Validator.of(john) - .validate(User::name, Objects::nonNull, "name cannot be null") - .validate(User::age, age -> age > 21, "user is underage") - .get() - ); + () -> + Validator.of(john) + .validate(User::name, Objects::nonNull, "name cannot be null") + .validate(User::age, age -> age > 21, "user is underage") + .get()); } @Test void testForValid() { var sarah = new User("Sarah", 42, Sex.FEMALE, "sarah@det.org"); - var validated = Validator.of(sarah) - .validate(User::name, Objects::nonNull, "name cannot be null") - .validate(User::age, age -> age > 21, "user is underage") - .validate(User::sex, sex -> sex == Sex.FEMALE, "user is not female") - .validate(User::email, email -> email.contains("@"), "email does not contain @ sign") - .get(); + var validated = + Validator.of(sarah) + .validate(User::name, Objects::nonNull, "name cannot be null") + .validate(User::age, age -> age > 21, "user is underage") + .validate(User::sex, sex -> sex == Sex.FEMALE, "user is not female") + .validate(User::email, email -> email.contains("@"), "email does not contain @ sign") + .get(); assertSame(validated, sarah); } } diff --git a/money/pom.xml b/money/pom.xml index 0129bab95..fbe629646 100644 --- a/money/pom.xml +++ b/money/pom.xml @@ -41,9 +41,28 @@ org.junit.jupiter - junit-jupiter-api + junit-jupiter-engine test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.App + + + + + + + + \ No newline at end of file diff --git a/money/src/main/java/com/iluwatar/App.java b/money/src/main/java/com/iluwatar/App.java index c677119de..3a31b8b7d 100644 --- a/money/src/main/java/com/iluwatar/App.java +++ b/money/src/main/java/com/iluwatar/App.java @@ -26,6 +26,7 @@ package com.iluwatar; import java.util.logging.Level; import java.util.logging.Logger; + /** * The `App` class demonstrates the functionality of the {@link Money} class, which encapsulates * monetary values and their associated currencies. It showcases operations like addition, @@ -41,6 +42,7 @@ public class App { // Initialize the logger private static final Logger logger = Logger.getLogger(App.class.getName()); + /** * Program entry point. * @@ -79,11 +81,12 @@ public class App { try { double exchangeRateUsdToEur = 0.85; // Example exchange rate usdAmount1.exchangeCurrency("EUR", exchangeRateUsdToEur); - logger.log(Level.INFO, "USD converted to EUR: {0} {1}", new Object[]{usdAmount1.getAmount(), usdAmount1.getCurrency()}); + logger.log( + Level.INFO, + "USD converted to EUR: {0} {1}", + new Object[] {usdAmount1.getAmount(), usdAmount1.getCurrency()}); } catch (IllegalArgumentException e) { logger.log(Level.SEVERE, "Error converting currency: {0}", e.getMessage()); } - } } - diff --git a/money/src/main/java/com/iluwatar/CannotAddTwoCurrienciesException.java b/money/src/main/java/com/iluwatar/CannotAddTwoCurrienciesException.java index 21fd6fb08..022205558 100644 --- a/money/src/main/java/com/iluwatar/CannotAddTwoCurrienciesException.java +++ b/money/src/main/java/com/iluwatar/CannotAddTwoCurrienciesException.java @@ -23,9 +23,8 @@ * THE SOFTWARE. */ package com.iluwatar; -/** - * An exception for when the user tries to add two diffrent currencies. - */ + +/** An exception for when the user tries to add two diffrent currencies. */ public class CannotAddTwoCurrienciesException extends Exception { /** * Constructs an exception with the specified message. @@ -35,4 +34,4 @@ public class CannotAddTwoCurrienciesException extends Exception { public CannotAddTwoCurrienciesException(String message) { super(message); } -} \ No newline at end of file +} diff --git a/money/src/main/java/com/iluwatar/CannotSubtractException.java b/money/src/main/java/com/iluwatar/CannotSubtractException.java index 92205de56..f0403415d 100644 --- a/money/src/main/java/com/iluwatar/CannotSubtractException.java +++ b/money/src/main/java/com/iluwatar/CannotSubtractException.java @@ -23,8 +23,10 @@ * THE SOFTWARE. */ package com.iluwatar; + /** - * An exception for when the user tries to subtract two different currencies or subtract an amount he doesn't have. + * An exception for when the user tries to subtract two different currencies or subtract an amount + * he doesn't have. */ public class CannotSubtractException extends Exception { /** @@ -35,5 +37,4 @@ public class CannotSubtractException extends Exception { public CannotSubtractException(String message) { super(message); } - } diff --git a/money/src/main/java/com/iluwatar/Money.java b/money/src/main/java/com/iluwatar/Money.java index b697dee12..a486c4b4c 100644 --- a/money/src/main/java/com/iluwatar/Money.java +++ b/money/src/main/java/com/iluwatar/Money.java @@ -27,9 +27,9 @@ package com.iluwatar; import lombok.Getter; /** - * Represents a monetary value with an associated currency. - * Provides operations for basic arithmetic (addition, subtraction, multiplication), - * as well as currency conversion while ensuring proper rounding. + * Represents a monetary value with an associated currency. Provides operations for basic arithmetic + * (addition, subtraction, multiplication), as well as currency conversion while ensuring proper + * rounding. */ @Getter public class Money { @@ -74,13 +74,15 @@ public class Money { * Subtracts another Money object from the current instance. * * @param moneyToBeSubtracted the Money object to subtract. - * @throws CannotSubtractException if the currencies do not match or if the amount to subtract is larger than the current amount. + * @throws CannotSubtractException if the currencies do not match or if the amount to subtract is + * larger than the current amount. */ public void subtractMoney(Money moneyToBeSubtracted) throws CannotSubtractException { if (!moneyToBeSubtracted.getCurrency().equals(this.currency)) { throw new CannotSubtractException("You are trying to subtract two different currencies"); } else if (moneyToBeSubtracted.getAmount() > this.amount) { - throw new CannotSubtractException("The amount you are trying to subtract is larger than the amount you have"); + throw new CannotSubtractException( + "The amount you are trying to subtract is larger than the amount you have"); } this.amount = roundToTwoDecimals(this.amount - moneyToBeSubtracted.getAmount()); } diff --git a/money/src/test/java/com/iluwater/money/MoneyTest.java b/money/src/test/java/com/iluwater/money/MoneyTest.java index 15d7e45a8..491b12ee2 100644 --- a/money/src/test/java/com/iluwater/money/MoneyTest.java +++ b/money/src/test/java/com/iluwater/money/MoneyTest.java @@ -24,18 +24,18 @@ */ package com.iluwater.money; -import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; + +import com.iluwatar.App; import com.iluwatar.CannotAddTwoCurrienciesException; import com.iluwatar.CannotSubtractException; import com.iluwatar.Money; -import com.iluwatar.App; +import org.junit.jupiter.api.Test; - - class MoneyTest { +class MoneyTest { @Test - void testConstructor() { + void testConstructor() { // Test the constructor Money money = new Money(100.00, "USD"); assertEquals(100.00, money.getAmount()); @@ -43,7 +43,7 @@ import com.iluwatar.App; } @Test - void testAddMoney_SameCurrency() throws CannotAddTwoCurrienciesException { + void testAddMoney_SameCurrency() throws CannotAddTwoCurrienciesException { // Test adding two Money objects with the same currency Money money1 = new Money(100.00, "USD"); Money money2 = new Money(50.25, "USD"); @@ -54,18 +54,20 @@ import com.iluwatar.App; } @Test - void testAddMoney_DifferentCurrency() { + void testAddMoney_DifferentCurrency() { // Test adding two Money objects with different currencies Money money1 = new Money(100.00, "USD"); Money money2 = new Money(50.25, "EUR"); - assertThrows(CannotAddTwoCurrienciesException.class, () -> { - money1.addMoney(money2); - }); + assertThrows( + CannotAddTwoCurrienciesException.class, + () -> { + money1.addMoney(money2); + }); } @Test - void testSubtractMoney_SameCurrency() throws CannotSubtractException { + void testSubtractMoney_SameCurrency() throws CannotSubtractException { // Test subtracting two Money objects with the same currency Money money1 = new Money(100.00, "USD"); Money money2 = new Money(50.25, "USD"); @@ -76,29 +78,33 @@ import com.iluwatar.App; } @Test - void testSubtractMoney_DifferentCurrency() { + void testSubtractMoney_DifferentCurrency() { // Test subtracting two Money objects with different currencies Money money1 = new Money(100.00, "USD"); Money money2 = new Money(50.25, "EUR"); - assertThrows(CannotSubtractException.class, () -> { - money1.subtractMoney(money2); - }); + assertThrows( + CannotSubtractException.class, + () -> { + money1.subtractMoney(money2); + }); } @Test - void testSubtractMoney_AmountTooLarge() { + void testSubtractMoney_AmountTooLarge() { // Test subtracting an amount larger than the current amount Money money1 = new Money(50.00, "USD"); Money money2 = new Money(60.00, "USD"); - assertThrows(CannotSubtractException.class, () -> { - money1.subtractMoney(money2); - }); + assertThrows( + CannotSubtractException.class, + () -> { + money1.subtractMoney(money2); + }); } @Test - void testMultiply() { + void testMultiply() { // Test multiplying the money amount by a factor Money money = new Money(100.00, "USD"); @@ -108,17 +114,19 @@ import com.iluwatar.App; } @Test - void testMultiply_NegativeFactor() { + void testMultiply_NegativeFactor() { // Test multiplying by a negative factor Money money = new Money(100.00, "USD"); - assertThrows(IllegalArgumentException.class, () -> { - money.multiply(-2); - }); + assertThrows( + IllegalArgumentException.class, + () -> { + money.multiply(-2); + }); } @Test - void testExchangeCurrency() { + void testExchangeCurrency() { // Test converting currency using an exchange rate Money money = new Money(100.00, "USD"); @@ -129,21 +137,23 @@ import com.iluwatar.App; } @Test - void testExchangeCurrency_NegativeExchangeRate() { + void testExchangeCurrency_NegativeExchangeRate() { // Test converting currency with a negative exchange rate Money money = new Money(100.00, "USD"); - assertThrows(IllegalArgumentException.class, () -> { - money.exchangeCurrency("EUR", -0.85); - }); + assertThrows( + IllegalArgumentException.class, + () -> { + money.exchangeCurrency("EUR", -0.85); + }); } - @Test - void testAppExecution() { - assertDoesNotThrow(() -> { - App.main(new String[]{}); - }, "App execution should not throw any exceptions"); - } - + void testAppExecution() { + assertDoesNotThrow( + () -> { + App.main(new String[] {}); + }, + "App execution should not throw any exceptions"); + } } diff --git a/monitor/pom.xml b/monitor/pom.xml index 1f87196d4..67e24c3bb 100644 --- a/monitor/pom.xml +++ b/monitor/pom.xml @@ -34,6 +34,14 @@ monitor + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine @@ -52,7 +60,7 @@ - com.iluwatar.abstractdocument.Main + com.iluwatar.monitor.Main diff --git a/monitor/src/main/java/com/iluwatar/monitor/Bank.java b/monitor/src/main/java/com/iluwatar/monitor/Bank.java index ade21985a..bc89c26ea 100644 --- a/monitor/src/main/java/com/iluwatar/monitor/Bank.java +++ b/monitor/src/main/java/com/iluwatar/monitor/Bank.java @@ -23,27 +23,27 @@ * THE SOFTWARE. */ /* -*The MIT License -*Copyright © 2014-2021 Ilkka Seppälä -* -*Permission is hereby granted, free of charge, to any person obtaining a copy -*of this software and associated documentation files (the "Software"), to deal -*in the Software without restriction, including without limitation the rights -*to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -*copies of the Software, and to permit persons to whom the Software is -*furnished to do so, subject to the following conditions: -* -*The above copyright notice and this permission notice shall be included in -*all copies or substantial portions of the Software. -* -*THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -*IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -*FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -*AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -*LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -*OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -*THE SOFTWARE. -*/ + *The MIT License + *Copyright © 2014-2021 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.monitor; @@ -55,8 +55,7 @@ import lombok.extern.slf4j.Slf4j; @Slf4j public class Bank { - @Getter - private final int[] accounts; + @Getter private final int[] accounts; /** * Constructor. @@ -74,7 +73,7 @@ public class Bank { * * @param accountA - source account * @param accountB - destination account - * @param amount - amount to be transferred + * @param amount - amount to be transferred */ public synchronized void transfer(int accountA, int accountB, int amount) { if (accounts[accountA] >= amount && accountA != accountB) { diff --git a/monitor/src/main/java/com/iluwatar/monitor/Main.java b/monitor/src/main/java/com/iluwatar/monitor/Main.java index 7324e6e7a..37d0af0dd 100644 --- a/monitor/src/main/java/com/iluwatar/monitor/Main.java +++ b/monitor/src/main/java/com/iluwatar/monitor/Main.java @@ -28,6 +28,7 @@ import java.security.SecureRandom; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executors; import lombok.extern.slf4j.Slf4j; + /** * The Monitor pattern is used in concurrent algorithms to achieve mutual exclusion. * @@ -46,7 +47,7 @@ public class Main { /** * Runner to perform a bunch of transfers and handle exception. * - * @param bank bank object + * @param bank bank object * @param latch signal finished execution */ public static void runner(Bank bank, CountDownLatch latch) { diff --git a/monitor/src/test/java/com/iluwatar/monitor/BankTest.java b/monitor/src/test/java/com/iluwatar/monitor/BankTest.java index 6d0c671eb..6f3b9a145 100644 --- a/monitor/src/test/java/com/iluwatar/monitor/BankTest.java +++ b/monitor/src/test/java/com/iluwatar/monitor/BankTest.java @@ -24,11 +24,12 @@ */ package com.iluwatar.monitor; +import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assumptions.*; + import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.*; -import static org.junit.jupiter.api.Assumptions.*; class BankTest { diff --git a/monitor/src/test/java/com/iluwatar/monitor/MainTest.java b/monitor/src/test/java/com/iluwatar/monitor/MainTest.java index 4d69aeebd..fa067cf9d 100644 --- a/monitor/src/test/java/com/iluwatar/monitor/MainTest.java +++ b/monitor/src/test/java/com/iluwatar/monitor/MainTest.java @@ -24,10 +24,11 @@ */ package com.iluwatar.monitor; -import org.junit.jupiter.api.Test; -import java.util.concurrent.CountDownLatch; import static org.junit.jupiter.api.Assertions.*; +import java.util.concurrent.CountDownLatch; +import org.junit.jupiter.api.Test; + /** Test if the application starts without throwing an exception. */ class MainTest { diff --git a/monolithic-architecture/src/main/java/com/iluwatar/monolithic/EcommerceApp.java b/monolithic-architecture/src/main/java/com/iluwatar/monolithic/EcommerceApp.java index 9eed3705a..148dfa176 100644 --- a/monolithic-architecture/src/main/java/com/iluwatar/monolithic/EcommerceApp.java +++ b/monolithic-architecture/src/main/java/com/iluwatar/monolithic/EcommerceApp.java @@ -39,16 +39,13 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; /** * Main entry point for the Monolithic E-commerce application. - * ------------------------------------------------------------------------ - * Monolithic architecture is a software design pattern where all components - * of the application (presentation, business logic, and data access layers) - * are part of a single unified codebase and deployable unit. - * ------------------------------------------------------------------------ - * This example implements a monolithic architecture by integrating - * user management, product management, and order placement within - * the same application, sharing common resources and a single database. + * ------------------------------------------------------------------------ Monolithic architecture + * is a software design pattern where all components of the application (presentation, business + * logic, and data access layers) are part of a single unified codebase and deployable unit. + * ------------------------------------------------------------------------ This example implements + * a monolithic architecture by integrating user management, product management, and order placement + * within the same application, sharing common resources and a single database. */ - @SpringBootApplication public class EcommerceApp implements CommandLineRunner { @@ -56,18 +53,19 @@ public class EcommerceApp implements CommandLineRunner { private final UserController userService; private final ProductController productService; private final OrderController orderService; - /** - * Initilizing controllers as services. - * */ - public EcommerceApp(UserController userService, ProductController productService, OrderController orderService) { + + /** Initilizing controllers as services. */ + public EcommerceApp( + UserController userService, ProductController productService, OrderController orderService) { this.userService = userService; this.productService = productService; this.orderService = orderService; } + /** - * The main entry point for the Monolithic E-commerce application. - * Initializes the Spring Boot application and starts the embedded server. - */ + * The main entry point for the Monolithic E-commerce application. Initializes the Spring Boot + * application and starts the embedded server. + */ public static void main(String... args) { SpringApplication.run(EcommerceApp.class, args); } @@ -100,9 +98,8 @@ public class EcommerceApp implements CommandLineRunner { } } } - /** - * Handles User Registration through user CLI inputs. - * */ + + /** Handles User Registration through user CLI inputs. */ protected void registerUser(Scanner scanner) { log.info("Enter user details:"); log.info("Name: "); @@ -116,9 +113,8 @@ public class EcommerceApp implements CommandLineRunner { userService.registerUser(user); log.info("User registered successfully!"); } - /** - * Handles the addition of products. - * */ + + /** Handles the addition of products. */ protected void addProduct(Scanner scanner) { log.info("Enter product details:"); log.info("Name: "); @@ -134,9 +130,8 @@ public class EcommerceApp implements CommandLineRunner { productService.addProduct(product); log.info("Product added successfully!"); } - /** - * Handles Order Placement through user CLI inputs. - */ + + /** Handles Order Placement through user CLI inputs. */ protected void placeOrder(Scanner scanner) { log.info("Enter order details:"); log.info("User ID: "); diff --git a/monolithic-architecture/src/main/java/com/iluwatar/monolithic/controller/OrderController.java b/monolithic-architecture/src/main/java/com/iluwatar/monolithic/controller/OrderController.java index 897c10b0e..94776a0d2 100644 --- a/monolithic-architecture/src/main/java/com/iluwatar/monolithic/controller/OrderController.java +++ b/monolithic-architecture/src/main/java/com/iluwatar/monolithic/controller/OrderController.java @@ -23,6 +23,7 @@ * THE SOFTWARE. */ package com.iluwatar.monolithic.controller; + import com.iluwatar.monolithic.exceptions.InsufficientStockException; import com.iluwatar.monolithic.exceptions.NonExistentProductException; import com.iluwatar.monolithic.exceptions.NonExistentUserException; @@ -33,30 +34,39 @@ import com.iluwatar.monolithic.repository.OrderRepository; import com.iluwatar.monolithic.repository.ProductRepository; import com.iluwatar.monolithic.repository.UserRepository; import org.springframework.stereotype.Service; -/** - * OrderController is a controller class for managing Order operations. - * */ + +/** OrderController is a controller class for managing Order operations. */ @Service public class OrderController { private final OrderRepository orderRepository; private final UserRepository userRepository; private final ProductRepository productRepository; - /** - * This function handles the initializing of the controller. - * */ - public OrderController(OrderRepository orderRepository, UserRepository userRepository, ProductRepository productRepository) { + + /** This function handles the initializing of the controller. */ + public OrderController( + OrderRepository orderRepository, + UserRepository userRepository, + ProductRepository productRepository) { this.orderRepository = orderRepository; this.userRepository = userRepository; this.productRepository = productRepository; } - /** - * This function handles placing orders with all of its cases. - * */ - public Order placeOrder(Long userId, Long productId, Integer quantity) { - final User user = userRepository.findById(userId).orElseThrow(() -> new NonExistentUserException("User with ID " + userId + " not found")); - final Product product = productRepository.findById(productId).orElseThrow(() -> new NonExistentProductException("Product with ID " + productId + " not found")); - + /** This function handles placing orders with all of its cases. */ + public Order placeOrder(Long userId, Long productId, Integer quantity) { + final User user = + userRepository + .findById(userId) + .orElseThrow( + () -> new NonExistentUserException("User with ID " + userId + " not found")); + + final Product product = + productRepository + .findById(productId) + .orElseThrow( + () -> + new NonExistentProductException("Product with ID " + productId + " not found")); + if (product.getStock() < quantity) { throw new InsufficientStockException("Not enough stock for product " + productId); } diff --git a/monolithic-architecture/src/main/java/com/iluwatar/monolithic/controller/ProductController.java b/monolithic-architecture/src/main/java/com/iluwatar/monolithic/controller/ProductController.java index c2f90276a..b409fd8e8 100644 --- a/monolithic-architecture/src/main/java/com/iluwatar/monolithic/controller/ProductController.java +++ b/monolithic-architecture/src/main/java/com/iluwatar/monolithic/controller/ProductController.java @@ -29,29 +29,22 @@ import com.iluwatar.monolithic.repository.ProductRepository; import java.util.List; import org.springframework.stereotype.Service; -/** - * ProductCon is a controller class for managing Product operations. - * */ - - +/** ProductCon is a controller class for managing Product operations. */ @Service public class ProductController { private final ProductRepository productRepository; - /** - * Linking Controller to DB. - * */ + + /** Linking Controller to DB. */ public ProductController(ProductRepository productRepository) { this.productRepository = productRepository; } - /** - * Adds a product to the DB. - * */ + + /** Adds a product to the DB. */ public Product addProduct(Product product) { return productRepository.save(product); } - /** - * Returns all relevant Product. - * */ + + /** Returns all relevant Product. */ public List getAllProducts() { return productRepository.findAll(); } diff --git a/monolithic-architecture/src/main/java/com/iluwatar/monolithic/controller/UserController.java b/monolithic-architecture/src/main/java/com/iluwatar/monolithic/controller/UserController.java index cec2c6121..a4fe6dbe3 100644 --- a/monolithic-architecture/src/main/java/com/iluwatar/monolithic/controller/UserController.java +++ b/monolithic-architecture/src/main/java/com/iluwatar/monolithic/controller/UserController.java @@ -27,21 +27,18 @@ package com.iluwatar.monolithic.controller; import com.iluwatar.monolithic.model.User; import com.iluwatar.monolithic.repository.UserRepository; import org.springframework.stereotype.Service; -/** - * UserController is a controller class for managing user operations. - */ + +/** UserController is a controller class for managing user operations. */ @Service public class UserController { private final UserRepository userRepository; - /** - * Linking Controller to DB. - */ + + /** Linking Controller to DB. */ public UserController(UserRepository userRepository) { this.userRepository = userRepository; } - /** - * Adds a user to the DB. - */ + + /** Adds a user to the DB. */ public User registerUser(User user) { return userRepository.save(user); } diff --git a/monolithic-architecture/src/main/java/com/iluwatar/monolithic/exceptions/InsufficientStockException.java b/monolithic-architecture/src/main/java/com/iluwatar/monolithic/exceptions/InsufficientStockException.java index 9e476c714..d5fd9edfc 100644 --- a/monolithic-architecture/src/main/java/com/iluwatar/monolithic/exceptions/InsufficientStockException.java +++ b/monolithic-architecture/src/main/java/com/iluwatar/monolithic/exceptions/InsufficientStockException.java @@ -25,15 +25,14 @@ package com.iluwatar.monolithic.exceptions; import java.io.Serial; -/** - * Custom Exception class for enhanced readability. - * */ + +/** Custom Exception class for enhanced readability. */ public class InsufficientStockException extends RuntimeException { - @Serial - private static final long serialVersionUID = 1005208208127745099L; + @Serial private static final long serialVersionUID = 1005208208127745099L; + /** * Exception Constructor that is readable through code and provides the message inputted into it. - * */ + */ public InsufficientStockException(String message) { super(message); } diff --git a/monolithic-architecture/src/main/java/com/iluwatar/monolithic/exceptions/NonExistentProductException.java b/monolithic-architecture/src/main/java/com/iluwatar/monolithic/exceptions/NonExistentProductException.java index 2615f3a8e..63c4821d9 100644 --- a/monolithic-architecture/src/main/java/com/iluwatar/monolithic/exceptions/NonExistentProductException.java +++ b/monolithic-architecture/src/main/java/com/iluwatar/monolithic/exceptions/NonExistentProductException.java @@ -25,15 +25,14 @@ package com.iluwatar.monolithic.exceptions; import java.io.Serial; -/** - * Custom Exception class for enhanced readability. - * */ + +/** Custom Exception class for enhanced readability. */ public class NonExistentProductException extends RuntimeException { - @Serial - private static final long serialVersionUID = -593425162052345565L; + @Serial private static final long serialVersionUID = -593425162052345565L; + /** * Exception Constructor that is readable through code and provides the message inputted into it. - * */ + */ public NonExistentProductException(String msg) { super(msg); } diff --git a/monolithic-architecture/src/main/java/com/iluwatar/monolithic/exceptions/NonExistentUserException.java b/monolithic-architecture/src/main/java/com/iluwatar/monolithic/exceptions/NonExistentUserException.java index 23df21092..99625ad7b 100644 --- a/monolithic-architecture/src/main/java/com/iluwatar/monolithic/exceptions/NonExistentUserException.java +++ b/monolithic-architecture/src/main/java/com/iluwatar/monolithic/exceptions/NonExistentUserException.java @@ -25,15 +25,14 @@ package com.iluwatar.monolithic.exceptions; import java.io.Serial; -/** - * Custom Exception class for enhanced readability. - * */ + +/** Custom Exception class for enhanced readability. */ public class NonExistentUserException extends RuntimeException { - @Serial - private static final long serialVersionUID = -7660909426227843633L; + @Serial private static final long serialVersionUID = -7660909426227843633L; + /** * Exception Constructor that is readable through code and provides the message inputted into it. - * */ + */ public NonExistentUserException(String msg) { super(msg); } diff --git a/monolithic-architecture/src/main/java/com/iluwatar/monolithic/model/Order.java b/monolithic-architecture/src/main/java/com/iluwatar/monolithic/model/Order.java index 09a3c8de8..91caaf9c7 100644 --- a/monolithic-architecture/src/main/java/com/iluwatar/monolithic/model/Order.java +++ b/monolithic-architecture/src/main/java/com/iluwatar/monolithic/model/Order.java @@ -33,9 +33,7 @@ import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; -/** - * Represents a Database in which Order are stored. - */ +/** Represents a Database in which Order are stored. */ @Entity @Data @NoArgsConstructor @@ -45,11 +43,9 @@ public class Order { @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; - @ManyToOne - private User user; + @ManyToOne private User user; - @ManyToOne - private Product product; + @ManyToOne private Product product; private Integer quantity; diff --git a/monolithic-architecture/src/main/java/com/iluwatar/monolithic/model/Product.java b/monolithic-architecture/src/main/java/com/iluwatar/monolithic/model/Product.java index 8c4e442b1..bcfe52c44 100644 --- a/monolithic-architecture/src/main/java/com/iluwatar/monolithic/model/Product.java +++ b/monolithic-architecture/src/main/java/com/iluwatar/monolithic/model/Product.java @@ -32,9 +32,7 @@ import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; -/** - * Represents a database of products. - */ +/** Represents a database of products. */ @Entity @Data @NoArgsConstructor @@ -52,4 +50,3 @@ public class Product { private Integer stock; } - diff --git a/monolithic-architecture/src/main/java/com/iluwatar/monolithic/model/User.java b/monolithic-architecture/src/main/java/com/iluwatar/monolithic/model/User.java index c3c278dbd..0b05f447c 100644 --- a/monolithic-architecture/src/main/java/com/iluwatar/monolithic/model/User.java +++ b/monolithic-architecture/src/main/java/com/iluwatar/monolithic/model/User.java @@ -33,9 +33,7 @@ import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; -/** - * Represents a Product entity for the database. - */ +/** Represents a Product entity for the database. */ @Entity @Data @NoArgsConstructor diff --git a/monolithic-architecture/src/main/java/com/iluwatar/monolithic/repository/OrderRepository.java b/monolithic-architecture/src/main/java/com/iluwatar/monolithic/repository/OrderRepository.java index 366fa1c7b..af38c56f1 100644 --- a/monolithic-architecture/src/main/java/com/iluwatar/monolithic/repository/OrderRepository.java +++ b/monolithic-architecture/src/main/java/com/iluwatar/monolithic/repository/OrderRepository.java @@ -26,8 +26,6 @@ package com.iluwatar.monolithic.repository; import com.iluwatar.monolithic.model.Order; import org.springframework.data.jpa.repository.JpaRepository; -/** - * This interface allows JpaRepository to generate queries for the required tables. - */ -public interface OrderRepository extends JpaRepository { -} + +/** This interface allows JpaRepository to generate queries for the required tables. */ +public interface OrderRepository extends JpaRepository {} diff --git a/monolithic-architecture/src/main/java/com/iluwatar/monolithic/repository/ProductRepository.java b/monolithic-architecture/src/main/java/com/iluwatar/monolithic/repository/ProductRepository.java index 4d4c17521..660ed33bb 100644 --- a/monolithic-architecture/src/main/java/com/iluwatar/monolithic/repository/ProductRepository.java +++ b/monolithic-architecture/src/main/java/com/iluwatar/monolithic/repository/ProductRepository.java @@ -26,8 +26,6 @@ package com.iluwatar.monolithic.repository; import com.iluwatar.monolithic.model.Product; import org.springframework.data.jpa.repository.JpaRepository; -/** - * This interface allows JpaRepository to generate queries for the required tables. - */ -public interface ProductRepository extends JpaRepository { -} + +/** This interface allows JpaRepository to generate queries for the required tables. */ +public interface ProductRepository extends JpaRepository {} diff --git a/monolithic-architecture/src/main/java/com/iluwatar/monolithic/repository/UserRepository.java b/monolithic-architecture/src/main/java/com/iluwatar/monolithic/repository/UserRepository.java index 2a96a1b51..e05c68816 100644 --- a/monolithic-architecture/src/main/java/com/iluwatar/monolithic/repository/UserRepository.java +++ b/monolithic-architecture/src/main/java/com/iluwatar/monolithic/repository/UserRepository.java @@ -26,12 +26,12 @@ package com.iluwatar.monolithic.repository; import com.iluwatar.monolithic.model.User; import org.springframework.data.jpa.repository.JpaRepository; -/** - * This interface allows JpaRepository to generate queries for the required tables. - */ + +/** This interface allows JpaRepository to generate queries for the required tables. */ public interface UserRepository extends JpaRepository { /** - * Utilizes JpaRepository functionalities to generate a function which looks up in the User table using emails. - * */ + * Utilizes JpaRepository functionalities to generate a function which looks up in the User table + * using emails. + */ User findByEmail(String email); -} \ No newline at end of file +} diff --git a/monolithic-architecture/src/test/java/com/iluwatar/monolithic/MonolithicAppTest.java b/monolithic-architecture/src/test/java/com/iluwatar/monolithic/MonolithicAppTest.java index 5d3058783..1f3115732 100644 --- a/monolithic-architecture/src/test/java/com/iluwatar/monolithic/MonolithicAppTest.java +++ b/monolithic-architecture/src/test/java/com/iluwatar/monolithic/MonolithicAppTest.java @@ -24,6 +24,9 @@ */ package com.iluwatar.monolithic; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + import com.iluwatar.monolithic.controller.OrderController; import com.iluwatar.monolithic.controller.ProductController; import com.iluwatar.monolithic.controller.UserController; @@ -36,33 +39,25 @@ import com.iluwatar.monolithic.model.User; import com.iluwatar.monolithic.repository.OrderRepository; import com.iluwatar.monolithic.repository.ProductRepository; import com.iluwatar.monolithic.repository.UserRepository; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import java.nio.charset.StandardCharsets; import java.util.Locale; +import java.util.Optional; +import java.util.Scanner; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.PrintStream; -import java.nio.charset.StandardCharsets; -import java.util.Optional; -import java.util.Scanner; -import static org.junit.jupiter.api.Assertions.*; - - -import static org.mockito.Mockito.*; - class MonolithicAppTest { - @Mock - private UserController userService; + @Mock private UserController userService; - @Mock - private ProductController productService; + @Mock private ProductController productService; - @Mock - private OrderController orderService; + @Mock private OrderController orderService; private EcommerceApp ecommerceApp; @@ -96,16 +91,20 @@ class MonolithicAppTest { when(mockUserRepository.findById(1L)).thenReturn(Optional.empty()); - OrderController orderCon = new OrderController(mockOrderRepo, mockUserRepository, mockProductRepository); + OrderController orderCon = + new OrderController(mockOrderRepo, mockUserRepository, mockProductRepository); - Exception exception = assertThrows(NonExistentUserException.class, () -> { - orderCon.placeOrder(1L, 1L, 5); - }); + Exception exception = + assertThrows( + NonExistentUserException.class, + () -> { + orderCon.placeOrder(1L, 1L, 5); + }); assertEquals("User with ID 1 not found", exception.getMessage()); } - @Test + @Test void testPlaceOrderProductNotFound() { UserRepository mockUserRepository = mock(UserRepository.class); ProductRepository mockProductRepository = mock(ProductRepository.class); @@ -116,24 +115,27 @@ class MonolithicAppTest { when(mockProductRepository.findById(1L)).thenReturn(Optional.empty()); - OrderController orderCon = new OrderController(mockOrderRepository, mockUserRepository, mockProductRepository); + OrderController orderCon = + new OrderController(mockOrderRepository, mockUserRepository, mockProductRepository); - Exception exception = assertThrows(NonExistentProductException.class, () -> { - orderCon.placeOrder(1L, 1L, 5); - }); + Exception exception = + assertThrows( + NonExistentProductException.class, + () -> { + orderCon.placeOrder(1L, 1L, 5); + }); assertEquals("Product with ID 1 not found", exception.getMessage()); } - - @Test - void testOrderConstructor(){ + void testOrderConstructor() { OrderRepository mockOrderRepository = mock(OrderRepository.class); UserRepository mockUserRepository = mock(UserRepository.class); ProductRepository mockProductRepository = mock(ProductRepository.class); - OrderController orderCon = new OrderController(mockOrderRepository, mockUserRepository, mockProductRepository); + OrderController orderCon = + new OrderController(mockOrderRepository, mockUserRepository, mockProductRepository); assertNotNull(orderCon); } @@ -169,13 +171,15 @@ class MonolithicAppTest { System.setIn(new ByteArrayInputStream(simulatedInput.getBytes(StandardCharsets.UTF_8))); doThrow(new RuntimeException("Product out of stock")) - .when(orderService).placeOrder(anyLong(), anyLong(), anyInt()); + .when(orderService) + .placeOrder(anyLong(), anyLong(), anyInt()); ecommerceApp.placeOrder(new Scanner(System.in, StandardCharsets.UTF_8)); verify(orderService, times(1)).placeOrder(anyLong(), anyLong(), anyInt()); assertTrue(outputStream.toString().contains("Error placing order: Product out of stock")); } + @Test void testPlaceOrderInsufficientStock() { UserRepository mockUserRepository = mock(UserRepository.class); @@ -184,16 +188,22 @@ class MonolithicAppTest { User mockUser = new User(1L, "John Doe", "john@example.com", "password123"); when(mockUserRepository.findById(1L)).thenReturn(Optional.of(mockUser)); - Product mockProduct = new Product(1L, "Laptop", "High-end gaming laptop", 1500.00, 2); // Only 2 in stock + Product mockProduct = + new Product(1L, "Laptop", "High-end gaming laptop", 1500.00, 2); // Only 2 in stock when(mockProductRepository.findById(1L)).thenReturn(Optional.of(mockProduct)); - OrderController orderCon = new OrderController(mockOrderRepository, mockUserRepository, mockProductRepository); + OrderController orderCon = + new OrderController(mockOrderRepository, mockUserRepository, mockProductRepository); - Exception exception = assertThrows(InsufficientStockException.class, () -> { - orderCon.placeOrder(1L, 1L, 5); - }); + Exception exception = + assertThrows( + InsufficientStockException.class, + () -> { + orderCon.placeOrder(1L, 1L, 5); + }); assertEquals("Not enough stock for product 1", exception.getMessage()); -} + } + @Test void testProductConAddProduct() { ProductRepository mockProductRepository = mock(ProductRepository.class); @@ -217,7 +227,8 @@ class MonolithicAppTest { @Test void testRun() { - String simulatedInput = """ + String simulatedInput = + """ 1 John Doe john@example.com @@ -232,15 +243,24 @@ class MonolithicAppTest { 1 2 4 - """; // Exit + """; // Exit System.setIn(new ByteArrayInputStream(simulatedInput.getBytes(StandardCharsets.UTF_8))); ByteArrayOutputStream outputTest = new ByteArrayOutputStream(); System.setOut(new PrintStream(outputTest, true, StandardCharsets.UTF_8)); - when(userService.registerUser(any(User.class))).thenReturn(new User(1L, "John Doe", "john@example.com", "password123")); - when(productService.addProduct(any(Product.class))).thenReturn(new Product(1L, "Laptop", "Gaming Laptop", 1200.50, 10)); - when(orderService.placeOrder(anyLong(), anyLong(), anyInt())).thenReturn(new Order(1L, new User(1L, "John Doe", "john@example.com","password123" ), new Product(1L, "Laptop", "Gaming Laptop", 1200.50, 10), 5, 6002.50)); + when(userService.registerUser(any(User.class))) + .thenReturn(new User(1L, "John Doe", "john@example.com", "password123")); + when(productService.addProduct(any(Product.class))) + .thenReturn(new Product(1L, "Laptop", "Gaming Laptop", 1200.50, 10)); + when(orderService.placeOrder(anyLong(), anyLong(), anyInt())) + .thenReturn( + new Order( + 1L, + new User(1L, "John Doe", "john@example.com", "password123"), + new Product(1L, "Laptop", "Gaming Laptop", 1200.50, 10), + 5, + 6002.50)); ecommerceApp.run(); @@ -255,9 +275,5 @@ class MonolithicAppTest { assertTrue(output.contains("Add Product")); assertTrue(output.contains("Place Order")); assertTrue(output.contains("Exiting the application. Goodbye!")); + } } - - - - -} \ No newline at end of file diff --git a/monostate/pom.xml b/monostate/pom.xml index a9d3abfaf..fad322610 100644 --- a/monostate/pom.xml +++ b/monostate/pom.xml @@ -34,6 +34,14 @@ monostate + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine @@ -45,4 +53,23 @@ test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.monostate.App + + + + + + + + diff --git a/monostate/src/main/java/com/iluwatar/monostate/App.java b/monostate/src/main/java/com/iluwatar/monostate/App.java index 289362f30..3c3dab2fc 100644 --- a/monostate/src/main/java/com/iluwatar/monostate/App.java +++ b/monostate/src/main/java/com/iluwatar/monostate/App.java @@ -24,7 +24,6 @@ */ package com.iluwatar.monostate; - /** * The MonoState pattern ensures that all instances of the class will have the same state. This can * be used a direct replacement of the Singleton pattern. @@ -49,5 +48,4 @@ public class App { loadBalancer1.serverRequest(new Request("Hello")); loadBalancer2.serverRequest(new Request("Hello World")); } - } diff --git a/monostate/src/main/java/com/iluwatar/monostate/LoadBalancer.java b/monostate/src/main/java/com/iluwatar/monostate/LoadBalancer.java index 285dc573f..b93ae2789 100644 --- a/monostate/src/main/java/com/iluwatar/monostate/LoadBalancer.java +++ b/monostate/src/main/java/com/iluwatar/monostate/LoadBalancer.java @@ -33,26 +33,22 @@ import java.util.List; * instances of the class share the same state, all instances will delegate to the same server on * receiving a new Request. */ - public class LoadBalancer { private static final List SERVERS = new ArrayList<>(); private static int lastServedId; static { var id = 0; - for (var port : new int[]{8080, 8081, 8082, 8083, 8084}) { + for (var port : new int[] {8080, 8081, 8082, 8083, 8084}) { SERVERS.add(new Server("localhost", port, ++id)); } } - /** - * Add new server. - */ + /** Add new server. */ public final void addServer(Server server) { synchronized (SERVERS) { SERVERS.add(server); } - } public final int getNoOfServers() { @@ -63,9 +59,7 @@ public class LoadBalancer { return lastServedId; } - /** - * Handle request. - */ + /** Handle request. */ public synchronized void serverRequest(Request request) { if (lastServedId >= SERVERS.size()) { lastServedId = 0; @@ -73,5 +67,4 @@ public class LoadBalancer { var server = SERVERS.get(lastServedId++); server.serve(request); } - } diff --git a/monostate/src/main/java/com/iluwatar/monostate/Request.java b/monostate/src/main/java/com/iluwatar/monostate/Request.java index aa7dc8189..e08f2dd47 100644 --- a/monostate/src/main/java/com/iluwatar/monostate/Request.java +++ b/monostate/src/main/java/com/iluwatar/monostate/Request.java @@ -24,8 +24,5 @@ */ package com.iluwatar.monostate; -/** - * The Request record. A {@link Server} can handle an instance of a Request. - */ - +/** The Request record. A {@link Server} can handle an instance of a Request. */ public record Request(String value) {} diff --git a/monostate/src/main/java/com/iluwatar/monostate/Server.java b/monostate/src/main/java/com/iluwatar/monostate/Server.java index 13589c93f..e0af58a82 100644 --- a/monostate/src/main/java/com/iluwatar/monostate/Server.java +++ b/monostate/src/main/java/com/iluwatar/monostate/Server.java @@ -39,9 +39,7 @@ public class Server { public final int port; public final int id; - /** - * Constructor. - */ + /** Constructor. */ public Server(String host, int port, int id) { this.host = host; this.port = port; @@ -49,7 +47,11 @@ public class Server { } public void serve(Request request) { - LOGGER.info("Server ID {} associated to host : {} and port {}. Processed request with value {}", - id, host, port, request.value()); + LOGGER.info( + "Server ID {} associated to host : {} and port {}. Processed request with value {}", + id, + host, + port, + request.value()); } } diff --git a/monostate/src/test/java/com/iluwatar/monostate/AppTest.java b/monostate/src/test/java/com/iluwatar/monostate/AppTest.java index a701787c5..82ea4e195 100644 --- a/monostate/src/test/java/com/iluwatar/monostate/AppTest.java +++ b/monostate/src/test/java/com/iluwatar/monostate/AppTest.java @@ -28,15 +28,11 @@ import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import org.junit.jupiter.api.Test; -/** - * Application Test Entry - */ - +/** Application Test Entry */ class AppTest { @Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } - } diff --git a/monostate/src/test/java/com/iluwatar/monostate/LoadBalancerTest.java b/monostate/src/test/java/com/iluwatar/monostate/LoadBalancerTest.java index f3139b603..10a46e016 100644 --- a/monostate/src/test/java/com/iluwatar/monostate/LoadBalancerTest.java +++ b/monostate/src/test/java/com/iluwatar/monostate/LoadBalancerTest.java @@ -35,10 +35,7 @@ import static org.mockito.Mockito.when; import org.junit.jupiter.api.Test; -/** - * LoadBalancerTest - * - */ +/** LoadBalancerTest */ class LoadBalancerTest { @Test @@ -71,7 +68,5 @@ class LoadBalancerTest { verify(server, times(2)).serve(request); verifyNoMoreInteractions(server); - } - } diff --git a/multiton/pom.xml b/multiton/pom.xml index 6d2430560..f86151ca4 100644 --- a/multiton/pom.xml +++ b/multiton/pom.xml @@ -34,6 +34,14 @@ multiton + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/multiton/src/main/java/com/iluwatar/multiton/Nazgul.java b/multiton/src/main/java/com/iluwatar/multiton/Nazgul.java index 35e7ea337..d1c46bfa9 100644 --- a/multiton/src/main/java/com/iluwatar/multiton/Nazgul.java +++ b/multiton/src/main/java/com/iluwatar/multiton/Nazgul.java @@ -35,8 +35,7 @@ public final class Nazgul { private static final Map nazguls; - @Getter - private final NazgulName name; + @Getter private final NazgulName name; static { nazguls = new ConcurrentHashMap<>(); diff --git a/multiton/src/main/java/com/iluwatar/multiton/NazgulEnum.java b/multiton/src/main/java/com/iluwatar/multiton/NazgulEnum.java index e9fef5803..bde5c0d4a 100644 --- a/multiton/src/main/java/com/iluwatar/multiton/NazgulEnum.java +++ b/multiton/src/main/java/com/iluwatar/multiton/NazgulEnum.java @@ -24,9 +24,7 @@ */ package com.iluwatar.multiton; -/** - * enum based multiton implementation. - */ +/** enum based multiton implementation. */ public enum NazgulEnum { KHAMUL, MURAZOR, diff --git a/multiton/src/main/java/com/iluwatar/multiton/NazgulName.java b/multiton/src/main/java/com/iluwatar/multiton/NazgulName.java index 44474efb8..0d9c93cac 100644 --- a/multiton/src/main/java/com/iluwatar/multiton/NazgulName.java +++ b/multiton/src/main/java/com/iluwatar/multiton/NazgulName.java @@ -24,9 +24,7 @@ */ package com.iluwatar.multiton; -/** - * Each Nazgul has different {@link NazgulName}. - */ +/** Each Nazgul has different {@link NazgulName}. */ public enum NazgulName { KHAMUL, MURAZOR, diff --git a/multiton/src/test/java/com/iluwatar/multiton/AppTest.java b/multiton/src/test/java/com/iluwatar/multiton/AppTest.java index 16fbf3613..95478068b 100644 --- a/multiton/src/test/java/com/iluwatar/multiton/AppTest.java +++ b/multiton/src/test/java/com/iluwatar/multiton/AppTest.java @@ -28,14 +28,11 @@ import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import org.junit.jupiter.api.Test; -/** - * Test if the application starts without throwing an exception. - */ - +/** Test if the application starts without throwing an exception. */ class AppTest { @Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/multiton/src/test/java/com/iluwatar/multiton/NazgulEnumTest.java b/multiton/src/test/java/com/iluwatar/multiton/NazgulEnumTest.java index c514f871b..916409119 100644 --- a/multiton/src/test/java/com/iluwatar/multiton/NazgulEnumTest.java +++ b/multiton/src/test/java/com/iluwatar/multiton/NazgulEnumTest.java @@ -29,15 +29,12 @@ import static org.junit.jupiter.api.Assertions.assertSame; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.EnumSource; -/** - * NazgulEnumTest - * - */ +/** NazgulEnumTest */ class NazgulEnumTest { /** - * Check that multiple calls to any one of the instances in the multiton returns - * only that one particular instance, and do that for all instances in multiton + * Check that multiple calls to any one of the instances in the multiton returns only that one + * particular instance, and do that for all instances in multiton */ @ParameterizedTest @EnumSource diff --git a/multiton/src/test/java/com/iluwatar/multiton/NazgulTest.java b/multiton/src/test/java/com/iluwatar/multiton/NazgulTest.java index 4c998282f..8d7c3bfb8 100644 --- a/multiton/src/test/java/com/iluwatar/multiton/NazgulTest.java +++ b/multiton/src/test/java/com/iluwatar/multiton/NazgulTest.java @@ -30,10 +30,7 @@ import static org.junit.jupiter.api.Assertions.assertSame; import org.junit.jupiter.api.Test; -/** - * NazgulTest - * - */ +/** NazgulTest */ class NazgulTest { /** diff --git a/mute-idiom/pom.xml b/mute-idiom/pom.xml index 4f521c638..40654d7de 100644 --- a/mute-idiom/pom.xml +++ b/mute-idiom/pom.xml @@ -34,6 +34,14 @@ mute-idiom + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/mute-idiom/src/main/java/com/iluwatar/mute/App.java b/mute-idiom/src/main/java/com/iluwatar/mute/App.java index 341a9bb16..75525731a 100644 --- a/mute-idiom/src/main/java/com/iluwatar/mute/App.java +++ b/mute-idiom/src/main/java/com/iluwatar/mute/App.java @@ -34,6 +34,7 @@ import lombok.extern.slf4j.Slf4j; * when all we can do to handle the exception is to log it. This pattern should not be used * everywhere. It is very important to logically handle the exceptions in a system, but some * situations like the ones described above require this pattern, so that we don't need to repeat + * *

  * 
  *   try {
@@ -42,7 +43,9 @@ import lombok.extern.slf4j.Slf4j;
  *     // ignore by logging or throw error if unexpected exception occurs
  *   }
  * 
- * 
every time we need to ignore an exception. + * + * + * every time we need to ignore an exception. */ @Slf4j public class App { diff --git a/mute-idiom/src/main/java/com/iluwatar/mute/CheckedRunnable.java b/mute-idiom/src/main/java/com/iluwatar/mute/CheckedRunnable.java index 5c8d017b9..9698f6d12 100644 --- a/mute-idiom/src/main/java/com/iluwatar/mute/CheckedRunnable.java +++ b/mute-idiom/src/main/java/com/iluwatar/mute/CheckedRunnable.java @@ -24,9 +24,7 @@ */ package com.iluwatar.mute; -/** - * A runnable which may throw exception on execution. - */ +/** A runnable which may throw exception on execution. */ @FunctionalInterface public interface CheckedRunnable { /** diff --git a/mute-idiom/src/main/java/com/iluwatar/mute/Mute.java b/mute-idiom/src/main/java/com/iluwatar/mute/Mute.java index 092d940fa..8eab13a6d 100644 --- a/mute-idiom/src/main/java/com/iluwatar/mute/Mute.java +++ b/mute-idiom/src/main/java/com/iluwatar/mute/Mute.java @@ -28,22 +28,19 @@ import java.io.ByteArrayOutputStream; import java.io.IOException; import lombok.extern.slf4j.Slf4j; -/** - * A utility class that allows you to utilize mute idiom. - */ +/** A utility class that allows you to utilize mute idiom. */ @Slf4j public final class Mute { // The constructor is never meant to be called. - private Mute() { - } + private Mute() {} /** * Executes the runnable and throws the exception occurred within a {@link * AssertionError}. This method should be utilized to mute the operations that are guaranteed not - * to throw an exception. For instance {@link ByteArrayOutputStream#write(byte[])} declares in - * its signature that it can throw an {@link IOException}, but in reality it cannot. This is - * because the bulk write method is not overridden in {@link ByteArrayOutputStream}. + * to throw an exception. For instance {@link ByteArrayOutputStream#write(byte[])} declares in its + * signature that it can throw an {@link IOException}, but in reality it cannot. This is because + * the bulk write method is not overridden in {@link ByteArrayOutputStream}. * * @param runnable a runnable that should never throw an exception on execution. */ diff --git a/mute-idiom/src/main/java/com/iluwatar/mute/Resource.java b/mute-idiom/src/main/java/com/iluwatar/mute/Resource.java index cb32b2795..c4c4c6546 100644 --- a/mute-idiom/src/main/java/com/iluwatar/mute/Resource.java +++ b/mute-idiom/src/main/java/com/iluwatar/mute/Resource.java @@ -30,6 +30,4 @@ import java.io.Closeable; * Represents any resource that the application might acquire and that must be closed after it is * utilized. Example of such resources can be a database connection, open files, sockets. */ -public interface Resource extends Closeable { - -} +public interface Resource extends Closeable {} diff --git a/mute-idiom/src/test/java/com/iluwatar/mute/AppTest.java b/mute-idiom/src/test/java/com/iluwatar/mute/AppTest.java index ecfb1dabb..ef8dff8b0 100644 --- a/mute-idiom/src/test/java/com/iluwatar/mute/AppTest.java +++ b/mute-idiom/src/test/java/com/iluwatar/mute/AppTest.java @@ -24,17 +24,15 @@ */ package com.iluwatar.mute; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -/** - * Tests that Mute idiom example runs without errors. - */ +import org.junit.jupiter.api.Test; + +/** Tests that Mute idiom example runs without errors. */ class AppTest { @Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } } 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 07b17afac..06579d454 100644 --- a/mute-idiom/src/test/java/com/iluwatar/mute/MuteTest.java +++ b/mute-idiom/src/test/java/com/iluwatar/mute/MuteTest.java @@ -24,17 +24,15 @@ */ package com.iluwatar.mute; +import static org.junit.jupiter.api.Assertions.*; + import java.io.ByteArrayOutputStream; import java.io.PrintStream; import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import static org.junit.jupiter.api.Assertions.*; - -/** - * Test for the mute-idiom pattern - */ +/** Test for the mute-idiom pattern */ class MuteTest { private static final Logger LOGGER = LoggerFactory.getLogger(MuteTest.class); @@ -42,7 +40,8 @@ class MuteTest { private static final String MESSAGE = "should not occur"; @Test - void muteShouldRunTheCheckedRunnableAndNotThrowAnyExceptionIfCheckedRunnableDoesNotThrowAnyException() { + void + muteShouldRunTheCheckedRunnableAndNotThrowAnyExceptionIfCheckedRunnableDoesNotThrowAnyException() { assertDoesNotThrow(() -> Mute.mute(this::methodNotThrowingAnyException)); } @@ -52,7 +51,8 @@ class MuteTest { } @Test - void loggedMuteShouldRunTheCheckedRunnableAndNotThrowAnyExceptionIfCheckedRunnableDoesNotThrowAnyException() { + void + loggedMuteShouldRunTheCheckedRunnableAndNotThrowAnyExceptionIfCheckedRunnableDoesNotThrowAnyException() { assertDoesNotThrow(() -> Mute.mute(this::methodNotThrowingAnyException)); } diff --git a/notification/pom.xml b/notification/pom.xml index 760169ef8..829c90149 100644 --- a/notification/pom.xml +++ b/notification/pom.xml @@ -35,6 +35,14 @@ 1.26.0-SNAPSHOT + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-params diff --git a/notification/src/main/java/com/iluwatar/App.java b/notification/src/main/java/com/iluwatar/App.java index f62a62c32..fdf041929 100644 --- a/notification/src/main/java/com/iluwatar/App.java +++ b/notification/src/main/java/com/iluwatar/App.java @@ -27,14 +27,14 @@ package com.iluwatar; import java.time.LocalDate; /** - * The notification pattern captures information passed between layers, validates the information, and returns - * any errors to the presentation layer if needed. + * The notification pattern captures information passed between layers, validates the information, + * and returns any errors to the presentation layer if needed. * - *

In this code, this pattern is implemented through the example of a form being submitted to register - * a worker. The worker inputs their name, occupation, and date of birth to the RegisterWorkerForm (which acts - * as our presentation layer), and passes it to the RegisterWorker class (our domain layer) which validates it. - * Any errors caught by the domain layer are then passed back to the presentation layer through the - * RegisterWorkerDto.

+ *

In this code, this pattern is implemented through the example of a form being submitted to + * register a worker. The worker inputs their name, occupation, and date of birth to the + * RegisterWorkerForm (which acts as our presentation layer), and passes it to the RegisterWorker + * class (our domain layer) which validates it. Any errors caught by the domain layer are then + * passed back to the presentation layer through the RegisterWorkerDto. */ public class App { @@ -46,5 +46,4 @@ public class App { var form = new RegisterWorkerForm(NAME, OCCUPATION, DATE_OF_BIRTH); form.submit(); } - } diff --git a/notification/src/main/java/com/iluwatar/DataTransferObject.java b/notification/src/main/java/com/iluwatar/DataTransferObject.java index 11d648d16..e061a9976 100644 --- a/notification/src/main/java/com/iluwatar/DataTransferObject.java +++ b/notification/src/main/java/com/iluwatar/DataTransferObject.java @@ -28,13 +28,12 @@ import lombok.Getter; import lombok.NoArgsConstructor; /** - * Layer super type for all Data Transfer Objects. - * Also contains code for accessing our notification. + * Layer super type for all Data Transfer Objects. Also contains code for accessing our + * notification. */ @Getter @NoArgsConstructor public class DataTransferObject { private final Notification notification = new Notification(); - } diff --git a/notification/src/main/java/com/iluwatar/Notification.java b/notification/src/main/java/com/iluwatar/Notification.java index 47f36f5ee..dc8a40ea7 100644 --- a/notification/src/main/java/com/iluwatar/Notification.java +++ b/notification/src/main/java/com/iluwatar/Notification.java @@ -30,9 +30,8 @@ import lombok.Getter; import lombok.NoArgsConstructor; /** - * The notification. Used for storing errors and any other methods - * that may be necessary for when we send information back to the - * presentation layer. + * The notification. Used for storing errors and any other methods that may be necessary for when we + * send information back to the presentation layer. */ @Getter @NoArgsConstructor diff --git a/notification/src/main/java/com/iluwatar/NotificationError.java b/notification/src/main/java/com/iluwatar/NotificationError.java index a243a383b..29aa0fd13 100644 --- a/notification/src/main/java/com/iluwatar/NotificationError.java +++ b/notification/src/main/java/com/iluwatar/NotificationError.java @@ -28,8 +28,8 @@ import lombok.AllArgsConstructor; import lombok.Getter; /** - * Error class for storing information on the error. - * Error ID is not necessary, but may be useful for serialisation. + * Error class for storing information on the error. Error ID is not necessary, but may be useful + * for serialisation. */ @Getter @AllArgsConstructor diff --git a/notification/src/main/java/com/iluwatar/RegisterWorker.java b/notification/src/main/java/com/iluwatar/RegisterWorker.java index 9de39344b..5952010e3 100644 --- a/notification/src/main/java/com/iluwatar/RegisterWorker.java +++ b/notification/src/main/java/com/iluwatar/RegisterWorker.java @@ -29,19 +29,18 @@ import java.time.Period; import lombok.extern.slf4j.Slf4j; /** - * Class which handles actual internal logic and validation for worker registration. - * Part of the domain layer which collects information and sends it back to the presentation. + * Class which handles actual internal logic and validation for worker registration. Part of the + * domain layer which collects information and sends it back to the presentation. */ @Slf4j public class RegisterWorker extends ServerCommand { static final int LEGAL_AGE = 18; + protected RegisterWorker(RegisterWorkerDto worker) { super(worker); } - /** - * Validates the data provided and adds it to the database in the backend. - */ + /** Validates the data provided and adds it to the database in the backend. */ public void run() { validate(); @@ -50,12 +49,10 @@ public class RegisterWorker extends ServerCommand { } } - /** - * Validates our data. Checks for any errors and if found, adds to notification. - */ + /** Validates our data. Checks for any errors and if found, adds to notification. */ private void validate() { var ourData = ((RegisterWorkerDto) this.data); - //check if any of submitted data is not given + // check if any of submitted data is not given // passing for empty value validation fail(isNullOrBlank(ourData.getName()), RegisterWorkerDto.MISSING_NAME); fail(isNullOrBlank(ourData.getOccupation()), RegisterWorkerDto.MISSING_OCCUPATION); @@ -93,7 +90,7 @@ public class RegisterWorker extends ServerCommand { * If a condition is met, adds the error to our notification. * * @param condition condition to check for. - * @param error error to add if condition met. + * @param error error to add if condition met. */ protected void fail(boolean condition, NotificationError error) { if (condition) { diff --git a/notification/src/main/java/com/iluwatar/RegisterWorkerDto.java b/notification/src/main/java/com/iluwatar/RegisterWorkerDto.java index 7050c54dc..c1fbadf9d 100644 --- a/notification/src/main/java/com/iluwatar/RegisterWorkerDto.java +++ b/notification/src/main/java/com/iluwatar/RegisterWorkerDto.java @@ -29,8 +29,8 @@ import lombok.Getter; import lombok.Setter; /** - * Data transfer object which stores information about the worker. This is carried between - * objects and layers to reduce the number of method calls made. + * Data transfer object which stores information about the worker. This is carried between objects + * and layers to reduce the number of method calls made. */ @Getter @Setter @@ -39,30 +39,20 @@ public class RegisterWorkerDto extends DataTransferObject { private String occupation; private LocalDate dateOfBirth; - /** - * Error for when name field is blank or missing. - */ - public static final NotificationError MISSING_NAME = - new NotificationError(1, "Name is missing"); + /** Error for when name field is blank or missing. */ + public static final NotificationError MISSING_NAME = new NotificationError(1, "Name is missing"); - /** - * Error for when occupation field is blank or missing. - */ + /** Error for when occupation field is blank or missing. */ public static final NotificationError MISSING_OCCUPATION = - new NotificationError(2, "Occupation is missing"); + new NotificationError(2, "Occupation is missing"); - /** - * Error for when date of birth field is blank or missing. - */ + /** Error for when date of birth field is blank or missing. */ public static final NotificationError MISSING_DOB = - new NotificationError(3, "Date of birth is missing"); + new NotificationError(3, "Date of birth is missing"); - /** - * Error for when date of birth is less than 18 years ago. - */ + /** Error for when date of birth is less than 18 years ago. */ public static final NotificationError DOB_TOO_SOON = - new NotificationError(4, "Worker registered must be over 18"); - + new NotificationError(4, "Worker registered must be over 18"); protected RegisterWorkerDto() { super(); @@ -71,8 +61,8 @@ public class RegisterWorkerDto extends DataTransferObject { /** * Simple set up function for capturing our worker information. * - * @param name Name of the worker - * @param occupation occupation of the worker + * @param name Name of the worker + * @param occupation occupation of the worker * @param dateOfBirth Date of Birth of the worker */ public void setupWorkerDto(String name, String occupation, LocalDate dateOfBirth) { diff --git a/notification/src/main/java/com/iluwatar/RegisterWorkerForm.java b/notification/src/main/java/com/iluwatar/RegisterWorkerForm.java index 664191993..c1a5092f9 100644 --- a/notification/src/main/java/com/iluwatar/RegisterWorkerForm.java +++ b/notification/src/main/java/com/iluwatar/RegisterWorkerForm.java @@ -28,9 +28,8 @@ import java.time.LocalDate; import lombok.extern.slf4j.Slf4j; /** - * The form submitted by the user, part of the presentation layer, - * linked to the domain layer through a data transfer object and - * linked to the service layer directly. + * The form submitted by the user, part of the presentation layer, linked to the domain layer + * through a data transfer object and linked to the service layer directly. */ @Slf4j public class RegisterWorkerForm { @@ -41,10 +40,10 @@ public class RegisterWorkerForm { RegisterWorkerService service = new RegisterWorkerService(); /** - * Constructor. + * Constructor. * - * @param name Name of the worker - * @param occupation occupation of the worker + * @param name Name of the worker + * @param occupation occupation of the worker * @param dateOfBirth Date of Birth of the worker */ public RegisterWorkerForm(String name, String occupation, LocalDate dateOfBirth) { @@ -53,16 +52,14 @@ public class RegisterWorkerForm { this.dateOfBirth = dateOfBirth; } - /** - * Attempts to submit the form for registering a worker. - */ + /** Attempts to submit the form for registering a worker. */ public void submit() { - //Transmit information to our transfer object to communicate between layers + // Transmit information to our transfer object to communicate between layers saveToWorker(); - //call the service layer to register our worker + // call the service layer to register our worker service.registerWorker(worker); - //check for any errors + // check for any errors if (worker.getNotification().hasErrors()) { indicateErrors(); LOGGER.info("Not registered, see errors"); @@ -71,9 +68,7 @@ public class RegisterWorkerForm { } } - /** - * Saves worker information to the data transfer object. - */ + /** Saves worker information to the data transfer object. */ private void saveToWorker() { worker = new RegisterWorkerDto(); worker.setName(name); @@ -81,9 +76,7 @@ public class RegisterWorkerForm { worker.setDateOfBirth(dateOfBirth); } - /** - * Check for any errors with form submission and show them to the user. - */ + /** Check for any errors with form submission and show them to the user. */ public void indicateErrors() { worker.getNotification().getErrors().forEach(error -> LOGGER.error(error.toString())); } diff --git a/notification/src/main/java/com/iluwatar/RegisterWorkerService.java b/notification/src/main/java/com/iluwatar/RegisterWorkerService.java index aed162971..a77427395 100644 --- a/notification/src/main/java/com/iluwatar/RegisterWorkerService.java +++ b/notification/src/main/java/com/iluwatar/RegisterWorkerService.java @@ -25,13 +25,13 @@ package com.iluwatar; /** - * Service used to register a worker. - * This represents the basic framework of a service layer which can be built upon. + * Service used to register a worker. This represents the basic framework of a service layer which + * can be built upon. */ public class RegisterWorkerService { /** - * Creates and runs a command object to do the work needed, - * in this case, register a worker in the system. + * Creates and runs a command object to do the work needed, in this case, register a worker in the + * system. * * @param registration worker to be registered if possible */ diff --git a/notification/src/main/java/com/iluwatar/ServerCommand.java b/notification/src/main/java/com/iluwatar/ServerCommand.java index 69af66cc0..6dd1357cc 100644 --- a/notification/src/main/java/com/iluwatar/ServerCommand.java +++ b/notification/src/main/java/com/iluwatar/ServerCommand.java @@ -27,8 +27,8 @@ package com.iluwatar; import lombok.AllArgsConstructor; /** - * Stores the dto and access the notification within it. - * Acting as a layer supertype in this instance for the domain layer. + * Stores the dto and access the notification within it. Acting as a layer supertype in this + * instance for the domain layer. */ @AllArgsConstructor public class ServerCommand { diff --git a/notification/src/test/java/com/iluwatar/AppTest.java b/notification/src/test/java/com/iluwatar/AppTest.java index 8f5ff4a48..0eaaf7863 100644 --- a/notification/src/test/java/com/iluwatar/AppTest.java +++ b/notification/src/test/java/com/iluwatar/AppTest.java @@ -24,15 +24,14 @@ */ package com.iluwatar; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import org.junit.jupiter.api.Test; + class AppTest { @Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } } - diff --git a/notification/src/test/java/com/iluwatar/RegisterWorkerFormTest.java b/notification/src/test/java/com/iluwatar/RegisterWorkerFormTest.java index f4a7358da..fdc5b77cf 100644 --- a/notification/src/test/java/com/iluwatar/RegisterWorkerFormTest.java +++ b/notification/src/test/java/com/iluwatar/RegisterWorkerFormTest.java @@ -33,42 +33,41 @@ import org.junit.jupiter.api.Test; class RegisterWorkerFormTest { - private RegisterWorkerForm registerWorkerForm; + private RegisterWorkerForm registerWorkerForm; - @Test - void submitSuccessfully() { - // Ensure the worker is null initially - registerWorkerForm = new RegisterWorkerForm("John Doe", "Engineer", LocalDate.of(1990, 1, 1)); + @Test + void submitSuccessfully() { + // Ensure the worker is null initially + registerWorkerForm = new RegisterWorkerForm("John Doe", "Engineer", LocalDate.of(1990, 1, 1)); - assertNull(registerWorkerForm.worker); + assertNull(registerWorkerForm.worker); - // Submit the form - registerWorkerForm.submit(); + // Submit the form + registerWorkerForm.submit(); - // Verify that the worker is not null after submission - assertNotNull(registerWorkerForm.worker); + // Verify that the worker is not null after submission + assertNotNull(registerWorkerForm.worker); - // Verify that the worker's properties are set correctly - assertEquals("John Doe", registerWorkerForm.worker.getName()); - assertEquals("Engineer", registerWorkerForm.worker.getOccupation()); - assertEquals(LocalDate.of(1990, 1, 1), registerWorkerForm.worker.getDateOfBirth()); - } + // Verify that the worker's properties are set correctly + assertEquals("John Doe", registerWorkerForm.worker.getName()); + assertEquals("Engineer", registerWorkerForm.worker.getOccupation()); + assertEquals(LocalDate.of(1990, 1, 1), registerWorkerForm.worker.getDateOfBirth()); + } - @Test - void submitWithErrors() { - // Set up the worker with a notification containing errors - registerWorkerForm = new RegisterWorkerForm(null, null, null); + @Test + void submitWithErrors() { + // Set up the worker with a notification containing errors + registerWorkerForm = new RegisterWorkerForm(null, null, null); - // Submit the form - registerWorkerForm.submit(); + // Submit the form + registerWorkerForm.submit(); - // Verify that the worker's properties remain unchanged - assertNull(registerWorkerForm.worker.getName()); - assertNull(registerWorkerForm.worker.getOccupation()); - assertNull(registerWorkerForm.worker.getDateOfBirth()); - - // Verify the presence of errors - assertEquals(registerWorkerForm.worker.getNotification().getErrors().size(), 4); - } + // Verify that the worker's properties remain unchanged + assertNull(registerWorkerForm.worker.getName()); + assertNull(registerWorkerForm.worker.getOccupation()); + assertNull(registerWorkerForm.worker.getDateOfBirth()); + // Verify the presence of errors + assertEquals(registerWorkerForm.worker.getNotification().getErrors().size(), 4); + } } diff --git a/notification/src/test/java/com/iluwatar/RegisterWorkerTest.java b/notification/src/test/java/com/iluwatar/RegisterWorkerTest.java index 994c6ab58..5f455b4cc 100644 --- a/notification/src/test/java/com/iluwatar/RegisterWorkerTest.java +++ b/notification/src/test/java/com/iluwatar/RegisterWorkerTest.java @@ -24,91 +24,97 @@ */ package com.iluwatar; -import lombok.extern.slf4j.Slf4j; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; import java.time.LocalDate; - -import static org.junit.jupiter.api.Assertions.*; +import lombok.extern.slf4j.Slf4j; +import org.junit.jupiter.api.Test; @Slf4j class RegisterWorkerTest { - @Test - void runSuccessfully() { - RegisterWorkerDto validWorkerDto = createValidWorkerDto(); - validWorkerDto.setupWorkerDto("name", "occupation", LocalDate.of(2000, 12, 1)); - RegisterWorker registerWorker = new RegisterWorker(validWorkerDto); + @Test + void runSuccessfully() { + RegisterWorkerDto validWorkerDto = createValidWorkerDto(); + validWorkerDto.setupWorkerDto("name", "occupation", LocalDate.of(2000, 12, 1)); + RegisterWorker registerWorker = new RegisterWorker(validWorkerDto); - // Run the registration process - registerWorker.run(); + // Run the registration process + registerWorker.run(); - // Verify that there are no errors in the notification - assertFalse(registerWorker.getNotification().hasErrors()); - } + // Verify that there are no errors in the notification + assertFalse(registerWorker.getNotification().hasErrors()); + } - @Test - void runWithMissingName() { - RegisterWorkerDto workerDto = createValidWorkerDto(); - workerDto.setupWorkerDto(null, "occupation", LocalDate.of(2000, 12, 1)); - RegisterWorker registerWorker = new RegisterWorker(workerDto); + @Test + void runWithMissingName() { + RegisterWorkerDto workerDto = createValidWorkerDto(); + workerDto.setupWorkerDto(null, "occupation", LocalDate.of(2000, 12, 1)); + RegisterWorker registerWorker = new RegisterWorker(workerDto); - // Run the registration process - registerWorker.run(); + // Run the registration process + registerWorker.run(); - // Verify that the notification contains the missing name error - assertTrue(registerWorker.getNotification().hasErrors()); - assertTrue(registerWorker.getNotification().getErrors().contains(RegisterWorkerDto.MISSING_NAME)); - assertEquals(registerWorker.getNotification().getErrors().size(), 1); - } + // Verify that the notification contains the missing name error + assertTrue(registerWorker.getNotification().hasErrors()); + assertTrue( + registerWorker.getNotification().getErrors().contains(RegisterWorkerDto.MISSING_NAME)); + assertEquals(registerWorker.getNotification().getErrors().size(), 1); + } - @Test - void runWithMissingOccupation() { - RegisterWorkerDto workerDto = createValidWorkerDto(); - workerDto.setupWorkerDto("name", null, LocalDate.of(2000, 12, 1)); - RegisterWorker registerWorker = new RegisterWorker(workerDto); + @Test + void runWithMissingOccupation() { + RegisterWorkerDto workerDto = createValidWorkerDto(); + workerDto.setupWorkerDto("name", null, LocalDate.of(2000, 12, 1)); + RegisterWorker registerWorker = new RegisterWorker(workerDto); - // Run the registration process - registerWorker.run(); + // Run the registration process + registerWorker.run(); - // Verify that the notification contains the missing occupation error - assertTrue(registerWorker.getNotification().hasErrors()); - assertTrue(registerWorker.getNotification().getErrors().contains(RegisterWorkerDto.MISSING_OCCUPATION)); - assertEquals(registerWorker.getNotification().getErrors().size(), 1); - } + // Verify that the notification contains the missing occupation error + assertTrue(registerWorker.getNotification().hasErrors()); + assertTrue( + registerWorker + .getNotification() + .getErrors() + .contains(RegisterWorkerDto.MISSING_OCCUPATION)); + assertEquals(registerWorker.getNotification().getErrors().size(), 1); + } - @Test - void runWithMissingDOB() { - RegisterWorkerDto workerDto = createValidWorkerDto(); - workerDto.setupWorkerDto("name", "occupation", null); - RegisterWorker registerWorker = new RegisterWorker(workerDto); + @Test + void runWithMissingDOB() { + RegisterWorkerDto workerDto = createValidWorkerDto(); + workerDto.setupWorkerDto("name", "occupation", null); + RegisterWorker registerWorker = new RegisterWorker(workerDto); - // Run the registration process - registerWorker.run(); + // Run the registration process + registerWorker.run(); - // Verify that the notification contains the missing DOB error - assertTrue(registerWorker.getNotification().hasErrors()); - assertTrue(registerWorker.getNotification().getErrors().contains(RegisterWorkerDto.MISSING_DOB)); - assertEquals(registerWorker.getNotification().getErrors().size(), 2); - } + // Verify that the notification contains the missing DOB error + assertTrue(registerWorker.getNotification().hasErrors()); + assertTrue( + registerWorker.getNotification().getErrors().contains(RegisterWorkerDto.MISSING_DOB)); + assertEquals(registerWorker.getNotification().getErrors().size(), 2); + } - @Test - void runWithUnderageDOB() { - RegisterWorkerDto workerDto = createValidWorkerDto(); - workerDto.setDateOfBirth(LocalDate.now().minusYears(17)); // Under 18 - workerDto.setupWorkerDto("name", "occupation", LocalDate.now().minusYears(17)); - RegisterWorker registerWorker = new RegisterWorker(workerDto); + @Test + void runWithUnderageDOB() { + RegisterWorkerDto workerDto = createValidWorkerDto(); + workerDto.setDateOfBirth(LocalDate.now().minusYears(17)); // Under 18 + workerDto.setupWorkerDto("name", "occupation", LocalDate.now().minusYears(17)); + RegisterWorker registerWorker = new RegisterWorker(workerDto); - // Run the registration process - registerWorker.run(); + // Run the registration process + registerWorker.run(); - // Verify that the notification contains the underage DOB error - assertTrue(registerWorker.getNotification().hasErrors()); - assertTrue(registerWorker.getNotification().getErrors().contains(RegisterWorkerDto.DOB_TOO_SOON)); - assertEquals(registerWorker.getNotification().getErrors().size(), 1); - } + // Verify that the notification contains the underage DOB error + assertTrue(registerWorker.getNotification().hasErrors()); + assertTrue( + registerWorker.getNotification().getErrors().contains(RegisterWorkerDto.DOB_TOO_SOON)); + assertEquals(registerWorker.getNotification().getErrors().size(), 1); + } - private RegisterWorkerDto createValidWorkerDto() { - return new RegisterWorkerDto(); - } + private RegisterWorkerDto createValidWorkerDto() { + return new RegisterWorkerDto(); + } } diff --git a/null-object/pom.xml b/null-object/pom.xml index 1a68c1f10..9bc13a79e 100644 --- a/null-object/pom.xml +++ b/null-object/pom.xml @@ -34,6 +34,14 @@ null-object + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/null-object/src/main/java/com/iluwatar/nullobject/App.java b/null-object/src/main/java/com/iluwatar/nullobject/App.java index efeaac858..d8908ef32 100644 --- a/null-object/src/main/java/com/iluwatar/nullobject/App.java +++ b/null-object/src/main/java/com/iluwatar/nullobject/App.java @@ -38,16 +38,17 @@ public class App { * @param args command line args */ public static void main(String[] args) { - var root = new NodeImpl("1", - new NodeImpl("11", - new NodeImpl("111", NullNode.getInstance(), NullNode.getInstance()), - NullNode.getInstance() - ), - new NodeImpl("12", - NullNode.getInstance(), - new NodeImpl("122", NullNode.getInstance(), NullNode.getInstance()) - ) - ); + var root = + new NodeImpl( + "1", + new NodeImpl( + "11", + new NodeImpl("111", NullNode.getInstance(), NullNode.getInstance()), + NullNode.getInstance()), + new NodeImpl( + "12", + NullNode.getInstance(), + new NodeImpl("122", NullNode.getInstance(), NullNode.getInstance()))); root.walk(); } diff --git a/null-object/src/main/java/com/iluwatar/nullobject/Node.java b/null-object/src/main/java/com/iluwatar/nullobject/Node.java index 26830dc0a..a306c9123 100644 --- a/null-object/src/main/java/com/iluwatar/nullobject/Node.java +++ b/null-object/src/main/java/com/iluwatar/nullobject/Node.java @@ -1,41 +1,39 @@ -/* - * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). - * - * The MIT License - * Copyright © 2014-2022 Ilkka Seppälä - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package com.iluwatar.nullobject; - -/** - * Interface for binary tree node. - */ -public interface Node { - - String getName(); - - int getTreeSize(); - - Node getLeft(); - - Node getRight(); - - void walk(); -} +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.nullobject; + +/** Interface for binary tree node. */ +public interface Node { + + String getName(); + + int getTreeSize(); + + Node getLeft(); + + Node getRight(); + + void walk(); +} diff --git a/null-object/src/main/java/com/iluwatar/nullobject/NodeImpl.java b/null-object/src/main/java/com/iluwatar/nullobject/NodeImpl.java index 9dd4ccf2c..55fcf0eaf 100644 --- a/null-object/src/main/java/com/iluwatar/nullobject/NodeImpl.java +++ b/null-object/src/main/java/com/iluwatar/nullobject/NodeImpl.java @@ -1,63 +1,62 @@ -/* - * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). - * - * The MIT License - * Copyright © 2014-2022 Ilkka Seppälä - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package com.iluwatar.nullobject; - -import lombok.extern.slf4j.Slf4j; - -/** - * Implementation for binary tree's normal nodes. - */ - -@Slf4j -public record NodeImpl(String name, Node left, Node right) implements Node { - @Override - public Node getLeft() { - return left; - } - - @Override - public Node getRight() { - return right; - } - - @Override - public String getName() { - return name; - } - @Override - public int getTreeSize() { - return 1 + left.getTreeSize() + right.getTreeSize(); - } - @Override - public void walk() { - LOGGER.info(name); - if (left.getTreeSize() > 0) { - left.walk(); - } - if (right.getTreeSize() > 0) { - right.walk(); - } - } -} +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.nullobject; + +import lombok.extern.slf4j.Slf4j; + +/** Implementation for binary tree's normal nodes. */ +@Slf4j +public record NodeImpl(String name, Node left, Node right) implements Node { + @Override + public Node getLeft() { + return left; + } + + @Override + public Node getRight() { + return right; + } + + @Override + public String getName() { + return name; + } + + @Override + public int getTreeSize() { + return 1 + left.getTreeSize() + right.getTreeSize(); + } + + @Override + public void walk() { + LOGGER.info(name); + if (left.getTreeSize() > 0) { + left.walk(); + } + if (right.getTreeSize() > 0) { + right.walk(); + } + } +} diff --git a/null-object/src/main/java/com/iluwatar/nullobject/NullNode.java b/null-object/src/main/java/com/iluwatar/nullobject/NullNode.java index ce74ff056..dfa1454fa 100644 --- a/null-object/src/main/java/com/iluwatar/nullobject/NullNode.java +++ b/null-object/src/main/java/com/iluwatar/nullobject/NullNode.java @@ -33,8 +33,7 @@ public final class NullNode implements Node { private static final NullNode instance = new NullNode(); - private NullNode() { - } + private NullNode() {} public static NullNode getInstance() { return instance; diff --git a/null-object/src/test/java/com/iluwatar/nullobject/AppTest.java b/null-object/src/test/java/com/iluwatar/nullobject/AppTest.java index 01867936d..df790d108 100644 --- a/null-object/src/test/java/com/iluwatar/nullobject/AppTest.java +++ b/null-object/src/test/java/com/iluwatar/nullobject/AppTest.java @@ -24,17 +24,15 @@ */ package com.iluwatar.nullobject; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -/** - * Application test - */ +import org.junit.jupiter.api.Test; + +/** Application test */ class AppTest { @Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/null-object/src/test/java/com/iluwatar/nullobject/NullNodeTest.java b/null-object/src/test/java/com/iluwatar/nullobject/NullNodeTest.java index 8bcd8e7d9..1cc0a9d04 100644 --- a/null-object/src/test/java/com/iluwatar/nullobject/NullNodeTest.java +++ b/null-object/src/test/java/com/iluwatar/nullobject/NullNodeTest.java @@ -24,22 +24,17 @@ */ package com.iluwatar.nullobject; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertSame; -/** - * NullNodeTest - * - */ +import org.junit.jupiter.api.Test; + +/** NullNodeTest */ class NullNodeTest { - /** - * Verify if {@link NullNode#getInstance()} actually returns the same object instance - */ + /** Verify if {@link NullNode#getInstance()} actually returns the same object instance */ @Test void testGetInstance() { final var instance = NullNode.getInstance(); @@ -57,7 +52,7 @@ class NullNodeTest { } /** - * Removed unnecessary test method for {@link NullNode#walk()} as the method doesn't have an implementation. + * Removed unnecessary test method for {@link NullNode#walk()} as the method doesn't have an + * implementation. */ - } diff --git a/null-object/src/test/java/com/iluwatar/nullobject/TreeTest.java b/null-object/src/test/java/com/iluwatar/nullobject/TreeTest.java index ec2635c47..9c39e6f16 100644 --- a/null-object/src/test/java/com/iluwatar/nullobject/TreeTest.java +++ b/null-object/src/test/java/com/iluwatar/nullobject/TreeTest.java @@ -39,10 +39,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.slf4j.LoggerFactory; -/** - * TreeTest - * - */ +/** TreeTest */ class TreeTest { private InMemoryAppender appender; @@ -92,9 +89,7 @@ class TreeTest { assertEquals(7, TREE_ROOT.getTreeSize()); } - /** - * Walk through the tree and verify if every item is handled - */ + /** Walk through the tree and verify if every item is handled */ @Test void testWalk() { TREE_ROOT.walk(); @@ -160,5 +155,4 @@ class TreeTest { return log.size(); } } - } 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 0cde71918..9aae081c5 100644 --- a/object-mother/src/main/java/com/iluwatar/objectmother/King.java +++ b/object-mother/src/main/java/com/iluwatar/objectmother/King.java @@ -24,9 +24,7 @@ */ package com.iluwatar.objectmother; -/** - * Defines all attributes and behaviour related to the King. - */ +/** Defines all attributes and behaviour related to the King. */ public class King implements Royalty { boolean isDrunk = false; boolean isHappy = false; @@ -67,6 +65,5 @@ 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 22f944958..e210161b3 100644 --- a/object-mother/src/main/java/com/iluwatar/objectmother/Queen.java +++ b/object-mother/src/main/java/com/iluwatar/objectmother/Queen.java @@ -24,9 +24,7 @@ */ package com.iluwatar.objectmother; -/** - * Defines all attributes and behaviour related to the Queen. - */ +/** Defines all attributes and behaviour related to the Queen. */ public class Queen implements Royalty { private boolean isDrunk = false; private boolean isHappy = false; 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 795de80e6..f97e4d8d7 100644 --- a/object-mother/src/main/java/com/iluwatar/objectmother/Royalty.java +++ b/object-mother/src/main/java/com/iluwatar/objectmother/Royalty.java @@ -24,9 +24,7 @@ */ package com.iluwatar.objectmother; -/** - * Interface contracting Royalty Behaviour. - */ +/** Interface contracting Royalty Behaviour. */ public interface Royalty { void makeDrunk(); 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 1c30c3d94..509b32d70 100644 --- a/object-mother/src/main/java/com/iluwatar/objectmother/RoyaltyObjectMother.java +++ b/object-mother/src/main/java/com/iluwatar/objectmother/RoyaltyObjectMother.java @@ -24,9 +24,7 @@ */ package com.iluwatar.objectmother; -/** - * Object Mother Pattern generating Royalty Types. - */ +/** Object Mother Pattern generating Royalty Types. */ public final class RoyaltyObjectMother { /** 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 3b5655714..04f91372f 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,9 +33,7 @@ import com.iluwatar.objectmother.Queen; import com.iluwatar.objectmother.RoyaltyObjectMother; import org.junit.jupiter.api.Test; -/** - * Test Generation of Royalty Types using the object-mother - */ +/** Test Generation of Royalty Types using the object-mother */ class RoyaltyObjectMotherTest { @Test diff --git a/object-pool/pom.xml b/object-pool/pom.xml index 52233e375..72e46e4b5 100644 --- a/object-pool/pom.xml +++ b/object-pool/pom.xml @@ -34,6 +34,14 @@ object-pool + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine 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 5d97e4201..dfd1b118d 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 @@ -39,9 +39,7 @@ public abstract class ObjectPool { protected abstract T create(); - /** - * Checkout object from pool. - */ + /** Checkout object from pool. */ public synchronized T checkOut() { if (available.isEmpty()) { available.add(create()); diff --git a/object-pool/src/main/java/com/iluwatar/object/pool/Oliphaunt.java b/object-pool/src/main/java/com/iluwatar/object/pool/Oliphaunt.java index 6d7f5ce6d..97e8fea49 100644 --- a/object-pool/src/main/java/com/iluwatar/object/pool/Oliphaunt.java +++ b/object-pool/src/main/java/com/iluwatar/object/pool/Oliphaunt.java @@ -28,20 +28,15 @@ import java.util.concurrent.atomic.AtomicInteger; import lombok.Getter; import lombok.extern.slf4j.Slf4j; -/** - * Oliphaunts are expensive to create. - */ +/** Oliphaunts are expensive to create. */ @Slf4j public class Oliphaunt { private static final AtomicInteger counter = new AtomicInteger(0); - @Getter - private final int id; + @Getter private final int id; - /** - * Constructor. - */ + /** Constructor. */ public Oliphaunt() { id = counter.incrementAndGet(); try { diff --git a/object-pool/src/main/java/com/iluwatar/object/pool/OliphauntPool.java b/object-pool/src/main/java/com/iluwatar/object/pool/OliphauntPool.java index 0b1a2af18..c13fde73b 100644 --- a/object-pool/src/main/java/com/iluwatar/object/pool/OliphauntPool.java +++ b/object-pool/src/main/java/com/iluwatar/object/pool/OliphauntPool.java @@ -24,9 +24,7 @@ */ package com.iluwatar.object.pool; -/** - * Oliphaunt object pool. - */ +/** Oliphaunt object pool. */ public class OliphauntPool extends ObjectPool { @Override diff --git a/object-pool/src/test/java/com/iluwatar/object/pool/AppTest.java b/object-pool/src/test/java/com/iluwatar/object/pool/AppTest.java index c96c21bc5..8318e50bf 100644 --- a/object-pool/src/test/java/com/iluwatar/object/pool/AppTest.java +++ b/object-pool/src/test/java/com/iluwatar/object/pool/AppTest.java @@ -28,13 +28,11 @@ import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import org.junit.jupiter.api.Test; -/** - * Application test. - */ +/** Application test. */ class AppTest { @Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/object-pool/src/test/java/com/iluwatar/object/pool/OliphauntPoolTest.java b/object-pool/src/test/java/com/iluwatar/object/pool/OliphauntPoolTest.java index 1bd19c44b..b92995124 100644 --- a/object-pool/src/test/java/com/iluwatar/object/pool/OliphauntPoolTest.java +++ b/object-pool/src/test/java/com/iluwatar/object/pool/OliphauntPoolTest.java @@ -34,9 +34,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.List; import org.junit.jupiter.api.Test; -/** - * OliphauntPoolTest. - */ +/** OliphauntPoolTest. */ class OliphauntPoolTest { /** @@ -45,27 +43,29 @@ class OliphauntPoolTest { */ @Test void testSubsequentCheckinCheckout() { - assertTimeout(ofMillis(5000), () -> { - final var pool = new OliphauntPool(); - assertEquals("Pool available=0 inUse=0", pool.toString()); + assertTimeout( + ofMillis(5000), + () -> { + final var pool = new OliphauntPool(); + assertEquals("Pool available=0 inUse=0", pool.toString()); - final var expectedOliphaunt = pool.checkOut(); - assertEquals("Pool available=0 inUse=1", pool.toString()); + final var expectedOliphaunt = pool.checkOut(); + assertEquals("Pool available=0 inUse=1", pool.toString()); - pool.checkIn(expectedOliphaunt); - assertEquals("Pool available=1 inUse=0", pool.toString()); + pool.checkIn(expectedOliphaunt); + assertEquals("Pool available=1 inUse=0", pool.toString()); - for (int i = 0; i < 100; i++) { - final var oliphaunt = pool.checkOut(); - assertEquals("Pool available=0 inUse=1", pool.toString()); - assertSame(expectedOliphaunt, oliphaunt); - assertEquals(expectedOliphaunt.getId(), oliphaunt.getId()); - assertEquals(expectedOliphaunt.toString(), oliphaunt.toString()); + for (int i = 0; i < 100; i++) { + final var oliphaunt = pool.checkOut(); + assertEquals("Pool available=0 inUse=1", pool.toString()); + assertSame(expectedOliphaunt, oliphaunt); + assertEquals(expectedOliphaunt.getId(), oliphaunt.getId()); + assertEquals(expectedOliphaunt.toString(), oliphaunt.toString()); - pool.checkIn(oliphaunt); - assertEquals("Pool available=1 inUse=0", pool.toString()); - } - }); + pool.checkIn(oliphaunt); + assertEquals("Pool available=1 inUse=0", pool.toString()); + } + }); } /** @@ -74,50 +74,51 @@ class OliphauntPoolTest { */ @Test void testConcurrentCheckinCheckout() { - assertTimeout(ofMillis(5000), () -> { - final var pool = new OliphauntPool(); - assertEquals(pool.toString(), "Pool available=0 inUse=0"); + assertTimeout( + ofMillis(5000), + () -> { + final var pool = new OliphauntPool(); + assertEquals(pool.toString(), "Pool available=0 inUse=0"); - final var firstOliphaunt = pool.checkOut(); - assertEquals(pool.toString(), "Pool available=0 inUse=1"); + final var firstOliphaunt = pool.checkOut(); + assertEquals(pool.toString(), "Pool available=0 inUse=1"); - final var secondOliphaunt = pool.checkOut(); - assertEquals(pool.toString(), "Pool available=0 inUse=2"); + final var secondOliphaunt = pool.checkOut(); + assertEquals(pool.toString(), "Pool available=0 inUse=2"); - assertNotSame(firstOliphaunt, secondOliphaunt); - assertEquals(firstOliphaunt.getId() + 1, secondOliphaunt.getId()); + assertNotSame(firstOliphaunt, secondOliphaunt); + assertEquals(firstOliphaunt.getId() + 1, secondOliphaunt.getId()); - // After checking in the second, we should get the same when checking out a new oliphaunt ... - pool.checkIn(secondOliphaunt); - assertEquals(pool.toString(), "Pool available=1 inUse=1"); + // After checking in the second, we should get the same when checking out a new oliphaunt + // ... + pool.checkIn(secondOliphaunt); + assertEquals(pool.toString(), "Pool available=1 inUse=1"); - final var oliphaunt3 = pool.checkOut(); - assertEquals(pool.toString(), "Pool available=0 inUse=2"); - assertSame(secondOliphaunt, oliphaunt3); + final var oliphaunt3 = pool.checkOut(); + assertEquals(pool.toString(), "Pool available=0 inUse=2"); + assertSame(secondOliphaunt, oliphaunt3); - // ... and the same applies for the first one - pool.checkIn(firstOliphaunt); - assertEquals(pool.toString(), "Pool available=1 inUse=1"); + // ... and the same applies for the first one + pool.checkIn(firstOliphaunt); + assertEquals(pool.toString(), "Pool available=1 inUse=1"); - final var oliphaunt4 = pool.checkOut(); - assertEquals(pool.toString(), "Pool available=0 inUse=2"); - assertSame(firstOliphaunt, oliphaunt4); + final var oliphaunt4 = pool.checkOut(); + assertEquals(pool.toString(), "Pool available=0 inUse=2"); + assertSame(firstOliphaunt, oliphaunt4); - // When both oliphaunt return to the pool, we should still get the same instances - pool.checkIn(firstOliphaunt); - assertEquals(pool.toString(), "Pool available=1 inUse=1"); + // When both oliphaunt return to the pool, we should still get the same instances + pool.checkIn(firstOliphaunt); + assertEquals(pool.toString(), "Pool available=1 inUse=1"); - pool.checkIn(secondOliphaunt); - assertEquals(pool.toString(), "Pool available=2 inUse=0"); + pool.checkIn(secondOliphaunt); + assertEquals(pool.toString(), "Pool available=2 inUse=0"); - // The order of the returned instances is not determined, so just put them in a list - // and verify if both expected instances are in there. - final var oliphaunts = List.of(pool.checkOut(), pool.checkOut()); - assertEquals(pool.toString(), "Pool available=0 inUse=2"); - assertTrue(oliphaunts.contains(firstOliphaunt)); - assertTrue(oliphaunts.contains(secondOliphaunt)); - }); + // The order of the returned instances is not determined, so just put them in a list + // and verify if both expected instances are in there. + final var oliphaunts = List.of(pool.checkOut(), pool.checkOut()); + assertEquals(pool.toString(), "Pool available=0 inUse=2"); + assertTrue(oliphaunts.contains(firstOliphaunt)); + assertTrue(oliphaunts.contains(secondOliphaunt)); + }); } - - -} \ No newline at end of file +} diff --git a/observer/pom.xml b/observer/pom.xml index af7f26e7f..41fe814e0 100644 --- a/observer/pom.xml +++ b/observer/pom.xml @@ -34,6 +34,14 @@ observer + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/observer/src/main/java/com/iluwatar/observer/Hobbits.java b/observer/src/main/java/com/iluwatar/observer/Hobbits.java index 43ce675f4..0698a8aaf 100644 --- a/observer/src/main/java/com/iluwatar/observer/Hobbits.java +++ b/observer/src/main/java/com/iluwatar/observer/Hobbits.java @@ -26,9 +26,7 @@ package com.iluwatar.observer; import lombok.extern.slf4j.Slf4j; -/** - * Hobbits. - */ +/** Hobbits. */ @Slf4j public class Hobbits implements WeatherObserver { diff --git a/observer/src/main/java/com/iluwatar/observer/Orcs.java b/observer/src/main/java/com/iluwatar/observer/Orcs.java index 542101840..ff09ea8ad 100644 --- a/observer/src/main/java/com/iluwatar/observer/Orcs.java +++ b/observer/src/main/java/com/iluwatar/observer/Orcs.java @@ -26,9 +26,7 @@ package com.iluwatar.observer; import lombok.extern.slf4j.Slf4j; -/** - * Orcs. - */ +/** Orcs. */ @Slf4j public class Orcs implements WeatherObserver { diff --git a/observer/src/main/java/com/iluwatar/observer/Weather.java b/observer/src/main/java/com/iluwatar/observer/Weather.java index 8769292d4..eb19f0acc 100644 --- a/observer/src/main/java/com/iluwatar/observer/Weather.java +++ b/observer/src/main/java/com/iluwatar/observer/Weather.java @@ -51,9 +51,7 @@ public class Weather { observers.remove(obs); } - /** - * Makes time pass for weather. - */ + /** Makes time pass for weather. */ public void timePasses() { var enumValues = WeatherType.values(); currentWeather = enumValues[(currentWeather.ordinal() + 1) % enumValues.length]; diff --git a/observer/src/main/java/com/iluwatar/observer/WeatherObserver.java b/observer/src/main/java/com/iluwatar/observer/WeatherObserver.java index 17cac1fff..106d016ba 100644 --- a/observer/src/main/java/com/iluwatar/observer/WeatherObserver.java +++ b/observer/src/main/java/com/iluwatar/observer/WeatherObserver.java @@ -1,34 +1,31 @@ -/* - * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). - * - * The MIT License - * Copyright © 2014-2022 Ilkka Seppälä - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package com.iluwatar.observer; - -/** - * Observer interface. - */ -public interface WeatherObserver { - - void update(WeatherType currentWeather); - -} +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.observer; + +/** Observer interface. */ +public interface WeatherObserver { + + void update(WeatherType currentWeather); +} diff --git a/observer/src/main/java/com/iluwatar/observer/WeatherType.java b/observer/src/main/java/com/iluwatar/observer/WeatherType.java index 600f58648..7f52d6432 100644 --- a/observer/src/main/java/com/iluwatar/observer/WeatherType.java +++ b/observer/src/main/java/com/iluwatar/observer/WeatherType.java @@ -24,18 +24,16 @@ */ package com.iluwatar.observer; -import lombok.Getter; /** - * WeatherType enumeration. - */ -public enum WeatherType { +import lombok.Getter; +/** WeatherType enumeration. */ +public enum WeatherType { SUNNY("Sunny"), RAINY("Rainy"), WINDY("Windy"), COLD("Cold"); - @Getter - private final String description; + @Getter private final String description; WeatherType(String description) { this.description = description; diff --git a/observer/src/main/java/com/iluwatar/observer/generic/GenHobbits.java b/observer/src/main/java/com/iluwatar/observer/generic/GenHobbits.java index 1d4e9baa6..22c1404c7 100644 --- a/observer/src/main/java/com/iluwatar/observer/generic/GenHobbits.java +++ b/observer/src/main/java/com/iluwatar/observer/generic/GenHobbits.java @@ -27,9 +27,7 @@ package com.iluwatar.observer.generic; import com.iluwatar.observer.WeatherType; import lombok.extern.slf4j.Slf4j; -/** - * GHobbits. - */ +/** GHobbits. */ @Slf4j public class GenHobbits implements Race { diff --git a/observer/src/main/java/com/iluwatar/observer/generic/GenOrcs.java b/observer/src/main/java/com/iluwatar/observer/generic/GenOrcs.java index bbf1c197f..163c38582 100644 --- a/observer/src/main/java/com/iluwatar/observer/generic/GenOrcs.java +++ b/observer/src/main/java/com/iluwatar/observer/generic/GenOrcs.java @@ -27,9 +27,7 @@ package com.iluwatar.observer.generic; import com.iluwatar.observer.WeatherType; import lombok.extern.slf4j.Slf4j; -/** - * GOrcs. - */ +/** GOrcs. */ @Slf4j public class GenOrcs implements Race { diff --git a/observer/src/main/java/com/iluwatar/observer/generic/GenWeather.java b/observer/src/main/java/com/iluwatar/observer/generic/GenWeather.java index 485f2ab36..c05277028 100644 --- a/observer/src/main/java/com/iluwatar/observer/generic/GenWeather.java +++ b/observer/src/main/java/com/iluwatar/observer/generic/GenWeather.java @@ -27,9 +27,7 @@ package com.iluwatar.observer.generic; import com.iluwatar.observer.WeatherType; import lombok.extern.slf4j.Slf4j; -/** - * GWeather. - */ +/** GWeather. */ @Slf4j public class GenWeather extends Observable { @@ -39,9 +37,7 @@ public class GenWeather extends Observable { currentWeather = WeatherType.SUNNY; } - /** - * Makes time pass for weather. - */ + /** Makes time pass for weather. */ public void timePasses() { var enumValues = WeatherType.values(); currentWeather = enumValues[(currentWeather.ordinal() + 1) % enumValues.length]; diff --git a/observer/src/main/java/com/iluwatar/observer/generic/Observable.java b/observer/src/main/java/com/iluwatar/observer/generic/Observable.java index ff7e917d4..2e10d7de2 100644 --- a/observer/src/main/java/com/iluwatar/observer/generic/Observable.java +++ b/observer/src/main/java/com/iluwatar/observer/generic/Observable.java @@ -50,9 +50,7 @@ public abstract class Observable, O extends Observ this.observers.remove(observer); } - /** - * Notify observers. - */ + /** Notify observers. */ @SuppressWarnings("unchecked") public void notifyObservers(A argument) { for (var observer : observers) { diff --git a/observer/src/main/java/com/iluwatar/observer/generic/Race.java b/observer/src/main/java/com/iluwatar/observer/generic/Race.java index 6b602e2f7..2f30d5881 100644 --- a/observer/src/main/java/com/iluwatar/observer/generic/Race.java +++ b/observer/src/main/java/com/iluwatar/observer/generic/Race.java @@ -26,8 +26,5 @@ package com.iluwatar.observer.generic; import com.iluwatar.observer.WeatherType; -/** - * Race. - */ -public interface Race extends Observer { -} +/** Race. */ +public interface Race extends Observer {} diff --git a/observer/src/test/java/com/iluwatar/observer/AppTest.java b/observer/src/test/java/com/iluwatar/observer/AppTest.java index 261b51fe4..2322ff31b 100644 --- a/observer/src/test/java/com/iluwatar/observer/AppTest.java +++ b/observer/src/test/java/com/iluwatar/observer/AppTest.java @@ -28,13 +28,11 @@ import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import org.junit.jupiter.api.Test; -/** - * Application test. - */ +/** Application test. */ class AppTest { @Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/observer/src/test/java/com/iluwatar/observer/HobbitsTest.java b/observer/src/test/java/com/iluwatar/observer/HobbitsTest.java index 823061c72..abce5cfa4 100644 --- a/observer/src/test/java/com/iluwatar/observer/HobbitsTest.java +++ b/observer/src/test/java/com/iluwatar/observer/HobbitsTest.java @@ -27,26 +27,20 @@ package com.iluwatar.observer; import java.util.Collection; import java.util.List; -/** - * HobbitsTest - * - */ +/** HobbitsTest */ class HobbitsTest extends WeatherObserverTest { @Override public Collection dataProvider() { return List.of( - new Object[]{WeatherType.SUNNY, "The hobbits are facing Sunny weather now"}, - new Object[]{WeatherType.RAINY, "The hobbits are facing Rainy weather now"}, - new Object[]{WeatherType.WINDY, "The hobbits are facing Windy weather now"}, - new Object[]{WeatherType.COLD, "The hobbits are facing Cold weather now"}); + new Object[] {WeatherType.SUNNY, "The hobbits are facing Sunny weather now"}, + new Object[] {WeatherType.RAINY, "The hobbits are facing Rainy weather now"}, + new Object[] {WeatherType.WINDY, "The hobbits are facing Windy weather now"}, + new Object[] {WeatherType.COLD, "The hobbits are facing Cold weather now"}); } - /** - * Create a new test with the given weather and expected response - */ + /** Create a new test with the given weather and expected response */ public HobbitsTest() { super(Hobbits::new); } - } diff --git a/observer/src/test/java/com/iluwatar/observer/OrcsTest.java b/observer/src/test/java/com/iluwatar/observer/OrcsTest.java index 71dacc948..05e34758c 100644 --- a/observer/src/test/java/com/iluwatar/observer/OrcsTest.java +++ b/observer/src/test/java/com/iluwatar/observer/OrcsTest.java @@ -27,26 +27,20 @@ package com.iluwatar.observer; import java.util.Collection; import java.util.List; -/** - * OrcsTest - * - */ +/** OrcsTest */ class OrcsTest extends WeatherObserverTest { @Override public Collection dataProvider() { return List.of( - new Object[]{WeatherType.SUNNY, "The orcs are facing Sunny weather now"}, - new Object[]{WeatherType.RAINY, "The orcs are facing Rainy weather now"}, - new Object[]{WeatherType.WINDY, "The orcs are facing Windy weather now"}, - new Object[]{WeatherType.COLD, "The orcs are facing Cold weather now"}); + new Object[] {WeatherType.SUNNY, "The orcs are facing Sunny weather now"}, + new Object[] {WeatherType.RAINY, "The orcs are facing Rainy weather now"}, + new Object[] {WeatherType.WINDY, "The orcs are facing Windy weather now"}, + new Object[] {WeatherType.COLD, "The orcs are facing Cold weather now"}); } - /** - * Create a new test with the given weather and expected response - */ + /** Create a new test with the given weather and expected response */ public OrcsTest() { super(Orcs::new); } - } diff --git a/observer/src/test/java/com/iluwatar/observer/WeatherObserverTest.java b/observer/src/test/java/com/iluwatar/observer/WeatherObserverTest.java index 6702438b6..95958139e 100644 --- a/observer/src/test/java/com/iluwatar/observer/WeatherObserverTest.java +++ b/observer/src/test/java/com/iluwatar/observer/WeatherObserverTest.java @@ -37,6 +37,7 @@ import org.junit.jupiter.params.provider.MethodSource; /** * Weather Observer Tests + * * @param Type of WeatherObserver */ @TestInstance(TestInstance.Lifecycle.PER_CLASS) @@ -54,15 +55,13 @@ public abstract class WeatherObserverTest { appender.stop(); } - /** - * The observer instance factory - */ + /** The observer instance factory */ private final Supplier factory; /** * Create a new test instance using the given parameters * - * @param factory The factory, used to create an instance of the tested observer + * @param factory The factory, used to create an instance of the tested observer */ WeatherObserverTest(final Supplier factory) { this.factory = factory; @@ -70,9 +69,7 @@ public abstract class WeatherObserverTest { public abstract Collection dataProvider(); - /** - * Verify if the weather has the expected influence on the observer - */ + /** Verify if the weather has the expected influence on the observer */ @ParameterizedTest @MethodSource("dataProvider") void testObserver(WeatherType weather, String response) { @@ -83,5 +80,4 @@ public abstract class WeatherObserverTest { assertEquals(response, appender.getLastMessage()); assertEquals(1, appender.getLogSize()); } - } diff --git a/observer/src/test/java/com/iluwatar/observer/WeatherTest.java b/observer/src/test/java/com/iluwatar/observer/WeatherTest.java index 15b3f5db8..9d33eaaa0 100644 --- a/observer/src/test/java/com/iluwatar/observer/WeatherTest.java +++ b/observer/src/test/java/com/iluwatar/observer/WeatherTest.java @@ -35,10 +35,7 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -/** - * WeatherTest - * - */ +/** WeatherTest */ class WeatherTest { private InMemoryAppender appender; @@ -77,9 +74,7 @@ class WeatherTest { assertEquals(2, appender.getLogSize()); } - /** - * Verify if the weather passes in the order of the {@link WeatherType}s - */ + /** Verify if the weather passes in the order of the {@link WeatherType}s */ @Test void testTimePasses() { final var observer = mock(WeatherObserver.class); @@ -95,5 +90,4 @@ class WeatherTest { verifyNoMoreInteractions(observer); } - } diff --git a/observer/src/test/java/com/iluwatar/observer/generic/GHobbitsTest.java b/observer/src/test/java/com/iluwatar/observer/generic/GHobbitsTest.java index 54ec19440..d1c9af42c 100644 --- a/observer/src/test/java/com/iluwatar/observer/generic/GHobbitsTest.java +++ b/observer/src/test/java/com/iluwatar/observer/generic/GHobbitsTest.java @@ -28,26 +28,20 @@ import com.iluwatar.observer.WeatherType; import java.util.Collection; import java.util.List; -/** - * GHobbitsTest. - */ +/** GHobbitsTest. */ class GHobbitsTest extends ObserverTest { @Override public Collection dataProvider() { return List.of( - new Object[]{WeatherType.SUNNY, "The hobbits are facing Sunny weather now"}, - new Object[]{WeatherType.RAINY, "The hobbits are facing Rainy weather now"}, - new Object[]{WeatherType.WINDY, "The hobbits are facing Windy weather now"}, - new Object[]{WeatherType.COLD, "The hobbits are facing Cold weather now"} - ); + new Object[] {WeatherType.SUNNY, "The hobbits are facing Sunny weather now"}, + new Object[] {WeatherType.RAINY, "The hobbits are facing Rainy weather now"}, + new Object[] {WeatherType.WINDY, "The hobbits are facing Windy weather now"}, + new Object[] {WeatherType.COLD, "The hobbits are facing Cold weather now"}); } - /** - * Create a new test with the given weather and expected response. - */ + /** Create a new test with the given weather and expected response. */ public GHobbitsTest() { super(GenHobbits::new); } - } diff --git a/observer/src/test/java/com/iluwatar/observer/generic/GWeatherTest.java b/observer/src/test/java/com/iluwatar/observer/generic/GWeatherTest.java index 1fd42a1cd..a052cf2c1 100644 --- a/observer/src/test/java/com/iluwatar/observer/generic/GWeatherTest.java +++ b/observer/src/test/java/com/iluwatar/observer/generic/GWeatherTest.java @@ -37,10 +37,7 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -/** - * GWeatherTest - * - */ +/** GWeatherTest */ class GWeatherTest { private InMemoryAppender appender; @@ -79,9 +76,7 @@ class GWeatherTest { assertEquals(2, appender.getLogSize()); } - /** - * Verify if the weather passes in the order of the {@link WeatherType}s - */ + /** Verify if the weather passes in the order of the {@link WeatherType}s */ @Test void testTimePasses() { final var observer = mock(Race.class); @@ -97,5 +92,4 @@ class GWeatherTest { verifyNoMoreInteractions(observer); } - } 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 9a76e9bdb..2a06651b2 100644 --- a/observer/src/test/java/com/iluwatar/observer/generic/ObserverTest.java +++ b/observer/src/test/java/com/iluwatar/observer/generic/ObserverTest.java @@ -24,21 +24,21 @@ */ package com.iluwatar.observer.generic; +import static org.junit.jupiter.api.Assertions.assertEquals; + import com.iluwatar.observer.WeatherType; import com.iluwatar.observer.utils.InMemoryAppender; +import java.util.Collection; +import java.util.function.Supplier; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.TestInstance; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; -import java.util.Collection; -import java.util.function.Supplier; - -import static org.junit.jupiter.api.Assertions.assertEquals; - /** * Test for Observers + * * @param Type of Observer */ @TestInstance(TestInstance.Lifecycle.PER_CLASS) @@ -56,15 +56,13 @@ public abstract class ObserverTest> { appender.stop(); } - /** - * The observer instance factory - */ + /** The observer instance factory */ private final Supplier factory; /** * Create a new test instance using the given parameters * - * @param factory The factory, used to create an instance of the tested observer + * @param factory The factory, used to create an instance of the tested observer */ ObserverTest(final Supplier factory) { this.factory = factory; @@ -72,9 +70,7 @@ public abstract class ObserverTest> { public abstract Collection dataProvider(); - /** - * Verify if the weather has the expected influence on the observer - */ + /** Verify if the weather has the expected influence on the observer */ @ParameterizedTest @MethodSource("dataProvider") void testObserver(WeatherType weather, String response) { @@ -85,5 +81,4 @@ public abstract class ObserverTest> { assertEquals(response, appender.getLastMessage()); assertEquals(1, appender.getLogSize()); } - } diff --git a/observer/src/test/java/com/iluwatar/observer/generic/OrcsTest.java b/observer/src/test/java/com/iluwatar/observer/generic/OrcsTest.java index 0439bf56b..47d604fd7 100644 --- a/observer/src/test/java/com/iluwatar/observer/generic/OrcsTest.java +++ b/observer/src/test/java/com/iluwatar/observer/generic/OrcsTest.java @@ -28,27 +28,20 @@ import com.iluwatar.observer.WeatherType; import java.util.Collection; import java.util.List; -/** - * OrcsTest - * - */ +/** OrcsTest */ class OrcsTest extends ObserverTest { @Override public Collection dataProvider() { return List.of( - new Object[]{WeatherType.SUNNY, "The orcs are facing Sunny weather now"}, - new Object[]{WeatherType.RAINY, "The orcs are facing Rainy weather now"}, - new Object[]{WeatherType.WINDY, "The orcs are facing Windy weather now"}, - new Object[]{WeatherType.COLD, "The orcs are facing Cold weather now"} - ); + new Object[] {WeatherType.SUNNY, "The orcs are facing Sunny weather now"}, + new Object[] {WeatherType.RAINY, "The orcs are facing Rainy weather now"}, + new Object[] {WeatherType.WINDY, "The orcs are facing Windy weather now"}, + new Object[] {WeatherType.COLD, "The orcs are facing Cold weather now"}); } - /** - * Create a new test with the given weather and expected response - */ + /** Create a new test with the given weather and expected response */ public OrcsTest() { super(GenOrcs::new); } - } 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 1fc486881..36e92d66e 100644 --- a/observer/src/test/java/com/iluwatar/observer/utils/InMemoryAppender.java +++ b/observer/src/test/java/com/iluwatar/observer/utils/InMemoryAppender.java @@ -31,9 +31,7 @@ import java.util.LinkedList; import java.util.List; import org.slf4j.LoggerFactory; -/** - * InMemory Log Appender Util. - */ +/** InMemory Log Appender Util. */ public class InMemoryAppender extends AppenderBase { private final List log = new LinkedList<>(); diff --git a/optimistic-offline-lock/src/main/java/com/iluwatar/api/UpdateService.java b/optimistic-offline-lock/src/main/java/com/iluwatar/api/UpdateService.java index e41af6d50..5b7489c4a 100644 --- a/optimistic-offline-lock/src/main/java/com/iluwatar/api/UpdateService.java +++ b/optimistic-offline-lock/src/main/java/com/iluwatar/api/UpdateService.java @@ -35,7 +35,7 @@ public interface UpdateService { * Update entity. * * @param obj entity to update - * @param id primary key + * @param id primary key * @return modified entity */ T doUpdate(T obj, long id); diff --git a/optimistic-offline-lock/src/main/java/com/iluwatar/exception/ApplicationException.java b/optimistic-offline-lock/src/main/java/com/iluwatar/exception/ApplicationException.java index 4dbd1918b..ed065c597 100644 --- a/optimistic-offline-lock/src/main/java/com/iluwatar/exception/ApplicationException.java +++ b/optimistic-offline-lock/src/main/java/com/iluwatar/exception/ApplicationException.java @@ -24,9 +24,7 @@ */ package com.iluwatar.exception; -/** - * Exception happens in application during business-logic execution. - */ +/** Exception happens in application during business-logic execution. */ public class ApplicationException extends RuntimeException { /** diff --git a/optimistic-offline-lock/src/main/java/com/iluwatar/model/Card.java b/optimistic-offline-lock/src/main/java/com/iluwatar/model/Card.java index 73e27b2ec..9728d7c7f 100644 --- a/optimistic-offline-lock/src/main/java/com/iluwatar/model/Card.java +++ b/optimistic-offline-lock/src/main/java/com/iluwatar/model/Card.java @@ -24,38 +24,27 @@ */ package com.iluwatar.model; - import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; -/** - * Bank card entity. - */ +/** Bank card entity. */ @Data @Builder @NoArgsConstructor @AllArgsConstructor public class Card { - /** - * Primary key. - */ + /** Primary key. */ private long id; - /** - * Foreign key points to card's owner. - */ + /** Foreign key points to card's owner. */ private long personId; - /** - * Sum of money. - */ + /** Sum of money. */ private float sum; - /** - * Current version of object. - */ + /** Current version of object. */ private int version; } diff --git a/optimistic-offline-lock/src/main/java/com/iluwatar/service/CardUpdateService.java b/optimistic-offline-lock/src/main/java/com/iluwatar/service/CardUpdateService.java index d36e092c9..9e70ee24e 100644 --- a/optimistic-offline-lock/src/main/java/com/iluwatar/service/CardUpdateService.java +++ b/optimistic-offline-lock/src/main/java/com/iluwatar/service/CardUpdateService.java @@ -30,9 +30,7 @@ import com.iluwatar.model.Card; import com.iluwatar.repository.JpaRepository; import lombok.RequiredArgsConstructor; -/** - * Service to update {@link Card} entity. - */ +/** Service to update {@link Card} entity. */ @RequiredArgsConstructor public class CardUpdateService implements UpdateService { @@ -45,11 +43,10 @@ public class CardUpdateService implements UpdateService { int initialVersion = cardToUpdate.getVersion(); float resultSum = cardToUpdate.getSum() + additionalSum; cardToUpdate.setSum(resultSum); - //Maybe more complex business-logic e.g. HTTP-requests and so on + // Maybe more complex business-logic e.g. HTTP-requests and so on if (initialVersion != cardJpaRepository.getEntityVersionById(id)) { - String exMessage = - String.format("Entity with id %s were updated in another transaction", id); + String exMessage = String.format("Entity with id %s were updated in another transaction", id); throw new ApplicationException(exMessage); } diff --git a/optimistic-offline-lock/src/test/java/com/iluwatar/OptimisticLockTest.java b/optimistic-offline-lock/src/test/java/com/iluwatar/OptimisticLockTest.java index c50ed8780..7731d12d7 100644 --- a/optimistic-offline-lock/src/test/java/com/iluwatar/OptimisticLockTest.java +++ b/optimistic-offline-lock/src/test/java/com/iluwatar/OptimisticLockTest.java @@ -24,6 +24,9 @@ */ package com.iluwatar; +import static org.mockito.Mockito.eq; +import static org.mockito.Mockito.when; + import com.iluwatar.exception.ApplicationException; import com.iluwatar.model.Card; import com.iluwatar.repository.JpaRepository; @@ -33,9 +36,6 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import static org.mockito.Mockito.when; -import static org.mockito.Mockito.eq; - @SuppressWarnings({"rawtypes", "unchecked"}) public class OptimisticLockTest { @@ -53,27 +53,19 @@ public class OptimisticLockTest { public void shouldNotUpdateEntityOnDifferentVersion() { int initialVersion = 1; long cardId = 123L; - Card card = Card.builder() - .id(cardId) - .version(initialVersion) - .sum(123f) - .build(); + Card card = Card.builder().id(cardId).version(initialVersion).sum(123f).build(); when(cardRepository.findById(eq(cardId))).thenReturn(card); when(cardRepository.getEntityVersionById(Mockito.eq(cardId))).thenReturn(initialVersion + 1); - Assertions.assertThrows(ApplicationException.class, - () -> cardUpdateService.doUpdate(card, cardId)); + Assertions.assertThrows( + ApplicationException.class, () -> cardUpdateService.doUpdate(card, cardId)); } @Test public void shouldUpdateOnSameVersion() { int initialVersion = 1; long cardId = 123L; - Card card = Card.builder() - .id(cardId) - .version(initialVersion) - .sum(123f) - .build(); + Card card = Card.builder().id(cardId).version(initialVersion).sum(123f).build(); when(cardRepository.findById(eq(cardId))).thenReturn(card); when(cardRepository.getEntityVersionById(Mockito.eq(cardId))).thenReturn(initialVersion); diff --git a/page-controller/pom.xml b/page-controller/pom.xml index 70afb0675..c314459e9 100644 --- a/page-controller/pom.xml +++ b/page-controller/pom.xml @@ -37,22 +37,12 @@ page-controller page-controller page-controller - - - - org.springframework.boot - spring-boot-dependencies - pom - 3.2.4 - import - - - org.springframework spring-webmvc + 6.2.5 org.springframework.boot @@ -61,10 +51,12 @@ org.springframework spring-context + 6.2.5 org.springframework.boot spring-boot-starter-thymeleaf + 3.4.4 org.junit.jupiter @@ -81,11 +73,6 @@ spring-boot-starter-test test - - org.springframework - spring-test - test - diff --git a/page-controller/src/main/java/com/iluwatar/page/controller/App.java b/page-controller/src/main/java/com/iluwatar/page/controller/App.java index 278c01396..076ebf081 100644 --- a/page-controller/src/main/java/com/iluwatar/page/controller/App.java +++ b/page-controller/src/main/java/com/iluwatar/page/controller/App.java @@ -30,10 +30,11 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; /** * Page Controller pattern is utilized when we want to simplify relationship in a dynamic website. - * It is an approach of one front page leading to one logical file that handles HTTP requests and actions. - * In this example, we build a website with signup page handling an input form with Signup Controller, Signup View, and Signup Model - * and after signup, it is redirected to a user page handling with User Controller, User View, and User Model. -*/ + * It is an approach of one front page leading to one logical file that handles HTTP requests and + * actions. In this example, we build a website with signup page handling an input form with Signup + * Controller, Signup View, and Signup Model and after signup, it is redirected to a user page + * handling with User Controller, User View, and User Model. + */ @Slf4j @SpringBootApplication public class App { diff --git a/page-controller/src/main/java/com/iluwatar/page/controller/SignupController.java b/page-controller/src/main/java/com/iluwatar/page/controller/SignupController.java index 2efdc9ef1..08d64cebf 100644 --- a/page-controller/src/main/java/com/iluwatar/page/controller/SignupController.java +++ b/page-controller/src/main/java/com/iluwatar/page/controller/SignupController.java @@ -31,31 +31,23 @@ import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.servlet.mvc.support.RedirectAttributes; -/** - * Signup Controller. - */ +/** Signup Controller. */ @Slf4j @Controller @Component public class SignupController { SignupView view = new SignupView(); - /** - * Signup Controller can handle http request and decide which model and view use. - */ - SignupController() { - } - /** - * Handle http GET request. - */ + /** Signup Controller can handle http request and decide which model and view use. */ + SignupController() {} + + /** Handle http GET request. */ @GetMapping("/signup") public String getSignup() { return view.display(); } - /** - * Handle http POST request and access model and view. - */ + /** Handle http POST request and access model and view. */ @PostMapping("/signup") public String create(SignupModel form, RedirectAttributes redirectAttributes) { LOGGER.info(form.getName()); diff --git a/page-controller/src/main/java/com/iluwatar/page/controller/SignupModel.java b/page-controller/src/main/java/com/iluwatar/page/controller/SignupModel.java index ee9c2e1ce..88134b923 100644 --- a/page-controller/src/main/java/com/iluwatar/page/controller/SignupModel.java +++ b/page-controller/src/main/java/com/iluwatar/page/controller/SignupModel.java @@ -28,9 +28,7 @@ import lombok.Data; import lombok.NoArgsConstructor; import org.springframework.stereotype.Component; -/** - * ignup model. - */ +/** ignup model. */ @Component @Data @NoArgsConstructor @@ -38,5 +36,4 @@ public class SignupModel { private String name; private String email; private String password; - -} \ No newline at end of file +} diff --git a/page-controller/src/main/java/com/iluwatar/page/controller/SignupView.java b/page-controller/src/main/java/com/iluwatar/page/controller/SignupView.java index c295fa471..ef0cad94d 100644 --- a/page-controller/src/main/java/com/iluwatar/page/controller/SignupView.java +++ b/page-controller/src/main/java/com/iluwatar/page/controller/SignupView.java @@ -27,9 +27,7 @@ package com.iluwatar.page.controller; import lombok.NoArgsConstructor; import lombok.extern.slf4j.Slf4j; -/** - * Signup View. - */ +/** Signup View. */ @Slf4j @NoArgsConstructor public class SignupView { @@ -39,11 +37,10 @@ public class SignupView { return "/signup"; } - /** - * redirect to user page. - */ + /** redirect to user page. */ public String redirect(SignupModel form) { - LOGGER.info("Redirect to user page with " + "name " + form.getName() + " email " + form.getEmail()); + LOGGER.info( + "Redirect to user page with " + "name " + form.getName() + " email " + form.getEmail()); return "redirect:/user"; } -} \ No newline at end of file +} diff --git a/page-controller/src/main/java/com/iluwatar/page/controller/UserController.java b/page-controller/src/main/java/com/iluwatar/page/controller/UserController.java index 0f4743778..2e0ee6682 100644 --- a/page-controller/src/main/java/com/iluwatar/page/controller/UserController.java +++ b/page-controller/src/main/java/com/iluwatar/page/controller/UserController.java @@ -30,22 +30,18 @@ import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; -/** - * User Controller. - */ +/** User Controller. */ @Slf4j @Controller @NoArgsConstructor public class UserController { private final UserView view = new UserView(); - /** - * Handle http GET request and access view and model. - */ + /** Handle http GET request and access view and model. */ @GetMapping("/user") public String getUserPath(SignupModel form, Model model) { model.addAttribute("name", form.getName()); model.addAttribute("email", form.getEmail()); return view.display(form); } -} \ No newline at end of file +} diff --git a/page-controller/src/main/java/com/iluwatar/page/controller/UserModel.java b/page-controller/src/main/java/com/iluwatar/page/controller/UserModel.java index 0f099b2e6..3dcb0e43e 100644 --- a/page-controller/src/main/java/com/iluwatar/page/controller/UserModel.java +++ b/page-controller/src/main/java/com/iluwatar/page/controller/UserModel.java @@ -27,13 +27,10 @@ package com.iluwatar.page.controller; import lombok.Data; import lombok.NoArgsConstructor; -/** - * User model. - */ +/** User model. */ @Data @NoArgsConstructor public class UserModel { private String name; private String email; - -} \ No newline at end of file +} diff --git a/page-controller/src/main/java/com/iluwatar/page/controller/UserView.java b/page-controller/src/main/java/com/iluwatar/page/controller/UserView.java index 3f4469d7d..e759cc54f 100644 --- a/page-controller/src/main/java/com/iluwatar/page/controller/UserView.java +++ b/page-controller/src/main/java/com/iluwatar/page/controller/UserView.java @@ -26,13 +26,12 @@ package com.iluwatar.page.controller; import lombok.extern.slf4j.Slf4j; -/** - * User view class generating html file. - */ +/** User view class generating html file. */ @Slf4j public class UserView { /** * displaying command to generate html. + * * @param user model content. */ public String display(SignupModel user) { diff --git a/page-controller/src/test/java/com/iluwatar/page/controller/AppTest.java b/page-controller/src/test/java/com/iluwatar/page/controller/AppTest.java index 9dcbfe3f8..b3d374210 100644 --- a/page-controller/src/test/java/com/iluwatar/page/controller/AppTest.java +++ b/page-controller/src/test/java/com/iluwatar/page/controller/AppTest.java @@ -24,15 +24,14 @@ */ package com.iluwatar.page.controller; -import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -/** - * Application test - */ +import org.junit.jupiter.api.Test; + +/** Application test */ public class AppTest { @Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/page-controller/src/test/java/com/iluwatar/page/controller/SignupControllerTest.java b/page-controller/src/test/java/com/iluwatar/page/controller/SignupControllerTest.java index 7260c24d4..08440d88d 100644 --- a/page-controller/src/test/java/com/iluwatar/page/controller/SignupControllerTest.java +++ b/page-controller/src/test/java/com/iluwatar/page/controller/SignupControllerTest.java @@ -24,19 +24,16 @@ */ package com.iluwatar.page.controller; +import static org.junit.jupiter.api.Assertions.assertEquals; + import org.junit.jupiter.api.Test; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import org.springframework.web.servlet.mvc.support.RedirectAttributesModelMap; -import static org.junit.jupiter.api.Assertions.assertEquals; -/** - * Test for Signup Controller - */ +/** Test for Signup Controller */ public class SignupControllerTest { - /** - * Verify if user can sign up and redirect to user page - */ + /** Verify if user can sign up and redirect to user page */ @Test void testSignup() { var controller = new SignupController(); diff --git a/page-controller/src/test/java/com/iluwatar/page/controller/SignupModelTest.java b/page-controller/src/test/java/com/iluwatar/page/controller/SignupModelTest.java index 46e60eb94..237ea138c 100644 --- a/page-controller/src/test/java/com/iluwatar/page/controller/SignupModelTest.java +++ b/page-controller/src/test/java/com/iluwatar/page/controller/SignupModelTest.java @@ -24,16 +24,13 @@ */ package com.iluwatar.page.controller; -import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; -/** - * Test for Signup Model - */ +import org.junit.jupiter.api.Test; + +/** Test for Signup Model */ public class SignupModelTest { - /** - * Verify if a user can set a name properly - */ + /** Verify if a user can set a name properly */ @Test void testSetName() { SignupModel model = new SignupModel(); @@ -41,9 +38,7 @@ public class SignupModelTest { assertEquals("Lily", model.getName()); } - /** - * Verify if a user can set an email properly - */ + /** Verify if a user can set an email properly */ @Test void testSetEmail() { SignupModel model = new SignupModel(); @@ -51,9 +46,7 @@ public class SignupModelTest { assertEquals("Lily@email", model.getEmail()); } - /** - * Verify if a user can set a password properly - */ + /** Verify if a user can set a password properly */ @Test void testSetPassword() { SignupModel model = new SignupModel(); diff --git a/page-controller/src/test/java/com/iluwatar/page/controller/UserControllerTest.java b/page-controller/src/test/java/com/iluwatar/page/controller/UserControllerTest.java index 7fd1c0cd1..bf5eef595 100644 --- a/page-controller/src/test/java/com/iluwatar/page/controller/UserControllerTest.java +++ b/page-controller/src/test/java/com/iluwatar/page/controller/UserControllerTest.java @@ -24,6 +24,10 @@ */ package com.iluwatar.page.controller; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; @@ -31,9 +35,6 @@ import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMock import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.web.servlet.MockMvc; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @ExtendWith(SpringExtension.class) @SpringBootTest @@ -41,17 +42,13 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. public class UserControllerTest { private UserController userController; - @Autowired - MockMvc mockMvc; + @Autowired MockMvc mockMvc; - /** - * Verify if view and model are directed properly - */ + /** Verify if view and model are directed properly */ @Test - void testGetUserPath () throws Exception { - this.mockMvc.perform(get("/user") - .param("name", "Lily") - .param("email", "Lily@email.com")) + void testGetUserPath() throws Exception { + this.mockMvc + .perform(get("/user").param("name", "Lily").param("email", "Lily@email.com")) .andExpect(status().isOk()) .andExpect(model().attribute("name", "Lily")) .andExpect(model().attribute("email", "Lily@email.com")) diff --git a/page-controller/src/test/java/com/iluwatar/page/controller/UserModelTest.java b/page-controller/src/test/java/com/iluwatar/page/controller/UserModelTest.java index 49e1102c8..8ecafae2d 100644 --- a/page-controller/src/test/java/com/iluwatar/page/controller/UserModelTest.java +++ b/page-controller/src/test/java/com/iluwatar/page/controller/UserModelTest.java @@ -29,9 +29,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; public class UserModelTest { - /** - * Verify if a user can set a name properly - */ + /** Verify if a user can set a name properly */ @Test void testSetName() { UserModel model = new UserModel(); @@ -39,9 +37,7 @@ public class UserModelTest { assertEquals("Lily", model.getName()); } - /** - * Verify if a user can set an email properly - */ + /** Verify if a user can set an email properly */ @Test void testSetEmail() { UserModel model = new UserModel(); diff --git a/page-object/pom.xml b/page-object/pom.xml index 4f70425c9..380288a53 100644 --- a/page-object/pom.xml +++ b/page-object/pom.xml @@ -27,17 +27,6 @@ --> 4.0.0 - - 11 - 11 - - - - org.htmlunit - htmlunit - test - - com.iluwatar java-design-patterns @@ -49,6 +38,13 @@ sample-application test-automation + + + org.htmlunit + htmlunit + test + + diff --git a/page-object/sample-application/pom.xml b/page-object/sample-application/pom.xml index e74f4f539..cf1b96e09 100644 --- a/page-object/sample-application/pom.xml +++ b/page-object/sample-application/pom.xml @@ -32,5 +32,15 @@ com.iluwatar 1.26.0-SNAPSHOT + + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + + sample-application diff --git a/page-object/sample-application/src/main/java/com/iluwatar/pageobject/App.java b/page-object/sample-application/src/main/java/com/iluwatar/pageobject/App.java index 0913af68e..aaf19fb0c 100644 --- a/page-object/sample-application/src/main/java/com/iluwatar/pageobject/App.java +++ b/page-object/sample-application/src/main/java/com/iluwatar/pageobject/App.java @@ -52,8 +52,7 @@ import lombok.extern.slf4j.Slf4j; @Slf4j public final class App { - private App() { - } + private App() {} /** * Application entry point @@ -85,6 +84,5 @@ public final class App { } catch (IOException ex) { LOGGER.error("An error occurred.", ex); } - } } diff --git a/page-object/src/main/java/com/iluwatar/pageobject/App.java b/page-object/src/main/java/com/iluwatar/pageobject/App.java index c779ff9e3..a0eda082f 100644 --- a/page-object/src/main/java/com/iluwatar/pageobject/App.java +++ b/page-object/src/main/java/com/iluwatar/pageobject/App.java @@ -50,8 +50,7 @@ import java.io.IOException; */ public final class App { - private App() { - } + private App() {} /** * Application entry point @@ -84,6 +83,5 @@ public final class App { } catch (IOException ex) { ex.printStackTrace(); } - } } 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 4b565cc8b..bbaf6bfea 100644 --- a/page-object/src/test/java/com/iluwatar/pageobject/AlbumListPageTest.java +++ b/page-object/src/test/java/com/iluwatar/pageobject/AlbumListPageTest.java @@ -26,14 +26,12 @@ package com.iluwatar.pageobject; import static org.junit.jupiter.api.Assertions.assertTrue; -import org.htmlunit.WebClient; import com.iluwatar.pageobject.pages.AlbumListPage; +import org.htmlunit.WebClient; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -/** - * Test Album Selection and Album Listing - */ +/** Test Album Selection and Album Listing */ class AlbumListPageTest { private final AlbumListPage albumListPage = new AlbumListPage(new WebClient()); @@ -49,5 +47,4 @@ class AlbumListPageTest { albumPage.navigateToPage(); assertTrue(albumPage.isAt()); } - } 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 7dbd1b91d..08dbd6d59 100644 --- a/page-object/src/test/java/com/iluwatar/pageobject/AlbumPageTest.java +++ b/page-object/src/test/java/com/iluwatar/pageobject/AlbumPageTest.java @@ -26,14 +26,12 @@ package com.iluwatar.pageobject; import static org.junit.jupiter.api.Assertions.assertTrue; -import org.htmlunit.WebClient; import com.iluwatar.pageobject.pages.AlbumPage; +import org.htmlunit.WebClient; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -/** - * Test Album Page Operations - */ +/** Test Album Page Operations */ class AlbumPageTest { private final AlbumPage albumPage = new AlbumPage(new WebClient()); @@ -46,16 +44,16 @@ class AlbumPageTest { @Test void testSaveAlbum() { - var albumPageAfterChanges = albumPage - .changeAlbumTitle("25") - .changeArtist("Adele Laurie Blue Adkins") - .changeAlbumYear(2015) - .changeAlbumRating("B") - .changeNumberOfSongs(20) - .saveChanges(); + var albumPageAfterChanges = + albumPage + .changeAlbumTitle("25") + .changeArtist("Adele Laurie Blue Adkins") + .changeAlbumYear(2015) + .changeAlbumRating("B") + .changeNumberOfSongs(20) + .saveChanges(); assertTrue(albumPageAfterChanges.isAt()); - } @Test @@ -64,5 +62,4 @@ class AlbumPageTest { albumListPage.navigateToPage(); assertTrue(albumListPage.isAt()); } - } 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 4e525b13e..8cf221769 100644 --- a/page-object/src/test/java/com/iluwatar/pageobject/LoginPageTest.java +++ b/page-object/src/test/java/com/iluwatar/pageobject/LoginPageTest.java @@ -26,14 +26,12 @@ package com.iluwatar.pageobject; import static org.junit.jupiter.api.Assertions.assertTrue; -import org.htmlunit.WebClient; import com.iluwatar.pageobject.pages.LoginPage; +import org.htmlunit.WebClient; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -/** - * Test Login Page Object - */ +/** Test Login Page Object */ class LoginPageTest { private final LoginPage loginPage = new LoginPage(new WebClient()); @@ -45,12 +43,8 @@ class LoginPageTest { @Test void testLogin() { - var albumListPage = loginPage - .enterUsername("admin") - .enterPassword("password") - .login(); + var albumListPage = loginPage.enterUsername("admin").enterPassword("password").login(); albumListPage.navigateToPage(); assertTrue(albumListPage.isAt()); } - } diff --git a/page-object/src/test/java/com/iluwatar/pageobject/pages/AlbumListPage.java b/page-object/src/test/java/com/iluwatar/pageobject/pages/AlbumListPage.java index f4d769187..bd59d9292 100644 --- a/page-object/src/test/java/com/iluwatar/pageobject/pages/AlbumListPage.java +++ b/page-object/src/test/java/com/iluwatar/pageobject/pages/AlbumListPage.java @@ -24,15 +24,13 @@ */ package com.iluwatar.pageobject.pages; +import java.io.IOException; +import java.util.List; import org.htmlunit.WebClient; import org.htmlunit.html.HtmlAnchor; import org.htmlunit.html.HtmlPage; -import java.io.IOException; -import java.util.List; -/** - * Page Object encapsulating the Album List page (album-list.html) - */ +/** Page Object encapsulating the Album List page (album-list.html) */ public class AlbumListPage extends Page { private static final String ALBUM_LIST_HTML_FILE = "album-list.html"; @@ -40,15 +38,11 @@ public class AlbumListPage extends Page { private HtmlPage page; - - /** - * Constructor - */ + /** Constructor */ public AlbumListPage(WebClient webClient) { super(webClient); } - /** * Navigates to the Album List Page * @@ -63,9 +57,7 @@ public class AlbumListPage extends Page { return this; } - /** - * {@inheritDoc} - */ + /** {@inheritDoc} */ @Override public boolean isAt() { return "Album List".equals(page.getTitleText()); @@ -92,6 +84,4 @@ public class AlbumListPage extends Page { } throw new IllegalArgumentException("No links with the album title: " + albumTitle); } - - } diff --git a/page-object/src/test/java/com/iluwatar/pageobject/pages/AlbumPage.java b/page-object/src/test/java/com/iluwatar/pageobject/pages/AlbumPage.java index 385bcf86c..e21898b8c 100644 --- a/page-object/src/test/java/com/iluwatar/pageobject/pages/AlbumPage.java +++ b/page-object/src/test/java/com/iluwatar/pageobject/pages/AlbumPage.java @@ -24,18 +24,15 @@ */ package com.iluwatar.pageobject.pages; +import java.io.IOException; import org.htmlunit.WebClient; import org.htmlunit.html.HtmlNumberInput; -import org.htmlunit.html.HtmlOption; import org.htmlunit.html.HtmlPage; import org.htmlunit.html.HtmlSelect; import org.htmlunit.html.HtmlSubmitInput; import org.htmlunit.html.HtmlTextInput; -import java.io.IOException; -/** - * Page Object encapsulating the Album Page (album-page.html) - */ +/** Page Object encapsulating the Album Page (album-page.html) */ public class AlbumPage extends Page { private static final String ALBUM_PAGE_HTML_FILE = "album-page.html"; @@ -43,15 +40,11 @@ public class AlbumPage extends Page { private HtmlPage page; - - /** - * Constructor - */ + /** Constructor */ public AlbumPage(WebClient webClient) { super(webClient); } - /** * Navigates to the album page * @@ -66,16 +59,12 @@ public class AlbumPage extends Page { return this; } - - /** - * {@inheritDoc} - */ + /** {@inheritDoc} */ @Override public boolean isAt() { return "Album Page".equals(page.getTitleText()); } - /** * Sets the album title input text field * @@ -88,7 +77,6 @@ public class AlbumPage extends Page { return this; } - /** * Sets the artist input text field * @@ -101,7 +89,6 @@ public class AlbumPage extends Page { return this; } - /** * Selects the select's option value based on the year value given * @@ -115,7 +102,6 @@ public class AlbumPage extends Page { return this; } - /** * Sets the album rating input text field * @@ -140,7 +126,6 @@ public class AlbumPage extends Page { return this; } - /** * Cancel changes made by clicking the cancel button * @@ -156,7 +141,6 @@ public class AlbumPage extends Page { return new AlbumListPage(webClient); } - /** * Saves changes made by clicking the save button * @@ -171,5 +155,4 @@ public class AlbumPage extends Page { } return this; } - } diff --git a/page-object/src/test/java/com/iluwatar/pageobject/pages/LoginPage.java b/page-object/src/test/java/com/iluwatar/pageobject/pages/LoginPage.java index 5d2ef992e..b113696c0 100644 --- a/page-object/src/test/java/com/iluwatar/pageobject/pages/LoginPage.java +++ b/page-object/src/test/java/com/iluwatar/pageobject/pages/LoginPage.java @@ -24,16 +24,14 @@ */ package com.iluwatar.pageobject.pages; +import java.io.IOException; import org.htmlunit.WebClient; import org.htmlunit.html.HtmlPage; import org.htmlunit.html.HtmlPasswordInput; import org.htmlunit.html.HtmlSubmitInput; import org.htmlunit.html.HtmlTextInput; -import java.io.IOException; -/** - * Page Object encapsulating the Login Page (login.html) - */ +/** Page Object encapsulating the Login Page (login.html) */ public class LoginPage extends Page { private static final String LOGIN_PAGE_HTML_FILE = "login.html"; @@ -64,15 +62,12 @@ public class LoginPage extends Page { return this; } - /** - * {@inheritDoc} - */ + /** {@inheritDoc} */ @Override public boolean isAt() { return "Login".equals(page.getTitleText()); } - /** * Enters the username into the username input text field * @@ -85,7 +80,6 @@ public class LoginPage extends Page { return this; } - /** * Enters the password into the password input password field * @@ -98,7 +92,6 @@ public class LoginPage extends Page { return this; } - /** * Clicking on the login button to 'login' * @@ -114,5 +107,4 @@ public class LoginPage extends Page { } return new AlbumListPage(webClient); } - } diff --git a/page-object/src/test/java/com/iluwatar/pageobject/pages/Page.java b/page-object/src/test/java/com/iluwatar/pageobject/pages/Page.java index 5331e03fe..499a15774 100644 --- a/page-object/src/test/java/com/iluwatar/pageobject/pages/Page.java +++ b/page-object/src/test/java/com/iluwatar/pageobject/pages/Page.java @@ -26,14 +26,10 @@ package com.iluwatar.pageobject.pages; import org.htmlunit.WebClient; -/** - * Encapsulation for a generic 'Page' - */ +/** Encapsulation for a generic 'Page' */ public abstract class Page { - /** - * Application Under Test path This directory location is where html web pages are located - */ + /** Application Under Test path This directory location is where html web pages are located */ public static final String AUT_PATH = "src/main/resources/sample-ui/"; protected final WebClient webClient; @@ -53,6 +49,4 @@ public abstract class Page { * @return true if so, otherwise false */ public abstract boolean isAt(); - - } diff --git a/page-object/test-automation/pom.xml b/page-object/test-automation/pom.xml index 81bdf93fb..ea5ac819f 100644 --- a/page-object/test-automation/pom.xml +++ b/page-object/test-automation/pom.xml @@ -34,9 +34,17 @@ test-automation + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter - junit-jupiter-api + junit-jupiter-engine test diff --git a/page-object/test-automation/src/main/java/com/iluwatar/pageobject/AlbumListPage.java b/page-object/test-automation/src/main/java/com/iluwatar/pageobject/AlbumListPage.java index fa58b9caf..9b78b0a8b 100644 --- a/page-object/test-automation/src/main/java/com/iluwatar/pageobject/AlbumListPage.java +++ b/page-object/test-automation/src/main/java/com/iluwatar/pageobject/AlbumListPage.java @@ -31,9 +31,7 @@ import org.htmlunit.WebClient; import org.htmlunit.html.HtmlAnchor; import org.htmlunit.html.HtmlPage; -/** - * Page Object encapsulating the Album List page (album-list.html) - */ +/** Page Object encapsulating the Album List page (album-list.html) */ @Slf4j public class AlbumListPage extends Page { private static final String ALBUM_LIST_HTML_FILE = "album-list.html"; @@ -41,15 +39,11 @@ public class AlbumListPage extends Page { private HtmlPage page; - - /** - * Constructor. - */ + /** Constructor. */ public AlbumListPage(WebClient webClient) { super(webClient); } - /** * Navigates to the Album List Page. * @@ -64,9 +58,7 @@ public class AlbumListPage extends Page { return this; } - /** - * {@inheritDoc} - */ + /** {@inheritDoc} */ @Override public boolean isAt() { return "Album List".equals(page.getTitleText()); @@ -93,6 +85,4 @@ public class AlbumListPage extends Page { } throw new IllegalArgumentException("No links with the album title: " + albumTitle); } - - } diff --git a/page-object/test-automation/src/main/java/com/iluwatar/pageobject/AlbumPage.java b/page-object/test-automation/src/main/java/com/iluwatar/pageobject/AlbumPage.java index 64d833551..6da0b05f3 100644 --- a/page-object/test-automation/src/main/java/com/iluwatar/pageobject/AlbumPage.java +++ b/page-object/test-automation/src/main/java/com/iluwatar/pageobject/AlbumPage.java @@ -33,9 +33,7 @@ import org.htmlunit.html.HtmlSelect; import org.htmlunit.html.HtmlSubmitInput; import org.htmlunit.html.HtmlTextInput; -/** - * Page Object encapsulating the Album Page (album-page.html) - */ +/** Page Object encapsulating the Album Page (album-page.html) */ @Slf4j public class AlbumPage extends Page { private static final String ALBUM_PAGE_HTML_FILE = "album-page.html"; @@ -43,15 +41,11 @@ public class AlbumPage extends Page { private HtmlPage page; - - /** - * Constructor. - */ + /** Constructor. */ public AlbumPage(WebClient webClient) { super(webClient); } - /** * Navigates to the album page. * @@ -66,16 +60,12 @@ public class AlbumPage extends Page { return this; } - - /** - * {@inheritDoc} - */ + /** {@inheritDoc} */ @Override public boolean isAt() { return "Album Page".equals(page.getTitleText()); } - /** * Sets the album title input text field. * @@ -88,7 +78,6 @@ public class AlbumPage extends Page { return this; } - /** * Sets the artist input text field. * @@ -101,7 +90,6 @@ public class AlbumPage extends Page { return this; } - /** * Selects the select's option value based on the year value given. * @@ -115,7 +103,6 @@ public class AlbumPage extends Page { return this; } - /** * Sets the album rating input text field. * @@ -140,7 +127,6 @@ public class AlbumPage extends Page { return this; } - /** * Cancel changes made by clicking the cancel button. * @@ -156,7 +142,6 @@ public class AlbumPage extends Page { return new AlbumListPage(webClient); } - /** * Saves changes made by clicking the save button. * @@ -171,5 +156,4 @@ public class AlbumPage extends Page { } return this; } - } diff --git a/page-object/test-automation/src/main/java/com/iluwatar/pageobject/LoginPage.java b/page-object/test-automation/src/main/java/com/iluwatar/pageobject/LoginPage.java index 2f48e0893..3d4f7c8f2 100644 --- a/page-object/test-automation/src/main/java/com/iluwatar/pageobject/LoginPage.java +++ b/page-object/test-automation/src/main/java/com/iluwatar/pageobject/LoginPage.java @@ -32,9 +32,7 @@ import org.htmlunit.html.HtmlPasswordInput; import org.htmlunit.html.HtmlSubmitInput; import org.htmlunit.html.HtmlTextInput; -/** - * Page Object encapsulating the Login Page (login.html) - */ +/** Page Object encapsulating the Login Page (login.html) */ @Slf4j public class LoginPage extends Page { private static final String LOGIN_PAGE_HTML_FILE = "login.html"; @@ -65,15 +63,12 @@ public class LoginPage extends Page { return this; } - /** - * {@inheritDoc} - */ + /** {@inheritDoc} */ @Override public boolean isAt() { return "Login".equals(page.getTitleText()); } - /** * Enters the username into the username input text field. * @@ -86,7 +81,6 @@ public class LoginPage extends Page { return this; } - /** * Enters the password into the password input password field. * @@ -99,7 +93,6 @@ public class LoginPage extends Page { return this; } - /** * Clicking on the login button to 'login'. * @@ -115,5 +108,4 @@ public class LoginPage extends Page { } return new AlbumListPage(webClient); } - } diff --git a/page-object/test-automation/src/main/java/com/iluwatar/pageobject/Page.java b/page-object/test-automation/src/main/java/com/iluwatar/pageobject/Page.java index 0a2186f43..cbc24bd6e 100644 --- a/page-object/test-automation/src/main/java/com/iluwatar/pageobject/Page.java +++ b/page-object/test-automation/src/main/java/com/iluwatar/pageobject/Page.java @@ -26,14 +26,10 @@ package com.iluwatar.pageobject; import org.htmlunit.WebClient; -/** - * Encapsulation for a generic 'Page'. - */ +/** Encapsulation for a generic 'Page'. */ public abstract class Page { - /** - * Application Under Test path This directory location is where html web pages are located. - */ + /** Application Under Test path This directory location is where html web pages are located. */ public static final String AUT_PATH = "../sample-application/src/main/resources/sample-ui/"; protected final WebClient webClient; @@ -53,6 +49,4 @@ public abstract class Page { * @return true if so, otherwise false */ public abstract boolean isAt(); - - } diff --git a/page-object/test-automation/src/test/java/com/iluwatar/pageobject/AlbumListPageTest.java b/page-object/test-automation/src/test/java/com/iluwatar/pageobject/AlbumListPageTest.java index ff6dd877d..1b710a37b 100644 --- a/page-object/test-automation/src/test/java/com/iluwatar/pageobject/AlbumListPageTest.java +++ b/page-object/test-automation/src/test/java/com/iluwatar/pageobject/AlbumListPageTest.java @@ -30,9 +30,7 @@ import org.htmlunit.WebClient; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -/** - * Test Album Selection and Album Listing - */ +/** Test Album Selection and Album Listing */ class AlbumListPageTest { private final AlbumListPage albumListPage = new AlbumListPage(new WebClient()); @@ -48,5 +46,4 @@ class AlbumListPageTest { albumPage.navigateToPage(); assertTrue(albumPage.isAt()); } - } diff --git a/page-object/test-automation/src/test/java/com/iluwatar/pageobject/AlbumPageTest.java b/page-object/test-automation/src/test/java/com/iluwatar/pageobject/AlbumPageTest.java index 830201c1c..85a9afe80 100644 --- a/page-object/test-automation/src/test/java/com/iluwatar/pageobject/AlbumPageTest.java +++ b/page-object/test-automation/src/test/java/com/iluwatar/pageobject/AlbumPageTest.java @@ -30,9 +30,7 @@ import org.htmlunit.WebClient; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -/** - * Test Album Page Operations - */ +/** Test Album Page Operations */ class AlbumPageTest { private final AlbumPage albumPage = new AlbumPage(new WebClient()); @@ -45,16 +43,16 @@ class AlbumPageTest { @Test void testSaveAlbum() { - var albumPageAfterChanges = albumPage - .changeAlbumTitle("25") - .changeArtist("Adele Laurie Blue Adkins") - .changeAlbumYear(2015) - .changeAlbumRating("B") - .changeNumberOfSongs(20) - .saveChanges(); + var albumPageAfterChanges = + albumPage + .changeAlbumTitle("25") + .changeArtist("Adele Laurie Blue Adkins") + .changeAlbumYear(2015) + .changeAlbumRating("B") + .changeNumberOfSongs(20) + .saveChanges(); assertTrue(albumPageAfterChanges.isAt()); - } @Test @@ -63,5 +61,4 @@ class AlbumPageTest { albumListPage.navigateToPage(); assertTrue(albumListPage.isAt()); } - } diff --git a/page-object/test-automation/src/test/java/com/iluwatar/pageobject/LoginPageTest.java b/page-object/test-automation/src/test/java/com/iluwatar/pageobject/LoginPageTest.java index ed6232030..660487002 100644 --- a/page-object/test-automation/src/test/java/com/iluwatar/pageobject/LoginPageTest.java +++ b/page-object/test-automation/src/test/java/com/iluwatar/pageobject/LoginPageTest.java @@ -30,9 +30,7 @@ import org.htmlunit.WebClient; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -/** - * Test Login Page Object - */ +/** Test Login Page Object */ class LoginPageTest { private final LoginPage loginPage = new LoginPage(new WebClient()); @@ -44,12 +42,8 @@ class LoginPageTest { @Test void testLogin() { - var albumListPage = loginPage - .enterUsername("admin") - .enterPassword("password") - .login(); + var albumListPage = loginPage.enterUsername("admin").enterPassword("password").login(); albumListPage.navigateToPage(); assertTrue(albumListPage.isAt()); } - } diff --git a/parameter-object/pom.xml b/parameter-object/pom.xml index a9cfec473..9906e880a 100644 --- a/parameter-object/pom.xml +++ b/parameter-object/pom.xml @@ -34,6 +34,14 @@ parameter-object + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/parameter-object/src/main/java/com/iluwatar/parameter/object/App.java b/parameter-object/src/main/java/com/iluwatar/parameter/object/App.java index 8e02434a7..d4d1e45ab 100644 --- a/parameter-object/src/main/java/com/iluwatar/parameter/object/App.java +++ b/parameter-object/src/main/java/com/iluwatar/parameter/object/App.java @@ -28,19 +28,18 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * The syntax of Java language doesn’t allow you to declare a method with a predefined value - * for a parameter. Probably the best option to achieve default method parameters in Java is - * by using the method overloading. Method overloading allows you to declare several methods - * with the same name but with a different number of parameters. But the main problem with - * method overloading as a solution for default parameter values reveals itself when a method - * accepts multiple parameters. Creating an overloaded method for each possible combination of - * parameters might be cumbersome. To deal with this issue, the Parameter Object pattern is used. - * The Parameter Object is simply a wrapper object for all parameters of a method. - * It is nothing more than just a regular POJO. The advantage of the Parameter Object over a - * regular method parameter list is the fact that class fields can have default values. - * Once the wrapper class is created for the method parameter list, a corresponding builder class - * is also created. Usually it's an inner static class. The final step is to use the builder - * to construct a new parameter object. For those parameters that are skipped, + * The syntax of Java language doesn’t allow you to declare a method with a predefined value for a + * parameter. Probably the best option to achieve default method parameters in Java is by using the + * method overloading. Method overloading allows you to declare several methods with the same name + * but with a different number of parameters. But the main problem with method overloading as a + * solution for default parameter values reveals itself when a method accepts multiple parameters. + * Creating an overloaded method for each possible combination of parameters might be cumbersome. To + * deal with this issue, the Parameter Object pattern is used. The Parameter Object is simply a + * wrapper object for all parameters of a method. It is nothing more than just a regular POJO. The + * advantage of the Parameter Object over a regular method parameter list is the fact that class + * fields can have default values. Once the wrapper class is created for the method parameter list, + * a corresponding builder class is also created. Usually it's an inner static class. The final step + * is to use the builder to construct a new parameter object. For those parameters that are skipped, * their default values are going to be used. */ public class App { @@ -53,10 +52,8 @@ public class App { * @param args command line args */ public static void main(String[] args) { - ParameterObject params = ParameterObject.newBuilder() - .withType("sneakers") - .sortBy("brand") - .build(); + ParameterObject params = + ParameterObject.newBuilder().withType("sneakers").sortBy("brand").build(); LOGGER.info(params.toString()); LOGGER.info(new SearchService().search(params)); } diff --git a/parameter-object/src/main/java/com/iluwatar/parameter/object/ParameterObject.java b/parameter-object/src/main/java/com/iluwatar/parameter/object/ParameterObject.java index 154733202..d211d5089 100644 --- a/parameter-object/src/main/java/com/iluwatar/parameter/object/ParameterObject.java +++ b/parameter-object/src/main/java/com/iluwatar/parameter/object/ParameterObject.java @@ -27,30 +27,24 @@ package com.iluwatar.parameter.object; import lombok.Getter; import lombok.Setter; -/** - * ParameterObject. - */ +/** ParameterObject. */ @Getter @Setter public class ParameterObject { - /** - * Default values are defined here. - */ + /** Default values are defined here. */ public static final String DEFAULT_SORT_BY = "price"; + public static final SortOrder DEFAULT_SORT_ORDER = SortOrder.ASC; private String type; - /** - * Default values are assigned here. - */ + /** Default values are assigned here. */ private String sortBy = DEFAULT_SORT_BY; + private SortOrder sortOrder = DEFAULT_SORT_ORDER; - /** - * Overriding default values on object creation only when builder object has a valid value. - */ + /** Overriding default values on object creation only when builder object has a valid value. */ private ParameterObject(Builder builder) { setType(builder.type); setSortBy(builder.sortBy != null && !builder.sortBy.isBlank() ? builder.sortBy : sortBy); @@ -63,21 +57,18 @@ public class ParameterObject { @Override public String toString() { - return String.format("ParameterObject[type='%s', sortBy='%s', sortOrder='%s']", - type, sortBy, sortOrder); + return String.format( + "ParameterObject[type='%s', sortBy='%s', sortOrder='%s']", type, sortBy, sortOrder); } - /** - * Builder for ParameterObject. - */ + /** Builder for ParameterObject. */ public static final class Builder { private String type; private String sortBy; private SortOrder sortOrder; - private Builder() { - } + private Builder() {} public Builder withType(String type) { this.type = type; diff --git a/parameter-object/src/main/java/com/iluwatar/parameter/object/SearchService.java b/parameter-object/src/main/java/com/iluwatar/parameter/object/SearchService.java index e356c2f5b..9adf9fbfd 100644 --- a/parameter-object/src/main/java/com/iluwatar/parameter/object/SearchService.java +++ b/parameter-object/src/main/java/com/iluwatar/parameter/object/SearchService.java @@ -24,17 +24,15 @@ */ package com.iluwatar.parameter.object; -/** - * SearchService to demonstrate parameter object pattern. - */ +/** SearchService to demonstrate parameter object pattern. */ public class SearchService { /** - * Below two methods of name `search` is overloaded so that we can send a default value for - * one of the criteria and call the final api. A default SortOrder is sent in the first method - * and a default SortBy is sent in the second method. So two separate method definitions are - * needed for having default values for one argument in each case. Hence, multiple overloaded - * methods are needed as the number of argument increases. + * Below two methods of name `search` is overloaded so that we can send a default value for one of + * the criteria and call the final api. A default SortOrder is sent in the first method and a + * default SortBy is sent in the second method. So two separate method definitions are needed for + * having default values for one argument in each case. Hence, multiple overloaded methods are + * needed as the number of argument increases. */ public String search(String type, String sortBy) { return getQuerySummary(type, sortBy, SortOrder.ASC); @@ -44,21 +42,19 @@ public class SearchService { return getQuerySummary(type, "price", sortOrder); } - /** - * The need for multiple method definitions can be avoided by the Parameter Object pattern. - * Below is the example where only one method is required and all the logic for having default - * values are abstracted into the Parameter Object at the time of object creation. + * The need for multiple method definitions can be avoided by the Parameter Object pattern. Below + * is the example where only one method is required and all the logic for having default values + * are abstracted into the Parameter Object at the time of object creation. */ public String search(ParameterObject parameterObject) { - return getQuerySummary(parameterObject.getType(), parameterObject.getSortBy(), - parameterObject.getSortOrder()); + return getQuerySummary( + parameterObject.getType(), parameterObject.getSortBy(), parameterObject.getSortOrder()); } private String getQuerySummary(String type, String sortBy, SortOrder sortOrder) { - return String.format("Requesting shoes of type \"%s\" sorted by \"%s\" in \"%sending\" order..", - type, - sortBy, - sortOrder.getValue()); + return String.format( + "Requesting shoes of type \"%s\" sorted by \"%s\" in \"%sending\" order..", + type, sortBy, sortOrder.getValue()); } } diff --git a/parameter-object/src/main/java/com/iluwatar/parameter/object/SortOrder.java b/parameter-object/src/main/java/com/iluwatar/parameter/object/SortOrder.java index faae9e581..68a7b701f 100644 --- a/parameter-object/src/main/java/com/iluwatar/parameter/object/SortOrder.java +++ b/parameter-object/src/main/java/com/iluwatar/parameter/object/SortOrder.java @@ -26,15 +26,12 @@ package com.iluwatar.parameter.object; import lombok.Getter; -/** - * enum for sort order types. - */ +/** enum for sort order types. */ public enum SortOrder { ASC("asc"), DESC("desc"); - @Getter - private String value; + @Getter private String value; SortOrder(String value) { this.value = value; diff --git a/parameter-object/src/test/java/com/iluwatar/parameter/object/AppTest.java b/parameter-object/src/test/java/com/iluwatar/parameter/object/AppTest.java index d51b71cd8..c28e77fed 100644 --- a/parameter-object/src/test/java/com/iluwatar/parameter/object/AppTest.java +++ b/parameter-object/src/test/java/com/iluwatar/parameter/object/AppTest.java @@ -28,12 +28,10 @@ import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import org.junit.jupiter.api.Test; -/** - * Application test - */ +/** Application test */ class AppTest { @Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/parameter-object/src/test/java/com/iluwatar/parameter/object/ParameterObjectTest.java b/parameter-object/src/test/java/com/iluwatar/parameter/object/ParameterObjectTest.java index 93b1aff5e..0db0c0d36 100644 --- a/parameter-object/src/test/java/com/iluwatar/parameter/object/ParameterObjectTest.java +++ b/parameter-object/src/test/java/com/iluwatar/parameter/object/ParameterObjectTest.java @@ -24,41 +24,38 @@ */ package com.iluwatar.parameter.object; +import static org.junit.jupiter.api.Assertions.assertEquals; + import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import static org.junit.jupiter.api.Assertions.assertEquals; - class ParameterObjectTest { private static final Logger LOGGER = LoggerFactory.getLogger(ParameterObjectTest.class); @Test void testForDefaultSortBy() { - //Creating parameter object with default value for SortBy set - ParameterObject params = ParameterObject.newBuilder() - .withType("sneakers") - .sortOrder(SortOrder.DESC) - .build(); + // Creating parameter object with default value for SortBy set + ParameterObject params = + ParameterObject.newBuilder().withType("sneakers").sortOrder(SortOrder.DESC).build(); - assertEquals(ParameterObject.DEFAULT_SORT_BY, params.getSortBy(), - "Default SortBy is not set."); - LOGGER.info("{} Default parameter value is set during object creation as no value is passed." - , "SortBy"); + assertEquals(ParameterObject.DEFAULT_SORT_BY, params.getSortBy(), "Default SortBy is not set."); + LOGGER.info( + "{} Default parameter value is set during object creation as no value is passed.", + "SortBy"); } @Test void testForDefaultSortOrder() { - //Creating parameter object with default value for SortOrder set - ParameterObject params = ParameterObject.newBuilder() - .withType("sneakers") - .sortBy("brand") - .build(); + // Creating parameter object with default value for SortOrder set + ParameterObject params = + ParameterObject.newBuilder().withType("sneakers").sortBy("brand").build(); - assertEquals(ParameterObject.DEFAULT_SORT_ORDER, params.getSortOrder(), - "Default SortOrder is not set."); - LOGGER.info("{} Default parameter value is set during object creation as no value is passed." - , "SortOrder"); + assertEquals( + ParameterObject.DEFAULT_SORT_ORDER, params.getSortOrder(), "Default SortOrder is not set."); + LOGGER.info( + "{} Default parameter value is set during object creation as no value is passed.", + "SortOrder"); } } diff --git a/parameter-object/src/test/java/com/iluwatar/parameter/object/SearchServiceTest.java b/parameter-object/src/test/java/com/iluwatar/parameter/object/SearchServiceTest.java index 32e669832..ce7a0afcc 100644 --- a/parameter-object/src/test/java/com/iluwatar/parameter/object/SearchServiceTest.java +++ b/parameter-object/src/test/java/com/iluwatar/parameter/object/SearchServiceTest.java @@ -24,13 +24,13 @@ */ package com.iluwatar.parameter.object; +import static org.junit.jupiter.api.Assertions.assertEquals; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import static org.junit.jupiter.api.Assertions.assertEquals; - class SearchServiceTest { private static final Logger LOGGER = LoggerFactory.getLogger(SearchServiceTest.class); private ParameterObject parameterObject; @@ -38,25 +38,25 @@ class SearchServiceTest { @BeforeEach void setUp() { - //Creating parameter object with default values set - parameterObject = ParameterObject.newBuilder() - .withType("sneakers") - .build(); + // Creating parameter object with default values set + parameterObject = ParameterObject.newBuilder().withType("sneakers").build(); searchService = new SearchService(); } - /** - * Testing parameter object against the overloaded method to verify if the behaviour is same. - */ + /** Testing parameter object against the overloaded method to verify if the behaviour is same. */ @Test void testDefaultParametersMatch() { - assertEquals(searchService.search(parameterObject), searchService.search("sneakers", - SortOrder.ASC), "Default Parameter values do not not match."); + assertEquals( + searchService.search(parameterObject), + searchService.search("sneakers", SortOrder.ASC), + "Default Parameter values do not not match."); LOGGER.info("SortBy Default parameter value matches."); - assertEquals(searchService.search(parameterObject), searchService.search("sneakers", - "price"), "Default Parameter values do not not match."); + assertEquals( + searchService.search(parameterObject), + searchService.search("sneakers", "price"), + "Default Parameter values do not not match."); LOGGER.info("SortOrder Default parameter value matches."); LOGGER.info("testDefaultParametersMatch executed successfully without errors."); diff --git a/partial-response/pom.xml b/partial-response/pom.xml index 20c136598..7b10001ca 100644 --- a/partial-response/pom.xml +++ b/partial-response/pom.xml @@ -34,9 +34,18 @@ 4.0.0 partial-response + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.mockito mockito-junit-jupiter + 5.16.1 test diff --git a/partial-response/src/main/java/com/iluwatar/partialresponse/App.java b/partial-response/src/main/java/com/iluwatar/partialresponse/App.java index 2a729f889..a9f1be453 100644 --- a/partial-response/src/main/java/com/iluwatar/partialresponse/App.java +++ b/partial-response/src/main/java/com/iluwatar/partialresponse/App.java @@ -34,7 +34,6 @@ import lombok.extern.slf4j.Slf4j; * *

{@link VideoResource} act as server to serve video information. */ - @Slf4j public class App { @@ -44,17 +43,22 @@ public class App { * @param args program argument. */ public static void main(String[] args) throws Exception { - var videos = Map.of( - 1, new Video(1, "Avatar", 178, "epic science fiction film", - "James Cameron", "English"), - 2, new Video(2, "Godzilla Resurgence", 120, "Action & drama movie|", - "Hideaki Anno", "Japanese"), - 3, new Video(3, "Interstellar", 169, "Adventure & Sci-Fi", - "Christopher Nolan", "English") - ); + var videos = + Map.of( + 1, new Video(1, "Avatar", 178, "epic science fiction film", "James Cameron", "English"), + 2, + new Video( + 2, + "Godzilla Resurgence", + 120, + "Action & drama movie|", + "Hideaki Anno", + "Japanese"), + 3, + new Video( + 3, "Interstellar", 169, "Adventure & Sci-Fi", "Christopher Nolan", "English")); var videoResource = new VideoResource(new FieldJsonMapper(), videos); - LOGGER.info("Retrieving full response from server:-"); LOGGER.info("Get all video information:"); var videoDetails = videoResource.getDetails(1); diff --git a/partial-response/src/main/java/com/iluwatar/partialresponse/FieldJsonMapper.java b/partial-response/src/main/java/com/iluwatar/partialresponse/FieldJsonMapper.java index 62ce17320..2e4109fdf 100644 --- a/partial-response/src/main/java/com/iluwatar/partialresponse/FieldJsonMapper.java +++ b/partial-response/src/main/java/com/iluwatar/partialresponse/FieldJsonMapper.java @@ -27,15 +27,13 @@ package com.iluwatar.partialresponse; import java.lang.reflect.Field; import java.util.StringJoiner; -/** - * Map a video to json. - */ +/** Map a video to json. */ public class FieldJsonMapper { /** * Gets json of required fields from video. * - * @param video object containing video information + * @param video object containing video information * @param fields fields information to get * @return json of required fields from video */ diff --git a/partial-response/src/main/java/com/iluwatar/partialresponse/Video.java b/partial-response/src/main/java/com/iluwatar/partialresponse/Video.java index c0bcac7b2..36ce69d26 100644 --- a/partial-response/src/main/java/com/iluwatar/partialresponse/Video.java +++ b/partial-response/src/main/java/com/iluwatar/partialresponse/Video.java @@ -25,11 +25,16 @@ package com.iluwatar.partialresponse; /** - * {@link Video} is an entity to serve from server.It contains all video related information. - * Video is a record class. + * {@link Video} is an entity to serve from server.It contains all video related information. Video + * is a record class. */ - -public record Video(Integer id, String title, Integer length, String description, String director, String language) { +public record Video( + Integer id, + String title, + Integer length, + String description, + String director, + String language) { /** * ToString. * @@ -38,12 +43,24 @@ public record Video(Integer id, String title, Integer length, String description @Override public String toString() { return "{" - + "\"id\": " + id + "," - + "\"title\": \"" + title + "\"," - + "\"length\": " + length + "," - + "\"description\": \"" + description + "\"," - + "\"director\": \"" + director + "\"," - + "\"language\": \"" + language + "\"" - + "}"; + + "\"id\": " + + id + + "," + + "\"title\": \"" + + title + + "\"," + + "\"length\": " + + length + + "," + + "\"description\": \"" + + description + + "\"," + + "\"director\": \"" + + director + + "\"," + + "\"language\": \"" + + language + + "\"" + + "}"; } } diff --git a/partial-response/src/main/java/com/iluwatar/partialresponse/VideoResource.java b/partial-response/src/main/java/com/iluwatar/partialresponse/VideoResource.java index 84dd35a3e..6522f143d 100644 --- a/partial-response/src/main/java/com/iluwatar/partialresponse/VideoResource.java +++ b/partial-response/src/main/java/com/iluwatar/partialresponse/VideoResource.java @@ -27,18 +27,17 @@ package com.iluwatar.partialresponse; import java.util.Map; /** - * The resource record class which serves video information. This class act as server in the demo. Which - * has all video details. + * The resource record class which serves video information. This class act as server in the demo. + * Which has all video details. * * @param fieldJsonMapper map object to json. - * @param videos initialize resource with existing videos. Act as database. + * @param videos initialize resource with existing videos. Act as database. */ - public record VideoResource(FieldJsonMapper fieldJsonMapper, Map videos) { /** * Get Details. * - * @param id video id + * @param id video id * @param fields fields to get information about * @return full response if no fields specified else partial response for given field. */ diff --git a/partial-response/src/test/java/com/iluwatar/partialresponse/AppTest.java b/partial-response/src/test/java/com/iluwatar/partialresponse/AppTest.java index 16f5fff29..6d712b820 100644 --- a/partial-response/src/test/java/com/iluwatar/partialresponse/AppTest.java +++ b/partial-response/src/test/java/com/iluwatar/partialresponse/AppTest.java @@ -24,17 +24,14 @@ */ package com.iluwatar.partialresponse; -import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; -/** - * Application test - */ +/** Application test */ class AppTest { @Test void shouldExecuteApplicationWithoutException() { - Assertions.assertDoesNotThrow(() -> App.main(new String[]{})); + Assertions.assertDoesNotThrow(() -> App.main(new String[] {})); } - -} \ No newline at end of file +} diff --git a/partial-response/src/test/java/com/iluwatar/partialresponse/FieldJsonMapperTest.java b/partial-response/src/test/java/com/iluwatar/partialresponse/FieldJsonMapperTest.java index eb8677130..59e075e6b 100644 --- a/partial-response/src/test/java/com/iluwatar/partialresponse/FieldJsonMapperTest.java +++ b/partial-response/src/test/java/com/iluwatar/partialresponse/FieldJsonMapperTest.java @@ -24,13 +24,11 @@ */ package com.iluwatar.partialresponse; -import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; -/** - * tests {@link FieldJsonMapper}. - */ +/** tests {@link FieldJsonMapper}. */ class FieldJsonMapperTest { private static FieldJsonMapper mapper; @@ -41,15 +39,14 @@ class FieldJsonMapperTest { @Test void shouldReturnJsonForSpecifiedFieldsInVideo() throws Exception { - var fields = new String[]{"id", "title", "length"}; - var video = new Video( - 2, "Godzilla Resurgence", 120, - "Action & drama movie|", "Hideaki Anno", "Japanese" - ); + var fields = new String[] {"id", "title", "length"}; + var video = + new Video( + 2, "Godzilla Resurgence", 120, "Action & drama movie|", "Hideaki Anno", "Japanese"); var jsonFieldResponse = mapper.toJson(video, fields); var expectedDetails = "{\"id\": 2,\"title\": \"Godzilla Resurgence\",\"length\": 120}"; Assertions.assertEquals(expectedDetails, jsonFieldResponse); } -} \ No newline at end of file +} diff --git a/partial-response/src/test/java/com/iluwatar/partialresponse/VideoResourceTest.java b/partial-response/src/test/java/com/iluwatar/partialresponse/VideoResourceTest.java index 1b6593d1a..630f68c02 100644 --- a/partial-response/src/test/java/com/iluwatar/partialresponse/VideoResourceTest.java +++ b/partial-response/src/test/java/com/iluwatar/partialresponse/VideoResourceTest.java @@ -36,25 +36,29 @@ import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; -/** - * tests {@link VideoResource}. - */ +/** tests {@link VideoResource}. */ @ExtendWith(MockitoExtension.class) class VideoResourceTest { - @Mock - private static FieldJsonMapper fieldJsonMapper; + @Mock private static FieldJsonMapper fieldJsonMapper; private static VideoResource resource; @BeforeEach void setUp() { - var videos = Map.of( - 1, new Video(1, "Avatar", 178, "epic science fiction film", - "James Cameron", "English"), - 2, new Video(2, "Godzilla Resurgence", 120, "Action & drama movie|", - "Hideaki Anno", "Japanese"), - 3, new Video(3, "Interstellar", 169, "Adventure & Sci-Fi", - "Christopher Nolan", "English")); + var videos = + Map.of( + 1, new Video(1, "Avatar", 178, "epic science fiction film", "James Cameron", "English"), + 2, + new Video( + 2, + "Godzilla Resurgence", + 120, + "Action & drama movie|", + "Hideaki Anno", + "Japanese"), + 3, + new Video( + 3, "Interstellar", 169, "Adventure & Sci-Fi", "Christopher Nolan", "English")); resource = new VideoResource(fieldJsonMapper, videos); } @@ -62,14 +66,15 @@ class VideoResourceTest { void shouldGiveVideoDetailsById() throws Exception { var actualDetails = resource.getDetails(1); - var expectedDetails = "{\"id\": 1,\"title\": \"Avatar\",\"length\": 178,\"description\": " - + "\"epic science fiction film\",\"director\": \"James Cameron\",\"language\": \"English\"}"; + var expectedDetails = + "{\"id\": 1,\"title\": \"Avatar\",\"length\": 178,\"description\": " + + "\"epic science fiction film\",\"director\": \"James Cameron\",\"language\": \"English\"}"; Assertions.assertEquals(expectedDetails, actualDetails); } @Test void shouldGiveSpecifiedFieldsInformationOfVideo() throws Exception { - var fields = new String[]{"id", "title", "length"}; + var fields = new String[] {"id", "title", "length"}; var expectedDetails = "{\"id\": 1,\"title\": \"Avatar\",\"length\": 178}"; Mockito.when(fieldJsonMapper.toJson(any(Video.class), eq(fields))).thenReturn(expectedDetails); @@ -81,10 +86,11 @@ class VideoResourceTest { @Test void shouldAllSpecifiedFieldsInformationOfVideo() throws Exception { - var fields = new String[]{"id", "title", "length", "description", "director", "language"}; + var fields = new String[] {"id", "title", "length", "description", "director", "language"}; - var expectedDetails = "{\"id\": 1,\"title\": \"Avatar\",\"length\": 178,\"description\": " - + "\"epic science fiction film\",\"director\": \"James Cameron\",\"language\": \"English\"}"; + var expectedDetails = + "{\"id\": 1,\"title\": \"Avatar\",\"length\": 178,\"description\": " + + "\"epic science fiction film\",\"director\": \"James Cameron\",\"language\": \"English\"}"; Mockito.when(fieldJsonMapper.toJson(any(Video.class), eq(fields))).thenReturn(expectedDetails); var actualFieldsDetails = resource.getDetails(1, fields); diff --git a/pipeline/pom.xml b/pipeline/pom.xml index a45118dd8..f28889c47 100644 --- a/pipeline/pom.xml +++ b/pipeline/pom.xml @@ -34,6 +34,14 @@ pipeline + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/pipeline/src/main/java/com/iluwatar/pipeline/App.java b/pipeline/src/main/java/com/iluwatar/pipeline/App.java index 2f0892e70..9f82a6e9e 100644 --- a/pipeline/src/main/java/com/iluwatar/pipeline/App.java +++ b/pipeline/src/main/java/com/iluwatar/pipeline/App.java @@ -45,28 +45,29 @@ public class App { */ public static void main(String[] args) { /* - Suppose we wanted to pass through a String to a series of filtering stages and convert it - as a char array on the last stage. + Suppose we wanted to pass through a String to a series of filtering stages and convert it + as a char array on the last stage. - - Stage handler 1 (pipe): Removing the alphabets, accepts a String input and returns the - processed String output. This will be used by the next handler as its input. + - Stage handler 1 (pipe): Removing the alphabets, accepts a String input and returns the + processed String output. This will be used by the next handler as its input. - - Stage handler 2 (pipe): Removing the digits, accepts a String input and returns the - processed String output. This shall also be used by the last handler we have. + - Stage handler 2 (pipe): Removing the digits, accepts a String input and returns the + processed String output. This shall also be used by the last handler we have. - - Stage handler 3 (pipe): Converting the String input to a char array handler. We would - be returning a different type in here since that is what's specified by the requirement. - This means that at any stages along the pipeline, the handler can return any type of data - as long as it fulfills the requirements for the next handler's input. + - Stage handler 3 (pipe): Converting the String input to a char array handler. We would + be returning a different type in here since that is what's specified by the requirement. + This means that at any stages along the pipeline, the handler can return any type of data + as long as it fulfills the requirements for the next handler's input. - Suppose we wanted to add another handler after ConvertToCharArrayHandler. That handler - then is expected to receive an input of char[] array since that is the type being returned - by the previous handler, ConvertToCharArrayHandler. - */ + Suppose we wanted to add another handler after ConvertToCharArrayHandler. That handler + then is expected to receive an input of char[] array since that is the type being returned + by the previous handler, ConvertToCharArrayHandler. + */ LOGGER.info("Creating pipeline"); - var filters = new Pipeline<>(new RemoveAlphabetsHandler()) - .addHandler(new RemoveDigitsHandler()) - .addHandler(new ConvertToCharArrayHandler()); + var filters = + new Pipeline<>(new RemoveAlphabetsHandler()) + .addHandler(new RemoveDigitsHandler()) + .addHandler(new ConvertToCharArrayHandler()); var input = "GoYankees123!"; LOGGER.info("Executing pipeline with input: {}", input); var output = filters.execute(input); diff --git a/pipeline/src/main/java/com/iluwatar/pipeline/ConvertToCharArrayHandler.java b/pipeline/src/main/java/com/iluwatar/pipeline/ConvertToCharArrayHandler.java index 24393333f..f7edde565 100644 --- a/pipeline/src/main/java/com/iluwatar/pipeline/ConvertToCharArrayHandler.java +++ b/pipeline/src/main/java/com/iluwatar/pipeline/ConvertToCharArrayHandler.java @@ -28,9 +28,7 @@ import java.util.Arrays; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -/** - * Stage handler that converts an input String to its char[] array counterpart. - */ +/** Stage handler that converts an input String to its char[] array counterpart. */ class ConvertToCharArrayHandler implements Handler { private static final Logger LOGGER = LoggerFactory.getLogger(ConvertToCharArrayHandler.class); @@ -40,9 +38,9 @@ class ConvertToCharArrayHandler implements Handler { var characters = input.toCharArray(); var string = Arrays.toString(characters); LOGGER.info( - String.format("Current handler: %s, input is %s of type %s, output is %s, of type %s", - ConvertToCharArrayHandler.class, input, String.class, string, Character[].class) - ); + String.format( + "Current handler: %s, input is %s of type %s, output is %s, of type %s", + ConvertToCharArrayHandler.class, input, String.class, string, Character[].class)); return characters; } diff --git a/pipeline/src/main/java/com/iluwatar/pipeline/Handler.java b/pipeline/src/main/java/com/iluwatar/pipeline/Handler.java index 1e72f863c..a27e0592c 100644 --- a/pipeline/src/main/java/com/iluwatar/pipeline/Handler.java +++ b/pipeline/src/main/java/com/iluwatar/pipeline/Handler.java @@ -33,4 +33,4 @@ package com.iluwatar.pipeline; */ interface Handler { O process(I input); -} \ No newline at end of file +} diff --git a/pipeline/src/main/java/com/iluwatar/pipeline/Pipeline.java b/pipeline/src/main/java/com/iluwatar/pipeline/Pipeline.java index 6c030e513..b7a619692 100644 --- a/pipeline/src/main/java/com/iluwatar/pipeline/Pipeline.java +++ b/pipeline/src/main/java/com/iluwatar/pipeline/Pipeline.java @@ -46,4 +46,4 @@ class Pipeline { O execute(I input) { return currentHandler.process(input); } -} \ No newline at end of file +} diff --git a/pipeline/src/main/java/com/iluwatar/pipeline/RemoveAlphabetsHandler.java b/pipeline/src/main/java/com/iluwatar/pipeline/RemoveAlphabetsHandler.java index 85a23e690..3bf01bf8a 100644 --- a/pipeline/src/main/java/com/iluwatar/pipeline/RemoveAlphabetsHandler.java +++ b/pipeline/src/main/java/com/iluwatar/pipeline/RemoveAlphabetsHandler.java @@ -40,7 +40,8 @@ class RemoveAlphabetsHandler implements Handler { public String process(String input) { var inputWithoutAlphabets = new StringBuilder(); var isAlphabetic = (IntPredicate) Character::isAlphabetic; - input.chars() + input + .chars() .filter(isAlphabetic.negate()) .mapToObj(x -> (char) x) .forEachOrdered(inputWithoutAlphabets::append); @@ -49,11 +50,12 @@ class RemoveAlphabetsHandler implements Handler { LOGGER.info( String.format( "Current handler: %s, input is %s of type %s, output is %s, of type %s", - RemoveAlphabetsHandler.class, input, - String.class, inputWithoutAlphabetsStr, String.class - ) - ); + RemoveAlphabetsHandler.class, + input, + String.class, + inputWithoutAlphabetsStr, + String.class)); return inputWithoutAlphabetsStr; } -} \ No newline at end of file +} diff --git a/pipeline/src/main/java/com/iluwatar/pipeline/RemoveDigitsHandler.java b/pipeline/src/main/java/com/iluwatar/pipeline/RemoveDigitsHandler.java index 75e7a460e..e84b1693a 100644 --- a/pipeline/src/main/java/com/iluwatar/pipeline/RemoveDigitsHandler.java +++ b/pipeline/src/main/java/com/iluwatar/pipeline/RemoveDigitsHandler.java @@ -40,7 +40,8 @@ class RemoveDigitsHandler implements Handler { public String process(String input) { var inputWithoutDigits = new StringBuilder(); var isDigit = (IntPredicate) Character::isDigit; - input.chars() + input + .chars() .filter(isDigit.negate()) .mapToObj(x -> (char) x) .forEachOrdered(inputWithoutDigits::append); @@ -49,10 +50,8 @@ class RemoveDigitsHandler implements Handler { LOGGER.info( String.format( "Current handler: %s, input is %s of type %s, output is %s, of type %s", - RemoveDigitsHandler.class, input, String.class, inputWithoutDigitsStr, String.class - ) - ); + RemoveDigitsHandler.class, input, String.class, inputWithoutDigitsStr, String.class)); return inputWithoutDigitsStr; } -} \ No newline at end of file +} diff --git a/pipeline/src/test/java/com/iluwatar/pipeline/AppTest.java b/pipeline/src/test/java/com/iluwatar/pipeline/AppTest.java index 2a49dbe0b..5f1c0d231 100644 --- a/pipeline/src/test/java/com/iluwatar/pipeline/AppTest.java +++ b/pipeline/src/test/java/com/iluwatar/pipeline/AppTest.java @@ -24,17 +24,15 @@ */ package com.iluwatar.pipeline; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -/** - * Application Test - */ +import org.junit.jupiter.api.Test; + +/** Application Test */ class AppTest { @Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/pipeline/src/test/java/com/iluwatar/pipeline/PipelineTest.java b/pipeline/src/test/java/com/iluwatar/pipeline/PipelineTest.java index 677c8eb50..d26069dc7 100644 --- a/pipeline/src/test/java/com/iluwatar/pipeline/PipelineTest.java +++ b/pipeline/src/test/java/com/iluwatar/pipeline/PipelineTest.java @@ -28,20 +28,17 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals; import org.junit.jupiter.api.Test; -/** - * Test for {@link Pipeline} - */ +/** Test for {@link Pipeline} */ class PipelineTest { @Test void testAddHandlersToPipeline() { - var filters = new Pipeline<>(new RemoveAlphabetsHandler()) - .addHandler(new RemoveDigitsHandler()) - .addHandler(new ConvertToCharArrayHandler()); + var filters = + new Pipeline<>(new RemoveAlphabetsHandler()) + .addHandler(new RemoveDigitsHandler()) + .addHandler(new ConvertToCharArrayHandler()); assertArrayEquals( - new char[]{'#', '!', '(', '&', '%', '#', '!'}, - filters.execute("#H!E(L&L0O%THE3R#34E!") - ); + new char[] {'#', '!', '(', '&', '%', '#', '!'}, filters.execute("#H!E(L&L0O%THE3R#34E!")); } } diff --git a/poison-pill/pom.xml b/poison-pill/pom.xml index 803c9fd75..74f4ce8a9 100644 --- a/poison-pill/pom.xml +++ b/poison-pill/pom.xml @@ -34,6 +34,14 @@ poison-pill + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/poison-pill/src/main/java/com/iluwatar/poison/pill/App.java b/poison-pill/src/main/java/com/iluwatar/poison/pill/App.java index 0dd2b2e45..222bfdbb5 100644 --- a/poison-pill/src/main/java/com/iluwatar/poison/pill/App.java +++ b/poison-pill/src/main/java/com/iluwatar/poison/pill/App.java @@ -50,11 +50,13 @@ public class App { new Thread(consumer::consume).start(); - new Thread(() -> { - producer.send("hand shake"); - producer.send("some very important information"); - producer.send("bye!"); - producer.stop(); - }).start(); + new Thread( + () -> { + producer.send("hand shake"); + producer.send("some very important information"); + producer.send("bye!"); + producer.stop(); + }) + .start(); } } diff --git a/poison-pill/src/main/java/com/iluwatar/poison/pill/Consumer.java b/poison-pill/src/main/java/com/iluwatar/poison/pill/Consumer.java index 8fc05f8ab..c6c24af95 100644 --- a/poison-pill/src/main/java/com/iluwatar/poison/pill/Consumer.java +++ b/poison-pill/src/main/java/com/iluwatar/poison/pill/Consumer.java @@ -27,9 +27,7 @@ package com.iluwatar.poison.pill; import com.iluwatar.poison.pill.Message.Headers; import lombok.extern.slf4j.Slf4j; -/** - * Class responsible for receiving and handling submitted to the queue messages. - */ +/** Class responsible for receiving and handling submitted to the queue messages. */ @Slf4j public class Consumer { @@ -41,9 +39,7 @@ public class Consumer { this.queue = queue; } - /** - * Consume message. - */ + /** Consume message. */ public void consume() { while (true) { try { 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 09cb20a6c..ab7dbdf31 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 @@ -32,44 +32,43 @@ import java.util.Map; */ public interface Message { - Message POISON_PILL = new Message() { + Message POISON_PILL = + new Message() { - @Override - public void addHeader(Headers header, String value) { - throw poison(); - } + @Override + public void addHeader(Headers header, String value) { + throw poison(); + } - @Override - public String getHeader(Headers header) { - throw poison(); - } + @Override + public String getHeader(Headers header) { + throw poison(); + } - @Override - public Map getHeaders() { - throw poison(); - } + @Override + public Map getHeaders() { + throw poison(); + } - @Override - public void setBody(String body) { - throw poison(); - } + @Override + public void setBody(String body) { + throw poison(); + } - @Override - public String getBody() { - throw poison(); - } + @Override + public String getBody() { + throw poison(); + } - private RuntimeException poison() { - return new UnsupportedOperationException("Poison"); - } + private RuntimeException poison() { + return new UnsupportedOperationException("Poison"); + } + }; - }; - - /** - * Enumeration of Type of Headers. - */ + /** Enumeration of Type of Headers. */ enum Headers { - DATE, SENDER + DATE, + SENDER } void addHeader(Headers header, String value); diff --git a/poison-pill/src/main/java/com/iluwatar/poison/pill/MessageQueue.java b/poison-pill/src/main/java/com/iluwatar/poison/pill/MessageQueue.java index 9477a80b2..91584b517 100644 --- a/poison-pill/src/main/java/com/iluwatar/poison/pill/MessageQueue.java +++ b/poison-pill/src/main/java/com/iluwatar/poison/pill/MessageQueue.java @@ -27,6 +27,4 @@ package com.iluwatar.poison.pill; /** * Represents abstraction of channel (or pipe) that bounds {@link Producer} and {@link Consumer}. */ -public interface MessageQueue extends MqPublishPoint, MqSubscribePoint { - -} +public interface MessageQueue extends MqPublishPoint, MqSubscribePoint {} diff --git a/poison-pill/src/main/java/com/iluwatar/poison/pill/MqPublishPoint.java b/poison-pill/src/main/java/com/iluwatar/poison/pill/MqPublishPoint.java index f4fdac944..a4c986d76 100644 --- a/poison-pill/src/main/java/com/iluwatar/poison/pill/MqPublishPoint.java +++ b/poison-pill/src/main/java/com/iluwatar/poison/pill/MqPublishPoint.java @@ -24,9 +24,7 @@ */ package com.iluwatar.poison.pill; -/** - * Endpoint to publish {@link Message} to queue. - */ +/** Endpoint to publish {@link Message} to queue. */ public interface MqPublishPoint { void put(Message msg) throws InterruptedException; diff --git a/poison-pill/src/main/java/com/iluwatar/poison/pill/MqSubscribePoint.java b/poison-pill/src/main/java/com/iluwatar/poison/pill/MqSubscribePoint.java index a89c6fb82..d0521cc7e 100644 --- a/poison-pill/src/main/java/com/iluwatar/poison/pill/MqSubscribePoint.java +++ b/poison-pill/src/main/java/com/iluwatar/poison/pill/MqSubscribePoint.java @@ -24,9 +24,7 @@ */ package com.iluwatar.poison.pill; -/** - * Endpoint to retrieve {@link Message} from queue. - */ +/** Endpoint to retrieve {@link Message} from queue. */ public interface MqSubscribePoint { Message take() throws InterruptedException; diff --git a/poison-pill/src/main/java/com/iluwatar/poison/pill/Producer.java b/poison-pill/src/main/java/com/iluwatar/poison/pill/Producer.java index 23e703db6..1d9966139 100644 --- a/poison-pill/src/main/java/com/iluwatar/poison/pill/Producer.java +++ b/poison-pill/src/main/java/com/iluwatar/poison/pill/Producer.java @@ -39,22 +39,19 @@ public class Producer { private final String name; private boolean isStopped; - /** - * Constructor. - */ + /** Constructor. */ public Producer(String name, MqPublishPoint queue) { this.name = name; this.queue = queue; this.isStopped = false; } - /** - * Send message to queue. - */ + /** Send message to queue. */ public void send(String body) { if (isStopped) { - throw new IllegalStateException(String.format( - "Producer %s was stopped and fail to deliver requested message [%s].", body, name)); + throw new IllegalStateException( + String.format( + "Producer %s was stopped and fail to deliver requested message [%s].", body, name)); } var msg = new SimpleMessage(); msg.addHeader(Headers.DATE, new Date().toString()); @@ -69,9 +66,7 @@ public class Producer { } } - /** - * Stop system by sending poison pill. - */ + /** Stop system by sending poison pill. */ public void stop() { isStopped = true; try { diff --git a/poison-pill/src/main/java/com/iluwatar/poison/pill/SimpleMessage.java b/poison-pill/src/main/java/com/iluwatar/poison/pill/SimpleMessage.java index 013b0e5d4..c8efb7ec2 100644 --- a/poison-pill/src/main/java/com/iluwatar/poison/pill/SimpleMessage.java +++ b/poison-pill/src/main/java/com/iluwatar/poison/pill/SimpleMessage.java @@ -28,9 +28,7 @@ import java.util.Collections; import java.util.HashMap; import java.util.Map; -/** - * {@link Message} basic implementation. - */ +/** {@link Message} basic implementation. */ public class SimpleMessage implements Message { private final Map headers = new HashMap<>(); diff --git a/poison-pill/src/main/java/com/iluwatar/poison/pill/SimpleMessageQueue.java b/poison-pill/src/main/java/com/iluwatar/poison/pill/SimpleMessageQueue.java index 288664c7f..32fc48a2a 100644 --- a/poison-pill/src/main/java/com/iluwatar/poison/pill/SimpleMessageQueue.java +++ b/poison-pill/src/main/java/com/iluwatar/poison/pill/SimpleMessageQueue.java @@ -27,9 +27,7 @@ package com.iluwatar.poison.pill; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; -/** - * Bounded blocking queue wrapper. - */ +/** Bounded blocking queue wrapper. */ public class SimpleMessageQueue implements MessageQueue { private final BlockingQueue queue; diff --git a/poison-pill/src/test/java/com/iluwatar/poison/pill/AppTest.java b/poison-pill/src/test/java/com/iluwatar/poison/pill/AppTest.java index b12166382..a4c2844fe 100644 --- a/poison-pill/src/test/java/com/iluwatar/poison/pill/AppTest.java +++ b/poison-pill/src/test/java/com/iluwatar/poison/pill/AppTest.java @@ -24,17 +24,15 @@ */ package com.iluwatar.poison.pill; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -/** - * Application test - */ +import org.junit.jupiter.api.Test; + +/** Application test */ class AppTest { @Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/poison-pill/src/test/java/com/iluwatar/poison/pill/ConsumerTest.java b/poison-pill/src/test/java/com/iluwatar/poison/pill/ConsumerTest.java index 8ed5f2cb1..3d03a5043 100644 --- a/poison-pill/src/test/java/com/iluwatar/poison/pill/ConsumerTest.java +++ b/poison-pill/src/test/java/com/iluwatar/poison/pill/ConsumerTest.java @@ -37,10 +37,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.slf4j.LoggerFactory; -/** - * ConsumerTest - * - */ +/** ConsumerTest */ class ConsumerTest { private InMemoryAppender appender; @@ -57,12 +54,12 @@ class ConsumerTest { @Test void testConsume() throws Exception { - final var messages = List.of( - createMessage("you", "Hello!"), - createMessage("me", "Hi!"), - Message.POISON_PILL, - createMessage("late_for_the_party", "Hello? Anyone here?") - ); + final var messages = + List.of( + createMessage("you", "Hello!"), + createMessage("me", "Hi!"), + Message.POISON_PILL, + createMessage("late_for_the_party", "Hello? Anyone here?")); final var queue = new SimpleMessageQueue(messages.size()); for (final var message : messages) { @@ -79,7 +76,7 @@ class ConsumerTest { /** * Create a new message from the given sender with the given message body * - * @param sender The sender's name + * @param sender The sender's name * @param message The message body * @return The message instance */ @@ -108,5 +105,4 @@ class ConsumerTest { return log.stream().map(ILoggingEvent::getFormattedMessage).anyMatch(message::equals); } } - } diff --git a/poison-pill/src/test/java/com/iluwatar/poison/pill/PoisonMessageTest.java b/poison-pill/src/test/java/com/iluwatar/poison/pill/PoisonMessageTest.java index aeed814b7..40688f8c3 100644 --- a/poison-pill/src/test/java/com/iluwatar/poison/pill/PoisonMessageTest.java +++ b/poison-pill/src/test/java/com/iluwatar/poison/pill/PoisonMessageTest.java @@ -30,15 +30,13 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import org.junit.jupiter.api.Test; -/** - * PoisonMessageTest - * - */ +/** PoisonMessageTest */ class PoisonMessageTest { @Test void testAddHeader() { - assertThrows(UnsupportedOperationException.class, () -> POISON_PILL.addHeader(Headers.SENDER, "sender")); + assertThrows( + UnsupportedOperationException.class, () -> POISON_PILL.addHeader(Headers.SENDER, "sender")); } @Test @@ -60,5 +58,4 @@ class PoisonMessageTest { void testGetBody() { assertThrows(UnsupportedOperationException.class, POISON_PILL::getBody); } - } diff --git a/poison-pill/src/test/java/com/iluwatar/poison/pill/ProducerTest.java b/poison-pill/src/test/java/com/iluwatar/poison/pill/ProducerTest.java index 3eb0a2dcc..3d5d50f70 100644 --- a/poison-pill/src/test/java/com/iluwatar/poison/pill/ProducerTest.java +++ b/poison-pill/src/test/java/com/iluwatar/poison/pill/ProducerTest.java @@ -35,10 +35,7 @@ import static org.mockito.Mockito.verifyNoMoreInteractions; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; -/** - * ProducerTest - * - */ +/** ProducerTest */ class ProducerTest { @Test @@ -76,11 +73,11 @@ class ProducerTest { } catch (IllegalStateException e) { assertNotNull(e); assertNotNull(e.getMessage()); - assertEquals("Producer Hello! was stopped and fail to deliver requested message [producer].", + assertEquals( + "Producer Hello! was stopped and fail to deliver requested message [producer].", e.getMessage()); } verifyNoMoreInteractions(publishPoint); } - } diff --git a/poison-pill/src/test/java/com/iluwatar/poison/pill/SimpleMessageTest.java b/poison-pill/src/test/java/com/iluwatar/poison/pill/SimpleMessageTest.java index f066d1425..77c547d61 100644 --- a/poison-pill/src/test/java/com/iluwatar/poison/pill/SimpleMessageTest.java +++ b/poison-pill/src/test/java/com/iluwatar/poison/pill/SimpleMessageTest.java @@ -32,10 +32,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; -/** - * SimpleMessageTest - * - */ +/** SimpleMessageTest */ class SimpleMessageTest { @Test @@ -55,6 +52,7 @@ class SimpleMessageTest { void testUnModifiableHeaders() { final var message = new SimpleMessage(); final var headers = message.getHeaders(); - assertThrows(UnsupportedOperationException.class, () -> headers.put(Message.Headers.SENDER, "test")); + assertThrows( + UnsupportedOperationException.class, () -> headers.put(Message.Headers.SENDER, "test")); } -} \ No newline at end of file +} diff --git a/pom.xml b/pom.xml index 83d430bff..4ff9bc9c9 100644 --- a/pom.xml +++ b/pom.xml @@ -37,7 +37,7 @@ UTF-8 5.0.0.4389 - 2.7.5 + 3.4.4 0.8.12 1.4 4.7.0 @@ -45,11 +45,17 @@ 6.0.0 1.1.0 3.5.2 - 3.6.0 4.6 2.1.1 3.14.0 1.18.36 + 5.11.4 + 2.0.17 + 1.5.18 + 5.16.1 + 5.4.0 + 5.4.0 + 2.3.232 https://sonarcloud.io iluwatar @@ -58,175 +64,175 @@ Java Design Patterns + abstract-document abstract-factory - collecting-parameter - monitor - builder - factory-method - prototype - singleton + active-object + acyclic-visitor adapter + ambassador + anti-corruption-layer + arrange-act-assert + async-method-invocation + balking + bloc bridge - composite - data-access-object - data-mapper - decorator - facade - flyweight - proxy + builder + business-delegate + bytecode + caching + callback chain-of-responsibility + circuit-breaker + client-session + collecting-parameter + collection-pipeline + combinator command + command-query-responsibility-segregation + commander + component + composite + composite-entity + composite-view + context-object + converter + curiously-recurring-template-pattern + currying + data-access-object + data-bus + data-locality + data-mapper + data-transfer-object + decorator + delegation + dependency-injection + dirty-flag + domain-model + double-buffer + double-checked-locking + double-dispatch + dynamic-proxy + event-aggregator + event-based-asynchronous + event-driven-architecture + event-queue + event-sourcing + execute-around + extension-objects + facade + factory + factory-kit + factory-method + fanout-fanin + feature-toggle + filterer + fluent-interface + flux + flyweight + front-controller + function-composition + game-loop + gateway + guarded-suspension + half-sync-half-async + health-check + hexagonal-architecture + identity-map + intercepting-filter interpreter iterator - mediator - memento - model-view-presenter - observer - state - strategy - template-method - version-number - visitor - double-checked-locking - servant - service-locator - null-object - event-aggregator - callback - execute-around - property - intercepting-filter - producer-consumer - pipeline - poison-pill - lazy-loading - service-layer - specification - tolerant-reader - model-view-controller - flux - double-dispatch - multiton - resource-acquisition-is-initialization - twin - private-class-data - object-pool - dependency-injection - front-controller - repository - async-method-invocation - monostate - step-builder - business-delegate - half-sync-half-async layered-architecture - fluent-interface - reactor - caching - delegation - event-driven-architecture - microservices-api-gateway - factory-kit - feature-toggle - value-object - monad - mute-idiom - hexagonal-architecture - abstract-document + lazy-loading + leader-election + leader-followers + lockable-object + map-reduce + marker-interface + master-worker + mediator + memento + metadata-mapping microservices-aggregrator - promise + microservices-api-gateway + microservices-client-side-ui-composition + microservices-distributed-tracing + microservices-idempotent-consumer + microservices-log-aggregation + model-view-controller + model-view-intent + model-view-presenter + model-view-viewmodel + monad + money + monitor + monolithic-architecture + monostate + multiton + mute-idiom + notification + null-object + object-mother + object-pool + observer + optimistic-offline-lock page-controller page-object - event-based-asynchronous - event-queue - queue-based-load-leveling - object-mother - data-bus - converter - guarded-suspension - balking - extension-objects - marker-interface - command-query-responsibility-segregation - event-sourcing - data-transfer-object - throttling - unit-of-work + parameter-object partial-response + pipeline + poison-pill + presentation-model + private-class-data + producer-consumer + promise + property + prototype + proxy + queue-based-load-leveling + reactor + registry + repository + resource-acquisition-is-initialization retry - dirty-flag - trampoline - ambassador - acyclic-visitor - collection-pipeline - master-worker - spatial-partition - commander - type-object - bytecode - leader-election - data-locality - subclass-sandbox - circuit-breaker role-object saga - double-buffer - sharding - game-loop - combinator - update-method - leader-followers - strangler - arrange-act-assert - transaction-script - registry - filterer - factory separated-interface - special-case - parameter-object - active-object - model-view-viewmodel - composite-entity - table-module - presentation-model - lockable-object - fanout-fanin - domain-model - composite-view - metadata-mapping - service-to-worker - client-session - model-view-intent - currying serialized-entity - identity-map - component - context-object - optimistic-offline-lock - curiously-recurring-template-pattern - microservices-log-aggregation - anti-corruption-layer - health-check - notification - single-table-inheritance - dynamic-proxy - gateway serialized-lob + servant server-session - virtual-proxy - function-composition - microservices-distributed-tracing - microservices-client-side-ui-composition - microservices-idempotent-consumer - monolithic-architecture + service-layer + service-locator + service-stub + service-to-worker session-facade - templateview - money + sharding + single-table-inheritance + singleton + spatial-partition + special-case + specification + state + step-builder + strangler + strategy + subclass-sandbox table-inheritance - bloc - map-reduce - service-stub + table-module + template-method + templateview + throttling + tolerant-reader + trampoline + transaction-script + twin + type-object + unit-of-work + update-method + value-object + version-number + virtual-proxy + visitor @@ -238,10 +244,29 @@ org.springframework.boot - spring-boot-dependencies + spring-boot-starter + ${spring-boot.version} + + + org.springframework.boot + spring-boot-starter-web + ${spring-boot.version} + + + org.springframework.boot + spring-boot-starter-actuator + ${spring-boot.version} + + + org.springframework.boot + spring-boot-starter-data-jpa + ${spring-boot.version} + + + org.springframework.boot + spring-boot-starter-test + test ${spring-boot.version} - pom - import commons-dbcp @@ -269,21 +294,51 @@ ${system-lambda.version} test + + org.junit.jupiter + junit-jupiter-engine + ${junit.version} + test + + + org.junit.jupiter + junit-jupiter-params + ${junit.version} + test + + + org.slf4j + slf4j-api + ${slf4j.version} + + + ch.qos.logback + logback-classic + ${logback.version} + + + org.mockito + mockito-core + ${mockito.version} + + + org.mongodb + bson + ${bson.version} + + + org.mongodb + mongodb-driver-legacy + ${mongo.version} + + + com.h2database + h2 + ${h2.version} + - - org.slf4j - slf4j-api - - - ch.qos.logback - logback-classic - - - ch.qos.logback - logback-core - org.projectlombok lombok @@ -348,28 +403,6 @@ - - org.apache.maven.plugins - maven-checkstyle-plugin - ${maven-checkstyle-plugin.version} - - - validate - - check - - validate - - google_checks.xml - checkstyle-suppressions.xml - - true - warning - false - - - - com.mycila license-maven-plugin @@ -423,6 +456,26 @@ + + com.diffplug.spotless + spotless-maven-plugin + 2.44.3 + + + + check + apply + + + + + + + 1.17.0 + + + + diff --git a/presentation-model/pom.xml b/presentation-model/pom.xml index 3edea0713..e2701838c 100644 --- a/presentation-model/pom.xml +++ b/presentation-model/pom.xml @@ -34,6 +34,14 @@ presentation-model + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/presentation-model/src/main/java/com/iluwatar/presentationmodel/Album.java b/presentation-model/src/main/java/com/iluwatar/presentationmodel/Album.java index aa32312de..af2dc0662 100644 --- a/presentation-model/src/main/java/com/iluwatar/presentationmodel/Album.java +++ b/presentation-model/src/main/java/com/iluwatar/presentationmodel/Album.java @@ -28,28 +28,20 @@ import lombok.AllArgsConstructor; import lombok.Getter; import lombok.Setter; -/** - *A class used to store the information of album. - */ +/** A class used to store the information of album. */ @Setter @Getter @AllArgsConstructor public class Album { - /** - * the title of the album. - */ + /** the title of the album. */ private String title; - /** - * the artist name of the album. - */ + + /** the artist name of the album. */ private String artist; - /** - * is the album classical, true or false. - */ + + /** is the album classical, true or false. */ private boolean isClassical; - /** - * only when the album is classical, - * composer can have content. - */ + + /** only when the album is classical, composer can have content. */ private String composer; } diff --git a/presentation-model/src/main/java/com/iluwatar/presentationmodel/App.java b/presentation-model/src/main/java/com/iluwatar/presentationmodel/App.java index d799480b8..0393c4826 100644 --- a/presentation-model/src/main/java/com/iluwatar/presentationmodel/App.java +++ b/presentation-model/src/main/java/com/iluwatar/presentationmodel/App.java @@ -27,16 +27,13 @@ package com.iluwatar.presentationmodel; import lombok.extern.slf4j.Slf4j; /** - * The Presentation model pattern is used to divide the presentation and controlling. - * This demo is a used to information of some albums with GUI. + * The Presentation model pattern is used to divide the presentation and controlling. This demo is a + * used to information of some albums with GUI. */ @Slf4j public final class App { - /** - * the constructor. - */ - private App() { - } + /** the constructor. */ + private App() {} /** * main method. @@ -48,4 +45,3 @@ public final class App { view.createView(); } } - diff --git a/presentation-model/src/main/java/com/iluwatar/presentationmodel/DisplayedAlbums.java b/presentation-model/src/main/java/com/iluwatar/presentationmodel/DisplayedAlbums.java index 11dae6df6..0e74e4c6d 100644 --- a/presentation-model/src/main/java/com/iluwatar/presentationmodel/DisplayedAlbums.java +++ b/presentation-model/src/main/java/com/iluwatar/presentationmodel/DisplayedAlbums.java @@ -29,21 +29,14 @@ import java.util.List; import lombok.Getter; import lombok.extern.slf4j.Slf4j; -/** - * a class used to deal with albums. - * - */ +/** a class used to deal with albums. */ @Slf4j @Getter public class DisplayedAlbums { - /** - * albums a list of albums. - */ + /** albums a list of albums. */ private final List albums; - /** - * a constructor method. - */ + /** a constructor method. */ public DisplayedAlbums() { this.albums = new ArrayList<>(); } @@ -51,15 +44,13 @@ public class DisplayedAlbums { /** * a method used to add a new album to album list. * - * @param title the title of the album. - * @param artist the artist name of the album. + * @param title the title of the album. + * @param artist the artist name of the album. * @param isClassical is the album classical, true or false. - * @param composer only when the album is classical, - * composer can have content. + * @param composer only when the album is classical, composer can have content. */ - public void addAlbums(final String title, - final String artist, final boolean isClassical, - final String composer) { + public void addAlbums( + final String title, final String artist, final boolean isClassical, final String composer) { if (isClassical) { this.albums.add(new Album(title, artist, true, composer)); } else { diff --git a/presentation-model/src/main/java/com/iluwatar/presentationmodel/PresentationModel.java b/presentation-model/src/main/java/com/iluwatar/presentationmodel/PresentationModel.java index 67414d6ae..8f6f7597b 100644 --- a/presentation-model/src/main/java/com/iluwatar/presentationmodel/PresentationModel.java +++ b/presentation-model/src/main/java/com/iluwatar/presentationmodel/PresentationModel.java @@ -26,22 +26,16 @@ package com.iluwatar.presentationmodel; import lombok.extern.slf4j.Slf4j; -/** - * The class between view and albums, it is used to control the data. - */ +/** The class between view and albums, it is used to control the data. */ @Slf4j public class PresentationModel { - /** - * the data of all albums that will be shown. - */ + /** the data of all albums that will be shown. */ private final DisplayedAlbums data; - /** - * the no of selected album. - */ + + /** the no of selected album. */ private int selectedAlbumNumber; - /** - * the selected album. - */ + + /** the selected album. */ private Album selectedAlbum; /** @@ -50,17 +44,23 @@ public class PresentationModel { * @return a instance of DsAlbum which store the data. */ public static DisplayedAlbums albumDataSet() { - var titleList = new String[]{"HQ", "The Rough Dancer and Cyclical Night", - "The Black Light", "Symphony No.5"}; - var artistList = new String[]{"Roy Harper", "Astor Piazzola", - "The Black Light", "CBSO"}; - var isClassicalList = new boolean[]{false, false, false, true}; - var composerList = new String[]{null, null, null, "Sibelius"}; + var titleList = + new String[] { + "HQ", "The Rough Dancer and Cyclical Night", + "The Black Light", "Symphony No.5" + }; + var artistList = + new String[] { + "Roy Harper", "Astor Piazzola", + "The Black Light", "CBSO" + }; + var isClassicalList = new boolean[] {false, false, false, true}; + var composerList = new String[] {null, null, null, "Sibelius"}; var result = new DisplayedAlbums(); for (var i = 1; i <= titleList.length; i++) { - result.addAlbums(titleList[i - 1], artistList[i - 1], - isClassicalList[i - 1], composerList[i - 1]); + result.addAlbums( + titleList[i - 1], artistList[i - 1], isClassicalList[i - 1], composerList[i - 1]); } return result; } @@ -82,8 +82,7 @@ public class PresentationModel { * @param albumNumber the number of album which is shown on the view. */ public void setSelectedAlbumNumber(final int albumNumber) { - LOGGER.info("Change select number from {} to {}", - this.selectedAlbumNumber, albumNumber); + LOGGER.info("Change select number from {} to {}", this.selectedAlbumNumber, albumNumber); this.selectedAlbumNumber = albumNumber; this.selectedAlbum = data.getAlbums().get(this.selectedAlbumNumber - 1); } @@ -103,8 +102,7 @@ public class PresentationModel { * @param value the title which user want to user. */ public void setTitle(final String value) { - LOGGER.info("Change album title from {} to {}", - selectedAlbum.getTitle(), value); + LOGGER.info("Change album title from {} to {}", selectedAlbum.getTitle(), value); selectedAlbum.setTitle(value); } @@ -123,8 +121,7 @@ public class PresentationModel { * @param value the name want artist to be. */ public void setArtist(final String value) { - LOGGER.info("Change album artist from {} to {}", - selectedAlbum.getArtist(), value); + LOGGER.info("Change album artist from {} to {}", selectedAlbum.getArtist(), value); selectedAlbum.setArtist(value); } @@ -143,8 +140,7 @@ public class PresentationModel { * @param value is the album classical. */ public void setIsClassical(final boolean value) { - LOGGER.info("Change album isClassical from {} to {}", - selectedAlbum.isClassical(), value); + LOGGER.info("Change album isClassical from {} to {}", selectedAlbum.isClassical(), value); selectedAlbum.setClassical(value); } @@ -164,8 +160,7 @@ public class PresentationModel { */ public void setComposer(final String value) { if (selectedAlbum.isClassical()) { - LOGGER.info("Change album composer from {} to {}", - selectedAlbum.getComposer(), value); + LOGGER.info("Change album composer from {} to {}", selectedAlbum.getComposer(), value); selectedAlbum.setComposer(value); } else { LOGGER.info("Composer can not be changed"); diff --git a/presentation-model/src/main/java/com/iluwatar/presentationmodel/View.java b/presentation-model/src/main/java/com/iluwatar/presentationmodel/View.java index 2d694644f..f62335293 100644 --- a/presentation-model/src/main/java/com/iluwatar/presentationmodel/View.java +++ b/presentation-model/src/main/java/com/iluwatar/presentationmodel/View.java @@ -35,70 +35,52 @@ import javax.swing.JList; import lombok.Getter; import lombok.extern.slf4j.Slf4j; -/** - * Generates the GUI of albums. - */ +/** Generates the GUI of albums. */ @Getter @Slf4j public class View { - /** - * the model that controls this view. - */ + /** the model that controls this view. */ private final PresentationModel model; - /** - * the filed to show and modify title. - */ + /** the filed to show and modify title. */ private TextField txtTitle; - /** - * the filed to show and modify the name of artist. - */ + + /** the filed to show and modify the name of artist. */ private TextField txtArtist; - /** - * the checkbox for is classical. - */ + + /** the checkbox for is classical. */ private JCheckBox chkClassical; - /** - * the filed to show and modify composer. - */ + + /** the filed to show and modify composer. */ private TextField txtComposer; - /** - * a list to show all the name of album. - */ + + /** a list to show all the name of album. */ private JList albumList; - /** - * a button to apply of all the change. - */ + + /** a button to apply of all the change. */ private JButton apply; - /** - * roll back the change. - */ + + /** roll back the change. */ private JButton cancel; - /** - * the value of the text field size. - */ + /** the value of the text field size. */ static final int WIDTH_TXT = 200; + static final int HEIGHT_TXT = 50; - /** - * the value of the GUI size and location. - */ + /** the value of the GUI size and location. */ static final int LOCATION_X = 200; + static final int LOCATION_Y = 200; static final int WIDTH = 500; static final int HEIGHT = 300; - /** - * constructor method. - */ + /** constructor method. */ public View() { model = new PresentationModel(PresentationModel.albumDataSet()); } - /** - * save the data to PresentationModel. - */ + /** save the data to PresentationModel. */ public void saveToMod() { LOGGER.info("Save data to PresentationModel"); model.setArtist(txtArtist.getText()); @@ -107,9 +89,7 @@ public class View { model.setComposer(txtComposer.getText()); } - /** - * load the data from PresentationModel. - */ + /** load the data from PresentationModel. */ public void loadFromMod() { LOGGER.info("Load data from PresentationModel"); txtArtist.setText(model.getArtist()); @@ -119,22 +99,21 @@ public class View { txtComposer.setText(model.getComposer()); } - /** - * initialize the GUI. - */ + /** initialize the GUI. */ public void createView() { var frame = new JFrame("Album"); var b1 = Box.createHorizontalBox(); frame.add(b1); albumList = new JList<>(model.getAlbumList()); - albumList.addMouseListener(new MouseAdapter() { - @Override - public void mouseClicked(final MouseEvent e) { - model.setSelectedAlbumNumber(albumList.getSelectedIndex() + 1); - loadFromMod(); - } - }); + albumList.addMouseListener( + new MouseAdapter() { + @Override + public void mouseClicked(final MouseEvent e) { + model.setSelectedAlbumNumber(albumList.getSelectedIndex() + 1); + loadFromMod(); + } + }); b1.add(albumList); var b2 = Box.createVerticalBox(); @@ -148,30 +127,33 @@ public class View { chkClassical = new JCheckBox(); txtComposer = new TextField(); - chkClassical.addActionListener(itemEvent -> { - txtComposer.setEditable(chkClassical.isSelected()); - if (!chkClassical.isSelected()) { - txtComposer.setText(""); - } - }); + chkClassical.addActionListener( + itemEvent -> { + txtComposer.setEditable(chkClassical.isSelected()); + if (!chkClassical.isSelected()) { + txtComposer.setText(""); + } + }); txtComposer.setSize(WIDTH_TXT, HEIGHT_TXT); txtComposer.setEditable(model.getIsClassical()); apply = new JButton("Apply"); - apply.addMouseListener(new MouseAdapter() { - @Override - public void mouseClicked(final MouseEvent e) { - saveToMod(); - loadFromMod(); - } - }); + apply.addMouseListener( + new MouseAdapter() { + @Override + public void mouseClicked(final MouseEvent e) { + saveToMod(); + loadFromMod(); + } + }); cancel = new JButton("Cancel"); - cancel.addMouseListener(new MouseAdapter() { - @Override - public void mouseClicked(final MouseEvent e) { - loadFromMod(); - } - }); + cancel.addMouseListener( + new MouseAdapter() { + @Override + public void mouseClicked(final MouseEvent e) { + loadFromMod(); + } + }); b2.add(txtArtist); b2.add(txtTitle); @@ -186,5 +168,4 @@ public class View { frame.setBounds(LOCATION_X, LOCATION_Y, WIDTH, HEIGHT); frame.setVisible(true); } - } diff --git a/presentation-model/src/test/java/com/iluwatar/presentationmodel/AlbumTest.java b/presentation-model/src/test/java/com/iluwatar/presentationmodel/AlbumTest.java index dd4d84884..1f87055b4 100644 --- a/presentation-model/src/test/java/com/iluwatar/presentationmodel/AlbumTest.java +++ b/presentation-model/src/test/java/com/iluwatar/presentationmodel/AlbumTest.java @@ -24,35 +24,35 @@ */ package com.iluwatar.presentationmodel; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.Test; + class AlbumTest { @Test - void testSetTitle(){ + void testSetTitle() { Album album = new Album("a", "b", false, ""); album.setTitle("b"); assertEquals("b", album.getTitle()); } @Test - void testSetArtist(){ + void testSetArtist() { Album album = new Album("a", "b", false, ""); album.setArtist("c"); assertEquals("c", album.getArtist()); } @Test - void testSetClassical(){ + void testSetClassical() { Album album = new Album("a", "b", false, ""); album.setClassical(true); assertTrue(album.isClassical()); } @Test - void testSetComposer(){ + void testSetComposer() { Album album = new Album("a", "b", false, ""); album.setClassical(true); album.setComposer("w"); diff --git a/presentation-model/src/test/java/com/iluwatar/presentationmodel/AppTest.java b/presentation-model/src/test/java/com/iluwatar/presentationmodel/AppTest.java index c3715ed5a..fb8780a1f 100644 --- a/presentation-model/src/test/java/com/iluwatar/presentationmodel/AppTest.java +++ b/presentation-model/src/test/java/com/iluwatar/presentationmodel/AppTest.java @@ -24,20 +24,20 @@ */ package com.iluwatar.presentationmodel; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import org.junit.jupiter.api.Test; + /** * Issue: Add at least one assertion to this test case. * - * Solution: Inserted assertion to check whether the execution of the main method in {@link App} + *

Solution: Inserted assertion to check whether the execution of the main method in {@link App} * throws an exception. */ class AppTest { - @Test - void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); - } + @Test + void shouldExecuteApplicationWithoutException() { + assertDoesNotThrow(() -> App.main(new String[] {})); + } } diff --git a/presentation-model/src/test/java/com/iluwatar/presentationmodel/DisplayedAlbumsTest.java b/presentation-model/src/test/java/com/iluwatar/presentationmodel/DisplayedAlbumsTest.java index b9d571642..8c5599fe1 100644 --- a/presentation-model/src/test/java/com/iluwatar/presentationmodel/DisplayedAlbumsTest.java +++ b/presentation-model/src/test/java/com/iluwatar/presentationmodel/DisplayedAlbumsTest.java @@ -24,21 +24,20 @@ */ package com.iluwatar.presentationmodel; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; + class DisplayedAlbumsTest { @Test - void testAdd_true(){ + void testAdd_true() { DisplayedAlbums displayedAlbums = new DisplayedAlbums(); displayedAlbums.addAlbums("title", "artist", true, "composer"); assertEquals("composer", displayedAlbums.getAlbums().get(0).getComposer()); - } @Test - void testAdd_false(){ + void testAdd_false() { DisplayedAlbums displayedAlbums = new DisplayedAlbums(); displayedAlbums.addAlbums("title", "artist", false, "composer"); assertEquals("", displayedAlbums.getAlbums().get(0).getComposer()); diff --git a/presentation-model/src/test/java/com/iluwatar/presentationmodel/PresentationTest.java b/presentation-model/src/test/java/com/iluwatar/presentationmodel/PresentationTest.java index 2a7d26caf..0326824c0 100644 --- a/presentation-model/src/test/java/com/iluwatar/presentationmodel/PresentationTest.java +++ b/presentation-model/src/test/java/com/iluwatar/presentationmodel/PresentationTest.java @@ -24,15 +24,16 @@ */ package com.iluwatar.presentationmodel; -import org.junit.jupiter.api.Test; - -import java.util.Arrays; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; +import java.util.Arrays; +import org.junit.jupiter.api.Test; + class PresentationTest { - String[] albumList = {"HQ", "The Rough Dancer and Cyclical Night", "The Black Light", "Symphony No.5"}; + String[] albumList = { + "HQ", "The Rough Dancer and Cyclical Night", "The Black Light", "Symphony No.5" + }; @Test void testCreateAlbumList() { diff --git a/presentation-model/src/test/java/com/iluwatar/presentationmodel/ViewTest.java b/presentation-model/src/test/java/com/iluwatar/presentationmodel/ViewTest.java index 7a0e6edd0..6428c6ac0 100644 --- a/presentation-model/src/test/java/com/iluwatar/presentationmodel/ViewTest.java +++ b/presentation-model/src/test/java/com/iluwatar/presentationmodel/ViewTest.java @@ -24,15 +24,18 @@ */ package com.iluwatar.presentationmodel; -import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.Test; + class ViewTest { - String[] albumList = {"HQ", "The Rough Dancer and Cyclical Night", "The Black Light", "Symphony No.5"}; + String[] albumList = { + "HQ", "The Rough Dancer and Cyclical Night", "The Black Light", "Symphony No.5" + }; @Test - void testSave_setArtistAndTitle(){ + void testSave_setArtistAndTitle() { View view = new View(); view.createView(); String testTitle = "testTitle"; @@ -46,7 +49,7 @@ class ViewTest { } @Test - void testSave_setClassicalAndComposer(){ + void testSave_setClassicalAndComposer() { View view = new View(); view.createView(); boolean isClassical = true; @@ -60,7 +63,7 @@ class ViewTest { } @Test - void testLoad_1(){ + void testLoad_1() { View view = new View(); view.createView(); view.getModel().setSelectedAlbumNumber(2); @@ -69,7 +72,7 @@ class ViewTest { } @Test - void testLoad_2(){ + void testLoad_2() { View view = new View(); view.createView(); view.getModel().setSelectedAlbumNumber(4); diff --git a/private-class-data/pom.xml b/private-class-data/pom.xml index 57fc5eba9..393832527 100644 --- a/private-class-data/pom.xml +++ b/private-class-data/pom.xml @@ -34,6 +34,14 @@ private-class-data + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/private-class-data/src/main/java/com/iluwatar/privateclassdata/ImmutableStew.java b/private-class-data/src/main/java/com/iluwatar/privateclassdata/ImmutableStew.java index e13577911..3a7f8c809 100644 --- a/private-class-data/src/main/java/com/iluwatar/privateclassdata/ImmutableStew.java +++ b/private-class-data/src/main/java/com/iluwatar/privateclassdata/ImmutableStew.java @@ -26,9 +26,7 @@ package com.iluwatar.privateclassdata; import lombok.extern.slf4j.Slf4j; -/** - * Immutable stew class, protected with Private Class Data pattern. - */ +/** Immutable stew class, protected with Private Class Data pattern. */ @Slf4j public class ImmutableStew { @@ -38,12 +36,13 @@ public class ImmutableStew { data = new StewData(numPotatoes, numCarrots, numMeat, numPeppers); } - /** - * Mix the stew. - */ + /** Mix the stew. */ public void mix() { - LOGGER - .info("Mixing the immutable stew we find: {} potatoes, {} carrots, {} meat and {} peppers", - data.numPotatoes(), data.numCarrots(), data.numMeat(), data.numPeppers()); + LOGGER.info( + "Mixing the immutable stew we find: {} potatoes, {} carrots, {} meat and {} peppers", + data.numPotatoes(), + data.numCarrots(), + data.numMeat(), + data.numPeppers()); } } diff --git a/private-class-data/src/main/java/com/iluwatar/privateclassdata/Stew.java b/private-class-data/src/main/java/com/iluwatar/privateclassdata/Stew.java index fe6122f9d..7d58698d3 100644 --- a/private-class-data/src/main/java/com/iluwatar/privateclassdata/Stew.java +++ b/private-class-data/src/main/java/com/iluwatar/privateclassdata/Stew.java @@ -1,76 +1,72 @@ -/* - * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). - * - * The MIT License - * Copyright © 2014-2022 Ilkka Seppälä - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package com.iluwatar.privateclassdata; - -import lombok.extern.slf4j.Slf4j; - -/** - * Mutable stew class. - */ -@Slf4j -public class Stew { - - private int numPotatoes; - private int numCarrots; - private int numMeat; - private int numPeppers; - - /** - * Constructor. - */ - public Stew(int numPotatoes, int numCarrots, int numMeat, int numPeppers) { - this.numPotatoes = numPotatoes; - this.numCarrots = numCarrots; - this.numMeat = numMeat; - this.numPeppers = numPeppers; - } - - /** - * Mix the stew. - */ - public void mix() { - LOGGER.info("Mixing the stew we find: {} potatoes, {} carrots, {} meat and {} peppers", - numPotatoes, numCarrots, numMeat, numPeppers); - } - - /** - * Taste the stew. - */ - public void taste() { - LOGGER.info("Tasting the stew"); - if (numPotatoes > 0) { - numPotatoes--; - } - if (numCarrots > 0) { - numCarrots--; - } - if (numMeat > 0) { - numMeat--; - } - if (numPeppers > 0) { - numPeppers--; - } - } -} +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.privateclassdata; + +import lombok.extern.slf4j.Slf4j; + +/** Mutable stew class. */ +@Slf4j +public class Stew { + + private int numPotatoes; + private int numCarrots; + private int numMeat; + private int numPeppers; + + /** Constructor. */ + public Stew(int numPotatoes, int numCarrots, int numMeat, int numPeppers) { + this.numPotatoes = numPotatoes; + this.numCarrots = numCarrots; + this.numMeat = numMeat; + this.numPeppers = numPeppers; + } + + /** Mix the stew. */ + public void mix() { + LOGGER.info( + "Mixing the stew we find: {} potatoes, {} carrots, {} meat and {} peppers", + numPotatoes, + numCarrots, + numMeat, + numPeppers); + } + + /** Taste the stew. */ + public void taste() { + LOGGER.info("Tasting the stew"); + if (numPotatoes > 0) { + numPotatoes--; + } + if (numCarrots > 0) { + numCarrots--; + } + if (numMeat > 0) { + numMeat--; + } + if (numPeppers > 0) { + numPeppers--; + } + } +} diff --git a/private-class-data/src/main/java/com/iluwatar/privateclassdata/StewData.java b/private-class-data/src/main/java/com/iluwatar/privateclassdata/StewData.java index 8812cf29d..31b918afc 100644 --- a/private-class-data/src/main/java/com/iluwatar/privateclassdata/StewData.java +++ b/private-class-data/src/main/java/com/iluwatar/privateclassdata/StewData.java @@ -24,8 +24,5 @@ */ package com.iluwatar.privateclassdata; -/** - * Stew ingredients. - */ - +/** Stew ingredients. */ public record StewData(int numPotatoes, int numCarrots, int numMeat, int numPeppers) {} diff --git a/private-class-data/src/test/java/com/iluwatar/privateclassdata/AppTest.java b/private-class-data/src/test/java/com/iluwatar/privateclassdata/AppTest.java index 575b37719..4ec59c8ae 100644 --- a/private-class-data/src/test/java/com/iluwatar/privateclassdata/AppTest.java +++ b/private-class-data/src/test/java/com/iluwatar/privateclassdata/AppTest.java @@ -24,17 +24,15 @@ */ package com.iluwatar.privateclassdata; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -/** - * Application test - */ +import org.junit.jupiter.api.Test; + +/** Application test */ class AppTest { @Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/private-class-data/src/test/java/com/iluwatar/privateclassdata/ImmutableStewTest.java b/private-class-data/src/test/java/com/iluwatar/privateclassdata/ImmutableStewTest.java index 6a68bb001..9caf7dd1b 100644 --- a/private-class-data/src/test/java/com/iluwatar/privateclassdata/ImmutableStewTest.java +++ b/private-class-data/src/test/java/com/iluwatar/privateclassdata/ImmutableStewTest.java @@ -31,10 +31,7 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -/** - * ImmutableStewTest - * - */ +/** ImmutableStewTest */ class ImmutableStewTest { private InMemoryAppender appender; @@ -49,9 +46,7 @@ class ImmutableStewTest { appender.stop(); } - /** - * Verify if mixing the stew doesn't change the internal state - */ + /** Verify if mixing the stew doesn't change the internal state */ @Test void testMix() { var stew = new Stew(1, 2, 3, 4); @@ -65,22 +60,22 @@ class ImmutableStewTest { assertEquals(20, appender.getLogSize()); } - /** - * Verify if tasting the stew actually removes one of each ingredient - */ + /** Verify if tasting the stew actually removes one of each ingredient */ @Test void testDrink() { final var stew = new Stew(1, 2, 3, 4); stew.mix(); - assertEquals("Mixing the stew we find: 1 potatoes, 2 carrots, 3 meat and 4 peppers", appender - .getLastMessage()); + assertEquals( + "Mixing the stew we find: 1 potatoes, 2 carrots, 3 meat and 4 peppers", + appender.getLastMessage()); stew.taste(); assertEquals("Tasting the stew", appender.getLastMessage()); stew.mix(); - assertEquals("Mixing the stew we find: 0 potatoes, 1 carrots, 2 meat and 3 peppers", appender - .getLastMessage()); + assertEquals( + "Mixing the stew we find: 0 potatoes, 1 carrots, 2 meat and 3 peppers", + appender.getLastMessage()); } } diff --git a/private-class-data/src/test/java/com/iluwatar/privateclassdata/StewTest.java b/private-class-data/src/test/java/com/iluwatar/privateclassdata/StewTest.java index 0dbe5ca85..8715160b6 100644 --- a/private-class-data/src/test/java/com/iluwatar/privateclassdata/StewTest.java +++ b/private-class-data/src/test/java/com/iluwatar/privateclassdata/StewTest.java @@ -31,10 +31,7 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -/** - * StewTest - * - */ +/** StewTest */ class StewTest { private InMemoryAppender appender; @@ -49,14 +46,12 @@ class StewTest { appender.stop(); } - /** - * Verify if mixing the stew doesn't change the internal state - */ + /** Verify if mixing the stew doesn't change the internal state */ @Test void testMix() { final var stew = new ImmutableStew(1, 2, 3, 4); - final var expectedMessage = "Mixing the immutable stew we find: 1 potatoes, " - + "2 carrots, 3 meat and 4 peppers"; + final var expectedMessage = + "Mixing the immutable stew we find: 1 potatoes, " + "2 carrots, 3 meat and 4 peppers"; for (var i = 0; i < 20; i++) { stew.mix(); @@ -65,5 +60,4 @@ class StewTest { assertEquals(20, appender.getLogSize()); } - } 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 262a41995..edb785354 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 @@ -31,9 +31,7 @@ import java.util.LinkedList; import java.util.List; import org.slf4j.LoggerFactory; -/** - * InMemory Log Appender Util. - */ +/** InMemory Log Appender Util. */ public class InMemoryAppender extends AppenderBase { private final List log = new LinkedList<>(); diff --git a/producer-consumer/pom.xml b/producer-consumer/pom.xml index f82049cd6..41eda2a36 100644 --- a/producer-consumer/pom.xml +++ b/producer-consumer/pom.xml @@ -34,6 +34,14 @@ producer-consumer + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/producer-consumer/src/main/java/com/iluwatar/producer/consumer/App.java b/producer-consumer/src/main/java/com/iluwatar/producer/consumer/App.java index 81ed325ba..22aad7002 100644 --- a/producer-consumer/src/main/java/com/iluwatar/producer/consumer/App.java +++ b/producer-consumer/src/main/java/com/iluwatar/producer/consumer/App.java @@ -54,20 +54,22 @@ public class App { for (var i = 0; i < 2; i++) { final var producer = new Producer("Producer_" + i, queue); - executorService.submit(() -> { - while (true) { - producer.produce(); - } - }); + executorService.submit( + () -> { + while (true) { + producer.produce(); + } + }); } for (var i = 0; i < 3; i++) { final var consumer = new Consumer("Consumer_" + i, queue); - executorService.submit(() -> { - while (true) { - consumer.consume(); - } - }); + executorService.submit( + () -> { + while (true) { + consumer.consume(); + } + }); } executorService.shutdown(); diff --git a/producer-consumer/src/main/java/com/iluwatar/producer/consumer/Consumer.java b/producer-consumer/src/main/java/com/iluwatar/producer/consumer/Consumer.java index 1d26f2b4a..4574473db 100644 --- a/producer-consumer/src/main/java/com/iluwatar/producer/consumer/Consumer.java +++ b/producer-consumer/src/main/java/com/iluwatar/producer/consumer/Consumer.java @@ -26,9 +26,7 @@ package com.iluwatar.producer.consumer; import lombok.extern.slf4j.Slf4j; -/** - * Class responsible for consume the {@link Item} produced by {@link Producer}. - */ +/** Class responsible for consume the {@link Item} produced by {@link Producer}. */ @Slf4j public class Consumer { @@ -41,13 +39,10 @@ public class Consumer { this.queue = queue; } - /** - * Consume item from the queue. - */ + /** Consume item from the queue. */ public void consume() throws InterruptedException { var item = queue.take(); - LOGGER.info("Consumer [{}] consume item [{}] produced by [{}]", name, - item.id(), item.producer()); - + LOGGER.info( + "Consumer [{}] consume item [{}] produced by [{}]", name, item.id(), item.producer()); } } diff --git a/producer-consumer/src/main/java/com/iluwatar/producer/consumer/Item.java b/producer-consumer/src/main/java/com/iluwatar/producer/consumer/Item.java index 01ca81b5a..b670086f6 100644 --- a/producer-consumer/src/main/java/com/iluwatar/producer/consumer/Item.java +++ b/producer-consumer/src/main/java/com/iluwatar/producer/consumer/Item.java @@ -24,7 +24,5 @@ */ package com.iluwatar.producer.consumer; -/** - * Class take part of an {@link Producer}-{@link Consumer} exchange. - */ +/** Class take part of an {@link Producer}-{@link Consumer} exchange. */ public record Item(String producer, int id) {} diff --git a/producer-consumer/src/main/java/com/iluwatar/producer/consumer/ItemQueue.java b/producer-consumer/src/main/java/com/iluwatar/producer/consumer/ItemQueue.java index 7fd3debad..cdfff3f99 100644 --- a/producer-consumer/src/main/java/com/iluwatar/producer/consumer/ItemQueue.java +++ b/producer-consumer/src/main/java/com/iluwatar/producer/consumer/ItemQueue.java @@ -27,9 +27,7 @@ package com.iluwatar.producer.consumer; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; -/** - * Class as a channel for {@link Producer}-{@link Consumer} exchange. - */ +/** Class as a channel for {@link Producer}-{@link Consumer} exchange. */ public class ItemQueue { private final BlockingQueue queue; @@ -48,5 +46,4 @@ public class ItemQueue { return queue.take(); } - } diff --git a/producer-consumer/src/main/java/com/iluwatar/producer/consumer/Producer.java b/producer-consumer/src/main/java/com/iluwatar/producer/consumer/Producer.java index b0d4bd384..a28a9e78d 100644 --- a/producer-consumer/src/main/java/com/iluwatar/producer/consumer/Producer.java +++ b/producer-consumer/src/main/java/com/iluwatar/producer/consumer/Producer.java @@ -45,9 +45,7 @@ public class Producer { this.queue = queue; } - /** - * Put item in the queue. - */ + /** Put item in the queue. */ public void produce() throws InterruptedException { var item = new Item(name, itemId++); diff --git a/producer-consumer/src/test/java/com/iluwatar/producer/consumer/AppTest.java b/producer-consumer/src/test/java/com/iluwatar/producer/consumer/AppTest.java index 5dbf70ade..aeb12f59b 100644 --- a/producer-consumer/src/test/java/com/iluwatar/producer/consumer/AppTest.java +++ b/producer-consumer/src/test/java/com/iluwatar/producer/consumer/AppTest.java @@ -24,18 +24,15 @@ */ package com.iluwatar.producer.consumer; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -/** - * Application test - */ +import org.junit.jupiter.api.Test; + +/** Application test */ class AppTest { @Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); - + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/producer-consumer/src/test/java/com/iluwatar/producer/consumer/ConsumerTest.java b/producer-consumer/src/test/java/com/iluwatar/producer/consumer/ConsumerTest.java index 004faed52..2f65d8e75 100644 --- a/producer-consumer/src/test/java/com/iluwatar/producer/consumer/ConsumerTest.java +++ b/producer-consumer/src/test/java/com/iluwatar/producer/consumer/ConsumerTest.java @@ -31,10 +31,7 @@ import static org.mockito.Mockito.verify; import org.junit.jupiter.api.Test; -/** - * ConsumerTest - * - */ +/** ConsumerTest */ class ConsumerTest { private static final int ITEM_COUNT = 5; @@ -55,5 +52,4 @@ class ConsumerTest { verify(queue, times(ITEM_COUNT)).take(); } - } diff --git a/producer-consumer/src/test/java/com/iluwatar/producer/consumer/ProducerTest.java b/producer-consumer/src/test/java/com/iluwatar/producer/consumer/ProducerTest.java index af95a1d36..3aef8bfe4 100644 --- a/producer-consumer/src/test/java/com/iluwatar/producer/consumer/ProducerTest.java +++ b/producer-consumer/src/test/java/com/iluwatar/producer/consumer/ProducerTest.java @@ -33,23 +33,21 @@ import static org.mockito.Mockito.verifyNoMoreInteractions; import org.junit.jupiter.api.Test; -/** - * ProducerTest - * - */ +/** ProducerTest */ class ProducerTest { @Test void testProduce() { - assertTimeout(ofMillis(6000), () -> { - final var queue = mock(ItemQueue.class); - final var producer = new Producer("producer", queue); + assertTimeout( + ofMillis(6000), + () -> { + final var queue = mock(ItemQueue.class); + final var producer = new Producer("producer", queue); - producer.produce(); - verify(queue).put(any(Item.class)); + producer.produce(); + verify(queue).put(any(Item.class)); - verifyNoMoreInteractions(queue); - }); + verifyNoMoreInteractions(queue); + }); } - -} \ No newline at end of file +} diff --git a/promise/pom.xml b/promise/pom.xml index 7a104ee3b..b43d3f57a 100644 --- a/promise/pom.xml +++ b/promise/pom.xml @@ -34,6 +34,14 @@ promise + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/promise/src/main/java/com/iluwatar/promise/App.java b/promise/src/main/java/com/iluwatar/promise/App.java index 1f66ae0da..7bfed9dc9 100644 --- a/promise/src/main/java/com/iluwatar/promise/App.java +++ b/promise/src/main/java/com/iluwatar/promise/App.java @@ -27,7 +27,6 @@ package com.iluwatar.promise; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import lombok.extern.slf4j.Slf4j; @@ -36,26 +35,28 @@ import lombok.extern.slf4j.Slf4j; * The Promise object is used for asynchronous computations. A Promise represents an operation that * hasn't completed yet, but is expected in the future. * - *

A Promise represents a proxy for a value not necessarily known when the promise is created. - * It allows you to associate dependent promises to an asynchronous action's eventual success value - * or failure reason. This lets asynchronous methods return values like synchronous methods: instead - * of the final value, the asynchronous method returns a promise of having a value at some point in - * the future. + *

A Promise represents a proxy for a value not necessarily known when the promise is created. It + * allows you to associate dependent promises to an asynchronous action's eventual success value or + * failure reason. This lets asynchronous methods return values like synchronous methods: instead of + * the final value, the asynchronous method returns a promise of having a value at some point in the + * future. * *

Promises provide a few advantages over callback objects: + * *

    - *
  • Functional composition and error handling - *
  • Prevents callback hell and provides callback aggregation + *
  • Functional composition and error handling + *
  • Prevents callback hell and provides callback aggregation *
* *

In this application the usage of promise is demonstrated with two examples: + * *

    - *
  • Count Lines: In this example a file is downloaded and its line count is calculated. - * The calculated line count is then consumed and printed on console. - *
  • Lowest Character Frequency: In this example a file is downloaded and its lowest frequency - * character is found and printed on console. This happens via a chain of promises, we start with - * a file download promise, then a promise of character frequency, then a promise of lowest - * frequency character which is finally consumed and result is printed on console. + *
  • Count Lines: In this example a file is downloaded and its line count is calculated. The + * calculated line count is then consumed and printed on console. + *
  • Lowest Character Frequency: In this example a file is downloaded and its lowest frequency + * character is found and printed on console. This happens via a chain of promises, we start + * with a file download promise, then a promise of character frequency, then a promise of + * lowest frequency character which is finally consumed and result is printed on console. *
* * @see CompletableFuture @@ -99,12 +100,12 @@ public class App { * consume the result in a Consumer */ private void calculateLowestFrequencyChar() { - lowestFrequencyChar().thenAccept( - charFrequency -> { - LOGGER.info("Char with lowest frequency is: {}", charFrequency); - taskCompleted(); - } - ); + lowestFrequencyChar() + .thenAccept( + charFrequency -> { + LOGGER.info("Char with lowest frequency is: {}", charFrequency); + taskCompleted(); + }); } /* @@ -112,12 +113,12 @@ public class App { * in a Consumer */ private void calculateLineCount() { - countLines().thenAccept( - count -> { - LOGGER.info("Line count is: {}", count); - taskCompleted(); - } - ); + countLines() + .thenAccept( + count -> { + LOGGER.info("Line count is: {}", count); + taskCompleted(); + }); } /* @@ -150,14 +151,12 @@ public class App { */ private Promise download(String urlString) { return new Promise() - .fulfillInAsync( - () -> Utility.downloadFile(urlString), executor) + .fulfillInAsync(() -> Utility.downloadFile(urlString), executor) .onError( throwable -> { LOGGER.error("An error occurred: ", throwable); taskCompleted(); - } - ); + }); } private void stop() throws InterruptedException { diff --git a/promise/src/main/java/com/iluwatar/promise/Promise.java b/promise/src/main/java/com/iluwatar/promise/Promise.java index 595814783..546e82a9b 100644 --- a/promise/src/main/java/com/iluwatar/promise/Promise.java +++ b/promise/src/main/java/com/iluwatar/promise/Promise.java @@ -44,9 +44,7 @@ public class Promise extends PromiseSupport { private Runnable fulfillmentAction; private Consumer exceptionHandler; - /** - * Creates a promise that will be fulfilled in the future. - */ + /** Creates a promise that will be fulfilled in the future. */ public Promise() { // Empty constructor } @@ -66,7 +64,7 @@ public class Promise extends PromiseSupport { * Fulfills the promise with exception due to error in execution. * * @param exception the exception will be wrapped in {@link ExecutionException} when accessing the - * value using {@link #get()}. + * value using {@link #get()}. */ @Override public void fulfillExceptionally(Exception exception) { @@ -93,18 +91,19 @@ public class Promise extends PromiseSupport { * Executes the task using the executor in other thread and fulfills the promise returned once the * task completes either successfully or with an exception. * - * @param task the task that will provide the value to fulfill the promise. + * @param task the task that will provide the value to fulfill the promise. * @param executor the executor in which the task should be run. * @return a promise that represents the result of running the task provided. */ public Promise fulfillInAsync(final Callable task, Executor executor) { - executor.execute(() -> { - try { - fulfill(task.call()); - } catch (Exception ex) { - fulfillExceptionally(ex); - } - }); + executor.execute( + () -> { + try { + fulfill(task.call()); + } catch (Exception ex) { + fulfillExceptionally(ex); + } + }); return this; } @@ -125,7 +124,7 @@ public class Promise extends PromiseSupport { * Set the exception handler on this promise. * * @param exceptionHandler a consumer that will handle the exception occurred while fulfilling the - * promise. + * promise. * @return this */ public Promise onError(Consumer exceptionHandler) { @@ -198,4 +197,4 @@ public class Promise extends PromiseSupport { } } } -} \ No newline at end of file +} diff --git a/promise/src/main/java/com/iluwatar/promise/Utility.java b/promise/src/main/java/com/iluwatar/promise/Utility.java index e3a2e0ad8..903dcfe8e 100644 --- a/promise/src/main/java/com/iluwatar/promise/Utility.java +++ b/promise/src/main/java/com/iluwatar/promise/Utility.java @@ -39,9 +39,7 @@ import java.util.function.Function; import java.util.stream.Collectors; import lombok.extern.slf4j.Slf4j; -/** - * Utility to perform various operations. - */ +/** Utility to perform various operations. */ @Slf4j public class Utility { @@ -53,7 +51,8 @@ public class Utility { */ public static Map characterFrequency(String fileLocation) { try (var bufferedReader = new BufferedReader(new FileReader(fileLocation))) { - return bufferedReader.lines() + return bufferedReader + .lines() .flatMapToInt(String::chars) .mapToObj(x -> (char) x) .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); @@ -69,9 +68,7 @@ public class Utility { * @return the character, {@code Optional.empty()} otherwise. */ public static Character lowestFrequencyChar(Map charFrequency) { - return charFrequency - .entrySet() - .stream() + return charFrequency.entrySet().stream() .min(Comparator.comparingLong(Entry::getValue)) .map(Entry::getKey) .orElseThrow(); @@ -101,7 +98,7 @@ public class Utility { var url = new URL(urlString); var file = File.createTempFile("promise_pattern", null); try (var bufferedReader = new BufferedReader(new InputStreamReader(url.openStream())); - var writer = new FileWriter(file)) { + var writer = new FileWriter(file)) { String line; while ((line = bufferedReader.readLine()) != null) { writer.write(line); diff --git a/promise/src/test/java/com/iluwatar/promise/AppTest.java b/promise/src/test/java/com/iluwatar/promise/AppTest.java index 502968466..ecc2ad88d 100644 --- a/promise/src/test/java/com/iluwatar/promise/AppTest.java +++ b/promise/src/test/java/com/iluwatar/promise/AppTest.java @@ -28,9 +28,7 @@ import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import org.junit.jupiter.api.Test; -/** - * Application test. - */ +/** Application test. */ class AppTest { @Test diff --git a/promise/src/test/java/com/iluwatar/promise/PromiseTest.java b/promise/src/test/java/com/iluwatar/promise/PromiseTest.java index 99bf9aeed..13c01eafd 100644 --- a/promise/src/test/java/com/iluwatar/promise/PromiseTest.java +++ b/promise/src/test/java/com/iluwatar/promise/PromiseTest.java @@ -41,9 +41,7 @@ import java.util.function.Consumer; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -/** - * Tests Promise class. - */ +/** Tests Promise class. */ class PromiseTest { private Executor executor; @@ -66,17 +64,18 @@ class PromiseTest { } @Test - void promiseIsFulfilledWithAnExceptionIfTaskThrowsAnException() - throws InterruptedException { + void promiseIsFulfilledWithAnExceptionIfTaskThrowsAnException() throws InterruptedException { testWaitingForeverForPromiseToBeFulfilled(); testWaitingSomeTimeForPromiseToBeFulfilled(); } private void testWaitingForeverForPromiseToBeFulfilled() throws InterruptedException { var promise = new Promise(); - promise.fulfillInAsync(() -> { - throw new RuntimeException("Barf!"); - }, executor); + promise.fulfillInAsync( + () -> { + throw new RuntimeException("Barf!"); + }, + executor); try { promise.get(); @@ -97,9 +96,11 @@ class PromiseTest { private void testWaitingSomeTimeForPromiseToBeFulfilled() throws InterruptedException { var promise = new Promise(); - promise.fulfillInAsync(() -> { - throw new RuntimeException("Barf!"); - }, executor); + promise.fulfillInAsync( + () -> { + throw new RuntimeException("Barf!"); + }, + executor); try { promise.get(1000, TimeUnit.SECONDS); @@ -116,15 +117,15 @@ class PromiseTest { assertTrue(promise.isDone()); assertFalse(promise.isCancelled()); } - } @Test void dependentPromiseIsFulfilledAfterTheConsumerConsumesTheResultOfThisPromise() throws InterruptedException, ExecutionException { - var dependentPromise = promise - .fulfillInAsync(new NumberCrunchingTask(), executor) - .thenAccept(value -> assertEquals(NumberCrunchingTask.CRUNCHED_NUMBER, value)); + var dependentPromise = + promise + .fulfillInAsync(new NumberCrunchingTask(), executor) + .thenAccept(value -> assertEquals(NumberCrunchingTask.CRUNCHED_NUMBER, value)); dependentPromise.get(); assertTrue(dependentPromise.isDone()); @@ -134,16 +135,19 @@ class PromiseTest { @Test void dependentPromiseIsFulfilledWithAnExceptionIfConsumerThrowsAnException() throws InterruptedException { - var dependentPromise = promise - .fulfillInAsync(new NumberCrunchingTask(), executor) - .thenAccept(value -> { - throw new RuntimeException("Barf!"); - }); + var dependentPromise = + promise + .fulfillInAsync(new NumberCrunchingTask(), executor) + .thenAccept( + value -> { + throw new RuntimeException("Barf!"); + }); try { dependentPromise.get(); - fail("Fetching dependent promise should result in exception " - + "if the action threw an exception"); + fail( + "Fetching dependent promise should result in exception " + + "if the action threw an exception"); } catch (ExecutionException ex) { assertTrue(promise.isDone()); assertFalse(promise.isCancelled()); @@ -151,8 +155,9 @@ class PromiseTest { try { dependentPromise.get(1000, TimeUnit.SECONDS); - fail("Fetching dependent promise should result in exception " - + "if the action threw an exception"); + fail( + "Fetching dependent promise should result in exception " + + "if the action threw an exception"); } catch (ExecutionException ex) { assertTrue(promise.isDone()); assertFalse(promise.isCancelled()); @@ -162,13 +167,14 @@ class PromiseTest { @Test void dependentPromiseIsFulfilledAfterTheFunctionTransformsTheResultOfThisPromise() throws InterruptedException, ExecutionException { - var dependentPromise = promise - .fulfillInAsync(new NumberCrunchingTask(), executor) - .thenApply(value -> { - assertEquals(NumberCrunchingTask.CRUNCHED_NUMBER, value); - return String.valueOf(value); - }); - + var dependentPromise = + promise + .fulfillInAsync(new NumberCrunchingTask(), executor) + .thenApply( + value -> { + assertEquals(NumberCrunchingTask.CRUNCHED_NUMBER, value); + return String.valueOf(value); + }); assertEquals(String.valueOf(NumberCrunchingTask.CRUNCHED_NUMBER), dependentPromise.get()); assertTrue(dependentPromise.isDone()); @@ -178,16 +184,19 @@ class PromiseTest { @Test void dependentPromiseIsFulfilledWithAnExceptionIfTheFunctionThrowsException() throws InterruptedException { - var dependentPromise = promise - .fulfillInAsync(new NumberCrunchingTask(), executor) - .thenApply(value -> { - throw new RuntimeException("Barf!"); - }); + var dependentPromise = + promise + .fulfillInAsync(new NumberCrunchingTask(), executor) + .thenApply( + value -> { + throw new RuntimeException("Barf!"); + }); try { dependentPromise.get(); - fail("Fetching dependent promise should result in exception " - + "if the function threw an exception"); + fail( + "Fetching dependent promise should result in exception " + + "if the function threw an exception"); } catch (ExecutionException ex) { assertTrue(promise.isDone()); assertFalse(promise.isCancelled()); @@ -195,8 +204,9 @@ class PromiseTest { try { dependentPromise.get(1000, TimeUnit.SECONDS); - fail("Fetching dependent promise should result in exception " - + "if the function threw an exception"); + fail( + "Fetching dependent promise should result in exception " + + "if the function threw an exception"); } catch (ExecutionException ex) { assertTrue(promise.isDone()); assertFalse(promise.isCancelled()); diff --git a/property/pom.xml b/property/pom.xml index 17d8e35a0..a2d894e2b 100644 --- a/property/pom.xml +++ b/property/pom.xml @@ -34,6 +34,14 @@ property + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/property/src/main/java/com/iluwatar/property/Character.java b/property/src/main/java/com/iluwatar/property/Character.java index 83506abe2..0738260f0 100644 --- a/property/src/main/java/com/iluwatar/property/Character.java +++ b/property/src/main/java/com/iluwatar/property/Character.java @@ -27,16 +27,14 @@ package com.iluwatar.property; import java.util.HashMap; import java.util.Map; -/** - * Represents Character in game and his abilities (base stats). - */ +/** Represents Character in game and his abilities (base stats). */ public class Character implements Prototype { - /** - * Enumeration of Character types. - */ + /** Enumeration of Character types. */ public enum Type { - WARRIOR, MAGE, ROGUE + WARRIOR, + MAGE, + ROGUE } private final Prototype prototype; @@ -45,31 +43,30 @@ public class Character implements Prototype { private String name; private Type type; - /** - * Constructor. - */ + /** Constructor. */ public Character() { - this.prototype = new Prototype() { // Null-value object - @Override - public Integer get(Stats stat) { - return null; - } + this.prototype = + new Prototype() { // Null-value object + @Override + public Integer get(Stats stat) { + return null; + } - @Override - public boolean has(Stats stat) { - return false; - } + @Override + public boolean has(Stats stat) { + return false; + } - @Override - public void set(Stats stat, Integer val) { - // Does Nothing - } + @Override + public void set(Stats stat, Integer val) { + // Does Nothing + } - @Override - public void remove(Stats stat) { - // Does Nothing. - } - }; + @Override + public void remove(Stats stat) { + // Does Nothing. + } + }; } public Character(Type type, Prototype prototype) { @@ -77,9 +74,7 @@ public class Character implements Prototype { this.prototype = prototype; } - /** - * Constructor. - */ + /** Constructor. */ public Character(String name, Character prototype) { this.name = name; this.type = prototype.type; @@ -140,5 +135,4 @@ public class Character implements Prototype { } return builder.toString(); } - } diff --git a/property/src/main/java/com/iluwatar/property/Prototype.java b/property/src/main/java/com/iluwatar/property/Prototype.java index 9c9209564..a353f8a57 100644 --- a/property/src/main/java/com/iluwatar/property/Prototype.java +++ b/property/src/main/java/com/iluwatar/property/Prototype.java @@ -24,9 +24,7 @@ */ package com.iluwatar.property; -/** - * Interface for prototype inheritance. - */ +/** Interface for prototype inheritance. */ public interface Prototype { Integer get(Stats stat); diff --git a/property/src/main/java/com/iluwatar/property/Stats.java b/property/src/main/java/com/iluwatar/property/Stats.java index 2605f3e4f..ab83b80ce 100644 --- a/property/src/main/java/com/iluwatar/property/Stats.java +++ b/property/src/main/java/com/iluwatar/property/Stats.java @@ -24,10 +24,14 @@ */ package com.iluwatar.property; -/** - * All possible attributes that Character can have. - */ +/** All possible attributes that Character can have. */ public enum Stats { - - AGILITY, STRENGTH, ATTACK_POWER, ARMOR, INTELLECT, SPIRIT, ENERGY, RAGE + AGILITY, + STRENGTH, + ATTACK_POWER, + ARMOR, + INTELLECT, + SPIRIT, + ENERGY, + RAGE } diff --git a/property/src/test/java/com/iluwatar/property/AppTest.java b/property/src/test/java/com/iluwatar/property/AppTest.java index 761f09208..86dd774a4 100644 --- a/property/src/test/java/com/iluwatar/property/AppTest.java +++ b/property/src/test/java/com/iluwatar/property/AppTest.java @@ -24,17 +24,15 @@ */ package com.iluwatar.property; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -/** - * Application test - */ +import org.junit.jupiter.api.Test; + +/** Application test */ class AppTest { @Test void shouldExecuteWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/property/src/test/java/com/iluwatar/property/CharacterTest.java b/property/src/test/java/com/iluwatar/property/CharacterTest.java index 6db74bbe9..0d3147b11 100644 --- a/property/src/test/java/com/iluwatar/property/CharacterTest.java +++ b/property/src/test/java/com/iluwatar/property/CharacterTest.java @@ -33,10 +33,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Arrays; import org.junit.jupiter.api.Test; -/** - * CharacterTest - * - */ +/** CharacterTest */ class CharacterTest { @Test @@ -56,7 +53,6 @@ class CharacterTest { assertFalse(prototype.has(stat)); assertNull(prototype.get(stat)); } - } @Test @@ -78,7 +74,8 @@ class CharacterTest { prototype.set(Stats.ARMOR, 1); prototype.set(Stats.AGILITY, 2); prototype.set(Stats.INTELLECT, 3); - var message = """ + var message = + """ Stats: - AGILITY:2 - ARMOR:1 @@ -88,7 +85,8 @@ class CharacterTest { final var stupid = new Character(Type.ROGUE, prototype); stupid.remove(Stats.INTELLECT); - String expectedStupidString = """ + String expectedStupidString = + """ Character type: ROGUE Stats: - AGILITY:2 @@ -98,14 +96,14 @@ class CharacterTest { final var weak = new Character("weak", prototype); weak.remove(Stats.ARMOR); - String expectedWeakString = """ + String expectedWeakString = + """ Player: weak Stats: - AGILITY:2 - INTELLECT:3 """; assertEquals(expectedWeakString, weak.toString()); - } @Test @@ -139,5 +137,4 @@ class CharacterTest { weak.remove(Stats.ARMOR); assertNull(weak.type()); } - -} \ No newline at end of file +} diff --git a/prototype/pom.xml b/prototype/pom.xml index 6ab8640f3..4e6a44b18 100644 --- a/prototype/pom.xml +++ b/prototype/pom.xml @@ -34,6 +34,14 @@ prototype + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/prototype/src/main/java/com/iluwatar/prototype/App.java b/prototype/src/main/java/com/iluwatar/prototype/App.java index f29747353..fdcad9077 100644 --- a/prototype/src/main/java/com/iluwatar/prototype/App.java +++ b/prototype/src/main/java/com/iluwatar/prototype/App.java @@ -33,8 +33,8 @@ import lombok.extern.slf4j.Slf4j; * application, like the abstract factory pattern, does. - avoid the inherent cost of creating a new * object in the standard way (e.g., using the 'new' keyword) * - *

In this example we have a factory class ({@link HeroFactoryImpl}) producing objects by - * cloning the existing ones. The factory's prototype objects are given as constructor parameters. + *

In this example we have a factory class ({@link HeroFactoryImpl}) producing objects by cloning + * the existing ones. The factory's prototype objects are given as constructor parameters. */ @Slf4j public class App { @@ -45,11 +45,9 @@ public class App { * @param args command line args */ public static void main(String[] args) { - var factory = new HeroFactoryImpl( - new ElfMage("cooking"), - new ElfWarlord("cleaning"), - new ElfBeast("protecting") - ); + var factory = + new HeroFactoryImpl( + new ElfMage("cooking"), new ElfWarlord("cleaning"), new ElfBeast("protecting")); var mage = factory.createMage(); var warlord = factory.createWarlord(); var beast = factory.createBeast(); @@ -57,11 +55,8 @@ public class App { LOGGER.info(warlord.toString()); LOGGER.info(beast.toString()); - factory = new HeroFactoryImpl( - new OrcMage("axe"), - new OrcWarlord("sword"), - new OrcBeast("laser") - ); + factory = + new HeroFactoryImpl(new OrcMage("axe"), new OrcWarlord("sword"), new OrcBeast("laser")); mage = factory.createMage(); warlord = factory.createWarlord(); beast = factory.createBeast(); diff --git a/prototype/src/main/java/com/iluwatar/prototype/Beast.java b/prototype/src/main/java/com/iluwatar/prototype/Beast.java index 1888133a7..027ad2b18 100644 --- a/prototype/src/main/java/com/iluwatar/prototype/Beast.java +++ b/prototype/src/main/java/com/iluwatar/prototype/Beast.java @@ -27,14 +27,10 @@ package com.iluwatar.prototype; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; -/** - * Beast. - */ +/** Beast. */ @EqualsAndHashCode(callSuper = false) @NoArgsConstructor public abstract class Beast extends Prototype { - public Beast(Beast source) { - } - + public Beast(Beast source) {} } diff --git a/prototype/src/main/java/com/iluwatar/prototype/ElfBeast.java b/prototype/src/main/java/com/iluwatar/prototype/ElfBeast.java index 0dbfd789f..0fa9822be 100644 --- a/prototype/src/main/java/com/iluwatar/prototype/ElfBeast.java +++ b/prototype/src/main/java/com/iluwatar/prototype/ElfBeast.java @@ -27,9 +27,7 @@ package com.iluwatar.prototype; import lombok.EqualsAndHashCode; import lombok.RequiredArgsConstructor; -/** - * ElfBeast. - */ +/** ElfBeast. */ @EqualsAndHashCode(callSuper = true) @RequiredArgsConstructor public class ElfBeast extends Beast { @@ -45,5 +43,4 @@ public class ElfBeast extends Beast { public String toString() { return "Elven eagle helps in " + helpType; } - } diff --git a/prototype/src/main/java/com/iluwatar/prototype/ElfMage.java b/prototype/src/main/java/com/iluwatar/prototype/ElfMage.java index f1cd27c84..5b00275e4 100644 --- a/prototype/src/main/java/com/iluwatar/prototype/ElfMage.java +++ b/prototype/src/main/java/com/iluwatar/prototype/ElfMage.java @@ -27,9 +27,7 @@ package com.iluwatar.prototype; import lombok.EqualsAndHashCode; import lombok.RequiredArgsConstructor; -/** - * ElfMage. - */ +/** ElfMage. */ @EqualsAndHashCode(callSuper = true) @RequiredArgsConstructor public class ElfMage extends Mage { @@ -45,5 +43,4 @@ public class ElfMage extends Mage { public String toString() { return "Elven mage helps in " + helpType; } - } diff --git a/prototype/src/main/java/com/iluwatar/prototype/ElfWarlord.java b/prototype/src/main/java/com/iluwatar/prototype/ElfWarlord.java index a876cdcb3..6a53e7309 100644 --- a/prototype/src/main/java/com/iluwatar/prototype/ElfWarlord.java +++ b/prototype/src/main/java/com/iluwatar/prototype/ElfWarlord.java @@ -27,9 +27,7 @@ package com.iluwatar.prototype; import lombok.EqualsAndHashCode; import lombok.RequiredArgsConstructor; -/** - * ElfWarlord. - */ +/** ElfWarlord. */ @EqualsAndHashCode(callSuper = true) @RequiredArgsConstructor public class ElfWarlord extends Warlord { diff --git a/prototype/src/main/java/com/iluwatar/prototype/HeroFactory.java b/prototype/src/main/java/com/iluwatar/prototype/HeroFactory.java index 91aa37229..8295e0bdb 100644 --- a/prototype/src/main/java/com/iluwatar/prototype/HeroFactory.java +++ b/prototype/src/main/java/com/iluwatar/prototype/HeroFactory.java @@ -1,38 +1,35 @@ -/* - * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). - * - * The MIT License - * Copyright © 2014-2022 Ilkka Seppälä - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package com.iluwatar.prototype; - -/** - * Interface for the factory class. - */ -public interface HeroFactory { - - Mage createMage(); - - Warlord createWarlord(); - - Beast createBeast(); - -} +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.prototype; + +/** Interface for the factory class. */ +public interface HeroFactory { + + Mage createMage(); + + Warlord createWarlord(); + + Beast createBeast(); +} diff --git a/prototype/src/main/java/com/iluwatar/prototype/HeroFactoryImpl.java b/prototype/src/main/java/com/iluwatar/prototype/HeroFactoryImpl.java index 21c20a5fd..c959aa89d 100644 --- a/prototype/src/main/java/com/iluwatar/prototype/HeroFactoryImpl.java +++ b/prototype/src/main/java/com/iluwatar/prototype/HeroFactoryImpl.java @@ -26,9 +26,7 @@ package com.iluwatar.prototype; import lombok.RequiredArgsConstructor; -/** - * Concrete factory class. - */ +/** Concrete factory class. */ @RequiredArgsConstructor public class HeroFactoryImpl implements HeroFactory { @@ -36,25 +34,18 @@ public class HeroFactoryImpl implements HeroFactory { private final Warlord warlord; private final Beast beast; - /** - * Create mage. - */ + /** Create mage. */ public Mage createMage() { return mage.copy(); } - /** - * Create warlord. - */ + /** Create warlord. */ public Warlord createWarlord() { return warlord.copy(); } - /** - * Create beast. - */ + /** Create beast. */ public Beast createBeast() { return beast.copy(); } - } diff --git a/prototype/src/main/java/com/iluwatar/prototype/Mage.java b/prototype/src/main/java/com/iluwatar/prototype/Mage.java index 8f90e53f0..70a777051 100644 --- a/prototype/src/main/java/com/iluwatar/prototype/Mage.java +++ b/prototype/src/main/java/com/iluwatar/prototype/Mage.java @@ -27,14 +27,10 @@ package com.iluwatar.prototype; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; -/** - * Mage. - */ +/** Mage. */ @EqualsAndHashCode(callSuper = false) @NoArgsConstructor public abstract class Mage extends Prototype { - public Mage(Mage source) { - } - + public Mage(Mage source) {} } diff --git a/prototype/src/main/java/com/iluwatar/prototype/OrcBeast.java b/prototype/src/main/java/com/iluwatar/prototype/OrcBeast.java index 4cd24ed7e..0ab3c3b9c 100644 --- a/prototype/src/main/java/com/iluwatar/prototype/OrcBeast.java +++ b/prototype/src/main/java/com/iluwatar/prototype/OrcBeast.java @@ -27,9 +27,7 @@ package com.iluwatar.prototype; import lombok.EqualsAndHashCode; import lombok.RequiredArgsConstructor; -/** - * OrcBeast. - */ +/** OrcBeast. */ @EqualsAndHashCode(callSuper = false) @RequiredArgsConstructor public class OrcBeast extends Beast { @@ -45,5 +43,4 @@ public class OrcBeast extends Beast { public String toString() { return "Orcish wolf attacks with " + weapon; } - } diff --git a/prototype/src/main/java/com/iluwatar/prototype/OrcMage.java b/prototype/src/main/java/com/iluwatar/prototype/OrcMage.java index 7a4aa0a4d..33c0cac9f 100644 --- a/prototype/src/main/java/com/iluwatar/prototype/OrcMage.java +++ b/prototype/src/main/java/com/iluwatar/prototype/OrcMage.java @@ -27,9 +27,7 @@ package com.iluwatar.prototype; import lombok.EqualsAndHashCode; import lombok.RequiredArgsConstructor; -/** - * OrcMage. - */ +/** OrcMage. */ @EqualsAndHashCode(callSuper = true) @RequiredArgsConstructor public class OrcMage extends Mage { @@ -45,5 +43,4 @@ public class OrcMage extends Mage { public String toString() { return "Orcish mage attacks with " + weapon; } - } diff --git a/prototype/src/main/java/com/iluwatar/prototype/OrcWarlord.java b/prototype/src/main/java/com/iluwatar/prototype/OrcWarlord.java index 5ee7da40b..54964bd33 100644 --- a/prototype/src/main/java/com/iluwatar/prototype/OrcWarlord.java +++ b/prototype/src/main/java/com/iluwatar/prototype/OrcWarlord.java @@ -27,9 +27,7 @@ package com.iluwatar.prototype; import lombok.EqualsAndHashCode; import lombok.RequiredArgsConstructor; -/** - * OrcWarlord. - */ +/** OrcWarlord. */ @EqualsAndHashCode(callSuper = true) @RequiredArgsConstructor public class OrcWarlord extends Warlord { @@ -45,5 +43,4 @@ public class OrcWarlord extends Warlord { public String toString() { return "Orcish warlord attacks with " + weapon; } - } diff --git a/prototype/src/main/java/com/iluwatar/prototype/Prototype.java b/prototype/src/main/java/com/iluwatar/prototype/Prototype.java index b5cd10188..ead3d4e86 100644 --- a/prototype/src/main/java/com/iluwatar/prototype/Prototype.java +++ b/prototype/src/main/java/com/iluwatar/prototype/Prototype.java @@ -27,15 +27,11 @@ package com.iluwatar.prototype; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; -/** - * Prototype. - */ +/** Prototype. */ @Slf4j public abstract class Prototype implements Cloneable { - /** - * Object a shallow copy of this object or null if this object is not Cloneable. - */ + /** Object a shallow copy of this object or null if this object is not Cloneable. */ @SuppressWarnings("unchecked") @SneakyThrows public T copy() { diff --git a/prototype/src/main/java/com/iluwatar/prototype/Warlord.java b/prototype/src/main/java/com/iluwatar/prototype/Warlord.java index f407673d1..a1cf5562b 100644 --- a/prototype/src/main/java/com/iluwatar/prototype/Warlord.java +++ b/prototype/src/main/java/com/iluwatar/prototype/Warlord.java @@ -27,14 +27,10 @@ package com.iluwatar.prototype; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; -/** - * Warlord. - */ +/** Warlord. */ @EqualsAndHashCode(callSuper = false) @NoArgsConstructor public abstract class Warlord extends Prototype { - public Warlord(Warlord source) { - } - + public Warlord(Warlord source) {} } diff --git a/prototype/src/test/java/com/iluwatar/prototype/AppTest.java b/prototype/src/test/java/com/iluwatar/prototype/AppTest.java index c9c55e0c6..2407c1c8d 100644 --- a/prototype/src/test/java/com/iluwatar/prototype/AppTest.java +++ b/prototype/src/test/java/com/iluwatar/prototype/AppTest.java @@ -28,13 +28,11 @@ import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import org.junit.jupiter.api.Test; -/** - * Application test - */ +/** Application test */ class AppTest { @Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/prototype/src/test/java/com/iluwatar/prototype/PrototypeTest.java b/prototype/src/test/java/com/iluwatar/prototype/PrototypeTest.java index e20d6e0d5..b8cdb73b8 100644 --- a/prototype/src/test/java/com/iluwatar/prototype/PrototypeTest.java +++ b/prototype/src/test/java/com/iluwatar/prototype/PrototypeTest.java @@ -42,13 +42,12 @@ import org.junit.jupiter.params.provider.MethodSource; class PrototypeTest

> { static Collection dataProvider() { return List.of( - new Object[]{new OrcBeast("axe"), "Orcish wolf attacks with axe"}, - new Object[]{new OrcMage("sword"), "Orcish mage attacks with sword"}, - new Object[]{new OrcWarlord("laser"), "Orcish warlord attacks with laser"}, - new Object[]{new ElfBeast("cooking"), "Elven eagle helps in cooking"}, - new Object[]{new ElfMage("cleaning"), "Elven mage helps in cleaning"}, - new Object[]{new ElfWarlord("protecting"), "Elven warlord helps in protecting"} - ); + new Object[] {new OrcBeast("axe"), "Orcish wolf attacks with axe"}, + new Object[] {new OrcMage("sword"), "Orcish mage attacks with sword"}, + new Object[] {new OrcWarlord("laser"), "Orcish warlord attacks with laser"}, + new Object[] {new ElfBeast("cooking"), "Elven eagle helps in cooking"}, + new Object[] {new ElfMage("cleaning"), "Elven mage helps in cleaning"}, + new Object[] {new ElfWarlord("protecting"), "Elven warlord helps in protecting"}); } @ParameterizedTest @@ -62,5 +61,4 @@ class PrototypeTest

> { assertSame(testedPrototype.getClass(), clone.getClass()); assertEquals(clone, testedPrototype); } - } diff --git a/proxy/pom.xml b/proxy/pom.xml index f700c2fbb..79a9f2c58 100644 --- a/proxy/pom.xml +++ b/proxy/pom.xml @@ -34,6 +34,14 @@ proxy + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/proxy/src/main/java/com/iluwatar/proxy/App.java b/proxy/src/main/java/com/iluwatar/proxy/App.java index dfd8550c6..9b4cd6b5a 100644 --- a/proxy/src/main/java/com/iluwatar/proxy/App.java +++ b/proxy/src/main/java/com/iluwatar/proxy/App.java @@ -40,9 +40,7 @@ package com.iluwatar.proxy; */ public class App { - /** - * Program entry point. - */ + /** Program entry point. */ public static void main(String[] args) { var proxy = new WizardTowerProxy(new IvoryTower()); @@ -51,6 +49,5 @@ public class App { proxy.enter(new Wizard("Black wizard")); proxy.enter(new Wizard("Green wizard")); proxy.enter(new Wizard("Brown wizard")); - } } diff --git a/proxy/src/main/java/com/iluwatar/proxy/IvoryTower.java b/proxy/src/main/java/com/iluwatar/proxy/IvoryTower.java index 64f69f1e6..2f815f511 100644 --- a/proxy/src/main/java/com/iluwatar/proxy/IvoryTower.java +++ b/proxy/src/main/java/com/iluwatar/proxy/IvoryTower.java @@ -26,14 +26,11 @@ package com.iluwatar.proxy; import lombok.extern.slf4j.Slf4j; -/** - * The object to be proxied. - */ +/** The object to be proxied. */ @Slf4j public class IvoryTower implements WizardTower { public void enter(Wizard wizard) { LOGGER.info("{} enters the tower.", wizard); } - } diff --git a/proxy/src/main/java/com/iluwatar/proxy/Wizard.java b/proxy/src/main/java/com/iluwatar/proxy/Wizard.java index e37d33805..ebc3307cb 100644 --- a/proxy/src/main/java/com/iluwatar/proxy/Wizard.java +++ b/proxy/src/main/java/com/iluwatar/proxy/Wizard.java @@ -26,9 +26,7 @@ package com.iluwatar.proxy; import lombok.RequiredArgsConstructor; -/** - * Wizard. - */ +/** Wizard. */ @RequiredArgsConstructor public class Wizard { @@ -38,5 +36,4 @@ public class Wizard { public String toString() { return name; } - } diff --git a/proxy/src/main/java/com/iluwatar/proxy/WizardTower.java b/proxy/src/main/java/com/iluwatar/proxy/WizardTower.java index 8dcbdb2d3..5e89539d0 100644 --- a/proxy/src/main/java/com/iluwatar/proxy/WizardTower.java +++ b/proxy/src/main/java/com/iluwatar/proxy/WizardTower.java @@ -24,9 +24,7 @@ */ package com.iluwatar.proxy; -/** - * WizardTower interface. - */ +/** WizardTower interface. */ public interface WizardTower { void enter(Wizard wizard); diff --git a/proxy/src/main/java/com/iluwatar/proxy/WizardTowerProxy.java b/proxy/src/main/java/com/iluwatar/proxy/WizardTowerProxy.java index 9f27fad34..11f4effd5 100644 --- a/proxy/src/main/java/com/iluwatar/proxy/WizardTowerProxy.java +++ b/proxy/src/main/java/com/iluwatar/proxy/WizardTowerProxy.java @@ -26,9 +26,7 @@ package com.iluwatar.proxy; import lombok.extern.slf4j.Slf4j; -/** - * The proxy controlling access to the {@link IvoryTower}. - */ +/** The proxy controlling access to the {@link IvoryTower}. */ @Slf4j public class WizardTowerProxy implements WizardTower { diff --git a/proxy/src/test/java/com/iluwatar/proxy/AppTest.java b/proxy/src/test/java/com/iluwatar/proxy/AppTest.java index 066eb6fe0..bf96c6c00 100644 --- a/proxy/src/test/java/com/iluwatar/proxy/AppTest.java +++ b/proxy/src/test/java/com/iluwatar/proxy/AppTest.java @@ -24,17 +24,15 @@ */ package com.iluwatar.proxy; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -/** - * Application test - */ +import org.junit.jupiter.api.Test; + +/** Application test */ class AppTest { @Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/proxy/src/test/java/com/iluwatar/proxy/IvoryTowerTest.java b/proxy/src/test/java/com/iluwatar/proxy/IvoryTowerTest.java index 4531a67fc..550814e26 100644 --- a/proxy/src/test/java/com/iluwatar/proxy/IvoryTowerTest.java +++ b/proxy/src/test/java/com/iluwatar/proxy/IvoryTowerTest.java @@ -33,9 +33,7 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -/** - * Tests for {@link IvoryTower} - */ +/** Tests for {@link IvoryTower} */ class IvoryTowerTest { private InMemoryAppender appender; @@ -52,12 +50,12 @@ class IvoryTowerTest { @Test void testEnter() { - final var wizards = List.of( - new Wizard("Gandalf"), - new Wizard("Dumbledore"), - new Wizard("Oz"), - new Wizard("Merlin") - ); + final var wizards = + List.of( + new Wizard("Gandalf"), + new Wizard("Dumbledore"), + new Wizard("Oz"), + new Wizard("Merlin")); var tower = new IvoryTower(); wizards.forEach(tower::enter); diff --git a/proxy/src/test/java/com/iluwatar/proxy/WizardTest.java b/proxy/src/test/java/com/iluwatar/proxy/WizardTest.java index 68ec25192..73ff41ac8 100644 --- a/proxy/src/test/java/com/iluwatar/proxy/WizardTest.java +++ b/proxy/src/test/java/com/iluwatar/proxy/WizardTest.java @@ -29,9 +29,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.List; import org.junit.jupiter.api.Test; -/** - * Tests for {@link Wizard} - */ +/** Tests for {@link Wizard} */ class WizardTest { @Test @@ -39,4 +37,4 @@ class WizardTest { List.of("Gandalf", "Dumbledore", "Oz", "Merlin") .forEach(name -> assertEquals(name, new Wizard(name).toString())); } -} \ No newline at end of file +} diff --git a/proxy/src/test/java/com/iluwatar/proxy/WizardTowerProxyTest.java b/proxy/src/test/java/com/iluwatar/proxy/WizardTowerProxyTest.java index 1b3305296..1e73e690e 100644 --- a/proxy/src/test/java/com/iluwatar/proxy/WizardTowerProxyTest.java +++ b/proxy/src/test/java/com/iluwatar/proxy/WizardTowerProxyTest.java @@ -33,9 +33,7 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -/** - * Tests for {@link WizardTowerProxy} - */ +/** Tests for {@link WizardTowerProxy} */ class WizardTowerProxyTest { private InMemoryAppender appender; @@ -52,12 +50,12 @@ class WizardTowerProxyTest { @Test void testEnter() { - final var wizards = List.of( - new Wizard("Gandalf"), - new Wizard("Dumbledore"), - new Wizard("Oz"), - new Wizard("Merlin") - ); + final var wizards = + List.of( + new Wizard("Gandalf"), + new Wizard("Dumbledore"), + new Wizard("Oz"), + new Wizard("Merlin")); final var proxy = new WizardTowerProxy(new IvoryTower()); wizards.forEach(proxy::enter); 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 fb982b96d..b3341c19f 100644 --- a/proxy/src/test/java/com/iluwatar/proxy/utils/InMemoryAppender.java +++ b/proxy/src/test/java/com/iluwatar/proxy/utils/InMemoryAppender.java @@ -31,10 +31,7 @@ import java.util.LinkedList; import java.util.List; import org.slf4j.LoggerFactory; - -/** - * InMemory Log Appender Util. - */ +/** InMemory Log Appender Util. */ public class InMemoryAppender extends AppenderBase { private final List log = new LinkedList<>(); diff --git a/queue-based-load-leveling/pom.xml b/queue-based-load-leveling/pom.xml index c789c6a39..701123f60 100644 --- a/queue-based-load-leveling/pom.xml +++ b/queue-based-load-leveling/pom.xml @@ -34,6 +34,14 @@ queue-based-load-leveling + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/queue-based-load-leveling/src/main/java/com/iluwatar/queue/load/leveling/App.java b/queue-based-load-leveling/src/main/java/com/iluwatar/queue/load/leveling/App.java index 7042ff7b7..368346630 100644 --- a/queue-based-load-leveling/src/main/java/com/iluwatar/queue/load/leveling/App.java +++ b/queue-based-load-leveling/src/main/java/com/iluwatar/queue/load/leveling/App.java @@ -31,11 +31,10 @@ import lombok.extern.slf4j.Slf4j; /** * Many solutions in the cloud involve running tasks that invoke services. In this environment, if a - * service is subjected to intermittent heavy loads, it can cause performance or reliability - * issues. + * service is subjected to intermittent heavy loads, it can cause performance or reliability issues. * - *

A service could be a component that is part of the same solution as the tasks that utilize - * it, or it could be a third-party service providing access to frequently used resources such as a + *

A service could be a component that is part of the same solution as the tasks that utilize it, + * or it could be a third-party service providing access to frequently used resources such as a * cache or a storage service. If the same service is utilized by a number of tasks running * concurrently, it can be difficult to predict the volume of requests to which the service might be * subjected at any given point in time. @@ -45,8 +44,7 @@ import lombok.extern.slf4j.Slf4j; * The task posts a message containing the data required by the service to a queue. The queue acts * as a buffer, storing the message until it is retrieved by the service. The service retrieves the * messages from the queue and processes them. Requests from a number of tasks, which can be - * generated at a highly variable rate, can be passed to the service through the same message - * queue. + * generated at a highly variable rate, can be passed to the service through the same message queue. * *

The queue effectively decouples the tasks from the service, and the service can handle the * messages at its own pace irrespective of the volume of requests from concurrent tasks. @@ -61,7 +59,7 @@ import lombok.extern.slf4j.Slf4j; @Slf4j public class App { - //Executor shut down time limit. + // Executor shut down time limit. private static final int SHUTDOWN_TIME = 15; /** @@ -71,7 +69,7 @@ public class App { */ public static void main(String[] args) { - // An Executor that provides methods to manage termination and methods that can + // An Executor that provides methods to manage termination and methods that can // produce a Future for tracking progress of one or more asynchronous tasks. ExecutorService executor = null; @@ -100,12 +98,13 @@ public class App { executor.submit(srvRunnable); // Initiates an orderly shutdown. - LOGGER.info("Initiating shutdown." - + " Executor will shutdown only after all the Threads are completed."); + LOGGER.info( + "Initiating shutdown." + + " Executor will shutdown only after all the Threads are completed."); executor.shutdown(); - // Wait for SHUTDOWN_TIME seconds for all the threads to complete - // their tasks and then shut down the executor and then exit. + // Wait for SHUTDOWN_TIME seconds for all the threads to complete + // their tasks and then shut down the executor and then exit. if (!executor.awaitTermination(SHUTDOWN_TIME, TimeUnit.SECONDS)) { LOGGER.info("Executor was shut down and Exiting."); executor.shutdownNow(); @@ -114,4 +113,4 @@ public class App { LOGGER.error(e.getMessage()); } } -} \ No newline at end of file +} diff --git a/queue-based-load-leveling/src/main/java/com/iluwatar/queue/load/leveling/Message.java b/queue-based-load-leveling/src/main/java/com/iluwatar/queue/load/leveling/Message.java index c57c171a1..3b1eb84b0 100644 --- a/queue-based-load-leveling/src/main/java/com/iluwatar/queue/load/leveling/Message.java +++ b/queue-based-load-leveling/src/main/java/com/iluwatar/queue/load/leveling/Message.java @@ -27,9 +27,7 @@ package com.iluwatar.queue.load.leveling; import lombok.Getter; import lombok.RequiredArgsConstructor; -/** - * Message class with only one parameter. - */ +/** Message class with only one parameter. */ @Getter @RequiredArgsConstructor public class Message { @@ -39,4 +37,4 @@ public class Message { public String toString() { return msg; } -} \ No newline at end of file +} diff --git a/queue-based-load-leveling/src/main/java/com/iluwatar/queue/load/leveling/MessageQueue.java b/queue-based-load-leveling/src/main/java/com/iluwatar/queue/load/leveling/MessageQueue.java index 1d28faa54..f027937f0 100644 --- a/queue-based-load-leveling/src/main/java/com/iluwatar/queue/load/leveling/MessageQueue.java +++ b/queue-based-load-leveling/src/main/java/com/iluwatar/queue/load/leveling/MessageQueue.java @@ -37,7 +37,7 @@ public class MessageQueue { private final BlockingQueue blkQueue; - // Default constructor when called creates Blocking Queue object. + // Default constructor when called creates Blocking Queue object. public MessageQueue() { this.blkQueue = new ArrayBlockingQueue<>(1024); } diff --git a/queue-based-load-leveling/src/main/java/com/iluwatar/queue/load/leveling/ServiceExecutor.java b/queue-based-load-leveling/src/main/java/com/iluwatar/queue/load/leveling/ServiceExecutor.java index 02530042b..0a8f1b5a7 100644 --- a/queue-based-load-leveling/src/main/java/com/iluwatar/queue/load/leveling/ServiceExecutor.java +++ b/queue-based-load-leveling/src/main/java/com/iluwatar/queue/load/leveling/ServiceExecutor.java @@ -39,9 +39,7 @@ public class ServiceExecutor implements Runnable { this.msgQueue = msgQueue; } - /** - * The ServiceExecutor thread will retrieve each message and process it. - */ + /** The ServiceExecutor thread will retrieve each message and process it. */ public void run() { try { while (!Thread.currentThread().isInterrupted()) { diff --git a/queue-based-load-leveling/src/main/java/com/iluwatar/queue/load/leveling/Task.java b/queue-based-load-leveling/src/main/java/com/iluwatar/queue/load/leveling/Task.java index ab2b79e28..dfdb44544 100644 --- a/queue-based-load-leveling/src/main/java/com/iluwatar/queue/load/leveling/Task.java +++ b/queue-based-load-leveling/src/main/java/com/iluwatar/queue/load/leveling/Task.java @@ -24,9 +24,7 @@ */ package com.iluwatar.queue.load.leveling; -/** - * Task Interface. - */ +/** Task Interface. */ public interface Task { void submit(Message msg); } diff --git a/queue-based-load-leveling/src/main/java/com/iluwatar/queue/load/leveling/TaskGenerator.java b/queue-based-load-leveling/src/main/java/com/iluwatar/queue/load/leveling/TaskGenerator.java index 9b1407277..904bb4101 100644 --- a/queue-based-load-leveling/src/main/java/com/iluwatar/queue/load/leveling/TaskGenerator.java +++ b/queue-based-load-leveling/src/main/java/com/iluwatar/queue/load/leveling/TaskGenerator.java @@ -45,9 +45,7 @@ public class TaskGenerator implements Task, Runnable { this.msgCount = msgCount; } - /** - * Submit messages to the Blocking Queue. - */ + /** Submit messages to the Blocking Queue. */ public void submit(Message msg) { try { this.msgQueue.submitMsg(msg); @@ -80,4 +78,4 @@ public class TaskGenerator implements Task, Runnable { LOGGER.error(e.getMessage()); } } -} \ No newline at end of file +} diff --git a/queue-based-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/AppTest.java b/queue-based-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/AppTest.java index 6ba3d87b4..06da02738 100644 --- a/queue-based-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/AppTest.java +++ b/queue-based-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/AppTest.java @@ -24,17 +24,15 @@ */ package com.iluwatar.queue.load.leveling; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -/** - * Application Test - */ +import org.junit.jupiter.api.Test; + +/** Application Test */ class AppTest { @Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } -} \ No newline at end of file +} diff --git a/queue-based-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/MessageQueueTest.java b/queue-based-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/MessageQueueTest.java index 4ddcc9937..fa7d6f3b1 100644 --- a/queue-based-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/MessageQueueTest.java +++ b/queue-based-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/MessageQueueTest.java @@ -28,9 +28,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; -/** - * Test case for submitting and retrieving messages from Blocking Queue. - */ +/** Test case for submitting and retrieving messages from Blocking Queue. */ class MessageQueueTest { @Test @@ -44,5 +42,4 @@ class MessageQueueTest { // retrieve message assertEquals("MessageQueue Test", msgQueue.retrieveMsg().getMsg()); } - } diff --git a/queue-based-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/MessageTest.java b/queue-based-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/MessageTest.java index a0314ed04..8af65cc1e 100644 --- a/queue-based-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/MessageTest.java +++ b/queue-based-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/MessageTest.java @@ -28,9 +28,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; -/** - * Test case for creating and checking the Message. - */ +/** Test case for creating and checking the Message. */ class MessageTest { @Test diff --git a/queue-based-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/TaskGenSrvExeTest.java b/queue-based-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/TaskGenSrvExeTest.java index 0a03bc560..395f5ec40 100644 --- a/queue-based-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/TaskGenSrvExeTest.java +++ b/queue-based-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/TaskGenSrvExeTest.java @@ -52,5 +52,4 @@ class TaskGenSrvExeTest { assertNotNull(srvExeThr); } - } diff --git a/reactor/pom.xml b/reactor/pom.xml index ff884ab58..738959d7c 100644 --- a/reactor/pom.xml +++ b/reactor/pom.xml @@ -34,6 +34,14 @@ reactor + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/reactor/src/main/java/com/iluwatar/reactor/app/App.java b/reactor/src/main/java/com/iluwatar/reactor/app/App.java index cb10d5edb..a01738d2e 100644 --- a/reactor/src/main/java/com/iluwatar/reactor/app/App.java +++ b/reactor/src/main/java/com/iluwatar/reactor/app/App.java @@ -47,45 +47,35 @@ import java.util.List; *

PROBLEM
* Server applications in a distributed system must handle multiple clients that send them service * requests. Following forces need to be resolved: + * *

    - *
  • Availability
  • - *
  • Efficiency
  • - *
  • Programming Simplicity
  • - *
  • Adaptability
  • + *
  • Availability + *
  • Efficiency + *
  • Programming Simplicity + *
  • Adaptability *
* *

PARTICIPANTS
+ * *

    - *
  • Synchronous Event De-multiplexer - *

    - * {@link NioReactor} plays the role of synchronous event de-multiplexer. - * It waits for events on multiple channels registered to it in an event loop. - *

    - *
  • - *
  • Initiation Dispatcher - *

    - * {@link NioReactor} plays this role as the application specific {@link ChannelHandler}s - * are registered to the reactor. - *

    - *
  • - *
  • Handle - *

    - * {@link AbstractNioChannel} acts as a handle that is registered to the reactor. - * When any events occur on a handle, reactor calls the appropriate handler. - *

    - *
  • - *
  • Event Handler - *

    - * {@link ChannelHandler} acts as an event handler, which is bound to a - * channel and is called back when any event occurs on any of its associated handles. Application - * logic resides in event handlers. - *

    - *
  • + *
  • Synchronous Event De-multiplexer + *

    {@link NioReactor} plays the role of synchronous event de-multiplexer. It waits for + * events on multiple channels registered to it in an event loop. + *

  • Initiation Dispatcher + *

    {@link NioReactor} plays this role as the application specific {@link ChannelHandler}s + * are registered to the reactor. + *

  • Handle + *

    {@link AbstractNioChannel} acts as a handle that is registered to the reactor. When any + * events occur on a handle, reactor calls the appropriate handler. + *

  • Event Handler + *

    {@link ChannelHandler} acts as an event handler, which is bound to a channel and is + * called back when any event occurs on any of its associated handles. Application logic + * resides in event handlers. *

+ * * The application utilizes single thread to listen for requests on all ports. It does not create a * separate thread for each client, which provides better scalability under load (number of clients - * increase). - * The example uses Java NIO framework to implement the Reactor. + * increase). The example uses Java NIO framework to implement the Reactor. */ public class App { @@ -103,9 +93,7 @@ public class App { this.dispatcher = dispatcher; } - /** - * App entry. - */ + /** App entry. */ public static void main(String[] args) throws IOException { new App(new ThreadPoolDispatcher(2)).start(); } @@ -143,7 +131,7 @@ public class App { * Stops the NIO reactor. This is a blocking call. * * @throws InterruptedException if interrupted while stopping the reactor. - * @throws IOException if any I/O error occurs + * @throws IOException if any I/O error occurs */ public void stop() throws InterruptedException, IOException { reactor.stop(); diff --git a/reactor/src/main/java/com/iluwatar/reactor/app/AppClient.java b/reactor/src/main/java/com/iluwatar/reactor/app/AppClient.java index 53f671991..8636150bd 100644 --- a/reactor/src/main/java/com/iluwatar/reactor/app/AppClient.java +++ b/reactor/src/main/java/com/iluwatar/reactor/app/AppClient.java @@ -70,9 +70,7 @@ public class AppClient { service.execute(new UdpLoggingClient("Client 4", 16669)); } - /** - * Stops logging clients. This is a blocking call. - */ + /** Stops logging clients. This is a blocking call. */ public void stop() { service.shutdown(); if (!service.isTerminated()) { @@ -94,9 +92,7 @@ public class AppClient { } } - /** - * A logging client that sends requests to Reactor on TCP socket. - */ + /** A logging client that sends requests to Reactor on TCP socket. */ static class TcpLoggingClient implements Runnable { private final int serverPort; @@ -141,12 +137,9 @@ public class AppClient { artificialDelayOf(100); } } - } - /** - * A logging client that sends requests to Reactor on UDP socket. - */ + /** A logging client that sends requests to Reactor on UDP socket. */ static class UdpLoggingClient implements Runnable { private final String clientName; private final InetSocketAddress remoteAddress; @@ -155,7 +148,7 @@ public class AppClient { * Creates a new UDP logging client. * * @param clientName the name of the client to be sent in logging requests. - * @param port the port on which client will send logging requests. + * @param port the port on which client will send logging requests. * @throws UnknownHostException if localhost is unknown */ public UdpLoggingClient(String clientName, int port) throws UnknownHostException { diff --git a/reactor/src/main/java/com/iluwatar/reactor/app/LoggingHandler.java b/reactor/src/main/java/com/iluwatar/reactor/app/LoggingHandler.java index 74ec2ed7e..bc71b0353 100644 --- a/reactor/src/main/java/com/iluwatar/reactor/app/LoggingHandler.java +++ b/reactor/src/main/java/com/iluwatar/reactor/app/LoggingHandler.java @@ -40,9 +40,7 @@ public class LoggingHandler implements ChannelHandler { private static final byte[] ACK = "Data logged successfully".getBytes(); - /** - * Decodes the received data and logs it on standard console. - */ + /** Decodes the received data and logs it on standard console. */ @Override public void handleChannelRead(AbstractNioChannel channel, Object readObject, SelectionKey key) { /* @@ -61,10 +59,7 @@ public class LoggingHandler implements ChannelHandler { } private static void sendReply( - AbstractNioChannel channel, - DatagramPacket incomingPacket, - SelectionKey key - ) { + AbstractNioChannel channel, DatagramPacket incomingPacket, SelectionKey key) { /* * Create a reply acknowledgement datagram packet setting the receiver to the sender of incoming * message. diff --git a/reactor/src/main/java/com/iluwatar/reactor/framework/AbstractNioChannel.java b/reactor/src/main/java/com/iluwatar/reactor/framework/AbstractNioChannel.java index 83a2d9303..df7ec1c82 100644 --- a/reactor/src/main/java/com/iluwatar/reactor/framework/AbstractNioChannel.java +++ b/reactor/src/main/java/com/iluwatar/reactor/framework/AbstractNioChannel.java @@ -47,8 +47,7 @@ import lombok.Getter; public abstract class AbstractNioChannel { private final SelectableChannel channel; - @Getter - private final ChannelHandler handler; + @Getter private final ChannelHandler handler; private final Map> channelToPendingWrites; private NioReactor reactor; @@ -64,9 +63,7 @@ public abstract class AbstractNioChannel { this.channelToPendingWrites = new ConcurrentHashMap<>(); } - /** - * Injects the reactor in this channel. - */ + /** Injects the reactor in this channel. */ void setReactor(NioReactor reactor) { this.reactor = reactor; } @@ -125,7 +122,7 @@ public abstract class AbstractNioChannel { * Writes the data to the channel. * * @param pendingWrite the data to be written on channel. - * @param key the key which is writable. + * @param key the key which is writable. * @throws IOException if any I/O error occurs. */ protected abstract void doWrite(Object pendingWrite, SelectionKey key) throws IOException; @@ -149,13 +146,15 @@ public abstract class AbstractNioChannel { * * * @param data the data to be written on underlying channel. - * @param key the key which is writable. + * @param key the key which is writable. */ public void write(Object data, SelectionKey key) { var pendingWrites = this.channelToPendingWrites.get(key.channel()); if (pendingWrites == null) { synchronized (this.channelToPendingWrites) { - pendingWrites = this.channelToPendingWrites.computeIfAbsent(key.channel(), k -> new ConcurrentLinkedQueue<>()); + pendingWrites = + this.channelToPendingWrites.computeIfAbsent( + key.channel(), k -> new ConcurrentLinkedQueue<>()); } } pendingWrites.add(data); diff --git a/reactor/src/main/java/com/iluwatar/reactor/framework/ChannelHandler.java b/reactor/src/main/java/com/iluwatar/reactor/framework/ChannelHandler.java index 46cb2fc54..1a37f2b59 100644 --- a/reactor/src/main/java/com/iluwatar/reactor/framework/ChannelHandler.java +++ b/reactor/src/main/java/com/iluwatar/reactor/framework/ChannelHandler.java @@ -31,17 +31,16 @@ import java.nio.channels.SelectionKey; * to it by the {@link Dispatcher}. This is where the application logic resides. * *

A {@link ChannelHandler} can be associated with one or many {@link AbstractNioChannel}s, and - * whenever an event occurs on any of the associated channels, the handler is notified of the - * event. + * whenever an event occurs on any of the associated channels, the handler is notified of the event. */ public interface ChannelHandler { /** * Called when the {@code channel} receives some data from remote peer. * - * @param channel the channel from which the data was received. + * @param channel the channel from which the data was received. * @param readObject the data read. - * @param key the key on which read event occurred. + * @param key the key on which read event occurred. */ void handleChannelRead(AbstractNioChannel channel, Object readObject, SelectionKey key); } diff --git a/reactor/src/main/java/com/iluwatar/reactor/framework/Dispatcher.java b/reactor/src/main/java/com/iluwatar/reactor/framework/Dispatcher.java index 583c1241b..403b58c90 100644 --- a/reactor/src/main/java/com/iluwatar/reactor/framework/Dispatcher.java +++ b/reactor/src/main/java/com/iluwatar/reactor/framework/Dispatcher.java @@ -30,8 +30,9 @@ import java.nio.channels.SelectionKey; * Represents the event dispatching strategy. When {@link NioReactor} senses any event on the * registered {@link AbstractNioChannel}s then it de-multiplexes the event type, read or write or * connect, and then calls the {@link Dispatcher} to dispatch the read events. This decouples the - * I/O processing from application specific processing.
Dispatcher should call the {@link - * ChannelHandler} associated with the channel on which event occurred. + * I/O processing from application specific processing.
+ * Dispatcher should call the {@link ChannelHandler} associated with the channel on which event + * occurred. * *

The application can customize the way in which event is dispatched such as using the reactor * thread to dispatch event to channels or use a worker pool to do the non I/O processing. @@ -47,9 +48,9 @@ public interface Dispatcher { * *

The type of readObject depends on the channel on which data was received. * - * @param channel on which read event occurred + * @param channel on which read event occurred * @param readObject object read by channel - * @param key on which event occurred + * @param key on which event occurred */ void onChannelReadEvent(AbstractNioChannel channel, Object readObject, SelectionKey key); diff --git a/reactor/src/main/java/com/iluwatar/reactor/framework/NioDatagramChannel.java b/reactor/src/main/java/com/iluwatar/reactor/framework/NioDatagramChannel.java index bb582b893..0272d3c90 100644 --- a/reactor/src/main/java/com/iluwatar/reactor/framework/NioDatagramChannel.java +++ b/reactor/src/main/java/com/iluwatar/reactor/framework/NioDatagramChannel.java @@ -35,9 +35,7 @@ import lombok.Getter; import lombok.Setter; import lombok.extern.slf4j.Slf4j; -/** - * A wrapper over {@link DatagramChannel} which can read and write data on a DatagramChannel. - */ +/** A wrapper over {@link DatagramChannel} which can read and write data on a DatagramChannel. */ @Slf4j public class NioDatagramChannel extends AbstractNioChannel { @@ -50,7 +48,7 @@ public class NioDatagramChannel extends AbstractNioChannel { *

Note the constructor does not bind the socket, {@link #bind()} method should be called for * binding the socket. * - * @param port the port to be bound to listen for incoming datagram requests. + * @param port the port to be bound to listen for incoming datagram requests. * @param handler the handler to be used for handling incoming requests on this channel. * @throws IOException if any I/O error occurs. */ @@ -130,16 +128,12 @@ public class NioDatagramChannel extends AbstractNioChannel { super.write(data, key); } - /** - * Container of data used for {@link NioDatagramChannel} to communicate with remote peer. - */ + /** Container of data used for {@link NioDatagramChannel} to communicate with remote peer. */ @Getter public static class DatagramPacket { private final ByteBuffer data; - @Setter - private SocketAddress sender; - @Setter - private SocketAddress receiver; + @Setter private SocketAddress sender; + @Setter private SocketAddress receiver; /** * Creates a container with underlying data. diff --git a/reactor/src/main/java/com/iluwatar/reactor/framework/NioReactor.java b/reactor/src/main/java/com/iluwatar/reactor/framework/NioReactor.java index fb0ab5784..714b16d59 100644 --- a/reactor/src/main/java/com/iluwatar/reactor/framework/NioReactor.java +++ b/reactor/src/main/java/com/iluwatar/reactor/framework/NioReactor.java @@ -42,9 +42,8 @@ import lombok.extern.slf4j.Slf4j; * synchronously de-multiplexes the event which can be any of read, write or accept, and dispatches * the event to the appropriate {@link ChannelHandler} using the {@link Dispatcher}. * - *

Implementation: A NIO reactor runs in its own thread when it is started using {@link - * #start()} method. {@link NioReactor} uses {@link Selector} for realizing Synchronous Event - * De-multiplexing. + *

Implementation: A NIO reactor runs in its own thread when it is started using {@link #start()} + * method. {@link NioReactor} uses {@link Selector} for realizing Synchronous Event De-multiplexing. * *

NOTE: This is one of the ways to implement NIO reactor, and it does not take care of all * possible edge cases which are required in a real application. This implementation is meant to @@ -55,6 +54,7 @@ public class NioReactor { private final Selector selector; private final Dispatcher dispatcher; + /** * All the work of altering the SelectionKey operations and Selector operations are performed in * the context of main event loop of reactor. So when any channel needs to change its readability @@ -62,6 +62,7 @@ public class NioReactor { * the command and executes it in next iteration. */ private final Queue pendingCommands = new ConcurrentLinkedQueue<>(); + private final ExecutorService reactorMain = Executors.newSingleThreadExecutor(); /** @@ -76,25 +77,24 @@ public class NioReactor { this.selector = Selector.open(); } - /** - * Starts the reactor event loop in a new thread. - */ + /** Starts the reactor event loop in a new thread. */ public void start() { - reactorMain.execute(() -> { - try { - LOGGER.info("Reactor started, waiting for events..."); - eventLoop(); - } catch (IOException e) { - LOGGER.error("exception in event loop", e); - } - }); + reactorMain.execute( + () -> { + try { + LOGGER.info("Reactor started, waiting for events..."); + eventLoop(); + } catch (IOException e) { + LOGGER.error("exception in event loop", e); + } + }); } /** * Stops the reactor and related resources such as dispatcher. * * @throws InterruptedException if interrupted while stopping the reactor. - * @throws IOException if any I/O error occurs. + * @throws IOException if any I/O error occurs. */ public void stop() throws InterruptedException, IOException { reactorMain.shutdown(); @@ -112,7 +112,7 @@ public class NioReactor { * AbstractNioChannel#getInterestedOps()} to know about the interested operation of this channel. * * @param channel a new channel on which reactor will wait for events. The channel must be bound - * prior to being registered. + * prior to being registered. * @return this * @throws IOException if any I/O error occurs. */ @@ -217,7 +217,7 @@ public class NioReactor { *

This is a non-blocking method and does not guarantee that the operations have changed when * this method returns. * - * @param key the key for which operations have to be changed. + * @param key the key for which operations have to be changed. * @param interestedOps the new interest operations. */ public void changeOps(SelectionKey key, int interestedOps) { @@ -225,9 +225,7 @@ public class NioReactor { selector.wakeup(); } - /** - * A command that changes the interested operations of the key provided. - */ + /** A command that changes the interested operations of the key provided. */ static class ChangeKeyOpsCommand implements Runnable { private final SelectionKey key; private final int interestedOps; diff --git a/reactor/src/main/java/com/iluwatar/reactor/framework/NioServerSocketChannel.java b/reactor/src/main/java/com/iluwatar/reactor/framework/NioServerSocketChannel.java index bc512f1c9..3e56b3fe6 100644 --- a/reactor/src/main/java/com/iluwatar/reactor/framework/NioServerSocketChannel.java +++ b/reactor/src/main/java/com/iluwatar/reactor/framework/NioServerSocketChannel.java @@ -43,13 +43,13 @@ public class NioServerSocketChannel extends AbstractNioChannel { private final int port; /** - * Creates a {@link ServerSocketChannel} which will bind at provided port and use - * handler to handle incoming events on this channel. + * Creates a {@link ServerSocketChannel} which will bind at provided port and use handler + * to handle incoming events on this channel. * *

Note the constructor does not bind the socket, {@link #bind()} method should be called for * binding the socket. * - * @param port the port on which channel will be bound to accept incoming connection requests. + * @param port the port on which channel will be bound to accept incoming connection requests. * @param handler the handler that will handle incoming requests on this channel. * @throws IOException if any I/O error occurs. */ @@ -58,7 +58,6 @@ public class NioServerSocketChannel extends AbstractNioChannel { this.port = port; } - @Override public int getInterestedOps() { // being a server socket channel it is interested in accepting connection from remote peers. diff --git a/reactor/src/main/java/com/iluwatar/reactor/framework/SameThreadDispatcher.java b/reactor/src/main/java/com/iluwatar/reactor/framework/SameThreadDispatcher.java index b075c71b6..b06fe8a66 100644 --- a/reactor/src/main/java/com/iluwatar/reactor/framework/SameThreadDispatcher.java +++ b/reactor/src/main/java/com/iluwatar/reactor/framework/SameThreadDispatcher.java @@ -38,8 +38,9 @@ import java.nio.channels.SelectionKey; public class SameThreadDispatcher implements Dispatcher { /** - * Dispatches the read event in the context of caller thread.
Note this is a blocking call. - * It returns only after the associated handler has handled the read event. + * Dispatches the read event in the context of caller thread.
+ * Note this is a blocking call. It returns only after the associated handler has handled the read + * event. */ @Override public void onChannelReadEvent(AbstractNioChannel channel, Object readObject, SelectionKey key) { @@ -50,9 +51,7 @@ public class SameThreadDispatcher implements Dispatcher { channel.getHandler().handleChannelRead(channel, readObject, key); } - /** - * No resources to free. - */ + /** No resources to free. */ @Override public void stop() { // no-op diff --git a/reactor/src/main/java/com/iluwatar/reactor/framework/ThreadPoolDispatcher.java b/reactor/src/main/java/com/iluwatar/reactor/framework/ThreadPoolDispatcher.java index c6c479d35..b202c9003 100644 --- a/reactor/src/main/java/com/iluwatar/reactor/framework/ThreadPoolDispatcher.java +++ b/reactor/src/main/java/com/iluwatar/reactor/framework/ThreadPoolDispatcher.java @@ -49,8 +49,9 @@ public class ThreadPoolDispatcher implements Dispatcher { /** * Submits the work of dispatching the read event to worker pool, where it gets picked up by - * worker threads.
Note that this is a non-blocking call and returns immediately. It is not - * guaranteed that the event has been handled by associated handler. + * worker threads.
+ * Note that this is a non-blocking call and returns immediately. It is not guaranteed that the + * event has been handled by associated handler. */ @Override public void onChannelReadEvent(AbstractNioChannel channel, Object readObject, SelectionKey key) { diff --git a/reactor/src/test/java/com/iluwatar/reactor/app/ReactorTest.java b/reactor/src/test/java/com/iluwatar/reactor/app/ReactorTest.java index cb9fd970d..79d4ffa59 100644 --- a/reactor/src/test/java/com/iluwatar/reactor/app/ReactorTest.java +++ b/reactor/src/test/java/com/iluwatar/reactor/app/ReactorTest.java @@ -42,7 +42,7 @@ class ReactorTest { /** * Test the application using pooled thread dispatcher. * - * @throws IOException if any I/O error occurs. + * @throws IOException if any I/O error occurs. * @throws InterruptedException if interrupted while stopping the application. */ @Test @@ -74,7 +74,7 @@ class ReactorTest { /** * Test the application using same thread dispatcher. * - * @throws IOException if any I/O error occurs. + * @throws IOException if any I/O error occurs. * @throws InterruptedException if interrupted while stopping the application. */ @Test diff --git a/registry/pom.xml b/registry/pom.xml index ec6431452..1063e5337 100644 --- a/registry/pom.xml +++ b/registry/pom.xml @@ -34,6 +34,14 @@ registry + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/registry/src/main/java/com/iluwatar/registry/App.java b/registry/src/main/java/com/iluwatar/registry/App.java index 1a9c5234b..8e463a67c 100644 --- a/registry/src/main/java/com/iluwatar/registry/App.java +++ b/registry/src/main/java/com/iluwatar/registry/App.java @@ -28,11 +28,11 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * In Registry pattern, objects of a single class are stored and provide a global point of access to them. - * Note that there is no restriction on the number of objects. - * - *

The given example {@link CustomerRegistry} represents the registry used to store and - * access {@link Customer} objects.

+ * In Registry pattern, objects of a single class are stored and provide a global point of access to + * them. Note that there is no restriction on the number of objects. + * + *

The given example {@link CustomerRegistry} represents the registry used to store and access + * {@link Customer} objects. */ public class App { @@ -54,5 +54,4 @@ public class App { LOGGER.info("John {}", customerRegistry.getCustomer("1")); LOGGER.info("Julia {}", customerRegistry.getCustomer("2")); } - } diff --git a/registry/src/main/java/com/iluwatar/registry/Customer.java b/registry/src/main/java/com/iluwatar/registry/Customer.java index 75dd42a5f..8998624ab 100644 --- a/registry/src/main/java/com/iluwatar/registry/Customer.java +++ b/registry/src/main/java/com/iluwatar/registry/Customer.java @@ -24,16 +24,11 @@ */ package com.iluwatar.registry; -/** - * Customer entity used in registry pattern example. - */ +/** Customer entity used in registry pattern example. */ public record Customer(String id, String name) { @Override public String toString() { - return "Customer{" - + "id='" + id + '\'' - + ", name='" + name + '\'' - + '}'; + return "Customer{" + "id='" + id + '\'' + ", name='" + name + '\'' + '}'; } } diff --git a/registry/src/main/java/com/iluwatar/registry/CustomerRegistry.java b/registry/src/main/java/com/iluwatar/registry/CustomerRegistry.java index ff5609911..4a3c8b2d6 100644 --- a/registry/src/main/java/com/iluwatar/registry/CustomerRegistry.java +++ b/registry/src/main/java/com/iluwatar/registry/CustomerRegistry.java @@ -28,13 +28,10 @@ import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import lombok.Getter; -/** - * CustomerRegistry class used to store/access {@link Customer} objects. - */ +/** CustomerRegistry class used to store/access {@link Customer} objects. */ public final class CustomerRegistry { - @Getter - private static final CustomerRegistry instance = new CustomerRegistry(); + @Getter private static final CustomerRegistry instance = new CustomerRegistry(); private final Map customerMap; @@ -49,5 +46,4 @@ public final class CustomerRegistry { public Customer getCustomer(String id) { return customerMap.get(id); } - } diff --git a/registry/src/test/java/com/iluwatar/registry/CustomerRegistryTest.java b/registry/src/test/java/com/iluwatar/registry/CustomerRegistryTest.java index af0697c45..48edaa6e2 100644 --- a/registry/src/test/java/com/iluwatar/registry/CustomerRegistryTest.java +++ b/registry/src/test/java/com/iluwatar/registry/CustomerRegistryTest.java @@ -24,13 +24,13 @@ */ package com.iluwatar.registry; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + class CustomerRegistryTest { private static CustomerRegistry customerRegistry; diff --git a/repository/pom.xml b/repository/pom.xml index 6bd1b9a6a..108c64a68 100644 --- a/repository/pom.xml +++ b/repository/pom.xml @@ -33,26 +33,15 @@ 1.26.0-SNAPSHOT repository - - - - org.springframework.boot - spring-boot-dependencies - pom - 3.2.3 - import - - - org.hibernate - hibernate-core - 6.4.4.Final - - - + + org.springframework.boot + spring-boot-starter + org.springframework.data spring-data-jpa + 3.4.4 org.hibernate @@ -74,14 +63,22 @@ jakarta.xml.bind jakarta.xml.bind-api + 4.0.2 jakarta.annotation jakarta.annotation-api + 2.1.1 org.springframework.boot spring-boot-starter-test + test + + + org.hibernate + hibernate-core + 6.4.4.Final diff --git a/repository/src/main/java/com/iluwatar/repository/App.java b/repository/src/main/java/com/iluwatar/repository/App.java index d7aba4dee..53d4b04cc 100644 --- a/repository/src/main/java/com/iluwatar/repository/App.java +++ b/repository/src/main/java/com/iluwatar/repository/App.java @@ -101,6 +101,5 @@ public class App { repository.deleteAll(); context.close(); - } } diff --git a/repository/src/main/java/com/iluwatar/repository/AppConfig.java b/repository/src/main/java/com/iluwatar/repository/AppConfig.java index 1ba9d5eaf..121399fcd 100644 --- a/repository/src/main/java/com/iluwatar/repository/AppConfig.java +++ b/repository/src/main/java/com/iluwatar/repository/AppConfig.java @@ -60,9 +60,7 @@ public class AppConfig { return basicDataSource; } - /** - * Factory to create a specific instance of Entity Manager. - */ + /** Factory to create a specific instance of Entity Manager. */ @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory() { var entityManager = new LocalContainerEntityManagerFactoryBean(); @@ -73,9 +71,7 @@ public class AppConfig { return entityManager; } - /** - * Properties for Jpa. - */ + /** Properties for Jpa. */ private static Properties jpaProperties() { var properties = new Properties(); properties.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect"); @@ -83,9 +79,7 @@ public class AppConfig { return properties; } - /** - * Get transaction manager. - */ + /** Get transaction manager. */ @Bean public JpaTransactionManager transactionManager() { var transactionManager = new JpaTransactionManager(); @@ -145,7 +139,5 @@ public class AppConfig { persons.stream().map(Person::toString).forEach(LOGGER::info); context.close(); - } - } diff --git a/repository/src/main/java/com/iluwatar/repository/Person.java b/repository/src/main/java/com/iluwatar/repository/Person.java index 923fd8f25..107b557a7 100644 --- a/repository/src/main/java/com/iluwatar/repository/Person.java +++ b/repository/src/main/java/com/iluwatar/repository/Person.java @@ -33,9 +33,7 @@ import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; -/** - * Person entity. - */ +/** Person entity. */ @ToString @EqualsAndHashCode @Setter @@ -44,20 +42,15 @@ import lombok.ToString; @NoArgsConstructor public class Person { - @Id - @GeneratedValue - private Long id; + @Id @GeneratedValue private Long id; private String name; private String surname; private int age; - /** - * Constructor. - */ + /** Constructor. */ public Person(String name, String surname, int age) { this.name = name; this.surname = surname; this.age = age; } - } diff --git a/repository/src/main/java/com/iluwatar/repository/PersonRepository.java b/repository/src/main/java/com/iluwatar/repository/PersonRepository.java index a82b14630..f67e618b6 100644 --- a/repository/src/main/java/com/iluwatar/repository/PersonRepository.java +++ b/repository/src/main/java/com/iluwatar/repository/PersonRepository.java @@ -29,9 +29,7 @@ import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; -/** - * Person repository. - */ +/** Person repository. */ @Repository public interface PersonRepository extends CrudRepository, JpaSpecificationExecutor { diff --git a/repository/src/main/java/com/iluwatar/repository/PersonSpecifications.java b/repository/src/main/java/com/iluwatar/repository/PersonSpecifications.java index ae0d6e864..193409d87 100644 --- a/repository/src/main/java/com/iluwatar/repository/PersonSpecifications.java +++ b/repository/src/main/java/com/iluwatar/repository/PersonSpecifications.java @@ -30,14 +30,10 @@ import jakarta.persistence.criteria.Predicate; import jakarta.persistence.criteria.Root; import org.springframework.data.jpa.domain.Specification; -/** - * Helper class, includes vary Specification as the abstraction of sql query criteria. - */ +/** Helper class, includes vary Specification as the abstraction of sql query criteria. */ public class PersonSpecifications { - /** - * Specifications stating the Between (From - To) Age Specification. - */ + /** Specifications stating the Between (From - To) Age Specification. */ public static class AgeBetweenSpec implements Specification { private final int from; @@ -53,12 +49,9 @@ public class PersonSpecifications { public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder cb) { return cb.between(root.get("age"), from, to); } - } - /** - * Name specification. - */ + /** Name specification. */ public static class NameEqualSpec implements Specification { public final String name; @@ -67,12 +60,9 @@ public class PersonSpecifications { this.name = name; } - /** - * Get predicate. - */ + /** Get predicate. */ public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder cb) { return cb.equal(root.get("name"), this.name); } } - } diff --git a/repository/src/test/java/com/iluwatar/repository/AnnotationBasedRepositoryTest.java b/repository/src/test/java/com/iluwatar/repository/AnnotationBasedRepositoryTest.java index 1843a42cc..66d5d9916 100644 --- a/repository/src/test/java/com/iluwatar/repository/AnnotationBasedRepositoryTest.java +++ b/repository/src/test/java/com/iluwatar/repository/AnnotationBasedRepositoryTest.java @@ -28,8 +28,8 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; -import java.util.List; import jakarta.annotation.Resource; +import java.util.List; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -45,8 +45,7 @@ import org.springframework.test.context.junit.jupiter.SpringExtension; @SpringBootTest(classes = {AppConfig.class}) class AnnotationBasedRepositoryTest { - @Resource - private PersonRepository repository; + @Resource private PersonRepository repository; private final Person peter = new Person("Peter", "Sagan", 17); private final Person nasta = new Person("Nasta", "Kuzminova", 25); @@ -55,9 +54,7 @@ class AnnotationBasedRepositoryTest { private final List persons = List.of(peter, nasta, john, terry); - /** - * Prepare data for test - */ + /** Prepare data for test */ @BeforeEach void setup() { repository.saveAll(persons); @@ -114,5 +111,4 @@ class AnnotationBasedRepositoryTest { void cleanup() { repository.deleteAll(); } - } diff --git a/repository/src/test/java/com/iluwatar/repository/AppConfigTest.java b/repository/src/test/java/com/iluwatar/repository/AppConfigTest.java index 66c7adc07..27b18d9e0 100644 --- a/repository/src/test/java/com/iluwatar/repository/AppConfigTest.java +++ b/repository/src/test/java/com/iluwatar/repository/AppConfigTest.java @@ -36,27 +36,20 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.transaction.annotation.Transactional; -/** - * This case is Just for test the Annotation Based configuration - */ +/** This case is Just for test the Annotation Based configuration */ @ExtendWith(SpringExtension.class) @SpringBootTest(classes = {AppConfig.class}) class AppConfigTest { - @Autowired - DataSource dataSource; + @Autowired DataSource dataSource; - /** - * Test for bean instance - */ + /** Test for bean instance */ @Test void testDataSource() { assertNotNull(dataSource); } - /** - * Test for correct query execution - */ + /** Test for correct query execution */ @Test @Transactional void testQuery() throws SQLException { diff --git a/repository/src/test/java/com/iluwatar/repository/AppTest.java b/repository/src/test/java/com/iluwatar/repository/AppTest.java index e9687dd38..600085930 100644 --- a/repository/src/test/java/com/iluwatar/repository/AppTest.java +++ b/repository/src/test/java/com/iluwatar/repository/AppTest.java @@ -24,17 +24,15 @@ */ package com.iluwatar.repository; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -/** - * Tests that Repository example runs without errors. - */ +import org.junit.jupiter.api.Test; + +/** Tests that Repository example runs without errors. */ class AppTest { @Test void shouldExecuteWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/repository/src/test/java/com/iluwatar/repository/RepositoryTest.java b/repository/src/test/java/com/iluwatar/repository/RepositoryTest.java index 745fc9bc5..226e3745c 100644 --- a/repository/src/test/java/com/iluwatar/repository/RepositoryTest.java +++ b/repository/src/test/java/com/iluwatar/repository/RepositoryTest.java @@ -28,8 +28,8 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; -import java.util.List; import jakarta.annotation.Resource; +import java.util.List; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -45,8 +45,7 @@ import org.springframework.test.context.junit.jupiter.SpringExtension; @SpringBootTest(properties = {"locations=classpath:applicationContext.xml"}) class RepositoryTest { - @Resource - private PersonRepository repository; + @Resource private PersonRepository repository; private final Person peter = new Person("Peter", "Sagan", 17); private final Person nasta = new Person("Nasta", "Kuzminova", 25); @@ -55,9 +54,7 @@ class RepositoryTest { private final List persons = List.of(peter, nasta, john, terry); - /** - * Prepare data for test - */ + /** Prepare data for test */ @BeforeEach void setup() { repository.saveAll(persons); @@ -114,5 +111,4 @@ class RepositoryTest { void cleanup() { repository.deleteAll(); } - } diff --git a/resource-acquisition-is-initialization/pom.xml b/resource-acquisition-is-initialization/pom.xml index c8061093a..465f7316e 100644 --- a/resource-acquisition-is-initialization/pom.xml +++ b/resource-acquisition-is-initialization/pom.xml @@ -34,6 +34,14 @@ resource-acquisition-is-initialization + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/resource-acquisition-is-initialization/src/main/java/com/iluwatar/resource/acquisition/is/initialization/App.java b/resource-acquisition-is-initialization/src/main/java/com/iluwatar/resource/acquisition/is/initialization/App.java index 49b1d48d1..d2bb59613 100644 --- a/resource-acquisition-is-initialization/src/main/java/com/iluwatar/resource/acquisition/is/initialization/App.java +++ b/resource-acquisition-is-initialization/src/main/java/com/iluwatar/resource/acquisition/is/initialization/App.java @@ -48,9 +48,7 @@ import lombok.extern.slf4j.Slf4j; @Slf4j public class App { - /** - * Program entry point. - */ + /** Program entry point. */ public static void main(String[] args) { try (var ignored = new SlidingDoor()) { diff --git a/resource-acquisition-is-initialization/src/main/java/com/iluwatar/resource/acquisition/is/initialization/SlidingDoor.java b/resource-acquisition-is-initialization/src/main/java/com/iluwatar/resource/acquisition/is/initialization/SlidingDoor.java index f29bdefba..8d4347df6 100644 --- a/resource-acquisition-is-initialization/src/main/java/com/iluwatar/resource/acquisition/is/initialization/SlidingDoor.java +++ b/resource-acquisition-is-initialization/src/main/java/com/iluwatar/resource/acquisition/is/initialization/SlidingDoor.java @@ -26,9 +26,7 @@ package com.iluwatar.resource.acquisition.is.initialization; import lombok.extern.slf4j.Slf4j; -/** - * SlidingDoor resource. - */ +/** SlidingDoor resource. */ @Slf4j public class SlidingDoor implements AutoCloseable { diff --git a/resource-acquisition-is-initialization/src/main/java/com/iluwatar/resource/acquisition/is/initialization/TreasureChest.java b/resource-acquisition-is-initialization/src/main/java/com/iluwatar/resource/acquisition/is/initialization/TreasureChest.java index 4085ee651..5c71261d2 100644 --- a/resource-acquisition-is-initialization/src/main/java/com/iluwatar/resource/acquisition/is/initialization/TreasureChest.java +++ b/resource-acquisition-is-initialization/src/main/java/com/iluwatar/resource/acquisition/is/initialization/TreasureChest.java @@ -27,9 +27,7 @@ package com.iluwatar.resource.acquisition.is.initialization; import java.io.Closeable; import lombok.extern.slf4j.Slf4j; -/** - * TreasureChest resource. - */ +/** TreasureChest resource. */ @Slf4j public class TreasureChest implements Closeable { diff --git a/resource-acquisition-is-initialization/src/test/java/com/iluwatar/resource/acquisition/is/initialization/AppTest.java b/resource-acquisition-is-initialization/src/test/java/com/iluwatar/resource/acquisition/is/initialization/AppTest.java index 06d8af823..dbd0979a0 100644 --- a/resource-acquisition-is-initialization/src/test/java/com/iluwatar/resource/acquisition/is/initialization/AppTest.java +++ b/resource-acquisition-is-initialization/src/test/java/com/iluwatar/resource/acquisition/is/initialization/AppTest.java @@ -24,17 +24,15 @@ */ package com.iluwatar.resource.acquisition.is.initialization; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -/** - * Application test - */ +import org.junit.jupiter.api.Test; + +/** Application test */ class AppTest { @Test void shouldExecuteWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } } 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 fae377358..0b4c42949 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 @@ -36,10 +36,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.slf4j.LoggerFactory; -/** - * ClosableTest - * - */ +/** ClosableTest */ class ClosableTest { private InMemoryAppender appender; @@ -56,7 +53,8 @@ class ClosableTest { @Test void testOpenClose() { - try (final var ignored = new SlidingDoor(); final var ignored1 = new TreasureChest()) { + try (final var ignored = new SlidingDoor(); + final var ignored1 = new TreasureChest()) { assertTrue(appender.logContains("Sliding door opens.")); assertTrue(appender.logContains("Treasure chest opens.")); } @@ -64,9 +62,7 @@ class ClosableTest { assertTrue(appender.logContains("Sliding door closes.")); } - /** - * Logging Appender Implementation - */ + /** Logging Appender Implementation */ static class InMemoryAppender extends AppenderBase { private final List log = new LinkedList<>(); diff --git a/retry/pom.xml b/retry/pom.xml index 331feb316..ba2248eeb 100644 --- a/retry/pom.xml +++ b/retry/pom.xml @@ -35,6 +35,14 @@ retry jar + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine @@ -43,6 +51,7 @@ org.hamcrest hamcrest-core + 3.0 test diff --git a/retry/src/main/java/com/iluwatar/retry/App.java b/retry/src/main/java/com/iluwatar/retry/App.java index 0d64239dc..2fdcbdc92 100644 --- a/retry/src/main/java/com/iluwatar/retry/App.java +++ b/retry/src/main/java/com/iluwatar/retry/App.java @@ -37,19 +37,19 @@ import org.slf4j.LoggerFactory; * operations that our application performs involving remote systems. The calling code should remain * decoupled from implementations. * - *

{@link FindCustomer} is a business operation that looks up a customer's record and returns - * its ID. Imagine its job is performed by looking up the customer in our local database and - * returning its ID. We can pass {@link CustomerNotFoundException} as one of its {@link + *

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

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

To keep the calling code as decoupled as possible from this workaround, we have implemented * the retry mechanism as a {@link BusinessOperation} named {@link Retry}. @@ -91,32 +91,34 @@ public final class App { } private static void errorWithRetry() throws Exception { - final var retry = new Retry<>( - new FindCustomer("123", new CustomerNotFoundException(NOT_FOUND)), - 3, //3 attempts - 100, //100 ms delay between attempts - e -> CustomerNotFoundException.class.isAssignableFrom(e.getClass()) - ); + final var retry = + new Retry<>( + new FindCustomer("123", new CustomerNotFoundException(NOT_FOUND)), + 3, // 3 attempts + 100, // 100 ms delay between attempts + e -> CustomerNotFoundException.class.isAssignableFrom(e.getClass())); op = retry; final var customerId = op.perform(); - LOG.info(String.format( - "However, retrying the operation while ignoring a recoverable error will eventually yield " - + "the result %s after a number of attempts %s", customerId, retry.attempts() - )); + LOG.info( + String.format( + "However, retrying the operation while ignoring a recoverable error will eventually yield " + + "the result %s after a number of attempts %s", + customerId, retry.attempts())); } private static void errorWithRetryExponentialBackoff() throws Exception { - final var retry = new RetryExponentialBackoff<>( - new FindCustomer("123", new CustomerNotFoundException(NOT_FOUND)), - 6, //6 attempts - 30000, //30 s max delay between attempts - e -> CustomerNotFoundException.class.isAssignableFrom(e.getClass()) - ); + final var retry = + new RetryExponentialBackoff<>( + new FindCustomer("123", new CustomerNotFoundException(NOT_FOUND)), + 6, // 6 attempts + 30000, // 30 s max delay between attempts + e -> CustomerNotFoundException.class.isAssignableFrom(e.getClass())); op = retry; final var customerId = op.perform(); - LOG.info(String.format( - "However, retrying the operation while ignoring a recoverable error will eventually yield " - + "the result %s after a number of attempts %s", customerId, retry.attempts() - )); + LOG.info( + String.format( + "However, retrying the operation while ignoring a recoverable error will eventually yield " + + "the result %s after a number of attempts %s", + customerId, retry.attempts())); } } diff --git a/retry/src/main/java/com/iluwatar/retry/BusinessException.java b/retry/src/main/java/com/iluwatar/retry/BusinessException.java index c652d48cb..e4912c69a 100644 --- a/retry/src/main/java/com/iluwatar/retry/BusinessException.java +++ b/retry/src/main/java/com/iluwatar/retry/BusinessException.java @@ -31,11 +31,9 @@ import java.io.Serial; * occurred. Its use is reserved as a "catch-all" for cases where no other subtype captures the * specificity of the error condition in question. Calling code is not expected to be able to handle * this error and should be reported to the maintainers immediately. - * */ public class BusinessException extends Exception { - @Serial - private static final long serialVersionUID = 6235833142062144336L; + @Serial private static final long serialVersionUID = 6235833142062144336L; /** * Ctor. diff --git a/retry/src/main/java/com/iluwatar/retry/BusinessOperation.java b/retry/src/main/java/com/iluwatar/retry/BusinessOperation.java index f6a61ecde..1e7edb345 100644 --- a/retry/src/main/java/com/iluwatar/retry/BusinessOperation.java +++ b/retry/src/main/java/com/iluwatar/retry/BusinessOperation.java @@ -37,7 +37,7 @@ public interface BusinessOperation { * * @return the return value * @throws BusinessException if the operation fails. Implementations are allowed to throw more - * specific subtypes depending on the error conditions + * specific subtypes depending on the error conditions */ T perform() throws BusinessException; } diff --git a/retry/src/main/java/com/iluwatar/retry/CustomerNotFoundException.java b/retry/src/main/java/com/iluwatar/retry/CustomerNotFoundException.java index b469d9e7c..222b251c3 100644 --- a/retry/src/main/java/com/iluwatar/retry/CustomerNotFoundException.java +++ b/retry/src/main/java/com/iluwatar/retry/CustomerNotFoundException.java @@ -32,12 +32,10 @@ import java.io.Serial; *

The severity of this error is bounded by its context: was the search for the customer * triggered by an input from some end user, or were the search parameters pulled from your * database? - * */ public final class CustomerNotFoundException extends BusinessException { - @Serial - private static final long serialVersionUID = -6972888602621778664L; + @Serial private static final long serialVersionUID = -6972888602621778664L; /** * Ctor. diff --git a/retry/src/main/java/com/iluwatar/retry/DatabaseNotAvailableException.java b/retry/src/main/java/com/iluwatar/retry/DatabaseNotAvailableException.java index 16d75b74d..24a71a22d 100644 --- a/retry/src/main/java/com/iluwatar/retry/DatabaseNotAvailableException.java +++ b/retry/src/main/java/com/iluwatar/retry/DatabaseNotAvailableException.java @@ -26,13 +26,9 @@ package com.iluwatar.retry; import java.io.Serial; -/** - * Catastrophic error indicating that we have lost connection to our database. - * - */ +/** Catastrophic error indicating that we have lost connection to our database. */ public final class DatabaseNotAvailableException extends BusinessException { - @Serial - private static final long serialVersionUID = -3750769625095997799L; + @Serial private static final long serialVersionUID = -3750769625095997799L; /** * Ctor. diff --git a/retry/src/main/java/com/iluwatar/retry/FindCustomer.java b/retry/src/main/java/com/iluwatar/retry/FindCustomer.java index 1dde9d561..b827935de 100644 --- a/retry/src/main/java/com/iluwatar/retry/FindCustomer.java +++ b/retry/src/main/java/com/iluwatar/retry/FindCustomer.java @@ -34,13 +34,13 @@ import java.util.List; *

This is an imaginary operation that, for some imagined input, returns the ID for a customer. * However, this is a "flaky" operation that is supposed to fail intermittently, but for the * purposes of this example it fails in a programmed way depending on the constructor parameters. - * */ - -public record FindCustomer(String customerId, Deque errors) implements BusinessOperation { +public record FindCustomer(String customerId, Deque errors) + implements BusinessOperation { public FindCustomer(String customerId, BusinessException... errors) { this(customerId, new ArrayDeque<>(List.of(errors))); } + @Override public String perform() throws BusinessException { if (!this.errors.isEmpty()) { diff --git a/retry/src/main/java/com/iluwatar/retry/Retry.java b/retry/src/main/java/com/iluwatar/retry/Retry.java index ad9580454..fb0e6c6c8 100644 --- a/retry/src/main/java/com/iluwatar/retry/Retry.java +++ b/retry/src/main/java/com/iluwatar/retry/Retry.java @@ -47,19 +47,15 @@ public final class Retry implements BusinessOperation { /** * Ctor. * - * @param op the {@link BusinessOperation} to retry + * @param op the {@link BusinessOperation} to retry * @param maxAttempts number of times to retry - * @param delay delay (in milliseconds) between attempts + * @param delay delay (in milliseconds) between attempts * @param ignoreTests tests to check whether the remote exception can be ignored. No exceptions - * will be ignored if no tests are given + * will be ignored if no tests are given */ @SafeVarargs public Retry( - BusinessOperation op, - int maxAttempts, - long delay, - Predicate... ignoreTests - ) { + BusinessOperation op, int maxAttempts, long delay, Predicate... ignoreTests) { this.op = op; this.maxAttempts = maxAttempts; this.delay = delay; @@ -101,7 +97,7 @@ public final class Retry implements BusinessOperation { try { Thread.sleep(this.delay); } catch (InterruptedException f) { - //ignore + // ignore } } } while (true); diff --git a/retry/src/main/java/com/iluwatar/retry/RetryExponentialBackoff.java b/retry/src/main/java/com/iluwatar/retry/RetryExponentialBackoff.java index 1661095b7..024097b6b 100644 --- a/retry/src/main/java/com/iluwatar/retry/RetryExponentialBackoff.java +++ b/retry/src/main/java/com/iluwatar/retry/RetryExponentialBackoff.java @@ -49,18 +49,17 @@ public final class RetryExponentialBackoff implements BusinessOperation { /** * Ctor. * - * @param op the {@link BusinessOperation} to retry + * @param op the {@link BusinessOperation} to retry * @param maxAttempts number of times to retry * @param ignoreTests tests to check whether the remote exception can be ignored. No exceptions - * will be ignored if no tests are given + * will be ignored if no tests are given */ @SafeVarargs public RetryExponentialBackoff( BusinessOperation op, int maxAttempts, long maxDelay, - Predicate... ignoreTests - ) { + Predicate... ignoreTests) { this.op = op; this.maxAttempts = maxAttempts; this.maxDelay = maxDelay; @@ -104,7 +103,7 @@ public final class RetryExponentialBackoff implements BusinessOperation { var delay = Math.min(testDelay, this.maxDelay); Thread.sleep(delay); } catch (InterruptedException f) { - //ignore + // ignore } } } while (true); diff --git a/retry/src/test/java/com/iluwatar/retry/FindCustomerTest.java b/retry/src/test/java/com/iluwatar/retry/FindCustomerTest.java index 3abd4f4e3..95ddba4bd 100644 --- a/retry/src/test/java/com/iluwatar/retry/FindCustomerTest.java +++ b/retry/src/test/java/com/iluwatar/retry/FindCustomerTest.java @@ -30,22 +30,15 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import org.junit.jupiter.api.Test; -/** - * Unit tests for {@link FindCustomer}. - * - */ +/** Unit tests for {@link FindCustomer}. */ class FindCustomerTest { - /** - * Returns the given result with no exceptions. - */ + /** Returns the given result with no exceptions. */ @Test void noExceptions() throws Exception { assertThat(new FindCustomer("123").perform(), is("123")); } - /** - * Throws the given exception. - */ + /** Throws the given exception. */ @Test void oneException() { var findCustomer = new FindCustomer("123", new BusinessException("test")); @@ -59,20 +52,20 @@ class FindCustomerTest { */ @Test void resultAfterExceptions() throws Exception { - final var op = new FindCustomer( - "123", - new CustomerNotFoundException("not found"), - new DatabaseNotAvailableException("not available") - ); + final var op = + new FindCustomer( + "123", + new CustomerNotFoundException("not found"), + new DatabaseNotAvailableException("not available")); try { op.perform(); } catch (CustomerNotFoundException e) { - //ignore + // ignore } try { op.perform(); } catch (DatabaseNotAvailableException e) { - //ignore + // ignore } assertThat(op.perform(), is("123")); diff --git a/retry/src/test/java/com/iluwatar/retry/RetryExponentialBackoffTest.java b/retry/src/test/java/com/iluwatar/retry/RetryExponentialBackoffTest.java index 085a1bd44..ceec4f523 100644 --- a/retry/src/test/java/com/iluwatar/retry/RetryExponentialBackoffTest.java +++ b/retry/src/test/java/com/iluwatar/retry/RetryExponentialBackoffTest.java @@ -30,28 +30,23 @@ import static org.hamcrest.MatcherAssert.assertThat; import org.junit.jupiter.api.Test; -/** - * Unit tests for {@link Retry}. - * - */ +/** Unit tests for {@link Retry}. */ class RetryExponentialBackoffTest { - /** - * Should contain all errors thrown. - */ + /** Should contain all errors thrown. */ @Test void errors() { final var e = new BusinessException("unhandled"); - final var retry = new RetryExponentialBackoff( - () -> { - throw e; - }, - 2, - 0 - ); + final var retry = + new RetryExponentialBackoff( + () -> { + throw e; + }, + 2, + 0); try { retry.perform(); } catch (BusinessException ex) { - //ignore + // ignore } assertThat(retry.errors(), hasItem(e)); @@ -64,17 +59,17 @@ class RetryExponentialBackoffTest { @Test void attempts() { final var e = new BusinessException("unhandled"); - final var retry = new RetryExponentialBackoff( - () -> { - throw e; - }, - 2, - 0 - ); + final var retry = + new RetryExponentialBackoff( + () -> { + throw e; + }, + 2, + 0); try { retry.perform(); } catch (BusinessException ex) { - //ignore + // ignore } assertThat(retry.attempts(), is(1)); @@ -87,18 +82,18 @@ class RetryExponentialBackoffTest { @Test void ignore() { final var e = new CustomerNotFoundException("customer not found"); - final var retry = new RetryExponentialBackoff( - () -> { - throw e; - }, - 2, - 0, - ex -> CustomerNotFoundException.class.isAssignableFrom(ex.getClass()) - ); + final var retry = + new RetryExponentialBackoff( + () -> { + throw e; + }, + 2, + 0, + ex -> CustomerNotFoundException.class.isAssignableFrom(ex.getClass())); try { retry.perform(); } catch (BusinessException ex) { - //ignore + // ignore } assertThat(retry.attempts(), is(2)); diff --git a/retry/src/test/java/com/iluwatar/retry/RetryTest.java b/retry/src/test/java/com/iluwatar/retry/RetryTest.java index b400ef5e0..c7f753ccb 100644 --- a/retry/src/test/java/com/iluwatar/retry/RetryTest.java +++ b/retry/src/test/java/com/iluwatar/retry/RetryTest.java @@ -30,29 +30,24 @@ import static org.hamcrest.MatcherAssert.assertThat; import org.junit.jupiter.api.Test; -/** - * Unit tests for {@link Retry}. - * - */ +/** Unit tests for {@link Retry}. */ class RetryTest { - /** - * Should contain all errors thrown. - */ + /** Should contain all errors thrown. */ @Test void errors() { final var e = new BusinessException("unhandled"); - final var retry = new Retry( - () -> { - throw e; - }, - 2, - 0 - ); + final var retry = + new Retry( + () -> { + throw e; + }, + 2, + 0); try { retry.perform(); } catch (BusinessException ex) { - //ignore + // ignore } assertThat(retry.errors(), hasItem(e)); @@ -65,17 +60,17 @@ class RetryTest { @Test void attempts() { final var e = new BusinessException("unhandled"); - final var retry = new Retry( - () -> { - throw e; - }, - 2, - 0 - ); + final var retry = + new Retry( + () -> { + throw e; + }, + 2, + 0); try { retry.perform(); } catch (BusinessException ex) { - //ignore + // ignore } assertThat(retry.attempts(), is(1)); @@ -88,21 +83,20 @@ class RetryTest { @Test void ignore() { final var e = new CustomerNotFoundException("customer not found"); - final var retry = new Retry( - () -> { - throw e; - }, - 2, - 0, - ex -> CustomerNotFoundException.class.isAssignableFrom(ex.getClass()) - ); + final var retry = + new Retry( + () -> { + throw e; + }, + 2, + 0, + ex -> CustomerNotFoundException.class.isAssignableFrom(ex.getClass())); try { retry.perform(); } catch (BusinessException ex) { - //ignore + // ignore } assertThat(retry.attempts(), is(2)); } - -} \ No newline at end of file +} diff --git a/role-object/pom.xml b/role-object/pom.xml index 066c1bfb6..3c75482e8 100644 --- a/role-object/pom.xml +++ b/role-object/pom.xml @@ -34,6 +34,14 @@ role-object + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/role-object/src/main/java/com/iluwatar/roleobject/ApplicationRoleObject.java b/role-object/src/main/java/com/iluwatar/roleobject/ApplicationRoleObject.java index 178ac9e6b..125fc24af 100644 --- a/role-object/src/main/java/com/iluwatar/roleobject/ApplicationRoleObject.java +++ b/role-object/src/main/java/com/iluwatar/roleobject/ApplicationRoleObject.java @@ -39,22 +39,22 @@ import lombok.extern.slf4j.Slf4j; * customer-specific roles is provided by {@link CustomerRole}, which also supports the {@link * Customer} interface. * - *

The {@link CustomerRole} class is abstract and not meant to be instantiated. - * Concrete subclasses of {@link CustomerRole}, for example {@link BorrowerRole} or {@link - * InvestorRole}, define and implement the interface for specific roles. It is only these subclasses - * which are instantiated at runtime. The {@link BorrowerRole} class defines the context-specific - * view of {@link Customer} objects as needed by the loan department. It defines additional - * operations to manage the customer’s credits and securities. Similarly, the {@link InvestorRole} - * class adds operations specific to the investment department’s view of customers. A client like - * the loan application may either work with objects of the {@link CustomerRole} class, using the - * interface class {@link Customer}, or with objects of concrete {@link CustomerRole} subclasses. - * Suppose the loan application knows a particular {@link Customer} instance through its {@link - * Customer} interface. The loan application may want to check whether the {@link Customer} object - * plays the role of Borrower. To this end it calls {@link Customer#hasRole(Role)} with a suitable - * role specification. For the purpose of our example, let’s assume we can name roles with enum. If - * the {@link Customer} object can play the role named “Borrower,” the loan application will ask it - * to return a reference to the corresponding object. The loan application may now use this - * reference to call Borrower-specific operations. + *

The {@link CustomerRole} class is abstract and not meant to be instantiated. Concrete + * subclasses of {@link CustomerRole}, for example {@link BorrowerRole} or {@link InvestorRole}, + * define and implement the interface for specific roles. It is only these subclasses which are + * instantiated at runtime. The {@link BorrowerRole} class defines the context-specific view of + * {@link Customer} objects as needed by the loan department. It defines additional operations to + * manage the customer’s credits and securities. Similarly, the {@link InvestorRole} class adds + * operations specific to the investment department’s view of customers. A client like the loan + * application may either work with objects of the {@link CustomerRole} class, using the interface + * class {@link Customer}, or with objects of concrete {@link CustomerRole} subclasses. Suppose the + * loan application knows a particular {@link Customer} instance through its {@link Customer} + * interface. The loan application may want to check whether the {@link Customer} object plays the + * role of Borrower. To this end it calls {@link Customer#hasRole(Role)} with a suitable role + * specification. For the purpose of our example, let’s assume we can name roles with enum. If the + * {@link Customer} object can play the role named “Borrower,” the loan application will ask it to + * return a reference to the corresponding object. The loan application may now use this reference + * to call Borrower-specific operations. */ @Slf4j public class ApplicationRoleObject { @@ -74,20 +74,23 @@ public class ApplicationRoleObject { var hasInvestorRole = customer.hasRole(INVESTOR); LOGGER.info("Customer has an investor role - {}", hasInvestorRole); - customer.getRole(INVESTOR, InvestorRole.class) - .ifPresent(inv -> { - inv.setAmountToInvest(1000); - inv.setName("Billy"); - }); - customer.getRole(BORROWER, BorrowerRole.class) - .ifPresent(inv -> inv.setName("Johny")); + customer + .getRole(INVESTOR, InvestorRole.class) + .ifPresent( + inv -> { + inv.setAmountToInvest(1000); + inv.setName("Billy"); + }); + customer.getRole(BORROWER, BorrowerRole.class).ifPresent(inv -> inv.setName("Johny")); - customer.getRole(INVESTOR, InvestorRole.class) + customer + .getRole(INVESTOR, InvestorRole.class) .map(InvestorRole::invest) .ifPresent(LOGGER::info); - customer.getRole(BORROWER, BorrowerRole.class) + customer + .getRole(BORROWER, BorrowerRole.class) .map(BorrowerRole::borrow) .ifPresent(LOGGER::info); } -} \ No newline at end of file +} diff --git a/role-object/src/main/java/com/iluwatar/roleobject/BorrowerRole.java b/role-object/src/main/java/com/iluwatar/roleobject/BorrowerRole.java index 5d0b8111c..172e9d489 100644 --- a/role-object/src/main/java/com/iluwatar/roleobject/BorrowerRole.java +++ b/role-object/src/main/java/com/iluwatar/roleobject/BorrowerRole.java @@ -27,9 +27,7 @@ package com.iluwatar.roleobject; import lombok.Getter; import lombok.Setter; -/** - * Borrower role. - */ +/** Borrower role. */ @Getter @Setter public class BorrowerRole extends CustomerRole { @@ -39,5 +37,4 @@ public class BorrowerRole extends CustomerRole { public String borrow() { return String.format("Borrower %s wants to get some money.", name); } - } diff --git a/role-object/src/main/java/com/iluwatar/roleobject/Customer.java b/role-object/src/main/java/com/iluwatar/roleobject/Customer.java index 573604cbc..1b5d15592 100644 --- a/role-object/src/main/java/com/iluwatar/roleobject/Customer.java +++ b/role-object/src/main/java/com/iluwatar/roleobject/Customer.java @@ -27,9 +27,7 @@ package com.iluwatar.roleobject; import java.util.Arrays; import java.util.Optional; -/** - * The main abstraction to work with Customer. - */ +/** The main abstraction to work with Customer. */ public abstract class Customer { /** @@ -46,7 +44,6 @@ public abstract class Customer { * @param role to check * @return true if the role exists otherwise false */ - public abstract boolean hasRole(Role role); /** @@ -60,13 +57,12 @@ public abstract class Customer { /** * Get specific instance associated with this role @see {@link Role}. * - * @param role to get + * @param role to get * @param expectedRole instance class expected to get * @return optional with value if the instance exists and corresponds expected class */ public abstract Optional getRole(Role role, Class expectedRole); - public static Customer newCustomer() { return new CustomerCore(); } @@ -82,5 +78,4 @@ public abstract class Customer { Arrays.stream(role).forEach(customer::addRole); return customer; } - } diff --git a/role-object/src/main/java/com/iluwatar/roleobject/CustomerCore.java b/role-object/src/main/java/com/iluwatar/roleobject/CustomerCore.java index 04652039f..079f6cb5f 100644 --- a/role-object/src/main/java/com/iluwatar/roleobject/CustomerCore.java +++ b/role-object/src/main/java/com/iluwatar/roleobject/CustomerCore.java @@ -45,12 +45,12 @@ public class CustomerCore extends Customer { @Override public boolean addRole(Role role) { - return role - .instance() - .map(inst -> { - roles.put(role, inst); - return true; - }) + return role.instance() + .map( + inst -> { + roles.put(role, inst); + return true; + }) .orElse(false); } @@ -66,8 +66,7 @@ public class CustomerCore extends Customer { @Override public Optional getRole(Role role, Class expectedRole) { - return Optional - .ofNullable(roles.get(role)) + return Optional.ofNullable(roles.get(role)) .filter(expectedRole::isInstance) .map(expectedRole::cast); } diff --git a/role-object/src/main/java/com/iluwatar/roleobject/CustomerRole.java b/role-object/src/main/java/com/iluwatar/roleobject/CustomerRole.java index cb8ad7bb8..044c80cf8 100644 --- a/role-object/src/main/java/com/iluwatar/roleobject/CustomerRole.java +++ b/role-object/src/main/java/com/iluwatar/roleobject/CustomerRole.java @@ -24,8 +24,5 @@ */ package com.iluwatar.roleobject; -/** - * Key abstraction for segregated roles. - */ -public abstract class CustomerRole extends CustomerCore { -} +/** Key abstraction for segregated roles. */ +public abstract class CustomerRole extends CustomerCore {} diff --git a/role-object/src/main/java/com/iluwatar/roleobject/InvestorRole.java b/role-object/src/main/java/com/iluwatar/roleobject/InvestorRole.java index 1390d72f6..ef8cb73ae 100644 --- a/role-object/src/main/java/com/iluwatar/roleobject/InvestorRole.java +++ b/role-object/src/main/java/com/iluwatar/roleobject/InvestorRole.java @@ -27,9 +27,7 @@ package com.iluwatar.roleobject; import lombok.Getter; import lombok.Setter; -/** - * Investor role. - */ +/** Investor role. */ @Getter @Setter public class InvestorRole extends CustomerRole { diff --git a/role-object/src/main/java/com/iluwatar/roleobject/Role.java b/role-object/src/main/java/com/iluwatar/roleobject/Role.java index 7a681f02a..98ef516b3 100644 --- a/role-object/src/main/java/com/iluwatar/roleobject/Role.java +++ b/role-object/src/main/java/com/iluwatar/roleobject/Role.java @@ -29,12 +29,10 @@ import java.util.Optional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -/** - * Possible roles. - */ +/** Possible roles. */ public enum Role { - - BORROWER(BorrowerRole.class), INVESTOR(InvestorRole.class); + BORROWER(BorrowerRole.class), + INVESTOR(InvestorRole.class); private final Class typeCst; @@ -44,18 +42,18 @@ public enum Role { private static final Logger logger = LoggerFactory.getLogger(Role.class); - /** - * Get instance. - */ + /** Get instance. */ @SuppressWarnings("unchecked") public Optional instance() { var typeCst = this.typeCst; try { return (Optional) Optional.of(typeCst.getDeclaredConstructor().newInstance()); - } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) { + } catch (InstantiationException + | IllegalAccessException + | NoSuchMethodException + | InvocationTargetException e) { logger.error("error creating an object", e); } return Optional.empty(); } - -} \ No newline at end of file +} diff --git a/role-object/src/test/java/com/iluwatar/roleobject/ApplicationRoleObjectTest.java b/role-object/src/test/java/com/iluwatar/roleobject/ApplicationRoleObjectTest.java index 7dab58c7e..aa5be60bb 100644 --- a/role-object/src/test/java/com/iluwatar/roleobject/ApplicationRoleObjectTest.java +++ b/role-object/src/test/java/com/iluwatar/roleobject/ApplicationRoleObjectTest.java @@ -32,6 +32,6 @@ class ApplicationRoleObjectTest { @Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> ApplicationRoleObject.main(new String[]{})); + assertDoesNotThrow(() -> ApplicationRoleObject.main(new String[] {})); } -} \ No newline at end of file +} diff --git a/role-object/src/test/java/com/iluwatar/roleobject/BorrowerRoleTest.java b/role-object/src/test/java/com/iluwatar/roleobject/BorrowerRoleTest.java index 95e6c6a4e..df366db16 100644 --- a/role-object/src/test/java/com/iluwatar/roleobject/BorrowerRoleTest.java +++ b/role-object/src/test/java/com/iluwatar/roleobject/BorrowerRoleTest.java @@ -36,4 +36,4 @@ class BorrowerRoleTest { borrowerRole.setName("test"); assertEquals("Borrower test wants to get some money.", borrowerRole.borrow()); } -} \ No newline at end of file +} diff --git a/role-object/src/test/java/com/iluwatar/roleobject/CustomerCoreTest.java b/role-object/src/test/java/com/iluwatar/roleobject/CustomerCoreTest.java index 9cb10b8e1..cd9027709 100644 --- a/role-object/src/test/java/com/iluwatar/roleobject/CustomerCoreTest.java +++ b/role-object/src/test/java/com/iluwatar/roleobject/CustomerCoreTest.java @@ -88,5 +88,4 @@ class CustomerCoreTest { core = new CustomerCore(); assertEquals("Customer{roles=[]}", core.toString()); } - -} \ No newline at end of file +} diff --git a/role-object/src/test/java/com/iluwatar/roleobject/InvestorRoleTest.java b/role-object/src/test/java/com/iluwatar/roleobject/InvestorRoleTest.java index 14609c6f8..79b26ced8 100644 --- a/role-object/src/test/java/com/iluwatar/roleobject/InvestorRoleTest.java +++ b/role-object/src/test/java/com/iluwatar/roleobject/InvestorRoleTest.java @@ -37,4 +37,4 @@ class InvestorRoleTest { investorRole.setAmountToInvest(10); assertEquals("Investor test has invested 10 dollars", investorRole.invest()); } -} \ No newline at end of file +} diff --git a/role-object/src/test/java/com/iluwatar/roleobject/RoleTest.java b/role-object/src/test/java/com/iluwatar/roleobject/RoleTest.java index 503685180..825dc6fea 100644 --- a/role-object/src/test/java/com/iluwatar/roleobject/RoleTest.java +++ b/role-object/src/test/java/com/iluwatar/roleobject/RoleTest.java @@ -37,4 +37,4 @@ class RoleTest { assertTrue(instance.isPresent()); assertEquals(instance.get().getClass(), BorrowerRole.class); } -} \ No newline at end of file +} diff --git a/saga/pom.xml b/saga/pom.xml index 6ca621c86..7697d9fbc 100644 --- a/saga/pom.xml +++ b/saga/pom.xml @@ -34,6 +34,14 @@ saga + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/saga/src/main/java/com/iluwatar/saga/choreography/ChoreographyChapter.java b/saga/src/main/java/com/iluwatar/saga/choreography/ChoreographyChapter.java index 5839773a4..8f46ff632 100644 --- a/saga/src/main/java/com/iluwatar/saga/choreography/ChoreographyChapter.java +++ b/saga/src/main/java/com/iluwatar/saga/choreography/ChoreographyChapter.java @@ -24,7 +24,6 @@ */ package com.iluwatar.saga.choreography; - /** * ChoreographyChapter is an interface representing a contract for an external service. In that * case, a service needs to make a decision what to do further hence the server needs to get all @@ -62,6 +61,4 @@ public interface ChoreographyChapter { * @return result {@link Saga} */ Saga rollback(Saga saga); - - } diff --git a/saga/src/main/java/com/iluwatar/saga/choreography/FlyBookingService.java b/saga/src/main/java/com/iluwatar/saga/choreography/FlyBookingService.java index 9140cd052..491b4a590 100644 --- a/saga/src/main/java/com/iluwatar/saga/choreography/FlyBookingService.java +++ b/saga/src/main/java/com/iluwatar/saga/choreography/FlyBookingService.java @@ -24,10 +24,7 @@ */ package com.iluwatar.saga.choreography; - -/** - * Class representing a service to book a fly. - */ +/** Class representing a service to book a fly. */ public class FlyBookingService extends Service { public FlyBookingService(ServiceDiscoveryService service) { super(service); diff --git a/saga/src/main/java/com/iluwatar/saga/choreography/HotelBookingService.java b/saga/src/main/java/com/iluwatar/saga/choreography/HotelBookingService.java index 280c0f05b..3f44fbd3e 100644 --- a/saga/src/main/java/com/iluwatar/saga/choreography/HotelBookingService.java +++ b/saga/src/main/java/com/iluwatar/saga/choreography/HotelBookingService.java @@ -24,10 +24,7 @@ */ package com.iluwatar.saga.choreography; - -/** - * Class representing a service to book a hotel. - */ +/** Class representing a service to book a hotel. */ public class HotelBookingService extends Service { public HotelBookingService(ServiceDiscoveryService service) { super(service); @@ -37,6 +34,4 @@ public class HotelBookingService extends Service { public String getName() { return "booking a Hotel"; } - - } diff --git a/saga/src/main/java/com/iluwatar/saga/choreography/OrderService.java b/saga/src/main/java/com/iluwatar/saga/choreography/OrderService.java index 55778bb1d..36b8717c3 100644 --- a/saga/src/main/java/com/iluwatar/saga/choreography/OrderService.java +++ b/saga/src/main/java/com/iluwatar/saga/choreography/OrderService.java @@ -24,10 +24,7 @@ */ package com.iluwatar.saga.choreography; - -/** - * Class representing a service to init a new order. - */ +/** Class representing a service to init a new order. */ public class OrderService extends Service { public OrderService(ServiceDiscoveryService service) { diff --git a/saga/src/main/java/com/iluwatar/saga/choreography/Saga.java b/saga/src/main/java/com/iluwatar/saga/choreography/Saga.java index c04a63dfd..4b690c3c2 100644 --- a/saga/src/main/java/com/iluwatar/saga/choreography/Saga.java +++ b/saga/src/main/java/com/iluwatar/saga/choreography/Saga.java @@ -41,7 +41,6 @@ public class Saga { private boolean forward; private boolean finished; - public static Saga create() { return new Saga(); } @@ -53,9 +52,7 @@ public class Saga { */ public SagaResult getResult() { if (finished) { - return forward - ? SagaResult.FINISHED - : SagaResult.ROLLBACKED; + return forward ? SagaResult.FINISHED : SagaResult.ROLLBACKED; } return SagaResult.PROGRESS; @@ -130,7 +127,6 @@ public class Saga { return --pos; } - private Saga() { this.chapters = new ArrayList<>(); this.pos = 0; @@ -142,7 +138,6 @@ public class Saga { return chapters.get(pos); } - boolean isPresent() { return pos >= 0 && pos < chapters.size(); } @@ -156,13 +151,9 @@ public class Saga { * outcoming parameter). */ public static class Chapter { - @Getter - private final String name; - @Setter - private ChapterResult result; - @Getter - @Setter - private Object inValue; + @Getter private final String name; + @Setter private ChapterResult result; + @Getter @Setter private Object inValue; public Chapter(String name) { this.name = name; @@ -179,19 +170,18 @@ public class Saga { } } - - /** - * result for chapter. - */ + /** result for chapter. */ public enum ChapterResult { - INIT, SUCCESS, ROLLBACK + INIT, + SUCCESS, + ROLLBACK } - /** - * result for saga. - */ + /** result for saga. */ public enum SagaResult { - PROGRESS, FINISHED, ROLLBACKED + PROGRESS, + FINISHED, + ROLLBACKED } @Override diff --git a/saga/src/main/java/com/iluwatar/saga/choreography/SagaApplication.java b/saga/src/main/java/com/iluwatar/saga/choreography/SagaApplication.java index 86758da00..09d68f429 100644 --- a/saga/src/main/java/com/iluwatar/saga/choreography/SagaApplication.java +++ b/saga/src/main/java/com/iluwatar/saga/choreography/SagaApplication.java @@ -31,12 +31,12 @@ import lombok.extern.slf4j.Slf4j; * an analog of transaction in a database but in terms of microservices architecture this is * executed in a distributed environment * - *

A saga is a sequence of local transactions in a certain context. - * If one transaction fails for some reason, the saga executes compensating transactions(rollbacks) - * to undo the impact of the preceding transactions. + *

A saga is a sequence of local transactions in a certain context. If one transaction fails for + * some reason, the saga executes compensating transactions(rollbacks) to undo the impact of the + * preceding transactions. * - *

In this approach, there are no mediators or orchestrators services. - * All chapters are handled and moved by services manually. + *

In this approach, there are no mediators or orchestrators services. All chapters are handled + * and moved by services manually. * *

The major difference with choreography saga is an ability to handle crashed services * (otherwise in choreography services very hard to prevent a saga if one of them has been crashed) @@ -47,24 +47,22 @@ import lombok.extern.slf4j.Slf4j; @Slf4j public class SagaApplication { - /** - * main method. - */ + /** main method. */ public static void main(String[] args) { var sd = serviceDiscovery(); var service = sd.findAny(); var goodOrderSaga = service.execute(newSaga("good_order")); var badOrderSaga = service.execute(newSaga("bad_order")); - LOGGER.info("orders: goodOrder is {}, badOrder is {}", - goodOrderSaga.getResult(), badOrderSaga.getResult()); - + LOGGER.info( + "orders: goodOrder is {}, badOrder is {}", + goodOrderSaga.getResult(), + badOrderSaga.getResult()); } - private static Saga newSaga(Object value) { - return Saga - .create() - .chapter("init an order").setInValue(value) + return Saga.create() + .chapter("init an order") + .setInValue(value) .chapter("booking a Fly") .chapter("booking a Hotel") .chapter("withdrawing Money"); @@ -72,8 +70,7 @@ public class SagaApplication { private static ServiceDiscoveryService serviceDiscovery() { var sd = new ServiceDiscoveryService(); - return sd - .discover(new OrderService(sd)) + return sd.discover(new OrderService(sd)) .discover(new FlyBookingService(sd)) .discover(new HotelBookingService(sd)) .discover(new WithdrawMoneyService(sd)); diff --git a/saga/src/main/java/com/iluwatar/saga/choreography/Service.java b/saga/src/main/java/com/iluwatar/saga/choreography/Service.java index 3cd7b84ff..6510b830c 100644 --- a/saga/src/main/java/com/iluwatar/saga/choreography/Service.java +++ b/saga/src/main/java/com/iluwatar/saga/choreography/Service.java @@ -28,7 +28,6 @@ import java.util.function.Supplier; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - /** * Common abstraction class representing services. implementing a general contract @see {@link * ChoreographyChapter} @@ -70,21 +69,24 @@ public abstract class Service implements ChoreographyChapter { } var finalNextSaga = nextSaga; - return sd.find(chapterName).map(ch -> ch.execute(finalNextSaga)) + return sd.find(chapterName) + .map(ch -> ch.execute(finalNextSaga)) .orElseThrow(serviceNotFoundException(chapterName)); } private Supplier serviceNotFoundException(String chServiceName) { - return () -> new RuntimeException( - String.format("the service %s has not been found", chServiceName)); + return () -> + new RuntimeException(String.format("the service %s has not been found", chServiceName)); } @Override public Saga process(Saga saga) { var inValue = saga.getCurrentValue(); - LOGGER.info("The chapter '{}' has been started. " + LOGGER.info( + "The chapter '{}' has been started. " + "The data {} has been stored or calculated successfully", - getName(), inValue); + getName(), + inValue); saga.setCurrentStatus(Saga.ChapterResult.SUCCESS); saga.setCurrentValue(inValue); return saga; @@ -93,9 +95,11 @@ public abstract class Service implements ChoreographyChapter { @Override public Saga rollback(Saga saga) { var inValue = saga.getCurrentValue(); - LOGGER.info("The Rollback for a chapter '{}' has been started. " + LOGGER.info( + "The Rollback for a chapter '{}' has been started. " + "The data {} has been rollbacked successfully", - getName(), inValue); + getName(), + inValue); saga.setCurrentStatus(Saga.ChapterResult.ROLLBACK); saga.setCurrentValue(inValue); @@ -110,5 +114,4 @@ public abstract class Service implements ChoreographyChapter { } return false; } - } diff --git a/saga/src/main/java/com/iluwatar/saga/choreography/ServiceDiscoveryService.java b/saga/src/main/java/com/iluwatar/saga/choreography/ServiceDiscoveryService.java index d159ea453..49cc7c92f 100644 --- a/saga/src/main/java/com/iluwatar/saga/choreography/ServiceDiscoveryService.java +++ b/saga/src/main/java/com/iluwatar/saga/choreography/ServiceDiscoveryService.java @@ -29,9 +29,7 @@ import java.util.Map; import java.util.NoSuchElementException; import java.util.Optional; -/** - * The class representing a service discovery pattern. - */ +/** The class representing a service discovery pattern. */ public class ServiceDiscoveryService { private final Map services; @@ -57,6 +55,4 @@ public class ServiceDiscoveryService { public ServiceDiscoveryService() { this.services = new HashMap<>(); } - - } diff --git a/saga/src/main/java/com/iluwatar/saga/choreography/WithdrawMoneyService.java b/saga/src/main/java/com/iluwatar/saga/choreography/WithdrawMoneyService.java index c9b370898..095170fb8 100644 --- a/saga/src/main/java/com/iluwatar/saga/choreography/WithdrawMoneyService.java +++ b/saga/src/main/java/com/iluwatar/saga/choreography/WithdrawMoneyService.java @@ -24,9 +24,7 @@ */ package com.iluwatar.saga.choreography; -/** - * Class representing a service to withdraw a money. - */ +/** Class representing a service to withdraw a money. */ public class WithdrawMoneyService extends Service { public WithdrawMoneyService(ServiceDiscoveryService service) { @@ -43,7 +41,8 @@ public class WithdrawMoneyService extends Service { var inValue = saga.getCurrentValue(); if (inValue.equals("bad_order")) { - LOGGER.info("The chapter '{}' has been started. But the exception has been raised." + LOGGER.info( + "The chapter '{}' has been started. But the exception has been raised." + "The rollback is about to start", getName()); saga.setCurrentStatus(Saga.ChapterResult.ROLLBACK); diff --git a/saga/src/main/java/com/iluwatar/saga/orchestration/ChapterResult.java b/saga/src/main/java/com/iluwatar/saga/orchestration/ChapterResult.java index a348b3a72..9790373f6 100644 --- a/saga/src/main/java/com/iluwatar/saga/orchestration/ChapterResult.java +++ b/saga/src/main/java/com/iluwatar/saga/orchestration/ChapterResult.java @@ -32,8 +32,7 @@ import lombok.Getter; * @param incoming value */ public class ChapterResult { - @Getter - private final K value; + @Getter private final K value; private final State state; ChapterResult(K value, State state) { @@ -53,10 +52,9 @@ public class ChapterResult { return new ChapterResult<>(val, State.FAILURE); } - /** - * state for chapter. - */ + /** state for chapter. */ public enum State { - SUCCESS, FAILURE + SUCCESS, + FAILURE } } diff --git a/saga/src/main/java/com/iluwatar/saga/orchestration/FlyBookingService.java b/saga/src/main/java/com/iluwatar/saga/orchestration/FlyBookingService.java index 1540b4afb..19a0fc1f8 100644 --- a/saga/src/main/java/com/iluwatar/saga/orchestration/FlyBookingService.java +++ b/saga/src/main/java/com/iluwatar/saga/orchestration/FlyBookingService.java @@ -24,9 +24,7 @@ */ package com.iluwatar.saga.orchestration; -/** - * Class representing a service to book a fly. - */ +/** Class representing a service to book a fly. */ public class FlyBookingService extends Service { @Override public String getName() { diff --git a/saga/src/main/java/com/iluwatar/saga/orchestration/HotelBookingService.java b/saga/src/main/java/com/iluwatar/saga/orchestration/HotelBookingService.java index aa3a9266e..ebd602032 100644 --- a/saga/src/main/java/com/iluwatar/saga/orchestration/HotelBookingService.java +++ b/saga/src/main/java/com/iluwatar/saga/orchestration/HotelBookingService.java @@ -24,29 +24,30 @@ */ package com.iluwatar.saga.orchestration; -/** - * Class representing a service to book a hotel. - */ +/** Class representing a service to book a hotel. */ public class HotelBookingService extends Service { @Override public String getName() { return "booking a Hotel"; } - @Override public ChapterResult rollback(String value) { if (value.equals("crashed_order")) { - LOGGER.info("The Rollback for a chapter '{}' has been started. " + LOGGER.info( + "The Rollback for a chapter '{}' has been started. " + "The data {} has been failed.The saga has been crashed.", - getName(), value); + getName(), + value); return ChapterResult.failure(value); } - LOGGER.info("The Rollback for a chapter '{}' has been started. " + LOGGER.info( + "The Rollback for a chapter '{}' has been started. " + "The data {} has been rollbacked successfully", - getName(), value); + getName(), + value); return super.rollback(value); } diff --git a/saga/src/main/java/com/iluwatar/saga/orchestration/OrchestrationChapter.java b/saga/src/main/java/com/iluwatar/saga/orchestration/OrchestrationChapter.java index 1197de110..537e5af14 100644 --- a/saga/src/main/java/com/iluwatar/saga/orchestration/OrchestrationChapter.java +++ b/saga/src/main/java/com/iluwatar/saga/orchestration/OrchestrationChapter.java @@ -53,5 +53,4 @@ public interface OrchestrationChapter { * @return result {@link ChapterResult} */ ChapterResult rollback(K value); - } diff --git a/saga/src/main/java/com/iluwatar/saga/orchestration/OrderService.java b/saga/src/main/java/com/iluwatar/saga/orchestration/OrderService.java index 67d0f9089..2f1432d39 100644 --- a/saga/src/main/java/com/iluwatar/saga/orchestration/OrderService.java +++ b/saga/src/main/java/com/iluwatar/saga/orchestration/OrderService.java @@ -24,9 +24,7 @@ */ package com.iluwatar.saga.orchestration; -/** - * Class representing a service to init a new order. - */ +/** Class representing a service to init a new order. */ public class OrderService extends Service { @Override public String getName() { diff --git a/saga/src/main/java/com/iluwatar/saga/orchestration/Saga.java b/saga/src/main/java/com/iluwatar/saga/orchestration/Saga.java index 9057a23e3..b89886c4a 100644 --- a/saga/src/main/java/com/iluwatar/saga/orchestration/Saga.java +++ b/saga/src/main/java/com/iluwatar/saga/orchestration/Saga.java @@ -37,18 +37,15 @@ public class Saga { private final List chapters; - private Saga() { this.chapters = new ArrayList<>(); } - public Saga chapter(String name) { this.chapters.add(new Chapter(name)); return this; } - public Chapter get(int idx) { return chapters.get(idx); } @@ -57,21 +54,18 @@ public class Saga { return idx >= 0 && idx < chapters.size(); } - public static Saga create() { return new Saga(); } - /** - * result for saga. - */ + /** result for saga. */ public enum Result { - FINISHED, ROLLBACK, CRASHED + FINISHED, + ROLLBACK, + CRASHED } - /** - * class represents chapter name. - */ + /** class represents chapter name. */ @AllArgsConstructor @Getter public static class Chapter { diff --git a/saga/src/main/java/com/iluwatar/saga/orchestration/SagaApplication.java b/saga/src/main/java/com/iluwatar/saga/orchestration/SagaApplication.java index 2d5a748d9..200a73b8a 100644 --- a/saga/src/main/java/com/iluwatar/saga/orchestration/SagaApplication.java +++ b/saga/src/main/java/com/iluwatar/saga/orchestration/SagaApplication.java @@ -31,15 +31,14 @@ import lombok.extern.slf4j.Slf4j; * an analog of transaction in a database but in terms of microservices architecture this is * executed in a distributed environment * - *

A saga is a sequence of local transactions in a certain context. - * If one transaction fails for some reason, the saga executes compensating transactions(rollbacks) - * to undo the impact of the preceding transactions. + *

A saga is a sequence of local transactions in a certain context. If one transaction fails for + * some reason, the saga executes compensating transactions(rollbacks) to undo the impact of the + * preceding transactions. * - *

In this approach, there is an orchestrator @see {@link SagaOrchestrator} - * that manages all the transactions and directs the participant services to execute local - * transactions based on events. The major difference with choreography saga is an ability to handle - * crashed services (otherwise in choreography services very hard to prevent a saga if one of them - * has been crashed) + *

In this approach, there is an orchestrator @see {@link SagaOrchestrator} that manages all the + * transactions and directs the participant services to execute local transactions based on events. + * The major difference with choreography saga is an ability to handle crashed services (otherwise + * in choreography services very hard to prevent a saga if one of them has been crashed) * * @see Saga * @see SagaOrchestrator @@ -48,9 +47,7 @@ import lombok.extern.slf4j.Slf4j; @Slf4j public class SagaApplication { - /** - * method to show common saga logic. - */ + /** method to show common saga logic. */ public static void main(String[] args) { var sagaOrchestrator = new SagaOrchestrator(newSaga(), serviceDiscovery()); @@ -58,14 +55,15 @@ public class SagaApplication { Saga.Result badOrder = sagaOrchestrator.execute("bad_order"); Saga.Result crashedOrder = sagaOrchestrator.execute("crashed_order"); - LOGGER.info("orders: goodOrder is {}, badOrder is {},crashedOrder is {}", - goodOrder, badOrder, crashedOrder); + LOGGER.info( + "orders: goodOrder is {}, badOrder is {},crashedOrder is {}", + goodOrder, + badOrder, + crashedOrder); } - private static Saga newSaga() { - return Saga - .create() + return Saga.create() .chapter("init an order") .chapter("booking a Fly") .chapter("booking a Hotel") diff --git a/saga/src/main/java/com/iluwatar/saga/orchestration/SagaOrchestrator.java b/saga/src/main/java/com/iluwatar/saga/orchestration/SagaOrchestrator.java index 88128879a..2cfe2acc0 100644 --- a/saga/src/main/java/com/iluwatar/saga/orchestration/SagaOrchestrator.java +++ b/saga/src/main/java/com/iluwatar/saga/orchestration/SagaOrchestrator.java @@ -31,7 +31,6 @@ import static com.iluwatar.saga.orchestration.Saga.Result.ROLLBACK; import lombok.extern.slf4j.Slf4j; - /** * The orchestrator that manages all the transactions and directs the participant services to * execute local transactions based on events. @@ -42,12 +41,11 @@ public class SagaOrchestrator { private final ServiceDiscoveryService sd; private final CurrentState state; - /** * Create a new service to orchetrate sagas. * * @param saga saga to process - * @param sd service discovery @see {@link ServiceDiscoveryService} + * @param sd service discovery @see {@link ServiceDiscoveryService} */ public SagaOrchestrator(Saga saga, ServiceDiscoveryService sd) { this.saga = saga; @@ -59,7 +57,7 @@ public class SagaOrchestrator { * pipeline to execute saga process/story. * * @param value incoming value - * @param type for incoming value + * @param type for incoming value * @return result @see {@link Result} */ @SuppressWarnings("unchecked") @@ -101,15 +99,12 @@ public class SagaOrchestrator { } } - if (!saga.isPresent(next)) { return state.isForward() ? FINISHED : result == CRASHED ? CRASHED : ROLLBACK; } } - } - private static class CurrentState { int currentNumber; boolean isForward; @@ -124,7 +119,6 @@ public class SagaOrchestrator { this.isForward = true; } - boolean isForward() { return isForward; } @@ -145,5 +139,4 @@ public class SagaOrchestrator { return currentNumber; } } - } diff --git a/saga/src/main/java/com/iluwatar/saga/orchestration/Service.java b/saga/src/main/java/com/iluwatar/saga/orchestration/Service.java index 6fc74d194..00ec6d18e 100644 --- a/saga/src/main/java/com/iluwatar/saga/orchestration/Service.java +++ b/saga/src/main/java/com/iluwatar/saga/orchestration/Service.java @@ -39,22 +39,23 @@ public abstract class Service implements OrchestrationChapter { @Override public abstract String getName(); - @Override public ChapterResult process(K value) { - LOGGER.info("The chapter '{}' has been started. " + LOGGER.info( + "The chapter '{}' has been started. " + "The data {} has been stored or calculated successfully", - getName(), value); + getName(), + value); return ChapterResult.success(value); } @Override public ChapterResult rollback(K value) { - LOGGER.info("The Rollback for a chapter '{}' has been started. " + LOGGER.info( + "The Rollback for a chapter '{}' has been started. " + "The data {} has been rollbacked successfully", - getName(), value); + getName(), + value); return ChapterResult.success(value); } - - } diff --git a/saga/src/main/java/com/iluwatar/saga/orchestration/ServiceDiscoveryService.java b/saga/src/main/java/com/iluwatar/saga/orchestration/ServiceDiscoveryService.java index 19b85fd92..face085fb 100644 --- a/saga/src/main/java/com/iluwatar/saga/orchestration/ServiceDiscoveryService.java +++ b/saga/src/main/java/com/iluwatar/saga/orchestration/ServiceDiscoveryService.java @@ -28,9 +28,7 @@ import java.util.HashMap; import java.util.Map; import java.util.Optional; -/** - * The class representing a service discovery pattern. - */ +/** The class representing a service discovery pattern. */ public class ServiceDiscoveryService { private final Map> services; @@ -46,6 +44,4 @@ public class ServiceDiscoveryService { public ServiceDiscoveryService() { this.services = new HashMap<>(); } - - } diff --git a/saga/src/main/java/com/iluwatar/saga/orchestration/WithdrawMoneyService.java b/saga/src/main/java/com/iluwatar/saga/orchestration/WithdrawMoneyService.java index fe443cbd1..b6fb2a03c 100644 --- a/saga/src/main/java/com/iluwatar/saga/orchestration/WithdrawMoneyService.java +++ b/saga/src/main/java/com/iluwatar/saga/orchestration/WithdrawMoneyService.java @@ -24,9 +24,7 @@ */ package com.iluwatar.saga.orchestration; -/** - * Class representing a service to withdraw a money. - */ +/** Class representing a service to withdraw a money. */ public class WithdrawMoneyService extends Service { @Override public String getName() { @@ -36,7 +34,8 @@ public class WithdrawMoneyService extends Service { @Override public ChapterResult process(String value) { if (value.equals("bad_order") || value.equals("crashed_order")) { - LOGGER.info("The chapter '{}' has been started. But the exception has been raised." + LOGGER.info( + "The chapter '{}' has been started. But the exception has been raised." + "The rollback is about to start", getName()); return ChapterResult.failure(value); diff --git a/saga/src/test/java/com/iluwatar/saga/choreography/SagaApplicationTest.java b/saga/src/test/java/com/iluwatar/saga/choreography/SagaApplicationTest.java index 29f835684..a3d5b136e 100644 --- a/saga/src/test/java/com/iluwatar/saga/choreography/SagaApplicationTest.java +++ b/saga/src/test/java/com/iluwatar/saga/choreography/SagaApplicationTest.java @@ -35,6 +35,6 @@ import org.junit.jupiter.api.Test; class SagaApplicationTest { @Test void shouldExecuteWithoutException() { - assertDoesNotThrow(() -> SagaApplication.main(new String[]{})); + assertDoesNotThrow(() -> SagaApplication.main(new String[] {})); } } diff --git a/saga/src/test/java/com/iluwatar/saga/choreography/SagaChoreographyTest.java b/saga/src/test/java/com/iluwatar/saga/choreography/SagaChoreographyTest.java index 8154f368a..14e6658f4 100644 --- a/saga/src/test/java/com/iluwatar/saga/choreography/SagaChoreographyTest.java +++ b/saga/src/test/java/com/iluwatar/saga/choreography/SagaChoreographyTest.java @@ -24,13 +24,11 @@ */ package com.iluwatar.saga.choreography; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; -/** - * test to check choreography saga - */ +import org.junit.jupiter.api.Test; + +/** test to check choreography saga */ class SagaChoreographyTest { @Test @@ -45,9 +43,9 @@ class SagaChoreographyTest { } private static Saga newSaga(Object value) { - return Saga - .create() - .chapter("init an order").setInValue(value) + return Saga.create() + .chapter("init an order") + .setInValue(value) .chapter("booking a Fly") .chapter("booking a Hotel") .chapter("withdrawing Money"); @@ -55,8 +53,7 @@ class SagaChoreographyTest { private static ServiceDiscoveryService serviceDiscovery() { var sd = new ServiceDiscoveryService(); - return sd - .discover(new OrderService(sd)) + return sd.discover(new OrderService(sd)) .discover(new FlyBookingService(sd)) .discover(new HotelBookingService(sd)) .discover(new WithdrawMoneyService(sd)); diff --git a/saga/src/test/java/com/iluwatar/saga/orchestration/SagaApplicationTest.java b/saga/src/test/java/com/iluwatar/saga/orchestration/SagaApplicationTest.java index b06cb65a2..a428a109e 100644 --- a/saga/src/test/java/com/iluwatar/saga/orchestration/SagaApplicationTest.java +++ b/saga/src/test/java/com/iluwatar/saga/orchestration/SagaApplicationTest.java @@ -28,13 +28,11 @@ import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import org.junit.jupiter.api.Test; -/** - * Test if the application starts without throwing an exception. - */ +/** Test if the application starts without throwing an exception. */ class SagaApplicationTest { @Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> SagaApplication.main(new String[]{})); + assertDoesNotThrow(() -> SagaApplication.main(new String[] {})); } } diff --git a/saga/src/test/java/com/iluwatar/saga/orchestration/SagaOrchestratorInternallyTest.java b/saga/src/test/java/com/iluwatar/saga/orchestration/SagaOrchestratorInternallyTest.java index a9ff4db05..1270e6525 100644 --- a/saga/src/test/java/com/iluwatar/saga/orchestration/SagaOrchestratorInternallyTest.java +++ b/saga/src/test/java/com/iluwatar/saga/orchestration/SagaOrchestratorInternallyTest.java @@ -24,18 +24,15 @@ */ package com.iluwatar.saga.orchestration; -import org.junit.jupiter.api.Test; - import static com.iluwatar.saga.orchestration.Saga.Result; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.ArrayList; import java.util.List; +import org.junit.jupiter.api.Test; -/** - * test to test orchestration logic - */ +/** test to test orchestration logic */ class SagaOrchestratorInternallyTest { private final List records = new ArrayList<>(); @@ -46,16 +43,12 @@ class SagaOrchestratorInternallyTest { var result = sagaOrchestrator.execute(1); assertEquals(Result.ROLLBACK, result); assertArrayEquals( - new String[]{"+1", "+2", "+3", "+4", "-4", "-3", "-2", "-1"}, - records.toArray(new String[]{})); + new String[] {"+1", "+2", "+3", "+4", "-4", "-3", "-2", "-1"}, + records.toArray(new String[] {})); } private static Saga newSaga() { - return Saga.create() - .chapter("1") - .chapter("2") - .chapter("3") - .chapter("4"); + return Saga.create().chapter("1").chapter("2").chapter("3").chapter("4"); } private ServiceDiscoveryService serviceDiscovery() { @@ -145,4 +138,4 @@ class SagaOrchestratorInternallyTest { return ChapterResult.success(value); } } -} \ No newline at end of file +} diff --git a/saga/src/test/java/com/iluwatar/saga/orchestration/SagaOrchestratorTest.java b/saga/src/test/java/com/iluwatar/saga/orchestration/SagaOrchestratorTest.java index 687d77297..a136f90a9 100644 --- a/saga/src/test/java/com/iluwatar/saga/orchestration/SagaOrchestratorTest.java +++ b/saga/src/test/java/com/iluwatar/saga/orchestration/SagaOrchestratorTest.java @@ -24,13 +24,11 @@ */ package com.iluwatar.saga.orchestration; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; -/** - * test to check general logic - */ +import org.junit.jupiter.api.Test; + +/** test to check general logic */ class SagaOrchestratorTest { @Test @@ -44,8 +42,7 @@ class SagaOrchestratorTest { } private static Saga newSaga() { - return Saga - .create() + return Saga.create() .chapter("init an order") .chapter("booking a Fly") .chapter("booking a Hotel") @@ -53,11 +50,10 @@ class SagaOrchestratorTest { } private static ServiceDiscoveryService serviceDiscovery() { - return - new ServiceDiscoveryService() - .discover(new OrderService()) - .discover(new FlyBookingService()) - .discover(new HotelBookingService()) - .discover(new WithdrawMoneyService()); + return new ServiceDiscoveryService() + .discover(new OrderService()) + .discover(new FlyBookingService()) + .discover(new HotelBookingService()) + .discover(new WithdrawMoneyService()); } -} \ No newline at end of file +} diff --git a/separated-interface/pom.xml b/separated-interface/pom.xml index 1684ea124..9dd5816e0 100644 --- a/separated-interface/pom.xml +++ b/separated-interface/pom.xml @@ -34,6 +34,14 @@ separated-interface + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/separated-interface/src/main/java/com/iluwatar/separatedinterface/App.java b/separated-interface/src/main/java/com/iluwatar/separatedinterface/App.java index c50a5eb6c..0f4cb00f8 100644 --- a/separated-interface/src/main/java/com/iluwatar/separatedinterface/App.java +++ b/separated-interface/src/main/java/com/iluwatar/separatedinterface/App.java @@ -30,13 +30,13 @@ import com.iluwatar.separatedinterface.taxes.ForeignTaxCalculator; import lombok.extern.slf4j.Slf4j; /** - *

The Separated Interface pattern encourages to separate the interface definition and + * The Separated Interface pattern encourages to separate the interface definition and * implementation in different packages. This allows the client to be completely unaware of the - * implementation.

+ * implementation. * *

In this class the {@link InvoiceGenerator} class is injected with different instances of * {@link com.iluwatar.separatedinterface.invoice.TaxCalculator} implementations located in separate - * packages, to receive different responses for both of the implementations.

+ * packages, to receive different responses for both of the implementations. */ @Slf4j public class App { @@ -49,12 +49,12 @@ public class App { * @param args command line args */ public static void main(String[] args) { - //Create the invoice generator with product cost as 50 and foreign product tax - var internationalProductInvoice = new InvoiceGenerator(PRODUCT_COST, - new ForeignTaxCalculator()); + // Create the invoice generator with product cost as 50 and foreign product tax + var internationalProductInvoice = + new InvoiceGenerator(PRODUCT_COST, new ForeignTaxCalculator()); LOGGER.info("Foreign Tax applied: {}", "" + internationalProductInvoice.getAmountWithTax()); - //Create the invoice generator with product cost as 50 and domestic product tax + // Create the invoice generator with product cost as 50 and domestic product tax var domesticProductInvoice = new InvoiceGenerator(PRODUCT_COST, new DomesticTaxCalculator()); LOGGER.info("Domestic Tax applied: {}", "" + domesticProductInvoice.getAmountWithTax()); } diff --git a/separated-interface/src/main/java/com/iluwatar/separatedinterface/invoice/InvoiceGenerator.java b/separated-interface/src/main/java/com/iluwatar/separatedinterface/invoice/InvoiceGenerator.java index cdb2b6c1d..a3e2c8396 100644 --- a/separated-interface/src/main/java/com/iluwatar/separatedinterface/invoice/InvoiceGenerator.java +++ b/separated-interface/src/main/java/com/iluwatar/separatedinterface/invoice/InvoiceGenerator.java @@ -27,13 +27,11 @@ package com.iluwatar.separatedinterface.invoice; /** * InvoiceGenerator class generates an invoice, accepting the product cost and calculating the total * price payable inclusive tax (calculated by {@link TaxCalculator}). - * */ public record InvoiceGenerator(double amount, TaxCalculator taxCalculator) { - /** TaxCalculator description: - * The TaxCalculator interface to calculate the payable tax. - * Amount description: - * The base product amount without tax. + /** + * TaxCalculator description: The TaxCalculator interface to calculate the payable tax. Amount + * description: The base product amount without tax. */ public double getAmountWithTax() { return amount + taxCalculator.calculate(amount); diff --git a/separated-interface/src/main/java/com/iluwatar/separatedinterface/invoice/TaxCalculator.java b/separated-interface/src/main/java/com/iluwatar/separatedinterface/invoice/TaxCalculator.java index 85b6e6786..6132d0c48 100644 --- a/separated-interface/src/main/java/com/iluwatar/separatedinterface/invoice/TaxCalculator.java +++ b/separated-interface/src/main/java/com/iluwatar/separatedinterface/invoice/TaxCalculator.java @@ -24,11 +24,8 @@ */ package com.iluwatar.separatedinterface.invoice; -/** - * TaxCalculator interface to demonstrate The Separated Interface pattern. - */ +/** TaxCalculator interface to demonstrate The Separated Interface pattern. */ public interface TaxCalculator { double calculate(double amount); - } diff --git a/separated-interface/src/main/java/com/iluwatar/separatedinterface/taxes/DomesticTaxCalculator.java b/separated-interface/src/main/java/com/iluwatar/separatedinterface/taxes/DomesticTaxCalculator.java index cbf914658..0b372a0e1 100644 --- a/separated-interface/src/main/java/com/iluwatar/separatedinterface/taxes/DomesticTaxCalculator.java +++ b/separated-interface/src/main/java/com/iluwatar/separatedinterface/taxes/DomesticTaxCalculator.java @@ -26,9 +26,7 @@ package com.iluwatar.separatedinterface.taxes; import com.iluwatar.separatedinterface.invoice.TaxCalculator; -/** - * TaxCalculator for Domestic goods with 20% tax. - */ +/** TaxCalculator for Domestic goods with 20% tax. */ public class DomesticTaxCalculator implements TaxCalculator { public static final double TAX_PERCENTAGE = 20; @@ -37,5 +35,4 @@ public class DomesticTaxCalculator implements TaxCalculator { public double calculate(double amount) { return amount * TAX_PERCENTAGE / 100.0; } - } diff --git a/separated-interface/src/main/java/com/iluwatar/separatedinterface/taxes/ForeignTaxCalculator.java b/separated-interface/src/main/java/com/iluwatar/separatedinterface/taxes/ForeignTaxCalculator.java index b4265a5d3..0378c0108 100644 --- a/separated-interface/src/main/java/com/iluwatar/separatedinterface/taxes/ForeignTaxCalculator.java +++ b/separated-interface/src/main/java/com/iluwatar/separatedinterface/taxes/ForeignTaxCalculator.java @@ -26,9 +26,7 @@ package com.iluwatar.separatedinterface.taxes; import com.iluwatar.separatedinterface.invoice.TaxCalculator; -/** - * TaxCalculator for foreign goods with 60% tax. - */ +/** TaxCalculator for foreign goods with 60% tax. */ public class ForeignTaxCalculator implements TaxCalculator { public static final double TAX_PERCENTAGE = 60; @@ -37,5 +35,4 @@ public class ForeignTaxCalculator implements TaxCalculator { public double calculate(double amount) { return amount * TAX_PERCENTAGE / 100.0; } - } diff --git a/separated-interface/src/test/java/com/iluwatar/separatedinterface/AppTest.java b/separated-interface/src/test/java/com/iluwatar/separatedinterface/AppTest.java index 995aabf19..245077b1b 100644 --- a/separated-interface/src/test/java/com/iluwatar/separatedinterface/AppTest.java +++ b/separated-interface/src/test/java/com/iluwatar/separatedinterface/AppTest.java @@ -24,18 +24,15 @@ */ package com.iluwatar.separatedinterface; -import org.junit.jupiter.api.Test; -import com.iluwatar.separatedinterface.App; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -/** - * Application test. - */ +import org.junit.jupiter.api.Test; + +/** Application test. */ class AppTest { @Test void shouldExecuteWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/separated-interface/src/test/java/com/iluwatar/separatedinterface/invoice/InvoiceGeneratorTest.java b/separated-interface/src/test/java/com/iluwatar/separatedinterface/invoice/InvoiceGeneratorTest.java index 7772fc942..c0223ad25 100644 --- a/separated-interface/src/test/java/com/iluwatar/separatedinterface/invoice/InvoiceGeneratorTest.java +++ b/separated-interface/src/test/java/com/iluwatar/separatedinterface/invoice/InvoiceGeneratorTest.java @@ -48,5 +48,4 @@ class InvoiceGeneratorTest { Assertions.assertEquals(target.getAmountWithTax(), productCost + tax); verify(taxCalculatorMock, times(1)).calculate(productCost); } - } diff --git a/separated-interface/src/test/java/com/iluwatar/separatedinterface/taxes/DomesticTaxCalculatorTest.java b/separated-interface/src/test/java/com/iluwatar/separatedinterface/taxes/DomesticTaxCalculatorTest.java index be7261a2f..13974dc1d 100644 --- a/separated-interface/src/test/java/com/iluwatar/separatedinterface/taxes/DomesticTaxCalculatorTest.java +++ b/separated-interface/src/test/java/com/iluwatar/separatedinterface/taxes/DomesticTaxCalculatorTest.java @@ -38,5 +38,4 @@ class DomesticTaxCalculatorTest { var tax = target.calculate(100.0); Assertions.assertEquals(tax, 20.0); } - } diff --git a/separated-interface/src/test/java/com/iluwatar/separatedinterface/taxes/ForeignTaxCalculatorTest.java b/separated-interface/src/test/java/com/iluwatar/separatedinterface/taxes/ForeignTaxCalculatorTest.java index 53ba5064d..1e1441f22 100644 --- a/separated-interface/src/test/java/com/iluwatar/separatedinterface/taxes/ForeignTaxCalculatorTest.java +++ b/separated-interface/src/test/java/com/iluwatar/separatedinterface/taxes/ForeignTaxCalculatorTest.java @@ -38,5 +38,4 @@ class ForeignTaxCalculatorTest { var tax = target.calculate(100.0); Assertions.assertEquals(tax, 60.0); } - } diff --git a/serialized-entity/pom.xml b/serialized-entity/pom.xml index aea122f5a..928e28097 100644 --- a/serialized-entity/pom.xml +++ b/serialized-entity/pom.xml @@ -34,6 +34,14 @@ serialized-entity + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/serialized-entity/src/main/java/com/iluwatar/serializedentity/App.java b/serialized-entity/src/main/java/com/iluwatar/serializedentity/App.java index 538675576..c4cab51da 100644 --- a/serialized-entity/src/main/java/com/iluwatar/serializedentity/App.java +++ b/serialized-entity/src/main/java/com/iluwatar/serializedentity/App.java @@ -30,21 +30,22 @@ import javax.sql.DataSource; import lombok.extern.slf4j.Slf4j; import org.h2.jdbcx.JdbcDataSource; - /** * Serialized Entity Pattern. * - *

Serialized Entity Pattern allow us to easily persist Java objects to the database. It uses Serializable interface - * and DAO pattern. Serialized Entity Pattern will first use Serializable to convert a Java object into a set of bytes, - * then it will using DAO pattern to store this set of bytes as BLOB to database.

- * - *

In this example, we first initialize two Java objects (Country) "China" and "UnitedArabEmirates", then we - * initialize "serializedChina" with "China" object and "serializedUnitedArabEmirates" with "UnitedArabEmirates", - * then we use method "serializedChina.insertCountry()" and "serializedUnitedArabEmirates.insertCountry()" to serialize - * "China" and "UnitedArabEmirates" and persist them to database. - * Last, with "serializedChina.selectCountry()" and "serializedUnitedArabEmirates.selectCountry()" we could read "China" - * and "UnitedArabEmirates" from database as sets of bytes, then deserialize them back to Java object (Country).

+ *

Serialized Entity Pattern allow us to easily persist Java objects to the database. It uses + * Serializable interface and DAO pattern. Serialized Entity Pattern will first use Serializable to + * convert a Java object into a set of bytes, then it will using DAO pattern to store this set of + * bytes as BLOB to database. * + *

In this example, we first initialize two Java objects (Country) "China" and + * "UnitedArabEmirates", then we initialize "serializedChina" with "China" object and + * "serializedUnitedArabEmirates" with "UnitedArabEmirates", then we use method + * "serializedChina.insertCountry()" and "serializedUnitedArabEmirates.insertCountry()" to serialize + * "China" and "UnitedArabEmirates" and persist them to database. Last, with + * "serializedChina.selectCountry()" and "serializedUnitedArabEmirates.selectCountry()" we could + * read "China" and "UnitedArabEmirates" from database as sets of bytes, then deserialize them back + * to Java object (Country). */ @Slf4j public class App { @@ -55,6 +56,7 @@ public class App { /** * Program entry point. + * * @param args command line args. * @throws IOException if any * @throws ClassNotFoundException if any @@ -66,20 +68,10 @@ public class App { createSchema(dataSource); // Initializing Country Object China - final var China = new Country( - 86, - "China", - "Asia", - "Chinese" - ); + final var China = new Country(86, "China", "Asia", "Chinese"); // Initializing Country Object UnitedArabEmirates - final var UnitedArabEmirates = new Country( - 971, - "United Arab Emirates", - "Asia", - "Arabic" - ); + final var UnitedArabEmirates = new Country(971, "United Arab Emirates", "Asia", "Arabic"); // Initializing CountrySchemaSql Object with parameter "China" and "dataSource" final var serializedChina = new CountrySchemaSql(China, dataSource); @@ -105,7 +97,7 @@ public class App { private static void deleteSchema(DataSource dataSource) { try (var connection = dataSource.getConnection(); - var statement = connection.createStatement()) { + var statement = connection.createStatement()) { statement.execute(CountrySchemaSql.DELETE_SCHEMA_SQL); } catch (SQLException e) { LOGGER.info("Exception thrown " + e.getMessage()); @@ -114,7 +106,7 @@ public class App { private static void createSchema(DataSource dataSource) { try (var connection = dataSource.getConnection(); - var statement = connection.createStatement()) { + var statement = connection.createStatement()) { statement.execute(CountrySchemaSql.CREATE_SCHEMA_SQL); } catch (SQLException e) { LOGGER.info("Exception thrown " + e.getMessage()); @@ -126,4 +118,4 @@ public class App { dataSource.setURL(DB_URL); return dataSource; } -} \ No newline at end of file +} diff --git a/serialized-entity/src/main/java/com/iluwatar/serializedentity/Country.java b/serialized-entity/src/main/java/com/iluwatar/serializedentity/Country.java index f7430ef25..b406ab62f 100644 --- a/serialized-entity/src/main/java/com/iluwatar/serializedentity/Country.java +++ b/serialized-entity/src/main/java/com/iluwatar/serializedentity/Country.java @@ -23,6 +23,7 @@ * THE SOFTWARE. */ package com.iluwatar.serializedentity; + import java.io.Serial; import java.io.Serializable; import lombok.AllArgsConstructor; @@ -31,9 +32,7 @@ import lombok.Getter; import lombok.Setter; import lombok.ToString; -/** - * A Country POJO that represents the data that will serialize and store in database. - */ +/** A Country POJO that represents the data that will serialize and store in database. */ @Getter @Setter @EqualsAndHashCode @@ -45,7 +44,5 @@ public class Country implements Serializable { private String name; private String continents; private String language; - @Serial - private static final long serialVersionUID = 7149851; - + @Serial private static final long serialVersionUID = 7149851; } diff --git a/serialized-entity/src/main/java/com/iluwatar/serializedentity/CountryDao.java b/serialized-entity/src/main/java/com/iluwatar/serializedentity/CountryDao.java index 26d912c00..beffe1f4c 100644 --- a/serialized-entity/src/main/java/com/iluwatar/serializedentity/CountryDao.java +++ b/serialized-entity/src/main/java/com/iluwatar/serializedentity/CountryDao.java @@ -42,10 +42,9 @@ package com.iluwatar.serializedentity; import java.io.IOException; -/** - * DAO interface for Country transactions. - */ +/** DAO interface for Country transactions. */ public interface CountryDao { int insertCountry() throws IOException; + int selectCountry() throws IOException, ClassNotFoundException; } diff --git a/serialized-entity/src/main/java/com/iluwatar/serializedentity/CountrySchemaSql.java b/serialized-entity/src/main/java/com/iluwatar/serializedentity/CountrySchemaSql.java index 971f875c6..2de487fa0 100644 --- a/serialized-entity/src/main/java/com/iluwatar/serializedentity/CountrySchemaSql.java +++ b/serialized-entity/src/main/java/com/iluwatar/serializedentity/CountrySchemaSql.java @@ -35,12 +35,11 @@ import java.sql.SQLException; import javax.sql.DataSource; import lombok.extern.slf4j.Slf4j; -/** - * Country Schema SQL Class. - */ +/** Country Schema SQL Class. */ @Slf4j public class CountrySchemaSql implements CountryDao { - public static final String CREATE_SCHEMA_SQL = "CREATE TABLE IF NOT EXISTS WORLD (ID INT PRIMARY KEY, COUNTRY BLOB)"; + public static final String CREATE_SCHEMA_SQL = + "CREATE TABLE IF NOT EXISTS WORLD (ID INT PRIMARY KEY, COUNTRY BLOB)"; public static final String DELETE_SCHEMA_SQL = "DROP TABLE WORLD IF EXISTS"; @@ -54,27 +53,26 @@ public class CountrySchemaSql implements CountryDao { * @param country country */ public CountrySchemaSql(Country country, DataSource dataSource) { - this.country = new Country( - country.getCode(), - country.getName(), - country.getContinents(), - country.getLanguage() - ); + this.country = + new Country( + country.getCode(), country.getName(), country.getContinents(), country.getLanguage()); this.dataSource = dataSource; } /** * This method will serialize a Country object and store it to database. - * @return int type, if successfully insert a serialized object to database then return country code, else return -1. + * + * @return int type, if successfully insert a serialized object to database then return country + * code, else return -1. * @throws IOException if any. */ @Override public int insertCountry() throws IOException { var sql = "INSERT INTO WORLD (ID, COUNTRY) VALUES (?, ?)"; try (var connection = dataSource.getConnection(); - var preparedStatement = connection.prepareStatement(sql); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - ObjectOutputStream oss = new ObjectOutputStream(baos)) { + var preparedStatement = connection.prepareStatement(sql); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + ObjectOutputStream oss = new ObjectOutputStream(baos)) { oss.writeObject(country); oss.flush(); @@ -91,8 +89,9 @@ public class CountrySchemaSql implements CountryDao { /** * This method will select a data item from database and deserialize it. - * @return int type, if successfully select and deserialized object from database then return country code, - * else return -1. + * + * @return int type, if successfully select and deserialized object from database then return + * country code, else return -1. * @throws IOException if any. * @throws ClassNotFoundException if any. */ @@ -100,14 +99,15 @@ public class CountrySchemaSql implements CountryDao { public int selectCountry() throws IOException, ClassNotFoundException { var sql = "SELECT ID, COUNTRY FROM WORLD WHERE ID = ?"; try (var connection = dataSource.getConnection(); - var preparedStatement = connection.prepareStatement(sql)) { + var preparedStatement = connection.prepareStatement(sql)) { preparedStatement.setInt(1, country.getCode()); try (ResultSet rs = preparedStatement.executeQuery()) { if (rs.next()) { Blob countryBlob = rs.getBlob("country"); - ByteArrayInputStream baos = new ByteArrayInputStream(countryBlob.getBytes(1, (int) countryBlob.length())); + ByteArrayInputStream baos = + new ByteArrayInputStream(countryBlob.getBytes(1, (int) countryBlob.length())); ObjectInputStream ois = new ObjectInputStream(baos); country = (Country) ois.readObject(); LOGGER.info("Country: " + country); @@ -119,5 +119,4 @@ public class CountrySchemaSql implements CountryDao { } return -1; } - } diff --git a/serialized-entity/src/test/java/com/iluwatar/serializedentity/AppTest.java b/serialized-entity/src/test/java/com/iluwatar/serializedentity/AppTest.java index fde211a36..ad6a9d6d1 100644 --- a/serialized-entity/src/test/java/com/iluwatar/serializedentity/AppTest.java +++ b/serialized-entity/src/test/java/com/iluwatar/serializedentity/AppTest.java @@ -24,23 +24,19 @@ */ package com.iluwatar.serializedentity; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -/** - * Tests that Serialized Entity example runs without errors. - */ +import org.junit.jupiter.api.Test; + +/** Tests that Serialized Entity example runs without errors. */ class AppTest { - /** - * Issue: Add at least one assertion to this test case. - * Solution: Inserted assertion to check whether the execution of the main method in {@link App#main(String[])} - * throws an exception. - */ - - @Test - void shouldExecuteSerializedEntityWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); - } + /** + * Issue: Add at least one assertion to this test case. Solution: Inserted assertion to check + * whether the execution of the main method in {@link App#main(String[])} throws an exception. + */ + @Test + void shouldExecuteSerializedEntityWithoutException() { + assertDoesNotThrow(() -> App.main(new String[] {})); + } } diff --git a/serialized-entity/src/test/java/com/iluwatar/serializedentity/CountryTest.java b/serialized-entity/src/test/java/com/iluwatar/serializedentity/CountryTest.java index 37ba92660..36d7baceb 100644 --- a/serialized-entity/src/test/java/com/iluwatar/serializedentity/CountryTest.java +++ b/serialized-entity/src/test/java/com/iluwatar/serializedentity/CountryTest.java @@ -23,86 +23,70 @@ * THE SOFTWARE. */ package com.iluwatar.serializedentity; + +import static org.junit.jupiter.api.Assertions.*; + +import java.io.*; import java.nio.file.Files; import java.nio.file.Paths; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.Test; -import java.io.*; - -import static org.junit.jupiter.api.Assertions.*; - @Slf4j public class CountryTest { @Test void testGetMethod() { - Country China = new Country( - 86, - "China", - "Asia", - "Chinese" - ); + Country China = new Country(86, "China", "Asia", "Chinese"); - assertEquals(86, China.getCode()); - assertEquals("China", China.getName()); - assertEquals("Asia", China.getContinents()); - assertEquals("Chinese", China.getLanguage()); + assertEquals(86, China.getCode()); + assertEquals("China", China.getName()); + assertEquals("Asia", China.getContinents()); + assertEquals("Chinese", China.getLanguage()); } @Test void testSetMethod() { - Country country = new Country( - 86, - "China", - "Asia", - "Chinese" - ); + Country country = new Country(86, "China", "Asia", "Chinese"); - country.setCode(971); - country.setName("UAE"); - country.setContinents("West-Asia"); - country.setLanguage("Arabic"); + country.setCode(971); + country.setName("UAE"); + country.setContinents("West-Asia"); + country.setLanguage("Arabic"); - assertEquals(971, country.getCode()); - assertEquals("UAE", country.getName()); - assertEquals("West-Asia", country.getContinents()); - assertEquals("Arabic", country.getLanguage()); + assertEquals(971, country.getCode()); + assertEquals("UAE", country.getName()); + assertEquals("West-Asia", country.getContinents()); + assertEquals("Arabic", country.getLanguage()); } @Test - void testSerializable(){ - // Serializing Country - try { - Country country = new Country( - 86, - "China", - "Asia", - "Chinese"); - ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("output.txt")); - objectOutputStream.writeObject(country); - objectOutputStream.close(); - } catch (IOException e) { - LOGGER.error("Error occurred: ", e); - } + void testSerializable() { + // Serializing Country + try { + Country country = new Country(86, "China", "Asia", "Chinese"); + ObjectOutputStream objectOutputStream = + new ObjectOutputStream(new FileOutputStream("output.txt")); + objectOutputStream.writeObject(country); + objectOutputStream.close(); + } catch (IOException e) { + LOGGER.error("Error occurred: ", e); + } - // De-serialize Country - try { - ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("output.txt")); - Country country = (Country) objectInputStream.readObject(); - objectInputStream.close(); - System.out.println(country); + // De-serialize Country + try { + ObjectInputStream objectInputStream = + new ObjectInputStream(new FileInputStream("output.txt")); + Country country = (Country) objectInputStream.readObject(); + objectInputStream.close(); + System.out.println(country); - Country China = new Country( - 86, - "China", - "Asia", - "Chinese"); + Country China = new Country(86, "China", "Asia", "Chinese"); - assertEquals(China, country); - } catch (Exception e) { - LOGGER.error("Error occurred: ", e); - } + assertEquals(China, country); + } catch (Exception e) { + LOGGER.error("Error occurred: ", e); + } try { Files.deleteIfExists(Paths.get("output.txt")); } catch (IOException e) { diff --git a/serialized-lob/pom.xml b/serialized-lob/pom.xml index 60f98e98f..f705a848a 100644 --- a/serialized-lob/pom.xml +++ b/serialized-lob/pom.xml @@ -58,6 +58,14 @@ + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + junit-jupiter-engine org.junit.jupiter diff --git a/serialized-lob/src/main/java/com/iluwatar/slob/App.java b/serialized-lob/src/main/java/com/iluwatar/slob/App.java index 743cc8293..25006726e 100644 --- a/serialized-lob/src/main/java/com/iluwatar/slob/App.java +++ b/serialized-lob/src/main/java/com/iluwatar/slob/App.java @@ -41,9 +41,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xml.sax.SAXException; -/** - * SLOB Application using {@link LobSerializer} and H2 DB. - */ +/** SLOB Application using {@link LobSerializer} and H2 DB. */ public class App { public static final String CLOB = "CLOB"; @@ -51,20 +49,20 @@ public class App { /** * Main entry point to program. + * *

In the SLOB pattern, the object graph is serialized into a single large object (a BLOB or * CLOB, for Binary Large Object or Character Large Object, respectively) and stored in the * database. When the object graph needs to be retrieved, it is read from the database and - * deserialized back into the original object graph.

+ * deserialized back into the original object graph. * *

A Forest is created using {@link #createForest()} with Animals and Plants along with their - * respective relationships.

+ * respective relationships. * - *

Creates a {@link LobSerializer} using the method - * {@link #createLobSerializer(String[])}.

+ *

Creates a {@link LobSerializer} using the method {@link #createLobSerializer(String[])}. * - *

Once created the serializer is passed to the - * {@link #executeSerializer(Forest, LobSerializer)} which handles the serialization, - * deserialization and persisting and loading from DB.

+ *

Once created the serializer is passed to the {@link #executeSerializer(Forest, + * LobSerializer)} which handles the serialization, deserialization and persisting and loading + * from DB. * * @param args if first arg is CLOB then ClobSerializer is used else BlobSerializer is used. */ @@ -75,12 +73,13 @@ public class App { } /** - *

Creates a {@link LobSerializer} on the basis of input args.

- *

If input args are not empty and the value equals {@link App#CLOB} then a - * {@link ClobSerializer} is created else a {@link BlobSerializer} is created.

+ * Creates a {@link LobSerializer} on the basis of input args. + * + *

If input args are not empty and the value equals {@link App#CLOB} then a {@link + * ClobSerializer} is created else a {@link BlobSerializer} is created. * * @param args if first arg is {@link App#CLOB} then ClobSerializer is instantiated else - * BlobSerializer is instantiated. + * BlobSerializer is instantiated. */ private static LobSerializer createLobSerializer(String[] args) throws SQLException { LobSerializer serializer; @@ -96,14 +95,14 @@ public class App { * Creates a Forest with {@link Animal} and {@link Plant} along with their respective * relationships. * - *

The method creates a {@link Forest} with 2 Plants Grass and Oak of type Herb and tree - * respectively.

+ *

The method creates a {@link Forest} with 2 Plants Grass and Oak of type Herb and tree + * respectively. * - *

It also creates 3 animals Zebra and Buffalo which eat the plant grass. Lion consumes the - * Zebra and the Buffalo.

+ *

It also creates 3 animals Zebra and Buffalo which eat the plant grass. Lion consumes the + * Zebra and the Buffalo. * - *

With the above animals and plants and their relationships a forest - * object is created which represents the Object Graph.

+ *

With the above animals and plants and their relationships a forest object is created which + * represents the Object Graph. * * @return Forest Object */ @@ -122,7 +121,7 @@ public class App { * Serialize the input object using the input serializer and persist to DB. After this it loads * the same object back from DB and deserializes using the same serializer. * - * @param forest Object to Serialize and Persist + * @param forest Object to Serialize and Persist * @param lobSerializer Serializer to Serialize and Deserialize Object */ private static void executeSerializer(Forest forest, LobSerializer lobSerializer) { @@ -135,9 +134,12 @@ public class App { Forest forestFromDb = serializer.deSerialize(fromDb); LOGGER.info(forestFromDb.toString()); - } catch (SQLException | IOException | TransformerException | ParserConfigurationException - | SAXException - | ClassNotFoundException e) { + } catch (SQLException + | IOException + | TransformerException + | ParserConfigurationException + | SAXException + | ClassNotFoundException e) { throw new RuntimeException(e); } } diff --git a/serialized-lob/src/main/java/com/iluwatar/slob/dbservice/DatabaseService.java b/serialized-lob/src/main/java/com/iluwatar/slob/dbservice/DatabaseService.java index 66555a849..10f3b262d 100644 --- a/serialized-lob/src/main/java/com/iluwatar/slob/dbservice/DatabaseService.java +++ b/serialized-lob/src/main/java/com/iluwatar/slob/dbservice/DatabaseService.java @@ -30,9 +30,7 @@ import javax.sql.DataSource; import lombok.extern.slf4j.Slf4j; import org.h2.jdbcx.JdbcDataSource; -/** - * Service to handle database operations. - */ +/** Service to handle database operations. */ @Slf4j public class DatabaseService { @@ -73,8 +71,7 @@ public class DatabaseService { * * @throws SQLException if any issue occurs while executing DROP Query */ - public void shutDownService() - throws SQLException { + public void shutDownService() throws SQLException { try (var connection = dataSource.getConnection(); var statement = connection.createStatement()) { statement.execute(DELETE_SCHEMA_SQL); @@ -82,14 +79,13 @@ public class DatabaseService { } /** - * Initaites startup sequence and executes the query - * {@link DatabaseService#CREATE_BINARY_SCHEMA_DDL} if {@link DatabaseService#dataTypeDb} is - * binary else will execute the query {@link DatabaseService#CREATE_TEXT_SCHEMA_DDL}. + * Initaites startup sequence and executes the query {@link + * DatabaseService#CREATE_BINARY_SCHEMA_DDL} if {@link DatabaseService#dataTypeDb} is binary else + * will execute the query {@link DatabaseService#CREATE_TEXT_SCHEMA_DDL}. * * @throws SQLException if there are any issues during DDL execution */ - public void startupService() - throws SQLException { + public void startupService() throws SQLException { try (var connection = dataSource.getConnection(); var statement = connection.createStatement()) { if (dataTypeDb.equals(BINARY_DATA)) { @@ -103,14 +99,13 @@ public class DatabaseService { /** * Executes the insert query {@link DatabaseService#INSERT}. * - * @param id with which row is to be inserted + * @param id with which row is to be inserted * @param name name to be added in the row * @param data object data to be saved in the row - * @throws SQLException if there are any issues in executing insert query - * {@link DatabaseService#INSERT} + * @throws SQLException if there are any issues in executing insert query {@link + * DatabaseService#INSERT} */ - public void insert(int id, String name, Object data) - throws SQLException { + public void insert(int id, String name, Object data) throws SQLException { try (var connection = dataSource.getConnection(); var insert = connection.prepareStatement(INSERT)) { insert.setInt(1, id); @@ -121,22 +116,20 @@ public class DatabaseService { } /** - * Runs the select query {@link DatabaseService#SELECT} form the result set returns an - * {@link java.io.InputStream} if {@link DatabaseService#dataTypeDb} is 'binary' else will return - * the object as a {@link String}. + * Runs the select query {@link DatabaseService#SELECT} form the result set returns an {@link + * java.io.InputStream} if {@link DatabaseService#dataTypeDb} is 'binary' else will return the + * object as a {@link String}. * - * @param id with which row is to be selected + * @param id with which row is to be selected * @param columnsName column in which the object is stored * @return object found from DB - * @throws SQLException if there are any issues in executing insert query * - * {@link DatabaseService#SELECT} + * @throws SQLException if there are any issues in executing insert query * {@link + * DatabaseService#SELECT} */ public Object select(final long id, String columnsName) throws SQLException { ResultSet resultSet = null; try (var connection = dataSource.getConnection(); - var preparedStatement = - connection.prepareStatement(SELECT) - ) { + var preparedStatement = connection.prepareStatement(SELECT)) { Object result = null; preparedStatement.setLong(1, id); resultSet = preparedStatement.executeQuery(); diff --git a/serialized-lob/src/main/java/com/iluwatar/slob/lob/Animal.java b/serialized-lob/src/main/java/com/iluwatar/slob/lob/Animal.java index 770543cc5..17caa41e9 100644 --- a/serialized-lob/src/main/java/com/iluwatar/slob/lob/Animal.java +++ b/serialized-lob/src/main/java/com/iluwatar/slob/lob/Animal.java @@ -35,9 +35,7 @@ import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; -/** - * Creates an object Animal with a list of animals and/or plants it consumes. - */ +/** Creates an object Animal with a list of animals and/or plants it consumes. */ @Data @AllArgsConstructor @NoArgsConstructor @@ -51,12 +49,12 @@ public class Animal implements Serializable { * Iterates over the input nodes recursively and adds new plants to {@link Animal#plantsEaten} or * animals to {@link Animal#animalsEaten} found to input sets respectively. * - * @param childNodes contains the XML Node containing the Forest + * @param childNodes contains the XML Node containing the Forest * @param animalsEaten set of Animals eaten - * @param plantsEaten set of Plants eaten + * @param plantsEaten set of Plants eaten */ - protected static void iterateXmlForAnimalAndPlants(NodeList childNodes, Set animalsEaten, - Set plantsEaten) { + protected static void iterateXmlForAnimalAndPlants( + NodeList childNodes, Set animalsEaten, Set plantsEaten) { for (int i = 0; i < childNodes.getLength(); i++) { Node child = childNodes.item(i); if (child.getNodeType() == Node.ELEMENT_NODE) { diff --git a/serialized-lob/src/main/java/com/iluwatar/slob/lob/Forest.java b/serialized-lob/src/main/java/com/iluwatar/slob/lob/Forest.java index 644dc5db7..844e3c6bd 100644 --- a/serialized-lob/src/main/java/com/iluwatar/slob/lob/Forest.java +++ b/serialized-lob/src/main/java/com/iluwatar/slob/lob/Forest.java @@ -37,12 +37,11 @@ import lombok.NoArgsConstructor; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; + /** * Creates an object Forest which contains animals and plants as its constituents. Animals may eat * plants or other animals in the forest. */ - - @Data @NoArgsConstructor @AllArgsConstructor diff --git a/serialized-lob/src/main/java/com/iluwatar/slob/lob/Plant.java b/serialized-lob/src/main/java/com/iluwatar/slob/lob/Plant.java index 20aff543e..f41a8b67c 100644 --- a/serialized-lob/src/main/java/com/iluwatar/slob/lob/Plant.java +++ b/serialized-lob/src/main/java/com/iluwatar/slob/lob/Plant.java @@ -34,9 +34,7 @@ import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; -/** - * Creates an object Plant which contains its name and type. - */ +/** Creates an object Plant which contains its name and type. */ @Data @AllArgsConstructor @NoArgsConstructor diff --git a/serialized-lob/src/main/java/com/iluwatar/slob/serializers/BlobSerializer.java b/serialized-lob/src/main/java/com/iluwatar/slob/serializers/BlobSerializer.java index c3858a84a..f9fe3a7a7 100644 --- a/serialized-lob/src/main/java/com/iluwatar/slob/serializers/BlobSerializer.java +++ b/serialized-lob/src/main/java/com/iluwatar/slob/serializers/BlobSerializer.java @@ -69,7 +69,7 @@ public class BlobSerializer extends LobSerializer { * @param toDeserialize Input Object to De-serialize * @return Deserialized Object * @throws ClassNotFoundException {@inheritDoc} - * @throws IOException {@inheritDoc} + * @throws IOException {@inheritDoc} */ @Override public Forest deSerialize(Object toDeserialize) throws IOException, ClassNotFoundException { diff --git a/serialized-lob/src/main/java/com/iluwatar/slob/serializers/ClobSerializer.java b/serialized-lob/src/main/java/com/iluwatar/slob/serializers/ClobSerializer.java index 173444719..827477c30 100644 --- a/serialized-lob/src/main/java/com/iluwatar/slob/serializers/ClobSerializer.java +++ b/serialized-lob/src/main/java/com/iluwatar/slob/serializers/ClobSerializer.java @@ -76,7 +76,7 @@ public class ClobSerializer extends LobSerializer { * @param forest Object which is to be serialized * @return Serialized object * @throws ParserConfigurationException If any issues occur in parsing input object - * @throws TransformerException If any issues occur in Transformation from Node to XML + * @throws TransformerException If any issues occur in Transformation from Node to XML */ @Override public Object serialize(Forest forest) throws ParserConfigurationException, TransformerException { @@ -90,14 +90,14 @@ public class ClobSerializer extends LobSerializer { * @param toDeserialize Input Object to De-serialize * @return Deserialized Object * @throws ParserConfigurationException If any issues occur in parsing input object - * @throws IOException if any issues occur during reading object - * @throws SAXException If any issues occur in Transformation from Node to XML + * @throws IOException if any issues occur during reading object + * @throws SAXException If any issues occur in Transformation from Node to XML */ @Override public Forest deSerialize(Object toDeserialize) throws ParserConfigurationException, IOException, SAXException { - DocumentBuilder documentBuilder = DocumentBuilderFactory.newDefaultInstance() - .newDocumentBuilder(); + DocumentBuilder documentBuilder = + DocumentBuilderFactory.newDefaultInstance().newDocumentBuilder(); var stream = new ByteArrayInputStream(toDeserialize.toString().getBytes()); Document parsed = documentBuilder.parse(stream); Forest forest = new Forest(); diff --git a/serialized-lob/src/main/java/com/iluwatar/slob/serializers/LobSerializer.java b/serialized-lob/src/main/java/com/iluwatar/slob/serializers/LobSerializer.java index 54e9c8ba5..c97246f33 100644 --- a/serialized-lob/src/main/java/com/iluwatar/slob/serializers/LobSerializer.java +++ b/serialized-lob/src/main/java/com/iluwatar/slob/serializers/LobSerializer.java @@ -60,8 +60,8 @@ public abstract class LobSerializer implements Serializable, Closeable { * @param toSerialize Input Object to serialize * @return Serialized Object * @throws ParserConfigurationException if any issue occurs during parsing of input object - * @throws TransformerException if any issue occurs during Transformation - * @throws IOException if any issues occur during reading object + * @throws TransformerException if any issue occurs during Transformation + * @throws IOException if any issues occur during reading object */ public abstract Object serialize(Forest toSerialize) throws ParserConfigurationException, TransformerException, IOException; @@ -69,8 +69,8 @@ public abstract class LobSerializer implements Serializable, Closeable { /** * Saves the object to DB with the provided ID. * - * @param id key to be sent to DB service - * @param name Object name to store in DB + * @param id key to be sent to DB service + * @param name Object name to store in DB * @param object Object to store in DB * @return ID with which the object is stored in DB * @throws SQLException if any issue occurs while saving to DB @@ -83,7 +83,7 @@ public abstract class LobSerializer implements Serializable, Closeable { /** * Loads the object from db using the ID and column name. * - * @param id to query the DB + * @param id to query the DB * @param columnName column from which object is to be extracted * @return Object from DB * @throws SQLException if any issue occurs while loading from DB @@ -98,8 +98,8 @@ public abstract class LobSerializer implements Serializable, Closeable { * @param toDeserialize object to deserialize * @return Deserialized Object * @throws ParserConfigurationException If issue occurs during parsing of input object - * @throws IOException if any issues occur during reading object - * @throws SAXException if any issues occur during reading object for XML parsing + * @throws IOException if any issues occur during reading object + * @throws SAXException if any issues occur during reading object for XML parsing */ public abstract Forest deSerialize(Object toDeserialize) throws ParserConfigurationException, IOException, SAXException, ClassNotFoundException; diff --git a/serialized-lob/src/test/java/com/iluwatar/slob/AppTest.java b/serialized-lob/src/test/java/com/iluwatar/slob/AppTest.java index f8332a128..8d87608a2 100644 --- a/serialized-lob/src/test/java/com/iluwatar/slob/AppTest.java +++ b/serialized-lob/src/test/java/com/iluwatar/slob/AppTest.java @@ -43,20 +43,20 @@ import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.xml.sax.SAXException; -/** - * SLOB Application test - */ +/** SLOB Application test */ @Slf4j class AppTest { /** * Creates a Forest with Animals and Plants along with their respective relationships. - *

The method creates a forest with 2 Plants Grass and Oak of type Herb and tree - * respectively.

- *

It also creates 3 animals Zebra and Buffalo which eat the plant grass. Lion consumes the - * Zebra and the Buffalo.

- *

With the above animals and plants and their relationships a forest - * object is created which represents the Object Graph.

+ * + *

The method creates a forest with 2 Plants Grass and Oak of type Herb and tree respectively. + * + *

It also creates 3 animals Zebra and Buffalo which eat the plant grass. Lion consumes the + * Zebra and the Buffalo. + * + *

With the above animals and plants and their relationships a forest object is created which + * represents the Object Graph. * * @return Forest Object */ @@ -72,28 +72,30 @@ class AppTest { } /** - * Tests the {@link App} without passing any argument in the args to test the - * {@link ClobSerializer}. + * Tests the {@link App} without passing any argument in the args to test the {@link + * ClobSerializer}. */ @Test void shouldExecuteWithoutExceptionClob() { - assertDoesNotThrow(() -> App.main(new String[]{"CLOB"})); + assertDoesNotThrow(() -> App.main(new String[] {"CLOB"})); } /** - * Tests the {@link App} without passing any argument in the args to test the - * {@link BlobSerializer}. + * Tests the {@link App} without passing any argument in the args to test the {@link + * BlobSerializer}. */ @Test void shouldExecuteWithoutExceptionBlob() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } /** * Tests the serialization of the input object using the {@link ClobSerializer} and persists the * serialized object to DB, then load the object back from DB and deserializes it using the - * provided {@link ClobSerializer}.

After loading the object back from DB the test matches the - * hash of the input object with the hash of the object that was loaded from DB and deserialized. + * provided {@link ClobSerializer}. + * + *

After loading the object back from DB the test matches the hash of the input object with the + * hash of the object that was loaded from DB and deserialized. */ @Test void clobSerializerTest() { @@ -106,11 +108,16 @@ class AppTest { Object fromDb = serializer.loadFromDb(id, Forest.class.getSimpleName()); Forest forestFromDb = serializer.deSerialize(fromDb); - Assertions.assertEquals(forest.hashCode(), forestFromDb.hashCode(), + Assertions.assertEquals( + forest.hashCode(), + forestFromDb.hashCode(), "Hashes of objects after Serializing and Deserializing are the same"); - } catch (SQLException | IOException | TransformerException | ParserConfigurationException | - SAXException | - ClassNotFoundException e) { + } catch (SQLException + | IOException + | TransformerException + | ParserConfigurationException + | SAXException + | ClassNotFoundException e) { throw new RuntimeException(e); } } @@ -118,8 +125,10 @@ class AppTest { /** * Tests the serialization of the input object using the {@link BlobSerializer} and persists the * serialized object to DB, then loads the object back from DB and deserializes it using the - * {@link BlobSerializer}.

After loading the object back from DB the test matches the hash of - * the input object with the hash of the object that was loaded from DB and deserialized. + * {@link BlobSerializer}. + * + *

After loading the object back from DB the test matches the hash of the input object with the + * hash of the object that was loaded from DB and deserialized. */ @Test void blobSerializerTest() { @@ -132,11 +141,16 @@ class AppTest { Object fromDb = serializer.loadFromDb(id, Forest.class.getSimpleName()); Forest forestFromDb = serializer.deSerialize(fromDb); - Assertions.assertEquals(forest.hashCode(), forestFromDb.hashCode(), + Assertions.assertEquals( + forest.hashCode(), + forestFromDb.hashCode(), "Hashes of objects after Serializing and Deserializing are the same"); - } catch (SQLException | IOException | TransformerException | ParserConfigurationException | - SAXException | - ClassNotFoundException e) { + } catch (SQLException + | IOException + | TransformerException + | ParserConfigurationException + | SAXException + | ClassNotFoundException e) { throw new RuntimeException(e); } } diff --git a/servant/pom.xml b/servant/pom.xml index 65650364b..9917acddb 100644 --- a/servant/pom.xml +++ b/servant/pom.xml @@ -35,6 +35,14 @@ servant + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/servant/src/main/java/com/iluwatar/servant/App.java b/servant/src/main/java/com/iluwatar/servant/App.java index 9583823c8..122a4f0a4 100644 --- a/servant/src/main/java/com/iluwatar/servant/App.java +++ b/servant/src/main/java/com/iluwatar/servant/App.java @@ -27,7 +27,6 @@ package com.iluwatar.servant; import java.util.List; import lombok.extern.slf4j.Slf4j; - /** * Servant offers some functionality to a group of classes without defining that functionality in * each of them. A Servant is a class whose instance provides methods that take care of a desired @@ -41,17 +40,13 @@ public class App { private static final Servant jenkins = new Servant("Jenkins"); private static final Servant travis = new Servant("Travis"); - /** - * Program entry point. - */ + /** Program entry point. */ public static void main(String[] args) { scenario(jenkins, 1); scenario(travis, 0); } - /** - * Can add a List with enum Actions for variable scenarios. - */ + /** Can add a List with enum Actions for variable scenarios. */ public static void scenario(Servant servant, int compliment) { var k = new King(); var q = new Queen(); diff --git a/servant/src/main/java/com/iluwatar/servant/King.java b/servant/src/main/java/com/iluwatar/servant/King.java index a2fb35e1a..85150edf2 100644 --- a/servant/src/main/java/com/iluwatar/servant/King.java +++ b/servant/src/main/java/com/iluwatar/servant/King.java @@ -24,9 +24,7 @@ */ package com.iluwatar.servant; -/** - * King. - */ +/** King. */ public class King implements Royalty { private boolean isDrunk; diff --git a/servant/src/main/java/com/iluwatar/servant/Queen.java b/servant/src/main/java/com/iluwatar/servant/Queen.java index 50b2f97a7..e0de35938 100644 --- a/servant/src/main/java/com/iluwatar/servant/Queen.java +++ b/servant/src/main/java/com/iluwatar/servant/Queen.java @@ -24,9 +24,7 @@ */ package com.iluwatar.servant; -/** - * Queen. - */ +/** Queen. */ public class Queen implements Royalty { private boolean isDrunk = true; @@ -64,5 +62,4 @@ public class Queen implements Royalty { public void setFlirtiness(boolean f) { this.isFlirty = f; } - } diff --git a/servant/src/main/java/com/iluwatar/servant/Royalty.java b/servant/src/main/java/com/iluwatar/servant/Royalty.java index ae19d4e6b..befc71246 100644 --- a/servant/src/main/java/com/iluwatar/servant/Royalty.java +++ b/servant/src/main/java/com/iluwatar/servant/Royalty.java @@ -24,9 +24,7 @@ */ package com.iluwatar.servant; -/** - * Royalty. - */ +/** Royalty. */ interface Royalty { void getFed(); diff --git a/servant/src/main/java/com/iluwatar/servant/Servant.java b/servant/src/main/java/com/iluwatar/servant/Servant.java index e6d279b2f..f572b5d4a 100644 --- a/servant/src/main/java/com/iluwatar/servant/Servant.java +++ b/servant/src/main/java/com/iluwatar/servant/Servant.java @@ -26,16 +26,12 @@ package com.iluwatar.servant; import java.util.List; -/** - * Servant. - */ +/** Servant. */ public class Servant { public String name; - /** - * Constructor. - */ + /** Constructor. */ public Servant(String name) { this.name = name; } @@ -52,9 +48,7 @@ public class Servant { r.receiveCompliments(); } - /** - * Check if we will be hanged. - */ + /** Check if we will be hanged. */ public boolean checkIfYouWillBeHanged(List tableGuests) { return tableGuests.stream().allMatch(Royalty::getMood); } diff --git a/servant/src/test/java/com/iluwatar/servant/AppTest.java b/servant/src/test/java/com/iluwatar/servant/AppTest.java index 63322030e..dea095073 100644 --- a/servant/src/test/java/com/iluwatar/servant/AppTest.java +++ b/servant/src/test/java/com/iluwatar/servant/AppTest.java @@ -24,17 +24,15 @@ */ package com.iluwatar.servant; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -/** - * Application test - */ +import org.junit.jupiter.api.Test; + +/** Application test */ class AppTest { @Test void shouldExecuteWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/servant/src/test/java/com/iluwatar/servant/KingTest.java b/servant/src/test/java/com/iluwatar/servant/KingTest.java index cb14220e1..31d03ca1b 100644 --- a/servant/src/test/java/com/iluwatar/servant/KingTest.java +++ b/servant/src/test/java/com/iluwatar/servant/KingTest.java @@ -29,10 +29,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; -/** - * KingTest - * - */ +/** KingTest */ class KingTest { @Test @@ -102,5 +99,4 @@ class KingTest { king.changeMood(); assertFalse(king.getMood()); } - -} \ No newline at end of file +} diff --git a/servant/src/test/java/com/iluwatar/servant/QueenTest.java b/servant/src/test/java/com/iluwatar/servant/QueenTest.java index 9b7fe36ce..251e9934b 100644 --- a/servant/src/test/java/com/iluwatar/servant/QueenTest.java +++ b/servant/src/test/java/com/iluwatar/servant/QueenTest.java @@ -24,16 +24,12 @@ */ package com.iluwatar.servant; - import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; -/** - * QueenTest - * - */ +/** QueenTest */ class QueenTest { @Test @@ -67,5 +63,4 @@ class QueenTest { queen.changeMood(); assertTrue(queen.getMood()); } - -} \ No newline at end of file +} diff --git a/servant/src/test/java/com/iluwatar/servant/ServantTest.java b/servant/src/test/java/com/iluwatar/servant/ServantTest.java index 3f698d2ad..f0f476835 100644 --- a/servant/src/test/java/com/iluwatar/servant/ServantTest.java +++ b/servant/src/test/java/com/iluwatar/servant/ServantTest.java @@ -33,10 +33,7 @@ import static org.mockito.Mockito.when; import java.util.List; import org.junit.jupiter.api.Test; -/** - * ServantTest - * - */ +/** ServantTest */ class ServantTest { @Test @@ -80,7 +77,5 @@ class ServantTest { assertTrue(new Servant("test").checkIfYouWillBeHanged(goodCompany)); assertTrue(new Servant("test").checkIfYouWillBeHanged(badCompany)); - } - -} \ No newline at end of file +} diff --git a/server-session/pom.xml b/server-session/pom.xml index e7cdcf82c..50b52b405 100644 --- a/server-session/pom.xml +++ b/server-session/pom.xml @@ -38,9 +38,17 @@ server-session + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter - junit-jupiter-api + junit-jupiter-engine test diff --git a/server-session/src/main/java/com/iluwatar/sessionserver/App.java b/server-session/src/main/java/com/iluwatar/sessionserver/App.java index a3c66d3ff..512447b8a 100644 --- a/server-session/src/main/java/com/iluwatar/sessionserver/App.java +++ b/server-session/src/main/java/com/iluwatar/sessionserver/App.java @@ -34,22 +34,21 @@ import java.util.Map; import lombok.extern.slf4j.Slf4j; /** - * The server session pattern is a behavioral design pattern concerned with assigning the responsibility - * of storing session data on the server side. Within the context of stateless protocols like HTTP all - * requests are isolated events independent of previous requests. In order to create sessions during - * user-access for a particular web application various methods can be used, such as cookies. Cookies - * are a small piece of data that can be sent between client and server on every request and response - * so that the server can "remember" the previous requests. In general cookies can either store the session - * data or the cookie can store a session identifier and be used to access appropriate data from a persistent - * storage. In the latter case the session data is stored on the server-side and appropriate data is - * identified by the cookie sent from a client's request. - * This project demonstrates the latter case. - * In the following example the ({@link App}) class starts a server and assigns ({@link LoginHandler}) - * class to handle login request. When a user logs in a session identifier is created and stored for future - * requests in a list. When a user logs out the session identifier is deleted from the list along with - * the appropriate user session data, which is handle by the ({@link LogoutHandler}) class. + * The server session pattern is a behavioral design pattern concerned with assigning the + * responsibility of storing session data on the server side. Within the context of stateless + * protocols like HTTP all requests are isolated events independent of previous requests. In order + * to create sessions during user-access for a particular web application various methods can be + * used, such as cookies. Cookies are a small piece of data that can be sent between client and + * server on every request and response so that the server can "remember" the previous requests. In + * general cookies can either store the session data or the cookie can store a session identifier + * and be used to access appropriate data from a persistent storage. In the latter case the session + * data is stored on the server-side and appropriate data is identified by the cookie sent from a + * client's request. This project demonstrates the latter case. In the following example the ({@link + * App}) class starts a server and assigns ({@link LoginHandler}) class to handle login request. + * When a user logs in a session identifier is created and stored for future requests in a list. + * When a user logs out the session identifier is deleted from the list along with the appropriate + * user session data, which is handle by the ({@link LogoutHandler}) class. */ - @Slf4j public class App { @@ -60,6 +59,7 @@ public class App { /** * Main entry point. + * * @param args arguments * @throws IOException ex */ @@ -81,31 +81,36 @@ public class App { } private static void sessionExpirationTask() { - new Thread(() -> { - while (true) { - try { - LOGGER.info("Session expiration checker started..."); - Thread.sleep(SESSION_EXPIRATION_TIME); // Sleep for expiration time - Instant currentTime = Instant.now(); - synchronized (sessions) { - synchronized (sessionCreationTimes) { - Iterator> iterator = - sessionCreationTimes.entrySet().iterator(); - while (iterator.hasNext()) { - Map.Entry entry = iterator.next(); - if (entry.getValue().plusMillis(SESSION_EXPIRATION_TIME).isBefore(currentTime)) { - sessions.remove(entry.getKey()); - iterator.remove(); + new Thread( + () -> { + while (true) { + try { + LOGGER.info("Session expiration checker started..."); + Thread.sleep(SESSION_EXPIRATION_TIME); // Sleep for expiration time + Instant currentTime = Instant.now(); + synchronized (sessions) { + synchronized (sessionCreationTimes) { + Iterator> iterator = + sessionCreationTimes.entrySet().iterator(); + while (iterator.hasNext()) { + Map.Entry entry = iterator.next(); + if (entry + .getValue() + .plusMillis(SESSION_EXPIRATION_TIME) + .isBefore(currentTime)) { + sessions.remove(entry.getKey()); + iterator.remove(); + } + } + } + } + LOGGER.info("Session expiration checker finished!"); + } catch (InterruptedException e) { + LOGGER.error("An error occurred: ", e); + Thread.currentThread().interrupt(); } } - } - } - LOGGER.info("Session expiration checker finished!"); - } catch (InterruptedException e) { - LOGGER.error("An error occurred: ", e); - Thread.currentThread().interrupt(); - } - } - }).start(); + }) + .start(); } -} \ No newline at end of file +} diff --git a/server-session/src/main/java/com/iluwatar/sessionserver/LoginHandler.java b/server-session/src/main/java/com/iluwatar/sessionserver/LoginHandler.java index 1e36ac052..fd19aa5b9 100644 --- a/server-session/src/main/java/com/iluwatar/sessionserver/LoginHandler.java +++ b/server-session/src/main/java/com/iluwatar/sessionserver/LoginHandler.java @@ -33,9 +33,7 @@ import java.util.Map; import java.util.UUID; import lombok.extern.slf4j.Slf4j; -/** - * LoginHandler. - */ +/** LoginHandler. */ @Slf4j public class LoginHandler implements HttpHandler { diff --git a/server-session/src/main/java/com/iluwatar/sessionserver/LogoutHandler.java b/server-session/src/main/java/com/iluwatar/sessionserver/LogoutHandler.java index 5bea06f2f..3d98a7b60 100644 --- a/server-session/src/main/java/com/iluwatar/sessionserver/LogoutHandler.java +++ b/server-session/src/main/java/com/iluwatar/sessionserver/LogoutHandler.java @@ -32,9 +32,7 @@ import java.time.Instant; import java.util.Map; import lombok.extern.slf4j.Slf4j; -/** - * LogoutHandler. - */ +/** LogoutHandler. */ @Slf4j public class LogoutHandler implements HttpHandler { @@ -61,7 +59,7 @@ public class LogoutHandler implements HttpHandler { response = "Logout successful!\n" + "Session ID: " + currentSessionId; } - //Remove session + // Remove session if (currentSessionId != null) { LOGGER.info("User " + sessions.get(currentSessionId) + " deleted!"); } else { diff --git a/server-session/src/test/java/com/iluwatar/sessionserver/LoginHandlerTest.java b/server-session/src/test/java/com/iluwatar/sessionserver/LoginHandlerTest.java index db5445f88..1da0f3ab5 100644 --- a/server-session/src/test/java/com/iluwatar/sessionserver/LoginHandlerTest.java +++ b/server-session/src/test/java/com/iluwatar/sessionserver/LoginHandlerTest.java @@ -38,22 +38,17 @@ import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; -/** - * LoginHandlerTest. - */ +/** LoginHandlerTest. */ public class LoginHandlerTest { private LoginHandler loginHandler; - //private Headers headers; + // private Headers headers; private Map sessions; private Map sessionCreationTimes; - @Mock - private HttpExchange exchange; + @Mock private HttpExchange exchange; - /** - * Setup tests. - */ + /** Setup tests. */ @BeforeEach public void setUp() { MockitoAnnotations.initMocks(this); @@ -65,18 +60,20 @@ public class LoginHandlerTest { @Test public void testHandle() { - //assemble + // assemble ByteArrayOutputStream outputStream = - new ByteArrayOutputStream(); //Exchange object is mocked so OutputStream must be manually created - when(exchange.getResponseHeaders()).thenReturn( - new Headers()); //Exchange object is mocked so Header object must be manually created + new ByteArrayOutputStream(); // Exchange object is mocked so OutputStream must be manually + // created + when(exchange.getResponseHeaders()) + .thenReturn( + new Headers()); // Exchange object is mocked so Header object must be manually created when(exchange.getResponseBody()).thenReturn(outputStream); - //act + // act loginHandler.handle(exchange); - //assert + // assert String[] response = outputStream.toString().split("Session ID: "); assertEquals(sessions.entrySet().toArray()[0].toString().split("=1")[0], response[1]); } -} \ No newline at end of file +} diff --git a/server-session/src/test/java/com/iluwatar/sessionserver/LogoutHandlerTest.java b/server-session/src/test/java/com/iluwatar/sessionserver/LogoutHandlerTest.java index 1b9d817b0..3929aeb4b 100644 --- a/server-session/src/test/java/com/iluwatar/sessionserver/LogoutHandlerTest.java +++ b/server-session/src/test/java/com/iluwatar/sessionserver/LogoutHandlerTest.java @@ -38,9 +38,7 @@ import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; -/** - * LogoutHandlerTest. - */ +/** LogoutHandlerTest. */ public class LogoutHandlerTest { private LogoutHandler logoutHandler; @@ -48,12 +46,9 @@ public class LogoutHandlerTest { private Map sessions; private Map sessionCreationTimes; - @Mock - private HttpExchange exchange; + @Mock private HttpExchange exchange; - /** - * Setup tests. - */ + /** Setup tests. */ @BeforeEach public void setUp() { MockitoAnnotations.initMocks(this); @@ -61,25 +56,27 @@ public class LogoutHandlerTest { sessionCreationTimes = new HashMap<>(); logoutHandler = new LogoutHandler(sessions, sessionCreationTimes); headers = new Headers(); - headers.add("Cookie", - "sessionID=1234"); //Exchange object methods return Header Object but Exchange is mocked so Headers must be manually created + headers.add( + "Cookie", + "sessionID=1234"); // Exchange object methods return Header Object but Exchange is mocked so + // Headers must be manually created } @Test public void testHandler_SessionNotExpired() { - //assemble - sessions.put("1234", 1); //Fake login details since LoginHandler isn't called - sessionCreationTimes.put("1234", - Instant.now()); //Fake login details since LoginHandler isn't called + // assemble + sessions.put("1234", 1); // Fake login details since LoginHandler isn't called + sessionCreationTimes.put( + "1234", Instant.now()); // Fake login details since LoginHandler isn't called when(exchange.getRequestHeaders()).thenReturn(headers); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); when(exchange.getResponseBody()).thenReturn(outputStream); - //act + // act logoutHandler.handle(exchange); - //assert + // assert String[] response = outputStream.toString().split("Session ID: "); Assertions.assertEquals("1234", response[1]); Assertions.assertFalse(sessions.containsKey(response[1])); @@ -89,15 +86,15 @@ public class LogoutHandlerTest { @Test public void testHandler_SessionExpired() { - //assemble + // assemble ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); when(exchange.getRequestHeaders()).thenReturn(headers); when(exchange.getResponseBody()).thenReturn(outputStream); - //act + // act logoutHandler.handle(exchange); - //assert + // assert String[] response = outputStream.toString().split("Session ID: "); Assertions.assertEquals("Session has already expired!", response[0]); } diff --git a/service-layer/pom.xml b/service-layer/pom.xml index 19e8fd377..37795dae3 100644 --- a/service-layer/pom.xml +++ b/service-layer/pom.xml @@ -34,9 +34,18 @@ service-layer + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.hibernate hibernate-core + 6.6.11.Final com.h2database @@ -45,10 +54,17 @@ org.glassfish.jaxb jaxb-runtime + 4.0.5 javax.xml.bind jaxb-api + 2.4.0-b180830.0359 + + + jakarta.persistence + jakarta.persistence-api + 3.2.0 org.junit.jupiter diff --git a/service-layer/src/main/java/com/iluwatar/servicelayer/app/App.java b/service-layer/src/main/java/com/iluwatar/servicelayer/app/App.java index 947d1ea2e..9c37968e5 100644 --- a/service-layer/src/main/java/com/iluwatar/servicelayer/app/App.java +++ b/service-layer/src/main/java/com/iluwatar/servicelayer/app/App.java @@ -34,22 +34,21 @@ import com.iluwatar.servicelayer.wizard.Wizard; import com.iluwatar.servicelayer.wizard.WizardDaoImpl; import lombok.extern.slf4j.Slf4j; - /** * Service layer defines an application's boundary with a layer of services that establishes a set * of available operations and coordinates the application's response in each operation. * - *

Enterprise applications typically require different kinds of interfaces to the data they - * store and the logic they implement: data loaders, user interfaces, integration gateways, and - * others. Despite their different purposes, these interfaces often need common interactions with - * the application to access and manipulate its data and invoke its business logic. The interactions - * may be complex, involving transactions across multiple resources and the coordination of several + *

Enterprise applications typically require different kinds of interfaces to the data they store + * and the logic they implement: data loaders, user interfaces, integration gateways, and others. + * Despite their different purposes, these interfaces often need common interactions with the + * application to access and manipulate its data and invoke its business logic. The interactions may + * be complex, involving transactions across multiple resources and the coordination of several * responses to an action. Encoding the logic of the interactions separately in each interface * causes a lot of duplication. * - *

The example application demonstrates interactions between a client ({@link App}) and a - * service ({@link MagicService}). The service is implemented with 3-layer architecture (entity, - * dao, service). For persistence the example uses in-memory H2 database which is populated on each + *

The example application demonstrates interactions between a client ({@link App}) and a service + * ({@link MagicService}). The service is implemented with 3-layer architecture (entity, dao, + * service). For persistence the example uses in-memory H2 database which is populated on each * application startup. */ @Slf4j @@ -68,9 +67,7 @@ public class App { queryData(); } - /** - * Initialize data. - */ + /** Initialize data. */ public static void initData() { // spells var spell1 = new Spell("Ice dart"); @@ -173,9 +170,7 @@ public class App { wizardDao.merge(wizard4); } - /** - * Query the data. - */ + /** Query the data. */ public static void queryData() { var wizardDao = new WizardDaoImpl(); var spellbookDao = new SpellbookDaoImpl(); diff --git a/service-layer/src/main/java/com/iluwatar/servicelayer/common/BaseEntity.java b/service-layer/src/main/java/com/iluwatar/servicelayer/common/BaseEntity.java index 6f3f662aa..89b614d1b 100644 --- a/service-layer/src/main/java/com/iluwatar/servicelayer/common/BaseEntity.java +++ b/service-layer/src/main/java/com/iluwatar/servicelayer/common/BaseEntity.java @@ -24,15 +24,10 @@ */ package com.iluwatar.servicelayer.common; -import javax.persistence.Inheritance; -import javax.persistence.InheritanceType; -import javax.persistence.MappedSuperclass; +import jakarta.persistence.MappedSuperclass; -/** - * Base class for entities. - */ +/** Base class for entities. */ @MappedSuperclass -@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) public abstract class BaseEntity { /** @@ -62,5 +57,4 @@ public abstract class BaseEntity { * @param name The new name */ public abstract void setName(final String name); - } 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 9fc0b6392..e842d7b54 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 @@ -25,11 +25,11 @@ package com.iluwatar.servicelayer.common; import com.iluwatar.servicelayer.hibernate.HibernateUtil; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.Root; import java.lang.reflect.ParameterizedType; import java.util.List; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Root; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.query.Query; @@ -42,8 +42,9 @@ import org.hibernate.query.Query; public abstract class DaoBaseImpl implements Dao { @SuppressWarnings("unchecked") - protected Class persistentClass = (Class) ((ParameterizedType) getClass() - .getGenericSuperclass()).getActualTypeArguments()[0]; + protected Class persistentClass = + (Class) + ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]; /* * Making this getSessionFactory() instead of getSession() so that it is the responsibility diff --git a/service-layer/src/main/java/com/iluwatar/servicelayer/hibernate/HibernateUtil.java b/service-layer/src/main/java/com/iluwatar/servicelayer/hibernate/HibernateUtil.java index b1ef9f77f..b68ebc06b 100644 --- a/service-layer/src/main/java/com/iluwatar/servicelayer/hibernate/HibernateUtil.java +++ b/service-layer/src/main/java/com/iluwatar/servicelayer/hibernate/HibernateUtil.java @@ -31,19 +31,14 @@ import lombok.extern.slf4j.Slf4j; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; -/** - * Produces the Hibernate {@link SessionFactory}. - */ +/** Produces the Hibernate {@link SessionFactory}. */ @Slf4j public final class HibernateUtil { - /** - * The cached session factory. - */ + /** The cached session factory. */ private static volatile SessionFactory sessionFactory; - private HibernateUtil() { - } + private HibernateUtil() {} /** * Create the current session factory instance, create a new one when there is none yet. @@ -53,15 +48,17 @@ public final class HibernateUtil { public static synchronized SessionFactory getSessionFactory() { if (sessionFactory == null) { try { - sessionFactory = new Configuration() - .addAnnotatedClass(Wizard.class) - .addAnnotatedClass(Spellbook.class) - .addAnnotatedClass(Spell.class) - .setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect") - .setProperty("hibernate.connection.url", "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1") - .setProperty("hibernate.current_session_context_class", "thread") - .setProperty("hibernate.show_sql", "false") - .setProperty("hibernate.hbm2ddl.auto", "create-drop").buildSessionFactory(); + sessionFactory = + new Configuration() + .addAnnotatedClass(Wizard.class) + .addAnnotatedClass(Spellbook.class) + .addAnnotatedClass(Spell.class) + .setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect") + .setProperty("hibernate.connection.url", "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1") + .setProperty("hibernate.current_session_context_class", "thread") + .setProperty("hibernate.show_sql", "false") + .setProperty("hibernate.hbm2ddl.auto", "create-drop") + .buildSessionFactory(); } catch (Throwable ex) { LOGGER.error("Initial SessionFactory creation failed.", ex); throw new ExceptionInInitializerError(ex); @@ -78,5 +75,4 @@ public final class HibernateUtil { getSessionFactory().close(); sessionFactory = null; } - } diff --git a/service-layer/src/main/java/com/iluwatar/servicelayer/magic/MagicService.java b/service-layer/src/main/java/com/iluwatar/servicelayer/magic/MagicService.java index a51322866..33657f562 100644 --- a/service-layer/src/main/java/com/iluwatar/servicelayer/magic/MagicService.java +++ b/service-layer/src/main/java/com/iluwatar/servicelayer/magic/MagicService.java @@ -29,10 +29,7 @@ import com.iluwatar.servicelayer.spellbook.Spellbook; import com.iluwatar.servicelayer.wizard.Wizard; import java.util.List; - -/** - * Service interface. - */ +/** Service interface. */ public interface MagicService { List findAllWizards(); diff --git a/service-layer/src/main/java/com/iluwatar/servicelayer/magic/MagicServiceImpl.java b/service-layer/src/main/java/com/iluwatar/servicelayer/magic/MagicServiceImpl.java index af527963a..0c0c3bd1f 100644 --- a/service-layer/src/main/java/com/iluwatar/servicelayer/magic/MagicServiceImpl.java +++ b/service-layer/src/main/java/com/iluwatar/servicelayer/magic/MagicServiceImpl.java @@ -33,18 +33,14 @@ import com.iluwatar.servicelayer.wizard.WizardDao; import java.util.ArrayList; import java.util.List; -/** - * Service implementation. - */ +/** Service implementation. */ public class MagicServiceImpl implements MagicService { private final WizardDao wizardDao; private final SpellbookDao spellbookDao; private final SpellDao spellDao; - /** - * Constructor. - */ + /** Constructor. */ public MagicServiceImpl(WizardDao wizardDao, SpellbookDao spellbookDao, SpellDao spellDao) { this.wizardDao = wizardDao; this.spellbookDao = spellbookDao; diff --git a/service-layer/src/main/java/com/iluwatar/servicelayer/spell/Spell.java b/service-layer/src/main/java/com/iluwatar/servicelayer/spell/Spell.java index f27215166..c806530dc 100644 --- a/service-layer/src/main/java/com/iluwatar/servicelayer/spell/Spell.java +++ b/service-layer/src/main/java/com/iluwatar/servicelayer/spell/Spell.java @@ -26,23 +26,24 @@ package com.iluwatar.servicelayer.spell; import com.iluwatar.servicelayer.common.BaseEntity; import com.iluwatar.servicelayer.spellbook.Spellbook; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.Table; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; +import jakarta.persistence.Inheritance; +import jakarta.persistence.InheritanceType; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.Table; import lombok.Getter; import lombok.Setter; -/** - * Spell entity. - */ +/** Spell entity. */ @Entity @Table(name = "SPELL") @Getter @Setter +@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) public class Spell extends BaseEntity { private String name; @@ -56,8 +57,7 @@ public class Spell extends BaseEntity { @JoinColumn(name = "SPELLBOOK_ID_FK", referencedColumnName = "SPELLBOOK_ID") private Spellbook spellbook; - public Spell() { - } + public Spell() {} public Spell(String name) { this(); diff --git a/service-layer/src/main/java/com/iluwatar/servicelayer/spell/SpellDao.java b/service-layer/src/main/java/com/iluwatar/servicelayer/spell/SpellDao.java index 08dda1048..675db02ad 100644 --- a/service-layer/src/main/java/com/iluwatar/servicelayer/spell/SpellDao.java +++ b/service-layer/src/main/java/com/iluwatar/servicelayer/spell/SpellDao.java @@ -26,11 +26,8 @@ package com.iluwatar.servicelayer.spell; import com.iluwatar.servicelayer.common.Dao; -/** - * SpellDao interface. - */ +/** SpellDao interface. */ public interface SpellDao extends Dao { Spell findByName(String name); - } 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 5ee39f4be..0e238ccf8 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 @@ -25,16 +25,13 @@ package com.iluwatar.servicelayer.spell; import com.iluwatar.servicelayer.common.DaoBaseImpl; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Root; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.Root; import org.hibernate.Transaction; import org.hibernate.query.Query; - -/** - * SpellDao implementation. - */ +/** SpellDao implementation. */ public class SpellDaoImpl extends DaoBaseImpl implements SpellDao { @Override diff --git a/service-layer/src/main/java/com/iluwatar/servicelayer/spellbook/Spellbook.java b/service-layer/src/main/java/com/iluwatar/servicelayer/spellbook/Spellbook.java index d81fc8789..8a893724c 100644 --- a/service-layer/src/main/java/com/iluwatar/servicelayer/spellbook/Spellbook.java +++ b/service-layer/src/main/java/com/iluwatar/servicelayer/spellbook/Spellbook.java @@ -27,27 +27,28 @@ package com.iluwatar.servicelayer.spellbook; import com.iluwatar.servicelayer.common.BaseEntity; import com.iluwatar.servicelayer.spell.Spell; import com.iluwatar.servicelayer.wizard.Wizard; +import jakarta.persistence.CascadeType; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; +import jakarta.persistence.Inheritance; +import jakarta.persistence.InheritanceType; +import jakarta.persistence.ManyToMany; +import jakarta.persistence.OneToMany; +import jakarta.persistence.Table; import java.util.HashSet; import java.util.Set; -import javax.persistence.CascadeType; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.ManyToMany; -import javax.persistence.OneToMany; -import javax.persistence.Table; import lombok.Getter; import lombok.Setter; -/** - * Spellbook entity. - */ +/** Spellbook entity. */ @Entity @Table(name = "SPELLBOOK") @Getter @Setter +@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) public class Spellbook extends BaseEntity { @Id diff --git a/service-layer/src/main/java/com/iluwatar/servicelayer/spellbook/SpellbookDao.java b/service-layer/src/main/java/com/iluwatar/servicelayer/spellbook/SpellbookDao.java index 84fd5dfb7..c1c27ddf5 100644 --- a/service-layer/src/main/java/com/iluwatar/servicelayer/spellbook/SpellbookDao.java +++ b/service-layer/src/main/java/com/iluwatar/servicelayer/spellbook/SpellbookDao.java @@ -26,11 +26,8 @@ package com.iluwatar.servicelayer.spellbook; import com.iluwatar.servicelayer.common.Dao; -/** - * SpellbookDao interface. - */ +/** SpellbookDao interface. */ public interface SpellbookDao extends Dao { Spellbook findByName(String name); - } 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 463b06cdd..9169f6ca8 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 @@ -25,16 +25,13 @@ package com.iluwatar.servicelayer.spellbook; import com.iluwatar.servicelayer.common.DaoBaseImpl; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Root; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.Root; import org.hibernate.Transaction; import org.hibernate.query.Query; - -/** - * SpellbookDao implementation. - */ +/** SpellbookDao implementation. */ public class SpellbookDaoImpl extends DaoBaseImpl implements SpellbookDao { @Override @@ -58,5 +55,4 @@ public class SpellbookDaoImpl extends DaoBaseImpl implements Spellboo } return result; } - } diff --git a/service-layer/src/main/java/com/iluwatar/servicelayer/wizard/Wizard.java b/service-layer/src/main/java/com/iluwatar/servicelayer/wizard/Wizard.java index 8b607d76e..44c3c4b4a 100644 --- a/service-layer/src/main/java/com/iluwatar/servicelayer/wizard/Wizard.java +++ b/service-layer/src/main/java/com/iluwatar/servicelayer/wizard/Wizard.java @@ -26,25 +26,26 @@ package com.iluwatar.servicelayer.wizard; import com.iluwatar.servicelayer.common.BaseEntity; import com.iluwatar.servicelayer.spellbook.Spellbook; +import jakarta.persistence.CascadeType; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; +import jakarta.persistence.Inheritance; +import jakarta.persistence.InheritanceType; +import jakarta.persistence.ManyToMany; +import jakarta.persistence.Table; import java.util.HashSet; import java.util.Set; -import javax.persistence.CascadeType; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.ManyToMany; -import javax.persistence.Table; import lombok.Getter; import lombok.Setter; -/** - * Wizard entity. - */ +/** Wizard entity. */ @Entity @Table(name = "WIZARD") @Getter @Setter +@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) public class Wizard extends BaseEntity { @Id diff --git a/service-layer/src/main/java/com/iluwatar/servicelayer/wizard/WizardDao.java b/service-layer/src/main/java/com/iluwatar/servicelayer/wizard/WizardDao.java index 33dd3d343..e8ed2229f 100644 --- a/service-layer/src/main/java/com/iluwatar/servicelayer/wizard/WizardDao.java +++ b/service-layer/src/main/java/com/iluwatar/servicelayer/wizard/WizardDao.java @@ -26,11 +26,8 @@ package com.iluwatar.servicelayer.wizard; import com.iluwatar.servicelayer.common.Dao; -/** - * WizardDao interface. - */ +/** WizardDao interface. */ public interface WizardDao extends Dao { Wizard findByName(String name); - } 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 d35c9b0ca..e1dd3069d 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 @@ -25,15 +25,13 @@ package com.iluwatar.servicelayer.wizard; import com.iluwatar.servicelayer.common.DaoBaseImpl; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Root; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.Root; import org.hibernate.Transaction; import org.hibernate.query.Query; -/** - * WizardDao implementation. - */ +/** WizardDao implementation. */ public class WizardDaoImpl extends DaoBaseImpl implements WizardDao { @Override diff --git a/service-layer/src/test/java/com/iluwatar/servicelayer/app/AppTest.java b/service-layer/src/test/java/com/iluwatar/servicelayer/app/AppTest.java index c7d0b9139..11af9138d 100644 --- a/service-layer/src/test/java/com/iluwatar/servicelayer/app/AppTest.java +++ b/service-layer/src/test/java/com/iluwatar/servicelayer/app/AppTest.java @@ -24,25 +24,22 @@ */ package com.iluwatar.servicelayer.app; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + import com.iluwatar.servicelayer.hibernate.HibernateUtil; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; - -/** - * Application test - */ +/** Application test */ class AppTest { @Test void shouldExecuteWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } @AfterEach void tearDown() { HibernateUtil.dropSession(); } - } diff --git a/service-layer/src/test/java/com/iluwatar/servicelayer/common/BaseDaoTest.java b/service-layer/src/test/java/com/iluwatar/servicelayer/common/BaseDaoTest.java index c563ead81..1bfeeb79a 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 @@ -43,31 +43,23 @@ import org.junit.jupiter.api.Test; */ public abstract class BaseDaoTest> { - /** - * The number of entities stored before each test - */ + /** The number of entities stored before each test */ private static final int INITIAL_COUNT = 5; - /** - * The unique id generator, shared between all entities - */ + /** The unique id generator, shared between all entities */ private static final AtomicInteger ID_GENERATOR = new AtomicInteger(); - /** - * Factory, used to create new entity instances with the given name - */ + /** Factory, used to create new entity instances with the given name */ private final Function factory; - /** - * The tested data access object - */ + /** The tested data access object */ private final D dao; /** * Create a new test using the given factory and dao * * @param factory The factory, used to create new entity instances with the given name - * @param dao The tested data access object + * @param dao The tested data access object */ public BaseDaoTest(final Function factory, final D dao) { this.factory = factory; @@ -141,5 +133,4 @@ public abstract class BaseDaoTest assertEquals(expectedName, entity.getName()); assertEquals(expectedName, entity.toString()); } - } diff --git a/service-layer/src/test/java/com/iluwatar/servicelayer/magic/MagicServiceImplTest.java b/service-layer/src/test/java/com/iluwatar/servicelayer/magic/MagicServiceImplTest.java index 7badd9da3..22794ea8d 100644 --- a/service-layer/src/test/java/com/iluwatar/servicelayer/magic/MagicServiceImplTest.java +++ b/service-layer/src/test/java/com/iluwatar/servicelayer/magic/MagicServiceImplTest.java @@ -41,10 +41,7 @@ import com.iluwatar.servicelayer.wizard.WizardDao; import java.util.Set; import org.junit.jupiter.api.Test; -/** - * MagicServiceImplTest - * - */ +/** MagicServiceImplTest */ class MagicServiceImplTest { @Test @@ -93,11 +90,7 @@ class MagicServiceImplTest { void testFindWizardsWithSpellbook() { final var bookname = "bookname"; final var spellbook = mock(Spellbook.class); - final var wizards = Set.of( - mock(Wizard.class), - mock(Wizard.class), - mock(Wizard.class) - ); + final var wizards = Set.of(mock(Wizard.class), mock(Wizard.class), mock(Wizard.class)); when(spellbook.getWizards()).thenReturn(wizards); final var spellbookDao = mock(SpellbookDao.class); @@ -106,7 +99,6 @@ class MagicServiceImplTest { final var wizardDao = mock(WizardDao.class); final var spellDao = mock(SpellDao.class); - final var service = new MagicServiceImpl(wizardDao, spellbookDao, spellDao); verifyNoInteractions(wizardDao, spellbookDao, spellDao, spellbook); @@ -122,11 +114,7 @@ class MagicServiceImplTest { @Test void testFindWizardsWithSpell() { - final var wizards = Set.of( - mock(Wizard.class), - mock(Wizard.class), - mock(Wizard.class) - ); + final var wizards = Set.of(mock(Wizard.class), mock(Wizard.class), mock(Wizard.class)); final var spellbook = mock(Spellbook.class); when(spellbook.getWizards()).thenReturn(wizards); @@ -152,5 +140,4 @@ class MagicServiceImplTest { verifyNoMoreInteractions(wizardDao, spellbookDao, spellDao); } - } diff --git a/service-layer/src/test/java/com/iluwatar/servicelayer/spell/SpellDaoImplTest.java b/service-layer/src/test/java/com/iluwatar/servicelayer/spell/SpellDaoImplTest.java index 9b75f5319..616d80c12 100644 --- a/service-layer/src/test/java/com/iluwatar/servicelayer/spell/SpellDaoImplTest.java +++ b/service-layer/src/test/java/com/iluwatar/servicelayer/spell/SpellDaoImplTest.java @@ -30,10 +30,7 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import com.iluwatar.servicelayer.common.BaseDaoTest; import org.junit.jupiter.api.Test; -/** - * SpellDaoImplTest - * - */ +/** SpellDaoImplTest */ class SpellDaoImplTest extends BaseDaoTest { public SpellDaoImplTest() { @@ -51,5 +48,4 @@ class SpellDaoImplTest extends BaseDaoTest { assertEquals(spell.getName(), spellByName.getName()); } } - } diff --git a/service-layer/src/test/java/com/iluwatar/servicelayer/spellbook/SpellbookDaoImplTest.java b/service-layer/src/test/java/com/iluwatar/servicelayer/spellbook/SpellbookDaoImplTest.java index 55f3b8b96..5d7b20860 100644 --- a/service-layer/src/test/java/com/iluwatar/servicelayer/spellbook/SpellbookDaoImplTest.java +++ b/service-layer/src/test/java/com/iluwatar/servicelayer/spellbook/SpellbookDaoImplTest.java @@ -30,10 +30,7 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import com.iluwatar.servicelayer.common.BaseDaoTest; import org.junit.jupiter.api.Test; -/** - * SpellbookDaoImplTest - * - */ +/** SpellbookDaoImplTest */ class SpellbookDaoImplTest extends BaseDaoTest { public SpellbookDaoImplTest() { @@ -51,5 +48,4 @@ class SpellbookDaoImplTest extends BaseDaoTest { assertEquals(book.getName(), spellByName.getName()); } } - } diff --git a/service-layer/src/test/java/com/iluwatar/servicelayer/wizard/WizardDaoImplTest.java b/service-layer/src/test/java/com/iluwatar/servicelayer/wizard/WizardDaoImplTest.java index 22a7c6d08..f21380f50 100644 --- a/service-layer/src/test/java/com/iluwatar/servicelayer/wizard/WizardDaoImplTest.java +++ b/service-layer/src/test/java/com/iluwatar/servicelayer/wizard/WizardDaoImplTest.java @@ -30,10 +30,7 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import com.iluwatar.servicelayer.common.BaseDaoTest; import org.junit.jupiter.api.Test; -/** - * WizardDaoImplTest - * - */ +/** WizardDaoImplTest */ class WizardDaoImplTest extends BaseDaoTest { public WizardDaoImplTest() { @@ -51,5 +48,4 @@ class WizardDaoImplTest extends BaseDaoTest { assertEquals(spell.getName(), byName.getName()); } } - } diff --git a/service-locator/pom.xml b/service-locator/pom.xml index 515f5eff7..52fb0b932 100644 --- a/service-locator/pom.xml +++ b/service-locator/pom.xml @@ -34,6 +34,14 @@ service-locator + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/service-locator/src/main/java/com/iluwatar/servicelocator/App.java b/service-locator/src/main/java/com/iluwatar/servicelocator/App.java index f8467e0c4..061cee97b 100644 --- a/service-locator/src/main/java/com/iluwatar/servicelocator/App.java +++ b/service-locator/src/main/java/com/iluwatar/servicelocator/App.java @@ -31,9 +31,7 @@ package com.iluwatar.servicelocator; * necessary to perform a certain task. * *

In this example we use the Service locator pattern to lookup JNDI-services and cache them for - * subsequent requests. - *
- * + * subsequent requests.
*/ public class App { diff --git a/service-locator/src/main/java/com/iluwatar/servicelocator/InitContext.java b/service-locator/src/main/java/com/iluwatar/servicelocator/InitContext.java index 7b3b23742..2082a066b 100644 --- a/service-locator/src/main/java/com/iluwatar/servicelocator/InitContext.java +++ b/service-locator/src/main/java/com/iluwatar/servicelocator/InitContext.java @@ -29,7 +29,6 @@ import lombok.extern.slf4j.Slf4j; /** * For JNDI lookup of services from the web.xml. Will match name of the service name that is being * requested and return a newly created service object with the name - * */ @Slf4j public class InitContext { diff --git a/service-locator/src/main/java/com/iluwatar/servicelocator/Service.java b/service-locator/src/main/java/com/iluwatar/servicelocator/Service.java index 4c830fe50..876a6f727 100644 --- a/service-locator/src/main/java/com/iluwatar/servicelocator/Service.java +++ b/service-locator/src/main/java/com/iluwatar/servicelocator/Service.java @@ -26,9 +26,13 @@ package com.iluwatar.servicelocator; /** * This is going to be the parent service interface which we will use to create our services. All - * services will have a

  • service name
  • unique id
  • execution work - * flow
+ * services will have a * + *
    + *
  • service name + *
  • unique id + *
  • execution work flow + *
*/ public interface Service { diff --git a/service-locator/src/main/java/com/iluwatar/servicelocator/ServiceCache.java b/service-locator/src/main/java/com/iluwatar/servicelocator/ServiceCache.java index b8bcbcfc9..112abe8d5 100644 --- a/service-locator/src/main/java/com/iluwatar/servicelocator/ServiceCache.java +++ b/service-locator/src/main/java/com/iluwatar/servicelocator/ServiceCache.java @@ -33,7 +33,6 @@ import lombok.extern.slf4j.Slf4j; * the cache will be empty and thus any service that is being requested, will be created fresh and * then placed into the cache map. On next hit, if same service name will be requested, it will be * returned from the cache - * */ @Slf4j public class ServiceCache { diff --git a/service-locator/src/main/java/com/iluwatar/servicelocator/ServiceImpl.java b/service-locator/src/main/java/com/iluwatar/servicelocator/ServiceImpl.java index d2cc2bf51..12b635901 100644 --- a/service-locator/src/main/java/com/iluwatar/servicelocator/ServiceImpl.java +++ b/service-locator/src/main/java/com/iluwatar/servicelocator/ServiceImpl.java @@ -30,7 +30,6 @@ import lombok.extern.slf4j.Slf4j; * This is a single service implementation of a sample service. This is the actual service that will * process the request. The reference for this service is to be looked upon in the JNDI server that * can be set in the web.xml deployment descriptor - * */ @Slf4j public class ServiceImpl implements Service { @@ -38,9 +37,7 @@ public class ServiceImpl implements Service { private final String serviceName; private final int id; - /** - * Constructor. - */ + /** Constructor. */ public ServiceImpl(String serviceName) { // set the service name this.serviceName = serviceName; diff --git a/service-locator/src/main/java/com/iluwatar/servicelocator/ServiceLocator.java b/service-locator/src/main/java/com/iluwatar/servicelocator/ServiceLocator.java index 8ce2d27e9..53da47e89 100644 --- a/service-locator/src/main/java/com/iluwatar/servicelocator/ServiceLocator.java +++ b/service-locator/src/main/java/com/iluwatar/servicelocator/ServiceLocator.java @@ -27,14 +27,12 @@ package com.iluwatar.servicelocator; /** * The service locator module. Will fetch service from cache, otherwise creates a fresh service and * update cache - * */ public final class ServiceLocator { private static final ServiceCache serviceCache = new ServiceCache(); - private ServiceLocator() { - } + private ServiceLocator() {} /** * Fetch the service with the name param from the cache first, if no service is found, lookup the diff --git a/service-locator/src/test/java/com/iluwatar/servicelocator/AppTest.java b/service-locator/src/test/java/com/iluwatar/servicelocator/AppTest.java index 3622e4117..282ad2e41 100644 --- a/service-locator/src/test/java/com/iluwatar/servicelocator/AppTest.java +++ b/service-locator/src/test/java/com/iluwatar/servicelocator/AppTest.java @@ -24,17 +24,15 @@ */ package com.iluwatar.servicelocator; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -/** - * Application test - */ +import org.junit.jupiter.api.Test; + +/** Application test */ class AppTest { @Test void shouldExecuteWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/service-locator/src/test/java/com/iluwatar/servicelocator/ServiceLocatorTest.java b/service-locator/src/test/java/com/iluwatar/servicelocator/ServiceLocatorTest.java index cf56bd01e..90d6966b9 100644 --- a/service-locator/src/test/java/com/iluwatar/servicelocator/ServiceLocatorTest.java +++ b/service-locator/src/test/java/com/iluwatar/servicelocator/ServiceLocatorTest.java @@ -33,24 +33,17 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.List; import org.junit.jupiter.api.Test; -/** - * ServiceLocatorTest - * - */ +/** ServiceLocatorTest */ class ServiceLocatorTest { - /** - * Verify if we just receive 'null' when requesting a non-existing service - */ + /** Verify if we just receive 'null' when requesting a non-existing service */ @Test void testGetNonExistentService() { assertNull(ServiceLocator.getService("fantastic/unicorn/service")); assertNull(ServiceLocator.getService("another/fantastic/unicorn/service")); } - /** - * Verify if we get the same cached instance when requesting the same service twice - */ + /** Verify if we get the same cached instance when requesting the same service twice */ @Test void testServiceCache() { final var serviceNames = List.of("jndi/serviceA", "jndi/serviceB"); @@ -62,7 +55,5 @@ class ServiceLocatorTest { assertTrue(service.getId() > 0); // The id is generated randomly, but the minimum value is '1' assertSame(service, ServiceLocator.getService(serviceName)); } - } - -} \ No newline at end of file +} diff --git a/service-stub/pom.xml b/service-stub/pom.xml index 08d58b79e..128957867 100644 --- a/service-stub/pom.xml +++ b/service-stub/pom.xml @@ -38,9 +38,17 @@ service-stub + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter - junit-jupiter + junit-jupiter-engine test diff --git a/service-stub/src/main/java/com/iluwatar/servicestub/App.java b/service-stub/src/main/java/com/iluwatar/servicestub/App.java index 28f9588f5..34227bc54 100644 --- a/service-stub/src/main/java/com/iluwatar/servicestub/App.java +++ b/service-stub/src/main/java/com/iluwatar/servicestub/App.java @@ -38,11 +38,9 @@ import lombok.extern.slf4j.Slf4j; * *

The "real" sentiment analysis class simulates the processing time for the request by pausing * the execution of the thread for 5 seconds. In the stub sentiment analysis class the response is - * immediate. In addition, the stub returns a deterministic output with regard to the input. This - * is extra useful for testing purposes. + * immediate. In addition, the stub returns a deterministic output with regard to the input. This is + * extra useful for testing purposes. */ - - @Slf4j public class App { /** @@ -64,6 +62,5 @@ public class App { LOGGER.info("Analyzing input: {}", text); sentiment = stubSentimentAnalysisServer.analyzeSentiment(text); LOGGER.info("The sentiment is: {}", sentiment); - } } diff --git a/service-stub/src/main/java/com/iluwatar/servicestub/RealSentimentAnalysisServer.java b/service-stub/src/main/java/com/iluwatar/servicestub/RealSentimentAnalysisServer.java index d67d8e975..dc7c174cb 100644 --- a/service-stub/src/main/java/com/iluwatar/servicestub/RealSentimentAnalysisServer.java +++ b/service-stub/src/main/java/com/iluwatar/servicestub/RealSentimentAnalysisServer.java @@ -28,21 +28,19 @@ import java.util.Random; import java.util.function.Supplier; /** - * Real implementation of SentimentAnalysisServer. - * Simulates random sentiment classification with processing delay. + * Real implementation of SentimentAnalysisServer. Simulates random sentiment classification with + * processing delay. */ - public class RealSentimentAnalysisServer implements SentimentAnalysisServer { /** * A real sentiment analysis implementation would analyze the input string using, e.g., NLP and - * determine whether the sentiment is positive, negative or neutral. Here we simply choose a random - * number to simulate this. The "model" may take some time to process the input and we simulate - * this by delaying the execution 5 seconds. + * determine whether the sentiment is positive, negative or neutral. Here we simply choose a + * random number to simulate this. The "model" may take some time to process the input and we + * simulate this by delaying the execution 5 seconds. * * @param text the input string to analyze * @return sentiment classification result (Positive, Negative, or Neutral) */ - private final Supplier sentimentSupplier; // Constructor @@ -66,4 +64,3 @@ public class RealSentimentAnalysisServer implements SentimentAnalysisServer { return sentiment == 0 ? "Positive" : sentiment == 1 ? "Negative" : "Neutral"; } } - diff --git a/service-stub/src/main/java/com/iluwatar/servicestub/SentimentAnalysisServer.java b/service-stub/src/main/java/com/iluwatar/servicestub/SentimentAnalysisServer.java index c10cc6d4c..51bd6394f 100644 --- a/service-stub/src/main/java/com/iluwatar/servicestub/SentimentAnalysisServer.java +++ b/service-stub/src/main/java/com/iluwatar/servicestub/SentimentAnalysisServer.java @@ -24,10 +24,7 @@ */ package com.iluwatar.servicestub; -/** - * Sentiment analysis server interface to be implemented by sentiment analysis services. - */ - +/** Sentiment analysis server interface to be implemented by sentiment analysis services. */ public interface SentimentAnalysisServer { /** * Analyzes the sentiment of the input text and returns the result. diff --git a/service-stub/src/main/java/com/iluwatar/servicestub/StubSentimentAnalysisServer.java b/service-stub/src/main/java/com/iluwatar/servicestub/StubSentimentAnalysisServer.java index 7ad3de10c..95949c74f 100644 --- a/service-stub/src/main/java/com/iluwatar/servicestub/StubSentimentAnalysisServer.java +++ b/service-stub/src/main/java/com/iluwatar/servicestub/StubSentimentAnalysisServer.java @@ -25,10 +25,9 @@ package com.iluwatar.servicestub; /** - * Stub implementation of SentimentAnalysisServer. - * Returns deterministic sentiment based on input keywords. + * Stub implementation of SentimentAnalysisServer. Returns deterministic sentiment based on input + * keywords. */ - public class StubSentimentAnalysisServer implements SentimentAnalysisServer { /** diff --git a/service-stub/src/test/java/com/iluwatar/servicestub/AppTest.java b/service-stub/src/test/java/com/iluwatar/servicestub/AppTest.java index 656a0695c..13d2d190d 100644 --- a/service-stub/src/test/java/com/iluwatar/servicestub/AppTest.java +++ b/service-stub/src/test/java/com/iluwatar/servicestub/AppTest.java @@ -24,9 +24,10 @@ */ package com.iluwatar.servicestub; -import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import org.junit.jupiter.api.Test; + public class AppTest { @Test void shouldExecuteWithoutException() { diff --git a/service-stub/src/test/java/com/iluwatar/servicestub/RealSentimentAnalysisServerTest.java b/service-stub/src/test/java/com/iluwatar/servicestub/RealSentimentAnalysisServerTest.java index 6c730d889..0ae021826 100644 --- a/service-stub/src/test/java/com/iluwatar/servicestub/RealSentimentAnalysisServerTest.java +++ b/service-stub/src/test/java/com/iluwatar/servicestub/RealSentimentAnalysisServerTest.java @@ -24,9 +24,10 @@ */ package com.iluwatar.servicestub; -import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; + class RealSentimentAnalysisServerTest { @Test @@ -46,5 +47,4 @@ class RealSentimentAnalysisServerTest { RealSentimentAnalysisServer server = new RealSentimentAnalysisServer(() -> 2); assertEquals("Neutral", server.analyzeSentiment("Test")); } - } diff --git a/service-stub/src/test/java/com/iluwatar/servicestub/StubSentimentAnalysisServerTest.java b/service-stub/src/test/java/com/iluwatar/servicestub/StubSentimentAnalysisServerTest.java index 7ccd06bce..5a136633d 100644 --- a/service-stub/src/test/java/com/iluwatar/servicestub/StubSentimentAnalysisServerTest.java +++ b/service-stub/src/test/java/com/iluwatar/servicestub/StubSentimentAnalysisServerTest.java @@ -24,9 +24,10 @@ */ package com.iluwatar.servicestub; -import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; + class StubSentimentAnalysisServerTest { private final StubSentimentAnalysisServer stub = new StubSentimentAnalysisServer(); diff --git a/service-to-worker/src/main/java/com/iluwatar/servicetoworker/Command.java b/service-to-worker/src/main/java/com/iluwatar/servicetoworker/Command.java index df6d80eb4..3c033e8f8 100644 --- a/service-to-worker/src/main/java/com/iluwatar/servicetoworker/Command.java +++ b/service-to-worker/src/main/java/com/iluwatar/servicetoworker/Command.java @@ -29,12 +29,10 @@ import com.iluwatar.model.view.controller.Health; import com.iluwatar.model.view.controller.Nourishment; /** - * The type Command. - * Instantiates a new Command. + * The type Command. Instantiates a new Command. * - * @param fatigue the fatigue - * @param health the health + * @param fatigue the fatigue + * @param health the health * @param nourishment the nourishment */ -public record Command(Fatigue fatigue, Health health, Nourishment nourishment) { -} +public record Command(Fatigue fatigue, Health health, Nourishment nourishment) {} diff --git a/service-to-worker/src/main/java/com/iluwatar/servicetoworker/Dispatcher.java b/service-to-worker/src/main/java/com/iluwatar/servicetoworker/Dispatcher.java index 784784478..3d5d957e8 100644 --- a/service-to-worker/src/main/java/com/iluwatar/servicetoworker/Dispatcher.java +++ b/service-to-worker/src/main/java/com/iluwatar/servicetoworker/Dispatcher.java @@ -34,8 +34,7 @@ import lombok.Getter; */ public class Dispatcher { - @Getter - private final GiantView giantView; + @Getter private final GiantView giantView; private final List actions; /** @@ -60,7 +59,7 @@ public class Dispatcher { /** * Perform an action. * - * @param s the s + * @param s the s * @param actionIndex the action index */ public void performAction(Command s, int actionIndex) { @@ -75,5 +74,4 @@ public class Dispatcher { public void updateView(GiantModel giantModel) { giantView.displayGiant(giantModel); } - } diff --git a/service-to-worker/src/main/java/com/iluwatar/servicetoworker/GiantController.java b/service-to-worker/src/main/java/com/iluwatar/servicetoworker/GiantController.java index 0be3ee5ad..78add64f8 100644 --- a/service-to-worker/src/main/java/com/iluwatar/servicetoworker/GiantController.java +++ b/service-to-worker/src/main/java/com/iluwatar/servicetoworker/GiantController.java @@ -44,7 +44,7 @@ public class GiantController { /** * Sets command to control the dispatcher. * - * @param s the s + * @param s the s * @param index the index */ public void setCommand(Command s, int index) { diff --git a/service-to-worker/src/main/java/com/iluwatar/servicetoworker/GiantModel.java b/service-to-worker/src/main/java/com/iluwatar/servicetoworker/GiantModel.java index 202c25e56..69e4b834a 100644 --- a/service-to-worker/src/main/java/com/iluwatar/servicetoworker/GiantModel.java +++ b/service-to-worker/src/main/java/com/iluwatar/servicetoworker/GiantModel.java @@ -29,27 +29,23 @@ import com.iluwatar.model.view.controller.Health; import com.iluwatar.model.view.controller.Nourishment; import lombok.Getter; -/** - * GiantModel contains the giant data. - */ +/** GiantModel contains the giant data. */ public class GiantModel { private final com.iluwatar.model.view.controller.GiantModel model; - @Getter - private final String name; + @Getter private final String name; /** * Instantiates a new Giant model. * - * @param name the name - * @param health the health - * @param fatigue the fatigue + * @param name the name + * @param health the health + * @param fatigue the fatigue * @param nourishment the nourishment */ GiantModel(String name, Health health, Fatigue fatigue, Nourishment nourishment) { this.name = name; - this.model = new com.iluwatar.model.view.controller.GiantModel(health, fatigue, - nourishment); + this.model = new com.iluwatar.model.view.controller.GiantModel(health, fatigue, nourishment); } /** @@ -103,8 +99,8 @@ public class GiantModel { @Override public String toString() { - return String - .format("Giant %s, The giant looks %s, %s and %s.", name, - model.getHealth(), model.getFatigue(), model.getNourishment()); + return String.format( + "Giant %s, The giant looks %s, %s and %s.", + name, model.getHealth(), model.getFatigue(), model.getNourishment()); } } diff --git a/service-to-worker/src/main/java/com/iluwatar/servicetoworker/GiantView.java b/service-to-worker/src/main/java/com/iluwatar/servicetoworker/GiantView.java index 44d256cdb..667f4c889 100644 --- a/service-to-worker/src/main/java/com/iluwatar/servicetoworker/GiantView.java +++ b/service-to-worker/src/main/java/com/iluwatar/servicetoworker/GiantView.java @@ -26,9 +26,7 @@ package com.iluwatar.servicetoworker; import lombok.extern.slf4j.Slf4j; -/** - * GiantView displays the giant. - */ +/** GiantView displays the giant. */ @Slf4j public class GiantView { diff --git a/service-to-worker/src/test/java/com/iluwatar/servicetoworker/ActionTest.java b/service-to-worker/src/test/java/com/iluwatar/servicetoworker/ActionTest.java index 400010dd0..66bfc6251 100644 --- a/service-to-worker/src/test/java/com/iluwatar/servicetoworker/ActionTest.java +++ b/service-to-worker/src/test/java/com/iluwatar/servicetoworker/ActionTest.java @@ -31,18 +31,14 @@ import com.iluwatar.model.view.controller.Health; import com.iluwatar.model.view.controller.Nourishment; import org.junit.jupiter.api.Test; -/** - * The type Action test. - */ +/** The type Action test. */ class ActionTest { - /** - * Verify if the health value is set properly though the constructor and setter - */ + /** Verify if the health value is set properly though the constructor and setter */ @Test void testSetHealth() { - final var model = new GiantModel("giant1", Health.HEALTHY, Fatigue.ALERT, - Nourishment.SATURATED); + final var model = + new GiantModel("giant1", Health.HEALTHY, Fatigue.ALERT, Nourishment.SATURATED); Action action = new Action(model); assertEquals(Health.HEALTHY, model.getHealth()); var messageFormat = "Giant giant1, The giant looks %s, alert and saturated."; @@ -53,13 +49,11 @@ class ActionTest { } } - /** - * Verify if the fatigue level is set properly though the constructor and setter - */ + /** Verify if the fatigue level is set properly though the constructor and setter */ @Test void testSetFatigue() { - final var model = new GiantModel("giant1", Health.HEALTHY, Fatigue.ALERT, - Nourishment.SATURATED); + final var model = + new GiantModel("giant1", Health.HEALTHY, Fatigue.ALERT, Nourishment.SATURATED); Action action = new Action(model); assertEquals(Fatigue.ALERT, model.getFatigue()); var messageFormat = "Giant giant1, The giant looks healthy, %s and saturated."; @@ -70,13 +64,11 @@ class ActionTest { } } - /** - * Verify if the nourishment level is set properly though the constructor and setter - */ + /** Verify if the nourishment level is set properly though the constructor and setter */ @Test void testSetNourishment() { - final var model = new GiantModel("giant1", Health.HEALTHY, Fatigue.ALERT, - Nourishment.SATURATED); + final var model = + new GiantModel("giant1", Health.HEALTHY, Fatigue.ALERT, Nourishment.SATURATED); Action action = new Action(model); assertEquals(Nourishment.SATURATED, model.getNourishment()); var messageFormat = "Giant giant1, The giant looks healthy, alert and %s."; @@ -87,13 +79,11 @@ class ActionTest { } } - /** - * Test update model. - */ + /** Test update model. */ @Test void testUpdateModel() { - final var model = new GiantModel("giant1", Health.HEALTHY, Fatigue.ALERT, - Nourishment.SATURATED); + final var model = + new GiantModel("giant1", Health.HEALTHY, Fatigue.ALERT, Nourishment.SATURATED); Action action = new Action(model); assertEquals(Nourishment.SATURATED, model.getNourishment()); for (final var nourishment : Nourishment.values()) { diff --git a/service-to-worker/src/test/java/com/iluwatar/servicetoworker/AppTest.java b/service-to-worker/src/test/java/com/iluwatar/servicetoworker/AppTest.java index 0dce37fca..93b39ec28 100644 --- a/service-to-worker/src/test/java/com/iluwatar/servicetoworker/AppTest.java +++ b/service-to-worker/src/test/java/com/iluwatar/servicetoworker/AppTest.java @@ -24,17 +24,15 @@ */ package com.iluwatar.servicetoworker; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -/** - * Application test - */ +import org.junit.jupiter.api.Test; + +/** Application test */ class AppTest { @Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/service-to-worker/src/test/java/com/iluwatar/servicetoworker/DispatcherTest.java b/service-to-worker/src/test/java/com/iluwatar/servicetoworker/DispatcherTest.java index 0551f9b96..dafb12f12 100644 --- a/service-to-worker/src/test/java/com/iluwatar/servicetoworker/DispatcherTest.java +++ b/service-to-worker/src/test/java/com/iluwatar/servicetoworker/DispatcherTest.java @@ -32,18 +32,14 @@ import com.iluwatar.model.view.controller.Health; import com.iluwatar.model.view.controller.Nourishment; import org.junit.jupiter.api.Test; -/** - * The type Dispatcher test. - */ +/** The type Dispatcher test. */ class DispatcherTest { - /** - * Test perform action. - */ + /** Test perform action. */ @Test void testPerformAction() { - final var model = new GiantModel("giant1", Health.HEALTHY, Fatigue.ALERT, - Nourishment.SATURATED); + final var model = + new GiantModel("giant1", Health.HEALTHY, Fatigue.ALERT, Nourishment.SATURATED); Action action = new Action(model); GiantView giantView = new GiantView(); Dispatcher dispatcher = new Dispatcher(giantView); @@ -64,13 +60,10 @@ class DispatcherTest { @Test void testUpdateView() { - final var model = new GiantModel("giant1", Health.HEALTHY, Fatigue.ALERT, - Nourishment.SATURATED); + final var model = + new GiantModel("giant1", Health.HEALTHY, Fatigue.ALERT, Nourishment.SATURATED); GiantView giantView = new GiantView(); Dispatcher dispatcher = new Dispatcher(giantView); assertDoesNotThrow(() -> dispatcher.updateView(model)); } } - - - diff --git a/service-to-worker/src/test/java/com/iluwatar/servicetoworker/GiantControllerTest.java b/service-to-worker/src/test/java/com/iluwatar/servicetoworker/GiantControllerTest.java index ce7334b97..a4b9c35eb 100644 --- a/service-to-worker/src/test/java/com/iluwatar/servicetoworker/GiantControllerTest.java +++ b/service-to-worker/src/test/java/com/iluwatar/servicetoworker/GiantControllerTest.java @@ -32,19 +32,14 @@ import com.iluwatar.model.view.controller.Health; import com.iluwatar.model.view.controller.Nourishment; import org.junit.jupiter.api.Test; - -/** - * The type Giant controller test. - */ +/** The type Giant controller test. */ class GiantControllerTest { - /** - * Test set command. - */ + /** Test set command. */ @Test void testSetCommand() { - final var model = new GiantModel("giant1", Health.HEALTHY, Fatigue.ALERT, - Nourishment.SATURATED); + final var model = + new GiantModel("giant1", Health.HEALTHY, Fatigue.ALERT, Nourishment.SATURATED); Action action = new Action(model); GiantView giantView = new GiantView(); Dispatcher dispatcher = new Dispatcher(giantView); @@ -57,17 +52,14 @@ class GiantControllerTest { assertEquals(Nourishment.HUNGRY, model.getNourishment()); } - /** - * Test update view. - */ + /** Test update view. */ @Test void testUpdateView() { - final var model = new GiantModel("giant1", Health.HEALTHY, Fatigue.ALERT, - Nourishment.SATURATED); + final var model = + new GiantModel("giant1", Health.HEALTHY, Fatigue.ALERT, Nourishment.SATURATED); GiantView giantView = new GiantView(); Dispatcher dispatcher = new Dispatcher(giantView); GiantController giantController = new GiantController(dispatcher); assertDoesNotThrow(() -> giantController.updateView(model)); } - -} \ No newline at end of file +} diff --git a/service-to-worker/src/test/java/com/iluwatar/servicetoworker/GiantModelTest.java b/service-to-worker/src/test/java/com/iluwatar/servicetoworker/GiantModelTest.java index b45ba99d4..c6053e608 100644 --- a/service-to-worker/src/test/java/com/iluwatar/servicetoworker/GiantModelTest.java +++ b/service-to-worker/src/test/java/com/iluwatar/servicetoworker/GiantModelTest.java @@ -31,18 +31,14 @@ import com.iluwatar.model.view.controller.Health; import com.iluwatar.model.view.controller.Nourishment; import org.junit.jupiter.api.Test; -/** - * The type Giant model test. - */ +/** The type Giant model test. */ class GiantModelTest { - /** - * Verify if the health value is set properly though the constructor and setter - */ + /** Verify if the health value is set properly though the constructor and setter */ @Test void testSetHealth() { - final var model = new GiantModel("giant1", Health.HEALTHY, Fatigue.ALERT, - Nourishment.SATURATED); + final var model = + new GiantModel("giant1", Health.HEALTHY, Fatigue.ALERT, Nourishment.SATURATED); assertEquals(Health.HEALTHY, model.getHealth()); var messageFormat = "Giant giant1, The giant looks %s, alert and saturated."; for (final var health : Health.values()) { @@ -52,13 +48,11 @@ class GiantModelTest { } } - /** - * Verify if the fatigue level is set properly though the constructor and setter - */ + /** Verify if the fatigue level is set properly though the constructor and setter */ @Test void testSetFatigue() { - final var model = new GiantModel("giant1", Health.HEALTHY, Fatigue.ALERT, - Nourishment.SATURATED); + final var model = + new GiantModel("giant1", Health.HEALTHY, Fatigue.ALERT, Nourishment.SATURATED); assertEquals(Fatigue.ALERT, model.getFatigue()); var messageFormat = "Giant giant1, The giant looks healthy, %s and saturated."; for (final var fatigue : Fatigue.values()) { @@ -68,13 +62,11 @@ class GiantModelTest { } } - /** - * Verify if the nourishment level is set properly though the constructor and setter - */ + /** Verify if the nourishment level is set properly though the constructor and setter */ @Test void testSetNourishment() { - final var model = new GiantModel("giant1", Health.HEALTHY, Fatigue.ALERT, - Nourishment.SATURATED); + final var model = + new GiantModel("giant1", Health.HEALTHY, Fatigue.ALERT, Nourishment.SATURATED); assertEquals(Nourishment.SATURATED, model.getNourishment()); var messageFormat = "Giant giant1, The giant looks healthy, alert and %s."; for (final var nourishment : Nourishment.values()) { diff --git a/service-to-worker/src/test/java/com/iluwatar/servicetoworker/GiantViewTest.java b/service-to-worker/src/test/java/com/iluwatar/servicetoworker/GiantViewTest.java index 8f5f3bb35..fd4f39be9 100644 --- a/service-to-worker/src/test/java/com/iluwatar/servicetoworker/GiantViewTest.java +++ b/service-to-worker/src/test/java/com/iluwatar/servicetoworker/GiantViewTest.java @@ -31,18 +31,14 @@ import com.iluwatar.model.view.controller.Health; import com.iluwatar.model.view.controller.Nourishment; import org.junit.jupiter.api.Test; -/** - * The type Giant view test. - */ +/** The type Giant view test. */ class GiantViewTest { - /** - * Test display giant. - */ + /** Test display giant. */ @Test void testDispalyGiant() { - GiantModel giantModel = new GiantModel("giant1", Health.HEALTHY, Fatigue.ALERT, - Nourishment.SATURATED); + GiantModel giantModel = + new GiantModel("giant1", Health.HEALTHY, Fatigue.ALERT, Nourishment.SATURATED); GiantView giantView = new GiantView(); assertDoesNotThrow(() -> giantView.displayGiant(giantModel)); } diff --git a/session-facade/pom.xml b/session-facade/pom.xml index 2dfe12e0c..6dada70f5 100644 --- a/session-facade/pom.xml +++ b/session-facade/pom.xml @@ -37,9 +37,17 @@ session-facade + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter - junit-jupiter-api + junit-jupiter-engine test diff --git a/session-facade/src/main/java/com/iluwatar/sessionfacade/App.java b/session-facade/src/main/java/com/iluwatar/sessionfacade/App.java index 4f136b9fa..cd9194aad 100644 --- a/session-facade/src/main/java/com/iluwatar/sessionfacade/App.java +++ b/session-facade/src/main/java/com/iluwatar/sessionfacade/App.java @@ -26,23 +26,19 @@ package com.iluwatar.sessionfacade; /** - * The main entry point of the application that demonstrates the usage - * of the ShoppingFacade to manage the shopping process using the Session Facade pattern. - * This class serves as a client that interacts with the simplified - * interface provided by the ShoppingFacade, which encapsulates - * complex interactions with the underlying business services. - * The ShoppingFacade acts as a session bean that coordinates the communication - * between multiple services, hiding their complexity and providing a single, unified API. + * The main entry point of the application that demonstrates the usage of the ShoppingFacade to + * manage the shopping process using the Session Facade pattern. This class serves as a client that + * interacts with the simplified interface provided by the ShoppingFacade, which encapsulates + * complex interactions with the underlying business services. The ShoppingFacade acts as a session + * bean that coordinates the communication between multiple services, hiding their complexity and + * providing a single, unified API. */ public class App { /** - * The entry point of the application. - * This method demonstrates how the ShoppingFacade, acting as a Session Facade, is used to: - * - Add items to the shopping cart - * - Process a payment - * - Place the order - * The session facade manages the communication between the individual services - * and simplifies the interactions for the client. + * The entry point of the application. This method demonstrates how the ShoppingFacade, acting as + * a Session Facade, is used to: - Add items to the shopping cart - Process a payment - Place the + * order The session facade manages the communication between the individual services and + * simplifies the interactions for the client. * * @param args the input arguments */ diff --git a/session-facade/src/main/java/com/iluwatar/sessionfacade/CartService.java b/session-facade/src/main/java/com/iluwatar/sessionfacade/CartService.java index 4bf9bde26..00cfbb540 100644 --- a/session-facade/src/main/java/com/iluwatar/sessionfacade/CartService.java +++ b/session-facade/src/main/java/com/iluwatar/sessionfacade/CartService.java @@ -25,29 +25,24 @@ package com.iluwatar.sessionfacade; - import java.util.Map; import lombok.Getter; import lombok.extern.slf4j.Slf4j; /** - * The type Cart service. - * Represents the cart entity, has add to cart and remove from cart methods + * The type Cart service. Represents the cart entity, has add to cart and remove from cart methods */ @Slf4j public class CartService { - /** - * -- GETTER -- - * Gets cart. - */ - @Getter - private final Map cart; + /** -- GETTER -- Gets cart. */ + @Getter private final Map cart; + private final Map productCatalog; /** * Instantiates a new Cart service. * - * @param cart the cart + * @param cart the cart * @param productCatalog the product catalog */ public CartService(Map cart, Map productCatalog) { @@ -83,5 +78,4 @@ public class CartService { LOGGER.info("No product is found in cart with id {}", productId); } } - } diff --git a/session-facade/src/main/java/com/iluwatar/sessionfacade/OrderService.java b/session-facade/src/main/java/com/iluwatar/sessionfacade/OrderService.java index 9ffa94b71..a67dda0aa 100644 --- a/session-facade/src/main/java/com/iluwatar/sessionfacade/OrderService.java +++ b/session-facade/src/main/java/com/iluwatar/sessionfacade/OrderService.java @@ -29,12 +29,11 @@ import java.util.Map; import lombok.extern.slf4j.Slf4j; /** - * The OrderService class is responsible for finalizing a customer's order. - * It includes a method to calculate the total cost of the order, which follows - * the information expert principle from GRASP by assigning the responsibility - * of total calculation to this service. - * Additionally, it provides a method to complete the order, which empties the - * client's shopping cart once the order is finalized. + * The OrderService class is responsible for finalizing a customer's order. It includes a method to + * calculate the total cost of the order, which follows the information expert principle from GRASP + * by assigning the responsibility of total calculation to this service. Additionally, it provides a + * method to complete the order, which empties the client's shopping cart once the order is + * finalized. */ @Slf4j public class OrderService { @@ -49,14 +48,12 @@ public class OrderService { this.cart = cart; } - /** - * Order. - */ + /** Order. */ public void order() { Double total = getTotal(); if (!this.cart.isEmpty()) { - LOGGER.info("Client has chosen to order {} with total {}", cart, - String.format("%.2f", total)); + LOGGER.info( + "Client has chosen to order {} with total {}", cart, String.format("%.2f", total)); this.completeOrder(); } else { LOGGER.info("Client's shopping cart is empty"); @@ -74,9 +71,7 @@ public class OrderService { return total[0]; } - /** - * Complete order. - */ + /** Complete order. */ public void completeOrder() { this.cart.clear(); } diff --git a/session-facade/src/main/java/com/iluwatar/sessionfacade/PaymentService.java b/session-facade/src/main/java/com/iluwatar/sessionfacade/PaymentService.java index ce9ce8fed..92b6bf5fa 100644 --- a/session-facade/src/main/java/com/iluwatar/sessionfacade/PaymentService.java +++ b/session-facade/src/main/java/com/iluwatar/sessionfacade/PaymentService.java @@ -29,19 +29,15 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * The PaymentService class is responsible for handling the selection and processing - * of different payment methods. It provides functionality to select a payment method - * (cash or credit card) and process the corresponding payment option. The class uses - * logging to inform the client of the selected payment method. - * It includes methods to: - * - Select the payment method based on the client's choice. - * - Process cash payments through the `cashPayment()` method. - * - Process credit card payments through the `creditCardPayment()` method. + * The PaymentService class is responsible for handling the selection and processing of different + * payment methods. It provides functionality to select a payment method (cash or credit card) and + * process the corresponding payment option. The class uses logging to inform the client of the + * selected payment method. It includes methods to: - Select the payment method based on the + * client's choice. - Process cash payments through the `cashPayment()` method. - Process credit + * card payments through the `creditCardPayment()` method. */ public class PaymentService { - /** - * The constant LOGGER. - */ + /** The constant LOGGER. */ public static Logger LOGGER = LoggerFactory.getLogger(PaymentService.class); /** @@ -59,16 +55,12 @@ public class PaymentService { } } - /** - * Cash payment. - */ + /** Cash payment. */ public void cashPayment() { LOGGER.info("Client have chosen cash payment option"); } - /** - * Credit card payment. - */ + /** Credit card payment. */ public void creditCardPayment() { LOGGER.info("Client have chosen credit card payment option"); } diff --git a/session-facade/src/main/java/com/iluwatar/sessionfacade/Product.java b/session-facade/src/main/java/com/iluwatar/sessionfacade/Product.java index 9727a94db..ff4b8afd1 100644 --- a/session-facade/src/main/java/com/iluwatar/sessionfacade/Product.java +++ b/session-facade/src/main/java/com/iluwatar/sessionfacade/Product.java @@ -25,14 +25,10 @@ package com.iluwatar.sessionfacade; -/** - * The type Product. - */ +/** The type Product. */ public record Product(int id, String name, double price, String description) { @Override public String toString() { return "ID: " + id + "\nName: " + name + "\nPrice: $" + price + "\nDescription: " + description; } } - - diff --git a/session-facade/src/main/java/com/iluwatar/sessionfacade/ProductCatalogService.java b/session-facade/src/main/java/com/iluwatar/sessionfacade/ProductCatalogService.java index cd6a997f9..b892c32e9 100644 --- a/session-facade/src/main/java/com/iluwatar/sessionfacade/ProductCatalogService.java +++ b/session-facade/src/main/java/com/iluwatar/sessionfacade/ProductCatalogService.java @@ -28,10 +28,9 @@ package com.iluwatar.sessionfacade; import java.util.Map; /** - * The type ProductCatalogService. - * This class manages a catalog of products. It holds a map of products, - * where each product is identified by a unique ID. The class - * provides functionality to access and manage the products in the catalog. + * The type ProductCatalogService. This class manages a catalog of products. It holds a map of + * products, where each product is identified by a unique ID. The class provides functionality to + * access and manage the products in the catalog. */ public class ProductCatalogService { diff --git a/session-facade/src/main/java/com/iluwatar/sessionfacade/ShoppingFacade.java b/session-facade/src/main/java/com/iluwatar/sessionfacade/ShoppingFacade.java index 145605181..cdfe44a7c 100644 --- a/session-facade/src/main/java/com/iluwatar/sessionfacade/ShoppingFacade.java +++ b/session-facade/src/main/java/com/iluwatar/sessionfacade/ShoppingFacade.java @@ -29,21 +29,16 @@ import java.util.HashMap; import java.util.Map; import lombok.extern.slf4j.Slf4j; - /** - * The ShoppingFacade class provides a simplified interface for clients to interact with the shopping system. - * It acts as a facade to handle operations related to a shopping cart, order processing, and payment. - * Responsibilities: - * - Add products to the shopping cart. - * - Remove products from the shopping cart. - * - Retrieve the current shopping cart. - * - Finalize an order by calling the order service. - * - Check if a payment is required based on the order total. - * - Process payment using different payment methods (e.g., cash, credit card). - * The ShoppingFacade class delegates operations to the following services: - * - CartService: Manages the cart and product catalog. - * - OrderService: Handles the order finalization process and calculation of the total. - * - PaymentService: Handles the payment processing based on the selected payment method. + * The ShoppingFacade class provides a simplified interface for clients to interact with the + * shopping system. It acts as a facade to handle operations related to a shopping cart, order + * processing, and payment. Responsibilities: - Add products to the shopping cart. - Remove products + * from the shopping cart. - Retrieve the current shopping cart. - Finalize an order by calling the + * order service. - Check if a payment is required based on the order total. - Process payment using + * different payment methods (e.g., cash, credit card). The ShoppingFacade class delegates + * operations to the following services: - CartService: Manages the cart and product catalog. - + * OrderService: Handles the order finalization process and calculation of the total. - + * PaymentService: Handles the payment processing based on the selected payment method. */ @Slf4j public class ShoppingFacade { @@ -51,13 +46,15 @@ public class ShoppingFacade { private final OrderService orderService; private final PaymentService paymentService; - /** - * Instantiates a new Shopping facade. - */ + /** Instantiates a new Shopping facade. */ public ShoppingFacade() { Map productCatalog = new HashMap<>(); - productCatalog.put(1, new Product(1, "Wireless Mouse", 25.99, "Ergonomic wireless mouse with USB receiver.")); - productCatalog.put(2, new Product(2, "Gaming Keyboard", 79.99, "RGB mechanical gaming keyboard with programmable keys.")); + productCatalog.put( + 1, new Product(1, "Wireless Mouse", 25.99, "Ergonomic wireless mouse with USB receiver.")); + productCatalog.put( + 2, + new Product( + 2, "Gaming Keyboard", 79.99, "RGB mechanical gaming keyboard with programmable keys.")); Map cart = new HashMap<>(); cartService = new CartService(cart, productCatalog); orderService = new OrderService(cart); @@ -91,9 +88,7 @@ public class ShoppingFacade { this.cartService.removeFromCart(productId); } - /** - * Order. - */ + /** Order. */ public void order() { this.orderService.order(); } diff --git a/session-facade/src/test/java/com/iluwatar/sessionfacade/AppTest.java b/session-facade/src/test/java/com/iluwatar/sessionfacade/AppTest.java index 012fcf462..707fd944e 100644 --- a/session-facade/src/test/java/com/iluwatar/sessionfacade/AppTest.java +++ b/session-facade/src/test/java/com/iluwatar/sessionfacade/AppTest.java @@ -26,17 +26,12 @@ package com.iluwatar.sessionfacade; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -/** - * The type App test. - */ +/** The type App test. */ public class AppTest { - /** - * Should execute application without exception. - */ + /** Should execute application without exception. */ @org.junit.jupiter.api.Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } - } diff --git a/session-facade/src/test/java/com/iluwatar/sessionfacade/CartServiceTest.java b/session-facade/src/test/java/com/iluwatar/sessionfacade/CartServiceTest.java index 958bd20f9..ef42fcabd 100644 --- a/session-facade/src/test/java/com/iluwatar/sessionfacade/CartServiceTest.java +++ b/session-facade/src/test/java/com/iluwatar/sessionfacade/CartServiceTest.java @@ -24,43 +24,34 @@ */ package com.iluwatar.sessionfacade; +import static org.junit.jupiter.api.Assertions.*; + +import java.util.HashMap; +import java.util.Map; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.MockitoAnnotations; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import static org.junit.jupiter.api.Assertions.*; - -/** - * The type Cart service test. - */ +/** The type Cart service test. */ @Slf4j class CartServiceTest { private CartService cartService; - private Map cart; + private Map cart; - /** - * Sets up. - */ + /** Sets up. */ @BeforeEach void setUp() { MockitoAnnotations.openMocks(this); cart = new HashMap<>(); - Map productCatalog = new HashMap<>(); - productCatalog.put(1,new Product(1, "Product A", 2.0, "any description")); - productCatalog.put(2,new Product(2, "Product B", 300.0, "a watch")); + Map productCatalog = new HashMap<>(); + productCatalog.put(1, new Product(1, "Product A", 2.0, "any description")); + productCatalog.put(2, new Product(2, "Product B", 300.0, "a watch")); cartService = new CartService(cart, productCatalog); } - /** - * Test add to cart. - */ + /** Test add to cart. */ @Test void testAddToCart() { cartService.addToCart(1); @@ -68,9 +59,7 @@ class CartServiceTest { assertEquals("Product A", cart.get(1).name()); } - /** - * Test remove from cart. - */ + /** Test remove from cart. */ @Test void testRemoveFromCart() { cartService.addToCart(1); @@ -79,18 +68,14 @@ class CartServiceTest { assertTrue(cart.isEmpty()); } - /** - * Test add to cart with invalid product id. - */ + /** Test add to cart with invalid product id. */ @Test void testAddToCartWithInvalidProductId() { cartService.addToCart(999); assertTrue(cart.isEmpty()); } - /** - * Test remove from cart with invalid product id. - */ + /** Test remove from cart with invalid product id. */ @Test void testRemoveFromCartWithInvalidProductId() { cartService.removeFromCart(999); diff --git a/session-facade/src/test/java/com/iluwatar/sessionfacade/PaymentServiceTest.java b/session-facade/src/test/java/com/iluwatar/sessionfacade/PaymentServiceTest.java index 583b8a6f9..609cc3559 100644 --- a/session-facade/src/test/java/com/iluwatar/sessionfacade/PaymentServiceTest.java +++ b/session-facade/src/test/java/com/iluwatar/sessionfacade/PaymentServiceTest.java @@ -24,23 +24,19 @@ */ package com.iluwatar.sessionfacade; +import static org.mockito.Mockito.*; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.slf4j.Logger; -import static org.mockito.Mockito.*; - -/** - * The type Payment service test. - */ +/** The type Payment service test. */ class PaymentServiceTest { private PaymentService paymentService; private OrderService orderService; private Logger mockLogger; - /** - * Sets up. - */ + /** Sets up. */ @BeforeEach void setUp() { paymentService = new PaymentService(); @@ -48,9 +44,7 @@ class PaymentServiceTest { paymentService.LOGGER = mockLogger; } - /** - * Test select cash payment method. - */ + /** Test select cash payment method. */ @Test void testSelectCashPaymentMethod() { String method = "cash"; @@ -58,9 +52,7 @@ class PaymentServiceTest { verify(mockLogger).info("Client have chosen cash payment option"); } - /** - * Test select credit card payment method. - */ + /** Test select credit card payment method. */ @Test void testSelectCreditCardPaymentMethod() { String method = "credit"; @@ -68,9 +60,7 @@ class PaymentServiceTest { verify(mockLogger).info("Client have chosen credit card payment option"); } - /** - * Test select unspecified payment method. - */ + /** Test select unspecified payment method. */ @Test void testSelectUnspecifiedPaymentMethod() { String method = "cheque"; diff --git a/session-facade/src/test/java/com/iluwatar/sessionfacade/ProductTest.java b/session-facade/src/test/java/com/iluwatar/sessionfacade/ProductTest.java index 2d6646985..3da660ca8 100644 --- a/session-facade/src/test/java/com/iluwatar/sessionfacade/ProductTest.java +++ b/session-facade/src/test/java/com/iluwatar/sessionfacade/ProductTest.java @@ -24,33 +24,27 @@ */ package com.iluwatar.sessionfacade; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.*; -/** - * The type Product test. - */ +import org.junit.jupiter.api.Test; + +/** The type Product test. */ public class ProductTest { - /** - * Test product creation. - */ + /** Test product creation. */ @Test public void testProductCreation() { int id = 1; String name = "Product A"; double price = 200.0; String description = "a description"; - Product product = new Product(id,name,price,description); + Product product = new Product(id, name, price, description); assertEquals(id, product.id()); assertEquals(name, product.name()); assertEquals(price, product.price()); assertEquals(description, product.description()); } - /** - * Test equals and hash code. - */ + /** Test equals and hash code. */ @Test public void testEqualsAndHashCode() { Product product1 = new Product(1, "Product A", 99.99, "a description"); @@ -63,9 +57,7 @@ public class ProductTest { assertNotEquals(product1.hashCode(), product3.hashCode()); } - /** - * Test to string. - */ + /** Test to string. */ @Test public void testToString() { Product product = new Product(1, "Product A", 99.99, "a description"); @@ -73,5 +65,4 @@ public class ProductTest { assertTrue(toStringResult.contains("Product A")); assertTrue(toStringResult.contains("99.99")); } - } diff --git a/session-facade/src/test/java/com/iluwatar/sessionfacade/ShoppingFacadeTest.java b/session-facade/src/test/java/com/iluwatar/sessionfacade/ShoppingFacadeTest.java index 01e4cb588..b77e60296 100644 --- a/session-facade/src/test/java/com/iluwatar/sessionfacade/ShoppingFacadeTest.java +++ b/session-facade/src/test/java/com/iluwatar/sessionfacade/ShoppingFacadeTest.java @@ -24,17 +24,14 @@ */ package com.iluwatar.sessionfacade; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import java.util.List; -import java.util.Map; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; -/** - * Unit tests for ShoppingFacade. - */ +import java.util.Map; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** Unit tests for ShoppingFacade. */ class ShoppingFacadeTest { private ShoppingFacade shoppingFacade; @@ -48,10 +45,14 @@ class ShoppingFacadeTest { void testAddToCart() { shoppingFacade.addToCart(1); shoppingFacade.addToCart(2); - Map cart = shoppingFacade.getCart(); + Map cart = shoppingFacade.getCart(); assertEquals(2, cart.size(), "Cart should contain two items."); - assertEquals("Wireless Mouse", cart.get(1).name(), "First item in the cart should be 'Wireless Mouse'."); - assertEquals("Gaming Keyboard", cart.get(2).name(), "Second item in the cart should be 'Gaming Keyboard'."); + assertEquals( + "Wireless Mouse", cart.get(1).name(), "First item in the cart should be 'Wireless Mouse'."); + assertEquals( + "Gaming Keyboard", + cart.get(2).name(), + "Second item in the cart should be 'Gaming Keyboard'."); } @Test @@ -59,9 +60,10 @@ class ShoppingFacadeTest { shoppingFacade.addToCart(1); shoppingFacade.addToCart(2); shoppingFacade.removeFromCart(1); - Map cart = shoppingFacade.getCart(); + Map cart = shoppingFacade.getCart(); assertEquals(1, cart.size(), "Cart should contain one item after removal."); - assertEquals("Gaming Keyboard", cart.get(2).name(), "Remaining item should be 'Gaming Keyboard'."); + assertEquals( + "Gaming Keyboard", cart.get(2).name(), "Remaining item should be 'Gaming Keyboard'."); } @Test diff --git a/sharding/pom.xml b/sharding/pom.xml index 2edd3a458..8461ccf5f 100644 --- a/sharding/pom.xml +++ b/sharding/pom.xml @@ -34,6 +34,14 @@ 4.0.0 sharding + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/sharding/src/main/java/com/iluwatar/sharding/App.java b/sharding/src/main/java/com/iluwatar/sharding/App.java index f8c9ce2f8..56b0edb2f 100644 --- a/sharding/src/main/java/com/iluwatar/sharding/App.java +++ b/sharding/src/main/java/com/iluwatar/sharding/App.java @@ -85,5 +85,4 @@ public class App { shard2.clearData(); shard3.clearData(); } - } diff --git a/sharding/src/main/java/com/iluwatar/sharding/Data.java b/sharding/src/main/java/com/iluwatar/sharding/Data.java index e87a73748..c0b4188d1 100644 --- a/sharding/src/main/java/com/iluwatar/sharding/Data.java +++ b/sharding/src/main/java/com/iluwatar/sharding/Data.java @@ -27,9 +27,7 @@ package com.iluwatar.sharding; import lombok.Getter; import lombok.Setter; -/** - * Basic data structure for each tuple stored in data shards. - */ +/** Basic data structure for each tuple stored in data shards. */ @Getter @Setter public class Data { @@ -42,6 +40,7 @@ public class Data { /** * Constructor of Data class. + * * @param key data key * @param value data value * @param type data type @@ -53,14 +52,13 @@ public class Data { } enum DataType { - TYPE_1, TYPE_2, TYPE_3 + TYPE_1, + TYPE_2, + TYPE_3 } @Override public String toString() { - return "Data {" + "key=" - + key + ", value='" + value - + '\'' + ", type=" + type + '}'; + return "Data {" + "key=" + key + ", value='" + value + '\'' + ", type=" + type + '}'; } } - diff --git a/sharding/src/main/java/com/iluwatar/sharding/HashShardManager.java b/sharding/src/main/java/com/iluwatar/sharding/HashShardManager.java index 48961b8a1..c0d481a0d 100644 --- a/sharding/src/main/java/com/iluwatar/sharding/HashShardManager.java +++ b/sharding/src/main/java/com/iluwatar/sharding/HashShardManager.java @@ -27,10 +27,9 @@ package com.iluwatar.sharding; import lombok.extern.slf4j.Slf4j; /** - * ShardManager with hash strategy. The purpose of this strategy is to reduce the - * chance of hot-spots in the data. It aims to distribute the data across the shards - * in a way that achieves a balance between the size of each shard and the average - * load that each shard will encounter. + * ShardManager with hash strategy. The purpose of this strategy is to reduce the chance of + * hot-spots in the data. It aims to distribute the data across the shards in a way that achieves a + * balance between the size of each shard and the average load that each shard will encounter. */ @Slf4j public class HashShardManager extends ShardManager { @@ -50,5 +49,4 @@ public class HashShardManager extends ShardManager { var hash = data.getKey() % shardCount; return hash == 0 ? hash + shardCount : hash; } - } diff --git a/sharding/src/main/java/com/iluwatar/sharding/LookupShardManager.java b/sharding/src/main/java/com/iluwatar/sharding/LookupShardManager.java index 35195c9db..f9a5c05d6 100644 --- a/sharding/src/main/java/com/iluwatar/sharding/LookupShardManager.java +++ b/sharding/src/main/java/com/iluwatar/sharding/LookupShardManager.java @@ -30,9 +30,8 @@ import java.util.Map; import lombok.extern.slf4j.Slf4j; /** - * ShardManager with lookup strategy. In this strategy the sharding logic implements - * a map that routes a request for data to the shard that contains that data by using - * the shard key. + * ShardManager with lookup strategy. In this strategy the sharding logic implements a map that + * routes a request for data to the shard that contains that data by using the shard key. */ @Slf4j public class LookupShardManager extends ShardManager { @@ -59,5 +58,4 @@ public class LookupShardManager extends ShardManager { return new SecureRandom().nextInt(shardCount - 1) + 1; } } - } diff --git a/sharding/src/main/java/com/iluwatar/sharding/RangeShardManager.java b/sharding/src/main/java/com/iluwatar/sharding/RangeShardManager.java index 13596b356..093b29910 100644 --- a/sharding/src/main/java/com/iluwatar/sharding/RangeShardManager.java +++ b/sharding/src/main/java/com/iluwatar/sharding/RangeShardManager.java @@ -51,5 +51,4 @@ public class RangeShardManager extends ShardManager { case TYPE_3 -> 3; }; } - } diff --git a/sharding/src/main/java/com/iluwatar/sharding/Shard.java b/sharding/src/main/java/com/iluwatar/sharding/Shard.java index 535399e74..7ed2cda14 100644 --- a/sharding/src/main/java/com/iluwatar/sharding/Shard.java +++ b/sharding/src/main/java/com/iluwatar/sharding/Shard.java @@ -28,13 +28,10 @@ import java.util.HashMap; import java.util.Map; import lombok.Getter; -/** - * The Shard class stored data in a HashMap. - */ +/** The Shard class stored data in a HashMap. */ public class Shard { - @Getter - private final int id; + @Getter private final int id; private final Map dataStore; diff --git a/sharding/src/main/java/com/iluwatar/sharding/ShardManager.java b/sharding/src/main/java/com/iluwatar/sharding/ShardManager.java index a87b58d04..8283b2c67 100644 --- a/sharding/src/main/java/com/iluwatar/sharding/ShardManager.java +++ b/sharding/src/main/java/com/iluwatar/sharding/ShardManager.java @@ -28,9 +28,7 @@ import java.util.HashMap; import java.util.Map; import lombok.extern.slf4j.Slf4j; -/** - * Abstract class for ShardManager. - */ +/** Abstract class for ShardManager. */ @Slf4j public abstract class ShardManager { @@ -44,8 +42,8 @@ public abstract class ShardManager { * Add a provided shard instance to shardMap. * * @param shard new shard instance. - * @return {@code true} if succeed to add the new instance. - * {@code false} if the shardId is already existed. + * @return {@code true} if succeed to add the new instance. {@code false} if the shardId is + * already existed. */ public boolean addNewShard(final Shard shard) { var shardId = shard.getId(); @@ -97,5 +95,4 @@ public abstract class ShardManager { * @return id of shard that the data should be stored */ protected abstract int allocateShard(final Data data); - } diff --git a/sharding/src/test/java/com/iluwatar/sharding/AppTest.java b/sharding/src/test/java/com/iluwatar/sharding/AppTest.java index fc3c59073..c6d68aad1 100644 --- a/sharding/src/test/java/com/iluwatar/sharding/AppTest.java +++ b/sharding/src/test/java/com/iluwatar/sharding/AppTest.java @@ -28,14 +28,11 @@ import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import org.junit.jupiter.api.Test; -/** - * Unit tests for App class. - */ +/** Unit tests for App class. */ class AppTest { @Test void shouldExecuteWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } - } diff --git a/sharding/src/test/java/com/iluwatar/sharding/HashShardManagerTest.java b/sharding/src/test/java/com/iluwatar/sharding/HashShardManagerTest.java index b5b5202dc..d01d3406e 100644 --- a/sharding/src/test/java/com/iluwatar/sharding/HashShardManagerTest.java +++ b/sharding/src/test/java/com/iluwatar/sharding/HashShardManagerTest.java @@ -29,16 +29,12 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -/** - * Unit tests for HashShardManager class. - */ +/** Unit tests for HashShardManager class. */ class HashShardManagerTest { private HashShardManager hashShardManager; - /** - * Initialize hashShardManager instance. - */ + /** Initialize hashShardManager instance. */ @BeforeEach void setup() { hashShardManager = new HashShardManager(); @@ -56,5 +52,4 @@ class HashShardManagerTest { hashShardManager.storeData(data); assertEquals(data, hashShardManager.getShardById(1).getDataById(1)); } - } diff --git a/sharding/src/test/java/com/iluwatar/sharding/LookupShardManagerTest.java b/sharding/src/test/java/com/iluwatar/sharding/LookupShardManagerTest.java index a8b8ab1da..d4b3c02dc 100644 --- a/sharding/src/test/java/com/iluwatar/sharding/LookupShardManagerTest.java +++ b/sharding/src/test/java/com/iluwatar/sharding/LookupShardManagerTest.java @@ -31,16 +31,12 @@ import java.util.Map; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -/** - * Unit tests for LookupShardManager class. - */ +/** Unit tests for LookupShardManager class. */ class LookupShardManagerTest { private LookupShardManager lookupShardManager; - /** - * Initialize lookupShardManager instance. - */ + /** Initialize lookupShardManager instance. */ @BeforeEach void setup() { lookupShardManager = new LookupShardManager(); diff --git a/sharding/src/test/java/com/iluwatar/sharding/RangeShardManagerTest.java b/sharding/src/test/java/com/iluwatar/sharding/RangeShardManagerTest.java index 299adc622..dbc8a68ba 100644 --- a/sharding/src/test/java/com/iluwatar/sharding/RangeShardManagerTest.java +++ b/sharding/src/test/java/com/iluwatar/sharding/RangeShardManagerTest.java @@ -29,16 +29,12 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -/** - * Unit tests for RangeShardManager class. - */ +/** Unit tests for RangeShardManager class. */ class RangeShardManagerTest { private RangeShardManager rangeShardManager; - /** - * Initialize rangeShardManager instance. - */ + /** Initialize rangeShardManager instance. */ @BeforeEach void setup() { rangeShardManager = new RangeShardManager(); @@ -56,5 +52,4 @@ class RangeShardManagerTest { rangeShardManager.storeData(data); assertEquals(data, rangeShardManager.getShardById(1).getDataById(1)); } - } diff --git a/sharding/src/test/java/com/iluwatar/sharding/ShardManagerTest.java b/sharding/src/test/java/com/iluwatar/sharding/ShardManagerTest.java index f5da39ddb..fe7cf09c0 100644 --- a/sharding/src/test/java/com/iluwatar/sharding/ShardManagerTest.java +++ b/sharding/src/test/java/com/iluwatar/sharding/ShardManagerTest.java @@ -32,16 +32,12 @@ import java.util.Map; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -/** - * Unit tests for ShardManager class. - */ +/** Unit tests for ShardManager class. */ class ShardManagerTest { private ShardManager shardManager; - /** - * Initialize shardManager instance. - */ + /** Initialize shardManager instance. */ @BeforeEach void setup() { shardManager = new TestShardManager(); diff --git a/sharding/src/test/java/com/iluwatar/sharding/ShardTest.java b/sharding/src/test/java/com/iluwatar/sharding/ShardTest.java index 7b18440a8..81312e9e0 100644 --- a/sharding/src/test/java/com/iluwatar/sharding/ShardTest.java +++ b/sharding/src/test/java/com/iluwatar/sharding/ShardTest.java @@ -32,10 +32,7 @@ import java.util.Map; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; - -/** - * Unit tests for Shard class. - */ +/** Unit tests for Shard class. */ class ShardTest { private Data data; @@ -60,7 +57,6 @@ class ShardTest { } catch (NoSuchFieldException | IllegalAccessException e) { fail("Fail to modify field access."); } - } @Test diff --git a/single-table-inheritance/pom.xml b/single-table-inheritance/pom.xml index a9ea9c70e..6e3afcf38 100644 --- a/single-table-inheritance/pom.xml +++ b/single-table-inheritance/pom.xml @@ -36,18 +36,11 @@ single-table-inheritance - - - - org.springframework.boot - spring-boot-dependencies - pom - 3.2.3 - import - - - + + org.springframework.boot + spring-boot-starter + org.springframework.boot spring-boot-starter-data-jpa @@ -55,17 +48,13 @@ jakarta.xml.bind jakarta.xml.bind-api + 4.0.2 com.h2database h2 runtime - - org.projectlombok - lombok - true - org.springframework.boot spring-boot-starter-test diff --git a/single-table-inheritance/src/main/java/com/iluwatar/SingleTableInheritance.java b/single-table-inheritance/src/main/java/com/iluwatar/SingleTableInheritance.java index 69cc21be6..f27b71213 100644 --- a/single-table-inheritance/src/main/java/com/iluwatar/SingleTableInheritance.java +++ b/single-table-inheritance/src/main/java/com/iluwatar/SingleTableInheritance.java @@ -37,32 +37,28 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** - * Single Table Inheritance pattern : + * Single Table Inheritance pattern :
+ * It maps each instance of class in an inheritance tree into a single table.
+ * + *

In case of current project, in order to specify the Single Table Inheritance to Hibernate we + * annotate the main Vehicle root class with @Inheritance(strategy = InheritanceType.SINGLE_TABLE) + * due to which a single root Vehicle class table will be created in the database and it will + * have columns for all the fields of it's subclasses(Car, Freighter, Train, Truck).
+ * Additional to that, a new separate "vehicle_id" column would be added to the Vehicle table + * to save the type of the subclass object that is being stored in the database. This value is + * specified by the @DiscriminatorValue annotation value for each subclass in case of Hibernate. *
- * It maps each instance of class in an inheritance tree into a single table. *
- *

- * In case of current project, in order to specify the Single Table Inheritance to Hibernate - * we annotate the main Vehicle root class with @Inheritance(strategy = InheritanceType.SINGLE_TABLE) - * due to which a single root Vehicle class table will be created - * in the database and it will have columns for all the fields of - * it's subclasses(Car, Freighter, Train, Truck).
- * Additional to that, a new separate "vehicle_id" column would be added - * to the Vehicle table to save the type of the subclass object that - * is being stored in the database. This value is specified by the @DiscriminatorValue annotation - * value for each subclass in case of Hibernate.
- *


* Below is the main Spring Boot Application class from where the Program Runs. - *

- * It implements the CommandLineRunner to run the statements at the - * start of the application program. - *

+ * + *

It implements the CommandLineRunner to run the statements at the start of the application + * program. */ @SpringBootApplication @AllArgsConstructor public class SingleTableInheritance implements CommandLineRunner { - //Autowiring the VehicleService class to execute the business logic methods + // Autowiring the VehicleService class to execute the business logic methods private final VehicleService vehicleService; /** @@ -75,8 +71,7 @@ public class SingleTableInheritance implements CommandLineRunner { } /** - * The starting point of the CommandLineRunner - * where the main program is run. + * The starting point of the CommandLineRunner where the main program is run. * * @param args program runtime arguments */ @@ -97,7 +92,6 @@ public class SingleTableInheritance implements CommandLineRunner { Vehicle truck1 = vehicleService.saveVehicle(vehicle2); log.info("Vehicle 2 saved : {}\n", truck1); - log.info("Fetching Vehicles :- "); // Fetching the Car from DB @@ -114,4 +108,4 @@ public class SingleTableInheritance implements CommandLineRunner { List allVehiclesFromDb = vehicleService.getAllVehicles(); allVehiclesFromDb.forEach(s -> log.info(s.toString())); } -} \ No newline at end of file +} diff --git a/single-table-inheritance/src/main/java/com/iluwatar/entity/Car.java b/single-table-inheritance/src/main/java/com/iluwatar/entity/Car.java index 932b71af2..b934767e1 100644 --- a/single-table-inheritance/src/main/java/com/iluwatar/entity/Car.java +++ b/single-table-inheritance/src/main/java/com/iluwatar/entity/Car.java @@ -31,13 +31,12 @@ import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; /** - * A class that extends the PassengerVehicle class - * and provides the concrete inheritance implementation of the Car. + * A class that extends the PassengerVehicle class and provides the concrete inheritance + * implementation of the Car. * * @see PassengerVehicle PassengerVehicle * @see Vehicle Vehicle */ - @Data @NoArgsConstructor @EqualsAndHashCode(callSuper = true) @@ -55,9 +54,6 @@ public class Car extends PassengerVehicle { // Overridden the toString method to specify the Vehicle object @Override public String toString() { - return "Car{" - + super.toString() - + '}'; + return "Car{" + super.toString() + '}'; } - } diff --git a/single-table-inheritance/src/main/java/com/iluwatar/entity/Freighter.java b/single-table-inheritance/src/main/java/com/iluwatar/entity/Freighter.java index 32fcda144..f97343b71 100644 --- a/single-table-inheritance/src/main/java/com/iluwatar/entity/Freighter.java +++ b/single-table-inheritance/src/main/java/com/iluwatar/entity/Freighter.java @@ -31,8 +31,8 @@ import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; /** - * A class that extends the TransportVehicle class - * and provides the concrete inheritance implementation of the Car. + * A class that extends the TransportVehicle class and provides the concrete inheritance + * implementation of the Car. * * @see TransportVehicle TransportVehicle * @see Vehicle Vehicle @@ -54,12 +54,6 @@ public class Freighter extends TransportVehicle { // Overridden the toString method to specify the Vehicle object @Override public String toString() { - return "Freighter{ " - + super.toString() - + " ," - + "flightLength=" - + flightLength - + '}'; + return "Freighter{ " + super.toString() + " ," + "flightLength=" + flightLength + '}'; } - } diff --git a/single-table-inheritance/src/main/java/com/iluwatar/entity/PassengerVehicle.java b/single-table-inheritance/src/main/java/com/iluwatar/entity/PassengerVehicle.java index f4908c730..b189bbd56 100644 --- a/single-table-inheritance/src/main/java/com/iluwatar/entity/PassengerVehicle.java +++ b/single-table-inheritance/src/main/java/com/iluwatar/entity/PassengerVehicle.java @@ -29,8 +29,8 @@ import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; /** - * An abstract class that extends the Vehicle class - * and provides properties for the Passenger type of Vehicles. + * An abstract class that extends the Vehicle class and provides properties for the Passenger type + * of Vehicles. * * @see Vehicle */ diff --git a/single-table-inheritance/src/main/java/com/iluwatar/entity/Train.java b/single-table-inheritance/src/main/java/com/iluwatar/entity/Train.java index 00d881054..6d220475a 100644 --- a/single-table-inheritance/src/main/java/com/iluwatar/entity/Train.java +++ b/single-table-inheritance/src/main/java/com/iluwatar/entity/Train.java @@ -31,8 +31,8 @@ import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; /** - * A class that extends the PassengerVehicle class - * and provides the concrete inheritance implementation of the Car. + * A class that extends the PassengerVehicle class and provides the concrete inheritance + * implementation of the Car. * * @see PassengerVehicle PassengerVehicle * @see Vehicle Vehicle @@ -54,9 +54,6 @@ public class Train extends PassengerVehicle { // Overridden the toString method to specify the Vehicle object @Override public String toString() { - return "Train{" - + super.toString() - + '}'; + return "Train{" + super.toString() + '}'; } - } diff --git a/single-table-inheritance/src/main/java/com/iluwatar/entity/TransportVehicle.java b/single-table-inheritance/src/main/java/com/iluwatar/entity/TransportVehicle.java index d3c104f3a..a996a9bb7 100644 --- a/single-table-inheritance/src/main/java/com/iluwatar/entity/TransportVehicle.java +++ b/single-table-inheritance/src/main/java/com/iluwatar/entity/TransportVehicle.java @@ -29,8 +29,8 @@ import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; /** - * An abstract class that extends the Vehicle class - * and provides properties for the Transport type of Vehicles. + * An abstract class that extends the Vehicle class and provides properties for the Transport type + * of Vehicles. * * @see Vehicle */ @@ -45,5 +45,4 @@ public abstract class TransportVehicle extends Vehicle { super(manufacturer, model); this.loadCapacity = loadCapacity; } - } diff --git a/single-table-inheritance/src/main/java/com/iluwatar/entity/Truck.java b/single-table-inheritance/src/main/java/com/iluwatar/entity/Truck.java index 56f2d0f95..46ccc29ca 100644 --- a/single-table-inheritance/src/main/java/com/iluwatar/entity/Truck.java +++ b/single-table-inheritance/src/main/java/com/iluwatar/entity/Truck.java @@ -30,8 +30,8 @@ import lombok.Data; import lombok.NoArgsConstructor; /** - * A class that extends the PassengerVehicle class - * and provides the concrete inheritance implementation of the Car. + * A class that extends the PassengerVehicle class and provides the concrete inheritance + * implementation of the Car. * * @see TransportVehicle TransportVehicle * @see Vehicle Vehicle @@ -52,11 +52,6 @@ public class Truck extends TransportVehicle { // Overridden the toString method to specify the Vehicle object @Override public String toString() { - return "Truck{ " - + super.toString() - + ", " - + "towingCapacity=" - + towingCapacity - + '}'; + return "Truck{ " + super.toString() + ", " + "towingCapacity=" + towingCapacity + '}'; } } diff --git a/single-table-inheritance/src/main/java/com/iluwatar/entity/Vehicle.java b/single-table-inheritance/src/main/java/com/iluwatar/entity/Vehicle.java index 992c4de9c..ed3cf4ae9 100644 --- a/single-table-inheritance/src/main/java/com/iluwatar/entity/Vehicle.java +++ b/single-table-inheritance/src/main/java/com/iluwatar/entity/Vehicle.java @@ -37,8 +37,8 @@ import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; /** - * An abstract class that is the root of the Vehicle Inheritance hierarchy - * and basic provides properties for all the vehicles. + * An abstract class that is the root of the Vehicle Inheritance hierarchy and basic provides + * properties for all the vehicles. */ @Data @NoArgsConstructor @@ -65,14 +65,13 @@ public abstract class Vehicle { @Override public String toString() { return "Vehicle{" - + "vehicleId=" - + vehicleId - + ", manufacturer='" - + manufacturer - + '\'' - + ", model='" - + model - + '}'; + + "vehicleId=" + + vehicleId + + ", manufacturer='" + + manufacturer + + '\'' + + ", model='" + + model + + '}'; } - } diff --git a/single-table-inheritance/src/main/java/com/iluwatar/repository/VehicleRepository.java b/single-table-inheritance/src/main/java/com/iluwatar/repository/VehicleRepository.java index 42ee063ee..1de73abab 100644 --- a/single-table-inheritance/src/main/java/com/iluwatar/repository/VehicleRepository.java +++ b/single-table-inheritance/src/main/java/com/iluwatar/repository/VehicleRepository.java @@ -29,10 +29,8 @@ import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; /** - * A repository that is extending the JPA Repository - * to provide the default Spring DATA JPA methods for the Vehicle class. + * A repository that is extending the JPA Repository to provide the default Spring DATA JPA methods + * for the Vehicle class. */ @Repository -public interface VehicleRepository extends JpaRepository { - -} +public interface VehicleRepository extends JpaRepository {} diff --git a/single-table-inheritance/src/main/java/com/iluwatar/service/VehicleService.java b/single-table-inheritance/src/main/java/com/iluwatar/service/VehicleService.java index 66946c813..1179590df 100644 --- a/single-table-inheritance/src/main/java/com/iluwatar/service/VehicleService.java +++ b/single-table-inheritance/src/main/java/com/iluwatar/service/VehicleService.java @@ -31,9 +31,8 @@ import lombok.AllArgsConstructor; import org.springframework.stereotype.Service; /** - * A service class that is used to provide the business logic - * for the Vehicle class and connect to the database to - * perform the CRUD operations on the root Vehicle class. + * A service class that is used to provide the business logic for the Vehicle class and connect to + * the database to perform the CRUD operations on the root Vehicle class. * * @see Vehicle */ @@ -91,5 +90,4 @@ public class VehicleService { public void deleteVehicle(Vehicle vehicle) { vehicleRepository.delete(vehicle); } - } diff --git a/singleton/pom.xml b/singleton/pom.xml index c6e7a65ca..5d6a57326 100644 --- a/singleton/pom.xml +++ b/singleton/pom.xml @@ -34,6 +34,14 @@ singleton + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/singleton/src/main/java/com/iluwatar/singleton/App.java b/singleton/src/main/java/com/iluwatar/singleton/App.java index 1b14f9ad7..ccc0ff827 100644 --- a/singleton/src/main/java/com/iluwatar/singleton/App.java +++ b/singleton/src/main/java/com/iluwatar/singleton/App.java @@ -27,39 +27,40 @@ package com.iluwatar.singleton; import lombok.extern.slf4j.Slf4j; /** - *

Singleton pattern ensures that the class can have only one existing instance per Java - * classloader instance and provides global access to it.

+ * Singleton pattern ensures that the class can have only one existing instance per Java classloader + * instance and provides global access to it. * *

One of the risks of this pattern is that bugs resulting from setting a singleton up in a - * distributed environment can be tricky to debug since it will work fine if you debug with a - * single classloader. Additionally, these problems can crop up a while after the implementation of - * a singleton, since they may start synchronous and only become async with time, so it may - * not be clear why you are seeing certain changes in behavior.

+ * distributed environment can be tricky to debug since it will work fine if you debug with a single + * classloader. Additionally, these problems can crop up a while after the implementation of a + * singleton, since they may start synchronous and only become async with time, so it may not be + * clear why you are seeing certain changes in behavior. * *

There are many ways to implement the Singleton. The first one is the eagerly initialized * instance in {@link IvoryTower}. Eager initialization implies that the implementation is thread * safe. If you can afford to give up control of the instantiation moment, then this implementation - * will suit you fine.

+ * will suit you fine. * *

The other option to implement eagerly initialized Singleton is enum-based Singleton. The * example is found in {@link EnumIvoryTower}. At first glance, the code looks short and simple. * However, you should be aware of the downsides including committing to implementation strategy, * extending the enum class, serializability, and restrictions to coding. These are extensively - * discussed in Stack Overflow: http://programmers.stackexchange.com/questions/179386/what-are-the-downsides-of-implementing - * -a-singleton-with-javas-enum

+ * discussed in Stack Overflow: + * http://programmers.stackexchange.com/questions/179386/what-are-the-downsides-of-implementing + * -a-singleton-with-javas-enum * *

{@link ThreadSafeLazyLoadedIvoryTower} is a Singleton implementation that is initialized on * demand. The downside is that it is very slow to access since the whole access method is - * synchronized.

+ * synchronized. * - *

Another Singleton implementation that is initialized on demand is found in - * {@link ThreadSafeDoubleCheckLocking}. It is somewhat faster than {@link - * ThreadSafeLazyLoadedIvoryTower} since it doesn't synchronize the whole access method but only the - * method internals on specific conditions.

+ *

Another Singleton implementation that is initialized on demand is found in {@link + * ThreadSafeDoubleCheckLocking}. It is somewhat faster than {@link ThreadSafeLazyLoadedIvoryTower} + * since it doesn't synchronize the whole access method but only the method internals on specific + * conditions. * - *

Yet another way to implement thread-safe lazily initialized Singleton can be found in - * {@link InitializingOnDemandHolderIdiom}. However, this implementation requires at least Java 8 - * API level to work.

+ *

Yet another way to implement thread-safe lazily initialized Singleton can be found in {@link + * InitializingOnDemandHolderIdiom}. However, this implementation requires at least Java 8 API level + * to work. */ @Slf4j public class App { diff --git a/singleton/src/main/java/com/iluwatar/singleton/BillPughImplementation.java b/singleton/src/main/java/com/iluwatar/singleton/BillPughImplementation.java index c5f6f9f2c..6d784787f 100644 --- a/singleton/src/main/java/com/iluwatar/singleton/BillPughImplementation.java +++ b/singleton/src/main/java/com/iluwatar/singleton/BillPughImplementation.java @@ -25,20 +25,16 @@ package com.iluwatar.singleton; /** - *

Bill Pugh Singleton Implementation.

- * - *

This implementation of the singleton design pattern takes advantage of the - * Java memory model's guarantees about class initialization. Each class is - * initialized only once, when it is first used. If the class hasn't been used - * yet, it won't be loaded into memory, and no memory will be allocated for - * a static instance. This makes the singleton instance lazy-loaded and thread-safe.

+ * Bill Pugh Singleton Implementation. * + *

This implementation of the singleton design pattern takes advantage of the Java memory model's + * guarantees about class initialization. Each class is initialized only once, when it is first + * used. If the class hasn't been used yet, it won't be loaded into memory, and no memory will be + * allocated for a static instance. This makes the singleton instance lazy-loaded and thread-safe. */ public final class BillPughImplementation { - /** - * Private constructor to prevent instantiation from outside the class. - */ + /** Private constructor to prevent instantiation from outside the class. */ private BillPughImplementation() { // to prevent instantiating by Reflection call if (InstanceHolder.instance != null) { @@ -47,24 +43,19 @@ public final class BillPughImplementation { } /** - * The InstanceHolder is a static inner class, and it holds the Singleton instance. - * It is not loaded into memory until the getInstance() method is called. + * The InstanceHolder is a static inner class, and it holds the Singleton instance. It is not + * loaded into memory until the getInstance() method is called. */ private static class InstanceHolder { - /** - * Singleton instance of the class. - */ + /** Singleton instance of the class. */ private static BillPughImplementation instance = new BillPughImplementation(); } /** * Public accessor for the singleton instance. * - *

- * When this method is called, the InstanceHolder is loaded into memory - * and creates the Singleton instance. This method provides a global access point - * for the singleton instance. - *

+ *

When this method is called, the InstanceHolder is loaded into memory and creates the + * Singleton instance. This method provides a global access point for the singleton instance. * * @return an instance of the class. */ diff --git a/singleton/src/main/java/com/iluwatar/singleton/EnumIvoryTower.java b/singleton/src/main/java/com/iluwatar/singleton/EnumIvoryTower.java index 8130dc55d..a33876642 100644 --- a/singleton/src/main/java/com/iluwatar/singleton/EnumIvoryTower.java +++ b/singleton/src/main/java/com/iluwatar/singleton/EnumIvoryTower.java @@ -25,16 +25,14 @@ package com.iluwatar.singleton; /** - *

Enum based singleton implementation. Effective Java 2nd Edition (Joshua Bloch) p. 18

+ * Enum based singleton implementation. Effective Java 2nd Edition (Joshua Bloch) p. 18 * - *

This implementation is thread safe, however adding any other method and its thread safety - * is developers responsibility.

+ *

This implementation is thread safe, however adding any other method and its thread safety is + * developers responsibility. */ public enum EnumIvoryTower { - /** - * The singleton instance of the class, created by the Java enum singleton pattern. - */ + /** The singleton instance of the class, created by the Java enum singleton pattern. */ INSTANCE; @Override diff --git a/singleton/src/main/java/com/iluwatar/singleton/InitializingOnDemandHolderIdiom.java b/singleton/src/main/java/com/iluwatar/singleton/InitializingOnDemandHolderIdiom.java index f2e427775..9f9a21057 100644 --- a/singleton/src/main/java/com/iluwatar/singleton/InitializingOnDemandHolderIdiom.java +++ b/singleton/src/main/java/com/iluwatar/singleton/InitializingOnDemandHolderIdiom.java @@ -25,23 +25,20 @@ package com.iluwatar.singleton; /** - *

The Initialize-on-demand-holder idiom is a secure way of creating a lazy initialized singleton - * object in Java.

+ * The Initialize-on-demand-holder idiom is a secure way of creating a lazy initialized singleton + * object in Java. * *

The technique is as lazy as possible and works in all known versions of Java. It takes - * advantage of language guarantees about class initialization, and will therefore work correctly - * in all Java-compliant compilers and virtual machines.

+ * advantage of language guarantees about class initialization, and will therefore work correctly in + * all Java-compliant compilers and virtual machines. * *

The inner class is referenced no earlier (and therefore loaded no earlier by the class loader) * than the moment that getInstance() is called. Thus, this solution is thread-safe without - * requiring special language constructs (i.e. volatile or synchronized).

- * + * requiring special language constructs (i.e. volatile or synchronized). */ public final class InitializingOnDemandHolderIdiom { - /** - * Private constructor. - */ + /** Private constructor. */ private InitializingOnDemandHolderIdiom() { // to prevent instantiating by Reflection call if (HelperHolder.INSTANCE != null) { @@ -58,14 +55,10 @@ public final class InitializingOnDemandHolderIdiom { return HelperHolder.INSTANCE; } - /** - * Provides the lazy-loaded Singleton instance. - */ + /** Provides the lazy-loaded Singleton instance. */ private static class HelperHolder { - /** - * Singleton instance of the class. - */ + /** Singleton instance of the class. */ private static final InitializingOnDemandHolderIdiom INSTANCE = new InitializingOnDemandHolderIdiom(); } diff --git a/singleton/src/main/java/com/iluwatar/singleton/IvoryTower.java b/singleton/src/main/java/com/iluwatar/singleton/IvoryTower.java index 362e1634c..fc89ab312 100644 --- a/singleton/src/main/java/com/iluwatar/singleton/IvoryTower.java +++ b/singleton/src/main/java/com/iluwatar/singleton/IvoryTower.java @@ -1,55 +1,49 @@ -/* - * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). - * - * The MIT License - * Copyright © 2014-2022 Ilkka Seppälä - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package com.iluwatar.singleton; - -/** - * Singleton class. Eagerly initialized static instance guarantees thread safety. - */ -public final class IvoryTower { - - /** - * Private constructor so nobody can instantiate the class. - */ - private IvoryTower() { - // to prevent instantiating by Reflection call - if (INSTANCE != null) { - throw new IllegalStateException("Already initialized."); - } - } - - /** - * Static to class instance of the class. - */ - private static final IvoryTower INSTANCE = new IvoryTower(); - - /** - * To be called by user to obtain instance of the class. - * - * @return instance of the singleton. - */ - public static IvoryTower getInstance() { - return INSTANCE; - } -} +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.singleton; + +/** Singleton class. Eagerly initialized static instance guarantees thread safety. */ +public final class IvoryTower { + + /** Private constructor so nobody can instantiate the class. */ + private IvoryTower() { + // to prevent instantiating by Reflection call + if (INSTANCE != null) { + throw new IllegalStateException("Already initialized."); + } + } + + /** Static to class instance of the class. */ + private static final IvoryTower INSTANCE = new IvoryTower(); + + /** + * To be called by user to obtain instance of the class. + * + * @return instance of the singleton. + */ + public static IvoryTower getInstance() { + return INSTANCE; + } +} diff --git a/singleton/src/main/java/com/iluwatar/singleton/ThreadSafeDoubleCheckLocking.java b/singleton/src/main/java/com/iluwatar/singleton/ThreadSafeDoubleCheckLocking.java index 8e6372493..dc3907f12 100644 --- a/singleton/src/main/java/com/iluwatar/singleton/ThreadSafeDoubleCheckLocking.java +++ b/singleton/src/main/java/com/iluwatar/singleton/ThreadSafeDoubleCheckLocking.java @@ -25,22 +25,20 @@ package com.iluwatar.singleton; /** - *

Double check locking.

+ * Double check locking. * - *

http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html

- * - *

Broken under Java 1.4.

+ *

http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html * + *

Broken under Java 1.4. */ public final class ThreadSafeDoubleCheckLocking { /** - * Singleton instance of the class, declared as volatile to ensure atomic access by multiple threads. + * Singleton instance of the class, declared as volatile to ensure atomic access by multiple + * threads. */ private static volatile ThreadSafeDoubleCheckLocking instance; - /** - * private constructor to prevent client from instantiating. - */ + /** private constructor to prevent client from instantiating. */ private ThreadSafeDoubleCheckLocking() { // to prevent instantiating by Reflection call if (instance != null) { diff --git a/singleton/src/main/java/com/iluwatar/singleton/ThreadSafeLazyLoadedIvoryTower.java b/singleton/src/main/java/com/iluwatar/singleton/ThreadSafeLazyLoadedIvoryTower.java index 4d1c25739..1ead462b9 100644 --- a/singleton/src/main/java/com/iluwatar/singleton/ThreadSafeLazyLoadedIvoryTower.java +++ b/singleton/src/main/java/com/iluwatar/singleton/ThreadSafeLazyLoadedIvoryTower.java @@ -25,20 +25,18 @@ package com.iluwatar.singleton; /** - *

Thread-safe Singleton class. The instance is lazily initialized and thus needs synchronization - * mechanism.

- * + * Thread-safe Singleton class. The instance is lazily initialized and thus needs synchronization + * mechanism. */ public final class ThreadSafeLazyLoadedIvoryTower { /** - * Singleton instance of the class, declared as volatile to ensure atomic access by multiple threads. + * Singleton instance of the class, declared as volatile to ensure atomic access by multiple + * threads. */ private static volatile ThreadSafeLazyLoadedIvoryTower instance; - /** - * Private constructor to prevent instantiation from outside the class. - */ + /** Private constructor to prevent instantiation from outside the class. */ private ThreadSafeLazyLoadedIvoryTower() { // Protect against instantiation via reflection if (instance != null) { diff --git a/singleton/src/test/java/com/iluwatar/singleton/AppTest.java b/singleton/src/test/java/com/iluwatar/singleton/AppTest.java index 468fe7299..085cb0f15 100644 --- a/singleton/src/test/java/com/iluwatar/singleton/AppTest.java +++ b/singleton/src/test/java/com/iluwatar/singleton/AppTest.java @@ -24,17 +24,15 @@ */ package com.iluwatar.singleton; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -/** - * Application test. - */ +import org.junit.jupiter.api.Test; + +/** Application test. */ class AppTest { @Test void shouldExecuteWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/singleton/src/test/java/com/iluwatar/singleton/BillPughImplementationTest.java b/singleton/src/test/java/com/iluwatar/singleton/BillPughImplementationTest.java index 0b00cfe22..0f61c6776 100644 --- a/singleton/src/test/java/com/iluwatar/singleton/BillPughImplementationTest.java +++ b/singleton/src/test/java/com/iluwatar/singleton/BillPughImplementationTest.java @@ -24,16 +24,10 @@ */ package com.iluwatar.singleton; -/** - * BillPughImplementationTest - * - */ -public class BillPughImplementationTest - extends SingletonTest{ - /** - * Create a new singleton test instance using the given 'getInstance' method. - */ - public BillPughImplementationTest() { - super(BillPughImplementation::getInstance); - } +/** BillPughImplementationTest */ +public class BillPughImplementationTest extends SingletonTest { + /** Create a new singleton test instance using the given 'getInstance' method. */ + public BillPughImplementationTest() { + super(BillPughImplementation::getInstance); + } } diff --git a/singleton/src/test/java/com/iluwatar/singleton/EnumIvoryTowerTest.java b/singleton/src/test/java/com/iluwatar/singleton/EnumIvoryTowerTest.java index cd40f2d3a..c6af4420a 100644 --- a/singleton/src/test/java/com/iluwatar/singleton/EnumIvoryTowerTest.java +++ b/singleton/src/test/java/com/iluwatar/singleton/EnumIvoryTowerTest.java @@ -24,31 +24,24 @@ */ package com.iluwatar.singleton; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertThrows; -/** - * EnumIvoryTowerTest - * - */ +import org.junit.jupiter.api.Test; + +/** EnumIvoryTowerTest */ class EnumIvoryTowerTest extends SingletonTest { - /** - * Create a new singleton test instance using the given 'getInstance' method. - */ + /** Create a new singleton test instance using the given 'getInstance' method. */ public EnumIvoryTowerTest() { super(() -> EnumIvoryTower.INSTANCE); } - /** - * Test creating new instance by reflection. - */ + /** Test creating new instance by reflection. */ @Override @Test void testCreatingNewInstanceByReflection() throws Exception { - // Java does not allow Enum instantiation http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.9 + // Java does not allow Enum instantiation + // http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.9 assertThrows(ReflectiveOperationException.class, EnumIvoryTower.class::getDeclaredConstructor); } - } diff --git a/singleton/src/test/java/com/iluwatar/singleton/InitializingOnDemandHolderIdiomTest.java b/singleton/src/test/java/com/iluwatar/singleton/InitializingOnDemandHolderIdiomTest.java index 5fd63f87d..5071dfc4f 100644 --- a/singleton/src/test/java/com/iluwatar/singleton/InitializingOnDemandHolderIdiomTest.java +++ b/singleton/src/test/java/com/iluwatar/singleton/InitializingOnDemandHolderIdiomTest.java @@ -24,18 +24,11 @@ */ package com.iluwatar.singleton; -/** - * InitializingOnDemandHolderIdiomTest - * - */ -class InitializingOnDemandHolderIdiomTest - extends SingletonTest { +/** InitializingOnDemandHolderIdiomTest */ +class InitializingOnDemandHolderIdiomTest extends SingletonTest { - /** - * Create a new singleton test instance using the given 'getInstance' method. - */ + /** Create a new singleton test instance using the given 'getInstance' method. */ public InitializingOnDemandHolderIdiomTest() { super(InitializingOnDemandHolderIdiom::getInstance); } - -} \ No newline at end of file +} diff --git a/singleton/src/test/java/com/iluwatar/singleton/IvoryTowerTest.java b/singleton/src/test/java/com/iluwatar/singleton/IvoryTowerTest.java index d9ce652ae..98621224d 100644 --- a/singleton/src/test/java/com/iluwatar/singleton/IvoryTowerTest.java +++ b/singleton/src/test/java/com/iluwatar/singleton/IvoryTowerTest.java @@ -24,17 +24,11 @@ */ package com.iluwatar.singleton; -/** - * IvoryTowerTest - * - */ +/** IvoryTowerTest */ class IvoryTowerTest extends SingletonTest { - /** - * Create a new singleton test instance using the given 'getInstance' method. - */ + /** Create a new singleton test instance using the given 'getInstance' method. */ public IvoryTowerTest() { super(IvoryTower::getInstance); } - -} \ No newline at end of file +} diff --git a/singleton/src/test/java/com/iluwatar/singleton/SingletonTest.java b/singleton/src/test/java/com/iluwatar/singleton/SingletonTest.java index 81e5f4132..bf0b403d8 100644 --- a/singleton/src/test/java/com/iluwatar/singleton/SingletonTest.java +++ b/singleton/src/test/java/com/iluwatar/singleton/SingletonTest.java @@ -40,19 +40,17 @@ import java.util.stream.IntStream; import org.junit.jupiter.api.Test; /** - *

This class provides several test case that test singleton construction.

+ * This class provides several test case that test singleton construction. * *

The first proves that multiple calls to the singleton getInstance object are the same when * called in the SAME thread. The second proves that multiple calls to the singleton getInstance - * object are the same when called in the DIFFERENT thread.

+ * object are the same when called in the DIFFERENT thread. * * @param Supplier method generating singletons */ abstract class SingletonTest { - /** - * The singleton's getInstance method. - */ + /** The singleton's getInstance method. */ private final Supplier singletonInstanceMethod; /** @@ -64,9 +62,7 @@ abstract class SingletonTest { this.singletonInstanceMethod = singletonInstanceMethod; } - /** - * Test the singleton in a non-concurrent setting. - */ + /** Test the singleton in a non-concurrent setting. */ @Test void testMultipleCallsReturnTheSameObjectInSameThread() { // Create several instances in the same calling thread @@ -79,38 +75,36 @@ abstract class SingletonTest { assertSame(instance2, instance3); } - /** - * Test singleton instance in a concurrent setting. - */ + /** Test singleton instance in a concurrent setting. */ @Test void testMultipleCallsReturnTheSameObjectInDifferentThreads() { - assertTimeout(ofMillis(10000), () -> { - // Create 10000 tasks and inside each callable instantiate the singleton class - final var tasks = IntStream.range(0, 10000) - .>mapToObj(i -> this.singletonInstanceMethod::get) - .collect(Collectors.toCollection(ArrayList::new)); + assertTimeout( + ofMillis(10000), + () -> { + // Create 10000 tasks and inside each callable instantiate the singleton class + final var tasks = + IntStream.range(0, 10000) + .>mapToObj(i -> this.singletonInstanceMethod::get) + .collect(Collectors.toCollection(ArrayList::new)); - // Use up to 8 concurrent threads to handle the tasks - final var executorService = Executors.newFixedThreadPool(8); - final var results = executorService.invokeAll(tasks); + // Use up to 8 concurrent threads to handle the tasks + final var executorService = Executors.newFixedThreadPool(8); + final var results = executorService.invokeAll(tasks); - // wait for all the threads to complete - final var expectedInstance = this.singletonInstanceMethod.get(); - for (var res : results) { - final var instance = res.get(); - assertNotNull(instance); - assertSame(expectedInstance, instance); - } - - // tidy up the executor - executorService.shutdown(); - }); + // wait for all the threads to complete + final var expectedInstance = this.singletonInstanceMethod.get(); + for (var res : results) { + final var instance = res.get(); + assertNotNull(instance); + assertSame(expectedInstance, instance); + } + // tidy up the executor + executorService.shutdown(); + }); } - /** - * Test creating new instance by reflection. - */ + /** Test creating new instance by reflection. */ @Test void testCreatingNewInstanceByReflection() throws Exception { var firstTimeInstantiated = this.singletonInstanceMethod.get(); diff --git a/singleton/src/test/java/com/iluwatar/singleton/ThreadSafeDoubleCheckLockingTest.java b/singleton/src/test/java/com/iluwatar/singleton/ThreadSafeDoubleCheckLockingTest.java index e88968223..b0bc8a4b9 100644 --- a/singleton/src/test/java/com/iluwatar/singleton/ThreadSafeDoubleCheckLockingTest.java +++ b/singleton/src/test/java/com/iluwatar/singleton/ThreadSafeDoubleCheckLockingTest.java @@ -24,17 +24,11 @@ */ package com.iluwatar.singleton; -/** - * ThreadSafeDoubleCheckLockingTest - * - */ +/** ThreadSafeDoubleCheckLockingTest */ class ThreadSafeDoubleCheckLockingTest extends SingletonTest { - /** - * Create a new singleton test instance using the given 'getInstance' method. - */ + /** Create a new singleton test instance using the given 'getInstance' method. */ public ThreadSafeDoubleCheckLockingTest() { super(ThreadSafeDoubleCheckLocking::getInstance); } - } diff --git a/singleton/src/test/java/com/iluwatar/singleton/ThreadSafeLazyLoadedIvoryTowerTest.java b/singleton/src/test/java/com/iluwatar/singleton/ThreadSafeLazyLoadedIvoryTowerTest.java index a451f9c21..e1cd097a2 100644 --- a/singleton/src/test/java/com/iluwatar/singleton/ThreadSafeLazyLoadedIvoryTowerTest.java +++ b/singleton/src/test/java/com/iluwatar/singleton/ThreadSafeLazyLoadedIvoryTowerTest.java @@ -24,18 +24,11 @@ */ package com.iluwatar.singleton; -/** - * ThreadSafeLazyLoadedIvoryTowerTest - * - */ -class ThreadSafeLazyLoadedIvoryTowerTest - extends SingletonTest { +/** ThreadSafeLazyLoadedIvoryTowerTest */ +class ThreadSafeLazyLoadedIvoryTowerTest extends SingletonTest { - /** - * Create a new singleton test instance using the given 'getInstance' method. - */ + /** Create a new singleton test instance using the given 'getInstance' method. */ public ThreadSafeLazyLoadedIvoryTowerTest() { super(ThreadSafeLazyLoadedIvoryTower::getInstance); } - } diff --git a/spatial-partition/pom.xml b/spatial-partition/pom.xml index 753ee7422..a9d33cff6 100644 --- a/spatial-partition/pom.xml +++ b/spatial-partition/pom.xml @@ -34,6 +34,14 @@ spatial-partition + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/spatial-partition/src/main/java/com/iluwatar/spatialpartition/App.java b/spatial-partition/src/main/java/com/iluwatar/spatialpartition/App.java index e7b14249a..8eabbed06 100644 --- a/spatial-partition/src/main/java/com/iluwatar/spatialpartition/App.java +++ b/spatial-partition/src/main/java/com/iluwatar/spatialpartition/App.java @@ -30,76 +30,77 @@ import java.util.concurrent.ConcurrentHashMap; import lombok.extern.slf4j.Slf4j; /** - *

The idea behind the Spatial Partition design pattern is to enable efficient location - * of objects by storing them in a data structure that is organised by their positions. This is + * The idea behind the Spatial Partition design pattern is to enable efficient location of + * objects by storing them in a data structure that is organised by their positions. This is * especially useful in the gaming world, where one may need to look up all the objects within a * certain boundary, or near a certain other object, repeatedly. The data structure can be used to * store moving and static objects, though in order to keep track of the moving objects, their * positions will have to be reset each time they move. This would mean having to create a new * instance of the data structure each frame, which would use up additional memory, and so this * pattern should only be used if one does not mind trading memory for speed and the number of - * objects to keep track of is large to justify the use of the extra space.

+ * objects to keep track of is large to justify the use of the extra space. + * *

In our example, we use {@link QuadTree} data structure which divides into 4 (quad) * sub-sections when the number of objects added to it exceeds a certain number (int field - * capacity). There is also a - * {@link Rect} class to define the boundary of the quadtree. We use an abstract class - * {@link Point} - * with x and y coordinate fields and also an id field so that it can easily be put and looked up in - * the hashmap. This class has abstract methods to define how the object moves (move()), when to - * check for collision with any object (touches(obj)) and how to handle collision - * (handleCollision(obj)), and will be extended by any object whose position has to be kept track of - * in the quadtree. The {@link SpatialPartitionGeneric} abstract class has 2 fields - a - * hashmap containing all objects (we use hashmap for faster lookups, insertion and deletion) - * and a quadtree, and contains an abstract method which defines how to handle interactions between - * objects using the quadtree.

+ * capacity). There is also a {@link Rect} class to define the boundary of the quadtree. We + * use an abstract class {@link Point} with x and y coordinate fields and also an id field so + * that it can easily be put and looked up in the hashmap. This class has abstract methods to define + * how the object moves (move()), when to check for collision with any object (touches(obj)) and how + * to handle collision (handleCollision(obj)), and will be extended by any object whose position has + * to be kept track of in the quadtree. The {@link SpatialPartitionGeneric} abstract class + * has 2 fields - a hashmap containing all objects (we use hashmap for faster lookups, insertion and + * deletion) and a quadtree, and contains an abstract method which defines how to handle + * interactions between objects using the quadtree. + * *

Using the quadtree data structure will reduce the time complexity of finding the objects * within a certain range from O(n^2) to O(nlogn), increasing the speed of computations * immensely in case of large number of objects, which will have a positive effect on the rendering - * speed of the game.

+ * speed of the game. */ - @Slf4j public class App { static void noSpatialPartition(int numOfMovements, Map bubbles) { - //all bubbles have to be checked for collision for all bubbles + // all bubbles have to be checked for collision for all bubbles var bubblesToCheck = bubbles.values(); - //will run numOfMovement times or till all bubbles have popped + // will run numOfMovement times or till all bubbles have popped while (numOfMovements > 0 && !bubbles.isEmpty()) { - bubbles.forEach((i, bubble) -> { - // bubble moves, new position gets updated - // and collisions are checked with all bubbles in bubblesToCheck - bubble.move(); - bubbles.replace(i, bubble); - bubble.handleCollision(bubblesToCheck, bubbles); - }); + bubbles.forEach( + (i, bubble) -> { + // bubble moves, new position gets updated + // and collisions are checked with all bubbles in bubblesToCheck + bubble.move(); + bubbles.replace(i, bubble); + bubble.handleCollision(bubblesToCheck, bubbles); + }); numOfMovements--; } - //bubbles not popped + // bubbles not popped bubbles.keySet().forEach(key -> LOGGER.info("Bubble {} not popped", key)); } static void withSpatialPartition( int height, int width, int numOfMovements, Map bubbles) { - //creating quadtree + // creating quadtree var rect = new Rect(width / 2D, height / 2D, width, height); var quadTree = new QuadTree(rect, 4); - //will run numOfMovement times or till all bubbles have popped + // will run numOfMovement times or till all bubbles have popped while (numOfMovements > 0 && !bubbles.isEmpty()) { - //quadtree updated each time + // quadtree updated each time bubbles.values().forEach(quadTree::insert); - bubbles.forEach((i, bubble) -> { - //bubble moves, new position gets updated, quadtree used to reduce computations - bubble.move(); - bubbles.replace(i, bubble); - var sp = new SpatialPartitionBubbles(bubbles, quadTree); - sp.handleCollisionsUsingQt(bubble); - }); + bubbles.forEach( + (i, bubble) -> { + // bubble moves, new position gets updated, quadtree used to reduce computations + bubble.move(); + bubbles.replace(i, bubble); + var sp = new SpatialPartitionBubbles(bubbles, quadTree); + sp.handleCollisionsUsingQt(bubble); + }); numOfMovements--; } - //bubbles not popped + // bubbles not popped bubbles.keySet().forEach(key -> LOGGER.info("Bubble {} not popped", key)); } @@ -108,7 +109,6 @@ public class App { * * @param args command line args */ - public static void main(String[] args) { var bubbles1 = new ConcurrentHashMap(); var bubbles2 = new ConcurrentHashMap(); @@ -117,8 +117,8 @@ public class App { var b = new Bubble(rand.nextInt(300), rand.nextInt(300), i, rand.nextInt(2) + 1); bubbles1.put(i, b); bubbles2.put(i, b); - LOGGER.info("Bubble {} with radius {} added at ({},{})", - i, b.radius, b.coordinateX, b.coordinateY); + LOGGER.info( + "Bubble {} with radius {} added at ({},{})", i, b.radius, b.coordinateX, b.coordinateY); } var start1 = System.currentTimeMillis(); diff --git a/spatial-partition/src/main/java/com/iluwatar/spatialpartition/Bubble.java b/spatial-partition/src/main/java/com/iluwatar/spatialpartition/Bubble.java index 70f8cae48..b2b0a10d9 100644 --- a/spatial-partition/src/main/java/com/iluwatar/spatialpartition/Bubble.java +++ b/spatial-partition/src/main/java/com/iluwatar/spatialpartition/Bubble.java @@ -33,7 +33,6 @@ import lombok.extern.slf4j.Slf4j; * Bubble class extends Point. In this example, we create several bubbles in the field, let them * move and keep track of which ones have popped and which ones remain. */ - @Slf4j public class Bubble extends Point { private static final SecureRandom RANDOM = new SecureRandom(); @@ -46,15 +45,15 @@ public class Bubble extends Point { } void move() { - //moves by 1 unit in either direction + // moves by 1 unit in either direction this.coordinateX += RANDOM.nextInt(3) - 1; this.coordinateY += RANDOM.nextInt(3) - 1; } boolean touches(Bubble b) { - //distance between them is greater than sum of radii (both sides of equation squared) + // distance between them is greater than sum of radii (both sides of equation squared) return (this.coordinateX - b.coordinateX) * (this.coordinateX - b.coordinateX) - + (this.coordinateY - b.coordinateY) * (this.coordinateY - b.coordinateY) + + (this.coordinateY - b.coordinateY) * (this.coordinateY - b.coordinateY) <= (this.radius + b.radius) * (this.radius + b.radius); } @@ -64,12 +63,12 @@ public class Bubble extends Point { } void handleCollision(Collection toCheck, Map allBubbles) { - var toBePopped = false; //if any other bubble collides with it, made true + var toBePopped = false; // if any other bubble collides with it, made true for (var point : toCheck) { var otherId = point.id; - if (allBubbles.get(otherId) != null //the bubble hasn't been popped yet - && this.id != otherId //the two bubbles are not the same - && this.touches(allBubbles.get(otherId))) { //the bubbles touch + if (allBubbles.get(otherId) != null // the bubble hasn't been popped yet + && this.id != otherId // the two bubbles are not the same + && this.touches(allBubbles.get(otherId))) { // the bubbles touch allBubbles.get(otherId).pop(allBubbles); toBePopped = true; } diff --git a/spatial-partition/src/main/java/com/iluwatar/spatialpartition/Point.java b/spatial-partition/src/main/java/com/iluwatar/spatialpartition/Point.java index 1b24e70fa..adcc4862b 100644 --- a/spatial-partition/src/main/java/com/iluwatar/spatialpartition/Point.java +++ b/spatial-partition/src/main/java/com/iluwatar/spatialpartition/Point.java @@ -33,7 +33,6 @@ import java.util.Map; * * @param T will be type subclass */ - public abstract class Point { public int coordinateX; @@ -46,9 +45,7 @@ public abstract class Point { this.id = id; } - /** - * defines how the object moves. - */ + /** defines how the object moves. */ abstract void move(); /** @@ -63,7 +60,7 @@ public abstract class Point { * handling interactions/collisions with other objects. * * @param toCheck contains the objects which need to be checked - * @param all contains hashtable of all points on field at this time + * @param all contains hashtable of all points on field at this time */ abstract void handleCollision(Collection toCheck, Map all); } diff --git a/spatial-partition/src/main/java/com/iluwatar/spatialpartition/QuadTree.java b/spatial-partition/src/main/java/com/iluwatar/spatialpartition/QuadTree.java index 40c09a1d8..c83ccc42c 100644 --- a/spatial-partition/src/main/java/com/iluwatar/spatialpartition/QuadTree.java +++ b/spatial-partition/src/main/java/com/iluwatar/spatialpartition/QuadTree.java @@ -33,7 +33,6 @@ import java.util.Map; * insert(Point) and query(range) methods to insert a new object and find the objects within a * certain (rectangular) range respectively. */ - public class QuadTree { Rect boundary; int capacity; @@ -93,13 +92,9 @@ public class QuadTree { } Collection query(Rect r, Collection relevantPoints) { - //could also be a circle instead of a rectangle + // could also be a circle instead of a rectangle if (this.boundary.intersects(r)) { - this.points - .values() - .stream() - .filter(r::contains) - .forEach(relevantPoints::add); + this.points.values().stream().filter(r::contains).forEach(relevantPoints::add); if (this.divided) { this.northwest.query(r, relevantPoints); this.northeast.query(r, relevantPoints); diff --git a/spatial-partition/src/main/java/com/iluwatar/spatialpartition/Rect.java b/spatial-partition/src/main/java/com/iluwatar/spatialpartition/Rect.java index 5fc654949..9f743e0d6 100644 --- a/spatial-partition/src/main/java/com/iluwatar/spatialpartition/Rect.java +++ b/spatial-partition/src/main/java/com/iluwatar/spatialpartition/Rect.java @@ -28,14 +28,13 @@ package com.iluwatar.spatialpartition; * The Rect class helps in defining the boundary of the quadtree and is also used to define the * range within which objects need to be found in our example. */ - public class Rect { double coordinateX; double coordinateY; double width; double height; - //(x,y) - centre of rectangle + // (x,y) - centre of rectangle Rect(double x, double y, double width, double height) { this.coordinateX = x; @@ -58,4 +57,3 @@ public class Rect { || this.coordinateY - this.height / 2 >= other.coordinateY + other.height / 2); } } - diff --git a/spatial-partition/src/main/java/com/iluwatar/spatialpartition/SpatialPartitionBubbles.java b/spatial-partition/src/main/java/com/iluwatar/spatialpartition/SpatialPartitionBubbles.java index 3551f5ca3..cefc1a824 100644 --- a/spatial-partition/src/main/java/com/iluwatar/spatialpartition/SpatialPartitionBubbles.java +++ b/spatial-partition/src/main/java/com/iluwatar/spatialpartition/SpatialPartitionBubbles.java @@ -31,7 +31,6 @@ import java.util.Map; * This class extends the generic SpatialPartition abstract class and is used in our example to keep * track of all the bubbles that collide, pop and stay un-popped. */ - public class SpatialPartitionBubbles extends SpatialPartitionGeneric { private final Map bubbles; @@ -48,7 +47,7 @@ public class SpatialPartitionBubbles extends SpatialPartitionGeneric { var rect = new Rect(b.coordinateX, b.coordinateY, 2D * b.radius, 2D * b.radius); var quadTreeQueryResult = new ArrayList(); this.bubblesQuadTree.query(rect, quadTreeQueryResult); - //handling these collisions + // handling these collisions b.handleCollision(quadTreeQueryResult, this.bubbles); } } diff --git a/spatial-partition/src/main/java/com/iluwatar/spatialpartition/SpatialPartitionGeneric.java b/spatial-partition/src/main/java/com/iluwatar/spatialpartition/SpatialPartitionGeneric.java index 7c03969a0..1e5baabb8 100644 --- a/spatial-partition/src/main/java/com/iluwatar/spatialpartition/SpatialPartitionGeneric.java +++ b/spatial-partition/src/main/java/com/iluwatar/spatialpartition/SpatialPartitionGeneric.java @@ -32,7 +32,6 @@ import java.util.Map; * * @param T will be type of object (that extends Point) */ - public abstract class SpatialPartitionGeneric { Map playerPositions; diff --git a/spatial-partition/src/test/java/com/iluwatar/spatialpartition/BubbleTest.java b/spatial-partition/src/test/java/com/iluwatar/spatialpartition/BubbleTest.java index 2fb277057..3f9ae809d 100644 --- a/spatial-partition/src/test/java/com/iluwatar/spatialpartition/BubbleTest.java +++ b/spatial-partition/src/test/java/com/iluwatar/spatialpartition/BubbleTest.java @@ -33,10 +33,7 @@ import java.util.ArrayList; import java.util.HashMap; import org.junit.jupiter.api.Test; -/** - * Testing methods in Bubble class. - */ - +/** Testing methods in Bubble class. */ class BubbleTest { @Test @@ -45,7 +42,7 @@ class BubbleTest { var initialX = b.coordinateX; var initialY = b.coordinateY; b.move(); - //change in x and y < |2| + // change in x and y < |2| assertTrue(b.coordinateX - initialX < 2 && b.coordinateX - initialX > -2); assertTrue(b.coordinateY - initialY < 2 && b.coordinateY - initialY > -2); } @@ -55,7 +52,7 @@ class BubbleTest { var b1 = new Bubble(0, 0, 1, 2); var b2 = new Bubble(1, 1, 2, 1); var b3 = new Bubble(10, 10, 3, 1); - //b1 touches b2 but not b3 + // b1 touches b2 but not b3 assertTrue(b1.touches(b2)); assertFalse(b1.touches(b3)); } @@ -68,7 +65,7 @@ class BubbleTest { bubbles.put(1, b1); bubbles.put(2, b2); b1.pop(bubbles); - //after popping, bubble no longer in hashMap containing all bubbles + // after popping, bubble no longer in hashMap containing all bubbles assertNull(bubbles.get(1)); assertNotNull(bubbles.get(2)); } @@ -86,7 +83,7 @@ class BubbleTest { bubblesToCheck.add(b2); bubblesToCheck.add(b3); b1.handleCollision(bubblesToCheck, bubbles); - //b1 touches b2 and not b3, so b1, b2 will be popped + // b1 touches b2 and not b3, so b1, b2 will be popped assertNull(bubbles.get(1)); assertNull(bubbles.get(2)); assertNotNull(bubbles.get(3)); diff --git a/spatial-partition/src/test/java/com/iluwatar/spatialpartition/QuadTreeTest.java b/spatial-partition/src/test/java/com/iluwatar/spatialpartition/QuadTreeTest.java index 8d4adadaa..b1d9e48b7 100644 --- a/spatial-partition/src/test/java/com/iluwatar/spatialpartition/QuadTreeTest.java +++ b/spatial-partition/src/test/java/com/iluwatar/spatialpartition/QuadTreeTest.java @@ -33,10 +33,7 @@ import java.util.Random; import java.util.stream.Collectors; import org.junit.jupiter.api.Test; -/** - * Testing QuadTree class. - */ - +/** Testing QuadTree class. */ class QuadTreeTest { @Test @@ -47,22 +44,21 @@ class QuadTreeTest { var p = new Bubble(rand.nextInt(300), rand.nextInt(300), i, rand.nextInt(2) + 1); points.add(p); } - var field = new Rect(150, 150, 300, 300); //size of field - var queryRange = new Rect(70, 130, 100, 100); //result = all points lying in this rectangle - //points found in the query range using quadtree and normal method is same + var field = new Rect(150, 150, 300, 300); // size of field + var queryRange = new Rect(70, 130, 100, 100); // result = all points lying in this rectangle + // points found in the query range using quadtree and normal method is same var points1 = QuadTreeTest.quadTreeTest(points, field, queryRange); var points2 = QuadTreeTest.verify(points, queryRange); assertEquals(points1, points2); } - static Hashtable quadTreeTest(Collection points, Rect field, Rect queryRange) { - //creating quadtree and inserting all points + static Hashtable quadTreeTest( + Collection points, Rect field, Rect queryRange) { + // creating quadtree and inserting all points var qTree = new QuadTree(queryRange, 4); points.forEach(qTree::insert); - return qTree - .query(field, new ArrayList<>()) - .stream() + return qTree.query(field, new ArrayList<>()).stream() .collect(Collectors.toMap(p -> p.id, p -> p, (a, b) -> b, Hashtable::new)); } diff --git a/spatial-partition/src/test/java/com/iluwatar/spatialpartition/RectTest.java b/spatial-partition/src/test/java/com/iluwatar/spatialpartition/RectTest.java index 3a2ea4562..0aca25388 100644 --- a/spatial-partition/src/test/java/com/iluwatar/spatialpartition/RectTest.java +++ b/spatial-partition/src/test/java/com/iluwatar/spatialpartition/RectTest.java @@ -29,10 +29,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; -/** - * Testing Rect class. - */ - +/** Testing Rect class. */ class RectTest { @Test @@ -40,7 +37,7 @@ class RectTest { var r = new Rect(10, 10, 20, 20); var b1 = new Bubble(2, 2, 1, 1); var b2 = new Bubble(30, 30, 2, 1); - //r contains b1 and not b2 + // r contains b1 and not b2 assertTrue(r.contains(b1)); assertFalse(r.contains(b2)); } @@ -50,7 +47,7 @@ class RectTest { var r1 = new Rect(10, 10, 20, 20); var r2 = new Rect(15, 15, 20, 20); var r3 = new Rect(50, 50, 20, 20); - //r1 intersects r2 and not r3 + // r1 intersects r2 and not r3 assertTrue(r1.intersects(r2)); assertFalse(r1.intersects(r3)); } diff --git a/spatial-partition/src/test/java/com/iluwatar/spatialpartition/SpatialPartitionBubblesTest.java b/spatial-partition/src/test/java/com/iluwatar/spatialpartition/SpatialPartitionBubblesTest.java index c491ecb46..b36fa99bc 100644 --- a/spatial-partition/src/test/java/com/iluwatar/spatialpartition/SpatialPartitionBubblesTest.java +++ b/spatial-partition/src/test/java/com/iluwatar/spatialpartition/SpatialPartitionBubblesTest.java @@ -30,10 +30,7 @@ import static org.junit.jupiter.api.Assertions.assertNull; import java.util.HashMap; import org.junit.jupiter.api.Test; -/** - * Testing SpatialPartition_Bubbles class. - */ - +/** Testing SpatialPartition_Bubbles class. */ class SpatialPartitionBubblesTest { @Test @@ -55,7 +52,7 @@ class SpatialPartitionBubblesTest { qt.insert(b4); var sp = new SpatialPartitionBubbles(bubbles, qt); sp.handleCollisionsUsingQt(b1); - //b1 touches b3 and b4 but not b2 - so b1,b3,b4 get popped + // b1 touches b3 and b4 but not b2 - so b1,b3,b4 get popped assertNull(bubbles.get(1)); assertNotNull(bubbles.get(2)); assertNull(bubbles.get(3)); diff --git a/special-case/pom.xml b/special-case/pom.xml index 59ec1c10f..55400ffba 100644 --- a/special-case/pom.xml +++ b/special-case/pom.xml @@ -34,10 +34,37 @@ 4.0.0 special-case + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + com.iluwatar.specialcase.App + + + + + + + + diff --git a/special-case/src/main/java/com/iluwatar/specialcase/App.java b/special-case/src/main/java/com/iluwatar/specialcase/App.java index 5c6a10602..6bbad3322 100644 --- a/special-case/src/main/java/com/iluwatar/specialcase/App.java +++ b/special-case/src/main/java/com/iluwatar/specialcase/App.java @@ -28,10 +28,10 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - *

The Special Case Pattern is a software design pattern that encapsulates particular cases - * into subclasses that provide special behaviors.

+ * The Special Case Pattern is a software design pattern that encapsulates particular cases into + * subclasses that provide special behaviors. * - *

In this example ({@link ReceiptViewModel}) encapsulates all particular cases.

+ *

In this example ({@link ReceiptViewModel}) encapsulates all particular cases. */ public class App { @@ -44,13 +44,13 @@ public class App { private static final String ITEM_CAR = "car"; private static final String ITEM_COMPUTER = "computer"; - /** - * Program entry point. - */ + /** Program entry point. */ public static void main(String[] args) { // DB seeding - LOGGER.info("Db seeding: " + "1 user: {\"ignite1771\", amount = 1000.0}, " - + "2 products: {\"computer\": price = 800.0, \"car\": price = 20000.0}"); + LOGGER.info( + "Db seeding: " + + "1 user: {\"ignite1771\", amount = 1000.0}, " + + "2 products: {\"computer\": price = 800.0, \"car\": price = 20000.0}"); Db.getInstance().seedUser(TEST_USER_1, 1000.0); Db.getInstance().seedItem(ITEM_COMPUTER, 800.0); Db.getInstance().seedItem(ITEM_CAR, 20000.0); diff --git a/special-case/src/main/java/com/iluwatar/specialcase/ApplicationServices.java b/special-case/src/main/java/com/iluwatar/specialcase/ApplicationServices.java index 9dafdba44..507415663 100644 --- a/special-case/src/main/java/com/iluwatar/specialcase/ApplicationServices.java +++ b/special-case/src/main/java/com/iluwatar/specialcase/ApplicationServices.java @@ -24,9 +24,7 @@ */ package com.iluwatar.specialcase; -/** - * ApplicationServices interface to demonstrate special case pattern. - */ +/** ApplicationServices interface to demonstrate special case pattern. */ public interface ApplicationServices { ReceiptViewModel loggedInUserPurchase(String userName, String itemName); diff --git a/special-case/src/main/java/com/iluwatar/specialcase/ApplicationServicesImpl.java b/special-case/src/main/java/com/iluwatar/specialcase/ApplicationServicesImpl.java index cb21e57f6..fa455a23d 100644 --- a/special-case/src/main/java/com/iluwatar/specialcase/ApplicationServicesImpl.java +++ b/special-case/src/main/java/com/iluwatar/specialcase/ApplicationServicesImpl.java @@ -24,9 +24,7 @@ */ package com.iluwatar.specialcase; -/** - * Implementation of special case pattern. - */ +/** Implementation of special case pattern. */ public class ApplicationServicesImpl implements ApplicationServices { private DomainServicesImpl domain = new DomainServicesImpl(); diff --git a/special-case/src/main/java/com/iluwatar/specialcase/Db.java b/special-case/src/main/java/com/iluwatar/specialcase/Db.java index da8d588a3..32ac6501d 100644 --- a/special-case/src/main/java/com/iluwatar/specialcase/Db.java +++ b/special-case/src/main/java/com/iluwatar/specialcase/Db.java @@ -29,9 +29,7 @@ import java.util.Map; import lombok.Getter; import lombok.RequiredArgsConstructor; -/** - * DB class for seeding user info. - */ +/** DB class for seeding user info. */ public class Db { private static Db instance; @@ -118,9 +116,7 @@ public class Db { return itemName2Product.get(itemName); } - /** - * User class to store user info. - */ + /** User class to store user info. */ @RequiredArgsConstructor @Getter public class User { @@ -132,9 +128,7 @@ public class Db { } } - /** - * Account info. - */ + /** Account info. */ @RequiredArgsConstructor @Getter public static class Account { @@ -155,9 +149,7 @@ public class Db { } } - /** - * Product info. - */ + /** Product info. */ @RequiredArgsConstructor @Getter public static class Product { diff --git a/special-case/src/main/java/com/iluwatar/specialcase/DomainServices.java b/special-case/src/main/java/com/iluwatar/specialcase/DomainServices.java index 84502e64d..daf14c062 100644 --- a/special-case/src/main/java/com/iluwatar/specialcase/DomainServices.java +++ b/special-case/src/main/java/com/iluwatar/specialcase/DomainServices.java @@ -24,8 +24,5 @@ */ package com.iluwatar.specialcase; -/** - * DomainServices interface. - */ -public interface DomainServices { -} +/** DomainServices interface. */ +public interface DomainServices {} diff --git a/special-case/src/main/java/com/iluwatar/specialcase/DomainServicesImpl.java b/special-case/src/main/java/com/iluwatar/specialcase/DomainServicesImpl.java index ac31a9083..54c7b9983 100644 --- a/special-case/src/main/java/com/iluwatar/specialcase/DomainServicesImpl.java +++ b/special-case/src/main/java/com/iluwatar/specialcase/DomainServicesImpl.java @@ -24,9 +24,7 @@ */ package com.iluwatar.specialcase; -/** - * Implementation of DomainServices for special case. - */ +/** Implementation of DomainServices for special case. */ public class DomainServicesImpl implements DomainServices { /** @@ -47,9 +45,8 @@ public class DomainServicesImpl implements DomainServices { } /** - * Domain purchase with user, account and itemName, - * with validation for whether product is out of stock - * and whether user has insufficient funds in the account. + * Domain purchase with user, account and itemName, with validation for whether product is out of + * stock and whether user has insufficient funds in the account. * * @param user in Db * @param account in Db diff --git a/special-case/src/main/java/com/iluwatar/specialcase/DownForMaintenance.java b/special-case/src/main/java/com/iluwatar/specialcase/DownForMaintenance.java index 713dcaef7..504678eca 100644 --- a/special-case/src/main/java/com/iluwatar/specialcase/DownForMaintenance.java +++ b/special-case/src/main/java/com/iluwatar/specialcase/DownForMaintenance.java @@ -27,9 +27,7 @@ package com.iluwatar.specialcase; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -/** - * Down for Maintenance view for the ReceiptViewModel. - */ +/** Down for Maintenance view for the ReceiptViewModel. */ public class DownForMaintenance implements ReceiptViewModel { private static final Logger LOGGER = LoggerFactory.getLogger(DownForMaintenance.class); diff --git a/special-case/src/main/java/com/iluwatar/specialcase/InsufficientFunds.java b/special-case/src/main/java/com/iluwatar/specialcase/InsufficientFunds.java index 03dff2c41..66c974ca5 100644 --- a/special-case/src/main/java/com/iluwatar/specialcase/InsufficientFunds.java +++ b/special-case/src/main/java/com/iluwatar/specialcase/InsufficientFunds.java @@ -26,9 +26,7 @@ package com.iluwatar.specialcase; import lombok.extern.slf4j.Slf4j; -/** - * View representing insufficient funds. - */ +/** View representing insufficient funds. */ @Slf4j public class InsufficientFunds implements ReceiptViewModel { @@ -51,7 +49,12 @@ public class InsufficientFunds implements ReceiptViewModel { @Override public void show() { - LOGGER.info("Insufficient funds: " + amount + " of user: " + userName - + " for buying item: " + itemName); + LOGGER.info( + "Insufficient funds: " + + amount + + " of user: " + + userName + + " for buying item: " + + itemName); } } diff --git a/special-case/src/main/java/com/iluwatar/specialcase/InvalidUser.java b/special-case/src/main/java/com/iluwatar/specialcase/InvalidUser.java index 861d69e8c..37c08d1f7 100644 --- a/special-case/src/main/java/com/iluwatar/specialcase/InvalidUser.java +++ b/special-case/src/main/java/com/iluwatar/specialcase/InvalidUser.java @@ -27,9 +27,7 @@ package com.iluwatar.specialcase; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -/** - * Receipt View representing invalid user. - */ +/** Receipt View representing invalid user. */ public class InvalidUser implements ReceiptViewModel { private static final Logger LOGGER = LoggerFactory.getLogger(InvalidUser.class); diff --git a/special-case/src/main/java/com/iluwatar/specialcase/MaintenanceLock.java b/special-case/src/main/java/com/iluwatar/specialcase/MaintenanceLock.java index b98094285..0e39e900f 100644 --- a/special-case/src/main/java/com/iluwatar/specialcase/MaintenanceLock.java +++ b/special-case/src/main/java/com/iluwatar/specialcase/MaintenanceLock.java @@ -28,17 +28,14 @@ import lombok.Getter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -/** - * Acquire lock on the DB for maintenance. - */ +/** Acquire lock on the DB for maintenance. */ public class MaintenanceLock { private static final Logger LOGGER = LoggerFactory.getLogger(MaintenanceLock.class); private static MaintenanceLock instance; - @Getter - private boolean lock = true; + @Getter private boolean lock = true; /** * Get the instance of MaintenanceLock. diff --git a/special-case/src/main/java/com/iluwatar/specialcase/MoneyTransaction.java b/special-case/src/main/java/com/iluwatar/specialcase/MoneyTransaction.java index 4bf9b92f9..cdaf3fb78 100644 --- a/special-case/src/main/java/com/iluwatar/specialcase/MoneyTransaction.java +++ b/special-case/src/main/java/com/iluwatar/specialcase/MoneyTransaction.java @@ -26,9 +26,7 @@ package com.iluwatar.specialcase; import lombok.RequiredArgsConstructor; -/** - * Represents the money transaction taking place at a given moment. - */ +/** Represents the money transaction taking place at a given moment. */ @RequiredArgsConstructor public class MoneyTransaction { diff --git a/special-case/src/main/java/com/iluwatar/specialcase/OutOfStock.java b/special-case/src/main/java/com/iluwatar/specialcase/OutOfStock.java index 5bfa09186..79c47df9a 100644 --- a/special-case/src/main/java/com/iluwatar/specialcase/OutOfStock.java +++ b/special-case/src/main/java/com/iluwatar/specialcase/OutOfStock.java @@ -27,9 +27,7 @@ package com.iluwatar.specialcase; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -/** - * Receipt view for showing out of stock message. - */ +/** Receipt view for showing out of stock message. */ public class OutOfStock implements ReceiptViewModel { private static final Logger LOGGER = LoggerFactory.getLogger(OutOfStock.class); diff --git a/special-case/src/main/java/com/iluwatar/specialcase/ReceiptDto.java b/special-case/src/main/java/com/iluwatar/specialcase/ReceiptDto.java index 7143d797b..45d2129d6 100644 --- a/special-case/src/main/java/com/iluwatar/specialcase/ReceiptDto.java +++ b/special-case/src/main/java/com/iluwatar/specialcase/ReceiptDto.java @@ -29,9 +29,7 @@ import lombok.RequiredArgsConstructor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -/** - * Receipt view representing the transaction recceipt. - */ +/** Receipt view representing the transaction recceipt. */ @RequiredArgsConstructor @Getter public class ReceiptDto implements ReceiptViewModel { diff --git a/special-case/src/main/java/com/iluwatar/specialcase/ReceiptViewModel.java b/special-case/src/main/java/com/iluwatar/specialcase/ReceiptViewModel.java index 633005b07..df33227bb 100644 --- a/special-case/src/main/java/com/iluwatar/specialcase/ReceiptViewModel.java +++ b/special-case/src/main/java/com/iluwatar/specialcase/ReceiptViewModel.java @@ -24,9 +24,7 @@ */ package com.iluwatar.specialcase; -/** - * ReceiptViewModel interface. - */ +/** ReceiptViewModel interface. */ public interface ReceiptViewModel { void show(); diff --git a/special-case/src/test/java/com/iluwatar/specialcase/AppTest.java b/special-case/src/test/java/com/iluwatar/specialcase/AppTest.java index a571024a5..15dd9cf10 100644 --- a/special-case/src/test/java/com/iluwatar/specialcase/AppTest.java +++ b/special-case/src/test/java/com/iluwatar/specialcase/AppTest.java @@ -28,13 +28,11 @@ import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import org.junit.jupiter.api.Test; -/** - * Application test. - */ +/** Application test. */ class AppTest { @Test void shouldExecuteWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/special-case/src/test/java/com/iluwatar/specialcase/SpecialCasesTest.java b/special-case/src/test/java/com/iluwatar/specialcase/SpecialCasesTest.java index 8411398b2..da5d532b8 100644 --- a/special-case/src/test/java/com/iluwatar/specialcase/SpecialCasesTest.java +++ b/special-case/src/test/java/com/iluwatar/specialcase/SpecialCasesTest.java @@ -26,19 +26,17 @@ package com.iluwatar.specialcase; import static org.junit.jupiter.api.Assertions.assertEquals; -import org.junit.jupiter.api.BeforeAll; -import org.slf4j.LoggerFactory; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.read.ListAppender; import java.util.List; -import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.slf4j.LoggerFactory; -/** - * Special cases unit tests. (including the successful scenario {@link ReceiptDto}) - */ +/** Special cases unit tests. (including the successful scenario {@link ReceiptDto}) */ class SpecialCasesTest { private static ApplicationServices applicationServices; private static ReceiptViewModel receipt; @@ -102,8 +100,8 @@ class SpecialCasesTest { receipt.show(); List loggingEventList = listAppender.list; - assertEquals("Out of stock: tv for user = ignite1771 to buy" - , loggingEventList.get(0).getMessage()); + assertEquals( + "Out of stock: tv for user = ignite1771 to buy", loggingEventList.get(0).getMessage()); assertEquals(Level.INFO, loggingEventList.get(0).getLevel()); } @@ -119,8 +117,9 @@ class SpecialCasesTest { receipt.show(); List loggingEventList = listAppender.list; - assertEquals("Insufficient funds: 1000.0 of user: ignite1771 for buying item: car" - , loggingEventList.get(0).getMessage()); + assertEquals( + "Insufficient funds: 1000.0 of user: ignite1771 for buying item: car", + loggingEventList.get(0).getMessage()); assertEquals(Level.INFO, loggingEventList.get(0).getLevel()); } @@ -136,8 +135,7 @@ class SpecialCasesTest { receipt.show(); List loggingEventList = listAppender.list; - assertEquals("Receipt: 800.0 paid" - , loggingEventList.get(0).getMessage()); + assertEquals("Receipt: 800.0 paid", loggingEventList.get(0).getMessage()); assertEquals(Level.INFO, loggingEventList.get(0).getLevel()); } } diff --git a/specification/pom.xml b/specification/pom.xml index 6f97d68dc..078025193 100644 --- a/specification/pom.xml +++ b/specification/pom.xml @@ -34,6 +34,14 @@ specification + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/specification/src/main/java/com/iluwatar/specification/app/App.java b/specification/src/main/java/com/iluwatar/specification/app/App.java index 381cce202..83486d21d 100644 --- a/specification/src/main/java/com/iluwatar/specification/app/App.java +++ b/specification/src/main/java/com/iluwatar/specification/app/App.java @@ -44,32 +44,25 @@ import java.util.function.Predicate; import lombok.extern.slf4j.Slf4j; /** - *

The central idea of the Specification pattern is to separate the statement of how to match a + * The central idea of the Specification pattern is to separate the statement of how to match a * candidate, from the candidate object that it is matched against. As well as its usefulness in - * selection, it is also valuable for validation and for building to order.

+ * selection, it is also valuable for validation and for building to order. * *

In this example we have a pool of creatures with different properties. We then have defined * separate selection rules (Specifications) that we apply to the collection and as output receive - * only the creatures that match the selection criteria.

+ * only the creatures that match the selection criteria. * - *

http://martinfowler.com/apsupp/spec.pdf

+ *

http://martinfowler.com/apsupp/spec.pdf */ @Slf4j public class App { - /** - * Program entry point. - */ + /** Program entry point. */ public static void main(String[] args) { // initialize creatures list - var creatures = List.of( - new Goblin(), - new Octopus(), - new Dragon(), - new Shark(), - new Troll(), - new KillerBee() - ); + var creatures = + List.of( + new Goblin(), new Octopus(), new Dragon(), new Shark(), new Troll(), new KillerBee()); // so-called "hard-coded" specification LOGGER.info("Demonstrating hard-coded specification :"); // find all walking creatures @@ -96,9 +89,11 @@ public class App { print(creatures, redAndFlying); // find all creatures dark or red, non-swimming, and heavier than or equal to 400kg LOGGER.info("Find all scary creatures"); - var scaryCreaturesSelector = new ColorSelector(Color.DARK) - .or(new ColorSelector(Color.RED)).and(new MovementSelector(Movement.SWIMMING).not()) - .and(new MassGreaterThanSelector(400.0).or(new MassEqualSelector(400.0))); + var scaryCreaturesSelector = + new ColorSelector(Color.DARK) + .or(new ColorSelector(Color.RED)) + .and(new MovementSelector(Movement.SWIMMING).not()) + .and(new MassGreaterThanSelector(400.0).or(new MassEqualSelector(400.0))); print(creatures, scaryCreaturesSelector); } diff --git a/specification/src/main/java/com/iluwatar/specification/creature/AbstractCreature.java b/specification/src/main/java/com/iluwatar/specification/creature/AbstractCreature.java index 610404fb9..9afa65e43 100644 --- a/specification/src/main/java/com/iluwatar/specification/creature/AbstractCreature.java +++ b/specification/src/main/java/com/iluwatar/specification/creature/AbstractCreature.java @@ -29,9 +29,7 @@ import com.iluwatar.specification.property.Mass; import com.iluwatar.specification.property.Movement; import com.iluwatar.specification.property.Size; -/** - * Base class for concrete creatures. - */ +/** Base class for concrete creatures. */ public abstract class AbstractCreature implements Creature { private final String name; @@ -40,9 +38,7 @@ public abstract class AbstractCreature implements Creature { private final Color color; private final Mass mass; - /** - * Constructor. - */ + /** Constructor. */ public AbstractCreature(String name, Size size, Movement movement, Color color, Mass mass) { this.name = name; this.size = size; @@ -53,8 +49,8 @@ public abstract class AbstractCreature implements Creature { @Override public String toString() { - return String.format("%s [size=%s, movement=%s, color=%s, mass=%s]", - name, size, movement, color, mass); + return String.format( + "%s [size=%s, movement=%s, color=%s, mass=%s]", name, size, movement, color, mass); } @Override diff --git a/specification/src/main/java/com/iluwatar/specification/creature/Creature.java b/specification/src/main/java/com/iluwatar/specification/creature/Creature.java index b52d2d7ef..0e02e8b6d 100644 --- a/specification/src/main/java/com/iluwatar/specification/creature/Creature.java +++ b/specification/src/main/java/com/iluwatar/specification/creature/Creature.java @@ -29,9 +29,7 @@ import com.iluwatar.specification.property.Mass; import com.iluwatar.specification.property.Movement; import com.iluwatar.specification.property.Size; -/** - * Creature interface. - */ +/** Creature interface. */ public interface Creature { String getName(); diff --git a/specification/src/main/java/com/iluwatar/specification/creature/Dragon.java b/specification/src/main/java/com/iluwatar/specification/creature/Dragon.java index 9d85da31b..5d05819c0 100644 --- a/specification/src/main/java/com/iluwatar/specification/creature/Dragon.java +++ b/specification/src/main/java/com/iluwatar/specification/creature/Dragon.java @@ -29,9 +29,7 @@ import com.iluwatar.specification.property.Mass; import com.iluwatar.specification.property.Movement; import com.iluwatar.specification.property.Size; -/** - * Dragon creature. - */ +/** Dragon creature. */ public class Dragon extends AbstractCreature { public Dragon() { diff --git a/specification/src/main/java/com/iluwatar/specification/creature/Goblin.java b/specification/src/main/java/com/iluwatar/specification/creature/Goblin.java index 4177df1ed..faff6750a 100644 --- a/specification/src/main/java/com/iluwatar/specification/creature/Goblin.java +++ b/specification/src/main/java/com/iluwatar/specification/creature/Goblin.java @@ -29,9 +29,7 @@ import com.iluwatar.specification.property.Mass; import com.iluwatar.specification.property.Movement; import com.iluwatar.specification.property.Size; -/** - * Goblin creature. - */ +/** Goblin creature. */ public class Goblin extends AbstractCreature { public Goblin() { diff --git a/specification/src/main/java/com/iluwatar/specification/creature/KillerBee.java b/specification/src/main/java/com/iluwatar/specification/creature/KillerBee.java index c27e93119..4bfc3eefe 100644 --- a/specification/src/main/java/com/iluwatar/specification/creature/KillerBee.java +++ b/specification/src/main/java/com/iluwatar/specification/creature/KillerBee.java @@ -29,9 +29,7 @@ import com.iluwatar.specification.property.Mass; import com.iluwatar.specification.property.Movement; import com.iluwatar.specification.property.Size; -/** - * KillerBee creature. - */ +/** KillerBee creature. */ public class KillerBee extends AbstractCreature { public KillerBee() { diff --git a/specification/src/main/java/com/iluwatar/specification/creature/Octopus.java b/specification/src/main/java/com/iluwatar/specification/creature/Octopus.java index 66096d465..5760511cf 100644 --- a/specification/src/main/java/com/iluwatar/specification/creature/Octopus.java +++ b/specification/src/main/java/com/iluwatar/specification/creature/Octopus.java @@ -29,9 +29,7 @@ import com.iluwatar.specification.property.Mass; import com.iluwatar.specification.property.Movement; import com.iluwatar.specification.property.Size; -/** - * Octopus creature. - */ +/** Octopus creature. */ public class Octopus extends AbstractCreature { public Octopus() { diff --git a/specification/src/main/java/com/iluwatar/specification/creature/Shark.java b/specification/src/main/java/com/iluwatar/specification/creature/Shark.java index 2a485092d..972feae76 100644 --- a/specification/src/main/java/com/iluwatar/specification/creature/Shark.java +++ b/specification/src/main/java/com/iluwatar/specification/creature/Shark.java @@ -29,9 +29,7 @@ import com.iluwatar.specification.property.Mass; import com.iluwatar.specification.property.Movement; import com.iluwatar.specification.property.Size; -/** - * Shark creature. - */ +/** Shark creature. */ public class Shark extends AbstractCreature { public Shark() { diff --git a/specification/src/main/java/com/iluwatar/specification/creature/Troll.java b/specification/src/main/java/com/iluwatar/specification/creature/Troll.java index de4ab9b75..0ef9ca257 100644 --- a/specification/src/main/java/com/iluwatar/specification/creature/Troll.java +++ b/specification/src/main/java/com/iluwatar/specification/creature/Troll.java @@ -29,9 +29,7 @@ import com.iluwatar.specification.property.Mass; import com.iluwatar.specification.property.Movement; import com.iluwatar.specification.property.Size; -/** - * Troll creature. - */ +/** Troll creature. */ public class Troll extends AbstractCreature { public Troll() { diff --git a/specification/src/main/java/com/iluwatar/specification/property/Color.java b/specification/src/main/java/com/iluwatar/specification/property/Color.java index 9b15a82c9..d52ec3088 100644 --- a/specification/src/main/java/com/iluwatar/specification/property/Color.java +++ b/specification/src/main/java/com/iluwatar/specification/property/Color.java @@ -24,12 +24,12 @@ */ package com.iluwatar.specification.property; -/** - * Color property. - */ +/** Color property. */ public enum Color { - - DARK("dark"), LIGHT("light"), GREEN("green"), RED("red"); + DARK("dark"), + LIGHT("light"), + GREEN("green"), + RED("red"); private final String title; diff --git a/specification/src/main/java/com/iluwatar/specification/property/Mass.java b/specification/src/main/java/com/iluwatar/specification/property/Mass.java index 384f0dc7b..686822351 100644 --- a/specification/src/main/java/com/iluwatar/specification/property/Mass.java +++ b/specification/src/main/java/com/iluwatar/specification/property/Mass.java @@ -26,9 +26,7 @@ package com.iluwatar.specification.property; import lombok.EqualsAndHashCode; -/** - * Mass property. - */ +/** Mass property. */ @EqualsAndHashCode public class Mass { @@ -60,5 +58,4 @@ public class Mass { public String toString() { return title; } - } diff --git a/specification/src/main/java/com/iluwatar/specification/property/Movement.java b/specification/src/main/java/com/iluwatar/specification/property/Movement.java index d6deb7cac..2bead5153 100644 --- a/specification/src/main/java/com/iluwatar/specification/property/Movement.java +++ b/specification/src/main/java/com/iluwatar/specification/property/Movement.java @@ -24,12 +24,11 @@ */ package com.iluwatar.specification.property; -/** - * Movement property. - */ +/** Movement property. */ public enum Movement { - - WALKING("walking"), SWIMMING("swimming"), FLYING("flying"); + WALKING("walking"), + SWIMMING("swimming"), + FLYING("flying"); private final String title; diff --git a/specification/src/main/java/com/iluwatar/specification/property/Size.java b/specification/src/main/java/com/iluwatar/specification/property/Size.java index 9869c26b7..66b32dc88 100644 --- a/specification/src/main/java/com/iluwatar/specification/property/Size.java +++ b/specification/src/main/java/com/iluwatar/specification/property/Size.java @@ -24,12 +24,11 @@ */ package com.iluwatar.specification.property; -/** - * Size property. - */ +/** Size property. */ public enum Size { - - SMALL("small"), NORMAL("normal"), LARGE("large"); + SMALL("small"), + NORMAL("normal"), + LARGE("large"); private final String title; diff --git a/specification/src/main/java/com/iluwatar/specification/selector/AbstractSelector.java b/specification/src/main/java/com/iluwatar/specification/selector/AbstractSelector.java index c223c203a..48b04c2bd 100644 --- a/specification/src/main/java/com/iluwatar/specification/selector/AbstractSelector.java +++ b/specification/src/main/java/com/iluwatar/specification/selector/AbstractSelector.java @@ -26,9 +26,7 @@ package com.iluwatar.specification.selector; import java.util.function.Predicate; -/** - * Base class for selectors. - */ +/** Base class for selectors. */ public abstract class AbstractSelector implements Predicate { public AbstractSelector and(AbstractSelector other) { diff --git a/specification/src/main/java/com/iluwatar/specification/selector/ColorSelector.java b/specification/src/main/java/com/iluwatar/specification/selector/ColorSelector.java index a14bb6c98..97d9757e0 100644 --- a/specification/src/main/java/com/iluwatar/specification/selector/ColorSelector.java +++ b/specification/src/main/java/com/iluwatar/specification/selector/ColorSelector.java @@ -27,9 +27,7 @@ package com.iluwatar.specification.selector; import com.iluwatar.specification.creature.Creature; import com.iluwatar.specification.property.Color; -/** - * Color selector. - */ +/** Color selector. */ public class ColorSelector extends AbstractSelector { private final Color color; diff --git a/specification/src/main/java/com/iluwatar/specification/selector/ConjunctionSelector.java b/specification/src/main/java/com/iluwatar/specification/selector/ConjunctionSelector.java index 60d13deb9..303fea7ae 100644 --- a/specification/src/main/java/com/iluwatar/specification/selector/ConjunctionSelector.java +++ b/specification/src/main/java/com/iluwatar/specification/selector/ConjunctionSelector.java @@ -26,9 +26,7 @@ package com.iluwatar.specification.selector; import java.util.List; -/** - * A Selector defined as the conjunction (AND) of other (leaf) selectors. - */ +/** A Selector defined as the conjunction (AND) of other (leaf) selectors. */ public class ConjunctionSelector extends AbstractSelector { private final List> leafComponents; @@ -38,9 +36,7 @@ public class ConjunctionSelector extends AbstractSelector { this.leafComponents = List.of(selectors); } - /** - * Tests if *all* selectors pass the test. - */ + /** Tests if *all* selectors pass the test. */ @Override public boolean test(T t) { return leafComponents.stream().allMatch(comp -> (comp.test(t))); diff --git a/specification/src/main/java/com/iluwatar/specification/selector/DisjunctionSelector.java b/specification/src/main/java/com/iluwatar/specification/selector/DisjunctionSelector.java index 212b6f9df..0a8003034 100644 --- a/specification/src/main/java/com/iluwatar/specification/selector/DisjunctionSelector.java +++ b/specification/src/main/java/com/iluwatar/specification/selector/DisjunctionSelector.java @@ -26,9 +26,7 @@ package com.iluwatar.specification.selector; import java.util.List; -/** - * A Selector defined as the disjunction (OR) of other (leaf) selectors. - */ +/** A Selector defined as the disjunction (OR) of other (leaf) selectors. */ public class DisjunctionSelector extends AbstractSelector { private final List> leafComponents; @@ -38,9 +36,7 @@ public class DisjunctionSelector extends AbstractSelector { this.leafComponents = List.of(selectors); } - /** - * Tests if *at least one* selector passes the test. - */ + /** Tests if *at least one* selector passes the test. */ @Override public boolean test(T t) { return leafComponents.stream().anyMatch(comp -> comp.test(t)); diff --git a/specification/src/main/java/com/iluwatar/specification/selector/MassEqualSelector.java b/specification/src/main/java/com/iluwatar/specification/selector/MassEqualSelector.java index 32cbee445..244b49d55 100644 --- a/specification/src/main/java/com/iluwatar/specification/selector/MassEqualSelector.java +++ b/specification/src/main/java/com/iluwatar/specification/selector/MassEqualSelector.java @@ -27,16 +27,12 @@ package com.iluwatar.specification.selector; import com.iluwatar.specification.creature.Creature; import com.iluwatar.specification.property.Mass; -/** - * Mass selector for values exactly equal than the parameter. - */ +/** Mass selector for values exactly equal than the parameter. */ public class MassEqualSelector extends AbstractSelector { private final Mass mass; - /** - * The use of a double as a parameter will spare some typing when instantiating this class. - */ + /** The use of a double as a parameter will spare some typing when instantiating this class. */ public MassEqualSelector(double mass) { this.mass = new Mass(mass); } diff --git a/specification/src/main/java/com/iluwatar/specification/selector/MassGreaterThanSelector.java b/specification/src/main/java/com/iluwatar/specification/selector/MassGreaterThanSelector.java index d77b2cbdb..62a92281c 100644 --- a/specification/src/main/java/com/iluwatar/specification/selector/MassGreaterThanSelector.java +++ b/specification/src/main/java/com/iluwatar/specification/selector/MassGreaterThanSelector.java @@ -27,16 +27,12 @@ package com.iluwatar.specification.selector; import com.iluwatar.specification.creature.Creature; import com.iluwatar.specification.property.Mass; -/** - * Mass selector for values greater than the parameter. - */ +/** Mass selector for values greater than the parameter. */ public class MassGreaterThanSelector extends AbstractSelector { private final Mass mass; - /** - * The use of a double as a parameter will spare some typing when instantiating this class. - */ + /** The use of a double as a parameter will spare some typing when instantiating this class. */ public MassGreaterThanSelector(double mass) { this.mass = new Mass(mass); } diff --git a/specification/src/main/java/com/iluwatar/specification/selector/MassSmallerThanOrEqSelector.java b/specification/src/main/java/com/iluwatar/specification/selector/MassSmallerThanOrEqSelector.java index 75b6d0bc2..7abb593a0 100644 --- a/specification/src/main/java/com/iluwatar/specification/selector/MassSmallerThanOrEqSelector.java +++ b/specification/src/main/java/com/iluwatar/specification/selector/MassSmallerThanOrEqSelector.java @@ -27,16 +27,12 @@ package com.iluwatar.specification.selector; import com.iluwatar.specification.creature.Creature; import com.iluwatar.specification.property.Mass; -/** - * Mass selector for values smaller or equal to the parameter. - */ +/** Mass selector for values smaller or equal to the parameter. */ public class MassSmallerThanOrEqSelector extends AbstractSelector { private final Mass mass; - /** - * The use of a double as a parameter will spare some typing when instantiating this class. - */ + /** The use of a double as a parameter will spare some typing when instantiating this class. */ public MassSmallerThanOrEqSelector(double mass) { this.mass = new Mass(mass); } diff --git a/specification/src/main/java/com/iluwatar/specification/selector/MovementSelector.java b/specification/src/main/java/com/iluwatar/specification/selector/MovementSelector.java index c4b6a5da2..d6c56de8a 100644 --- a/specification/src/main/java/com/iluwatar/specification/selector/MovementSelector.java +++ b/specification/src/main/java/com/iluwatar/specification/selector/MovementSelector.java @@ -27,9 +27,7 @@ package com.iluwatar.specification.selector; import com.iluwatar.specification.creature.Creature; import com.iluwatar.specification.property.Movement; -/** - * Movement selector. - */ +/** Movement selector. */ public class MovementSelector extends AbstractSelector { private final Movement movement; diff --git a/specification/src/main/java/com/iluwatar/specification/selector/NegationSelector.java b/specification/src/main/java/com/iluwatar/specification/selector/NegationSelector.java index 3239eee01..2948e26bd 100644 --- a/specification/src/main/java/com/iluwatar/specification/selector/NegationSelector.java +++ b/specification/src/main/java/com/iluwatar/specification/selector/NegationSelector.java @@ -24,7 +24,6 @@ */ package com.iluwatar.specification.selector; - /** * A Selector defined as the negation (NOT) of a (leaf) selectors. This is of course only useful * when used in combination with other composite selectors. @@ -37,9 +36,7 @@ public class NegationSelector extends AbstractSelector { this.component = selector; } - /** - * Tests if the selector fails the test (yes). - */ + /** Tests if the selector fails the test (yes). */ @Override public boolean test(T t) { return !(component.test(t)); diff --git a/specification/src/main/java/com/iluwatar/specification/selector/SizeSelector.java b/specification/src/main/java/com/iluwatar/specification/selector/SizeSelector.java index 16e6d1f22..c9b7764f9 100644 --- a/specification/src/main/java/com/iluwatar/specification/selector/SizeSelector.java +++ b/specification/src/main/java/com/iluwatar/specification/selector/SizeSelector.java @@ -27,9 +27,7 @@ package com.iluwatar.specification.selector; import com.iluwatar.specification.creature.Creature; import com.iluwatar.specification.property.Size; -/** - * Size selector. - */ +/** Size selector. */ public class SizeSelector extends AbstractSelector { private final Size size; diff --git a/specification/src/test/java/com/iluwatar/specification/app/AppTest.java b/specification/src/test/java/com/iluwatar/specification/app/AppTest.java index 1d1be65a7..5b9d76843 100644 --- a/specification/src/test/java/com/iluwatar/specification/app/AppTest.java +++ b/specification/src/test/java/com/iluwatar/specification/app/AppTest.java @@ -24,17 +24,15 @@ */ package com.iluwatar.specification.app; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -/** - * Application test - */ +import org.junit.jupiter.api.Test; + +/** Application test */ class AppTest { @Test void shouldExecuteWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/specification/src/test/java/com/iluwatar/specification/creature/CreatureTest.java b/specification/src/test/java/com/iluwatar/specification/creature/CreatureTest.java index 96923741a..e400c9835 100644 --- a/specification/src/test/java/com/iluwatar/specification/creature/CreatureTest.java +++ b/specification/src/test/java/com/iluwatar/specification/creature/CreatureTest.java @@ -36,10 +36,7 @@ import java.util.List; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; -/** - * CreatureTest - * - */ +/** CreatureTest */ class CreatureTest { /** @@ -47,19 +44,24 @@ class CreatureTest { */ public static Collection dataProvider() { return List.of( - new Object[]{new Dragon(), "Dragon", Size.LARGE, Movement.FLYING, Color.RED, - new Mass(39300.0)}, - new Object[]{new Goblin(), "Goblin", Size.SMALL, Movement.WALKING, Color.GREEN, - new Mass(30.0)}, - new Object[]{new KillerBee(), "KillerBee", Size.SMALL, Movement.FLYING, Color.LIGHT, - new Mass(6.7)}, - new Object[]{new Octopus(), "Octopus", Size.NORMAL, Movement.SWIMMING, Color.DARK, - new Mass(12.0)}, - new Object[]{new Shark(), "Shark", Size.NORMAL, Movement.SWIMMING, Color.LIGHT, - new Mass(500.0)}, - new Object[]{new Troll(), "Troll", Size.LARGE, Movement.WALKING, Color.DARK, - new Mass(4000.0)} - ); + new Object[] { + new Dragon(), "Dragon", Size.LARGE, Movement.FLYING, Color.RED, new Mass(39300.0) + }, + new Object[] { + new Goblin(), "Goblin", Size.SMALL, Movement.WALKING, Color.GREEN, new Mass(30.0) + }, + new Object[] { + new KillerBee(), "KillerBee", Size.SMALL, Movement.FLYING, Color.LIGHT, new Mass(6.7) + }, + new Object[] { + new Octopus(), "Octopus", Size.NORMAL, Movement.SWIMMING, Color.DARK, new Mass(12.0) + }, + new Object[] { + new Shark(), "Shark", Size.NORMAL, Movement.SWIMMING, Color.LIGHT, new Mass(500.0) + }, + new Object[] { + new Troll(), "Troll", Size.LARGE, Movement.WALKING, Color.DARK, new Mass(4000.0) + }); } @ParameterizedTest @@ -82,25 +84,27 @@ class CreatureTest { @ParameterizedTest @MethodSource("dataProvider") - void testGetColor(Creature testedCreature, String name, Size size, Movement movement, - Color color) { + void testGetColor( + Creature testedCreature, String name, Size size, Movement movement, Color color) { assertEquals(color, testedCreature.getColor()); } @ParameterizedTest @MethodSource("dataProvider") - void testGetMass(Creature testedCreature, String name, Size size, Movement movement, - Color color, Mass mass) { + void testGetMass( + Creature testedCreature, String name, Size size, Movement movement, Color color, Mass mass) { assertEquals(mass, testedCreature.getMass()); } @ParameterizedTest @MethodSource("dataProvider") - void testToString(Creature testedCreature, String name, Size size, Movement movement, - Color color, Mass mass) { + void testToString( + Creature testedCreature, String name, Size size, Movement movement, Color color, Mass mass) { final var toString = testedCreature.toString(); assertNotNull(toString); - assertEquals(String - .format("%s [size=%s, movement=%s, color=%s, mass=%s]", name, size, movement, color, mass), toString); + assertEquals( + String.format( + "%s [size=%s, movement=%s, color=%s, mass=%s]", name, size, movement, color, mass), + toString); } -} \ No newline at end of file +} diff --git a/specification/src/test/java/com/iluwatar/specification/selector/ColorSelectorTest.java b/specification/src/test/java/com/iluwatar/specification/selector/ColorSelectorTest.java index d9f4aeaf5..d2e6d2624 100644 --- a/specification/src/test/java/com/iluwatar/specification/selector/ColorSelectorTest.java +++ b/specification/src/test/java/com/iluwatar/specification/selector/ColorSelectorTest.java @@ -33,15 +33,10 @@ import com.iluwatar.specification.creature.Creature; import com.iluwatar.specification.property.Color; import org.junit.jupiter.api.Test; -/** - * ColorSelectorTest - * - */ +/** ColorSelectorTest */ class ColorSelectorTest { - /** - * Verify if the color selector gives the correct results - */ + /** Verify if the color selector gives the correct results */ @Test void testColor() { final var greenCreature = mock(Creature.class); @@ -53,7 +48,5 @@ class ColorSelectorTest { final var greenSelector = new ColorSelector(Color.GREEN); assertTrue(greenSelector.test(greenCreature)); assertFalse(greenSelector.test(redCreature)); - } - -} \ No newline at end of file +} diff --git a/specification/src/test/java/com/iluwatar/specification/selector/CompositeSelectorsTest.java b/specification/src/test/java/com/iluwatar/specification/selector/CompositeSelectorsTest.java index cc314dd6b..d7dc5e12c 100644 --- a/specification/src/test/java/com/iluwatar/specification/selector/CompositeSelectorsTest.java +++ b/specification/src/test/java/com/iluwatar/specification/selector/CompositeSelectorsTest.java @@ -36,9 +36,7 @@ import org.junit.jupiter.api.Test; class CompositeSelectorsTest { - /** - * Verify if the conjunction selector gives the correct results. - */ + /** Verify if the conjunction selector gives the correct results. */ @Test void testAndComposition() { final var swimmingHeavyCreature = mock(Creature.class); @@ -49,15 +47,13 @@ class CompositeSelectorsTest { when(swimmingLightCreature.getMovement()).thenReturn(Movement.SWIMMING); when(swimmingLightCreature.getMass()).thenReturn(new Mass(25.0)); - final var lightAndSwimmingSelector = new MassSmallerThanOrEqSelector(50.0) - .and(new MovementSelector(Movement.SWIMMING)); + final var lightAndSwimmingSelector = + new MassSmallerThanOrEqSelector(50.0).and(new MovementSelector(Movement.SWIMMING)); assertFalse(lightAndSwimmingSelector.test(swimmingHeavyCreature)); assertTrue(lightAndSwimmingSelector.test(swimmingLightCreature)); } - /** - * Verify if the disjunction selector gives the correct results. - */ + /** Verify if the disjunction selector gives the correct results. */ @Test void testOrComposition() { final var swimmingHeavyCreature = mock(Creature.class); @@ -68,15 +64,13 @@ class CompositeSelectorsTest { when(swimmingLightCreature.getMovement()).thenReturn(Movement.SWIMMING); when(swimmingLightCreature.getMass()).thenReturn(new Mass(25.0)); - final var lightOrSwimmingSelector = new MassSmallerThanOrEqSelector(50.0) - .or(new MovementSelector(Movement.SWIMMING)); + final var lightOrSwimmingSelector = + new MassSmallerThanOrEqSelector(50.0).or(new MovementSelector(Movement.SWIMMING)); assertTrue(lightOrSwimmingSelector.test(swimmingHeavyCreature)); assertTrue(lightOrSwimmingSelector.test(swimmingLightCreature)); } - /** - * Verify if the negation selector gives the correct results. - */ + /** Verify if the negation selector gives the correct results. */ @Test void testNotComposition() { final var swimmingHeavyCreature = mock(Creature.class); diff --git a/specification/src/test/java/com/iluwatar/specification/selector/MassSelectorTest.java b/specification/src/test/java/com/iluwatar/specification/selector/MassSelectorTest.java index b4697b60f..e55ddbde1 100644 --- a/specification/src/test/java/com/iluwatar/specification/selector/MassSelectorTest.java +++ b/specification/src/test/java/com/iluwatar/specification/selector/MassSelectorTest.java @@ -35,9 +35,7 @@ import org.junit.jupiter.api.Test; class MassSelectorTest { - /** - * Verify if the mass selector gives the correct results. - */ + /** Verify if the mass selector gives the correct results. */ @Test void testMass() { final var lightCreature = mock(Creature.class); diff --git a/specification/src/test/java/com/iluwatar/specification/selector/MovementSelectorTest.java b/specification/src/test/java/com/iluwatar/specification/selector/MovementSelectorTest.java index 7118a6817..e0fb51569 100644 --- a/specification/src/test/java/com/iluwatar/specification/selector/MovementSelectorTest.java +++ b/specification/src/test/java/com/iluwatar/specification/selector/MovementSelectorTest.java @@ -33,15 +33,10 @@ import com.iluwatar.specification.creature.Creature; import com.iluwatar.specification.property.Movement; import org.junit.jupiter.api.Test; -/** - * MovementSelectorTest - * - */ +/** MovementSelectorTest */ class MovementSelectorTest { - /** - * Verify if the movement selector gives the correct results. - */ + /** Verify if the movement selector gives the correct results. */ @Test void testMovement() { final var swimmingCreature = mock(Creature.class); @@ -53,7 +48,5 @@ class MovementSelectorTest { final var swimmingSelector = new MovementSelector(Movement.SWIMMING); assertTrue(swimmingSelector.test(swimmingCreature)); assertFalse(swimmingSelector.test(flyingCreature)); - } - -} \ No newline at end of file +} diff --git a/specification/src/test/java/com/iluwatar/specification/selector/SizeSelectorTest.java b/specification/src/test/java/com/iluwatar/specification/selector/SizeSelectorTest.java index 68f7692ef..6aa65226a 100644 --- a/specification/src/test/java/com/iluwatar/specification/selector/SizeSelectorTest.java +++ b/specification/src/test/java/com/iluwatar/specification/selector/SizeSelectorTest.java @@ -33,15 +33,10 @@ import com.iluwatar.specification.creature.Creature; import com.iluwatar.specification.property.Size; import org.junit.jupiter.api.Test; -/** - * SizeSelectorTest - * - */ +/** SizeSelectorTest */ class SizeSelectorTest { - /** - * Verify if the size selector gives the correct results - */ + /** Verify if the size selector gives the correct results */ @Test void testMovement() { final var normalCreature = mock(Creature.class); @@ -54,5 +49,4 @@ class SizeSelectorTest { assertTrue(normalSelector.test(normalCreature)); assertFalse(normalSelector.test(smallCreature)); } - } diff --git a/state/pom.xml b/state/pom.xml index c4ce3b6f3..9bd6df825 100644 --- a/state/pom.xml +++ b/state/pom.xml @@ -34,6 +34,14 @@ state + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/state/src/main/java/com/iluwatar/state/AngryState.java b/state/src/main/java/com/iluwatar/state/AngryState.java index c20085c44..f26126ee0 100644 --- a/state/src/main/java/com/iluwatar/state/AngryState.java +++ b/state/src/main/java/com/iluwatar/state/AngryState.java @@ -26,9 +26,7 @@ package com.iluwatar.state; import lombok.extern.slf4j.Slf4j; -/** - * Angry state. - */ +/** Angry state. */ @Slf4j public class AngryState implements State { @@ -47,5 +45,4 @@ public class AngryState implements State { public void onEnterState() { LOGGER.info("{} gets angry!", mammoth); } - } diff --git a/state/src/main/java/com/iluwatar/state/App.java b/state/src/main/java/com/iluwatar/state/App.java index 12ee7871b..37d8ae37b 100644 --- a/state/src/main/java/com/iluwatar/state/App.java +++ b/state/src/main/java/com/iluwatar/state/App.java @@ -28,16 +28,14 @@ package com.iluwatar.state; * In the State pattern, the container object has an internal state object that defines the current * behavior. The state object can be changed to alter the behavior. * - *

This can be a cleaner way for an object to change its behavior at runtime without resorting - * to large monolithic conditional statements and thus improves maintainability. + *

This can be a cleaner way for an object to change its behavior at runtime without resorting to + * large monolithic conditional statements and thus improves maintainability. * *

In this example the {@link Mammoth} changes its behavior as time passes by. */ public class App { - /** - * Program entry point. - */ + /** Program entry point. */ public static void main(String[] args) { var mammoth = new Mammoth(); diff --git a/state/src/main/java/com/iluwatar/state/Mammoth.java b/state/src/main/java/com/iluwatar/state/Mammoth.java index 4815e1259..f9b3006ec 100644 --- a/state/src/main/java/com/iluwatar/state/Mammoth.java +++ b/state/src/main/java/com/iluwatar/state/Mammoth.java @@ -1,62 +1,58 @@ -/* - * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). - * - * The MIT License - * Copyright © 2014-2022 Ilkka Seppälä - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package com.iluwatar.state; - -/** - * Mammoth has internal state that defines its behavior. - */ -public class Mammoth { - - private State state; - - public Mammoth() { - state = new PeacefulState(this); - } - - /** - * Makes time pass for the mammoth. - */ - public void timePasses() { - if (state.getClass().equals(PeacefulState.class)) { - changeStateTo(new AngryState(this)); - } else { - changeStateTo(new PeacefulState(this)); - } - } - - private void changeStateTo(State newState) { - this.state = newState; - this.state.onEnterState(); - } - - @Override - public String toString() { - return "The mammoth"; - } - - public void observe() { - this.state.observe(); - } -} +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.state; + +/** Mammoth has internal state that defines its behavior. */ +public class Mammoth { + + private State state; + + public Mammoth() { + state = new PeacefulState(this); + } + + /** Makes time pass for the mammoth. */ + public void timePasses() { + if (state.getClass().equals(PeacefulState.class)) { + changeStateTo(new AngryState(this)); + } else { + changeStateTo(new PeacefulState(this)); + } + } + + private void changeStateTo(State newState) { + this.state = newState; + this.state.onEnterState(); + } + + @Override + public String toString() { + return "The mammoth"; + } + + public void observe() { + this.state.observe(); + } +} diff --git a/state/src/main/java/com/iluwatar/state/PeacefulState.java b/state/src/main/java/com/iluwatar/state/PeacefulState.java index 4f558bb7d..3511ba4cb 100644 --- a/state/src/main/java/com/iluwatar/state/PeacefulState.java +++ b/state/src/main/java/com/iluwatar/state/PeacefulState.java @@ -26,9 +26,7 @@ package com.iluwatar.state; import lombok.extern.slf4j.Slf4j; -/** - * Peaceful state. - */ +/** Peaceful state. */ @Slf4j public class PeacefulState implements State { @@ -47,5 +45,4 @@ public class PeacefulState implements State { public void onEnterState() { LOGGER.info("{} calms down.", mammoth); } - } diff --git a/state/src/main/java/com/iluwatar/state/State.java b/state/src/main/java/com/iluwatar/state/State.java index ee39a8aa6..f305dff21 100644 --- a/state/src/main/java/com/iluwatar/state/State.java +++ b/state/src/main/java/com/iluwatar/state/State.java @@ -1,35 +1,33 @@ -/* - * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). - * - * The MIT License - * Copyright © 2014-2022 Ilkka Seppälä - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package com.iluwatar.state; - -/** - * State interface. - */ -public interface State { - - void onEnterState(); - - void observe(); -} +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.state; + +/** State interface. */ +public interface State { + + void onEnterState(); + + void observe(); +} diff --git a/state/src/test/java/com/iluwatar/state/AppTest.java b/state/src/test/java/com/iluwatar/state/AppTest.java index e6623790d..dc80141b9 100644 --- a/state/src/test/java/com/iluwatar/state/AppTest.java +++ b/state/src/test/java/com/iluwatar/state/AppTest.java @@ -24,17 +24,15 @@ */ package com.iluwatar.state; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -/** - * Application test - */ +import org.junit.jupiter.api.Test; + +/** Application test */ class AppTest { @Test void shouldExecuteWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/state/src/test/java/com/iluwatar/state/MammothTest.java b/state/src/test/java/com/iluwatar/state/MammothTest.java index 629963580..8fa8be1ea 100644 --- a/state/src/test/java/com/iluwatar/state/MammothTest.java +++ b/state/src/test/java/com/iluwatar/state/MammothTest.java @@ -37,10 +37,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.slf4j.LoggerFactory; -/** - * MammothTest - * - */ +/** MammothTest */ class MammothTest { private InMemoryAppender appender; @@ -82,12 +79,9 @@ class MammothTest { mammoth.observe(); assertEquals("The mammoth is calm and peaceful.", appender.getLastMessage()); assertEquals(5, appender.getLogSize()); - } - /** - * Verify if {@link Mammoth#toString()} gives the expected value - */ + /** Verify if {@link Mammoth#toString()} gives the expected value */ @Test void testToString() { final var toString = new Mammoth().toString(); @@ -116,5 +110,4 @@ class MammothTest { return log.get(log.size() - 1).getFormattedMessage(); } } - } diff --git a/step-builder/pom.xml b/step-builder/pom.xml index 2c6979d48..79ebbec52 100644 --- a/step-builder/pom.xml +++ b/step-builder/pom.xml @@ -34,6 +34,14 @@ step-builder + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/step-builder/src/main/java/com/iluwatar/stepbuilder/App.java b/step-builder/src/main/java/com/iluwatar/stepbuilder/App.java index a5ffb6060..dfa73e573 100644 --- a/step-builder/src/main/java/com/iluwatar/stepbuilder/App.java +++ b/step-builder/src/main/java/com/iluwatar/stepbuilder/App.java @@ -31,30 +31,28 @@ import lombok.extern.slf4j.Slf4j; * *

Intent
* An extension of the Builder pattern that fully guides the user through the creation of the object - * with no chances of confusion.
The user experience will be much more improved by the fact - * that he will only see the next step methods available, NO build method until is the right time to - * build the object. + * with no chances of confusion.
+ * The user experience will be much more improved by the fact that he will only see the next step + * methods available, NO build method until is the right time to build the object. * *

Implementation
* The concept is simple: + * *

    - * - *
  • Write creational steps inner classes or interfaces where each method knows what can be - * displayed next.
  • - * - *
  • Implement all your steps interfaces in an inner static class.
  • - * - *
  • Last step is the BuildStep, in charge of creating the object you need to build.
  • + *
  • Write creational steps inner classes or interfaces where each method knows what can be + * displayed next. + *
  • Implement all your steps interfaces in an inner static class. + *
  • Last step is the BuildStep, in charge of creating the object you need to build. *
* *

Applicability
* Use the Step Builder pattern when the algorithm for creating a complex object should be * independent of the parts that make up the object and how they're assembled the construction * process must allow different representations for the object that's constructed when in the - * process of constructing the order is important. - *
+ * process of constructing the order is important.
* - * @see http://rdafbn.blogspot.co.uk/2012/07/step-builder-pattern_28.html + * @see http://rdafbn.blogspot.co.uk/2012/07/step-builder-pattern_28.html */ @Slf4j public class App { @@ -66,34 +64,30 @@ public class App { */ public static void main(String[] args) { - var warrior = CharacterStepBuilder - .newBuilder() - .name("Amberjill") - .fighterClass("Paladin") - .withWeapon("Sword") - .noAbilities() - .build(); + var warrior = + CharacterStepBuilder.newBuilder() + .name("Amberjill") + .fighterClass("Paladin") + .withWeapon("Sword") + .noAbilities() + .build(); LOGGER.info(warrior.toString()); - var mage = CharacterStepBuilder - .newBuilder() - .name("Riobard") - .wizardClass("Sorcerer") - .withSpell("Fireball") - .withAbility("Fire Aura") - .withAbility("Teleport") - .noMoreAbilities() - .build(); + var mage = + CharacterStepBuilder.newBuilder() + .name("Riobard") + .wizardClass("Sorcerer") + .withSpell("Fireball") + .withAbility("Fire Aura") + .withAbility("Teleport") + .noMoreAbilities() + .build(); LOGGER.info(mage.toString()); - var thief = CharacterStepBuilder - .newBuilder() - .name("Desmond") - .fighterClass("Rogue") - .noWeapon() - .build(); + var thief = + CharacterStepBuilder.newBuilder().name("Desmond").fighterClass("Rogue").noWeapon().build(); LOGGER.info(thief.toString()); } diff --git a/step-builder/src/main/java/com/iluwatar/stepbuilder/Character.java b/step-builder/src/main/java/com/iluwatar/stepbuilder/Character.java index 3ecd70de4..dedcd33ef 100644 --- a/step-builder/src/main/java/com/iluwatar/stepbuilder/Character.java +++ b/step-builder/src/main/java/com/iluwatar/stepbuilder/Character.java @@ -28,11 +28,7 @@ import java.util.List; import lombok.Getter; import lombok.Setter; - - -/** - * The class with many parameters. - */ +/** The class with many parameters. */ @Getter @Setter public class Character { @@ -48,7 +44,6 @@ public class Character { this.name = name; } - @Override public String toString() { return new StringBuilder() diff --git a/step-builder/src/main/java/com/iluwatar/stepbuilder/CharacterStepBuilder.java b/step-builder/src/main/java/com/iluwatar/stepbuilder/CharacterStepBuilder.java index 01c23130f..ff5b13631 100644 --- a/step-builder/src/main/java/com/iluwatar/stepbuilder/CharacterStepBuilder.java +++ b/step-builder/src/main/java/com/iluwatar/stepbuilder/CharacterStepBuilder.java @@ -27,21 +27,16 @@ package com.iluwatar.stepbuilder; import java.util.ArrayList; import java.util.List; -/** - * The Step Builder class. - */ +/** The Step Builder class. */ public final class CharacterStepBuilder { - private CharacterStepBuilder() { - } + private CharacterStepBuilder() {} public static NameStep newBuilder() { return new CharacterSteps(); } - /** - * First Builder Step in charge of the Character name. Next Step available : ClassStep - */ + /** First Builder Step in charge of the Character name. Next Step available : ClassStep */ public interface NameStep { ClassStep name(String name); } @@ -76,9 +71,7 @@ public final class CharacterStepBuilder { BuildStep noSpell(); } - /** - * This step is in charge of abilities. Next Step available : BuildStep - */ + /** This step is in charge of abilities. Next Step available : BuildStep */ public interface AbilityStep { AbilityStep withAbility(String ability); @@ -94,12 +87,9 @@ public final class CharacterStepBuilder { Character build(); } - - /** - * Step Builder implementation. - */ - private static class CharacterSteps implements NameStep, ClassStep, WeaponStep, SpellStep, - AbilityStep, BuildStep { + /** Step Builder implementation. */ + private static class CharacterSteps + implements NameStep, ClassStep, WeaponStep, SpellStep, AbilityStep, BuildStep { private String name; private String fighterClass; diff --git a/step-builder/src/test/java/com/iluwatar/stepbuilder/AppTest.java b/step-builder/src/test/java/com/iluwatar/stepbuilder/AppTest.java index b147f6da8..1fcf9ae93 100644 --- a/step-builder/src/test/java/com/iluwatar/stepbuilder/AppTest.java +++ b/step-builder/src/test/java/com/iluwatar/stepbuilder/AppTest.java @@ -24,17 +24,15 @@ */ package com.iluwatar.stepbuilder; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -/** - * Application test - */ +import org.junit.jupiter.api.Test; + +/** Application test */ class AppTest { @Test void shouldExecuteWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/step-builder/src/test/java/com/iluwatar/stepbuilder/CharacterStepBuilderTest.java b/step-builder/src/test/java/com/iluwatar/stepbuilder/CharacterStepBuilderTest.java index f20572263..e6c1ba59d 100644 --- a/step-builder/src/test/java/com/iluwatar/stepbuilder/CharacterStepBuilderTest.java +++ b/step-builder/src/test/java/com/iluwatar/stepbuilder/CharacterStepBuilderTest.java @@ -31,25 +31,21 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; -/** - * CharacterStepBuilderTest - * - */ +/** CharacterStepBuilderTest */ class CharacterStepBuilderTest { - /** - * Build a new wizard {@link Character} and verify if it has the expected attributes - */ + /** Build a new wizard {@link Character} and verify if it has the expected attributes */ @Test void testBuildWizard() { - final var character = CharacterStepBuilder.newBuilder() - .name("Merlin") - .wizardClass("alchemist") - .withSpell("poison") - .withAbility("invisibility") - .withAbility("wisdom") - .noMoreAbilities() - .build(); + final var character = + CharacterStepBuilder.newBuilder() + .name("Merlin") + .wizardClass("alchemist") + .withSpell("poison") + .withAbility("invisibility") + .withAbility("wisdom") + .noMoreAbilities() + .build(); assertEquals("Merlin", character.getName()); assertEquals("alchemist", character.getWizardClass()); @@ -61,7 +57,6 @@ class CharacterStepBuilderTest { assertEquals(2, abilities.size()); assertTrue(abilities.contains("invisibility")); assertTrue(abilities.contains("wisdom")); - } /** @@ -70,53 +65,46 @@ class CharacterStepBuilderTest { */ @Test void testBuildPoorWizard() { - final var character = CharacterStepBuilder.newBuilder() - .name("Merlin") - .wizardClass("alchemist") - .noSpell() - .build(); + final var character = + CharacterStepBuilder.newBuilder().name("Merlin").wizardClass("alchemist").noSpell().build(); assertEquals("Merlin", character.getName()); assertEquals("alchemist", character.getWizardClass()); assertNull(character.getSpell()); assertNull(character.getAbilities()); assertNotNull(character.toString()); - } - /** - * Build a new wizard {@link Character} and verify if it has the expected attributes - */ + /** Build a new wizard {@link Character} and verify if it has the expected attributes */ @Test void testBuildWeakWizard() { - final var character = CharacterStepBuilder.newBuilder() - .name("Merlin") - .wizardClass("alchemist") - .withSpell("poison") - .noAbilities() - .build(); + final var character = + CharacterStepBuilder.newBuilder() + .name("Merlin") + .wizardClass("alchemist") + .withSpell("poison") + .noAbilities() + .build(); assertEquals("Merlin", character.getName()); assertEquals("alchemist", character.getWizardClass()); assertEquals("poison", character.getSpell()); assertNull(character.getAbilities()); assertNotNull(character.toString()); - } - /** - * Build a new warrior {@link Character} and verify if it has the expected attributes - */ + /** Build a new warrior {@link Character} and verify if it has the expected attributes */ @Test void testBuildWarrior() { - final var character = CharacterStepBuilder.newBuilder() - .name("Cuauhtemoc") - .fighterClass("aztec") - .withWeapon("spear") - .withAbility("speed") - .withAbility("strength") - .noMoreAbilities() - .build(); + final var character = + CharacterStepBuilder.newBuilder() + .name("Cuauhtemoc") + .fighterClass("aztec") + .withWeapon("spear") + .withAbility("speed") + .withAbility("strength") + .noMoreAbilities() + .build(); assertEquals("Cuauhtemoc", character.getName()); assertEquals("aztec", character.getFighterClass()); @@ -128,7 +116,6 @@ class CharacterStepBuilderTest { assertEquals(2, abilities.size()); assertTrue(abilities.contains("speed")); assertTrue(abilities.contains("strength")); - } /** @@ -137,18 +124,18 @@ class CharacterStepBuilderTest { */ @Test void testBuildPoorWarrior() { - final var character = CharacterStepBuilder.newBuilder() - .name("Poor warrior") - .fighterClass("none") - .noWeapon() - .build(); + final var character = + CharacterStepBuilder.newBuilder() + .name("Poor warrior") + .fighterClass("none") + .noWeapon() + .build(); assertEquals("Poor warrior", character.getName()); assertEquals("none", character.getFighterClass()); assertNull(character.getWeapon()); assertNull(character.getAbilities()); assertNotNull(character.toString()); - } /** @@ -157,19 +144,18 @@ class CharacterStepBuilderTest { */ @Test void testBuildWeakWarrior() { - final var character = CharacterStepBuilder.newBuilder() - .name("Weak warrior") - .fighterClass("none") - .withWeapon("Slingshot") - .noAbilities() - .build(); + final var character = + CharacterStepBuilder.newBuilder() + .name("Weak warrior") + .fighterClass("none") + .withWeapon("Slingshot") + .noAbilities() + .build(); assertEquals("Weak warrior", character.getName()); assertEquals("none", character.getFighterClass()); assertEquals("Slingshot", character.getWeapon()); assertNull(character.getAbilities()); assertNotNull(character.toString()); - } - -} \ No newline at end of file +} diff --git a/strangler/pom.xml b/strangler/pom.xml index 74b800b06..c05d6c7ec 100644 --- a/strangler/pom.xml +++ b/strangler/pom.xml @@ -34,6 +34,14 @@ 4.0.0 strangler + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/strangler/src/main/java/com/iluwatar/strangler/App.java b/strangler/src/main/java/com/iluwatar/strangler/App.java index 930ce457d..ab8382ca6 100644 --- a/strangler/src/main/java/com/iluwatar/strangler/App.java +++ b/strangler/src/main/java/com/iluwatar/strangler/App.java @@ -25,43 +25,40 @@ package com.iluwatar.strangler; /** + * The Strangler pattern is a software design pattern that incrementally migrate a legacy system by + * gradually replacing specific pieces of functionality with new applications and services. As + * features from the legacy system are replaced, the new system eventually replaces all of the old + * system's features, strangling the old system and allowing you to decommission it. * - *

The Strangler pattern is a software design pattern that incrementally migrate a legacy - * system by gradually replacing specific pieces of functionality with new applications and - * services. As features from the legacy system are replaced, the new system eventually - * replaces all of the old system's features, strangling the old system and allowing you - * to decommission it.

- * - *

This pattern is not only about updating but also enhancement.

- * - *

In this example, {@link OldArithmetic} indicates old system and its implementation depends - * on its source ({@link OldSource}). Now we tend to update system with new techniques and - * new features. In reality, the system may too complex, so usually need gradual migration. - * {@link HalfArithmetic} indicates system in the process of migration, its implementation - * depends on old one ({@link OldSource}) and under development one ({@link HalfSource}). The - * {@link HalfSource} covers part of {@link OldSource} and add new functionality. You can release - * this version system with new features, which also supports old version system functionalities. - * After whole migration, the new system ({@link NewArithmetic}) only depends on new source - * ({@link NewSource}).

+ *

This pattern is not only about updating but also enhancement. * + *

In this example, {@link OldArithmetic} indicates old system and its implementation depends on + * its source ({@link OldSource}). Now we tend to update system with new techniques and new + * features. In reality, the system may too complex, so usually need gradual migration. {@link + * HalfArithmetic} indicates system in the process of migration, its implementation depends on old + * one ({@link OldSource}) and under development one ({@link HalfSource}). The {@link HalfSource} + * covers part of {@link OldSource} and add new functionality. You can release this version system + * with new features, which also supports old version system functionalities. After whole migration, + * the new system ({@link NewArithmetic}) only depends on new source ({@link NewSource}). */ public class App { /** * Program entry point. + * * @param args command line args */ public static void main(final String[] args) { - final var nums = new int[]{1, 2, 3, 4, 5}; - //Before migration + final var nums = new int[] {1, 2, 3, 4, 5}; + // Before migration final var oldSystem = new OldArithmetic(new OldSource()); oldSystem.sum(nums); oldSystem.mul(nums); - //In process of migration + // In process of migration final var halfSystem = new HalfArithmetic(new HalfSource(), new OldSource()); halfSystem.sum(nums); halfSystem.mul(nums); halfSystem.ifHasZero(nums); - //After migration + // After migration final var newSystem = new NewArithmetic(new NewSource()); newSystem.sum(nums); newSystem.mul(nums); diff --git a/strangler/src/main/java/com/iluwatar/strangler/HalfArithmetic.java b/strangler/src/main/java/com/iluwatar/strangler/HalfArithmetic.java index 161ec0655..a34e46bde 100644 --- a/strangler/src/main/java/com/iluwatar/strangler/HalfArithmetic.java +++ b/strangler/src/main/java/com/iluwatar/strangler/HalfArithmetic.java @@ -27,8 +27,8 @@ package com.iluwatar.strangler; import lombok.extern.slf4j.Slf4j; /** - * System under migration. Depends on old version source ({@link OldSource}) and - * developing one ({@link HalfSource}). + * System under migration. Depends on old version source ({@link OldSource}) and developing one + * ({@link HalfSource}). */ @Slf4j public class HalfArithmetic { @@ -44,6 +44,7 @@ public class HalfArithmetic { /** * Accumulate sum. + * * @param nums numbers need to add together * @return accumulate sum */ @@ -54,6 +55,7 @@ public class HalfArithmetic { /** * Accumulate multiplication. + * * @param nums numbers need to multiply together * @return accumulate multiplication */ @@ -64,6 +66,7 @@ public class HalfArithmetic { /** * Check if it has any zero. + * * @param nums numbers need to check * @return if it has any zero, return true, else, return false */ diff --git a/strangler/src/main/java/com/iluwatar/strangler/HalfSource.java b/strangler/src/main/java/com/iluwatar/strangler/HalfSource.java index 9413b55d2..ad9f38ec0 100644 --- a/strangler/src/main/java/com/iluwatar/strangler/HalfSource.java +++ b/strangler/src/main/java/com/iluwatar/strangler/HalfSource.java @@ -27,26 +27,18 @@ package com.iluwatar.strangler; import java.util.Arrays; import lombok.extern.slf4j.Slf4j; -/** - * Source under development. Replace part of old source and has added some new features. - */ +/** Source under development. Replace part of old source and has added some new features. */ @Slf4j public class HalfSource { private static final String VERSION = "1.5"; - /** - * Implement accumulate sum with new technique. - * Replace old one in {@link OldSource} - */ + /** Implement accumulate sum with new technique. Replace old one in {@link OldSource} */ public int accumulateSum(int... nums) { LOGGER.info("Source module {}", VERSION); return Arrays.stream(nums).reduce(0, Integer::sum); } - /** - * Check if all number is not zero. - * New feature. - */ + /** Check if all number is not zero. New feature. */ public boolean ifNonZero(int... nums) { LOGGER.info("Source module {}", VERSION); return Arrays.stream(nums).allMatch(num -> num != 0); diff --git a/strangler/src/main/java/com/iluwatar/strangler/NewArithmetic.java b/strangler/src/main/java/com/iluwatar/strangler/NewArithmetic.java index bd90fc123..75156da20 100644 --- a/strangler/src/main/java/com/iluwatar/strangler/NewArithmetic.java +++ b/strangler/src/main/java/com/iluwatar/strangler/NewArithmetic.java @@ -26,9 +26,7 @@ package com.iluwatar.strangler; import lombok.extern.slf4j.Slf4j; -/** - * System after whole migration. Only depends on new version source ({@link NewSource}). - */ +/** System after whole migration. Only depends on new version source ({@link NewSource}). */ @Slf4j public class NewArithmetic { private static final String VERSION = "2.0"; @@ -41,6 +39,7 @@ public class NewArithmetic { /** * Accumulate sum. + * * @param nums numbers need to add together * @return accumulate sum */ @@ -51,6 +50,7 @@ public class NewArithmetic { /** * Accumulate multiplication. + * * @param nums numbers need to multiply together * @return accumulate multiplication */ @@ -61,6 +61,7 @@ public class NewArithmetic { /** * Check if it has any zero. + * * @param nums numbers need to check * @return if it has any zero, return true, else, return false */ diff --git a/strangler/src/main/java/com/iluwatar/strangler/NewSource.java b/strangler/src/main/java/com/iluwatar/strangler/NewSource.java index 25bef8a3e..78e709408 100644 --- a/strangler/src/main/java/com/iluwatar/strangler/NewSource.java +++ b/strangler/src/main/java/com/iluwatar/strangler/NewSource.java @@ -28,8 +28,8 @@ import java.util.Arrays; import lombok.extern.slf4j.Slf4j; /** - * New source. Completely covers functionalities of old source with new techniques - * and also has some new features. + * New source. Completely covers functionalities of old source with new techniques and also has some + * new features. */ @Slf4j public class NewSource { @@ -41,10 +41,7 @@ public class NewSource { return Arrays.stream(nums).reduce(0, Integer::sum); } - /** - * Implement accumulate multiply with new technique. - * Replace old one in {@link OldSource} - */ + /** Implement accumulate multiply with new technique. Replace old one in {@link OldSource} */ public int accumulateMul(int... nums) { LOGGER.info(SOURCE_MODULE, VERSION); return Arrays.stream(nums).reduce(1, (a, b) -> a * b); diff --git a/strangler/src/main/java/com/iluwatar/strangler/OldArithmetic.java b/strangler/src/main/java/com/iluwatar/strangler/OldArithmetic.java index 5b5162b32..299f61d30 100644 --- a/strangler/src/main/java/com/iluwatar/strangler/OldArithmetic.java +++ b/strangler/src/main/java/com/iluwatar/strangler/OldArithmetic.java @@ -26,9 +26,7 @@ package com.iluwatar.strangler; import lombok.extern.slf4j.Slf4j; -/** - * Old version system depends on old version source ({@link OldSource}). - */ +/** Old version system depends on old version source ({@link OldSource}). */ @Slf4j public class OldArithmetic { private static final String VERSION = "1.0"; @@ -41,6 +39,7 @@ public class OldArithmetic { /** * Accumulate sum. + * * @param nums numbers need to add together * @return accumulate sum */ @@ -51,6 +50,7 @@ public class OldArithmetic { /** * Accumulate multiplication. + * * @param nums numbers need to multiply together * @return accumulate multiplication */ diff --git a/strangler/src/main/java/com/iluwatar/strangler/OldSource.java b/strangler/src/main/java/com/iluwatar/strangler/OldSource.java index 7e833dea9..5be29bffc 100644 --- a/strangler/src/main/java/com/iluwatar/strangler/OldSource.java +++ b/strangler/src/main/java/com/iluwatar/strangler/OldSource.java @@ -26,16 +26,12 @@ package com.iluwatar.strangler; import lombok.extern.slf4j.Slf4j; -/** - * Old source with techniques out of date. - */ +/** Old source with techniques out of date. */ @Slf4j public class OldSource { private static final String VERSION = "1.0"; - /** - * Implement accumulate sum with old technique. - */ + /** Implement accumulate sum with old technique. */ public int accumulateSum(int... nums) { LOGGER.info("Source module {}", VERSION); var sum = 0; @@ -45,9 +41,7 @@ public class OldSource { return sum; } - /** - * Implement accumulate multiply with old technique. - */ + /** Implement accumulate multiply with old technique. */ public int accumulateMul(int... nums) { LOGGER.info("Source module {}", VERSION); var sum = 1; diff --git a/strangler/src/test/java/com/iluwatar/strangler/AppTest.java b/strangler/src/test/java/com/iluwatar/strangler/AppTest.java index 2e5c20150..777af1766 100644 --- a/strangler/src/test/java/com/iluwatar/strangler/AppTest.java +++ b/strangler/src/test/java/com/iluwatar/strangler/AppTest.java @@ -24,17 +24,15 @@ */ package com.iluwatar.strangler; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -/** - * Application test - */ +import org.junit.jupiter.api.Test; + +/** Application test */ class AppTest { @Test void shouldExecuteWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/strangler/src/test/java/com/iluwatar/strangler/HalfArithmeticTest.java b/strangler/src/test/java/com/iluwatar/strangler/HalfArithmeticTest.java index 94aee3743..c8f92e18a 100644 --- a/strangler/src/test/java/com/iluwatar/strangler/HalfArithmeticTest.java +++ b/strangler/src/test/java/com/iluwatar/strangler/HalfArithmeticTest.java @@ -29,11 +29,10 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; -/** - * Test methods in HalfArithmetic - */ +/** Test methods in HalfArithmetic */ class HalfArithmeticTest { - private static final HalfArithmetic arithmetic = new HalfArithmetic(new HalfSource(), new OldSource()); + private static final HalfArithmetic arithmetic = + new HalfArithmetic(new HalfSource(), new OldSource()); @Test void testSum() { @@ -49,4 +48,4 @@ class HalfArithmeticTest { void testIfHasZero() { assertTrue(arithmetic.ifHasZero(-1, 0, 1)); } -} \ No newline at end of file +} diff --git a/strangler/src/test/java/com/iluwatar/strangler/HalfSourceTest.java b/strangler/src/test/java/com/iluwatar/strangler/HalfSourceTest.java index 4b6926a0c..09ae98c92 100644 --- a/strangler/src/test/java/com/iluwatar/strangler/HalfSourceTest.java +++ b/strangler/src/test/java/com/iluwatar/strangler/HalfSourceTest.java @@ -29,9 +29,7 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import org.junit.jupiter.api.Test; -/** - * Test methods in HalfSource - */ +/** Test methods in HalfSource */ class HalfSourceTest { private static final HalfSource source = new HalfSource(); diff --git a/strangler/src/test/java/com/iluwatar/strangler/NewArithmeticTest.java b/strangler/src/test/java/com/iluwatar/strangler/NewArithmeticTest.java index 51dda81c6..5c6958f3d 100644 --- a/strangler/src/test/java/com/iluwatar/strangler/NewArithmeticTest.java +++ b/strangler/src/test/java/com/iluwatar/strangler/NewArithmeticTest.java @@ -29,9 +29,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; -/** - * Test methods in NewArithmetic - */ +/** Test methods in NewArithmetic */ class NewArithmeticTest { private static final NewArithmetic arithmetic = new NewArithmetic(new NewSource()); @@ -49,4 +47,4 @@ class NewArithmeticTest { void testIfHasZero() { assertTrue(arithmetic.ifHasZero(-1, 0, 1)); } -} \ No newline at end of file +} diff --git a/strangler/src/test/java/com/iluwatar/strangler/NewSourceTest.java b/strangler/src/test/java/com/iluwatar/strangler/NewSourceTest.java index 2ceb745ee..658aa5397 100644 --- a/strangler/src/test/java/com/iluwatar/strangler/NewSourceTest.java +++ b/strangler/src/test/java/com/iluwatar/strangler/NewSourceTest.java @@ -29,9 +29,7 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import org.junit.jupiter.api.Test; -/** - * Test methods in NewSource - */ +/** Test methods in NewSource */ class NewSourceTest { private static final NewSource source = new NewSource(); diff --git a/strangler/src/test/java/com/iluwatar/strangler/OldArithmeticTest.java b/strangler/src/test/java/com/iluwatar/strangler/OldArithmeticTest.java index 4c449cbdf..4ce9d2ddd 100644 --- a/strangler/src/test/java/com/iluwatar/strangler/OldArithmeticTest.java +++ b/strangler/src/test/java/com/iluwatar/strangler/OldArithmeticTest.java @@ -28,9 +28,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; -/** - * Test methods in OldArithmetic - */ +/** Test methods in OldArithmetic */ class OldArithmeticTest { private static final OldArithmetic arithmetic = new OldArithmetic(new OldSource()); @@ -43,4 +41,4 @@ class OldArithmeticTest { void testMul() { assertEquals(0, arithmetic.mul(-1, 0, 1)); } -} \ No newline at end of file +} diff --git a/strangler/src/test/java/com/iluwatar/strangler/OldSourceTest.java b/strangler/src/test/java/com/iluwatar/strangler/OldSourceTest.java index cb1d1b331..b90d08af3 100644 --- a/strangler/src/test/java/com/iluwatar/strangler/OldSourceTest.java +++ b/strangler/src/test/java/com/iluwatar/strangler/OldSourceTest.java @@ -28,9 +28,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; -/** - * Test methods in OldSource - */ +/** Test methods in OldSource */ class OldSourceTest { private static final OldSource source = new OldSource(); diff --git a/strategy/pom.xml b/strategy/pom.xml index 9b7b1e9c8..3c84050bf 100644 --- a/strategy/pom.xml +++ b/strategy/pom.xml @@ -34,6 +34,14 @@ strategy + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/strategy/src/main/java/com/iluwatar/strategy/App.java b/strategy/src/main/java/com/iluwatar/strategy/App.java index 28cb88dfb..6c24d0e46 100644 --- a/strategy/src/main/java/com/iluwatar/strategy/App.java +++ b/strategy/src/main/java/com/iluwatar/strategy/App.java @@ -27,17 +27,15 @@ package com.iluwatar.strategy; import lombok.extern.slf4j.Slf4j; /** + * The Strategy pattern (also known as the policy pattern) is a software design pattern that enables + * an algorithm's behavior to be selected at runtime. * - *

The Strategy pattern (also known as the policy pattern) is a software design pattern that - * enables an algorithm's behavior to be selected at runtime.

- * - *

Before Java 8 the Strategies needed to be separate classes forcing the developer - * to write lots of boilerplate code. With modern Java, it is easy to pass behavior - * with method references and lambdas making the code shorter and more readable.

+ *

Before Java 8 the Strategies needed to be separate classes forcing the developer to write lots + * of boilerplate code. With modern Java, it is easy to pass behavior with method references and + * lambdas making the code shorter and more readable. * *

In this example ({@link DragonSlayingStrategy}) encapsulates an algorithm. The containing - * object ({@link DragonSlayer}) can alter its behavior by changing its strategy.

- * + * object ({@link DragonSlayer}) can alter its behavior by changing its strategy. */ @Slf4j public class App { @@ -65,16 +63,20 @@ public class App { // Java 8 functional implementation Strategy pattern LOGGER.info(GREEN_DRAGON_SPOTTED); - dragonSlayer = new DragonSlayer( - () -> LOGGER.info("With your Excalibur you sever the dragon's head!")); + dragonSlayer = + new DragonSlayer(() -> LOGGER.info("With your Excalibur you sever the dragon's head!")); dragonSlayer.goToBattle(); LOGGER.info(RED_DRAGON_EMERGES); - dragonSlayer.changeStrategy(() -> LOGGER.info( - "You shoot the dragon with the magical crossbow and it falls dead on the ground!")); + dragonSlayer.changeStrategy( + () -> + LOGGER.info( + "You shoot the dragon with the magical crossbow and it falls dead on the ground!")); dragonSlayer.goToBattle(); LOGGER.info(BLACK_DRAGON_LANDS); - dragonSlayer.changeStrategy(() -> LOGGER.info( - "You cast the spell of disintegration and the dragon vaporizes in a pile of dust!")); + dragonSlayer.changeStrategy( + () -> + LOGGER.info( + "You cast the spell of disintegration and the dragon vaporizes in a pile of dust!")); dragonSlayer.goToBattle(); // Java 8 lambda implementation with enum Strategy pattern @@ -88,4 +90,4 @@ public class App { dragonSlayer.changeStrategy(LambdaStrategy.Strategy.SPELL_STRATEGY); dragonSlayer.goToBattle(); } -} \ No newline at end of file +} diff --git a/strategy/src/main/java/com/iluwatar/strategy/DragonSlayer.java b/strategy/src/main/java/com/iluwatar/strategy/DragonSlayer.java index 43416a4f6..1e623e665 100644 --- a/strategy/src/main/java/com/iluwatar/strategy/DragonSlayer.java +++ b/strategy/src/main/java/com/iluwatar/strategy/DragonSlayer.java @@ -1,45 +1,43 @@ -/* - * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). - * - * The MIT License - * Copyright © 2014-2022 Ilkka Seppälä - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package com.iluwatar.strategy; - -/** - * DragonSlayer uses different strategies to slay the dragon. - */ -public class DragonSlayer { - - private DragonSlayingStrategy strategy; - - public DragonSlayer(DragonSlayingStrategy strategy) { - this.strategy = strategy; - } - - public void changeStrategy(DragonSlayingStrategy strategy) { - this.strategy = strategy; - } - - public void goToBattle() { - strategy.execute(); - } -} +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.strategy; + +/** DragonSlayer uses different strategies to slay the dragon. */ +public class DragonSlayer { + + private DragonSlayingStrategy strategy; + + public DragonSlayer(DragonSlayingStrategy strategy) { + this.strategy = strategy; + } + + public void changeStrategy(DragonSlayingStrategy strategy) { + this.strategy = strategy; + } + + public void goToBattle() { + strategy.execute(); + } +} diff --git a/strategy/src/main/java/com/iluwatar/strategy/DragonSlayingStrategy.java b/strategy/src/main/java/com/iluwatar/strategy/DragonSlayingStrategy.java index ccba43736..c05b1965a 100644 --- a/strategy/src/main/java/com/iluwatar/strategy/DragonSlayingStrategy.java +++ b/strategy/src/main/java/com/iluwatar/strategy/DragonSlayingStrategy.java @@ -1,35 +1,32 @@ -/* - * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). - * - * The MIT License - * Copyright © 2014-2022 Ilkka Seppälä - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package com.iluwatar.strategy; - -/** - * Strategy interface. - */ -@FunctionalInterface -public interface DragonSlayingStrategy { - - void execute(); - -} +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.strategy; + +/** Strategy interface. */ +@FunctionalInterface +public interface DragonSlayingStrategy { + + void execute(); +} diff --git a/strategy/src/main/java/com/iluwatar/strategy/LambdaStrategy.java b/strategy/src/main/java/com/iluwatar/strategy/LambdaStrategy.java index da9b76a84..27137bcc1 100644 --- a/strategy/src/main/java/com/iluwatar/strategy/LambdaStrategy.java +++ b/strategy/src/main/java/com/iluwatar/strategy/LambdaStrategy.java @@ -26,22 +26,21 @@ package com.iluwatar.strategy; import lombok.extern.slf4j.Slf4j; -/** - * Lambda implementation for enum strategy pattern. - */ +/** Lambda implementation for enum strategy pattern. */ @Slf4j public class LambdaStrategy { - /** - * Enum to demonstrate strategy pattern. - */ + /** Enum to demonstrate strategy pattern. */ public enum Strategy implements DragonSlayingStrategy { - MELEE_STRATEGY(() -> LOGGER.info( - "With your Excalibur you sever the dragon's head!")), - PROJECTILE_STRATEGY(() -> LOGGER.info( - "You shoot the dragon with the magical crossbow and it falls dead on the ground!")), - SPELL_STRATEGY(() -> LOGGER.info( - "You cast the spell of disintegration and the dragon vaporizes in a pile of dust!")); + MELEE_STRATEGY(() -> LOGGER.info("With your Excalibur you sever the dragon's head!")), + PROJECTILE_STRATEGY( + () -> + LOGGER.info( + "You shoot the dragon with the magical crossbow and it falls dead on the ground!")), + SPELL_STRATEGY( + () -> + LOGGER.info( + "You cast the spell of disintegration and the dragon vaporizes in a pile of dust!")); private final DragonSlayingStrategy dragonSlayingStrategy; @@ -54,4 +53,4 @@ public class LambdaStrategy { dragonSlayingStrategy.execute(); } } -} \ No newline at end of file +} diff --git a/strategy/src/main/java/com/iluwatar/strategy/MeleeStrategy.java b/strategy/src/main/java/com/iluwatar/strategy/MeleeStrategy.java index 23769944c..6bf4603f4 100644 --- a/strategy/src/main/java/com/iluwatar/strategy/MeleeStrategy.java +++ b/strategy/src/main/java/com/iluwatar/strategy/MeleeStrategy.java @@ -1,39 +1,37 @@ -/* - * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). - * - * The MIT License - * Copyright © 2014-2022 Ilkka Seppälä - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package com.iluwatar.strategy; - -import lombok.extern.slf4j.Slf4j; - -/** - * Melee strategy. - */ -@Slf4j -public class MeleeStrategy implements DragonSlayingStrategy { - - @Override - public void execute() { - LOGGER.info("With your Excalibur you sever the dragon's head!"); - } -} +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.strategy; + +import lombok.extern.slf4j.Slf4j; + +/** Melee strategy. */ +@Slf4j +public class MeleeStrategy implements DragonSlayingStrategy { + + @Override + public void execute() { + LOGGER.info("With your Excalibur you sever the dragon's head!"); + } +} diff --git a/strategy/src/main/java/com/iluwatar/strategy/ProjectileStrategy.java b/strategy/src/main/java/com/iluwatar/strategy/ProjectileStrategy.java index 93af41fa6..38f51bd8a 100644 --- a/strategy/src/main/java/com/iluwatar/strategy/ProjectileStrategy.java +++ b/strategy/src/main/java/com/iluwatar/strategy/ProjectileStrategy.java @@ -1,39 +1,37 @@ -/* - * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). - * - * The MIT License - * Copyright © 2014-2022 Ilkka Seppälä - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package com.iluwatar.strategy; - -import lombok.extern.slf4j.Slf4j; - -/** - * Projectile strategy. - */ -@Slf4j -public class ProjectileStrategy implements DragonSlayingStrategy { - - @Override - public void execute() { - LOGGER.info("You shoot the dragon with the magical crossbow and it falls dead on the ground!"); - } -} +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.strategy; + +import lombok.extern.slf4j.Slf4j; + +/** Projectile strategy. */ +@Slf4j +public class ProjectileStrategy implements DragonSlayingStrategy { + + @Override + public void execute() { + LOGGER.info("You shoot the dragon with the magical crossbow and it falls dead on the ground!"); + } +} diff --git a/strategy/src/main/java/com/iluwatar/strategy/SpellStrategy.java b/strategy/src/main/java/com/iluwatar/strategy/SpellStrategy.java index 5b7127bc2..6b284dbd7 100644 --- a/strategy/src/main/java/com/iluwatar/strategy/SpellStrategy.java +++ b/strategy/src/main/java/com/iluwatar/strategy/SpellStrategy.java @@ -1,40 +1,37 @@ -/* - * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). - * - * The MIT License - * Copyright © 2014-2022 Ilkka Seppälä - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package com.iluwatar.strategy; - -import lombok.extern.slf4j.Slf4j; - -/** - * Spell strategy. - */ -@Slf4j -public class SpellStrategy implements DragonSlayingStrategy { - - @Override - public void execute() { - LOGGER.info("You cast the spell of disintegration and the dragon vaporizes in a pile of dust!"); - } - -} +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.strategy; + +import lombok.extern.slf4j.Slf4j; + +/** Spell strategy. */ +@Slf4j +public class SpellStrategy implements DragonSlayingStrategy { + + @Override + public void execute() { + LOGGER.info("You cast the spell of disintegration and the dragon vaporizes in a pile of dust!"); + } +} diff --git a/strategy/src/test/java/com/iluwatar/strategy/AppTest.java b/strategy/src/test/java/com/iluwatar/strategy/AppTest.java index 5e0ec437a..e26c469a5 100644 --- a/strategy/src/test/java/com/iluwatar/strategy/AppTest.java +++ b/strategy/src/test/java/com/iluwatar/strategy/AppTest.java @@ -24,17 +24,15 @@ */ package com.iluwatar.strategy; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -/** - * Application test. - */ +import org.junit.jupiter.api.Test; + +/** Application test. */ class AppTest { @Test void shouldExecuteWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/strategy/src/test/java/com/iluwatar/strategy/DragonSlayerTest.java b/strategy/src/test/java/com/iluwatar/strategy/DragonSlayerTest.java index d0df5f468..49b636ecf 100644 --- a/strategy/src/test/java/com/iluwatar/strategy/DragonSlayerTest.java +++ b/strategy/src/test/java/com/iluwatar/strategy/DragonSlayerTest.java @@ -30,15 +30,10 @@ import static org.mockito.Mockito.verifyNoMoreInteractions; import org.junit.jupiter.api.Test; -/** - * DragonSlayerTest - * - */ +/** DragonSlayerTest */ class DragonSlayerTest { - /** - * Verify if the dragon slayer uses the strategy during battle. - */ + /** Verify if the dragon slayer uses the strategy during battle. */ @Test void testGoToBattle() { final var strategy = mock(DragonSlayingStrategy.class); @@ -49,9 +44,7 @@ class DragonSlayerTest { verifyNoMoreInteractions(strategy); } - /** - * Verify if the dragon slayer uses the new strategy during battle after a change of strategy. - */ + /** Verify if the dragon slayer uses the new strategy during battle after a change of strategy. */ @Test void testChangeStrategy() { final var initialStrategy = mock(DragonSlayingStrategy.class); @@ -68,4 +61,4 @@ class DragonSlayerTest { verifyNoMoreInteractions(initialStrategy, newStrategy); } -} \ No newline at end of file +} diff --git a/strategy/src/test/java/com/iluwatar/strategy/DragonSlayingStrategyTest.java b/strategy/src/test/java/com/iluwatar/strategy/DragonSlayingStrategyTest.java index 75ed97366..6162c641c 100644 --- a/strategy/src/test/java/com/iluwatar/strategy/DragonSlayingStrategyTest.java +++ b/strategy/src/test/java/com/iluwatar/strategy/DragonSlayingStrategyTest.java @@ -38,10 +38,7 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import org.slf4j.LoggerFactory; -/** - * DragonSlayingStrategyTest - * - */ +/** DragonSlayingStrategyTest */ class DragonSlayingStrategyTest { /** @@ -51,19 +48,15 @@ class DragonSlayingStrategyTest { */ static Collection dataProvider() { return List.of( - new Object[]{ - new MeleeStrategy(), - "With your Excalibur you sever the dragon's head!" + new Object[] {new MeleeStrategy(), "With your Excalibur you sever the dragon's head!"}, + new Object[] { + new ProjectileStrategy(), + "You shoot the dragon with the magical crossbow and it falls dead on the ground!" }, - new Object[]{ - new ProjectileStrategy(), - "You shoot the dragon with the magical crossbow and it falls dead on the ground!" - }, - new Object[]{ - new SpellStrategy(), - "You cast the spell of disintegration and the dragon vaporizes in a pile of dust!" - } - ); + new Object[] { + new SpellStrategy(), + "You cast the spell of disintegration and the dragon vaporizes in a pile of dust!" + }); } private InMemoryAppender appender; @@ -78,10 +71,7 @@ class DragonSlayingStrategyTest { appender.stop(); } - - /** - * Test if executing the strategy gives the correct response. - */ + /** Test if executing the strategy gives the correct response. */ @ParameterizedTest @MethodSource("dataProvider") void testExecute(DragonSlayingStrategy strategy, String expectedResult) { diff --git a/subclass-sandbox/src/main/java/com/iluwatar/subclasssandbox/App.java b/subclass-sandbox/src/main/java/com/iluwatar/subclasssandbox/App.java index fad01e36c..7db986965 100644 --- a/subclass-sandbox/src/main/java/com/iluwatar/subclasssandbox/App.java +++ b/subclass-sandbox/src/main/java/com/iluwatar/subclasssandbox/App.java @@ -27,17 +27,18 @@ package com.iluwatar.subclasssandbox; import lombok.extern.slf4j.Slf4j; /** - * The subclass sandbox pattern describes a basic idea, while not having a lot - * of detailed mechanics. You will need the pattern when you have several similar - * subclasses. If you have to make a tiny change, then change the base class, - * while all subclasses shouldn't have to be touched. So the base class has to be - * able to provide all the operations a derived class needs to perform. + * The subclass sandbox pattern describes a basic idea, while not having a lot of detailed + * mechanics. You will need the pattern when you have several similar subclasses. If you have to + * make a tiny change, then change the base class, while all subclasses shouldn't have to be + * touched. So the base class has to be able to provide all the operations a derived class needs to + * perform. */ @Slf4j public class App { /** * Entry point of the main program. + * * @param args Program runtime arguments. */ public static void main(String[] args) { @@ -48,5 +49,4 @@ public class App { var groundDive = new GroundDive(); groundDive.activate(); } - } diff --git a/subclass-sandbox/src/main/java/com/iluwatar/subclasssandbox/GroundDive.java b/subclass-sandbox/src/main/java/com/iluwatar/subclasssandbox/GroundDive.java index 6cd9d324a..606dd3206 100644 --- a/subclass-sandbox/src/main/java/com/iluwatar/subclasssandbox/GroundDive.java +++ b/subclass-sandbox/src/main/java/com/iluwatar/subclasssandbox/GroundDive.java @@ -26,9 +26,7 @@ package com.iluwatar.subclasssandbox; import org.slf4j.LoggerFactory; -/** - * GroundDive superpower. - */ +/** GroundDive superpower. */ public class GroundDive extends Superpower { public GroundDive() { diff --git a/subclass-sandbox/src/main/java/com/iluwatar/subclasssandbox/SkyLaunch.java b/subclass-sandbox/src/main/java/com/iluwatar/subclasssandbox/SkyLaunch.java index 9bab6ef9f..611dacb2f 100644 --- a/subclass-sandbox/src/main/java/com/iluwatar/subclasssandbox/SkyLaunch.java +++ b/subclass-sandbox/src/main/java/com/iluwatar/subclasssandbox/SkyLaunch.java @@ -26,9 +26,7 @@ package com.iluwatar.subclasssandbox; import org.slf4j.LoggerFactory; -/** - * SkyLaunch superpower. - */ +/** SkyLaunch superpower. */ public class SkyLaunch extends Superpower { public SkyLaunch() { diff --git a/subclass-sandbox/src/main/java/com/iluwatar/subclasssandbox/Superpower.java b/subclass-sandbox/src/main/java/com/iluwatar/subclasssandbox/Superpower.java index 3c4f42aba..fefcce736 100644 --- a/subclass-sandbox/src/main/java/com/iluwatar/subclasssandbox/Superpower.java +++ b/subclass-sandbox/src/main/java/com/iluwatar/subclasssandbox/Superpower.java @@ -27,21 +27,22 @@ package com.iluwatar.subclasssandbox; import org.slf4j.Logger; /** - * Superpower abstract class. In this class the basic operations of all types of - * superpowers are provided as protected methods. + * Superpower abstract class. In this class the basic operations of all types of superpowers are + * provided as protected methods. */ public abstract class Superpower { protected Logger logger; /** - * Subclass of superpower should implement this sandbox method by calling the - * methods provided in this super class. + * Subclass of superpower should implement this sandbox method by calling the methods provided in + * this super class. */ protected abstract void activate(); /** * Move to (x, y, z). + * * @param x X coordinate. * @param y Y coordinate. * @param z Z coordinate. @@ -52,6 +53,7 @@ public abstract class Superpower { /** * Play sound effect for the superpower. + * * @param soundName Sound name. * @param volume Value of volume. */ @@ -61,6 +63,7 @@ public abstract class Superpower { /** * Spawn particles for the superpower. + * * @param particleType Particle type. * @param count Count of particles to be spawned. */ diff --git a/subclass-sandbox/src/test/java/com/iluwatar/subclasssandbox/AppTest.java b/subclass-sandbox/src/test/java/com/iluwatar/subclasssandbox/AppTest.java index e578f32ed..18eb36065 100644 --- a/subclass-sandbox/src/test/java/com/iluwatar/subclasssandbox/AppTest.java +++ b/subclass-sandbox/src/test/java/com/iluwatar/subclasssandbox/AppTest.java @@ -28,13 +28,11 @@ import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import org.junit.jupiter.api.Test; -/** - * App unit tests. - */ +/** App unit tests. */ class AppTest { @Test void shouldExecuteWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/subclass-sandbox/src/test/java/com/iluwatar/subclasssandbox/GroundDiveTest.java b/subclass-sandbox/src/test/java/com/iluwatar/subclasssandbox/GroundDiveTest.java index cda2ee8c4..45cb4ff50 100644 --- a/subclass-sandbox/src/test/java/com/iluwatar/subclasssandbox/GroundDiveTest.java +++ b/subclass-sandbox/src/test/java/com/iluwatar/subclasssandbox/GroundDiveTest.java @@ -30,9 +30,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import com.github.stefanbirkner.systemlambda.Statement; import org.junit.jupiter.api.Test; -/** - * GroundDive unit tests. - */ +/** GroundDive unit tests. */ class GroundDiveTest { @Test @@ -55,8 +53,7 @@ class GroundDiveTest { @Test void testSpawnParticles() throws Exception { var groundDive = new GroundDive(); - final var outputLog = getLogContent( - () -> groundDive.spawnParticles("PARTICLE_TYPE", 100)); + final var outputLog = getLogContent(() -> groundDive.spawnParticles("PARTICLE_TYPE", 100)); final var expectedLog = "Spawn 100 particle with type PARTICLE_TYPE"; assertEquals(outputLog, expectedLog); } @@ -64,8 +61,7 @@ class GroundDiveTest { @Test void testActivate() throws Exception { var groundDive = new GroundDive(); - var logs = tapSystemOutNormalized(groundDive::activate) - .split("\n"); + var logs = tapSystemOutNormalized(groundDive::activate).split("\n"); final var expectedSize = 3; final var log1 = logs[0].split("--")[1].trim(); final var expectedLog1 = "Move to ( 0.0, 0.0, -20.0 )"; @@ -87,5 +83,4 @@ class GroundDiveTest { private String getLogContent(String log) { return log.split("--")[1].trim(); } - } diff --git a/subclass-sandbox/src/test/java/com/iluwatar/subclasssandbox/SkyLaunchTest.java b/subclass-sandbox/src/test/java/com/iluwatar/subclasssandbox/SkyLaunchTest.java index 5af6cf68e..3af507fb0 100644 --- a/subclass-sandbox/src/test/java/com/iluwatar/subclasssandbox/SkyLaunchTest.java +++ b/subclass-sandbox/src/test/java/com/iluwatar/subclasssandbox/SkyLaunchTest.java @@ -30,9 +30,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import com.github.stefanbirkner.systemlambda.Statement; import org.junit.jupiter.api.Test; -/** - * SkyLaunch unit tests. - */ +/** SkyLaunch unit tests. */ class SkyLaunchTest { @Test @@ -54,8 +52,7 @@ class SkyLaunchTest { @Test void testSpawnParticles() throws Exception { var skyLaunch = new SkyLaunch(); - var outputLog = getLogContent( - () -> skyLaunch.spawnParticles("PARTICLE_TYPE", 100)); + var outputLog = getLogContent(() -> skyLaunch.spawnParticles("PARTICLE_TYPE", 100)); var expectedLog = "Spawn 100 particle with type PARTICLE_TYPE"; assertEquals(outputLog, expectedLog); } @@ -63,8 +60,7 @@ class SkyLaunchTest { @Test void testActivate() throws Exception { var skyLaunch = new SkyLaunch(); - var logs = tapSystemOutNormalized(skyLaunch::activate) - .split("\n"); + var logs = tapSystemOutNormalized(skyLaunch::activate).split("\n"); final var expectedSize = 3; final var log1 = getLogContent(logs[0]); final var expectedLog1 = "Move to ( 0.0, 0.0, 20.0 )"; diff --git a/table-inheritance/src/main/java/com/iluwatar/table/inheritance/App.java b/table-inheritance/src/main/java/com/iluwatar/table/inheritance/App.java index cfcce1860..da097ab9e 100644 --- a/table-inheritance/src/main/java/com/iluwatar/table/inheritance/App.java +++ b/table-inheritance/src/main/java/com/iluwatar/table/inheritance/App.java @@ -30,39 +30,36 @@ import java.util.logging.Logger; * The main entry point of the application demonstrating the use of vehicles. * *

The Table Inheritance pattern models a class hierarchy in a relational database by creating - * separate tables for each class in the hierarchy. These tables share a common primary key, which in - * subclass tables also serves as a foreign key referencing the primary key of the base class table. - * This linkage maintains relationships and effectively represents the inheritance structure. This - * pattern enables the organization of complex data models, particularly when subclasses have unique - * properties that must be stored in distinct tables. + * separate tables for each class in the hierarchy. These tables share a common primary key, which + * in subclass tables also serves as a foreign key referencing the primary key of the base class + * table. This linkage maintains relationships and effectively represents the inheritance structure. + * This pattern enables the organization of complex data models, particularly when subclasses have + * unique properties that must be stored in distinct tables. */ - public class App { /** * Manages the storage and retrieval of Vehicle objects, including Cars and Trucks. * - *

This example demonstrates the **Table Inheritance** pattern, where each vehicle type - * (Car and Truck) is stored in its own separate table. The `VehicleDatabase` simulates - * a simple database that manages these entities, with each subclass (Car and Truck) - * being stored in its respective table. + *

This example demonstrates the **Table Inheritance** pattern, where each vehicle type (Car + * and Truck) is stored in its own separate table. The `VehicleDatabase` simulates a simple + * database that manages these entities, with each subclass (Car and Truck) being stored in its + * respective table. * - *

The `VehicleDatabase` contains the following tables: - * - `vehicleTable`: Stores all vehicle objects, including both `Car` and `Truck` objects. - * - `carTable`: Stores only `Car` objects, with fields specific to cars. - * - `truckTable`: Stores only `Truck` objects, with fields specific to trucks. + *

The `VehicleDatabase` contains the following tables: - `vehicleTable`: Stores all vehicle + * objects, including both `Car` and `Truck` objects. - `carTable`: Stores only `Car` objects, + * with fields specific to cars. - `truckTable`: Stores only `Truck` objects, with fields specific + * to trucks. * - *

The example demonstrates: - * 1. Saving instances of `Car` and `Truck` to their respective tables in the database. - * 2. Retrieving vehicles (both cars and trucks) from the appropriate table based on their ID. - * 3. Printing all vehicles stored in the database. - * 4. Showing how to retrieve specific types of vehicles (`Car` or `Truck`) by their IDs. + *

The example demonstrates: 1. Saving instances of `Car` and `Truck` to their respective + * tables in the database. 2. Retrieving vehicles (both cars and trucks) from the appropriate + * table based on their ID. 3. Printing all vehicles stored in the database. 4. Showing how to + * retrieve specific types of vehicles (`Car` or `Truck`) by their IDs. * - *

In the **Table Inheritance** pattern, each subclass has its own table, making it easier - * to manage specific attributes of each subclass. + *

In the **Table Inheritance** pattern, each subclass has its own table, making it easier to + * manage specific attributes of each subclass. * * @param args command-line arguments */ - public static void main(String[] args) { final Logger logger = Logger.getLogger(App.class.getName()); @@ -84,6 +81,5 @@ public class App { logger.info(String.format("Retrieved Vehicle: %s", vehicle)); logger.info(String.format("Retrieved Car: %s", retrievedCar)); logger.info(String.format("Retrieved Truck: %s", retrievedTruck)); - } } diff --git a/table-inheritance/src/main/java/com/iluwatar/table/inheritance/Car.java b/table-inheritance/src/main/java/com/iluwatar/table/inheritance/Car.java index 991fc1b6a..0adaaa648 100644 --- a/table-inheritance/src/main/java/com/iluwatar/table/inheritance/Car.java +++ b/table-inheritance/src/main/java/com/iluwatar/table/inheritance/Car.java @@ -23,11 +23,10 @@ * THE SOFTWARE. */ package com.iluwatar.table.inheritance; -import lombok.Getter; -/** - * Represents a car with a specific number of doors. - */ +import lombok.Getter; + +/** Represents a car with a specific number of doors. */ @Getter public class Car extends Vehicle { private int numDoors; @@ -35,11 +34,11 @@ public class Car extends Vehicle { /** * Constructs a Car object. * - * @param year the manufacturing year - * @param make the make of the car - * @param model the model of the car + * @param year the manufacturing year + * @param make the make of the car + * @param model the model of the car * @param numDoors the number of doors - * @param id the unique identifier for the car + * @param id the unique identifier for the car */ public Car(int year, String make, String model, int numDoors, int id) { super(year, make, model, id); @@ -64,11 +63,18 @@ public class Car extends Vehicle { @Override public String toString() { return "Car{" - + "id=" + getId() - + ", make='" + getMake() + '\'' - + ", model='" + getModel() + '\'' - + ", year=" + getYear() - + ", numberOfDoors=" + getNumDoors() + + "id=" + + getId() + + ", make='" + + getMake() + + '\'' + + ", model='" + + getModel() + + '\'' + + ", year=" + + getYear() + + ", numberOfDoors=" + + getNumDoors() + '}'; } } diff --git a/table-inheritance/src/main/java/com/iluwatar/table/inheritance/Truck.java b/table-inheritance/src/main/java/com/iluwatar/table/inheritance/Truck.java index bf3eac051..b79c53622 100644 --- a/table-inheritance/src/main/java/com/iluwatar/table/inheritance/Truck.java +++ b/table-inheritance/src/main/java/com/iluwatar/table/inheritance/Truck.java @@ -26,9 +26,7 @@ package com.iluwatar.table.inheritance; import lombok.Getter; -/** - * Represents a truck, a type of vehicle with a specific load capacity. - */ +/** Represents a truck, a type of vehicle with a specific load capacity. */ @Getter public class Truck extends Vehicle { private double loadCapacity; @@ -36,11 +34,11 @@ public class Truck extends Vehicle { /** * Constructs a Truck object with the given parameters. * - * @param year the year of manufacture - * @param make the make of the truck - * @param model the model of the truck + * @param year the year of manufacture + * @param make the make of the truck + * @param model the model of the truck * @param loadCapacity the load capacity of the truck - * @param id the unique ID of the truck + * @param id the unique ID of the truck */ public Truck(int year, String make, String model, double loadCapacity, int id) { super(year, make, model, id); @@ -70,12 +68,18 @@ public class Truck extends Vehicle { @Override public String toString() { return "Truck{" - + "id=" + getId() - + ", make='" + getMake() + '\'' - + ", model='" + getModel() + '\'' - + ", year=" + getYear() - + ", payloadCapacity=" + getLoadCapacity() + + "id=" + + getId() + + ", make='" + + getMake() + + '\'' + + ", model='" + + getModel() + + '\'' + + ", year=" + + getYear() + + ", payloadCapacity=" + + getLoadCapacity() + '}'; } } - diff --git a/table-inheritance/src/main/java/com/iluwatar/table/inheritance/Vehicle.java b/table-inheritance/src/main/java/com/iluwatar/table/inheritance/Vehicle.java index 9fdd82a79..87db4092d 100644 --- a/table-inheritance/src/main/java/com/iluwatar/table/inheritance/Vehicle.java +++ b/table-inheritance/src/main/java/com/iluwatar/table/inheritance/Vehicle.java @@ -27,10 +27,7 @@ package com.iluwatar.table.inheritance; import lombok.Getter; import lombok.Setter; -/** - * Represents a generic vehicle with basic attributes like make, model, year, and ID. - */ - +/** Represents a generic vehicle with basic attributes like make, model, year, and ID. */ @Setter @Getter public class Vehicle { @@ -43,10 +40,10 @@ public class Vehicle { /** * Constructs a Vehicle object with the given parameters. * - * @param year the year of manufacture - * @param make the make of the vehicle + * @param year the year of manufacture + * @param make the make of the vehicle * @param model the model of the vehicle - * @param id the unique ID of the vehicle + * @param id the unique ID of the vehicle */ public Vehicle(int year, String make, String model, int id) { this.make = make; @@ -63,10 +60,16 @@ public class Vehicle { @Override public String toString() { return "Vehicle{" - + "id=" + id - + ", make='" + make + '\'' - + ", model='" + model + '\'' - + ", year=" + year + + "id=" + + id + + ", make='" + + make + + '\'' + + ", model='" + + model + + '\'' + + ", year=" + + year + '}'; } } diff --git a/table-inheritance/src/main/java/com/iluwatar/table/inheritance/VehicleDatabase.java b/table-inheritance/src/main/java/com/iluwatar/table/inheritance/VehicleDatabase.java index 95d7faf06..0f04ab0a9 100644 --- a/table-inheritance/src/main/java/com/iluwatar/table/inheritance/VehicleDatabase.java +++ b/table-inheritance/src/main/java/com/iluwatar/table/inheritance/VehicleDatabase.java @@ -24,15 +24,11 @@ */ package com.iluwatar.table.inheritance; - import java.util.HashMap; import java.util.Map; import java.util.logging.Logger; - -/** - * Manages the storage and retrieval of Vehicle objects, including Cars and Trucks. - */ +/** Manages the storage and retrieval of Vehicle objects, including Cars and Trucks. */ public class VehicleDatabase { final Logger logger = Logger.getLogger(VehicleDatabase.class.getName()); @@ -42,7 +38,8 @@ public class VehicleDatabase { private Map truckTable = new HashMap<>(); /** - * Saves a vehicle to the database. If the vehicle is a Car or Truck, it is added to the respective table. + * Saves a vehicle to the database. If the vehicle is a Car or Truck, it is added to the + * respective table. * * @param vehicle the vehicle to save */ @@ -85,13 +82,10 @@ public class VehicleDatabase { return truckTable.get(id); } - /** - * Prints all vehicles in the database. - */ + /** Prints all vehicles in the database. */ public void printAllVehicles() { for (Vehicle vehicle : vehicleTable.values()) { logger.info(vehicle.toString()); } } } - diff --git a/table-inheritance/src/test/java/AppTest.java b/table-inheritance/src/test/java/AppTest.java index 6fe3c1856..1d8e27142 100644 --- a/table-inheritance/src/test/java/AppTest.java +++ b/table-inheritance/src/test/java/AppTest.java @@ -32,10 +32,7 @@ import java.util.logging.Handler; import java.util.logging.Logger; import org.junit.jupiter.api.Test; -/** - * Tests if the main method runs without throwing exceptions and prints expected output. - */ - +/** Tests if the main method runs without throwing exceptions and prints expected output. */ class AppTest { @Test @@ -48,27 +45,24 @@ class AppTest { Logger logger = Logger.getLogger(App.class.getName()); - Handler handler = new ConsoleHandler() { - @Override - public void publish(java.util.logging.LogRecord recordObj) { - printStream.println(getFormatter().format(recordObj)); - } - }; + Handler handler = + new ConsoleHandler() { + @Override + public void publish(java.util.logging.LogRecord recordObj) { + printStream.println(getFormatter().format(recordObj)); + } + }; handler.setLevel(java.util.logging.Level.ALL); logger.addHandler(handler); - App.main(new String[]{}); + App.main(new String[] {}); String output = outContent.toString(); assertTrue(output.contains("Retrieved Vehicle:")); - assertTrue(output.contains("Toyota")); // Car make - assertTrue(output.contains("Ford")); // Truck make + assertTrue(output.contains("Toyota")); // Car make + assertTrue(output.contains("Ford")); // Truck make assertTrue(output.contains("Retrieved Car:")); assertTrue(output.contains("Retrieved Truck:")); } } - - - - diff --git a/table-inheritance/src/test/java/VehicleDatabaseTest.java b/table-inheritance/src/test/java/VehicleDatabaseTest.java index 7d0e508f4..71461f990 100644 --- a/table-inheritance/src/test/java/VehicleDatabaseTest.java +++ b/table-inheritance/src/test/java/VehicleDatabaseTest.java @@ -34,24 +34,20 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; /** - * Unit tests for the {@link VehicleDatabase} class. - * Tests saving, retrieving, and printing vehicles of different types. + * Unit tests for the {@link VehicleDatabase} class. Tests saving, retrieving, and printing vehicles + * of different types. */ class VehicleDatabaseTest { private VehicleDatabase vehicleDatabase; - /** - * Sets up a new instance of {@link VehicleDatabase} before each test. - */ + /** Sets up a new instance of {@link VehicleDatabase} before each test. */ @BeforeEach public void setUp() { vehicleDatabase = new VehicleDatabase(); } - /** - * Tests saving a {@link Car} to the database and retrieving it. - */ + /** Tests saving a {@link Car} to the database and retrieving it. */ @Test void testSaveAndRetrieveCar() { Car car = new Car(2020, "Toyota", "Corolla", 4, 1); @@ -69,9 +65,7 @@ class VehicleDatabaseTest { assertEquals(car.getNumDoors(), retrievedCar.getNumDoors()); } - /** - * Tests saving a {@link Truck} to the database and retrieving it. - */ + /** Tests saving a {@link Truck} to the database and retrieving it. */ @Test void testSaveAndRetrieveTruck() { Truck truck = new Truck(2018, "Ford", "F-150", 60, 2); @@ -89,9 +83,7 @@ class VehicleDatabaseTest { assertEquals(truck.getLoadCapacity(), retrievedTruck.getLoadCapacity()); } - /** - * Tests saving multiple vehicles to the database and printing them. - */ + /** Tests saving multiple vehicles to the database and printing them. */ @Test void testPrintAllVehicles() { Car car = new Car(2020, "Toyota", "Corolla", 4, 1); @@ -108,9 +100,7 @@ class VehicleDatabaseTest { assertNotNull(retrievedTruck); } - /** - * Tests the constructor of {@link Car} with valid values. - */ + /** Tests the constructor of {@link Car} with valid values. */ @Test void testCarConstructor() { Car car = new Car(2020, "Toyota", "Corolla", 4, 1); @@ -121,73 +111,77 @@ class VehicleDatabaseTest { assertEquals(1, car.getId()); // Assuming the ID is auto-generated in the constructor } - /** - * Tests the constructor of {@link Car} with invalid number of doors (negative value). - */ + /** Tests the constructor of {@link Car} with invalid number of doors (negative value). */ @Test void testCarConstructorWithInvalidNumDoors() { - IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> { - new Car(2020, "Toyota", "Corolla", -4, 1); - }); + IllegalArgumentException exception = + assertThrows( + IllegalArgumentException.class, + () -> { + new Car(2020, "Toyota", "Corolla", -4, 1); + }); assertEquals("Number of doors must be positive.", exception.getMessage()); } - /** - * Tests the constructor of {@link Car} with zero doors. - */ + /** Tests the constructor of {@link Car} with zero doors. */ @Test void testCarConstructorWithZeroDoors() { - IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> { - new Car(2020, "Toyota", "Corolla", 0, 1); - }); + IllegalArgumentException exception = + assertThrows( + IllegalArgumentException.class, + () -> { + new Car(2020, "Toyota", "Corolla", 0, 1); + }); assertEquals("Number of doors must be positive.", exception.getMessage()); } - /** - * Tests the constructor of {@link Truck} with invalid load capacity (negative value). - */ + /** Tests the constructor of {@link Truck} with invalid load capacity (negative value). */ @Test void testTruckConstructorWithInvalidLoadCapacity() { - IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> { - new Truck(2018, "Ford", "F-150", -60, 2); - }); + IllegalArgumentException exception = + assertThrows( + IllegalArgumentException.class, + () -> { + new Truck(2018, "Ford", "F-150", -60, 2); + }); assertEquals("Load capacity must be positive.", exception.getMessage()); } - /** - * Tests the constructor of {@link Truck} with zero load capacity. - */ + /** Tests the constructor of {@link Truck} with zero load capacity. */ @Test void testTruckConstructorWithZeroLoadCapacity() { - IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> { - new Truck(2018, "Ford", "F-150", 0, 2); - }); + IllegalArgumentException exception = + assertThrows( + IllegalArgumentException.class, + () -> { + new Truck(2018, "Ford", "F-150", 0, 2); + }); assertEquals("Load capacity must be positive.", exception.getMessage()); } - /** - * Tests setting invalid number of doors in {@link Car} using setter (negative value). - */ + /** Tests setting invalid number of doors in {@link Car} using setter (negative value). */ @Test void testSetInvalidNumDoors() { Car car = new Car(2020, "Toyota", "Corolla", 4, 1); - IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> { - car.setNumDoors(-2); - }); + IllegalArgumentException exception = + assertThrows( + IllegalArgumentException.class, + () -> { + car.setNumDoors(-2); + }); assertEquals("Number of doors must be positive.", exception.getMessage()); } - /** - * Tests setting invalid load capacity in {@link Truck} using setter (negative value). - */ + /** Tests setting invalid load capacity in {@link Truck} using setter (negative value). */ @Test void testSetInvalidLoadCapacity() { Truck truck = new Truck(2018, "Ford", "F-150", 60, 2); - IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> { - truck.setLoadCapacity(-10); - }); + IllegalArgumentException exception = + assertThrows( + IllegalArgumentException.class, + () -> { + truck.setLoadCapacity(-10); + }); assertEquals("Load capacity must be positive.", exception.getMessage()); } } - - diff --git a/table-module/pom.xml b/table-module/pom.xml index f931a8701..9e06a4d8c 100644 --- a/table-module/pom.xml +++ b/table-module/pom.xml @@ -34,6 +34,14 @@ 4.0.0 table-module + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + com.h2database h2 diff --git a/table-module/src/main/java/com/iluwatar/tablemodule/App.java b/table-module/src/main/java/com/iluwatar/tablemodule/App.java index 1c528df8a..4d222e852 100644 --- a/table-module/src/main/java/com/iluwatar/tablemodule/App.java +++ b/table-module/src/main/java/com/iluwatar/tablemodule/App.java @@ -29,30 +29,22 @@ import javax.sql.DataSource; import lombok.extern.slf4j.Slf4j; import org.h2.jdbcx.JdbcDataSource; - /** - * Table Module pattern is a domain logic pattern. - * In Table Module a single class encapsulates all the domain logic for all - * records stored in a table or view. It's important to note that there is no - * translation of data between objects and rows, as it happens in Domain Model, - * hence implementation is relatively simple when compared to the Domain - * Model pattern. + * Table Module pattern is a domain logic pattern. In Table Module a single class encapsulates all + * the domain logic for all records stored in a table or view. It's important to note that there is + * no translation of data between objects and rows, as it happens in Domain Model, hence + * implementation is relatively simple when compared to the Domain Model pattern. * - *

In this example we will use the Table Module pattern to implement register - * and login methods for the records stored in the user table. The main - * method will initialise an instance of {@link UserTableModule} and use it to - * handle the domain logic for the user table.

+ *

In this example we will use the Table Module pattern to implement register and login methods + * for the records stored in the user table. The main method will initialise an instance of {@link + * UserTableModule} and use it to handle the domain logic for the user table. */ @Slf4j public final class App { private static final String DB_URL = "jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1"; - /** - * Private constructor. - */ - private App() { - - } + /** Private constructor. */ + private App() {} /** * Program entry point. @@ -80,18 +72,16 @@ public final class App { deleteSchema(dataSource); } - private static void deleteSchema(final DataSource dataSource) - throws SQLException { + private static void deleteSchema(final DataSource dataSource) throws SQLException { try (var connection = dataSource.getConnection(); - var statement = connection.createStatement()) { + var statement = connection.createStatement()) { statement.execute(UserTableModule.DELETE_SCHEMA_SQL); } } - private static void createSchema(final DataSource dataSource) - throws SQLException { + private static void createSchema(final DataSource dataSource) throws SQLException { try (var connection = dataSource.getConnection(); - var statement = connection.createStatement()) { + var statement = connection.createStatement()) { statement.execute(UserTableModule.CREATE_SCHEMA_SQL); } } diff --git a/table-module/src/main/java/com/iluwatar/tablemodule/User.java b/table-module/src/main/java/com/iluwatar/tablemodule/User.java index 1acdc93db..4af0f73dc 100644 --- a/table-module/src/main/java/com/iluwatar/tablemodule/User.java +++ b/table-module/src/main/java/com/iluwatar/tablemodule/User.java @@ -30,10 +30,7 @@ import lombok.Getter; import lombok.Setter; import lombok.ToString; - -/** - * A user POJO that represents the data that will be read from the data source. - */ +/** A user POJO that represents the data that will be read from the data source. */ @Setter @Getter @ToString @@ -43,5 +40,4 @@ public class User { private int id; private String username; private String password; - } diff --git a/table-module/src/main/java/com/iluwatar/tablemodule/UserTableModule.java b/table-module/src/main/java/com/iluwatar/tablemodule/UserTableModule.java index 92ffb6db6..ea0b58fc3 100644 --- a/table-module/src/main/java/com/iluwatar/tablemodule/UserTableModule.java +++ b/table-module/src/main/java/com/iluwatar/tablemodule/UserTableModule.java @@ -29,26 +29,21 @@ import java.sql.SQLException; import javax.sql.DataSource; import lombok.extern.slf4j.Slf4j; - /** - * This class organizes domain logic with the user table in the - * database. A single instance of this class contains the various - * procedures that will act on the data. + * This class organizes domain logic with the user table in the database. A single instance of this + * class contains the various procedures that will act on the data. */ @Slf4j public class UserTableModule { - /** - * Public element for creating schema. - */ + /** Public element for creating schema. */ public static final String CREATE_SCHEMA_SQL = - "CREATE TABLE IF NOT EXISTS USERS (ID NUMBER, USERNAME VARCHAR(30) " - + "UNIQUE,PASSWORD VARCHAR(30))"; - /** - * Public element for deleting schema. - */ - public static final String DELETE_SCHEMA_SQL = "DROP TABLE USERS IF EXISTS"; - private final DataSource dataSource; + "CREATE TABLE IF NOT EXISTS USERS (ID NUMBER, USERNAME VARCHAR(30) " + + "UNIQUE,PASSWORD VARCHAR(30))"; + /** Public element for deleting schema. */ + public static final String DELETE_SCHEMA_SQL = "DROP TABLE USERS IF EXISTS"; + + private final DataSource dataSource; /** * Public constructor. @@ -59,7 +54,6 @@ public class UserTableModule { this.dataSource = userDataSource; } - /** * Login using username and password. * @@ -68,14 +62,11 @@ public class UserTableModule { * @return the execution result of the method * @throws SQLException if any error */ - public int login(final String username, final String password) - throws SQLException { + public int login(final String username, final String password) throws SQLException { var sql = "select count(*) from USERS where username=? and password=?"; ResultSet resultSet = null; try (var connection = dataSource.getConnection(); - var preparedStatement = - connection.prepareStatement(sql) - ) { + var preparedStatement = connection.prepareStatement(sql)) { var result = 0; preparedStatement.setString(1, username); preparedStatement.setString(2, password); @@ -106,9 +97,7 @@ public class UserTableModule { public int registerUser(final User user) throws SQLException { var sql = "insert into USERS (username, password) values (?,?)"; try (var connection = dataSource.getConnection(); - var preparedStatement = - connection.prepareStatement(sql) - ) { + var preparedStatement = connection.prepareStatement(sql)) { preparedStatement.setString(1, user.getUsername()); preparedStatement.setString(2, user.getPassword()); var result = preparedStatement.executeUpdate(); diff --git a/table-module/src/test/java/com/iluwatar/tablemodule/AppTest.java b/table-module/src/test/java/com/iluwatar/tablemodule/AppTest.java index d401d36ca..f17cd4722 100644 --- a/table-module/src/test/java/com/iluwatar/tablemodule/AppTest.java +++ b/table-module/src/test/java/com/iluwatar/tablemodule/AppTest.java @@ -24,17 +24,15 @@ */ package com.iluwatar.tablemodule; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -/** - * Tests that the table module example runs without errors. - */ +import org.junit.jupiter.api.Test; + +/** Tests that the table module example runs without errors. */ class AppTest { @Test void shouldExecuteWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/table-module/src/test/java/com/iluwatar/tablemodule/UserTableModuleTest.java b/table-module/src/test/java/com/iluwatar/tablemodule/UserTableModuleTest.java index f77067e6f..f6b31a858 100644 --- a/table-module/src/test/java/com/iluwatar/tablemodule/UserTableModuleTest.java +++ b/table-module/src/test/java/com/iluwatar/tablemodule/UserTableModuleTest.java @@ -24,16 +24,16 @@ */ package com.iluwatar.tablemodule; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.sql.DriverManager; +import java.sql.SQLException; +import javax.sql.DataSource; import org.h2.jdbcx.JdbcDataSource; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import javax.sql.DataSource; -import java.sql.DriverManager; -import java.sql.SQLException; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; class UserTableModuleTest { private static final String DB_URL = "jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1"; @@ -47,7 +47,7 @@ class UserTableModuleTest { @BeforeEach void setUp() throws SQLException { try (var connection = DriverManager.getConnection(DB_URL); - var statement = connection.createStatement()) { + var statement = connection.createStatement()) { statement.execute(UserTableModule.DELETE_SCHEMA_SQL); statement.execute(UserTableModule.CREATE_SCHEMA_SQL); } @@ -56,7 +56,7 @@ class UserTableModuleTest { @AfterEach void tearDown() throws SQLException { try (var connection = DriverManager.getConnection(DB_URL); - var statement = connection.createStatement()) { + var statement = connection.createStatement()) { statement.execute(UserTableModule.DELETE_SCHEMA_SQL); } } @@ -66,8 +66,7 @@ class UserTableModuleTest { var dataSource = createDataSource(); var userTableModule = new UserTableModule(dataSource); var user = new User(1, "123456", "123456"); - assertEquals(0, userTableModule.login(user.getUsername(), - user.getPassword())); + assertEquals(0, userTableModule.login(user.getUsername(), user.getPassword())); } @Test @@ -76,8 +75,7 @@ class UserTableModuleTest { var userTableModule = new UserTableModule(dataSource); var user = new User(1, "123456", "123456"); userTableModule.registerUser(user); - assertEquals(1, userTableModule.login(user.getUsername(), - user.getPassword())); + assertEquals(1, userTableModule.login(user.getUsername(), user.getPassword())); } @Test @@ -96,4 +94,4 @@ class UserTableModuleTest { var user = new User(1, "123456", "123456"); assertEquals(1, userTableModule.registerUser(user)); } -} \ No newline at end of file +} diff --git a/table-module/src/test/java/com/iluwatar/tablemodule/UserTest.java b/table-module/src/test/java/com/iluwatar/tablemodule/UserTest.java index 51da1847c..ca827f3a9 100644 --- a/table-module/src/test/java/com/iluwatar/tablemodule/UserTest.java +++ b/table-module/src/test/java/com/iluwatar/tablemodule/UserTest.java @@ -24,104 +24,89 @@ */ package com.iluwatar.tablemodule; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; + class UserTest { @Test void testCanEqual() { - assertFalse((new User(1, "janedoe", "iloveyou")) - .canEqual("Other")); + assertFalse((new User(1, "janedoe", "iloveyou")).canEqual("Other")); } @Test void testCanEqual2() { var user = new User(1, "janedoe", "iloveyou"); - assertTrue(user.canEqual(new User(1, "janedoe", - "iloveyou"))); + assertTrue(user.canEqual(new User(1, "janedoe", "iloveyou"))); } @Test void testEquals1() { var user = new User(1, "janedoe", "iloveyou"); - assertNotEquals(user, new User(123, "abcd", - "qwerty")); + assertNotEquals(user, new User(123, "abcd", "qwerty")); } @Test void testEquals2() { var user = new User(1, "janedoe", "iloveyou"); - assertEquals(user, new User(1, "janedoe", - "iloveyou")); + assertEquals(user, new User(1, "janedoe", "iloveyou")); } @Test void testEquals3() { var user = new User(123, "janedoe", "iloveyou"); - assertNotEquals(user, new User(1, "janedoe", - "iloveyou")); + assertNotEquals(user, new User(1, "janedoe", "iloveyou")); } @Test void testEquals4() { var user = new User(1, null, "iloveyou"); - assertNotEquals(user, new User(1, "janedoe", - "iloveyou")); + assertNotEquals(user, new User(1, "janedoe", "iloveyou")); } @Test void testEquals5() { var user = new User(1, "iloveyou", "iloveyou"); - assertNotEquals(user, new User(1, "janedoe", - "iloveyou")); + assertNotEquals(user, new User(1, "janedoe", "iloveyou")); } @Test void testEquals6() { var user = new User(1, "janedoe", "janedoe"); - assertNotEquals(user, new User(1, "janedoe", - "iloveyou")); + assertNotEquals(user, new User(1, "janedoe", "iloveyou")); } @Test void testEquals7() { var user = new User(1, "janedoe", null); - assertNotEquals(user, new User(1, "janedoe", - "iloveyou")); + assertNotEquals(user, new User(1, "janedoe", "iloveyou")); } @Test void testEquals8() { var user = new User(1, null, "iloveyou"); - assertEquals(user, new User(1, null, - "iloveyou")); + assertEquals(user, new User(1, null, "iloveyou")); } @Test void testEquals9() { var user = new User(1, "janedoe", null); - assertEquals(user, new User(1, "janedoe", - null)); + assertEquals(user, new User(1, "janedoe", null)); } @Test void testHashCode1() { - assertEquals(-1758941372, (new User(1, "janedoe", - "iloveyou")).hashCode()); - + assertEquals(-1758941372, (new User(1, "janedoe", "iloveyou")).hashCode()); } @Test void testHashCode2() { - assertEquals(-1332207447, (new User(1, null, - "iloveyou")).hashCode()); + assertEquals(-1332207447, (new User(1, null, "iloveyou")).hashCode()); } @Test void testHashCode3() { - assertEquals(-426522485, (new User(1, "janedoe", - null)).hashCode()); + assertEquals(-426522485, (new User(1, "janedoe", null)).hashCode()); } @Test @@ -148,9 +133,10 @@ class UserTest { @Test void testToString() { var user = new User(1, "janedoe", "iloveyou"); - assertEquals(String.format("User(id=%s, username=%s, password=%s)", + assertEquals( + String.format( + "User(id=%s, username=%s, password=%s)", user.getId(), user.getUsername(), user.getPassword()), - user.toString()); + user.toString()); } } - diff --git a/template-method/pom.xml b/template-method/pom.xml index ec791eae4..401af5c72 100644 --- a/template-method/pom.xml +++ b/template-method/pom.xml @@ -34,6 +34,14 @@ template-method + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/template-method/src/main/java/com/iluwatar/templatemethod/HalflingThief.java b/template-method/src/main/java/com/iluwatar/templatemethod/HalflingThief.java index 06dff72fa..d7d14d52b 100644 --- a/template-method/src/main/java/com/iluwatar/templatemethod/HalflingThief.java +++ b/template-method/src/main/java/com/iluwatar/templatemethod/HalflingThief.java @@ -24,9 +24,7 @@ */ package com.iluwatar.templatemethod; -/** - * Halfling thief uses {@link StealingMethod} to steal. - */ +/** Halfling thief uses {@link StealingMethod} to steal. */ public class HalflingThief { private StealingMethod method; diff --git a/template-method/src/main/java/com/iluwatar/templatemethod/HitAndRunMethod.java b/template-method/src/main/java/com/iluwatar/templatemethod/HitAndRunMethod.java index 24c8bed10..a809fa688 100644 --- a/template-method/src/main/java/com/iluwatar/templatemethod/HitAndRunMethod.java +++ b/template-method/src/main/java/com/iluwatar/templatemethod/HitAndRunMethod.java @@ -26,9 +26,7 @@ package com.iluwatar.templatemethod; import lombok.extern.slf4j.Slf4j; -/** - * HitAndRunMethod implementation of {@link StealingMethod}. - */ +/** HitAndRunMethod implementation of {@link StealingMethod}. */ @Slf4j public class HitAndRunMethod extends StealingMethod { diff --git a/template-method/src/main/java/com/iluwatar/templatemethod/StealingMethod.java b/template-method/src/main/java/com/iluwatar/templatemethod/StealingMethod.java index db8813fa2..f2479b075 100644 --- a/template-method/src/main/java/com/iluwatar/templatemethod/StealingMethod.java +++ b/template-method/src/main/java/com/iluwatar/templatemethod/StealingMethod.java @@ -1,50 +1,46 @@ -/* - * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). - * - * The MIT License - * Copyright © 2014-2022 Ilkka Seppälä - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package com.iluwatar.templatemethod; - -import lombok.extern.slf4j.Slf4j; - -/** - * StealingMethod defines skeleton for the algorithm. - */ -@Slf4j -public abstract class StealingMethod { - - protected abstract String pickTarget(); - - protected abstract void confuseTarget(String target); - - protected abstract void stealTheItem(String target); - - /** - * Steal. - */ - public final void steal() { - var target = pickTarget(); - LOGGER.info("The target has been chosen as {}.", target); - confuseTarget(target); - stealTheItem(target); - } -} +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.templatemethod; + +import lombok.extern.slf4j.Slf4j; + +/** StealingMethod defines skeleton for the algorithm. */ +@Slf4j +public abstract class StealingMethod { + + protected abstract String pickTarget(); + + protected abstract void confuseTarget(String target); + + protected abstract void stealTheItem(String target); + + /** Steal. */ + public final void steal() { + var target = pickTarget(); + LOGGER.info("The target has been chosen as {}.", target); + confuseTarget(target); + stealTheItem(target); + } +} diff --git a/template-method/src/main/java/com/iluwatar/templatemethod/SubtleMethod.java b/template-method/src/main/java/com/iluwatar/templatemethod/SubtleMethod.java index 0ca294f66..4843fae27 100644 --- a/template-method/src/main/java/com/iluwatar/templatemethod/SubtleMethod.java +++ b/template-method/src/main/java/com/iluwatar/templatemethod/SubtleMethod.java @@ -26,9 +26,7 @@ package com.iluwatar.templatemethod; import lombok.extern.slf4j.Slf4j; -/** - * SubtleMethod implementation of {@link StealingMethod}. - */ +/** SubtleMethod implementation of {@link StealingMethod}. */ @Slf4j public class SubtleMethod extends StealingMethod { diff --git a/template-method/src/test/java/com/iluwatar/templatemethod/AppTest.java b/template-method/src/test/java/com/iluwatar/templatemethod/AppTest.java index 5e8023e64..e9faed224 100644 --- a/template-method/src/test/java/com/iluwatar/templatemethod/AppTest.java +++ b/template-method/src/test/java/com/iluwatar/templatemethod/AppTest.java @@ -24,17 +24,15 @@ */ package com.iluwatar.templatemethod; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -/** - * Application test - */ +import org.junit.jupiter.api.Test; + +/** Application test */ class AppTest { @Test void shouldExecuteWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/template-method/src/test/java/com/iluwatar/templatemethod/HalflingThiefTest.java b/template-method/src/test/java/com/iluwatar/templatemethod/HalflingThiefTest.java index 922492089..da39b5fdb 100644 --- a/template-method/src/test/java/com/iluwatar/templatemethod/HalflingThiefTest.java +++ b/template-method/src/test/java/com/iluwatar/templatemethod/HalflingThiefTest.java @@ -26,20 +26,13 @@ package com.iluwatar.templatemethod; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; -import static org.mockito.Mockito.when; import org.junit.jupiter.api.Test; -/** - * HalflingThiefTest - * - */ +/** HalflingThiefTest */ class HalflingThiefTest { - /** - * Verify if the thief uses the provided stealing method - */ + /** Verify if the thief uses the provided stealing method */ @Test void testSteal() { final var method = spy(StealingMethod.class); @@ -48,9 +41,7 @@ class HalflingThiefTest { verify(method).steal(); } - /** - * Verify if the thief uses the provided stealing method, and the new method after changing it - */ + /** Verify if the thief uses the provided stealing method, and the new method after changing it */ @Test void testChangeMethod() { final var initialMethod = spy(StealingMethod.class); diff --git a/template-method/src/test/java/com/iluwatar/templatemethod/HitAndRunMethodTest.java b/template-method/src/test/java/com/iluwatar/templatemethod/HitAndRunMethodTest.java index d066d2bed..85666667c 100644 --- a/template-method/src/test/java/com/iluwatar/templatemethod/HitAndRunMethodTest.java +++ b/template-method/src/test/java/com/iluwatar/templatemethod/HitAndRunMethodTest.java @@ -24,23 +24,16 @@ */ package com.iluwatar.templatemethod; -/** - * HitAndRunMethodTest - * - */ +/** HitAndRunMethodTest */ class HitAndRunMethodTest extends StealingMethodTest { - /** - * Create a new test for the {@link HitAndRunMethod} - */ + /** Create a new test for the {@link HitAndRunMethod} */ public HitAndRunMethodTest() { super( new HitAndRunMethod(), "old goblin woman", "The target has been chosen as old goblin woman.", "Approach the old goblin woman from behind.", - "Grab the handbag and run away fast!" - ); + "Grab the handbag and run away fast!"); } - -} \ No newline at end of file +} 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 565a6fce4..ee01df1cb 100644 --- a/template-method/src/test/java/com/iluwatar/templatemethod/StealingMethodTest.java +++ b/template-method/src/test/java/com/iluwatar/templatemethod/StealingMethodTest.java @@ -56,42 +56,36 @@ public abstract class StealingMethodTest { appender.stop(); } - /** - * The tested stealing method - */ + /** The tested stealing method */ private final M method; - /** - * The expected target - */ + /** The expected target */ private final String expectedTarget; - /** - * The expected target picking result - */ + /** The expected target picking result */ private final String expectedTargetResult; - /** - * The expected confusion method - */ + /** The expected confusion method */ private final String expectedConfuseMethod; - /** - * The expected stealing method - */ + /** The expected stealing method */ private final String expectedStealMethod; /** * Create a new test for the given stealing method, together with the expected results * - * @param method The tested stealing method - * @param expectedTarget The expected target name - * @param expectedTargetResult The expected target picking result + * @param method The tested stealing method + * @param expectedTarget The expected target name + * @param expectedTargetResult The expected target picking result * @param expectedConfuseMethod The expected confusion method - * @param expectedStealMethod The expected stealing method + * @param expectedStealMethod The expected stealing method */ - public StealingMethodTest(final M method, String expectedTarget, final String expectedTargetResult, - final String expectedConfuseMethod, final String expectedStealMethod) { + public StealingMethodTest( + final M method, + String expectedTarget, + final String expectedTargetResult, + final String expectedConfuseMethod, + final String expectedStealMethod) { this.method = method; this.expectedTarget = expectedTarget; @@ -100,17 +94,13 @@ public abstract class StealingMethodTest { this.expectedStealMethod = expectedStealMethod; } - /** - * Verify if the thief picks the correct target - */ + /** Verify if the thief picks the correct target */ @Test void testPickTarget() { assertEquals(expectedTarget, this.method.pickTarget()); } - /** - * Verify if the target confusing step goes as planned - */ + /** Verify if the target confusing step goes as planned */ @Test void testConfuseTarget() { assertEquals(0, appender.getLogSize()); @@ -120,9 +110,7 @@ public abstract class StealingMethodTest { assertEquals(1, appender.getLogSize()); } - /** - * Verify if the stealing step goes as planned - */ + /** Verify if the stealing step goes as planned */ @Test void testStealTheItem() { assertEquals(0, appender.getLogSize()); @@ -132,9 +120,7 @@ public abstract class StealingMethodTest { assertEquals(1, appender.getLogSize()); } - /** - * Verify if the complete steal process goes as planned - */ + /** Verify if the complete steal process goes as planned */ @Test void testSteal() { this.method.steal(); diff --git a/template-method/src/test/java/com/iluwatar/templatemethod/SubtleMethodTest.java b/template-method/src/test/java/com/iluwatar/templatemethod/SubtleMethodTest.java index bcdabe8ff..2288a9f8b 100644 --- a/template-method/src/test/java/com/iluwatar/templatemethod/SubtleMethodTest.java +++ b/template-method/src/test/java/com/iluwatar/templatemethod/SubtleMethodTest.java @@ -24,23 +24,16 @@ */ package com.iluwatar.templatemethod; -/** - * SubtleMethodTest - * - */ +/** SubtleMethodTest */ class SubtleMethodTest extends StealingMethodTest { - /** - * Create a new test for the {@link SubtleMethod} - */ + /** Create a new test for the {@link SubtleMethod} */ public SubtleMethodTest() { super( new SubtleMethod(), "shop keeper", "The target has been chosen as shop keeper.", "Approach the shop keeper with tears running and hug him!", - "While in close contact grab the shop keeper's wallet." - ); + "While in close contact grab the shop keeper's wallet."); } - -} \ No newline at end of file +} diff --git a/templateview/pom.xml b/templateview/pom.xml index be61bde4b..6474b8362 100644 --- a/templateview/pom.xml +++ b/templateview/pom.xml @@ -34,6 +34,14 @@ templateview + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/templateview/src/main/java/com/iluwatar/templateview/App.java b/templateview/src/main/java/com/iluwatar/templateview/App.java index 55ec2b772..6f99598b4 100644 --- a/templateview/src/main/java/com/iluwatar/templateview/App.java +++ b/templateview/src/main/java/com/iluwatar/templateview/App.java @@ -30,9 +30,9 @@ import lombok.extern.slf4j.Slf4j; * Template View defines a consistent layout for rendering views, delegating dynamic content * rendering to subclasses. * - *

In this example, the {@link TemplateView} class provides the skeleton for rendering views - * with a header, dynamic content, and a footer. Subclasses {@link HomePageView} and - * {@link ContactPageView} define the specific dynamic content for their respective views. + *

In this example, the {@link TemplateView} class provides the skeleton for rendering views with + * a header, dynamic content, and a footer. Subclasses {@link HomePageView} and {@link + * ContactPageView} define the specific dynamic content for their respective views. * *

The {@link App} class demonstrates the usage of the Template View Pattern by rendering * instances of {@link HomePageView} and {@link ContactPageView}. diff --git a/templateview/src/main/java/com/iluwatar/templateview/ContactPageView.java b/templateview/src/main/java/com/iluwatar/templateview/ContactPageView.java index 980ed48fa..f44e0a496 100644 --- a/templateview/src/main/java/com/iluwatar/templateview/ContactPageView.java +++ b/templateview/src/main/java/com/iluwatar/templateview/ContactPageView.java @@ -27,14 +27,13 @@ package com.iluwatar.templateview; import lombok.extern.slf4j.Slf4j; /** - * ContactPageView implements the TemplateView and provides dynamic content specific to the contact page. + * ContactPageView implements the TemplateView and provides dynamic content specific to the contact + * page. */ @Slf4j public class ContactPageView extends TemplateView { - /** - * Renders dynamic content for the contact page. - */ + /** Renders dynamic content for the contact page. */ @Override protected void renderDynamicContent() { LOGGER.info("Contact us at: contact@example.com"); diff --git a/templateview/src/main/java/com/iluwatar/templateview/HomePageView.java b/templateview/src/main/java/com/iluwatar/templateview/HomePageView.java index 704f7b58f..b8a3cbe65 100644 --- a/templateview/src/main/java/com/iluwatar/templateview/HomePageView.java +++ b/templateview/src/main/java/com/iluwatar/templateview/HomePageView.java @@ -31,9 +31,7 @@ import lombok.extern.slf4j.Slf4j; */ @Slf4j public class HomePageView extends TemplateView { - /** - * Renders dynamic content for the homepage. - */ + /** Renders dynamic content for the homepage. */ @Override protected void renderDynamicContent() { LOGGER.info("Welcome to the Home Page!"); diff --git a/templateview/src/main/java/com/iluwatar/templateview/TemplateView.java b/templateview/src/main/java/com/iluwatar/templateview/TemplateView.java index 5d0fd36c5..58291ffc9 100644 --- a/templateview/src/main/java/com/iluwatar/templateview/TemplateView.java +++ b/templateview/src/main/java/com/iluwatar/templateview/TemplateView.java @@ -27,36 +27,28 @@ package com.iluwatar.templateview; import lombok.extern.slf4j.Slf4j; /** - * TemplateView defines the skeleton for rendering views. - * Concrete subclasses will provide the dynamic content for specific views. + * TemplateView defines the skeleton for rendering views. Concrete subclasses will provide the + * dynamic content for specific views. */ @Slf4j public abstract class TemplateView { - /** - * Render the common structure of the view, delegating dynamic content to subclasses. - */ + /** Render the common structure of the view, delegating dynamic content to subclasses. */ public final void render() { printHeader(); renderDynamicContent(); printFooter(); } - /** - * Prints the common header of the view. - */ + /** Prints the common header of the view. */ protected void printHeader() { LOGGER.info("Rendering header..."); } - /** - * Subclasses must provide the implementation for rendering dynamic content. - */ + /** Subclasses must provide the implementation for rendering dynamic content. */ protected abstract void renderDynamicContent(); - /** - * Prints the common footer of the view. - */ + /** Prints the common footer of the view. */ protected void printFooter() { LOGGER.info("Rendering footer..."); } diff --git a/templateview/src/test/java/com/iluwatar/templateview/AppTest.java b/templateview/src/test/java/com/iluwatar/templateview/AppTest.java index 79bd38125..785b093f8 100644 --- a/templateview/src/test/java/com/iluwatar/templateview/AppTest.java +++ b/templateview/src/test/java/com/iluwatar/templateview/AppTest.java @@ -24,17 +24,16 @@ */ package com.iluwatar.templateview; -import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -/** - * Application test - */ +import org.junit.jupiter.api.Test; + +/** Application test */ class AppTest { @Test void shouldExecuteWithoutException() { // Verify that main() method executes without throwing exceptions - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/templateview/src/test/java/com/iluwatar/templateview/ContactPageViewTest.java b/templateview/src/test/java/com/iluwatar/templateview/ContactPageViewTest.java index a5ccc2620..f906df724 100644 --- a/templateview/src/test/java/com/iluwatar/templateview/ContactPageViewTest.java +++ b/templateview/src/test/java/com/iluwatar/templateview/ContactPageViewTest.java @@ -24,10 +24,10 @@ */ package com.iluwatar.templateview; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; import static org.mockito.Mockito.*; +import org.junit.jupiter.api.Test; + class ContactPageViewTest { @Test diff --git a/templateview/src/test/java/com/iluwatar/templateview/HomePageViewTest.java b/templateview/src/test/java/com/iluwatar/templateview/HomePageViewTest.java index 53b1b34e2..1f546c66d 100644 --- a/templateview/src/test/java/com/iluwatar/templateview/HomePageViewTest.java +++ b/templateview/src/test/java/com/iluwatar/templateview/HomePageViewTest.java @@ -24,10 +24,10 @@ */ package com.iluwatar.templateview; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; import static org.mockito.Mockito.*; +import org.junit.jupiter.api.Test; + class HomePageViewTest { @Test diff --git a/templateview/src/test/java/com/iluwatar/templateview/TemplateViewTest.java b/templateview/src/test/java/com/iluwatar/templateview/TemplateViewTest.java index 90962fd90..67335e728 100644 --- a/templateview/src/test/java/com/iluwatar/templateview/TemplateViewTest.java +++ b/templateview/src/test/java/com/iluwatar/templateview/TemplateViewTest.java @@ -24,10 +24,10 @@ */ package com.iluwatar.templateview; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; import static org.mockito.Mockito.*; +import org.junit.jupiter.api.Test; + class TemplateViewTest { @Test diff --git a/throttling/pom.xml b/throttling/pom.xml index e6bda0867..91551e01d 100644 --- a/throttling/pom.xml +++ b/throttling/pom.xml @@ -34,6 +34,14 @@ 4.0.0 throttling + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/throttling/src/main/java/com/iluwatar/throttling/App.java b/throttling/src/main/java/com/iluwatar/throttling/App.java index f66d75fb5..7b25b0a6b 100644 --- a/throttling/src/main/java/com/iluwatar/throttling/App.java +++ b/throttling/src/main/java/com/iluwatar/throttling/App.java @@ -34,12 +34,11 @@ import lombok.extern.slf4j.Slf4j; * Throttling pattern is a design pattern to throttle or limit the use of resources or even a * complete service by users or a particular tenant. This can allow systems to continue to function * and meet service level agreements, even when an increase in demand places load on resources. - *

- * In this example there is a {@link Bartender} serving beer to {@link BarCustomer}s. This is a time - * based throttling, i.e. only a certain number of calls are allowed per second. - *

- * ({@link BarCustomer}) is the service tenant class having a name and the number of calls allowed. - * ({@link Bartender}) is the service which is consumed by the tenants and is throttled. + * + *

In this example there is a {@link Bartender} serving beer to {@link BarCustomer}s. This is a + * time based throttling, i.e. only a certain number of calls are allowed per second. ({@link + * BarCustomer}) is the service tenant class having a name and the number of calls allowed. ({@link + * Bartender}) is the service which is consumed by the tenants and is throttled. */ @Slf4j public class App { @@ -69,20 +68,20 @@ public class App { } } - /** - * Make calls to the bartender. - */ + /** Make calls to the bartender. */ private static void makeServiceCalls(BarCustomer barCustomer, CallsCount callsCount) { var timer = new ThrottleTimerImpl(1000, callsCount); var service = new Bartender(timer, callsCount); // Sleep is introduced to keep the output in check and easy to view and analyze the results. - IntStream.range(0, 50).forEach(i -> { - service.orderDrink(barCustomer); - try { - Thread.sleep(100); - } catch (InterruptedException e) { - LOGGER.error("Thread interrupted: {}", e.getMessage()); - } - }); + IntStream.range(0, 50) + .forEach( + i -> { + service.orderDrink(barCustomer); + try { + Thread.sleep(100); + } catch (InterruptedException e) { + LOGGER.error("Thread interrupted: {}", e.getMessage()); + } + }); } } diff --git a/throttling/src/main/java/com/iluwatar/throttling/BarCustomer.java b/throttling/src/main/java/com/iluwatar/throttling/BarCustomer.java index 5d9e5d2f3..da0dc8eda 100644 --- a/throttling/src/main/java/com/iluwatar/throttling/BarCustomer.java +++ b/throttling/src/main/java/com/iluwatar/throttling/BarCustomer.java @@ -27,9 +27,7 @@ package com.iluwatar.throttling; import java.security.InvalidParameterException; import lombok.Getter; -/** - * BarCustomer is a tenant with a name and a number of allowed calls per second. - */ +/** BarCustomer is a tenant with a name and a number of allowed calls per second. */ @Getter public class BarCustomer { diff --git a/throttling/src/main/java/com/iluwatar/throttling/Bartender.java b/throttling/src/main/java/com/iluwatar/throttling/Bartender.java index 7653fcec0..a89a80c67 100644 --- a/throttling/src/main/java/com/iluwatar/throttling/Bartender.java +++ b/throttling/src/main/java/com/iluwatar/throttling/Bartender.java @@ -30,8 +30,8 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * Bartender is a service which accepts a BarCustomer (tenant) and throttles - * the resource based on the time given to the tenant. + * Bartender is a service which accepts a BarCustomer (tenant) and throttles the resource based on + * the time given to the tenant. */ class Bartender { @@ -45,6 +45,7 @@ class Bartender { /** * Orders a drink from the bartender. + * * @return customer id which is randomly generated */ public int orderDrink(BarCustomer barCustomer) { diff --git a/throttling/src/main/java/com/iluwatar/throttling/CallsCount.java b/throttling/src/main/java/com/iluwatar/throttling/CallsCount.java index 4776f0e9b..2545a9943 100644 --- a/throttling/src/main/java/com/iluwatar/throttling/CallsCount.java +++ b/throttling/src/main/java/com/iluwatar/throttling/CallsCount.java @@ -29,10 +29,7 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicLong; import lombok.extern.slf4j.Slf4j; -/** - * A class to keep track of the counter of different Tenants. - * - */ +/** A class to keep track of the counter of different Tenants. */ @Slf4j public final class CallsCount { private final Map tenantCallsCount = new ConcurrentHashMap<>(); @@ -65,9 +62,7 @@ public final class CallsCount { return tenantCallsCount.get(tenantName).get(); } - /** - * Resets the count of all the tenants in the map. - */ + /** Resets the count of all the tenants in the map. */ public void reset() { tenantCallsCount.replaceAll((k, v) -> new AtomicLong(0)); LOGGER.info("reset counters"); diff --git a/throttling/src/main/java/com/iluwatar/throttling/timer/ThrottleTimerImpl.java b/throttling/src/main/java/com/iluwatar/throttling/timer/ThrottleTimerImpl.java index 32facaaf9..5eff99486 100644 --- a/throttling/src/main/java/com/iluwatar/throttling/timer/ThrottleTimerImpl.java +++ b/throttling/src/main/java/com/iluwatar/throttling/timer/ThrottleTimerImpl.java @@ -28,10 +28,7 @@ import com.iluwatar.throttling.CallsCount; import java.util.Timer; import java.util.TimerTask; -/** - * Implementation of throttler interface. This class resets the counter every second. - * - */ +/** Implementation of throttler interface. This class resets the counter every second. */ public class ThrottleTimerImpl implements Throttler { private final int throttlePeriod; @@ -42,17 +39,18 @@ public class ThrottleTimerImpl implements Throttler { this.callsCount = callsCount; } - /** - * A timer is initiated with this method. The timer runs every second and resets the - * counter. - */ + /** A timer is initiated with this method. The timer runs every second and resets the counter. */ @Override public void start() { - new Timer(true).schedule(new TimerTask() { - @Override - public void run() { - callsCount.reset(); - } - }, 0, throttlePeriod); + new Timer(true) + .schedule( + new TimerTask() { + @Override + public void run() { + callsCount.reset(); + } + }, + 0, + throttlePeriod); } } diff --git a/throttling/src/main/java/com/iluwatar/throttling/timer/Throttler.java b/throttling/src/main/java/com/iluwatar/throttling/timer/Throttler.java index 5f833619d..2600155be 100644 --- a/throttling/src/main/java/com/iluwatar/throttling/timer/Throttler.java +++ b/throttling/src/main/java/com/iluwatar/throttling/timer/Throttler.java @@ -24,10 +24,7 @@ */ package com.iluwatar.throttling.timer; -/** - * An interface for defining the structure of different types of throttling ways. - * - */ +/** An interface for defining the structure of different types of throttling ways. */ public interface Throttler { void start(); diff --git a/throttling/src/test/java/com/iluwatar/throttling/AppTest.java b/throttling/src/test/java/com/iluwatar/throttling/AppTest.java index 73663ea46..3cff5c201 100644 --- a/throttling/src/test/java/com/iluwatar/throttling/AppTest.java +++ b/throttling/src/test/java/com/iluwatar/throttling/AppTest.java @@ -24,17 +24,15 @@ */ package com.iluwatar.throttling; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -/** - * Application test - */ +import org.junit.jupiter.api.Test; + +/** Application test */ class AppTest { @Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/throttling/src/test/java/com/iluwatar/throttling/BarCustomerTest.java b/throttling/src/test/java/com/iluwatar/throttling/BarCustomerTest.java index b1107ec1a..a2eb12ba0 100644 --- a/throttling/src/test/java/com/iluwatar/throttling/BarCustomerTest.java +++ b/throttling/src/test/java/com/iluwatar/throttling/BarCustomerTest.java @@ -24,18 +24,17 @@ */ package com.iluwatar.throttling; -import org.junit.jupiter.api.Test; -import java.security.InvalidParameterException; - import static org.junit.jupiter.api.Assertions.assertThrows; -/** - * TenantTest to test the creation of Tenant with valid parameters. - */ +import java.security.InvalidParameterException; +import org.junit.jupiter.api.Test; + +/** TenantTest to test the creation of Tenant with valid parameters. */ class BarCustomerTest { @Test void constructorTest() { - assertThrows(InvalidParameterException.class, () -> new BarCustomer("sirBrave", -1, new CallsCount())); + assertThrows( + InvalidParameterException.class, () -> new BarCustomer("sirBrave", -1, new CallsCount())); } } diff --git a/throttling/src/test/java/com/iluwatar/throttling/BartenderTest.java b/throttling/src/test/java/com/iluwatar/throttling/BartenderTest.java index 9d241eb6d..0fcb034a1 100644 --- a/throttling/src/test/java/com/iluwatar/throttling/BartenderTest.java +++ b/throttling/src/test/java/com/iluwatar/throttling/BartenderTest.java @@ -30,9 +30,7 @@ import com.iluwatar.throttling.timer.Throttler; import java.util.stream.IntStream; import org.junit.jupiter.api.Test; -/** - * B2BServiceTest class to test the B2BService - */ +/** B2BServiceTest class to test the B2BService */ class BartenderTest { private final CallsCount callsCount = new CallsCount(); @@ -40,7 +38,8 @@ class BartenderTest { @Test void dummyCustomerApiTest() { var tenant = new BarCustomer("pirate", 2, callsCount); - // In order to assure that throttling limits will not be reset, we use an empty throttling implementation + // In order to assure that throttling limits will not be reset, we use an empty throttling + // implementation var timer = (Throttler) () -> {}; var service = new Bartender(timer, callsCount); diff --git a/tolerant-reader/pom.xml b/tolerant-reader/pom.xml index c6716bb84..0053bf282 100644 --- a/tolerant-reader/pom.xml +++ b/tolerant-reader/pom.xml @@ -34,6 +34,14 @@ tolerant-reader + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/tolerant-reader/src/main/java/com/iluwatar/tolerantreader/App.java b/tolerant-reader/src/main/java/com/iluwatar/tolerantreader/App.java index 16c636eea..c7ced392c 100644 --- a/tolerant-reader/src/main/java/com/iluwatar/tolerantreader/App.java +++ b/tolerant-reader/src/main/java/com/iluwatar/tolerantreader/App.java @@ -43,31 +43,44 @@ import lombok.extern.slf4j.Slf4j; @Slf4j public class App { - /** - * Program entry point. - */ + /** Program entry point. */ public static void main(String[] args) throws IOException, ClassNotFoundException { // Write V1 var fishV1 = new RainbowFish("Zed", 10, 11, 12); - LOGGER.info("fishV1 name={} age={} length={} weight={}", fishV1.getName(), - fishV1.getAge(), fishV1.getLengthMeters(), fishV1.getWeightTons()); + LOGGER.info( + "fishV1 name={} age={} length={} weight={}", + fishV1.getName(), + fishV1.getAge(), + fishV1.getLengthMeters(), + fishV1.getWeightTons()); RainbowFishSerializer.writeV1(fishV1, "fish1.out"); // Read V1 var deserializedRainbowFishV1 = RainbowFishSerializer.readV1("fish1.out"); - LOGGER.info("deserializedFishV1 name={} age={} length={} weight={}", - deserializedRainbowFishV1.getName(), deserializedRainbowFishV1.getAge(), - deserializedRainbowFishV1.getLengthMeters(), deserializedRainbowFishV1.getWeightTons()); + LOGGER.info( + "deserializedFishV1 name={} age={} length={} weight={}", + deserializedRainbowFishV1.getName(), + deserializedRainbowFishV1.getAge(), + deserializedRainbowFishV1.getLengthMeters(), + deserializedRainbowFishV1.getWeightTons()); // Write V2 var fishV2 = new RainbowFishV2("Scar", 5, 12, 15, true, true, true); LOGGER.info( "fishV2 name={} age={} length={} weight={} sleeping={} hungry={} angry={}", - fishV2.getName(), fishV2.getAge(), fishV2.getLengthMeters(), fishV2.getWeightTons(), - fishV2.isHungry(), fishV2.isAngry(), fishV2.isSleeping()); + fishV2.getName(), + fishV2.getAge(), + fishV2.getLengthMeters(), + fishV2.getWeightTons(), + fishV2.isHungry(), + fishV2.isAngry(), + fishV2.isSleeping()); RainbowFishSerializer.writeV2(fishV2, "fish2.out"); // Read V2 with V1 method var deserializedFishV2 = RainbowFishSerializer.readV1("fish2.out"); - LOGGER.info("deserializedFishV2 name={} age={} length={} weight={}", - deserializedFishV2.getName(), deserializedFishV2.getAge(), - deserializedFishV2.getLengthMeters(), deserializedFishV2.getWeightTons()); + LOGGER.info( + "deserializedFishV2 name={} age={} length={} weight={}", + deserializedFishV2.getName(), + deserializedFishV2.getAge(), + deserializedFishV2.getLengthMeters(), + deserializedFishV2.getWeightTons()); } } diff --git a/tolerant-reader/src/main/java/com/iluwatar/tolerantreader/RainbowFish.java b/tolerant-reader/src/main/java/com/iluwatar/tolerantreader/RainbowFish.java index 16f8c2d1d..d6eae6a44 100644 --- a/tolerant-reader/src/main/java/com/iluwatar/tolerantreader/RainbowFish.java +++ b/tolerant-reader/src/main/java/com/iluwatar/tolerantreader/RainbowFish.java @@ -29,19 +29,15 @@ import java.io.Serializable; import lombok.Getter; import lombok.RequiredArgsConstructor; -/** - * RainbowFish is the initial schema. - */ +/** RainbowFish is the initial schema. */ @Getter @RequiredArgsConstructor public class RainbowFish implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial private static final long serialVersionUID = 1L; private final String name; private final int age; private final int lengthMeters; private final int weightTons; - } 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 3a71cf466..d96697df4 100644 --- a/tolerant-reader/src/main/java/com/iluwatar/tolerantreader/RainbowFishSerializer.java +++ b/tolerant-reader/src/main/java/com/iluwatar/tolerantreader/RainbowFishSerializer.java @@ -44,51 +44,56 @@ public final class RainbowFishSerializer { public static final String LENGTH_METERS = "lengthMeters"; public static final String WEIGHT_TONS = "weightTons"; - /** - * Write V1 RainbowFish to file. - */ + /** Write V1 RainbowFish to file. */ public static void writeV1(RainbowFish rainbowFish, String filename) throws IOException { - var map = Map.of( - "name", rainbowFish.getName(), - "age", String.format("%d", rainbowFish.getAge()), - LENGTH_METERS, String.format("%d", rainbowFish.getLengthMeters()), - WEIGHT_TONS, String.format("%d", rainbowFish.getWeightTons()) - ); + var map = + Map.of( + "name", + rainbowFish.getName(), + "age", + String.format("%d", rainbowFish.getAge()), + LENGTH_METERS, + String.format("%d", rainbowFish.getLengthMeters()), + WEIGHT_TONS, + String.format("%d", rainbowFish.getWeightTons())); try (var fileOut = new FileOutputStream(filename); - var objOut = new ObjectOutputStream(fileOut)) { + var objOut = new ObjectOutputStream(fileOut)) { objOut.writeObject(map); } } - /** - * Write V2 RainbowFish to file. - */ + /** Write V2 RainbowFish to file. */ public static void writeV2(RainbowFishV2 rainbowFish, String filename) throws IOException { - var map = Map.of( - "name", rainbowFish.getName(), - "age", String.format("%d", rainbowFish.getAge()), - LENGTH_METERS, String.format("%d", rainbowFish.getLengthMeters()), - WEIGHT_TONS, String.format("%d", rainbowFish.getWeightTons()), - "angry", Boolean.toString(rainbowFish.isAngry()), - "hungry", Boolean.toString(rainbowFish.isHungry()), - "sleeping", Boolean.toString(rainbowFish.isSleeping()) - ); + var map = + Map.of( + "name", + rainbowFish.getName(), + "age", + String.format("%d", rainbowFish.getAge()), + LENGTH_METERS, + String.format("%d", rainbowFish.getLengthMeters()), + WEIGHT_TONS, + String.format("%d", rainbowFish.getWeightTons()), + "angry", + Boolean.toString(rainbowFish.isAngry()), + "hungry", + Boolean.toString(rainbowFish.isHungry()), + "sleeping", + Boolean.toString(rainbowFish.isSleeping())); try (var fileOut = new FileOutputStream(filename); - var objOut = new ObjectOutputStream(fileOut)) { + var objOut = new ObjectOutputStream(fileOut)) { objOut.writeObject(map); } } - /** - * Read V1 RainbowFish from file. - */ + /** Read V1 RainbowFish from file. */ public static RainbowFish readV1(String filename) throws IOException, ClassNotFoundException { Map map; try (var fileIn = new FileInputStream(filename); - var objIn = new ObjectInputStream(fileIn)) { + var objIn = new ObjectInputStream(fileIn)) { map = (Map) objIn.readObject(); } @@ -96,7 +101,6 @@ public final class RainbowFishSerializer { map.get("name"), Integer.parseInt(map.get("age")), Integer.parseInt(map.get(LENGTH_METERS)), - Integer.parseInt(map.get(WEIGHT_TONS)) - ); + Integer.parseInt(map.get(WEIGHT_TONS))); } } diff --git a/tolerant-reader/src/main/java/com/iluwatar/tolerantreader/RainbowFishV2.java b/tolerant-reader/src/main/java/com/iluwatar/tolerantreader/RainbowFishV2.java index c039f332f..78c49c16a 100644 --- a/tolerant-reader/src/main/java/com/iluwatar/tolerantreader/RainbowFishV2.java +++ b/tolerant-reader/src/main/java/com/iluwatar/tolerantreader/RainbowFishV2.java @@ -27,14 +27,11 @@ package com.iluwatar.tolerantreader; import java.io.Serial; import lombok.Getter; -/** - * RainbowFishV2 is the evolved schema. - */ +/** RainbowFishV2 is the evolved schema. */ @Getter public class RainbowFishV2 extends RainbowFish { - @Serial - private static final long serialVersionUID = 1L; + @Serial private static final long serialVersionUID = 1L; private boolean sleeping; private boolean hungry; @@ -44,15 +41,18 @@ public class RainbowFishV2 extends RainbowFish { super(name, age, lengthMeters, weightTons); } - /** - * Constructor. - */ - public RainbowFishV2(String name, int age, int lengthMeters, int weightTons, boolean sleeping, - boolean hungry, boolean angry) { + /** Constructor. */ + public RainbowFishV2( + String name, + int age, + int lengthMeters, + int weightTons, + boolean sleeping, + boolean hungry, + boolean angry) { this(name, age, lengthMeters, weightTons); this.sleeping = sleeping; this.hungry = hungry; this.angry = angry; } - } diff --git a/tolerant-reader/src/test/java/com/iluwatar/tolerantreader/AppTest.java b/tolerant-reader/src/test/java/com/iluwatar/tolerantreader/AppTest.java index 50adcdeda..c9c2533f4 100644 --- a/tolerant-reader/src/test/java/com/iluwatar/tolerantreader/AppTest.java +++ b/tolerant-reader/src/test/java/com/iluwatar/tolerantreader/AppTest.java @@ -31,14 +31,12 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -/** - * Application test - */ +/** Application test */ class AppTest { @Test void shouldExecuteWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } @BeforeEach diff --git a/tolerant-reader/src/test/java/com/iluwatar/tolerantreader/RainbowFishSerializerTest.java b/tolerant-reader/src/test/java/com/iluwatar/tolerantreader/RainbowFishSerializerTest.java index b23816a62..8b1ebda93 100644 --- a/tolerant-reader/src/test/java/com/iluwatar/tolerantreader/RainbowFishSerializerTest.java +++ b/tolerant-reader/src/test/java/com/iluwatar/tolerantreader/RainbowFishSerializerTest.java @@ -34,37 +34,24 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; -/** - * RainbowFishSerializerTest - * - */ - +/** RainbowFishSerializerTest */ class RainbowFishSerializerTest { - /** - * Create a temporary folder, used to generate files in during this test - */ - @TempDir - static Path testFolder; + /** Create a temporary folder, used to generate files in during this test */ + @TempDir static Path testFolder; @BeforeEach void beforeEach() { assertTrue(Files.isDirectory(testFolder)); } - /** - * Rainbow fish version 1 used during the tests - */ + /** Rainbow fish version 1 used during the tests */ private static final RainbowFish V1 = new RainbowFish("version1", 1, 2, 3); - /** - * Rainbow fish version 2 used during the tests - */ + /** Rainbow fish version 2 used during the tests */ private static final RainbowFishV2 V2 = new RainbowFishV2("version2", 4, 5, 6, true, false, true); - /** - * Verify if a fish, written as version 1 can be read back as version 1 - */ + /** Verify if a fish, written as version 1 can be read back as version 1 */ @Test void testWriteV1ReadV1() throws Exception { final var outputPath = Files.createFile(testFolder.resolve("outputFile")); @@ -76,12 +63,9 @@ class RainbowFishSerializerTest { assertEquals(V1.getAge(), fish.getAge()); assertEquals(V1.getLengthMeters(), fish.getLengthMeters()); assertEquals(V1.getWeightTons(), fish.getWeightTons()); - } - /** - * Verify if a fish, written as version 2 can be read back as version 1 - */ + /** Verify if a fish, written as version 2 can be read back as version 1 */ @Test void testWriteV2ReadV1() throws Exception { final var outputPath = Files.createFile(testFolder.resolve("outputFile2")); @@ -94,5 +78,4 @@ class RainbowFishSerializerTest { assertEquals(V2.getLengthMeters(), fish.getLengthMeters()); assertEquals(V2.getWeightTons(), fish.getWeightTons()); } - } diff --git a/tolerant-reader/src/test/java/com/iluwatar/tolerantreader/RainbowFishTest.java b/tolerant-reader/src/test/java/com/iluwatar/tolerantreader/RainbowFishTest.java index 437026b9b..bb250edc5 100644 --- a/tolerant-reader/src/test/java/com/iluwatar/tolerantreader/RainbowFishTest.java +++ b/tolerant-reader/src/test/java/com/iluwatar/tolerantreader/RainbowFishTest.java @@ -28,15 +28,10 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; -/** - * RainbowFishTest - * - */ +/** RainbowFishTest */ class RainbowFishTest { - /** - * Verify if the getters of a {@link RainbowFish} return the expected values - */ + /** Verify if the getters of a {@link RainbowFish} return the expected values */ @Test void testValues() { final var fish = new RainbowFish("name", 1, 2, 3); @@ -45,5 +40,4 @@ class RainbowFishTest { assertEquals(2, fish.getLengthMeters()); assertEquals(3, fish.getWeightTons()); } - -} \ No newline at end of file +} diff --git a/tolerant-reader/src/test/java/com/iluwatar/tolerantreader/RainbowFishV2Test.java b/tolerant-reader/src/test/java/com/iluwatar/tolerantreader/RainbowFishV2Test.java index 79a42df8c..1c478f2a3 100644 --- a/tolerant-reader/src/test/java/com/iluwatar/tolerantreader/RainbowFishV2Test.java +++ b/tolerant-reader/src/test/java/com/iluwatar/tolerantreader/RainbowFishV2Test.java @@ -30,15 +30,10 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; -/** - * RainbowFishV2Test - * - */ +/** RainbowFishV2Test */ class RainbowFishV2Test { - /** - * Verify if the getters of a {@link RainbowFish} return the expected values - */ + /** Verify if the getters of a {@link RainbowFish} return the expected values */ @Test void testValues() { final var fish = new RainbowFishV2("name", 1, 2, 3, false, true, false); @@ -50,5 +45,4 @@ class RainbowFishV2Test { assertTrue(fish.isHungry()); assertFalse(fish.isAngry()); } - -} \ No newline at end of file +} diff --git a/trampoline/pom.xml b/trampoline/pom.xml index 61ddcc040..6f5814155 100644 --- a/trampoline/pom.xml +++ b/trampoline/pom.xml @@ -34,6 +34,14 @@ trampoline + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/trampoline/src/main/java/com/iluwatar/trampoline/Trampoline.java b/trampoline/src/main/java/com/iluwatar/trampoline/Trampoline.java index 2dd0bc171..e73f54f2e 100644 --- a/trampoline/src/main/java/com/iluwatar/trampoline/Trampoline.java +++ b/trampoline/src/main/java/com/iluwatar/trampoline/Trampoline.java @@ -29,19 +29,18 @@ import java.util.stream.Stream; /** * Trampoline pattern allows to define recursive algorithms by iterative loop. * - *

When get is called on the returned Trampoline, internally it will iterate calling ‘jump’ - * on the returned Trampoline as long as the concrete instance returned is {@link - * #more(Trampoline)}, stopping once the returned instance is {@link #done(Object)}. + *

When get is called on the returned Trampoline, internally it will iterate calling ‘jump’ on + * the returned Trampoline as long as the concrete instance returned is {@link #more(Trampoline)}, + * stopping once the returned instance is {@link #done(Object)}. * - *

Essential we convert looping via recursion into iteration, - * the key enabling mechanism is the fact that {@link #more(Trampoline)} is a lazy operation. + *

Essential we convert looping via recursion into iteration, the key enabling mechanism is the + * fact that {@link #more(Trampoline)} is a lazy operation. * - * @param is type for returning result. + * @param is type for returning result. */ public interface Trampoline { T get(); - /** * Jump to next stage. * @@ -51,7 +50,6 @@ public interface Trampoline { return this; } - default T result() { return get(); } @@ -75,7 +73,6 @@ public interface Trampoline { return () -> result; } - /** * Create a Trampoline that has more work to do. * diff --git a/trampoline/src/main/java/com/iluwatar/trampoline/TrampolineApp.java b/trampoline/src/main/java/com/iluwatar/trampoline/TrampolineApp.java index 37c83c998..a6b6a60e8 100644 --- a/trampoline/src/main/java/com/iluwatar/trampoline/TrampolineApp.java +++ b/trampoline/src/main/java/com/iluwatar/trampoline/TrampolineApp.java @@ -29,26 +29,20 @@ import lombok.extern.slf4j.Slf4j; /** * Trampoline pattern allows to define recursive algorithms by iterative loop. * - *

It is possible to implement algorithms recursively in Java without blowing the stack - * and to interleave the execution of functions without hard coding them together or even using - * threads. + *

It is possible to implement algorithms recursively in Java without blowing the stack and to + * interleave the execution of functions without hard coding them together or even using threads. */ @Slf4j public class TrampolineApp { - /** - * Main program for showing pattern. It does loop with factorial function. - */ + /** Main program for showing pattern. It does loop with factorial function. */ public static void main(String[] args) { LOGGER.info("Start calculating war casualties"); var result = loop(10, 1).result(); LOGGER.info("The number of orcs perished in the war: {}", result); - } - /** - * Manager for pattern. Define it with a factorial function. - */ + /** Manager for pattern. Define it with a factorial function. */ public static Trampoline loop(int times, int prod) { if (times == 0) { return Trampoline.done(prod); diff --git a/trampoline/src/test/java/com/iluwatar/trampoline/TrampolineAppTest.java b/trampoline/src/test/java/com/iluwatar/trampoline/TrampolineAppTest.java index 71db6c582..6b5584946 100644 --- a/trampoline/src/test/java/com/iluwatar/trampoline/TrampolineAppTest.java +++ b/trampoline/src/test/java/com/iluwatar/trampoline/TrampolineAppTest.java @@ -28,9 +28,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; -/** - * Test for trampoline pattern. - */ +/** Test for trampoline pattern. */ class TrampolineAppTest { @Test @@ -38,5 +36,4 @@ class TrampolineAppTest { long result = TrampolineApp.loop(10, 1).result(); assertEquals(3_628_800, result); } - -} \ No newline at end of file +} diff --git a/transaction-script/pom.xml b/transaction-script/pom.xml index af6d4571a..9246dbd32 100644 --- a/transaction-script/pom.xml +++ b/transaction-script/pom.xml @@ -34,6 +34,14 @@ 4.0.0 transaction-script + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + com.h2database h2 diff --git a/transaction-script/src/main/java/com/iluwatar/transactionscript/App.java b/transaction-script/src/main/java/com/iluwatar/transactionscript/App.java index ee9db58fc..41d8cc498 100644 --- a/transaction-script/src/main/java/com/iluwatar/transactionscript/App.java +++ b/transaction-script/src/main/java/com/iluwatar/transactionscript/App.java @@ -31,18 +31,18 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * Transaction Script (TS) is one of the simplest domain logic pattern. - * It needs less work to implement than other domain logic patterns, and therefore - * it’s perfect fit for smaller applications that don't need big architecture behind them. + * Transaction Script (TS) is one of the simplest domain logic pattern. It needs less work to + * implement than other domain logic patterns, and therefore it’s perfect fit for smaller + * applications that don't need big architecture behind them. * - *

In this example we will use the TS pattern to implement booking and cancellation - * methods for a Hotel management App. The main method will initialise an instance of - * {@link Hotel} and add rooms to it. After that it will book and cancel a couple of rooms - * and that will be printed by the logger.

+ *

In this example we will use the TS pattern to implement booking and cancellation methods for a + * Hotel management App. The main method will initialise an instance of {@link Hotel} and add rooms + * to it. After that it will book and cancel a couple of rooms and that will be printed by the + * logger. * - *

The thing we have to note here is that all the operations related to booking or cancelling - * a room like checking the database if the room exists, checking the booking status or the - * room, calculating refund price are all clubbed inside a single transaction script method.

+ *

The thing we have to note here is that all the operations related to booking or cancelling a + * room like checking the database if the room exists, checking the booking status or the room, + * calculating refund price are all clubbed inside a single transaction script method. */ public class App { @@ -50,9 +50,9 @@ public class App { private static final Logger LOGGER = LoggerFactory.getLogger(App.class); /** - * Program entry point. - * Initialises an instance of Hotel and adds rooms to it. - * Carries out booking and cancel booking transactions. + * Program entry point. Initialises an instance of Hotel and adds rooms to it. Carries out booking + * and cancel booking transactions. + * * @param args command line arguments * @throws Exception if any error occurs */ @@ -87,7 +87,6 @@ public class App { getRoomStatus(dao); deleteSchema(dataSource); - } private static void getRoomStatus(HotelDaoImpl dao) throws Exception { @@ -98,14 +97,14 @@ public class App { private static void deleteSchema(DataSource dataSource) throws java.sql.SQLException { try (var connection = dataSource.getConnection(); - var statement = connection.createStatement()) { + var statement = connection.createStatement()) { statement.execute(RoomSchemaSql.DELETE_SCHEMA_SQL); } } private static void createSchema(DataSource dataSource) throws Exception { try (var connection = dataSource.getConnection(); - var statement = connection.createStatement()) { + var statement = connection.createStatement()) { statement.execute(RoomSchemaSql.CREATE_SCHEMA_SQL); } catch (Exception e) { throw new Exception(e.getMessage(), e); diff --git a/transaction-script/src/main/java/com/iluwatar/transactionscript/Hotel.java b/transaction-script/src/main/java/com/iluwatar/transactionscript/Hotel.java index f0d077952..0e1ae0d7b 100644 --- a/transaction-script/src/main/java/com/iluwatar/transactionscript/Hotel.java +++ b/transaction-script/src/main/java/com/iluwatar/transactionscript/Hotel.java @@ -26,9 +26,7 @@ package com.iluwatar.transactionscript; import lombok.extern.slf4j.Slf4j; -/** - * Hotel class to implement TS pattern. - */ +/** Hotel class to implement TS pattern. */ @Slf4j public class Hotel { diff --git a/transaction-script/src/main/java/com/iluwatar/transactionscript/HotelDao.java b/transaction-script/src/main/java/com/iluwatar/transactionscript/HotelDao.java index b698ab114..8675c5098 100644 --- a/transaction-script/src/main/java/com/iluwatar/transactionscript/HotelDao.java +++ b/transaction-script/src/main/java/com/iluwatar/transactionscript/HotelDao.java @@ -27,9 +27,7 @@ package com.iluwatar.transactionscript; import java.util.Optional; import java.util.stream.Stream; -/** - * DAO interface for hotel transactions. - */ +/** DAO interface for hotel transactions. */ public interface HotelDao { Stream getAll() throws Exception; diff --git a/transaction-script/src/main/java/com/iluwatar/transactionscript/HotelDaoImpl.java b/transaction-script/src/main/java/com/iluwatar/transactionscript/HotelDaoImpl.java index e64ad1548..13173a01f 100644 --- a/transaction-script/src/main/java/com/iluwatar/transactionscript/HotelDaoImpl.java +++ b/transaction-script/src/main/java/com/iluwatar/transactionscript/HotelDaoImpl.java @@ -36,9 +36,7 @@ import java.util.stream.StreamSupport; import javax.sql.DataSource; import lombok.extern.slf4j.Slf4j; -/** - * Implementation of database operations for Hotel class. - */ +/** Implementation of database operations for Hotel class. */ @Slf4j public class HotelDaoImpl implements HotelDao { @@ -54,28 +52,31 @@ public class HotelDaoImpl implements HotelDao { var connection = getConnection(); var statement = connection.prepareStatement("SELECT * FROM ROOMS"); // NOSONAR var resultSet = statement.executeQuery(); // NOSONAR - return StreamSupport.stream(new Spliterators.AbstractSpliterator(Long.MAX_VALUE, - Spliterator.ORDERED) { + return StreamSupport.stream( + new Spliterators.AbstractSpliterator(Long.MAX_VALUE, Spliterator.ORDERED) { - @Override - public boolean tryAdvance(Consumer action) { - try { - if (!resultSet.next()) { - return false; - } - action.accept(createRoom(resultSet)); - return true; - } catch (Exception e) { - throw new RuntimeException(e); // NOSONAR - } - } - }, false).onClose(() -> { - try { - mutedClose(connection, statement, resultSet); - } catch (Exception e) { - LOGGER.error(e.getMessage()); - } - }); + @Override + public boolean tryAdvance(Consumer action) { + try { + if (!resultSet.next()) { + return false; + } + action.accept(createRoom(resultSet)); + return true; + } catch (Exception e) { + throw new RuntimeException(e); // NOSONAR + } + } + }, + false) + .onClose( + () -> { + try { + mutedClose(connection, statement, resultSet); + } catch (Exception e) { + LOGGER.error(e.getMessage()); + } + }); } catch (Exception e) { throw new Exception(e.getMessage(), e); } @@ -86,7 +87,7 @@ public class HotelDaoImpl implements HotelDao { ResultSet resultSet = null; try (var connection = getConnection(); - var statement = connection.prepareStatement("SELECT * FROM ROOMS WHERE ID = ?")) { + var statement = connection.prepareStatement("SELECT * FROM ROOMS WHERE ID = ?")) { statement.setInt(1, id); resultSet = statement.executeQuery(); @@ -111,7 +112,7 @@ public class HotelDaoImpl implements HotelDao { } try (var connection = getConnection(); - var statement = connection.prepareStatement("INSERT INTO ROOMS VALUES (?,?,?,?)")) { + var statement = connection.prepareStatement("INSERT INTO ROOMS VALUES (?,?,?,?)")) { statement.setInt(1, room.getId()); statement.setString(2, room.getRoomType()); statement.setInt(3, room.getPrice()); @@ -126,10 +127,9 @@ public class HotelDaoImpl implements HotelDao { @Override public Boolean update(Room room) throws Exception { try (var connection = getConnection(); - var statement = - connection - .prepareStatement("UPDATE ROOMS SET ROOM_TYPE = ?, PRICE = ?, BOOKED = ?" - + " WHERE ID = ?")) { + var statement = + connection.prepareStatement( + "UPDATE ROOMS SET ROOM_TYPE = ?, PRICE = ?, BOOKED = ?" + " WHERE ID = ?")) { statement.setString(1, room.getRoomType()); statement.setInt(2, room.getPrice()); statement.setBoolean(3, room.isBooked()); @@ -143,7 +143,7 @@ public class HotelDaoImpl implements HotelDao { @Override public Boolean delete(Room room) throws Exception { try (var connection = getConnection(); - var statement = connection.prepareStatement("DELETE FROM ROOMS WHERE ID = ?")) { + var statement = connection.prepareStatement("DELETE FROM ROOMS WHERE ID = ?")) { statement.setInt(1, room.getId()); return statement.executeUpdate() > 0; } catch (Exception e) { @@ -167,7 +167,8 @@ public class HotelDaoImpl implements HotelDao { } private Room createRoom(ResultSet resultSet) throws Exception { - return new Room(resultSet.getInt("ID"), + return new Room( + resultSet.getInt("ID"), resultSet.getString("ROOM_TYPE"), resultSet.getInt("PRICE"), resultSet.getBoolean("BOOKED")); diff --git a/transaction-script/src/main/java/com/iluwatar/transactionscript/Room.java b/transaction-script/src/main/java/com/iluwatar/transactionscript/Room.java index 93716d2a0..ea0a8e1d3 100644 --- a/transaction-script/src/main/java/com/iluwatar/transactionscript/Room.java +++ b/transaction-script/src/main/java/com/iluwatar/transactionscript/Room.java @@ -30,9 +30,7 @@ import lombok.Getter; import lombok.Setter; import lombok.ToString; -/** - * A room POJO that represents the data that will be read from the data source. - */ +/** A room POJO that represents the data that will be read from the data source. */ @Setter @Getter @ToString @@ -44,5 +42,4 @@ public class Room { private String roomType; private int price; private boolean booked; - } diff --git a/transaction-script/src/main/java/com/iluwatar/transactionscript/RoomSchemaSql.java b/transaction-script/src/main/java/com/iluwatar/transactionscript/RoomSchemaSql.java index 29cad5862..08d581fc7 100644 --- a/transaction-script/src/main/java/com/iluwatar/transactionscript/RoomSchemaSql.java +++ b/transaction-script/src/main/java/com/iluwatar/transactionscript/RoomSchemaSql.java @@ -24,16 +24,12 @@ */ package com.iluwatar.transactionscript; -/** - * Customer Schema SQL Class. - */ +/** Customer Schema SQL Class. */ public final class RoomSchemaSql { public static final String CREATE_SCHEMA_SQL = "CREATE TABLE ROOMS (ID NUMBER, ROOM_TYPE VARCHAR(100), PRICE INT, BOOKED VARCHAR(100))"; public static final String DELETE_SCHEMA_SQL = "DROP TABLE ROOMS IF EXISTS"; - private RoomSchemaSql() { - } - + private RoomSchemaSql() {} } diff --git a/transaction-script/src/test/java/com/iluwatar/transactionscript/AppTest.java b/transaction-script/src/test/java/com/iluwatar/transactionscript/AppTest.java index ac33b852d..291c6847b 100644 --- a/transaction-script/src/test/java/com/iluwatar/transactionscript/AppTest.java +++ b/transaction-script/src/test/java/com/iluwatar/transactionscript/AppTest.java @@ -24,17 +24,15 @@ */ package com.iluwatar.transactionscript; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -/** - * Tests that Transaction script example runs without errors. - */ +import org.junit.jupiter.api.Test; + +/** Tests that Transaction script example runs without errors. */ class AppTest { @Test void shouldExecuteWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/transaction-script/src/test/java/com/iluwatar/transactionscript/HotelDaoImplTest.java b/transaction-script/src/test/java/com/iluwatar/transactionscript/HotelDaoImplTest.java index 87c8f58ad..cce65f594 100644 --- a/transaction-script/src/test/java/com/iluwatar/transactionscript/HotelDaoImplTest.java +++ b/transaction-script/src/test/java/com/iluwatar/transactionscript/HotelDaoImplTest.java @@ -44,9 +44,7 @@ import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.mockito.Mockito; -/** - * Tests {@link HotelDaoImpl}. - */ +/** Tests {@link HotelDaoImpl}. */ class HotelDaoImplTest { private static final String DB_URL = "jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1"; @@ -61,15 +59,13 @@ class HotelDaoImplTest { @BeforeEach void createSchema() throws SQLException { try (var connection = DriverManager.getConnection(DB_URL); - var statement = connection.createStatement()) { + var statement = connection.createStatement()) { statement.execute(RoomSchemaSql.DELETE_SCHEMA_SQL); statement.execute(RoomSchemaSql.CREATE_SCHEMA_SQL); } } - /** - * Represents the scenario where DB connectivity is present. - */ + /** Represents the scenario where DB connectivity is present. */ @Nested class ConnectionSuccess { @@ -87,9 +83,7 @@ class HotelDaoImplTest { Assertions.assertTrue(result); } - /** - * Represents the scenario when DAO operations are being performed on a non-existing room. - */ + /** Represents the scenario when DAO operations are being performed on a non-existing room. */ @Nested class NonExistingRoom { @@ -135,8 +129,7 @@ class HotelDaoImplTest { } /** - * Represents a scenario where DAO operations are being performed on an already existing - * room. + * Represents a scenario where DAO operations are being performed on an already existing room. */ @Nested class ExistingRoom { @@ -161,8 +154,8 @@ class HotelDaoImplTest { } @Test - void updationShouldBeSuccessAndAccessingTheSameRoomShouldReturnUpdatedInformation() throws - Exception { + void updationShouldBeSuccessAndAccessingTheSameRoomShouldReturnUpdatedInformation() + throws Exception { final var newRoomType = "Double"; final var newPrice = 80; final var newBookingStatus = false; @@ -222,7 +215,10 @@ class HotelDaoImplTest { final var newRoomType = "Double"; final var newPrice = 80; final var newBookingStatus = false; - assertThrows(Exception.class, () -> dao.update(new Room(existingRoom.getId(), newRoomType, newPrice, newBookingStatus))); + assertThrows( + Exception.class, + () -> + dao.update(new Room(existingRoom.getId(), newRoomType, newPrice, newBookingStatus))); } @Test @@ -234,7 +230,6 @@ class HotelDaoImplTest { void retrievingAllRoomsFailsWithExceptionAsFeedbackToClient() { assertThrows(Exception.class, () -> dao.getAll()); } - } /** @@ -245,7 +240,7 @@ class HotelDaoImplTest { @AfterEach void deleteSchema() throws SQLException { try (var connection = DriverManager.getConnection(DB_URL); - var statement = connection.createStatement()) { + var statement = connection.createStatement()) { statement.execute(RoomSchemaSql.DELETE_SCHEMA_SQL); } } diff --git a/transaction-script/src/test/java/com/iluwatar/transactionscript/HotelTest.java b/transaction-script/src/test/java/com/iluwatar/transactionscript/HotelTest.java index 4045ac3e3..b555cce8c 100644 --- a/transaction-script/src/test/java/com/iluwatar/transactionscript/HotelTest.java +++ b/transaction-script/src/test/java/com/iluwatar/transactionscript/HotelTest.java @@ -35,9 +35,7 @@ import org.h2.jdbcx.JdbcDataSource; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -/** - * Tests {@link Hotel} - */ +/** Tests {@link Hotel} */ class HotelTest { private static final String H2_DB_URL = "jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1"; @@ -53,7 +51,6 @@ class HotelTest { dao = new HotelDaoImpl(dataSource); addRooms(dao); hotel = new Hotel(dao); - } @Test @@ -68,7 +65,6 @@ class HotelTest { assertThrows(Exception.class, () -> hotel.bookRoom(getNonExistingRoomId())); } - @Test @SneakyThrows void bookingRoomAgainShouldRaiseException() { @@ -103,17 +99,16 @@ class HotelTest { assertThrows(Exception.class, () -> hotel.cancelRoomBooking(1)); } - private static void deleteSchema(DataSource dataSource) throws java.sql.SQLException { try (var connection = dataSource.getConnection(); - var statement = connection.createStatement()) { + var statement = connection.createStatement()) { statement.execute(RoomSchemaSql.DELETE_SCHEMA_SQL); } } private static void createSchema(DataSource dataSource) throws Exception { try (var connection = dataSource.getConnection(); - var statement = connection.createStatement()) { + var statement = connection.createStatement()) { statement.execute(RoomSchemaSql.CREATE_SCHEMA_SQL); } catch (Exception e) { throw new Exception(e.getMessage(), e); @@ -150,4 +145,4 @@ class HotelTest { private int getNonExistingRoomId() { return 999; } -} \ No newline at end of file +} diff --git a/transaction-script/src/test/java/com/iluwatar/transactionscript/RoomTest.java b/transaction-script/src/test/java/com/iluwatar/transactionscript/RoomTest.java index a1c9fa7ff..e567d393e 100644 --- a/transaction-script/src/test/java/com/iluwatar/transactionscript/RoomTest.java +++ b/transaction-script/src/test/java/com/iluwatar/transactionscript/RoomTest.java @@ -30,9 +30,7 @@ import static org.junit.jupiter.api.Assertions.assertNotEquals; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -/** - * Tests {@link Room}. - */ +/** Tests {@link Room}. */ class RoomTest { private Room room; @@ -90,7 +88,10 @@ class RoomTest { @Test void testToString() { - assertEquals(String.format("Room(id=%s, roomType=%s, price=%s, booked=%s)", - room.getId(), room.getRoomType(), room.getPrice(), room.isBooked()), room.toString()); + assertEquals( + String.format( + "Room(id=%s, roomType=%s, price=%s, booked=%s)", + room.getId(), room.getRoomType(), room.getPrice(), room.isBooked()), + room.toString()); } } diff --git a/twin/pom.xml b/twin/pom.xml index 6e76aa318..e5bb97552 100644 --- a/twin/pom.xml +++ b/twin/pom.xml @@ -34,6 +34,14 @@ twin + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/twin/src/main/java/com/iluwatar/twin/App.java b/twin/src/main/java/com/iluwatar/twin/App.java index 7804a5f7e..65ffadf36 100644 --- a/twin/src/main/java/com/iluwatar/twin/App.java +++ b/twin/src/main/java/com/iluwatar/twin/App.java @@ -32,7 +32,6 @@ package com.iluwatar.twin; * BallThread} class represent the twin objects to coordinate with each other (via the twin * reference) like a single class inheriting from {@link GameItem} and {@link Thread}. */ - public class App { /** diff --git a/twin/src/main/java/com/iluwatar/twin/BallItem.java b/twin/src/main/java/com/iluwatar/twin/BallItem.java index c1a0a2ddf..04d6b97c3 100644 --- a/twin/src/main/java/com/iluwatar/twin/BallItem.java +++ b/twin/src/main/java/com/iluwatar/twin/BallItem.java @@ -37,8 +37,7 @@ public class BallItem extends GameItem { private boolean isSuspended; - @Setter - private BallThread twin; + @Setter private BallThread twin; @Override public void doDraw() { @@ -62,4 +61,3 @@ public class BallItem extends GameItem { } } } - diff --git a/twin/src/main/java/com/iluwatar/twin/BallThread.java b/twin/src/main/java/com/iluwatar/twin/BallThread.java index 9d4d9cf71..7768d3ebb 100644 --- a/twin/src/main/java/com/iluwatar/twin/BallThread.java +++ b/twin/src/main/java/com/iluwatar/twin/BallThread.java @@ -31,20 +31,16 @@ import lombok.extern.slf4j.Slf4j; * This class is a UI thread for drawing the {@link BallItem}, and provide the method for suspend * and resume. It holds the reference of {@link BallItem} to delegate the draw task. */ - @Slf4j public class BallThread extends Thread { - @Setter - private BallItem twin; + @Setter private BallItem twin; private volatile boolean isSuspended; private volatile boolean isRunning = true; - /** - * Run the thread. - */ + /** Run the thread. */ public void run() { while (isRunning) { @@ -75,4 +71,3 @@ public class BallThread extends Thread { this.isSuspended = true; } } - diff --git a/twin/src/main/java/com/iluwatar/twin/GameItem.java b/twin/src/main/java/com/iluwatar/twin/GameItem.java index d557fc4ab..1cdb025ff 100644 --- a/twin/src/main/java/com/iluwatar/twin/GameItem.java +++ b/twin/src/main/java/com/iluwatar/twin/GameItem.java @@ -26,15 +26,11 @@ package com.iluwatar.twin; import lombok.extern.slf4j.Slf4j; -/** - * GameItem is a common class which provides some common methods for game object. - */ +/** GameItem is a common class which provides some common methods for game object. */ @Slf4j public abstract class GameItem { - /** - * Template method, do some common logic before draw. - */ + /** Template method, do some common logic before draw. */ public void draw() { LOGGER.info("draw"); doDraw(); @@ -42,6 +38,5 @@ public abstract class GameItem { public abstract void doDraw(); - public abstract void click(); } diff --git a/twin/src/test/java/com/iluwatar/twin/AppTest.java b/twin/src/test/java/com/iluwatar/twin/AppTest.java index 029d21761..8835f9185 100644 --- a/twin/src/test/java/com/iluwatar/twin/AppTest.java +++ b/twin/src/test/java/com/iluwatar/twin/AppTest.java @@ -24,17 +24,15 @@ */ package com.iluwatar.twin; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -/** - * Application test - */ +import org.junit.jupiter.api.Test; + +/** Application test */ class AppTest { @Test void shouldExecuteWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/twin/src/test/java/com/iluwatar/twin/BallItemTest.java b/twin/src/test/java/com/iluwatar/twin/BallItemTest.java index 2b2f6223c..df869e92c 100644 --- a/twin/src/test/java/com/iluwatar/twin/BallItemTest.java +++ b/twin/src/test/java/com/iluwatar/twin/BallItemTest.java @@ -41,10 +41,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.slf4j.LoggerFactory; -/** - * BallItemTest - * - */ +/** BallItemTest */ class BallItemTest { private InMemoryAppender appender; @@ -67,12 +64,14 @@ class BallItemTest { final var inOrder = inOrder(ballThread); - IntStream.range(0, 10).forEach(i -> { - ballItem.click(); - inOrder.verify(ballThread).suspendMe(); - ballItem.click(); - inOrder.verify(ballThread).resumeMe(); - }); + IntStream.range(0, 10) + .forEach( + i -> { + ballItem.click(); + inOrder.verify(ballThread).suspendMe(); + ballItem.click(); + inOrder.verify(ballThread).resumeMe(); + }); inOrder.verifyNoMoreInteractions(); } @@ -104,9 +103,7 @@ class BallItemTest { assertEquals(1, appender.getLogSize()); } - /** - * Logging Appender Implementation - */ + /** Logging Appender Implementation */ static class InMemoryAppender extends AppenderBase { private final List log = new LinkedList<>(); @@ -128,5 +125,4 @@ class BallItemTest { return log.size(); } } - } diff --git a/twin/src/test/java/com/iluwatar/twin/BallThreadTest.java b/twin/src/test/java/com/iluwatar/twin/BallThreadTest.java index 26cf78509..6ad431ff6 100644 --- a/twin/src/test/java/com/iluwatar/twin/BallThreadTest.java +++ b/twin/src/test/java/com/iluwatar/twin/BallThreadTest.java @@ -37,84 +37,81 @@ import static org.mockito.Mockito.verifyNoMoreInteractions; import org.junit.jupiter.api.Test; -/** - * BallThreadTest - * - */ +/** BallThreadTest */ class BallThreadTest { - /** - * Verify if the {@link BallThread} can be resumed - */ + /** Verify if the {@link BallThread} can be resumed */ @Test void testSuspend() { - assertTimeout(ofMillis(5000), () -> { - final var ballThread = new BallThread(); + assertTimeout( + ofMillis(5000), + () -> { + final var ballThread = new BallThread(); - final var ballItem = mock(BallItem.class); - ballThread.setTwin(ballItem); + final var ballItem = mock(BallItem.class); + ballThread.setTwin(ballItem); - ballThread.start(); - sleep(200); - verify(ballItem, atLeastOnce()).draw(); - verify(ballItem, atLeastOnce()).move(); - ballThread.suspendMe(); + ballThread.start(); + sleep(200); + verify(ballItem, atLeastOnce()).draw(); + verify(ballItem, atLeastOnce()).move(); + ballThread.suspendMe(); - sleep(1000); + sleep(1000); - ballThread.stopMe(); - ballThread.join(); + ballThread.stopMe(); + ballThread.join(); - verifyNoMoreInteractions(ballItem); - }); + verifyNoMoreInteractions(ballItem); + }); } - /** - * Verify if the {@link BallThread} can be resumed - */ + /** Verify if the {@link BallThread} can be resumed */ @Test void testResume() { - assertTimeout(ofMillis(5000), () -> { - final var ballThread = new BallThread(); + assertTimeout( + ofMillis(5000), + () -> { + final var ballThread = new BallThread(); - final var ballItem = mock(BallItem.class); - ballThread.setTwin(ballItem); + final var ballItem = mock(BallItem.class); + ballThread.setTwin(ballItem); - ballThread.suspendMe(); - ballThread.start(); + ballThread.suspendMe(); + ballThread.start(); - sleep(1000); + sleep(1000); - verifyNoMoreInteractions(ballItem); + verifyNoMoreInteractions(ballItem); - ballThread.resumeMe(); - sleep(300); - verify(ballItem, atLeastOnce()).draw(); - verify(ballItem, atLeastOnce()).move(); + ballThread.resumeMe(); + sleep(300); + verify(ballItem, atLeastOnce()).draw(); + verify(ballItem, atLeastOnce()).move(); - ballThread.stopMe(); - ballThread.join(); + ballThread.stopMe(); + ballThread.join(); - verifyNoMoreInteractions(ballItem); - }); + verifyNoMoreInteractions(ballItem); + }); } - /** - * Verify if the {@link BallThread} is interruptible - */ + /** Verify if the {@link BallThread} is interruptible */ @Test void testInterrupt() { - assertTimeout(ofMillis(5000), () -> { - final var ballThread = new BallThread(); - final var exceptionHandler = mock(UncaughtExceptionHandler.class); - ballThread.setUncaughtExceptionHandler(exceptionHandler); - ballThread.setTwin(mock(BallItem.class)); - ballThread.start(); - ballThread.interrupt(); - ballThread.join(); + assertTimeout( + ofMillis(5000), + () -> { + final var ballThread = new BallThread(); + final var exceptionHandler = mock(UncaughtExceptionHandler.class); + ballThread.setUncaughtExceptionHandler(exceptionHandler); + ballThread.setTwin(mock(BallItem.class)); + ballThread.start(); + ballThread.interrupt(); + ballThread.join(); - verify(exceptionHandler).uncaughtException(eq(ballThread), any(RuntimeException.class)); - verifyNoMoreInteractions(exceptionHandler); - }); + verify(exceptionHandler).uncaughtException(eq(ballThread), any(RuntimeException.class)); + verifyNoMoreInteractions(exceptionHandler); + }); } -} \ No newline at end of file +} diff --git a/type-object/pom.xml b/type-object/pom.xml index bf667b91d..a0809f9a8 100644 --- a/type-object/pom.xml +++ b/type-object/pom.xml @@ -34,6 +34,14 @@ type-object + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + com.google.code.gson gson diff --git a/type-object/src/main/java/com/iluwatar/typeobject/App.java b/type-object/src/main/java/com/iluwatar/typeobject/App.java index 2fd80a54e..15b262a60 100644 --- a/type-object/src/main/java/com/iluwatar/typeobject/App.java +++ b/type-object/src/main/java/com/iluwatar/typeobject/App.java @@ -31,19 +31,18 @@ import lombok.extern.slf4j.Slf4j; * inheriting from it just doesn't work for the case in hand. This happens when we either don't know * what types we will need upfront, or want to be able to modify or add new types conveniently w/o * recompiling repeatedly. The pattern provides a solution by allowing flexible creation of required - * objects by creating one class, which has a field which represents the 'type' of the object. - * In this example, we have a mini candy-crush game in action. There are many different candies - * in the game, which may change over time, as we may want to upgrade the game. To make the object - * creation convenient, we have a class {@link Candy} which has a field name, parent, points and - * Type. We have a json file {@link candy} which contains the details about the candies, and this is - * parsed to get all the different candies in {@link JsonParser}. The {@link Cell} class is what the - * game matrix is made of, which has the candies that are to be crushed, and contains information on - * how crushing can be done, how the matrix is to be reconfigured and how points are to be gained. - * The {@link CellPool} class is a pool which reuses the candy cells that have been crushed instead - * of making new ones repeatedly. The {@link CandyGame} class has the rules for the continuation of - * the game and the {@link App} class has the game itself. + * objects by creating one class, which has a field which represents the 'type' of the object. In + * this example, we have a mini candy-crush game in action. There are many different candies in the + * game, which may change over time, as we may want to upgrade the game. To make the object creation + * convenient, we have a class {@link Candy} which has a field name, parent, points and Type. We + * have a json file {@link candy} which contains the details about the candies, and this is parsed + * to get all the different candies in {@link JsonParser}. The {@link Cell} class is what the game + * matrix is made of, which has the candies that are to be crushed, and contains information on how + * crushing can be done, how the matrix is to be reconfigured and how points are to be gained. The + * {@link CellPool} class is a pool which reuses the candy cells that have been crushed instead of + * making new ones repeatedly. The {@link CandyGame} class has the rules for the continuation of the + * game and the {@link App} class has the game itself. */ - @Slf4j public class App { @@ -53,8 +52,8 @@ public class App { * @param args command line args */ public static void main(String[] args) { - var givenTime = 50; //50ms - var toWin = 500; //points + var givenTime = 50; // 50ms + var toWin = 500; // points var pointsWon = 0; var numOfRows = 3; var start = System.currentTimeMillis(); diff --git a/type-object/src/main/java/com/iluwatar/typeobject/Candy.java b/type-object/src/main/java/com/iluwatar/typeobject/Candy.java index 78a613da4..0edaea9f7 100644 --- a/type-object/src/main/java/com/iluwatar/typeobject/Candy.java +++ b/type-object/src/main/java/com/iluwatar/typeobject/Candy.java @@ -44,8 +44,7 @@ public class Candy { Candy parent; String parentName; - @Setter - private int points; + @Setter private int points; private final Type type; Candy(String name, String parentName, Type type, int points) { @@ -55,5 +54,4 @@ public class Candy { this.points = points; this.parentName = parentName; } - } diff --git a/type-object/src/main/java/com/iluwatar/typeobject/CandyGame.java b/type-object/src/main/java/com/iluwatar/typeobject/CandyGame.java index 6e07a88a3..40412fbbd 100644 --- a/type-object/src/main/java/com/iluwatar/typeobject/CandyGame.java +++ b/type-object/src/main/java/com/iluwatar/typeobject/CandyGame.java @@ -28,16 +28,13 @@ import com.iluwatar.typeobject.Candy.Type; import java.util.ArrayList; import java.util.List; import lombok.extern.slf4j.Slf4j; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; /** * The CandyGame class contains the rules for the continuation of the game and has the game matrix * (field 'cells') and totalPoints gained during the game. */ - @Slf4j -@SuppressWarnings("java:S3776") //"Cognitive Complexity of methods should not be too high" +@SuppressWarnings("java:S3776") // "Cognitive Complexity of methods should not be too high" public class CandyGame { Cell[][] cells; CellPool pool; @@ -67,8 +64,11 @@ public class CandyGame { var candyName = cell[j].candy.name; if (candyName.length() < 20) { var totalSpaces = 20 - candyName.length(); - LOGGER.info(numOfSpaces(totalSpaces / 2) + cell[j].candy.name - + numOfSpaces(totalSpaces - totalSpaces / 2) + "|"); + LOGGER.info( + numOfSpaces(totalSpaces / 2) + + cell[j].candy.name + + numOfSpaces(totalSpaces - totalSpaces / 2) + + "|"); } else { LOGGER.info(candyName + "|"); } @@ -89,12 +89,11 @@ public class CandyGame { if (y == cells.length - 1 && cells.length > 1) { adjacent.add(this.cells[cells.length - 2][x]); } - + if (x == cells.length - 1 && cells.length > 1) { adjacent.add(this.cells[y][cells.length - 2]); } - - + if (y > 0 && y < cells.length - 1) { adjacent.add(this.cells[y - 1][x]); adjacent.add(this.cells[y + 1][x]); @@ -173,5 +172,4 @@ public class CandyGame { end = System.currentTimeMillis(); } } - -} \ No newline at end of file +} diff --git a/type-object/src/main/java/com/iluwatar/typeobject/Cell.java b/type-object/src/main/java/com/iluwatar/typeobject/Cell.java index 7437e5eb1..d66eec8ee 100644 --- a/type-object/src/main/java/com/iluwatar/typeobject/Cell.java +++ b/type-object/src/main/java/com/iluwatar/typeobject/Cell.java @@ -40,7 +40,7 @@ public class Cell { int positionY; void crush(CellPool pool, Cell[][] cellMatrix) { - //take out from this position and put back in pool + // take out from this position and put back in pool pool.addNewCell(this); this.fillThisSpace(pool, cellMatrix); } @@ -67,8 +67,8 @@ public class Cell { } int interact(Cell c, CellPool pool, Cell[][] cellMatrix) { - if (this.candy.getType().equals(Type.REWARD_FRUIT) || c.candy.getType() - .equals(Type.REWARD_FRUIT)) { + if (this.candy.getType().equals(Type.REWARD_FRUIT) + || c.candy.getType().equals(Type.REWARD_FRUIT)) { return 0; } else { if (this.candy.name.equals(c.candy.name)) { diff --git a/type-object/src/main/java/com/iluwatar/typeobject/CellPool.java b/type-object/src/main/java/com/iluwatar/typeobject/CellPool.java index 37c98a6d5..18f94fe74 100644 --- a/type-object/src/main/java/com/iluwatar/typeobject/CellPool.java +++ b/type-object/src/main/java/com/iluwatar/typeobject/CellPool.java @@ -51,7 +51,7 @@ public class CellPool { this.randomCode = assignRandomCandytypes(); } catch (Exception e) { LOGGER.error("Error occurred: ", e); - //manually initialising this.randomCode + // manually initialising this.randomCode this.randomCode = new Candy[5]; randomCode[0] = new Candy("cherry", FRUIT, Type.REWARD_FRUIT, 20); randomCode[1] = new Candy("mango", FRUIT, Type.REWARD_FRUIT, 20); @@ -74,7 +74,7 @@ public class CellPool { } void addNewCell(Cell c) { - c.candy = randomCode[RANDOM.nextInt(randomCode.length)]; //changing candytype to new + c.candy = randomCode[RANDOM.nextInt(randomCode.length)]; // changing candytype to new this.pool.add(c); pointer++; } @@ -82,12 +82,12 @@ public class CellPool { Candy[] assignRandomCandytypes() throws JsonParseException { var jp = new JsonParser(); jp.parse(); - var randomCode = new Candy[jp.candies.size() - 2]; //exclude generic types 'fruit' and 'candy' + var randomCode = new Candy[jp.candies.size() - 2]; // exclude generic types 'fruit' and 'candy' var i = 0; for (var e = jp.candies.keys(); e.hasMoreElements(); ) { var s = e.nextElement(); if (!s.equals(FRUIT) && !s.equals(CANDY)) { - //not generic + // not generic randomCode[i] = jp.candies.get(s); i++; } diff --git a/type-object/src/main/java/com/iluwatar/typeobject/JsonParser.java b/type-object/src/main/java/com/iluwatar/typeobject/JsonParser.java index 80d079f29..a7c66bd94 100644 --- a/type-object/src/main/java/com/iluwatar/typeobject/JsonParser.java +++ b/type-object/src/main/java/com/iluwatar/typeobject/JsonParser.java @@ -31,10 +31,7 @@ import com.iluwatar.typeobject.Candy.Type; import java.io.InputStreamReader; import java.util.Hashtable; -/** - * The JsonParser class helps parse the json file candy.json to get all the different candies. - */ - +/** The JsonParser class helps parse the json file candy.json to get all the different candies. */ public class JsonParser { Hashtable candies; @@ -76,5 +73,4 @@ public class JsonParser { } } } - } diff --git a/type-object/src/test/java/com/iluwatar/typeobject/CandyGameTest.java b/type-object/src/test/java/com/iluwatar/typeobject/CandyGameTest.java index 8ae3feb4b..07310771d 100644 --- a/type-object/src/test/java/com/iluwatar/typeobject/CandyGameTest.java +++ b/type-object/src/test/java/com/iluwatar/typeobject/CandyGameTest.java @@ -29,10 +29,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import com.iluwatar.typeobject.Candy.Type; import org.junit.jupiter.api.Test; -/** - * The CandyGameTest class tests the methods in the {@link CandyGame} class. - */ - +/** The CandyGameTest class tests the methods in the {@link CandyGame} class. */ class CandyGameTest { @Test @@ -66,5 +63,4 @@ class CandyGameTest { var noneLeft = cg.continueRound(); assertTrue(fruitInLastRow && matchingCandy && !noneLeft); } - } diff --git a/type-object/src/test/java/com/iluwatar/typeobject/CellPoolTest.java b/type-object/src/test/java/com/iluwatar/typeobject/CellPoolTest.java index 9496db769..ae73fa0f6 100644 --- a/type-object/src/test/java/com/iluwatar/typeobject/CellPoolTest.java +++ b/type-object/src/test/java/com/iluwatar/typeobject/CellPoolTest.java @@ -29,10 +29,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Hashtable; import org.junit.jupiter.api.Test; -/** - * The CellPoolTest class tests the methods in the {@link CellPool} class. - */ - +/** The CellPoolTest class tests the methods in the {@link CellPool} class. */ class CellPoolTest { @Test @@ -48,5 +45,4 @@ class CellPoolTest { } assertTrue(ht.size() == 5 && parentTypes == 0); } - } diff --git a/type-object/src/test/java/com/iluwatar/typeobject/CellTest.java b/type-object/src/test/java/com/iluwatar/typeobject/CellTest.java index 28e51d860..58236f5e6 100644 --- a/type-object/src/test/java/com/iluwatar/typeobject/CellTest.java +++ b/type-object/src/test/java/com/iluwatar/typeobject/CellTest.java @@ -30,9 +30,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import com.iluwatar.typeobject.Candy.Type; import org.junit.jupiter.api.Test; -/** - * The CellTest class tests the methods in the {@link Cell} class. - */ +/** The CellTest class tests the methods in the {@link Cell} class. */ class CellTest { @Test diff --git a/unit-of-work/pom.xml b/unit-of-work/pom.xml index 670c97e8b..357ffdf85 100644 --- a/unit-of-work/pom.xml +++ b/unit-of-work/pom.xml @@ -34,6 +34,14 @@ 4.0.0 unit-of-work + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/unit-of-work/src/main/java/com/iluwatar/unitofwork/App.java b/unit-of-work/src/main/java/com/iluwatar/unitofwork/App.java index ca1bf66db..5713d4144 100644 --- a/unit-of-work/src/main/java/com/iluwatar/unitofwork/App.java +++ b/unit-of-work/src/main/java/com/iluwatar/unitofwork/App.java @@ -25,18 +25,14 @@ package com.iluwatar.unitofwork; import java.util.HashMap; -import java.util.List; -/** - * {@link App} Application demonstrating unit of work pattern. - */ +/** {@link App} Application demonstrating unit of work pattern. */ public class App { /** * Program entry point. * * @param args no argument sent */ - public static void main(String[] args) { // create some weapons var enchantedHammer = new Weapon(1, "enchanted hammer"); @@ -44,8 +40,7 @@ public class App { var silverTrident = new Weapon(3, "silver trident"); // create repository - var weaponRepository = new ArmsDealer(new HashMap<>(), - new WeaponDatabase()); + var weaponRepository = new ArmsDealer(new HashMap<>(), new WeaponDatabase()); // perform operations on the weapons weaponRepository.registerNew(enchantedHammer); diff --git a/unit-of-work/src/main/java/com/iluwatar/unitofwork/ArmsDealer.java b/unit-of-work/src/main/java/com/iluwatar/unitofwork/ArmsDealer.java index 9d10cce7d..c6a05026f 100644 --- a/unit-of-work/src/main/java/com/iluwatar/unitofwork/ArmsDealer.java +++ b/unit-of-work/src/main/java/com/iluwatar/unitofwork/ArmsDealer.java @@ -30,9 +30,7 @@ import java.util.Map; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; -/** - * {@link ArmsDealer} Weapon repository that supports unit of work for weapons. - */ +/** {@link ArmsDealer} Weapon repository that supports unit of work for weapons. */ @Slf4j @RequiredArgsConstructor public class ArmsDealer implements UnitOfWork { @@ -50,7 +48,6 @@ public class ArmsDealer implements UnitOfWork { public void registerModified(Weapon weapon) { LOGGER.info("Registering {} for modify in context.", weapon.getName()); register(weapon, UnitActions.MODIFY.getActionValue()); - } @Override @@ -68,9 +65,7 @@ public class ArmsDealer implements UnitOfWork { context.put(operation, weaponsToOperate); } - /** - * All UnitOfWork operations are batched and executed together on commit only. - */ + /** All UnitOfWork operations are batched and executed together on commit only. */ @Override public void commit() { if (context == null || context.isEmpty()) { diff --git a/unit-of-work/src/main/java/com/iluwatar/unitofwork/UnitActions.java b/unit-of-work/src/main/java/com/iluwatar/unitofwork/UnitActions.java index ce69e9693..d81ea3996 100644 --- a/unit-of-work/src/main/java/com/iluwatar/unitofwork/UnitActions.java +++ b/unit-of-work/src/main/java/com/iluwatar/unitofwork/UnitActions.java @@ -27,9 +27,7 @@ package com.iluwatar.unitofwork; import lombok.Getter; import lombok.RequiredArgsConstructor; -/** - * Enum representing unit actions. - */ +/** Enum representing unit actions. */ @Getter @RequiredArgsConstructor public enum UnitActions { diff --git a/unit-of-work/src/main/java/com/iluwatar/unitofwork/UnitOfWork.java b/unit-of-work/src/main/java/com/iluwatar/unitofwork/UnitOfWork.java index 5b7a9413a..648ec3602 100644 --- a/unit-of-work/src/main/java/com/iluwatar/unitofwork/UnitOfWork.java +++ b/unit-of-work/src/main/java/com/iluwatar/unitofwork/UnitOfWork.java @@ -31,9 +31,7 @@ package com.iluwatar.unitofwork; */ public interface UnitOfWork { - /** - * Any register new operation occurring on UnitOfWork is only going to be performed on commit. - */ + /** Any register new operation occurring on UnitOfWork is only going to be performed on commit. */ void registerNew(T entity); /** @@ -46,9 +44,6 @@ public interface UnitOfWork { */ void registerDeleted(T entity); - /** - * All UnitOfWork operations batched together executed in commit only. - */ + /** All UnitOfWork operations batched together executed in commit only. */ void commit(); - -} \ No newline at end of file +} diff --git a/unit-of-work/src/main/java/com/iluwatar/unitofwork/Weapon.java b/unit-of-work/src/main/java/com/iluwatar/unitofwork/Weapon.java index d91e73e20..5ceb55ad9 100644 --- a/unit-of-work/src/main/java/com/iluwatar/unitofwork/Weapon.java +++ b/unit-of-work/src/main/java/com/iluwatar/unitofwork/Weapon.java @@ -27,9 +27,7 @@ package com.iluwatar.unitofwork; import lombok.Getter; import lombok.RequiredArgsConstructor; -/** - * {@link Weapon} is an entity. - */ +/** {@link Weapon} is an entity. */ @Getter @RequiredArgsConstructor public class Weapon { diff --git a/unit-of-work/src/main/java/com/iluwatar/unitofwork/WeaponDatabase.java b/unit-of-work/src/main/java/com/iluwatar/unitofwork/WeaponDatabase.java index d6c5422c0..4ea15d46b 100644 --- a/unit-of-work/src/main/java/com/iluwatar/unitofwork/WeaponDatabase.java +++ b/unit-of-work/src/main/java/com/iluwatar/unitofwork/WeaponDatabase.java @@ -24,20 +24,18 @@ */ package com.iluwatar.unitofwork; -/** - * Act as database for weapon records. - */ +/** Act as database for weapon records. */ public class WeaponDatabase { public void insert(Weapon weapon) { - //Some insert logic to DB + // Some insert logic to DB } public void modify(Weapon weapon) { - //Some modify logic to DB + // Some modify logic to DB } public void delete(Weapon weapon) { - //Some delete logic to DB + // Some delete logic to DB } } diff --git a/unit-of-work/src/test/java/com/iluwatar/unitofwork/AppTest.java b/unit-of-work/src/test/java/com/iluwatar/unitofwork/AppTest.java index 342035db7..6f4557698 100644 --- a/unit-of-work/src/test/java/com/iluwatar/unitofwork/AppTest.java +++ b/unit-of-work/src/test/java/com/iluwatar/unitofwork/AppTest.java @@ -28,13 +28,11 @@ import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import org.junit.jupiter.api.Test; -/** - * AppTest - */ +/** AppTest */ class AppTest { @Test void shouldExecuteWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/unit-of-work/src/test/java/com/iluwatar/unitofwork/ArmsDealerTest.java b/unit-of-work/src/test/java/com/iluwatar/unitofwork/ArmsDealerTest.java index b4d93d99d..da06e2d76 100644 --- a/unit-of-work/src/test/java/com/iluwatar/unitofwork/ArmsDealerTest.java +++ b/unit-of-work/src/test/java/com/iluwatar/unitofwork/ArmsDealerTest.java @@ -36,10 +36,7 @@ import java.util.List; import java.util.Map; import org.junit.jupiter.api.Test; -/** - * tests {@link ArmsDealer} - */ - +/** tests {@link ArmsDealer} */ class ArmsDealerTest { private final Weapon weapon1 = new Weapon(1, "battle ram"); private final Weapon weapon2 = new Weapon(1, "wooden lance"); diff --git a/update-method/pom.xml b/update-method/pom.xml index 84e0c7664..c48003975 100644 --- a/update-method/pom.xml +++ b/update-method/pom.xml @@ -34,6 +34,14 @@ 4.0.0 update-method + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/update-method/src/main/java/com/iluwatar/updatemethod/App.java b/update-method/src/main/java/com/iluwatar/updatemethod/App.java index 9d9456d31..f51538842 100644 --- a/update-method/src/main/java/com/iluwatar/updatemethod/App.java +++ b/update-method/src/main/java/com/iluwatar/updatemethod/App.java @@ -27,10 +27,10 @@ package com.iluwatar.updatemethod; import lombok.extern.slf4j.Slf4j; /** - * This pattern simulate a collection of independent objects by telling each to - * process one frame of behavior at a time. The game world maintains a collection - * of objects. Each object implements an update method that simulates one frame of - * the object’s behavior. Each frame, the game updates every object in the collection. + * This pattern simulate a collection of independent objects by telling each to process one frame of + * behavior at a time. The game world maintains a collection of objects. Each object implements an + * update method that simulates one frame of the object’s behavior. Each frame, the game updates + * every object in the collection. */ @Slf4j public class App { @@ -39,6 +39,7 @@ public class App { /** * Program entry point. + * * @param args runtime arguments */ public static void main(String[] args) { diff --git a/update-method/src/main/java/com/iluwatar/updatemethod/Entity.java b/update-method/src/main/java/com/iluwatar/updatemethod/Entity.java index f7a8a0ff3..02de2638e 100644 --- a/update-method/src/main/java/com/iluwatar/updatemethod/Entity.java +++ b/update-method/src/main/java/com/iluwatar/updatemethod/Entity.java @@ -29,18 +29,14 @@ import lombok.Setter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -/** - * Abstract class for all the entity types. - */ +/** Abstract class for all the entity types. */ public abstract class Entity { protected final Logger logger = LoggerFactory.getLogger(this.getClass()); protected int id; - @Getter - @Setter - protected int position; + @Getter @Setter protected int position; public Entity(int id) { this.id = id; @@ -48,5 +44,4 @@ public abstract class Entity { } public abstract void update(); - } diff --git a/update-method/src/main/java/com/iluwatar/updatemethod/Skeleton.java b/update-method/src/main/java/com/iluwatar/updatemethod/Skeleton.java index f6e6f25d4..26d861d78 100644 --- a/update-method/src/main/java/com/iluwatar/updatemethod/Skeleton.java +++ b/update-method/src/main/java/com/iluwatar/updatemethod/Skeleton.java @@ -25,10 +25,9 @@ package com.iluwatar.updatemethod; /** - * Skeletons are always patrolling on the game map. Initially all the skeletons - * patrolling to the right, and after them reach the bounding, it will start - * patrolling to the left. For each frame, one skeleton will move 1 position - * step. + * Skeletons are always patrolling on the game map. Initially all the skeletons patrolling to the + * right, and after them reach the bounding, it will start patrolling to the left. For each frame, + * one skeleton will move 1 position step. */ public class Skeleton extends Entity { @@ -76,4 +75,3 @@ public class Skeleton extends Entity { logger.info("Skeleton {} is on position {}.", id, position); } } - diff --git a/update-method/src/main/java/com/iluwatar/updatemethod/Statue.java b/update-method/src/main/java/com/iluwatar/updatemethod/Statue.java index 7212a7a1b..d67baf2d0 100644 --- a/update-method/src/main/java/com/iluwatar/updatemethod/Statue.java +++ b/update-method/src/main/java/com/iluwatar/updatemethod/Statue.java @@ -24,9 +24,7 @@ */ package com.iluwatar.updatemethod; -/** - * Statues shoot lightning at regular intervals. - */ +/** Statues shoot lightning at regular intervals. */ public class Statue extends Entity { protected int frames; diff --git a/update-method/src/main/java/com/iluwatar/updatemethod/World.java b/update-method/src/main/java/com/iluwatar/updatemethod/World.java index d67f97e0d..ef93c82f8 100644 --- a/update-method/src/main/java/com/iluwatar/updatemethod/World.java +++ b/update-method/src/main/java/com/iluwatar/updatemethod/World.java @@ -29,9 +29,7 @@ import java.util.ArrayList; import java.util.List; import lombok.extern.slf4j.Slf4j; -/** - * The game world class. Maintain all the objects existed in the game frames. - */ +/** The game world class. Maintain all the objects existed in the game frames. */ @Slf4j public class World { @@ -45,9 +43,9 @@ public class World { } /** - * Main game loop. This loop will always run until the game is over. For - * each loop it will process user input, update internal status, and render - * the next frames. For more detail please refer to the game-loop pattern. + * Main game loop. This loop will always run until the game is over. For each loop it will process + * user input, update internal status, and render the next frames. For more detail please refer to + * the game-loop pattern. */ private void gameLoop() { while (isRunning) { @@ -58,9 +56,8 @@ public class World { } /** - * Handle any user input that has happened since the last call. In order to - * simulate the situation in real-life game, here we add a random time lag. - * The time lag ranges from 50 ms to 250 ms. + * Handle any user input that has happened since the last call. In order to simulate the situation + * in real-life game, here we add a random time lag. The time lag ranges from 50 ms to 250 ms. */ private void processInput() { try { @@ -73,8 +70,8 @@ public class World { } /** - * Update internal status. The update method pattern invoke update method for - * each entity in the game. + * Update internal status. The update method pattern invoke update method for each entity in the + * game. */ private void update() { for (var entity : entities) { @@ -82,17 +79,12 @@ public class World { } } - /** - * Render the next frame. Here we do nothing since it is not related to the - * pattern. - */ + /** Render the next frame. Here we do nothing since it is not related to the pattern. */ private void render() { // Does Nothing } - /** - * Run game loop. - */ + /** Run game loop. */ public void run() { LOGGER.info("Start game."); isRunning = true; @@ -100,9 +92,7 @@ public class World { thread.start(); } - /** - * Stop game loop. - */ + /** Stop game loop. */ public void stop() { LOGGER.info("Stop game."); isRunning = false; @@ -111,5 +101,4 @@ public class World { public void addEntity(Entity entity) { entities.add(entity); } - } diff --git a/update-method/src/test/java/com/iluwatar/updatemethod/AppTest.java b/update-method/src/test/java/com/iluwatar/updatemethod/AppTest.java index e684cfef0..53a9d2334 100644 --- a/update-method/src/test/java/com/iluwatar/updatemethod/AppTest.java +++ b/update-method/src/test/java/com/iluwatar/updatemethod/AppTest.java @@ -32,6 +32,6 @@ class AppTest { @Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/update-method/src/test/java/com/iluwatar/updatemethod/SkeletonTest.java b/update-method/src/test/java/com/iluwatar/updatemethod/SkeletonTest.java index c5672ae95..6f602245a 100644 --- a/update-method/src/test/java/com/iluwatar/updatemethod/SkeletonTest.java +++ b/update-method/src/test/java/com/iluwatar/updatemethod/SkeletonTest.java @@ -24,14 +24,14 @@ */ package com.iluwatar.updatemethod; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + class SkeletonTest { private static Skeleton skeleton; diff --git a/update-method/src/test/java/com/iluwatar/updatemethod/StatueTest.java b/update-method/src/test/java/com/iluwatar/updatemethod/StatueTest.java index 7df1b9755..45b062d53 100644 --- a/update-method/src/test/java/com/iluwatar/updatemethod/StatueTest.java +++ b/update-method/src/test/java/com/iluwatar/updatemethod/StatueTest.java @@ -24,12 +24,12 @@ */ package com.iluwatar.updatemethod; +import static org.junit.jupiter.api.Assertions.assertEquals; + import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; - class StatueTest { private static Statue statue; diff --git a/update-method/src/test/java/com/iluwatar/updatemethod/WorldTest.java b/update-method/src/test/java/com/iluwatar/updatemethod/WorldTest.java index d4284d801..3c94d5dd5 100644 --- a/update-method/src/test/java/com/iluwatar/updatemethod/WorldTest.java +++ b/update-method/src/test/java/com/iluwatar/updatemethod/WorldTest.java @@ -24,14 +24,14 @@ */ package com.iluwatar.updatemethod; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + class WorldTest { private static World world; diff --git a/value-object/pom.xml b/value-object/pom.xml index 2ffba3b64..b8b2d3433 100644 --- a/value-object/pom.xml +++ b/value-object/pom.xml @@ -34,6 +34,14 @@ value-object + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/value-object/src/main/java/com/iluwatar/value/object/App.java b/value-object/src/main/java/com/iluwatar/value/object/App.java index 03add5a89..0082fae44 100644 --- a/value-object/src/main/java/com/iluwatar/value/object/App.java +++ b/value-object/src/main/java/com/iluwatar/value/object/App.java @@ -43,9 +43,7 @@ import lombok.extern.slf4j.Slf4j; @Slf4j public class App { - /** - * This example creates three HeroStats (value objects) and checks equality between those. - */ + /** This example creates three HeroStats (value objects) and checks equality between those. */ public static void main(String[] args) { var statA = HeroStat.valueOf(10, 5, 0); var statB = HeroStat.valueOf(10, 5, 0); diff --git a/value-object/src/main/java/com/iluwatar/value/object/HeroStat.java b/value-object/src/main/java/com/iluwatar/value/object/HeroStat.java index a639e741f..fbeeadd75 100644 --- a/value-object/src/main/java/com/iluwatar/value/object/HeroStat.java +++ b/value-object/src/main/java/com/iluwatar/value/object/HeroStat.java @@ -31,8 +31,7 @@ import lombok.Value; * HeroStat is a value object. * * @see - * http://docs.oracle.com/javase/8/docs/api/java/lang/doc-files/ValueBased.html - * + * http://docs.oracle.com/javase/8/docs/api/java/lang/doc-files/ValueBased.html */ @Value(staticConstructor = "valueOf") @ToString diff --git a/value-object/src/test/java/com/iluwatar/value/object/AppTest.java b/value-object/src/test/java/com/iluwatar/value/object/AppTest.java index a0a76eac2..8e957df0c 100644 --- a/value-object/src/test/java/com/iluwatar/value/object/AppTest.java +++ b/value-object/src/test/java/com/iluwatar/value/object/AppTest.java @@ -24,17 +24,15 @@ */ package com.iluwatar.value.object; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -/** - * Application test - */ +import org.junit.jupiter.api.Test; + +/** Application test */ class AppTest { @Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/value-object/src/test/java/com/iluwatar/value/object/HeroStatTest.java b/value-object/src/test/java/com/iluwatar/value/object/HeroStatTest.java index 82c66322d..fe3238b3f 100644 --- a/value-object/src/test/java/com/iluwatar/value/object/HeroStatTest.java +++ b/value-object/src/test/java/com/iluwatar/value/object/HeroStatTest.java @@ -29,17 +29,16 @@ import static org.junit.jupiter.api.Assertions.assertNotEquals; import org.junit.jupiter.api.Test; -/** - * Unit test for HeroStat. - */ +/** Unit test for HeroStat. */ class HeroStatTest { /** * Tester for equals() and hashCode() methods of a class. Using guava's EqualsTester. * - * @see - * http://static.javadoc.io/com.google.guava/guava-testlib/19.0/com/google/common/testing/EqualsTester.html - * + * @see + * http://static.javadoc.io/com.google.guava/guava-testlib/19.0/com/google/common/testing/EqualsTester.html + * */ @Test void testEquals() { @@ -60,5 +59,4 @@ class HeroStatTest { assertEquals(heroStatA.toString(), heroStatB.toString()); assertNotEquals(heroStatA.toString(), heroStatC.toString()); } - } diff --git a/version-number/pom.xml b/version-number/pom.xml index 54128114e..d3fab29bd 100644 --- a/version-number/pom.xml +++ b/version-number/pom.xml @@ -34,6 +34,14 @@ version-number + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/version-number/src/main/java/com/iluwatar/versionnumber/App.java b/version-number/src/main/java/com/iluwatar/versionnumber/App.java index 8b1818e29..98e12228c 100644 --- a/version-number/src/main/java/com/iluwatar/versionnumber/App.java +++ b/version-number/src/main/java/com/iluwatar/versionnumber/App.java @@ -28,16 +28,15 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * The Version Number pattern helps to resolve concurrency conflicts in applications. - * Usually these conflicts arise in database operations, when multiple clients are trying - * to update the same record simultaneously. - * Resolving such conflicts requires determining whether an object has changed. - * For this reason we need a version number that is incremented with each change - * to the underlying data, e.g. database. The version number can be used by repositories - * to check for external changes and to report concurrency issues to the users. + * The Version Number pattern helps to resolve concurrency conflicts in applications. Usually these + * conflicts arise in database operations, when multiple clients are trying to update the same + * record simultaneously. Resolving such conflicts requires determining whether an object has + * changed. For this reason we need a version number that is incremented with each change to the + * underlying data, e.g. database. The version number can be used by repositories to check for + * external changes and to report concurrency issues to the users. * - *

In this example we show how Alice and Bob will try to update the {@link Book} - * and save it simultaneously to {@link BookRepository}, which represents a typical database. + *

In this example we show how Alice and Bob will try to update the {@link Book} and save it + * simultaneously to {@link BookRepository}, which represents a typical database. * *

As in real databases, each client operates with copy of the data instead of original data * passed by reference, that's why we are using {@link Book} copy-constructor here. @@ -50,10 +49,8 @@ public class App { * * @param args command line args */ - public static void main(String[] args) throws - BookDuplicateException, - BookNotFoundException, - VersionMismatchException { + public static void main(String[] args) + throws BookDuplicateException, BookNotFoundException, VersionMismatchException { var bookId = 1; var bookRepository = new BookRepository(); diff --git a/version-number/src/main/java/com/iluwatar/versionnumber/Book.java b/version-number/src/main/java/com/iluwatar/versionnumber/Book.java index 774ceac67..067e08291 100644 --- a/version-number/src/main/java/com/iluwatar/versionnumber/Book.java +++ b/version-number/src/main/java/com/iluwatar/versionnumber/Book.java @@ -27,9 +27,7 @@ package com.iluwatar.versionnumber; import lombok.Getter; import lombok.Setter; -/** - * Model class for Book entity. - */ +/** Model class for Book entity. */ @Getter @Setter public class Book { @@ -40,9 +38,7 @@ public class Book { public Book() {} - /** - * We need this copy constructor to copy book representation in {@link BookRepository}. - */ + /** We need this copy constructor to copy book representation in {@link BookRepository}. */ public Book(Book book) { this.id = book.id; this.title = book.title; diff --git a/version-number/src/main/java/com/iluwatar/versionnumber/BookDuplicateException.java b/version-number/src/main/java/com/iluwatar/versionnumber/BookDuplicateException.java index 9763e1fa5..7651a7bb5 100644 --- a/version-number/src/main/java/com/iluwatar/versionnumber/BookDuplicateException.java +++ b/version-number/src/main/java/com/iluwatar/versionnumber/BookDuplicateException.java @@ -24,9 +24,7 @@ */ package com.iluwatar.versionnumber; -/** - * When someone has tried to add a book which repository already have. - */ +/** When someone has tried to add a book which repository already have. */ public class BookDuplicateException extends Exception { public BookDuplicateException(String message) { super(message); diff --git a/version-number/src/main/java/com/iluwatar/versionnumber/BookNotFoundException.java b/version-number/src/main/java/com/iluwatar/versionnumber/BookNotFoundException.java index 9f45ad0cb..deceebdd1 100644 --- a/version-number/src/main/java/com/iluwatar/versionnumber/BookNotFoundException.java +++ b/version-number/src/main/java/com/iluwatar/versionnumber/BookNotFoundException.java @@ -24,9 +24,7 @@ */ package com.iluwatar.versionnumber; -/** - * Client has tried to make an operation with book which repository does not have. - */ +/** Client has tried to make an operation with book which repository does not have. */ public class BookNotFoundException extends Exception { public BookNotFoundException(String message) { super(message); diff --git a/version-number/src/main/java/com/iluwatar/versionnumber/BookRepository.java b/version-number/src/main/java/com/iluwatar/versionnumber/BookRepository.java index a1baa3665..087b28934 100644 --- a/version-number/src/main/java/com/iluwatar/versionnumber/BookRepository.java +++ b/version-number/src/main/java/com/iluwatar/versionnumber/BookRepository.java @@ -27,18 +27,17 @@ package com.iluwatar.versionnumber; import java.util.concurrent.ConcurrentHashMap; /** - * This repository represents simplified database. - * As a typical database do, repository operates with copies of object. - * So client and repo has different copies of book, which can lead to concurrency conflicts - * as much as in real databases. + * This repository represents simplified database. As a typical database do, repository operates + * with copies of object. So client and repo has different copies of book, which can lead to + * concurrency conflicts as much as in real databases. */ public class BookRepository { private final ConcurrentHashMap collection = new ConcurrentHashMap<>(); private final Object lock = new Object(); /** - * Adds book to collection. - * Actually we are putting copy of book (saving a book by value, not by reference); + * Adds book to collection. Actually we are putting copy of book (saving a book by value, not by + * reference); */ public void add(Book book) throws BookDuplicateException { if (collection.containsKey(book.getId())) { @@ -49,9 +48,7 @@ public class BookRepository { collection.put(book.getId(), new Book(book)); } - /** - * Updates book in collection only if client has modified the latest version of the book. - */ + /** Updates book in collection only if client has modified the latest version of the book. */ public void update(Book book) throws BookNotFoundException, VersionMismatchException { if (!collection.containsKey(book.getId())) { throw new BookNotFoundException("Not found book with id: " + book.getId()); @@ -62,9 +59,10 @@ public class BookRepository { var latestBook = collection.get(book.getId()); if (book.getVersion() != latestBook.getVersion()) { throw new VersionMismatchException( - "Tried to update stale version " + book.getVersion() - + " while actual version is " + latestBook.getVersion() - ); + "Tried to update stale version " + + book.getVersion() + + " while actual version is " + + latestBook.getVersion()); } // update version, including client representation - modify by reference here @@ -76,8 +74,8 @@ public class BookRepository { } /** - * Returns book representation to the client. - * Representation means we are returning copy of the book. + * Returns book representation to the client. Representation means we are returning copy of the + * book. */ public Book get(long bookId) throws BookNotFoundException { if (!collection.containsKey(bookId)) { diff --git a/version-number/src/main/java/com/iluwatar/versionnumber/VersionMismatchException.java b/version-number/src/main/java/com/iluwatar/versionnumber/VersionMismatchException.java index da4d29162..68d878333 100644 --- a/version-number/src/main/java/com/iluwatar/versionnumber/VersionMismatchException.java +++ b/version-number/src/main/java/com/iluwatar/versionnumber/VersionMismatchException.java @@ -24,9 +24,7 @@ */ package com.iluwatar.versionnumber; -/** - * Client has tried to update a stale version of the book. - */ +/** Client has tried to update a stale version of the book. */ public class VersionMismatchException extends Exception { public VersionMismatchException(String message) { super(message); diff --git a/version-number/src/test/java/com/iluwatar/versionnumber/AppTest.java b/version-number/src/test/java/com/iluwatar/versionnumber/AppTest.java index a47da0e83..640fd9533 100644 --- a/version-number/src/test/java/com/iluwatar/versionnumber/AppTest.java +++ b/version-number/src/test/java/com/iluwatar/versionnumber/AppTest.java @@ -24,24 +24,21 @@ */ package com.iluwatar.versionnumber; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -/** - * Application test - */ +import org.junit.jupiter.api.Test; + +/** Application test */ class AppTest { /** * Issue: Add at least one assertion to this test case. * - * Solution: Inserted assertion to check whether the execution of the main method in {@link App#main(String[])} - * throws an exception. + *

Solution: Inserted assertion to check whether the execution of the main method in {@link + * App#main(String[])} throws an exception. */ - @Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/version-number/src/test/java/com/iluwatar/versionnumber/BookRepositoryTest.java b/version-number/src/test/java/com/iluwatar/versionnumber/BookRepositoryTest.java index b480cfd41..f97e67150 100644 --- a/version-number/src/test/java/com/iluwatar/versionnumber/BookRepositoryTest.java +++ b/version-number/src/test/java/com/iluwatar/versionnumber/BookRepositoryTest.java @@ -24,14 +24,12 @@ */ package com.iluwatar.versionnumber; +import static org.junit.jupiter.api.Assertions.*; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.*; - -/** - * Tests for {@link BookRepository} - */ +/** Tests for {@link BookRepository} */ class BookRepositoryTest { private final long bookId = 1; private final BookRepository bookRepository = new BookRepository(); @@ -50,7 +48,8 @@ class BookRepositoryTest { } @Test - void testAliceAndBobHaveDifferentVersionsAfterAliceUpdate() throws BookNotFoundException, VersionMismatchException { + void testAliceAndBobHaveDifferentVersionsAfterAliceUpdate() + throws BookNotFoundException, VersionMismatchException { final var aliceBook = bookRepository.get(bookId); final var bobBook = bookRepository.get(bookId); @@ -66,7 +65,8 @@ class BookRepositoryTest { } @Test - void testShouldThrowVersionMismatchExceptionOnStaleUpdate() throws BookNotFoundException, VersionMismatchException { + void testShouldThrowVersionMismatchExceptionOnStaleUpdate() + throws BookNotFoundException, VersionMismatchException { final var aliceBook = bookRepository.get(bookId); final var bobBook = bookRepository.get(bookId); diff --git a/virtual-proxy/pom.xml b/virtual-proxy/pom.xml index 8f3fbc8f2..d9cf174f9 100644 --- a/virtual-proxy/pom.xml +++ b/virtual-proxy/pom.xml @@ -35,6 +35,14 @@ virtual-proxy + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine @@ -46,8 +54,9 @@ test - junit - junit + org.hamcrest + hamcrest + 3.0 test diff --git a/virtual-proxy/src/main/java/com/iluwatar/virtual/proxy/App.java b/virtual-proxy/src/main/java/com/iluwatar/virtual/proxy/App.java index b29d6fd99..3f78bfe81 100644 --- a/virtual-proxy/src/main/java/com/iluwatar/virtual/proxy/App.java +++ b/virtual-proxy/src/main/java/com/iluwatar/virtual/proxy/App.java @@ -25,9 +25,7 @@ package com.iluwatar.virtual.proxy; -/** - * The main application class that sets up and runs the Virtual Proxy pattern demo. - */ +/** The main application class that sets up and runs the Virtual Proxy pattern demo. */ public class App { /** * The entry point of the application. @@ -36,7 +34,7 @@ public class App { */ public static void main(String[] args) { ExpensiveObject videoObject = new VideoObjectProxy(); - videoObject.process(); // The first call creates and plays the video - videoObject.process(); // Subsequent call uses the already created object + videoObject.process(); // The first call creates and plays the video + videoObject.process(); // Subsequent call uses the already created object } -} \ No newline at end of file +} diff --git a/virtual-proxy/src/main/java/com/iluwatar/virtual/proxy/ExpensiveObject.java b/virtual-proxy/src/main/java/com/iluwatar/virtual/proxy/ExpensiveObject.java index b5474e161..12e183b4e 100644 --- a/virtual-proxy/src/main/java/com/iluwatar/virtual/proxy/ExpensiveObject.java +++ b/virtual-proxy/src/main/java/com/iluwatar/virtual/proxy/ExpensiveObject.java @@ -24,9 +24,7 @@ */ package com.iluwatar.virtual.proxy; -/** - * Interface for expensive object and proxy object. - */ +/** Interface for expensive object and proxy object. */ public interface ExpensiveObject { void process(); -} \ No newline at end of file +} diff --git a/virtual-proxy/src/main/java/com/iluwatar/virtual/proxy/RealVideoObject.java b/virtual-proxy/src/main/java/com/iluwatar/virtual/proxy/RealVideoObject.java index dbdd4353f..afadf1df6 100644 --- a/virtual-proxy/src/main/java/com/iluwatar/virtual/proxy/RealVideoObject.java +++ b/virtual-proxy/src/main/java/com/iluwatar/virtual/proxy/RealVideoObject.java @@ -28,9 +28,7 @@ package com.iluwatar.virtual.proxy; import lombok.Getter; import lombok.extern.slf4j.Slf4j; -/** - * Represents a real video object that is expensive to create and manage. - */ +/** Represents a real video object that is expensive to create and manage. */ @Slf4j @Getter public class RealVideoObject implements ExpensiveObject { @@ -47,4 +45,4 @@ public class RealVideoObject implements ExpensiveObject { public void process() { LOGGER.info("Processing and playing video content..."); } -} \ No newline at end of file +} diff --git a/virtual-proxy/src/main/java/com/iluwatar/virtual/proxy/VideoObjectProxy.java b/virtual-proxy/src/main/java/com/iluwatar/virtual/proxy/VideoObjectProxy.java index 52b0e5f3f..9138fc95b 100644 --- a/virtual-proxy/src/main/java/com/iluwatar/virtual/proxy/VideoObjectProxy.java +++ b/virtual-proxy/src/main/java/com/iluwatar/virtual/proxy/VideoObjectProxy.java @@ -28,7 +28,8 @@ package com.iluwatar.virtual.proxy; import lombok.Getter; /** - * A proxy class for the real video object, providing a layer of control over the object instantiation. + * A proxy class for the real video object, providing a layer of control over the object + * instantiation. */ @Getter public class VideoObjectProxy implements ExpensiveObject { @@ -41,4 +42,4 @@ public class VideoObjectProxy implements ExpensiveObject { } realVideoObject.process(); } -} \ No newline at end of file +} diff --git a/virtual-proxy/src/test/java/com/iluwatar/virtual/proxy/AppTest.java b/virtual-proxy/src/test/java/com/iluwatar/virtual/proxy/AppTest.java index 1f7cf8b6d..b4b424e94 100644 --- a/virtual-proxy/src/test/java/com/iluwatar/virtual/proxy/AppTest.java +++ b/virtual-proxy/src/test/java/com/iluwatar/virtual/proxy/AppTest.java @@ -25,17 +25,15 @@ package com.iluwatar.virtual.proxy; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -/** - * Application test - */ +import org.junit.jupiter.api.Test; + +/** Application test */ class AppTest { @Test void shouldExecuteApplicationWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } -} \ No newline at end of file +} diff --git a/virtual-proxy/src/test/java/com/iluwatar/virtual/proxy/RealVideoObjectTest.java b/virtual-proxy/src/test/java/com/iluwatar/virtual/proxy/RealVideoObjectTest.java index 90f203556..d3d471ad0 100644 --- a/virtual-proxy/src/test/java/com/iluwatar/virtual/proxy/RealVideoObjectTest.java +++ b/virtual-proxy/src/test/java/com/iluwatar/virtual/proxy/RealVideoObjectTest.java @@ -23,15 +23,14 @@ * THE SOFTWARE. */ package com.iluwatar.virtual.proxy; + import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.instanceOf; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import org.junit.jupiter.api.Test; -/** - * Tests for RealVideoObject. - */ +/** Tests for RealVideoObject. */ class RealVideoObjectTest { @Test @@ -50,4 +49,4 @@ class RealVideoObjectTest { RealVideoObject realVideoObject = new RealVideoObject(); assertDoesNotThrow(realVideoObject::process, "Process method should not throw any exception"); } -} \ No newline at end of file +} diff --git a/virtual-proxy/src/test/java/com/iluwatar/virtual/proxy/VideoObjectProxyTest.java b/virtual-proxy/src/test/java/com/iluwatar/virtual/proxy/VideoObjectProxyTest.java index 2ede2c8a4..7d91b7c39 100644 --- a/virtual-proxy/src/test/java/com/iluwatar/virtual/proxy/VideoObjectProxyTest.java +++ b/virtual-proxy/src/test/java/com/iluwatar/virtual/proxy/VideoObjectProxyTest.java @@ -31,9 +31,7 @@ import static org.junit.jupiter.api.Assertions.*; import org.hamcrest.MatcherAssert; import org.junit.jupiter.api.Test; -/** - * Tests for VideoObjectProxy. - */ +/** Tests for VideoObjectProxy. */ public class VideoObjectProxyTest { @Test void shouldBeInstanceOfExpensiveObject() { @@ -47,7 +45,7 @@ public class VideoObjectProxyTest { @Test void processDoesNotThrowException() { - assertDoesNotThrow(() -> new VideoObjectProxy().process(), "Process method should not throw any exception"); + assertDoesNotThrow( + () -> new VideoObjectProxy().process(), "Process method should not throw any exception"); } - -} \ No newline at end of file +} diff --git a/visitor/pom.xml b/visitor/pom.xml index 5825b7dbd..480fafd03 100644 --- a/visitor/pom.xml +++ b/visitor/pom.xml @@ -34,6 +34,14 @@ visitor + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + org.junit.jupiter junit-jupiter-engine diff --git a/visitor/src/main/java/com/iluwatar/visitor/App.java b/visitor/src/main/java/com/iluwatar/visitor/App.java index 6023649e6..61c91fbb3 100644 --- a/visitor/src/main/java/com/iluwatar/visitor/App.java +++ b/visitor/src/main/java/com/iluwatar/visitor/App.java @@ -25,12 +25,12 @@ package com.iluwatar.visitor; /** - *

Visitor pattern defines a mechanism to apply operations on nodes in a hierarchy. New - * operations can be added without altering the node interface.

+ * Visitor pattern defines a mechanism to apply operations on nodes in a hierarchy. New operations + * can be added without altering the node interface. * *

In this example there is a unit hierarchy beginning from {@link Commander}. This hierarchy is * traversed by visitors. {@link SoldierVisitor} applies its operation on {@link Soldier}s, {@link - * SergeantVisitor} on {@link Sergeant}s and so on.

+ * SergeantVisitor} on {@link Sergeant}s and so on. */ public class App { @@ -41,10 +41,10 @@ public class App { */ public static void main(String[] args) { - var commander = new Commander( - new Sergeant(new Soldier(), new Soldier(), new Soldier()), - new Sergeant(new Soldier(), new Soldier(), new Soldier()) - ); + var commander = + new Commander( + new Sergeant(new Soldier(), new Soldier(), new Soldier()), + new Sergeant(new Soldier(), new Soldier(), new Soldier())); commander.accept(new SoldierVisitor()); commander.accept(new SergeantVisitor()); commander.accept(new CommanderVisitor()); diff --git a/visitor/src/main/java/com/iluwatar/visitor/Commander.java b/visitor/src/main/java/com/iluwatar/visitor/Commander.java index 01c8a43ba..b6d2af80d 100644 --- a/visitor/src/main/java/com/iluwatar/visitor/Commander.java +++ b/visitor/src/main/java/com/iluwatar/visitor/Commander.java @@ -1,50 +1,49 @@ -/* - * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). - * - * The MIT License - * Copyright © 2014-2022 Ilkka Seppälä - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package com.iluwatar.visitor; - -/** - * Commander. - */ -public class Commander extends Unit { - - public Commander(Unit... children) { - super(children); - } - - /** - * Accept a Visitor. - * @param visitor UnitVisitor to be accepted - */ - @Override - public void accept(UnitVisitor visitor) { - visitor.visit(this); - super.accept(visitor); - } - - @Override - public String toString() { - return "commander"; - } -} +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.visitor; + +/** Commander. */ +public class Commander extends Unit { + + public Commander(Unit... children) { + super(children); + } + + /** + * Accept a Visitor. + * + * @param visitor UnitVisitor to be accepted + */ + @Override + public void accept(UnitVisitor visitor) { + visitor.visit(this); + super.accept(visitor); + } + + @Override + public String toString() { + return "commander"; + } +} diff --git a/visitor/src/main/java/com/iluwatar/visitor/CommanderVisitor.java b/visitor/src/main/java/com/iluwatar/visitor/CommanderVisitor.java index a0286163a..326d28764 100644 --- a/visitor/src/main/java/com/iluwatar/visitor/CommanderVisitor.java +++ b/visitor/src/main/java/com/iluwatar/visitor/CommanderVisitor.java @@ -1,61 +1,62 @@ -/* - * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). - * - * The MIT License - * Copyright © 2014-2022 Ilkka Seppälä - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package com.iluwatar.visitor; - -import lombok.extern.slf4j.Slf4j; - -/** - * CommanderVisitor. - */ -@Slf4j -public class CommanderVisitor implements UnitVisitor { - - /** - * Soldier Visitor method. - * @param soldier Soldier to be visited - */ - @Override - public void visit(Soldier soldier) { - // Do nothing - } - - /** - * Sergeant Visitor method. - * @param sergeant Sergeant to be visited - */ - @Override - public void visit(Sergeant sergeant) { - // Do nothing - } - - /** - * Commander Visitor method. - * @param commander Commander to be visited - */ - @Override - public void visit(Commander commander) { - LOGGER.info("Good to see you {}", commander); - } -} +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.visitor; + +import lombok.extern.slf4j.Slf4j; + +/** CommanderVisitor. */ +@Slf4j +public class CommanderVisitor implements UnitVisitor { + + /** + * Soldier Visitor method. + * + * @param soldier Soldier to be visited + */ + @Override + public void visit(Soldier soldier) { + // Do nothing + } + + /** + * Sergeant Visitor method. + * + * @param sergeant Sergeant to be visited + */ + @Override + public void visit(Sergeant sergeant) { + // Do nothing + } + + /** + * Commander Visitor method. + * + * @param commander Commander to be visited + */ + @Override + public void visit(Commander commander) { + LOGGER.info("Good to see you {}", commander); + } +} diff --git a/visitor/src/main/java/com/iluwatar/visitor/Sergeant.java b/visitor/src/main/java/com/iluwatar/visitor/Sergeant.java index ed9fc98b5..11ef218b2 100644 --- a/visitor/src/main/java/com/iluwatar/visitor/Sergeant.java +++ b/visitor/src/main/java/com/iluwatar/visitor/Sergeant.java @@ -1,50 +1,49 @@ -/* - * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). - * - * The MIT License - * Copyright © 2014-2022 Ilkka Seppälä - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package com.iluwatar.visitor; - -/** - * Sergeant. - */ -public class Sergeant extends Unit { - - public Sergeant(Unit... children) { - super(children); - } - - /** - * Accept a Visitor. - * @param visitor UnitVisitor to be accepted - */ - @Override - public void accept(UnitVisitor visitor) { - visitor.visit(this); - super.accept(visitor); - } - - @Override - public String toString() { - return "sergeant"; - } -} +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.visitor; + +/** Sergeant. */ +public class Sergeant extends Unit { + + public Sergeant(Unit... children) { + super(children); + } + + /** + * Accept a Visitor. + * + * @param visitor UnitVisitor to be accepted + */ + @Override + public void accept(UnitVisitor visitor) { + visitor.visit(this); + super.accept(visitor); + } + + @Override + public String toString() { + return "sergeant"; + } +} diff --git a/visitor/src/main/java/com/iluwatar/visitor/SergeantVisitor.java b/visitor/src/main/java/com/iluwatar/visitor/SergeantVisitor.java index 3377806b9..09f4fd4bb 100644 --- a/visitor/src/main/java/com/iluwatar/visitor/SergeantVisitor.java +++ b/visitor/src/main/java/com/iluwatar/visitor/SergeantVisitor.java @@ -1,61 +1,62 @@ -/* - * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). - * - * The MIT License - * Copyright © 2014-2022 Ilkka Seppälä - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package com.iluwatar.visitor; - -import lombok.extern.slf4j.Slf4j; - -/** - * SergeantVisitor. - */ -@Slf4j -public class SergeantVisitor implements UnitVisitor { - - /** - * Soldier Visitor method. - * @param soldier Soldier to be visited - */ - @Override - public void visit(Soldier soldier) { - // Do nothing - } - - /** - * Sergeant Visitor method. - * @param sergeant Sergeant to be visited - */ - @Override - public void visit(Sergeant sergeant) { - LOGGER.info("Hello {}", sergeant); - } - - /** - * Commander Visitor method. - * @param commander Commander to be visited - */ - @Override - public void visit(Commander commander) { - // Do nothing - } -} +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.visitor; + +import lombok.extern.slf4j.Slf4j; + +/** SergeantVisitor. */ +@Slf4j +public class SergeantVisitor implements UnitVisitor { + + /** + * Soldier Visitor method. + * + * @param soldier Soldier to be visited + */ + @Override + public void visit(Soldier soldier) { + // Do nothing + } + + /** + * Sergeant Visitor method. + * + * @param sergeant Sergeant to be visited + */ + @Override + public void visit(Sergeant sergeant) { + LOGGER.info("Hello {}", sergeant); + } + + /** + * Commander Visitor method. + * + * @param commander Commander to be visited + */ + @Override + public void visit(Commander commander) { + // Do nothing + } +} diff --git a/visitor/src/main/java/com/iluwatar/visitor/Soldier.java b/visitor/src/main/java/com/iluwatar/visitor/Soldier.java index 30398374e..565bcbdef 100644 --- a/visitor/src/main/java/com/iluwatar/visitor/Soldier.java +++ b/visitor/src/main/java/com/iluwatar/visitor/Soldier.java @@ -1,50 +1,49 @@ -/* - * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). - * - * The MIT License - * Copyright © 2014-2022 Ilkka Seppälä - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package com.iluwatar.visitor; - -/** - * Soldier. - */ -public class Soldier extends Unit { - - public Soldier(Unit... children) { - super(children); - } - - /** - * Accept a Visitor. - * @param visitor UnitVisitor to be accepted - */ - @Override - public void accept(UnitVisitor visitor) { - visitor.visit(this); - super.accept(visitor); - } - - @Override - public String toString() { - return "soldier"; - } -} +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.visitor; + +/** Soldier. */ +public class Soldier extends Unit { + + public Soldier(Unit... children) { + super(children); + } + + /** + * Accept a Visitor. + * + * @param visitor UnitVisitor to be accepted + */ + @Override + public void accept(UnitVisitor visitor) { + visitor.visit(this); + super.accept(visitor); + } + + @Override + public String toString() { + return "soldier"; + } +} diff --git a/visitor/src/main/java/com/iluwatar/visitor/SoldierVisitor.java b/visitor/src/main/java/com/iluwatar/visitor/SoldierVisitor.java index 6827c82d5..eb722ec86 100644 --- a/visitor/src/main/java/com/iluwatar/visitor/SoldierVisitor.java +++ b/visitor/src/main/java/com/iluwatar/visitor/SoldierVisitor.java @@ -1,61 +1,62 @@ -/* - * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). - * - * The MIT License - * Copyright © 2014-2022 Ilkka Seppälä - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package com.iluwatar.visitor; - -import lombok.extern.slf4j.Slf4j; - -/** - * SoldierVisitor. - */ -@Slf4j -public class SoldierVisitor implements UnitVisitor { - - /** - * Soldier Visitor method. - * @param soldier Soldier to be visited - */ - @Override - public void visit(Soldier soldier) { - LOGGER.info("Greetings {}", soldier); - } - - /** - * Sergeant Visitor method. - * @param sergeant Sergeant to be visited - */ - @Override - public void visit(Sergeant sergeant) { - // Do nothing - } - - /** - * Commander Visitor method. - * @param commander Commander to be visited - */ - @Override - public void visit(Commander commander) { - // Do nothing - } -} +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.visitor; + +import lombok.extern.slf4j.Slf4j; + +/** SoldierVisitor. */ +@Slf4j +public class SoldierVisitor implements UnitVisitor { + + /** + * Soldier Visitor method. + * + * @param soldier Soldier to be visited + */ + @Override + public void visit(Soldier soldier) { + LOGGER.info("Greetings {}", soldier); + } + + /** + * Sergeant Visitor method. + * + * @param sergeant Sergeant to be visited + */ + @Override + public void visit(Sergeant sergeant) { + // Do nothing + } + + /** + * Commander Visitor method. + * + * @param commander Commander to be visited + */ + @Override + public void visit(Commander commander) { + // Do nothing + } +} diff --git a/visitor/src/main/java/com/iluwatar/visitor/Unit.java b/visitor/src/main/java/com/iluwatar/visitor/Unit.java index cd5fc0b35..9bf3938da 100644 --- a/visitor/src/main/java/com/iluwatar/visitor/Unit.java +++ b/visitor/src/main/java/com/iluwatar/visitor/Unit.java @@ -26,9 +26,7 @@ package com.iluwatar.visitor; import java.util.Arrays; -/** - * Interface for the nodes in hierarchy. - */ +/** Interface for the nodes in hierarchy. */ public abstract class Unit { private final Unit[] children; @@ -37,9 +35,7 @@ public abstract class Unit { this.children = children; } - /** - * Accept visitor. - */ + /** Accept visitor. */ public void accept(UnitVisitor visitor) { Arrays.stream(children).forEach(child -> child.accept(visitor)); } diff --git a/visitor/src/main/java/com/iluwatar/visitor/UnitVisitor.java b/visitor/src/main/java/com/iluwatar/visitor/UnitVisitor.java index af6090228..c2f93d839 100644 --- a/visitor/src/main/java/com/iluwatar/visitor/UnitVisitor.java +++ b/visitor/src/main/java/com/iluwatar/visitor/UnitVisitor.java @@ -1,38 +1,35 @@ -/* - * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). - * - * The MIT License - * Copyright © 2014-2022 Ilkka Seppälä - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package com.iluwatar.visitor; - -/** - * Visitor interface. - */ -public interface UnitVisitor { - - void visit(Soldier soldier); - - void visit(Sergeant sergeant); - - void visit(Commander commander); - -} +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.visitor; + +/** Visitor interface. */ +public interface UnitVisitor { + + void visit(Soldier soldier); + + void visit(Sergeant sergeant); + + void visit(Commander commander); +} diff --git a/visitor/src/test/java/com/iluwatar/visitor/AppTest.java b/visitor/src/test/java/com/iluwatar/visitor/AppTest.java index 9fecce713..642b6b489 100644 --- a/visitor/src/test/java/com/iluwatar/visitor/AppTest.java +++ b/visitor/src/test/java/com/iluwatar/visitor/AppTest.java @@ -24,17 +24,15 @@ */ package com.iluwatar.visitor; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -/** - * Application test. - */ +import org.junit.jupiter.api.Test; + +/** Application test. */ class AppTest { @Test void shouldExecuteWithoutException() { - assertDoesNotThrow(() -> App.main(new String[]{})); + assertDoesNotThrow(() -> App.main(new String[] {})); } } diff --git a/visitor/src/test/java/com/iluwatar/visitor/CommanderTest.java b/visitor/src/test/java/com/iluwatar/visitor/CommanderTest.java index 94301c730..2961fc54e 100644 --- a/visitor/src/test/java/com/iluwatar/visitor/CommanderTest.java +++ b/visitor/src/test/java/com/iluwatar/visitor/CommanderTest.java @@ -27,15 +27,10 @@ package com.iluwatar.visitor; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.verify; -/** - * CommanderTest - * - */ +/** CommanderTest */ class CommanderTest extends UnitTest { - /** - * Create a new test instance for the given {@link Commander}. - */ + /** Create a new test instance for the given {@link Commander}. */ public CommanderTest() { super(Commander::new); } @@ -44,5 +39,4 @@ class CommanderTest extends UnitTest { void verifyVisit(Commander unit, UnitVisitor mockedVisitor) { verify(mockedVisitor).visit(eq(unit)); } - -} \ No newline at end of file +} diff --git a/visitor/src/test/java/com/iluwatar/visitor/CommanderVisitorTest.java b/visitor/src/test/java/com/iluwatar/visitor/CommanderVisitorTest.java index b3ff8da5b..96a1cd49d 100644 --- a/visitor/src/test/java/com/iluwatar/visitor/CommanderVisitorTest.java +++ b/visitor/src/test/java/com/iluwatar/visitor/CommanderVisitorTest.java @@ -24,24 +24,11 @@ */ package com.iluwatar.visitor; -import java.util.Optional; - -/** - * CommanderVisitorTest - * - */ +/** CommanderVisitorTest */ class CommanderVisitorTest extends VisitorTest { - /** - * Create a new test instance for the given visitor. - */ + /** Create a new test instance for the given visitor. */ public CommanderVisitorTest() { - super( - new CommanderVisitor(), - ("Good to see you commander"), - null, - null - ); + super(new CommanderVisitor(), ("Good to see you commander"), null, null); } - } diff --git a/visitor/src/test/java/com/iluwatar/visitor/SergeantTest.java b/visitor/src/test/java/com/iluwatar/visitor/SergeantTest.java index 0d57cc597..cf3af93bb 100644 --- a/visitor/src/test/java/com/iluwatar/visitor/SergeantTest.java +++ b/visitor/src/test/java/com/iluwatar/visitor/SergeantTest.java @@ -27,15 +27,10 @@ package com.iluwatar.visitor; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.verify; -/** - * SergeantTest - * - */ +/** SergeantTest */ class SergeantTest extends UnitTest { - /** - * Create a new test instance for the given {@link Sergeant}. - */ + /** Create a new test instance for the given {@link Sergeant}. */ public SergeantTest() { super(Sergeant::new); } @@ -44,5 +39,4 @@ class SergeantTest extends UnitTest { void verifyVisit(Sergeant unit, UnitVisitor mockedVisitor) { verify(mockedVisitor).visit(eq(unit)); } - -} \ No newline at end of file +} diff --git a/visitor/src/test/java/com/iluwatar/visitor/SergeantVisitorTest.java b/visitor/src/test/java/com/iluwatar/visitor/SergeantVisitorTest.java index b35473e39..a0468f6cb 100644 --- a/visitor/src/test/java/com/iluwatar/visitor/SergeantVisitorTest.java +++ b/visitor/src/test/java/com/iluwatar/visitor/SergeantVisitorTest.java @@ -24,24 +24,11 @@ */ package com.iluwatar.visitor; -import java.util.Optional; - -/** - * SergeantVisitorTest - * - */ +/** SergeantVisitorTest */ class SergeantVisitorTest extends VisitorTest { - /** - * Create a new test instance for the given visitor. - */ + /** Create a new test instance for the given visitor. */ public SergeantVisitorTest() { - super( - new SergeantVisitor(), - null, - ("Hello sergeant"), - null - ); + super(new SergeantVisitor(), null, ("Hello sergeant"), null); } - } diff --git a/visitor/src/test/java/com/iluwatar/visitor/SoldierTest.java b/visitor/src/test/java/com/iluwatar/visitor/SoldierTest.java index 82e71e0d7..71226a394 100644 --- a/visitor/src/test/java/com/iluwatar/visitor/SoldierTest.java +++ b/visitor/src/test/java/com/iluwatar/visitor/SoldierTest.java @@ -27,15 +27,10 @@ package com.iluwatar.visitor; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.verify; -/** - * SoldierTest - * - */ +/** SoldierTest */ class SoldierTest extends UnitTest { - /** - * Create a new test instance for the given {@link Soldier}. - */ + /** Create a new test instance for the given {@link Soldier}. */ public SoldierTest() { super(Soldier::new); } @@ -44,5 +39,4 @@ class SoldierTest extends UnitTest { void verifyVisit(Soldier unit, UnitVisitor mockedVisitor) { verify(mockedVisitor).visit(eq(unit)); } - -} \ No newline at end of file +} diff --git a/visitor/src/test/java/com/iluwatar/visitor/SoldierVisitorTest.java b/visitor/src/test/java/com/iluwatar/visitor/SoldierVisitorTest.java index 11efb124c..6844257dc 100644 --- a/visitor/src/test/java/com/iluwatar/visitor/SoldierVisitorTest.java +++ b/visitor/src/test/java/com/iluwatar/visitor/SoldierVisitorTest.java @@ -24,24 +24,11 @@ */ package com.iluwatar.visitor; -import java.util.Optional; - -/** - * SoldierVisitorTest - * - */ +/** SoldierVisitorTest */ class SoldierVisitorTest extends VisitorTest { - /** - * Create a new test instance for the given visitor. - */ + /** Create a new test instance for the given visitor. */ public SoldierVisitorTest() { - super( - new SoldierVisitor(), - null, - null, - ("Greetings soldier") - ); + super(new SoldierVisitor(), null, null, ("Greetings soldier")); } - } diff --git a/visitor/src/test/java/com/iluwatar/visitor/UnitTest.java b/visitor/src/test/java/com/iluwatar/visitor/UnitTest.java index 6e0b34a3c..57bfa4350 100644 --- a/visitor/src/test/java/com/iluwatar/visitor/UnitTest.java +++ b/visitor/src/test/java/com/iluwatar/visitor/UnitTest.java @@ -40,9 +40,7 @@ import org.junit.jupiter.api.Test; */ public abstract class UnitTest { - /** - * Factory to create new instances of the tested unit. - */ + /** Factory to create new instances of the tested unit. */ private final Function factory; /** @@ -73,9 +71,8 @@ public abstract class UnitTest { /** * Verify if the correct visit method is called on the mock, depending on the tested instance. * - * @param unit The tested unit instance + * @param unit The tested unit instance * @param mockedVisitor The mocked {@link UnitVisitor} who should have gotten a visit by the unit */ abstract void verifyVisit(final U unit, final UnitVisitor mockedVisitor); - } diff --git a/visitor/src/test/java/com/iluwatar/visitor/VisitorTest.java b/visitor/src/test/java/com/iluwatar/visitor/VisitorTest.java index b3dacb291..374f1fef6 100644 --- a/visitor/src/test/java/com/iluwatar/visitor/VisitorTest.java +++ b/visitor/src/test/java/com/iluwatar/visitor/VisitorTest.java @@ -55,39 +55,30 @@ public abstract class VisitorTest { appender.stop(); } - /** - * The tested visitor instance. - */ + /** The tested visitor instance. */ private final V visitor; - /** - * The expected response when being visited by a commander. - */ + /** The expected response when being visited by a commander. */ private final String commanderResponse; - /** - * The expected response when being visited by a sergeant. - */ + /** The expected response when being visited by a sergeant. */ private final String sergeantResponse; - /** - * The expected response when being visited by a soldier. - */ + /** The expected response when being visited by a soldier. */ private final String soldierResponse; /** * Create a new test instance for the given visitor. * * @param commanderResponse The expected response when being visited by a commander - * @param sergeantResponse The expected response when being visited by a sergeant - * @param soldierResponse The expected response when being visited by a soldier + * @param sergeantResponse The expected response when being visited by a sergeant + * @param soldierResponse The expected response when being visited by a soldier */ public VisitorTest( final V visitor, final String commanderResponse, final String sergeantResponse, - final String soldierResponse - ) { + final String soldierResponse) { this.visitor = visitor; this.commanderResponse = commanderResponse; this.sergeantResponse = sergeantResponse;