diff --git a/.gitignore b/.gitignore index 589d3fb13..64f833e2d 100644 --- a/.gitignore +++ b/.gitignore @@ -1,19 +1,19 @@ -target -.metadata -.settings -.classpath -.project -*.class -# Package Files # -*.jar -*.war -*.ear -.idea -*.iml -*.swp +target +.metadata +.settings +.classpath +.project +*.class +# Package Files # +*.jar +*.war +*.ear +.idea +*.iml +*.swp datanucleus.log /bin/ /bin/ /bin/ - -data-mapper/src/main/resources/log4j.xml \ No newline at end of file +*.log +data-mapper/src/main/resources/log4j.xml 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 d7758b6f7..35cdf7625 100644 --- a/abstract-document/src/main/java/com/iluwatar/abstractdocument/App.java +++ b/abstract-document/src/main/java/com/iluwatar/abstractdocument/App.java @@ -27,6 +27,8 @@ import com.iluwatar.abstractdocument.domain.HasModel; import com.iluwatar.abstractdocument.domain.HasParts; import com.iluwatar.abstractdocument.domain.HasPrice; import com.iluwatar.abstractdocument.domain.HasType; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.Arrays; import java.util.HashMap; @@ -44,11 +46,13 @@ import java.util.Map; */ public class App { + private static final Logger LOGGER = LoggerFactory.getLogger(App.class); + /** * Executes the App */ public App() { - System.out.println("Constructing parts and car"); + LOGGER.info("Constructing parts and car"); Map carProperties = new HashMap<>(); carProperties.put(HasModel.PROPERTY, "300SL"); @@ -68,12 +72,11 @@ public class App { Car car = new Car(carProperties); - System.out.println("Here is our car:"); - System.out.println("-> model: " + car.getModel().get()); - System.out.println("-> price: " + car.getPrice().get()); - System.out.println("-> parts: "); - car.getParts().forEach(p -> System.out - .println("\t" + p.getType().get() + "/" + p.getModel().get() + "/" + p.getPrice().get())); + LOGGER.info("Here is our car:"); + LOGGER.info("-> model: {}", car.getModel().get()); + LOGGER.info("-> price: {}", car.getPrice().get()); + LOGGER.info("-> parts: "); + car.getParts().forEach(p -> LOGGER.info("\t{}/{}/{}", p.getType().get(), p.getModel().get(), p.getPrice().get())); } /** 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 aae396f1d..abc75a951 100644 --- a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/App.java +++ b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/App.java @@ -22,6 +22,9 @@ */ package com.iluwatar.abstractfactory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * * The Abstract Factory pattern provides a way to encapsulate a group of individual factories that have a common theme @@ -39,6 +42,8 @@ package com.iluwatar.abstractfactory; */ public class App { + private static final Logger LOGGER = LoggerFactory.getLogger(App.class); + private King king; private Castle castle; private Army army; @@ -98,17 +103,17 @@ public class App { App app = new App(); - System.out.println("Elf Kingdom"); + LOGGER.info("Elf Kingdom"); app.createKingdom(new ElfKingdomFactory()); - System.out.println(app.getArmy().getDescription()); - System.out.println(app.getCastle().getDescription()); - System.out.println(app.getKing().getDescription()); + LOGGER.info(app.getArmy().getDescription()); + LOGGER.info(app.getCastle().getDescription()); + LOGGER.info(app.getKing().getDescription()); - System.out.println("\nOrc Kingdom"); + LOGGER.info("Orc Kingdom"); app.createKingdom(new OrcKingdomFactory()); - System.out.println(app.getArmy().getDescription()); - System.out.println(app.getCastle().getDescription()); - System.out.println(app.getKing().getDescription()); + LOGGER.info(app.getArmy().getDescription()); + LOGGER.info(app.getCastle().getDescription()); + LOGGER.info(app.getKing().getDescription()); } diff --git a/adapter/src/main/java/com/iluwatar/adapter/BattleFishingBoat.java b/adapter/src/main/java/com/iluwatar/adapter/BattleFishingBoat.java index a591818fe..265f127c4 100644 --- a/adapter/src/main/java/com/iluwatar/adapter/BattleFishingBoat.java +++ b/adapter/src/main/java/com/iluwatar/adapter/BattleFishingBoat.java @@ -22,6 +22,9 @@ */ package com.iluwatar.adapter; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * * Adapter class. Adapts the interface of the device ({@link FishingBoat}) into {@link BattleShip} @@ -33,6 +36,8 @@ package com.iluwatar.adapter; */ public class BattleFishingBoat implements BattleShip { + private static final Logger LOGGER = LoggerFactory.getLogger(BattleFishingBoat.class); + private FishingBoat boat; public BattleFishingBoat() { @@ -41,7 +46,7 @@ public class BattleFishingBoat implements BattleShip { @Override public void fire() { - System.out.println("fire!"); + LOGGER.info("fire!"); } @Override diff --git a/adapter/src/main/java/com/iluwatar/adapter/FishingBoat.java b/adapter/src/main/java/com/iluwatar/adapter/FishingBoat.java index 307437038..a10e90967 100644 --- a/adapter/src/main/java/com/iluwatar/adapter/FishingBoat.java +++ b/adapter/src/main/java/com/iluwatar/adapter/FishingBoat.java @@ -22,6 +22,9 @@ */ package com.iluwatar.adapter; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * * Device class (adaptee in the pattern). We want to reuse this class @@ -29,12 +32,14 @@ package com.iluwatar.adapter; */ public class FishingBoat { + private static final Logger LOGGER = LoggerFactory.getLogger(FishingBoat.class); + public void sail() { - System.out.println("The Boat is moving to that place"); + LOGGER.info("The Boat is moving to that place"); } public void fish() { - System.out.println("fishing ..."); + LOGGER.info("fishing ..."); } } diff --git a/aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInformationClientImpl.java b/aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInformationClientImpl.java index 1c5c1527c..e86a84563 100644 --- a/aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInformationClientImpl.java +++ b/aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInformationClientImpl.java @@ -27,6 +27,8 @@ import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import java.io.IOException; @@ -37,6 +39,8 @@ import java.io.IOException; @Component public class ProductInformationClientImpl implements ProductInformationClient { + private static final Logger LOGGER = LoggerFactory.getLogger(ProductInformationClientImpl.class); + @Override public String getProductTitle() { String response = null; @@ -46,7 +50,7 @@ public class ProductInformationClientImpl implements ProductInformationClient { response = EntityUtils.toString(httpResponse.getEntity()); } } catch (IOException e) { - e.printStackTrace(); + LOGGER.error("Exception caught.", e); } return response; } diff --git a/aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInventoryClientImpl.java b/aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInventoryClientImpl.java index 14d0a32c4..c736462e6 100644 --- a/aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInventoryClientImpl.java +++ b/aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInventoryClientImpl.java @@ -27,6 +27,8 @@ import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import java.io.IOException; @@ -37,6 +39,8 @@ import java.io.IOException; @Component public class ProductInventoryClientImpl implements ProductInventoryClient { + private static final Logger LOGGER = LoggerFactory.getLogger(ProductInventoryClientImpl.class); + @Override public int getProductInventories() { String response = "0"; @@ -46,7 +50,7 @@ public class ProductInventoryClientImpl implements ProductInventoryClient { response = EntityUtils.toString(httpResponse.getEntity()); } } catch (IOException e) { - e.printStackTrace(); + LOGGER.error("Exception caught.", e); } return Integer.parseInt(response); } 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 0a56dc166..ee33ea1db 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 @@ -22,6 +22,9 @@ */ package com.iluwatar.async.method.invocation; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.util.concurrent.Callable; /** @@ -54,6 +57,8 @@ import java.util.concurrent.Callable; */ public class App { + private static final Logger LOGGER = LoggerFactory.getLogger(App.class); + /** * Program entry point */ @@ -120,6 +125,6 @@ public class App { } private static void log(String msg) { - System.out.println(String.format("[%1$-10s] - %2$s", Thread.currentThread().getName(), msg)); + LOGGER.info(msg); } } diff --git a/bridge/src/main/java/com/iluwatar/bridge/Excalibur.java b/bridge/src/main/java/com/iluwatar/bridge/Excalibur.java index 2523b3557..28bcf13fa 100644 --- a/bridge/src/main/java/com/iluwatar/bridge/Excalibur.java +++ b/bridge/src/main/java/com/iluwatar/bridge/Excalibur.java @@ -22,6 +22,9 @@ */ package com.iluwatar.bridge; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * * Excalibur @@ -29,23 +32,25 @@ package com.iluwatar.bridge; */ public class Excalibur extends BlindingMagicWeaponImpl { + private static final Logger LOGGER = LoggerFactory.getLogger(Excalibur.class); + @Override public void wieldImp() { - System.out.println("wielding Excalibur"); + LOGGER.info("wielding Excalibur"); } @Override public void swingImp() { - System.out.println("swinging Excalibur"); + LOGGER.info("swinging Excalibur"); } @Override public void unwieldImp() { - System.out.println("unwielding Excalibur"); + LOGGER.info("unwielding Excalibur"); } @Override public void blindImp() { - System.out.println("bright light streams from Excalibur blinding the enemy"); + LOGGER.info("bright light streams from Excalibur blinding the enemy"); } } diff --git a/bridge/src/main/java/com/iluwatar/bridge/Mjollnir.java b/bridge/src/main/java/com/iluwatar/bridge/Mjollnir.java index 0cc31b471..a57d75abc 100644 --- a/bridge/src/main/java/com/iluwatar/bridge/Mjollnir.java +++ b/bridge/src/main/java/com/iluwatar/bridge/Mjollnir.java @@ -22,6 +22,9 @@ */ package com.iluwatar.bridge; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * * Mjollnir @@ -29,23 +32,25 @@ package com.iluwatar.bridge; */ public class Mjollnir extends FlyingMagicWeaponImpl { + private static final Logger LOGGER = LoggerFactory.getLogger(Mjollnir.class); + @Override public void wieldImp() { - System.out.println("wielding Mjollnir"); + LOGGER.info("wielding Mjollnir"); } @Override public void swingImp() { - System.out.println("swinging Mjollnir"); + LOGGER.info("swinging Mjollnir"); } @Override public void unwieldImp() { - System.out.println("unwielding Mjollnir"); + LOGGER.info("unwielding Mjollnir"); } @Override public void flyImp() { - System.out.println("Mjollnir hits the enemy in the air and returns back to the owner's hand"); + LOGGER.info("Mjollnir hits the enemy in the air and returns back to the owner's hand"); } } diff --git a/bridge/src/main/java/com/iluwatar/bridge/Stormbringer.java b/bridge/src/main/java/com/iluwatar/bridge/Stormbringer.java index 91cad9cc2..e9d65bc8c 100644 --- a/bridge/src/main/java/com/iluwatar/bridge/Stormbringer.java +++ b/bridge/src/main/java/com/iluwatar/bridge/Stormbringer.java @@ -22,6 +22,9 @@ */ package com.iluwatar.bridge; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * * Stormbringer @@ -29,23 +32,25 @@ package com.iluwatar.bridge; */ public class Stormbringer extends SoulEatingMagicWeaponImpl { + private static final Logger LOGGER = LoggerFactory.getLogger(Stormbringer.class); + @Override public void wieldImp() { - System.out.println("wielding Stormbringer"); + LOGGER.info("wielding Stormbringer"); } @Override public void swingImp() { - System.out.println("swinging Stormbringer"); + LOGGER.info("swinging Stormbringer"); } @Override public void unwieldImp() { - System.out.println("unwielding Stormbringer"); + LOGGER.info("unwielding Stormbringer"); } @Override public void eatSoulImp() { - System.out.println("Stormbringer devours the enemy's soul"); + LOGGER.info("Stormbringer devours the enemy's soul"); } } diff --git a/builder/src/main/java/com/iluwatar/builder/App.java b/builder/src/main/java/com/iluwatar/builder/App.java index d421de7b6..0790e3058 100644 --- a/builder/src/main/java/com/iluwatar/builder/App.java +++ b/builder/src/main/java/com/iluwatar/builder/App.java @@ -23,6 +23,8 @@ package com.iluwatar.builder; import com.iluwatar.builder.Hero.Builder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * @@ -50,6 +52,8 @@ import com.iluwatar.builder.Hero.Builder; */ public class App { + private static final Logger LOGGER = LoggerFactory.getLogger(App.class); + /** * Program entry point * @@ -60,18 +64,18 @@ public class App { Hero mage = new Hero.Builder(Profession.MAGE, "Riobard").withHairColor(HairColor.BLACK) .withWeapon(Weapon.DAGGER).build(); - System.out.println(mage); + LOGGER.info(mage.toString()); Hero warrior = new Hero.Builder(Profession.WARRIOR, "Amberjill").withHairColor(HairColor.BLOND) .withHairType(HairType.LONG_CURLY).withArmor(Armor.CHAIN_MAIL).withWeapon(Weapon.SWORD) .build(); - System.out.println(warrior); + LOGGER.info(warrior.toString()); Hero thief = new Hero.Builder(Profession.THIEF, "Desmond").withHairType(HairType.BALD) .withWeapon(Weapon.BOW).build(); - System.out.println(thief); + LOGGER.info(thief.toString()); } } diff --git a/business-delegate/src/main/java/com/iluwatar/business/delegate/EjbService.java b/business-delegate/src/main/java/com/iluwatar/business/delegate/EjbService.java index 7296f63b4..9c890b108 100644 --- a/business-delegate/src/main/java/com/iluwatar/business/delegate/EjbService.java +++ b/business-delegate/src/main/java/com/iluwatar/business/delegate/EjbService.java @@ -22,6 +22,9 @@ */ package com.iluwatar.business.delegate; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * * Service EJB implementation @@ -29,8 +32,10 @@ package com.iluwatar.business.delegate; */ public class EjbService implements BusinessService { + private static final Logger LOGGER = LoggerFactory.getLogger(EjbService.class); + @Override public void doProcessing() { - System.out.println("EjbService is now processing"); + LOGGER.info("EjbService is now processing"); } } diff --git a/business-delegate/src/main/java/com/iluwatar/business/delegate/JmsService.java b/business-delegate/src/main/java/com/iluwatar/business/delegate/JmsService.java index 5b71ce57d..5b5fa6247 100644 --- a/business-delegate/src/main/java/com/iluwatar/business/delegate/JmsService.java +++ b/business-delegate/src/main/java/com/iluwatar/business/delegate/JmsService.java @@ -22,6 +22,9 @@ */ package com.iluwatar.business.delegate; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * * Service JMS implementation @@ -29,8 +32,10 @@ package com.iluwatar.business.delegate; */ public class JmsService implements BusinessService { + private static final Logger LOGGER = LoggerFactory.getLogger(JmsService.class); + @Override public void doProcessing() { - System.out.println("JmsService is now processing"); + LOGGER.info("JmsService is now processing"); } } diff --git a/caching/src/main/java/com/iluwatar/caching/App.java b/caching/src/main/java/com/iluwatar/caching/App.java index 1b1b5e1ca..f30b20e05 100644 --- a/caching/src/main/java/com/iluwatar/caching/App.java +++ b/caching/src/main/java/com/iluwatar/caching/App.java @@ -22,6 +22,9 @@ */ package com.iluwatar.caching; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * * The Caching pattern describes how to avoid expensive re-acquisition of resources by not releasing @@ -60,6 +63,9 @@ package com.iluwatar.caching; */ public class App { + private static final Logger LOGGER = LoggerFactory.getLogger(App.class); + + /** * Program entry point * @@ -82,13 +88,13 @@ public class App { * Read-through and write-through */ public void useReadAndWriteThroughStrategy() { - System.out.println("# CachingPolicy.THROUGH"); + LOGGER.info("# CachingPolicy.THROUGH"); AppManager.initCachingPolicy(CachingPolicy.THROUGH); UserAccount userAccount1 = new UserAccount("001", "John", "He is a boy."); AppManager.save(userAccount1); - System.out.println(AppManager.printCacheContent()); + LOGGER.info(AppManager.printCacheContent()); AppManager.find("001"); AppManager.find("001"); } @@ -97,21 +103,21 @@ public class App { * Read-through and write-around */ public void useReadThroughAndWriteAroundStrategy() { - System.out.println("# CachingPolicy.AROUND"); + LOGGER.info("# CachingPolicy.AROUND"); AppManager.initCachingPolicy(CachingPolicy.AROUND); UserAccount userAccount2 = new UserAccount("002", "Jane", "She is a girl."); AppManager.save(userAccount2); - System.out.println(AppManager.printCacheContent()); + LOGGER.info(AppManager.printCacheContent()); AppManager.find("002"); - System.out.println(AppManager.printCacheContent()); + LOGGER.info(AppManager.printCacheContent()); userAccount2 = AppManager.find("002"); userAccount2.setUserName("Jane G."); AppManager.save(userAccount2); - System.out.println(AppManager.printCacheContent()); + LOGGER.info(AppManager.printCacheContent()); AppManager.find("002"); - System.out.println(AppManager.printCacheContent()); + LOGGER.info(AppManager.printCacheContent()); AppManager.find("002"); } @@ -119,7 +125,7 @@ public class App { * Read-through and write-behind */ public void useReadThroughAndWriteBehindStrategy() { - System.out.println("# CachingPolicy.BEHIND"); + LOGGER.info("# CachingPolicy.BEHIND"); AppManager.initCachingPolicy(CachingPolicy.BEHIND); UserAccount userAccount3 = new UserAccount("003", "Adam", "He likes food."); @@ -129,23 +135,23 @@ public class App { AppManager.save(userAccount3); AppManager.save(userAccount4); AppManager.save(userAccount5); - System.out.println(AppManager.printCacheContent()); + LOGGER.info(AppManager.printCacheContent()); AppManager.find("003"); - System.out.println(AppManager.printCacheContent()); + LOGGER.info(AppManager.printCacheContent()); UserAccount userAccount6 = new UserAccount("006", "Yasha", "She is an only child."); AppManager.save(userAccount6); - System.out.println(AppManager.printCacheContent()); + LOGGER.info(AppManager.printCacheContent()); AppManager.find("004"); - System.out.println(AppManager.printCacheContent()); + LOGGER.info(AppManager.printCacheContent()); } /** * Cache-Aside */ public void useCacheAsideStategy() { - System.out.println("# CachingPolicy.ASIDE"); + LOGGER.info("# CachingPolicy.ASIDE"); AppManager.initCachingPolicy(CachingPolicy.ASIDE); - System.out.println(AppManager.printCacheContent()); + LOGGER.info(AppManager.printCacheContent()); UserAccount userAccount3 = new UserAccount("003", "Adam", "He likes food."); UserAccount userAccount4 = new UserAccount("004", "Rita", "She hates cats."); @@ -154,10 +160,10 @@ public class App { AppManager.save(userAccount4); AppManager.save(userAccount5); - System.out.println(AppManager.printCacheContent()); + LOGGER.info(AppManager.printCacheContent()); AppManager.find("003"); - System.out.println(AppManager.printCacheContent()); + LOGGER.info(AppManager.printCacheContent()); AppManager.find("004"); - System.out.println(AppManager.printCacheContent()); + LOGGER.info(AppManager.printCacheContent()); } } diff --git a/caching/src/main/java/com/iluwatar/caching/CacheStore.java b/caching/src/main/java/com/iluwatar/caching/CacheStore.java index c2b95a1bd..fafe9d46f 100644 --- a/caching/src/main/java/com/iluwatar/caching/CacheStore.java +++ b/caching/src/main/java/com/iluwatar/caching/CacheStore.java @@ -22,6 +22,9 @@ */ package com.iluwatar.caching; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.util.List; /** @@ -31,6 +34,8 @@ import java.util.List; */ public class CacheStore { + private static final Logger LOGGER = LoggerFactory.getLogger(CacheStore.class); + static LruCache cache; private CacheStore() { @@ -52,10 +57,10 @@ public class CacheStore { */ public static UserAccount readThrough(String userId) { if (cache.contains(userId)) { - System.out.println("# Cache Hit!"); + LOGGER.info("# Cache Hit!"); return cache.get(userId); } - System.out.println("# Cache Miss!"); + LOGGER.info("# Cache Miss!"); UserAccount userAccount = DbManager.readFromDb(userId); cache.set(userId, userAccount); return userAccount; @@ -91,13 +96,13 @@ public class CacheStore { */ public static UserAccount readThroughWithWriteBackPolicy(String userId) { if (cache.contains(userId)) { - System.out.println("# Cache Hit!"); + LOGGER.info("# Cache Hit!"); return cache.get(userId); } - System.out.println("# Cache Miss!"); + LOGGER.info("# Cache Miss!"); UserAccount userAccount = DbManager.readFromDb(userId); if (cache.isFull()) { - System.out.println("# Cache is FULL! Writing LRU data to DB..."); + LOGGER.info("# Cache is FULL! Writing LRU data to DB..."); UserAccount toBeWrittenToDb = cache.getLruData(); DbManager.upsertDb(toBeWrittenToDb); } @@ -110,7 +115,7 @@ public class CacheStore { */ public static void writeBehind(UserAccount userAccount) { if (cache.isFull() && !cache.contains(userAccount.getUserId())) { - System.out.println("# Cache is FULL! Writing LRU data to DB..."); + LOGGER.info("# Cache is FULL! Writing LRU data to DB..."); UserAccount toBeWrittenToDb = cache.getLruData(); DbManager.upsertDb(toBeWrittenToDb); } @@ -130,7 +135,7 @@ public class CacheStore { * Writes remaining content in the cache into the DB. */ public static void flushCache() { - System.out.println("# flushCache..."); + LOGGER.info("# flushCache..."); if (null == cache) { return; } diff --git a/caching/src/main/java/com/iluwatar/caching/LruCache.java b/caching/src/main/java/com/iluwatar/caching/LruCache.java index 00e27ccf1..9e2d4cdbe 100644 --- a/caching/src/main/java/com/iluwatar/caching/LruCache.java +++ b/caching/src/main/java/com/iluwatar/caching/LruCache.java @@ -22,6 +22,9 @@ */ package com.iluwatar.caching; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -38,6 +41,8 @@ import java.util.Map; */ public class LruCache { + private static final Logger LOGGER = LoggerFactory.getLogger(LruCache.class); + class Node { String userId; UserAccount userAccount; @@ -115,7 +120,7 @@ public class LruCache { } else { Node newNode = new Node(userId, userAccount); if (cache.size() >= capacity) { - System.out.println("# Cache is FULL! Removing " + end.userId + " from cache..."); + LOGGER.info("# Cache is FULL! Removing {} from cache...", end.userId); cache.remove(end.userId); // remove LRU data from cache. remove(end); setHead(newNode); @@ -136,7 +141,7 @@ public class LruCache { public void invalidate(String userId) { Node toBeRemoved = cache.remove(userId); if (toBeRemoved != null) { - System.out.println("# " + userId + " has been updated! Removing older version from cache..."); + LOGGER.info("# {} has been updated! Removing older version from cache...", userId); remove(toBeRemoved); } } diff --git a/callback/src/main/java/com/iluwatar/callback/App.java b/callback/src/main/java/com/iluwatar/callback/App.java index bc1b2890e..ece6f8cce 100644 --- a/callback/src/main/java/com/iluwatar/callback/App.java +++ b/callback/src/main/java/com/iluwatar/callback/App.java @@ -22,6 +22,9 @@ */ package com.iluwatar.callback; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * * Callback pattern is more native for functional languages where functions are treated as @@ -31,6 +34,8 @@ package com.iluwatar.callback; */ public class App { + private static final Logger LOGGER = LoggerFactory.getLogger(App.class); + /** * Program entry point */ @@ -39,7 +44,7 @@ public class App { Callback callback = new Callback() { @Override public void call() { - System.out.println("I'm done now."); + LOGGER.info("I'm done now."); } }; task.executeWith(callback); diff --git a/callback/src/main/java/com/iluwatar/callback/LambdasApp.java b/callback/src/main/java/com/iluwatar/callback/LambdasApp.java index 78ca63e0b..33a49a461 100644 --- a/callback/src/main/java/com/iluwatar/callback/LambdasApp.java +++ b/callback/src/main/java/com/iluwatar/callback/LambdasApp.java @@ -22,6 +22,9 @@ */ package com.iluwatar.callback; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * * This example generates the exact same output as {@link App} however the callback has been @@ -30,12 +33,14 @@ package com.iluwatar.callback; */ public class LambdasApp { + private static final Logger LOGGER = LoggerFactory.getLogger(LambdasApp.class); + /** * Program entry point */ public static void main(String[] args) { Task task = new SimpleTask(); - Callback c = () -> System.out.println("I'm done now."); + Callback c = () -> LOGGER.info("I'm done now."); task.executeWith(c); } } diff --git a/callback/src/main/java/com/iluwatar/callback/SimpleTask.java b/callback/src/main/java/com/iluwatar/callback/SimpleTask.java index 2a7385607..2c56bea07 100644 --- a/callback/src/main/java/com/iluwatar/callback/SimpleTask.java +++ b/callback/src/main/java/com/iluwatar/callback/SimpleTask.java @@ -22,6 +22,9 @@ */ package com.iluwatar.callback; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * * Implementation of task that need to be executed @@ -29,8 +32,10 @@ package com.iluwatar.callback; */ public class SimpleTask extends Task { + private static final Logger LOGGER = LoggerFactory.getLogger(SimpleTask.class); + @Override public void execute() { - System.out.println("Perform some important activity and after call the callback method."); + LOGGER.info("Perform some important activity and after call the callback method."); } } diff --git a/chain/src/main/java/com/iluwatar/chain/RequestHandler.java b/chain/src/main/java/com/iluwatar/chain/RequestHandler.java index 78d68e5dc..2fd774f99 100644 --- a/chain/src/main/java/com/iluwatar/chain/RequestHandler.java +++ b/chain/src/main/java/com/iluwatar/chain/RequestHandler.java @@ -22,6 +22,9 @@ */ package com.iluwatar.chain; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * * RequestHandler @@ -29,6 +32,8 @@ package com.iluwatar.chain; */ public abstract class RequestHandler { + private static final Logger LOGGER = LoggerFactory.getLogger(RequestHandler.class); + private RequestHandler next; public RequestHandler(RequestHandler next) { @@ -45,7 +50,7 @@ public abstract class RequestHandler { } protected void printHandling(Request req) { - System.out.println(this + " handling request \"" + req + "\""); + LOGGER.info("{} handling request \"{}\"", this, req); } @Override diff --git a/command/src/main/java/com/iluwatar/command/Target.java b/command/src/main/java/com/iluwatar/command/Target.java index 2e49ab663..3bfbde926 100644 --- a/command/src/main/java/com/iluwatar/command/Target.java +++ b/command/src/main/java/com/iluwatar/command/Target.java @@ -22,6 +22,9 @@ */ package com.iluwatar.command; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * * Base class for spell targets. @@ -29,6 +32,8 @@ package com.iluwatar.command; */ public abstract class Target { + private static final Logger LOGGER = LoggerFactory.getLogger(Target.class); + private Size size; private Visibility visibility; @@ -56,8 +61,6 @@ public abstract class Target { * Print status */ public void printStatus() { - System.out.println(String.format("%s, [size=%s] [visibility=%s]", this, getSize(), - getVisibility())); - System.out.println(); + LOGGER.info("{}, [size={}] [visibility={}]", this, getSize(), getVisibility()); } } diff --git a/command/src/main/java/com/iluwatar/command/Wizard.java b/command/src/main/java/com/iluwatar/command/Wizard.java index bd0ef85d4..abfc49967 100644 --- a/command/src/main/java/com/iluwatar/command/Wizard.java +++ b/command/src/main/java/com/iluwatar/command/Wizard.java @@ -22,6 +22,9 @@ */ package com.iluwatar.command; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.util.Deque; import java.util.LinkedList; @@ -32,6 +35,8 @@ import java.util.LinkedList; */ public class Wizard { + private static final Logger LOGGER = LoggerFactory.getLogger(Wizard.class); + private Deque undoStack = new LinkedList<>(); private Deque redoStack = new LinkedList<>(); @@ -41,7 +46,7 @@ public class Wizard { * Cast spell */ public void castSpell(Command command, Target target) { - System.out.println(this + " casts " + command + " at " + target); + LOGGER.info("{} casts {} at {}", this, command, target); command.execute(target); undoStack.offerLast(command); } @@ -53,7 +58,7 @@ public class Wizard { if (!undoStack.isEmpty()) { Command previousSpell = undoStack.pollLast(); redoStack.offerLast(previousSpell); - System.out.println(this + " undoes " + previousSpell); + LOGGER.info("{} undoes {}", this, previousSpell); previousSpell.undo(); } } @@ -65,7 +70,7 @@ public class Wizard { if (!redoStack.isEmpty()) { Command previousSpell = redoStack.pollLast(); undoStack.offerLast(previousSpell); - System.out.println(this + " redoes " + previousSpell); + LOGGER.info("{} redoes {}", this, previousSpell); previousSpell.redo(); } } diff --git a/composite/src/main/java/com/iluwatar/composite/App.java b/composite/src/main/java/com/iluwatar/composite/App.java index cfe37876f..07d4f0b68 100644 --- a/composite/src/main/java/com/iluwatar/composite/App.java +++ b/composite/src/main/java/com/iluwatar/composite/App.java @@ -22,6 +22,9 @@ */ package com.iluwatar.composite; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * The Composite pattern is a partitioning design pattern. The Composite pattern describes that a * group of objects is to be treated in the same way as a single instance of an object. The intent @@ -35,20 +38,22 @@ package com.iluwatar.composite; */ public class App { + private static final Logger LOGGER = LoggerFactory.getLogger(App.class); + /** * Program entry point * * @param args command line args */ public static void main(String[] args) { - System.out.println("Message from the orcs: "); + LOGGER.info("Message from the orcs: "); LetterComposite orcMessage = new Messenger().messageFromOrcs(); orcMessage.print(); - System.out.println("\n"); + LOGGER.info("\n"); - System.out.println("Message from the elves: "); + LOGGER.info("Message from the elves: "); LetterComposite elfMessage = new Messenger().messageFromElves(); elfMessage.print(); diff --git a/composite/src/main/java/com/iluwatar/composite/Letter.java b/composite/src/main/java/com/iluwatar/composite/Letter.java index d6a4005d2..088cdd44c 100644 --- a/composite/src/main/java/com/iluwatar/composite/Letter.java +++ b/composite/src/main/java/com/iluwatar/composite/Letter.java @@ -23,7 +23,7 @@ package com.iluwatar.composite; /** - * + * * Letter * */ diff --git a/composite/src/main/java/com/iluwatar/composite/Sentence.java b/composite/src/main/java/com/iluwatar/composite/Sentence.java index eea1d4b1d..bccf6c751 100644 --- a/composite/src/main/java/com/iluwatar/composite/Sentence.java +++ b/composite/src/main/java/com/iluwatar/composite/Sentence.java @@ -25,7 +25,7 @@ package com.iluwatar.composite; import java.util.List; /** - * + * * Sentence * */ diff --git a/composite/src/main/java/com/iluwatar/composite/Word.java b/composite/src/main/java/com/iluwatar/composite/Word.java index 819f166dc..0174dc88a 100644 --- a/composite/src/main/java/com/iluwatar/composite/Word.java +++ b/composite/src/main/java/com/iluwatar/composite/Word.java @@ -25,7 +25,7 @@ package com.iluwatar.composite; import java.util.List; /** - * + * * Word * */ diff --git a/decorator/src/main/java/com/iluwatar/decorator/App.java b/decorator/src/main/java/com/iluwatar/decorator/App.java index 5cb5a7155..808bd1bd7 100644 --- a/decorator/src/main/java/com/iluwatar/decorator/App.java +++ b/decorator/src/main/java/com/iluwatar/decorator/App.java @@ -22,6 +22,9 @@ */ package com.iluwatar.decorator; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * * The Decorator pattern is a more flexible alternative to subclassing. The Decorator class @@ -36,6 +39,8 @@ package com.iluwatar.decorator; */ public class App { + private static final Logger LOGGER = LoggerFactory.getLogger(App.class); + /** * Program entry point * @@ -44,17 +49,17 @@ public class App { public static void main(String[] args) { // simple troll - System.out.println("A simple looking troll approaches."); + LOGGER.info("A simple looking troll approaches."); Hostile troll = new Troll(); troll.attack(); troll.fleeBattle(); - System.out.printf("Simple troll power %d.\n", troll.getAttackPower()); + LOGGER.info("Simple troll power {}.\n", troll.getAttackPower()); // change the behavior of the simple troll by adding a decorator - System.out.println("\nA smart looking troll surprises you."); + LOGGER.info("A smart looking troll surprises you."); Hostile smart = new SmartHostile(troll); smart.attack(); smart.fleeBattle(); - System.out.printf("Smart troll power %d.\n", smart.getAttackPower()); + LOGGER.info("Smart troll power {}.\n", smart.getAttackPower()); } } diff --git a/decorator/src/main/java/com/iluwatar/decorator/SmartHostile.java b/decorator/src/main/java/com/iluwatar/decorator/SmartHostile.java index 3b4b86276..9a4a136ad 100644 --- a/decorator/src/main/java/com/iluwatar/decorator/SmartHostile.java +++ b/decorator/src/main/java/com/iluwatar/decorator/SmartHostile.java @@ -22,6 +22,9 @@ */ package com.iluwatar.decorator; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * SmartHostile is a decorator for {@link Hostile} objects. The calls to the {@link Hostile} interface * are intercepted and decorated. Finally the calls are delegated to the decorated {@link Hostile} @@ -30,6 +33,8 @@ package com.iluwatar.decorator; */ public class SmartHostile implements Hostile { + private static final Logger LOGGER = LoggerFactory.getLogger(SmartHostile.class); + private Hostile decorated; public SmartHostile(Hostile decorated) { @@ -38,7 +43,7 @@ public class SmartHostile implements Hostile { @Override public void attack() { - System.out.println("It throws a rock at you!"); + LOGGER.info("It throws a rock at you!"); decorated.attack(); } @@ -50,7 +55,7 @@ public class SmartHostile implements Hostile { @Override public void fleeBattle() { - System.out.println("It calls for help!"); + LOGGER.info("It calls for help!"); decorated.fleeBattle(); } } diff --git a/decorator/src/main/java/com/iluwatar/decorator/Troll.java b/decorator/src/main/java/com/iluwatar/decorator/Troll.java index 628adda4b..0fff3b812 100644 --- a/decorator/src/main/java/com/iluwatar/decorator/Troll.java +++ b/decorator/src/main/java/com/iluwatar/decorator/Troll.java @@ -22,6 +22,9 @@ */ package com.iluwatar.decorator; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * * Troll implements {@link Hostile} interface directly. @@ -29,9 +32,11 @@ package com.iluwatar.decorator; */ public class Troll implements Hostile { + private static final Logger LOGGER = LoggerFactory.getLogger(Troll.class); + @Override public void attack() { - System.out.println("The troll swings at you with a club!"); + LOGGER.info("The troll swings at you with a club!"); } @Override @@ -41,6 +46,6 @@ public class Troll implements Hostile { @Override public void fleeBattle() { - System.out.println("The troll shrieks in horror and runs away!"); + LOGGER.info("The troll shrieks in horror and runs away!"); } } diff --git a/decorator/src/test/java/com/iluwatar/decorator/TrollTest.java b/decorator/src/test/java/com/iluwatar/decorator/TrollTest.java index 84b0f6d20..652c1fcdc 100644 --- a/decorator/src/test/java/com/iluwatar/decorator/TrollTest.java +++ b/decorator/src/test/java/com/iluwatar/decorator/TrollTest.java @@ -22,16 +22,18 @@ */ package com.iluwatar.decorator; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.AppenderBase; import org.junit.After; import org.junit.Before; import org.junit.Test; +import org.slf4j.LoggerFactory; -import java.io.PrintStream; +import java.util.LinkedList; +import java.util.List; import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.*; -import static org.mockito.internal.verification.VerificationModeFactory.times; /** * Date: 12/7/15 - 7:26 PM @@ -40,31 +42,16 @@ import static org.mockito.internal.verification.VerificationModeFactory.times; */ public class TrollTest { - /** - * The mocked standard out stream, required since the actions don't have any influence on other - * objects, except for writing to the std-out using {@link System#out} - */ - private final PrintStream stdOutMock = mock(PrintStream.class); + private InMemoryAppender appender; - /** - * Keep the original std-out so it can be restored after the test - */ - private final PrintStream stdOutOrig = System.out; - - /** - * Inject the mocked std-out {@link PrintStream} into the {@link System} class before each test - */ @Before public void setUp() { - System.setOut(this.stdOutMock); + appender = new InMemoryAppender(Troll.class); } - /** - * Removed the mocked std-out {@link PrintStream} again from the {@link System} class - */ @After public void tearDown() { - System.setOut(this.stdOutOrig); + appender.stop(); } @Test @@ -73,12 +60,34 @@ public class TrollTest { assertEquals(10, troll.getAttackPower()); troll.attack(); - verify(this.stdOutMock, times(1)).println(eq("The troll swings at you with a club!")); + assertEquals("The troll swings at you with a club!", appender.getLastMessage()); troll.fleeBattle(); - verify(this.stdOutMock, times(1)).println(eq("The troll shrieks in horror and runs away!")); + assertEquals("The troll shrieks in horror and runs away!", appender.getLastMessage()); - verifyNoMoreInteractions(this.stdOutMock); + assertEquals(2, appender.getLogSize()); } -} \ No newline at end of file + private class InMemoryAppender extends AppenderBase { + + private List log = new LinkedList<>(); + + public InMemoryAppender(Class clazz) { + ((Logger) LoggerFactory.getLogger(clazz)).addAppender(this); + start(); + } + + @Override + protected void append(ILoggingEvent eventObject) { + log.add(eventObject); + } + + public String getLastMessage() { + return log.get(log.size() - 1).getMessage(); + } + + public int getLogSize() { + return log.size(); + } + } +} 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 5e3966d85..1664e86e4 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 @@ -23,6 +23,8 @@ package com.iluwatar.delegation.simple.printers; import com.iluwatar.delegation.simple.Printer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * Specialised Implementation of {@link Printer} for a Canon Printer, in @@ -32,12 +34,14 @@ import com.iluwatar.delegation.simple.Printer; */ public class CanonPrinter implements Printer { + private static final Logger LOGGER = LoggerFactory.getLogger(CanonPrinter.class); + /** * {@inheritDoc} */ @Override public void print(String message) { - System.out.print("Canon Printer : " + 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 d37fbf613..f67f9defa 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 @@ -23,6 +23,8 @@ package com.iluwatar.delegation.simple.printers; import com.iluwatar.delegation.simple.Printer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * Specialised Implementation of {@link Printer} for a Epson Printer, in @@ -32,12 +34,14 @@ import com.iluwatar.delegation.simple.Printer; */ public class EpsonPrinter implements Printer { + private static final Logger LOGGER = LoggerFactory.getLogger(EpsonPrinter.class); + /** * {@inheritDoc} */ @Override public void print(String message) { - System.out.print("Epson Printer : " + 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 f81debf62..fdd89081b 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 @@ -23,6 +23,8 @@ package com.iluwatar.delegation.simple.printers; import com.iluwatar.delegation.simple.Printer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * Specialised Implementation of {@link Printer} for a HP Printer, in @@ -32,12 +34,14 @@ import com.iluwatar.delegation.simple.Printer; */ public class HpPrinter implements Printer { + private static final Logger LOGGER = LoggerFactory.getLogger(HpPrinter.class); + /** * {@inheritDoc} */ @Override public void print(String message) { - System.out.print("HP Printer : " + message); + LOGGER.info("HP Printer : {}", message); } } 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 6a19c9a1a..c1f32a8e0 100644 --- a/delegation/src/test/java/com/iluwatar/delegation/simple/DelegateTest.java +++ b/delegation/src/test/java/com/iluwatar/delegation/simple/DelegateTest.java @@ -22,28 +22,44 @@ */ package com.iluwatar.delegation.simple; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.AppenderBase; import com.iluwatar.delegation.simple.printers.CanonPrinter; import com.iluwatar.delegation.simple.printers.EpsonPrinter; import com.iluwatar.delegation.simple.printers.HpPrinter; -import org.junit.Rule; +import org.junit.After; +import org.junit.Before; import org.junit.Test; -import org.junit.contrib.java.lang.system.SystemOutRule; +import org.slf4j.LoggerFactory; + +import java.util.LinkedList; +import java.util.List; import static org.junit.Assert.assertEquals; public class DelegateTest { - private static final String MESSAGE = "Test Message Printed"; + private InMemoryAppender appender; - @Rule - public final SystemOutRule systemOutRule = new SystemOutRule().enableLog(); + @Before + public void setUp() { + appender = new InMemoryAppender(); + } + + @After + public void tearDown() { + appender.stop(); + } + + private static final String MESSAGE = "Test Message Printed"; @Test public void testCanonPrinter() throws Exception { PrinterController printerController = new PrinterController(new CanonPrinter()); printerController.print(MESSAGE); - assertEquals("Canon Printer : Test Message Printed", systemOutRule.getLog()); + assertEquals("Canon Printer : Test Message Printed", appender.getLastMessage()); } @Test @@ -51,7 +67,7 @@ public class DelegateTest { PrinterController printerController = new PrinterController(new HpPrinter()); printerController.print(MESSAGE); - assertEquals("HP Printer : Test Message Printed", systemOutRule.getLog()); + assertEquals("HP Printer : Test Message Printed", appender.getLastMessage()); } @Test @@ -59,7 +75,30 @@ public class DelegateTest { PrinterController printerController = new PrinterController(new EpsonPrinter()); printerController.print(MESSAGE); - assertEquals("Epson Printer : Test Message Printed", systemOutRule.getLog()); + assertEquals("Epson Printer : Test Message Printed", appender.getLastMessage()); + } + + private class InMemoryAppender extends AppenderBase { + + private List log = new LinkedList<>(); + + public InMemoryAppender() { + ((Logger) LoggerFactory.getLogger("root")).addAppender(this); + start(); + } + + @Override + protected void append(ILoggingEvent eventObject) { + log.add(eventObject); + } + + public String getLastMessage() { + return log.get(log.size() - 1).getFormattedMessage(); + } + + public int getLogSize() { + return log.size(); + } } } 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 74a564ab5..c003007e0 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 @@ -22,6 +22,9 @@ */ package com.iluwatar.dependency.injection; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * * Tobacco abstraction @@ -29,8 +32,10 @@ package com.iluwatar.dependency.injection; */ public abstract class Tobacco { + private static final Logger LOGGER = LoggerFactory.getLogger(Tobacco.class); + public void smoke(Wizard wizard) { - System.out.println(String.format("%s smoking %s", wizard.getClass().getSimpleName(), this - .getClass().getSimpleName())); + LOGGER.info("{} smoking {}", wizard.getClass().getSimpleName(), + this.getClass().getSimpleName()); } } 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 d1f5e574c..a0578626f 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 @@ -22,18 +22,31 @@ */ package com.iluwatar.dependency.injection; +import com.iluwatar.dependency.injection.utils.InMemoryAppender; +import org.junit.After; +import org.junit.Before; import org.junit.Test; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.junit.Assert.assertEquals; /** * Date: 12/10/15 - 8:40 PM * * @author Jeroen Meulemeester */ -public class AdvancedWizardTest extends StdOutTest { +public class AdvancedWizardTest { + + private InMemoryAppender appender; + + @Before + public void setUp() { + appender = new InMemoryAppender(Tobacco.class); + } + + @After + public void tearDown() { + appender.stop(); + } /** * Test if the {@link AdvancedWizard} smokes whatever instance of {@link Tobacco} is passed to him @@ -51,12 +64,13 @@ public class AdvancedWizardTest extends StdOutTest { advancedWizard.smoke(); // Verify if the wizard is smoking the correct tobacco ... - verify(getStdOutMock(), times(1)).println("AdvancedWizard smoking " + tobacco.getClass().getSimpleName()); + assertEquals("AdvancedWizard smoking " + tobacco.getClass().getSimpleName(), appender.getLastMessage()); - // ... and nothing else is happening. - verifyNoMoreInteractions(getStdOutMock()); } + // ... and nothing else is happening. + assertEquals(tobaccos.length, appender.getLogSize()); + } -} \ No newline at end of file +} 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 1d3d679df..811773678 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 @@ -25,19 +25,31 @@ package com.iluwatar.dependency.injection; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Injector; - +import com.iluwatar.dependency.injection.utils.InMemoryAppender; +import org.junit.After; +import org.junit.Before; import org.junit.Test; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.junit.Assert.assertEquals; /** * Date: 12/10/15 - 8:57 PM * * @author Jeroen Meulemeester */ -public class GuiceWizardTest extends StdOutTest { +public class GuiceWizardTest { + + private InMemoryAppender appender; + + @Before + public void setUp() { + appender = new InMemoryAppender(Tobacco.class); + } + + @After + public void tearDown() { + appender.stop(); + } /** * Test if the {@link GuiceWizard} smokes whatever instance of {@link Tobacco} is passed to him @@ -55,12 +67,11 @@ public class GuiceWizardTest extends StdOutTest { guiceWizard.smoke(); // Verify if the wizard is smoking the correct tobacco ... - verify(getStdOutMock(), times(1)).println("GuiceWizard smoking " + tobacco.getClass().getSimpleName()); - - // ... and nothing else is happening. - verifyNoMoreInteractions(getStdOutMock()); + assertEquals("GuiceWizard smoking " + tobacco.getClass().getSimpleName(), appender.getLastMessage()); } + // ... and nothing else is happening. + assertEquals(tobaccos.length, appender.getLogSize()); } /** @@ -89,12 +100,11 @@ public class GuiceWizardTest extends StdOutTest { guiceWizard.smoke(); // Verify if the wizard is smoking the correct tobacco ... - verify(getStdOutMock(), times(1)).println("GuiceWizard smoking " + tobaccoClass.getSimpleName()); - - // ... and nothing else is happening. - verifyNoMoreInteractions(getStdOutMock()); + assertEquals("GuiceWizard smoking " + tobaccoClass.getSimpleName(), appender.getLastMessage()); } + // ... and nothing else is happening. + assertEquals(tobaccos.length, appender.getLogSize()); } -} \ No newline at end of file +} 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 e5a856e8d..cda3eac47 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 @@ -22,16 +22,31 @@ */ package com.iluwatar.dependency.injection; +import com.iluwatar.dependency.injection.utils.InMemoryAppender; +import org.junit.After; +import org.junit.Before; import org.junit.Test; -import static org.mockito.Mockito.*; +import static org.junit.Assert.assertEquals; /** * Date: 12/10/15 - 8:26 PM * * @author Jeroen Meulemeester */ -public class SimpleWizardTest extends StdOutTest { +public class SimpleWizardTest { + + private InMemoryAppender appender; + + @Before + public void setUp() { + appender = new InMemoryAppender(Tobacco.class); + } + + @After + public void tearDown() { + appender.stop(); + } /** * Test if the {@link SimpleWizard} does the only thing it can do: Smoke it's {@link @@ -41,8 +56,8 @@ public class SimpleWizardTest extends StdOutTest { public void testSmoke() { final SimpleWizard simpleWizard = new SimpleWizard(); simpleWizard.smoke(); - verify(getStdOutMock(), times(1)).println("SimpleWizard smoking OldTobyTobacco"); - verifyNoMoreInteractions(getStdOutMock()); + assertEquals("SimpleWizard smoking OldTobyTobacco", appender.getLastMessage()); + assertEquals(1, appender.getLogSize()); } -} \ No newline at end of file +} diff --git a/dependency-injection/src/test/java/com/iluwatar/dependency/injection/StdOutTest.java b/dependency-injection/src/test/java/com/iluwatar/dependency/injection/StdOutTest.java deleted file mode 100644 index 57272c511..000000000 --- a/dependency-injection/src/test/java/com/iluwatar/dependency/injection/StdOutTest.java +++ /dev/null @@ -1,75 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014 Ilkka Seppälä - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package com.iluwatar.dependency.injection; - -import org.junit.After; -import org.junit.Before; - -import java.io.PrintStream; - -import static org.mockito.Mockito.mock; - -/** - * Date: 12/10/15 - 8:37 PM - * - * @author Jeroen Meulemeester - */ -public abstract class StdOutTest { - - /** - * The mocked standard out {@link PrintStream}, required since the actions of the wizard don't - * have any influence on any other accessible objects, except for writing to std-out using {@link - * System#out} - */ - private final PrintStream stdOutMock = mock(PrintStream.class); - - /** - * Keep the original std-out so it can be restored after the test - */ - private final PrintStream stdOutOrig = System.out; - - /** - * Inject the mocked std-out {@link PrintStream} into the {@link System} class before each test - */ - @Before - public void setUp() { - System.setOut(this.stdOutMock); - } - - /** - * Removed the mocked std-out {@link PrintStream} again from the {@link System} class - */ - @After - public void tearDown() { - System.setOut(this.stdOutOrig); - } - - /** - * Get the mocked stdOut {@link PrintStream} - * - * @return The stdOut print stream mock, renewed before each test - */ - final PrintStream getStdOutMock() { - return this.stdOutMock; - } -} 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 new file mode 100644 index 000000000..b4c60b8aa --- /dev/null +++ b/dependency-injection/src/test/java/com/iluwatar/dependency/injection/utils/InMemoryAppender.java @@ -0,0 +1,54 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.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; + +public class InMemoryAppender extends AppenderBase { + + private List log = new LinkedList<>(); + + public InMemoryAppender(Class clazz) { + ((Logger) LoggerFactory.getLogger(clazz)).addAppender(this); + start(); + } + + @Override + protected void append(ILoggingEvent eventObject) { + log.add(eventObject); + } + + public String getLastMessage() { + return log.get(log.size() - 1).getFormattedMessage(); + } + + public int getLogSize() { + return log.size(); + } +} 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 98309e181..9ce969037 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 @@ -22,6 +22,9 @@ */ package com.iluwatar.doublechecked.locking; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; @@ -40,6 +43,8 @@ import java.util.concurrent.TimeUnit; */ public class App { + private static final Logger LOGGER = LoggerFactory.getLogger(App.class); + /** * Program entry point * @@ -58,7 +63,7 @@ public class App { try { executorService.awaitTermination(5, TimeUnit.SECONDS); } catch (InterruptedException e) { - System.out.println("Error waiting for ExecutorService shutdown"); + LOGGER.error("Error waiting for ExecutorService shutdown"); } } } 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 176203a44..09a14d320 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 @@ -22,6 +22,9 @@ */ package com.iluwatar.doublechecked.locking; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -35,6 +38,8 @@ import java.util.concurrent.locks.ReentrantLock; */ public class Inventory { + private static final Logger LOGGER = LoggerFactory.getLogger(Inventory.class); + private final int inventorySize; private final List items; private final Lock lock; @@ -57,8 +62,7 @@ public class Inventory { try { if (items.size() < inventorySize) { items.add(item); - System.out.println(Thread.currentThread() + ": items.size()=" + items.size() - + ", inventorySize=" + inventorySize); + LOGGER.info("{}: items.size()={}, inventorySize={}", Thread.currentThread(), items.size(), inventorySize); return true; } } finally { diff --git a/double-checked-locking/src/main/resources/logback.xml b/double-checked-locking/src/main/resources/logback.xml new file mode 100644 index 000000000..c4c3058de --- /dev/null +++ b/double-checked-locking/src/main/resources/logback.xml @@ -0,0 +1,52 @@ + + + + double-checked-locking.log + + double-checked-locking-%d.log + 5 + + + %-5p [%d{ISO8601,UTC}] %c: %m%n + + + + + + %-5p [%d{ISO8601,UTC}] %c: %m%n + + + + + + + + + + + + + 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 485c9573e..9f5f608b0 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 @@ -22,24 +22,23 @@ */ package com.iluwatar.doublechecked.locking; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.AppenderBase; import org.junit.After; import org.junit.Before; import org.junit.Test; -import org.mockito.ArgumentCaptor; +import org.slf4j.LoggerFactory; -import java.io.PrintStream; +import java.util.LinkedList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; -import static junit.framework.Assert.assertTrue; import static junit.framework.TestCase.assertEquals; import static org.junit.Assert.assertNotNull; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.junit.Assert.assertTrue; /** * Date: 12/10/15 - 9:34 PM @@ -48,31 +47,16 @@ import static org.mockito.Mockito.verifyNoMoreInteractions; */ public class InventoryTest { - /** - * The mocked standard out {@link PrintStream}, used to verify a steady increasing size of the - * {@link Inventory} while adding items from multiple threads concurrently - */ - private final PrintStream stdOutMock = mock(PrintStream.class); + private InMemoryAppender appender; - /** - * Keep the original std-out so it can be restored after the test - */ - private final PrintStream stdOutOrig = System.out; - - /** - * Inject the mocked std-out {@link PrintStream} into the {@link System} class before each test - */ @Before public void setUp() { - System.setOut(this.stdOutMock); + appender = new InMemoryAppender(Inventory.class); } - /** - * Removed the mocked std-out {@link PrintStream} again from the {@link System} class - */ @After public void tearDown() { - System.setOut(this.stdOutOrig); + appender.stop(); } /** @@ -112,21 +96,32 @@ public class InventoryTest { assertNotNull(items); assertEquals(INVENTORY_SIZE, items.size()); - // Capture all stdOut messages ... - final ArgumentCaptor stdOutCaptor = ArgumentCaptor.forClass(String.class); - verify(this.stdOutMock, times(INVENTORY_SIZE)).println(stdOutCaptor.capture()); - - // ... verify if we got all 1000 - final List values = stdOutCaptor.getAllValues(); - assertEquals(INVENTORY_SIZE, values.size()); + assertEquals(INVENTORY_SIZE, appender.getLogSize()); // ... and check if the inventory size is increasing continuously - for (int i = 0; i < values.size(); i++) { - assertNotNull(values.get(i)); - assertTrue(values.get(i).contains("items.size()=" + (i + 1))); + for (int i = 0; i < items.size(); i++) { + assertTrue(appender.log.get(i).getFormattedMessage().contains("items.size()=" + (i + 1))); } - - verifyNoMoreInteractions(this.stdOutMock); } -} \ No newline at end of file + + + private class InMemoryAppender extends AppenderBase { + private List log = new LinkedList<>(); + + public InMemoryAppender(Class clazz) { + ((Logger) LoggerFactory.getLogger(clazz)).addAppender(this); + start(); + } + + @Override + protected void append(ILoggingEvent eventObject) { + log.add(eventObject); + } + + public int getLogSize() { + return log.size(); + } + } + +} 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 40a0485a5..601b0fcc0 100644 --- a/double-dispatch/src/main/java/com/iluwatar/doubledispatch/App.java +++ b/double-dispatch/src/main/java/com/iluwatar/doubledispatch/App.java @@ -22,6 +22,9 @@ */ package com.iluwatar.doubledispatch; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.util.ArrayList; import java.util.List; @@ -45,6 +48,8 @@ import java.util.List; */ public class App { + private static final Logger LOGGER = LoggerFactory.getLogger(App.class); + /** * Program entry point * @@ -58,8 +63,8 @@ public class App { objects.add(new SpaceStationMir(1, 1, 2, 2)); objects.add(new Meteoroid(10, 10, 15, 15)); objects.add(new SpaceStationIss(12, 12, 14, 14)); - objects.stream().forEach(o -> System.out.println(o)); - System.out.println(""); + objects.stream().forEach(o -> LOGGER.info(o.toString())); + LOGGER.info(""); // collision check objects.stream().forEach(o1 -> objects.stream().forEach(o2 -> { @@ -67,10 +72,10 @@ public class App { o1.collision(o2); } })); - System.out.println(""); + LOGGER.info(""); // output eventual object statuses - objects.stream().forEach(o -> System.out.println(o)); - System.out.println(""); + objects.stream().forEach(o -> LOGGER.info(o.toString())); + LOGGER.info(""); } } 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 cc68a85ec..fcda7f312 100644 --- a/double-dispatch/src/main/java/com/iluwatar/doubledispatch/Meteoroid.java +++ b/double-dispatch/src/main/java/com/iluwatar/doubledispatch/Meteoroid.java @@ -22,6 +22,9 @@ */ package com.iluwatar.doubledispatch; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * * Meteoroid game object @@ -29,6 +32,8 @@ package com.iluwatar.doubledispatch; */ public class Meteoroid extends GameObject { + private static final Logger LOGGER = LoggerFactory.getLogger(Meteoroid.class); + public Meteoroid(int left, int top, int right, int bottom) { super(left, top, right, bottom); } @@ -40,25 +45,21 @@ public class Meteoroid extends GameObject { @Override public void collisionResolve(FlamingAsteroid asteroid) { - System.out.println(String.format("%s hits %s.", asteroid.getClass().getSimpleName(), this - .getClass().getSimpleName())); + LOGGER.info("{} hits {}.", asteroid.getClass().getSimpleName(), this.getClass().getSimpleName()); } @Override public void collisionResolve(Meteoroid meteoroid) { - System.out.println(String.format("%s hits %s.", meteoroid.getClass().getSimpleName(), this - .getClass().getSimpleName())); + LOGGER.info("{} hits {}.", meteoroid.getClass().getSimpleName(), this.getClass().getSimpleName()); } @Override public void collisionResolve(SpaceStationMir mir) { - System.out.println(String.format("%s hits %s.", mir.getClass().getSimpleName(), this.getClass() - .getSimpleName())); + LOGGER.info("{} hits {}.", mir.getClass().getSimpleName(), this.getClass().getSimpleName()); } @Override public void collisionResolve(SpaceStationIss iss) { - System.out.println(String.format("%s hits %s.", iss.getClass().getSimpleName(), this.getClass() - .getSimpleName())); + LOGGER.info("{} hits {}.", iss.getClass().getSimpleName(), this.getClass().getSimpleName()); } } 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 e7a55d0ee..c1f750059 100644 --- a/double-dispatch/src/main/java/com/iluwatar/doubledispatch/SpaceStationMir.java +++ b/double-dispatch/src/main/java/com/iluwatar/doubledispatch/SpaceStationMir.java @@ -22,6 +22,9 @@ */ package com.iluwatar.doubledispatch; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * * Space station Mir game object @@ -29,6 +32,8 @@ package com.iluwatar.doubledispatch; */ public class SpaceStationMir extends GameObject { + private static final Logger LOGGER = LoggerFactory.getLogger(SpaceStationMir.class); + public SpaceStationMir(int left, int top, int right, int bottom) { super(left, top, right, bottom); } @@ -40,31 +45,30 @@ public class SpaceStationMir extends GameObject { @Override public void collisionResolve(FlamingAsteroid asteroid) { - System.out.println(String.format("%s hits %s. %s is damaged! %s is set on fire!", asteroid - .getClass().getSimpleName(), this.getClass().getSimpleName(), this.getClass() - .getSimpleName(), this.getClass().getSimpleName())); + LOGGER.info("{} hits {}. {} is damaged! {} is set on fire!", asteroid.getClass().getSimpleName(), + this.getClass().getSimpleName(), this.getClass().getSimpleName(), this.getClass().getSimpleName()); setDamaged(true); setOnFire(true); } @Override public void collisionResolve(Meteoroid meteoroid) { - System.out.println(String.format("%s hits %s. %s is damaged!", meteoroid.getClass() - .getSimpleName(), this.getClass().getSimpleName(), this.getClass().getSimpleName())); + LOGGER.info("{} hits {}. {} is damaged!", meteoroid.getClass().getSimpleName(), + this.getClass().getSimpleName(), this.getClass().getSimpleName()); setDamaged(true); } @Override public void collisionResolve(SpaceStationMir mir) { - System.out.println(String.format("%s hits %s. %s is damaged!", mir.getClass().getSimpleName(), - this.getClass().getSimpleName(), this.getClass().getSimpleName())); + LOGGER.info("{} hits {}. {} is damaged!", mir.getClass().getSimpleName(), + this.getClass().getSimpleName(), this.getClass().getSimpleName()); setDamaged(true); } @Override public void collisionResolve(SpaceStationIss iss) { - System.out.println(String.format("%s hits %s. %s is damaged!", iss.getClass().getSimpleName(), - this.getClass().getSimpleName(), this.getClass().getSimpleName())); + LOGGER.info("{} hits {}. {} is damaged!", iss.getClass().getSimpleName(), + this.getClass().getSimpleName(), this.getClass().getSimpleName()); setDamaged(true); } } 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 dbc8fc55e..6576d6d2f 100644 --- a/double-dispatch/src/test/java/com/iluwatar/doubledispatch/CollisionTest.java +++ b/double-dispatch/src/test/java/com/iluwatar/doubledispatch/CollisionTest.java @@ -22,17 +22,9 @@ */ package com.iluwatar.doubledispatch; -import org.junit.After; -import org.junit.Before; - -import java.io.PrintStream; import java.util.Objects; import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; /** * Date: 12/10/15 - 8:37 PM @@ -41,43 +33,6 @@ import static org.mockito.Mockito.verifyNoMoreInteractions; */ public abstract class CollisionTest { - /** - * The mocked standard out {@link PrintStream}, required if some of the actions on the tested - * object don't have a direct influence on any other accessible objects, except for writing to - * std-out using {@link System#out} - */ - private final PrintStream stdOutMock = mock(PrintStream.class); - - /** - * Keep the original std-out so it can be restored after the test - */ - private final PrintStream stdOutOrig = System.out; - - /** - * Inject the mocked std-out {@link PrintStream} into the {@link System} class before each test - */ - @Before - public void setUp() { - System.setOut(this.stdOutMock); - } - - /** - * Removed the mocked std-out {@link PrintStream} again from the {@link System} class - */ - @After - public void tearDown() { - System.setOut(this.stdOutOrig); - } - - /** - * Get the mocked stdOut {@link PrintStream} - * - * @return The stdOut print stream mock, renewed before each test - */ - final PrintStream getStdOutMock() { - return this.stdOutMock; - } - /** * Get the tested object * @@ -106,9 +61,6 @@ public abstract class CollisionTest { tested.collision(other); - verify(getStdOutMock(), times(1)).println(description); - verifyNoMoreInteractions(getStdOutMock()); - testOnFire(other, tested, otherOnFire); testDamaged(other, tested, otherDamaged); @@ -129,8 +81,8 @@ public abstract class CollisionTest { final String targetName = target.getClass().getSimpleName(); final String otherName = other.getClass().getSimpleName(); - final String errorMessage = expectTargetOnFire - ? "Expected [" + targetName + "] to be on fire after colliding with [" + otherName + "] but it was not!" + final String 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(errorMessage, expectTargetOnFire, target.isOnFire()); @@ -149,7 +101,7 @@ public abstract class CollisionTest { final String otherName = other.getClass().getSimpleName(); final String errorMessage = expectedDamage - ? "Expected [" + targetName + "] to be damaged after colliding with [" + otherName + "] but it was not!" + ? "Expected [" + targetName + "] to be damaged after colliding with [" + otherName + "] but it was not!" : "Expected [" + targetName + "] not to be damaged after colliding with [" + otherName + "] but it was!"; assertEquals(errorMessage, expectedDamage, target.isDamaged()); 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 fdda59693..1a0ad3345 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 @@ -22,6 +22,9 @@ */ package com.iluwatar.event.aggregator; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * * KingJoffrey observes events from {@link KingsHand}. @@ -29,8 +32,10 @@ package com.iluwatar.event.aggregator; */ public class KingJoffrey implements EventObserver { + private static final Logger LOGGER = LoggerFactory.getLogger(KingJoffrey.class); + @Override public void onEvent(Event e) { - System.out.println("Received event from the King's Hand: " + e.toString()); + LOGGER.info("Received event from the King's Hand: {}", e.toString()); } } 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 3e0028ac4..e06d10b6a 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 @@ -22,17 +22,18 @@ */ package com.iluwatar.event.aggregator; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.AppenderBase; import org.junit.After; import org.junit.Before; import org.junit.Test; +import org.slf4j.LoggerFactory; -import java.io.PrintStream; +import java.util.LinkedList; +import java.util.List; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyZeroInteractions; -import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.junit.Assert.assertEquals; /** * Date: 12/12/15 - 3:04 PM @@ -41,31 +42,16 @@ import static org.mockito.Mockito.verifyNoMoreInteractions; */ public class KingJoffreyTest { - /** - * The mocked standard out {@link PrintStream}, required since {@link KingJoffrey} does nothing - * except for writing to std-out using {@link System#out} - */ - private final PrintStream stdOutMock = mock(PrintStream.class); + private InMemoryAppender appender; - /** - * Keep the original std-out so it can be restored after the test - */ - private final PrintStream stdOutOrig = System.out; - - /** - * Inject the mocked std-out {@link PrintStream} into the {@link System} class before each test - */ @Before public void setUp() { - System.setOut(this.stdOutMock); + appender = new InMemoryAppender(KingJoffrey.class); } - /** - * Removed the mocked std-out {@link PrintStream} again from the {@link System} class - */ @After public void tearDown() { - System.setOut(this.stdOutOrig); + appender.stop(); } /** @@ -75,15 +61,38 @@ public class KingJoffreyTest { public void testOnEvent() { final KingJoffrey kingJoffrey = new KingJoffrey(); - for (final Event event : Event.values()) { - verifyZeroInteractions(this.stdOutMock); + for (int i = 0; i < Event.values().length; ++i) { + assertEquals(i, appender.getLogSize()); + Event event = Event.values()[i]; kingJoffrey.onEvent(event); final String expectedMessage = "Received event from the King's Hand: " + event.toString(); - verify(this.stdOutMock, times(1)).println(expectedMessage); - verifyNoMoreInteractions(this.stdOutMock); + assertEquals(expectedMessage, appender.getLastMessage()); + assertEquals(i + 1, appender.getLogSize()); } } -} \ No newline at end of file + private class InMemoryAppender extends AppenderBase { + private List log = new LinkedList<>(); + + public InMemoryAppender(Class clazz) { + ((Logger) LoggerFactory.getLogger(clazz)).addAppender(this); + start(); + } + + @Override + protected void append(ILoggingEvent eventObject) { + log.add(eventObject); + } + + public String getLastMessage() { + return log.get(log.size() - 1).getFormattedMessage(); + } + + public int getLogSize() { + return log.size(); + } + } + +} diff --git a/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/App.java b/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/App.java index 5a2565940..c7c543434 100644 --- a/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/App.java +++ b/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/App.java @@ -16,38 +16,43 @@ */ package com.iluwatar.event.asynchronous; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.io.IOException; import java.io.InputStream; import java.util.Properties; import java.util.Scanner; /** - * + * * This application demonstrates the Event-based Asynchronous pattern. Essentially, users (of the pattern) may * choose to run events in an Asynchronous or Synchronous mode. There can be multiple Asynchronous events running at * once but only one Synchronous event can run at a time. Asynchronous events are synonymous to multi-threads. The key * point here is that the threads run in the background and the user is free to carry on with other processes. Once an * event is complete, the appropriate listener/callback method will be called. The listener then proceeds to carry out * further processing depending on the needs of the user. - * + * * The {@link EventManager} manages the events/threads that the user creates. Currently, the supported event operations * are: start, stop, getStatus. For Synchronous events, the user is unable to * start another (Synchronous) event if one is already running at the time. The running event would have to either be * stopped or completed before a new event can be started. - * + * * The Event-based Asynchronous Pattern makes available the advantages of multithreaded applications while hiding many * of the complex issues inherent in multithreaded design. Using a class that supports this pattern can allow you to:- * (1) Perform time-consuming tasks, such as downloads and database operations, "in the background," without * interrupting your application. (2) Execute multiple operations simultaneously, receiving notifications when each * completes. (3) Wait for resources to become available without stopping ("hanging") your application. (4) Communicate * with pending asynchronous operations using the familiar events-and-delegates model. - * + * * @see EventManager * @see Event * */ public class App { + private static final Logger LOGGER = LoggerFactory.getLogger(App.class); + public static final String PROP_FILE_NAME = "config.properties"; boolean interactiveMode = false; @@ -77,7 +82,7 @@ public class App { try { prop.load(inputStream); } catch (IOException e) { - System.out.println(PROP_FILE_NAME + " was not found. Defaulting to non-interactive mode."); + LOGGER.error("{} was not found. Defaulting to non-interactive mode.", PROP_FILE_NAME, e); } String property = prop.getProperty("INTERACTIVE_MODE"); if (property.equalsIgnoreCase("YES")) { @@ -106,27 +111,27 @@ public class App { try { // Create an Asynchronous event. int aEventId = eventManager.createAsync(60); - System.out.println("Async Event [" + aEventId + "] has been created."); + LOGGER.info("Async Event [{}] has been created.", aEventId); eventManager.start(aEventId); - System.out.println("Async Event [" + aEventId + "] has been started."); + LOGGER.info("Async Event [{}] has been started.", aEventId); // Create a Synchronous event. int sEventId = eventManager.create(60); - System.out.println("Sync Event [" + sEventId + "] has been created."); + LOGGER.info("Sync Event [{}] has been created.", sEventId); eventManager.start(sEventId); - System.out.println("Sync Event [" + sEventId + "] has been started."); + LOGGER.info("Sync Event [{}] has been started.", sEventId); eventManager.status(aEventId); eventManager.status(sEventId); eventManager.cancel(aEventId); - System.out.println("Async Event [" + aEventId + "] has been stopped."); + LOGGER.info("Async Event [{}] has been stopped.", aEventId); eventManager.cancel(sEventId); - System.out.println("Sync Event [" + sEventId + "] has been stopped."); + LOGGER.info("Sync Event [{}] has been stopped.", sEventId); } catch (MaxNumOfEventsAllowedException | LongRunningEventException | EventDoesNotExistException | InvalidOperationException e) { - System.out.println(e.getMessage()); + LOGGER.error(e.getMessage()); } } @@ -139,58 +144,58 @@ public class App { Scanner s = new Scanner(System.in); int option = -1; while (option != 4) { - System.out.println("Hello. Would you like to boil some eggs?"); - System.out.println("(1) BOIL AN EGG \n(2) STOP BOILING THIS EGG \n(3) HOW ARE MY EGGS? \n(4) EXIT"); - System.out.print("Choose [1,2,3,4]: "); + LOGGER.info("Hello. Would you like to boil some eggs?"); + LOGGER.info("(1) BOIL AN EGG \n(2) STOP BOILING THIS EGG \n(3) HOW ARE MY EGGS? \n(4) EXIT"); + LOGGER.info("Choose [1,2,3,4]: "); option = s.nextInt(); if (option == 1) { s.nextLine(); - System.out.print("Boil multiple eggs at once (A) or boil them one-by-one (S)?: "); + LOGGER.info("Boil multiple eggs at once (A) or boil them one-by-one (S)?: "); String eventType = s.nextLine(); - System.out.print("How long should this egg be boiled for (in seconds)?: "); + LOGGER.info("How long should this egg be boiled for (in seconds)?: "); int eventTime = s.nextInt(); if (eventType.equalsIgnoreCase("A")) { try { int eventId = eventManager.createAsync(eventTime); eventManager.start(eventId); - System.out.println("Egg [" + eventId + "] is being boiled."); + LOGGER.info("Egg [{}] is being boiled.", eventId); } catch (MaxNumOfEventsAllowedException | LongRunningEventException | EventDoesNotExistException e) { - System.out.println(e.getMessage()); + LOGGER.error(e.getMessage()); } } else if (eventType.equalsIgnoreCase("S")) { try { int eventId = eventManager.create(eventTime); eventManager.start(eventId); - System.out.println("Egg [" + eventId + "] is being boiled."); + LOGGER.info("Egg [{}] is being boiled.", eventId); } catch (MaxNumOfEventsAllowedException | InvalidOperationException | LongRunningEventException | EventDoesNotExistException e) { - System.out.println(e.getMessage()); + LOGGER.error(e.getMessage()); } } else { - System.out.println("Unknown event type."); + LOGGER.info("Unknown event type."); } } else if (option == 2) { - System.out.print("Which egg?: "); + LOGGER.info("Which egg?: "); int eventId = s.nextInt(); try { eventManager.cancel(eventId); - System.out.println("Egg [" + eventId + "] is removed from boiler."); + LOGGER.info("Egg [{}] is removed from boiler.", eventId); } catch (EventDoesNotExistException e) { - System.out.println(e.getMessage()); + LOGGER.error(e.getMessage()); } } else if (option == 3) { s.nextLine(); - System.out.print("Just one egg (O) OR all of them (A) ?: "); + LOGGER.info("Just one egg (O) OR all of them (A) ?: "); String eggChoice = s.nextLine(); if (eggChoice.equalsIgnoreCase("O")) { - System.out.print("Which egg?: "); + LOGGER.info("Which egg?: "); int eventId = s.nextInt(); try { eventManager.status(eventId); } catch (EventDoesNotExistException e) { - System.out.println(e.getMessage()); + LOGGER.error(e.getMessage()); } } else if (eggChoice.equalsIgnoreCase("A")) { eventManager.statusOfAllEvents(); diff --git a/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/Event.java b/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/Event.java index 5e557fff2..bd4687dd5 100644 --- a/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/Event.java +++ b/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/Event.java @@ -16,13 +16,18 @@ */ package com.iluwatar.event.asynchronous; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** - * + * * Each Event runs as a separate/individual thread. * */ public class Event implements IEvent, Runnable { + private static final Logger LOGGER = LoggerFactory.getLogger(Event.class); + private int eventId; private int eventTime; private boolean isSynchronous; @@ -31,7 +36,7 @@ public class Event implements IEvent, Runnable { private ThreadCompleteListener eventListener; /** - * + * * @param eventId event ID * @param eventTime event time * @param isSynchronous is of synchronous type @@ -63,9 +68,9 @@ public class Event implements IEvent, Runnable { @Override public void status() { if (!isComplete) { - System.out.println("[" + eventId + "] is not done."); + LOGGER.info("[{}] is not done.", eventId); } else { - System.out.println("[" + eventId + "] is done."); + LOGGER.info("[{}] is done.", eventId); } } diff --git a/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/EventManager.java b/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/EventManager.java index dae995e38..e181e8704 100644 --- a/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/EventManager.java +++ b/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/EventManager.java @@ -22,7 +22,7 @@ import java.util.Random; import java.util.concurrent.ConcurrentHashMap; /** - * + * * EventManager handles and maintains a pool of event threads. {@link Event} 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. @@ -52,7 +52,7 @@ public class EventManager implements ThreadCompleteListener { /** * Create a Synchronous event. - * + * * @param eventTime Time an event should run for. * @return eventId * @throws MaxNumOfEventsAllowedException When too many events are running at a time. @@ -74,7 +74,7 @@ public class EventManager implements ThreadCompleteListener { /** * Create an Asynchronous event. - * + * * @param eventTime Time an event should run for. * @return eventId * @throws MaxNumOfEventsAllowedException When too many events are running at a time. @@ -106,7 +106,7 @@ public class EventManager implements ThreadCompleteListener { /** * Starts event. - * + * * @param eventId The event that needs to be started. * @throws EventDoesNotExistException If event does not exist in our eventPool. */ @@ -120,7 +120,7 @@ public class EventManager implements ThreadCompleteListener { /** * Stops event. - * + * * @param eventId The event that needs to be stopped. * @throws EventDoesNotExistException If event does not exist in our eventPool. */ @@ -139,7 +139,7 @@ public class EventManager implements ThreadCompleteListener { /** * Get status of a running event. - * + * * @param eventId The event to inquire status of. * @throws EventDoesNotExistException If event does not exist in our eventPool. */ diff --git a/event-asynchronous/src/test/java/com/iluwatar/event/asynchronous/EventAsynchronousTest.java b/event-asynchronous/src/test/java/com/iluwatar/event/asynchronous/EventAsynchronousTest.java index 213439203..f032c8971 100644 --- a/event-asynchronous/src/test/java/com/iluwatar/event/asynchronous/EventAsynchronousTest.java +++ b/event-asynchronous/src/test/java/com/iluwatar/event/asynchronous/EventAsynchronousTest.java @@ -16,10 +16,12 @@ */ package com.iluwatar.event.asynchronous; -import static org.junit.Assert.assertTrue; - import org.junit.Before; import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import static org.junit.Assert.assertTrue; /** * @@ -29,6 +31,8 @@ import org.junit.Test; public class EventAsynchronousTest { App app; + private static final Logger LOGGER = LoggerFactory.getLogger(EventAsynchronousTest.class); + @Before public void setUp() { app = new App(); @@ -46,7 +50,7 @@ public class EventAsynchronousTest { eventManager.cancel(aEventId); assertTrue(eventManager.getEventPool().size() == 0); } catch (MaxNumOfEventsAllowedException | LongRunningEventException | EventDoesNotExistException e) { - System.out.println(e.getMessage()); + LOGGER.error(e.getMessage()); } } @@ -63,7 +67,7 @@ public class EventAsynchronousTest { assertTrue(eventManager.getEventPool().size() == 0); } catch (MaxNumOfEventsAllowedException | LongRunningEventException | EventDoesNotExistException | InvalidOperationException e) { - System.out.println(e.getMessage()); + LOGGER.error(e.getMessage()); } } @@ -76,7 +80,7 @@ public class EventAsynchronousTest { sEventId = eventManager.create(60); eventManager.start(sEventId); } catch (MaxNumOfEventsAllowedException | LongRunningEventException | EventDoesNotExistException e) { - System.out.println(e.getMessage()); + LOGGER.error(e.getMessage()); } } @@ -101,7 +105,7 @@ public class EventAsynchronousTest { } catch (MaxNumOfEventsAllowedException | LongRunningEventException | EventDoesNotExistException | InvalidOperationException e) { - System.out.println(e.getMessage()); + LOGGER.error(e.getMessage()); } } @@ -129,7 +133,7 @@ public class EventAsynchronousTest { assertTrue(eventManager.getEventPool().size() == 0); } catch (MaxNumOfEventsAllowedException | LongRunningEventException | EventDoesNotExistException e) { - System.out.println(e.getMessage()); + LOGGER.error(e.getMessage()); } } } 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 3ef4e8255..ded6b76ce 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 @@ -24,17 +24,19 @@ package com.iluwatar.eda.handler; import com.iluwatar.eda.event.UserCreatedEvent; import com.iluwatar.eda.framework.Handler; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * Handles the {@link UserCreatedEvent} message. */ public class UserCreatedEventHandler implements Handler { + private static final Logger LOGGER = LoggerFactory.getLogger(UserCreatedEventHandler.class); + @Override public void onEvent(UserCreatedEvent event) { - - System.out.println(String.format( - "User '%s' has been Created!", event.getUser().getUsername())); + LOGGER.info("User '{}' has been Created!", event.getUser().getUsername()); } } 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 0311d5781..a0bf28c57 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 @@ -24,16 +24,18 @@ package com.iluwatar.eda.handler; import com.iluwatar.eda.event.UserUpdatedEvent; import com.iluwatar.eda.framework.Handler; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * Handles the {@link UserUpdatedEvent} message. */ public class UserUpdatedEventHandler implements Handler { + private static final Logger LOGGER = LoggerFactory.getLogger(UserUpdatedEventHandler.class); + @Override public void onEvent(UserUpdatedEvent event) { - - System.out.println(String.format( - "User '%s' has been Updated!", event.getUser().getUsername())); + LOGGER.info("User '{}' has been Updated!", event.getUser().getUsername()); } } diff --git a/facade/src/main/java/com/iluwatar/facade/DwarvenCartOperator.java b/facade/src/main/java/com/iluwatar/facade/DwarvenCartOperator.java index bdc839f57..61e64a153 100644 --- a/facade/src/main/java/com/iluwatar/facade/DwarvenCartOperator.java +++ b/facade/src/main/java/com/iluwatar/facade/DwarvenCartOperator.java @@ -22,6 +22,9 @@ */ package com.iluwatar.facade; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * * DwarvenCartOperator is one of the goldmine subsystems. @@ -29,9 +32,11 @@ package com.iluwatar.facade; */ public class DwarvenCartOperator extends DwarvenMineWorker { + private static final Logger LOGGER = LoggerFactory.getLogger(DwarvenCartOperator.class); + @Override public void work() { - System.out.println(name() + " moves gold chunks out of the mine."); + LOGGER.info("{} moves gold chunks out of the mine.", name()); } @Override diff --git a/facade/src/main/java/com/iluwatar/facade/DwarvenGoldDigger.java b/facade/src/main/java/com/iluwatar/facade/DwarvenGoldDigger.java index 54fa821f4..2eb464edf 100644 --- a/facade/src/main/java/com/iluwatar/facade/DwarvenGoldDigger.java +++ b/facade/src/main/java/com/iluwatar/facade/DwarvenGoldDigger.java @@ -22,6 +22,9 @@ */ package com.iluwatar.facade; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * * DwarvenGoldDigger is one of the goldmine subsystems. @@ -29,9 +32,11 @@ package com.iluwatar.facade; */ public class DwarvenGoldDigger extends DwarvenMineWorker { + private static final Logger LOGGER = LoggerFactory.getLogger(DwarvenGoldDigger.class); + @Override public void work() { - System.out.println(name() + " digs for gold."); + LOGGER.info("{} digs for gold.", name()); } @Override diff --git a/facade/src/main/java/com/iluwatar/facade/DwarvenMineWorker.java b/facade/src/main/java/com/iluwatar/facade/DwarvenMineWorker.java index f27054c53..48ec1db48 100644 --- a/facade/src/main/java/com/iluwatar/facade/DwarvenMineWorker.java +++ b/facade/src/main/java/com/iluwatar/facade/DwarvenMineWorker.java @@ -22,6 +22,9 @@ */ package com.iluwatar.facade; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * * DwarvenMineWorker is one of the goldmine subsystems. @@ -29,20 +32,22 @@ package com.iluwatar.facade; */ public abstract class DwarvenMineWorker { + private static final Logger LOGGER = LoggerFactory.getLogger(DwarvenMineWorker.class); + public void goToSleep() { - System.out.println(name() + " goes to sleep."); + LOGGER.info("{} goes to sleep.", name()); } public void wakeUp() { - System.out.println(name() + " wakes up."); + LOGGER.info("{} wakes up.", name()); } public void goHome() { - System.out.println(name() + " goes home."); + LOGGER.info("{} goes home.", name()); } public void goToMine() { - System.out.println(name() + " goes to the mine."); + LOGGER.info("{} goes to the mine.", name()); } private void action(Action action) { @@ -63,7 +68,7 @@ public abstract class DwarvenMineWorker { work(); break; default: - System.out.println("Undefined action"); + LOGGER.info("Undefined action"); break; } } diff --git a/facade/src/main/java/com/iluwatar/facade/DwarvenTunnelDigger.java b/facade/src/main/java/com/iluwatar/facade/DwarvenTunnelDigger.java index 74d8b89cc..54fcca73a 100644 --- a/facade/src/main/java/com/iluwatar/facade/DwarvenTunnelDigger.java +++ b/facade/src/main/java/com/iluwatar/facade/DwarvenTunnelDigger.java @@ -22,6 +22,9 @@ */ package com.iluwatar.facade; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * * DwarvenTunnelDigger is one of the goldmine subsystems. @@ -29,9 +32,11 @@ package com.iluwatar.facade; */ public class DwarvenTunnelDigger extends DwarvenMineWorker { + private static final Logger LOGGER = LoggerFactory.getLogger(DwarvenTunnelDigger.class); + @Override public void work() { - System.out.println(name() + " creates another promising tunnel."); + LOGGER.info("{} creates another promising tunnel.", name()); } @Override diff --git a/facade/src/test/java/com/iluwatar/facade/DwarvenGoldmineFacadeTest.java b/facade/src/test/java/com/iluwatar/facade/DwarvenGoldmineFacadeTest.java index 4a3b218e2..7718f7d41 100644 --- a/facade/src/test/java/com/iluwatar/facade/DwarvenGoldmineFacadeTest.java +++ b/facade/src/test/java/com/iluwatar/facade/DwarvenGoldmineFacadeTest.java @@ -22,17 +22,19 @@ */ package com.iluwatar.facade; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.AppenderBase; import org.junit.After; import org.junit.Before; import org.junit.Test; +import org.slf4j.LoggerFactory; -import java.io.PrintStream; +import java.util.LinkedList; +import java.util.List; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; -import static org.mockito.internal.verification.VerificationModeFactory.times; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; /** * Date: 12/9/15 - 9:40 PM @@ -41,35 +43,19 @@ import static org.mockito.internal.verification.VerificationModeFactory.times; */ public class DwarvenGoldmineFacadeTest { - /** - * The mocked standard out {@link PrintStream}, required since the actions on the gold mine facade - * don't have any influence on any other accessible objects, except for writing to std-out using - * {@link System#out} - */ - private final PrintStream stdOutMock = mock(PrintStream.class); + private InMemoryAppender appender; - /** - * Keep the original std-out so it can be restored after the test - */ - private final PrintStream stdOutOrig = System.out; - - /** - * Inject the mocked std-out {@link PrintStream} into the {@link System} class before each test - */ @Before public void setUp() { - System.setOut(this.stdOutMock); + appender = new InMemoryAppender(); } - /** - * Removed the mocked std-out {@link PrintStream} again from the {@link System} class - */ @After public void tearDown() { - System.setOut(this.stdOutOrig); + appender.stop(); } - /** + /** * 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()}. @@ -82,44 +68,68 @@ public class DwarvenGoldmineFacadeTest { goldMine.startNewDay(); // On the start of a day, all workers should wake up ... - verify(this.stdOutMock, times(1)).println(eq("Dwarf gold digger wakes up.")); - verify(this.stdOutMock, times(1)).println(eq("Dwarf cart operator wakes up.")); - verify(this.stdOutMock, times(1)).println(eq("Dwarven tunnel digger wakes up.")); + assertTrue(appender.logContains("Dwarf gold digger wakes up.")); + assertTrue(appender.logContains("Dwarf cart operator wakes up.")); + assertTrue(appender.logContains("Dwarven tunnel digger wakes up.")); // ... and go to the mine - verify(this.stdOutMock, times(1)).println(eq("Dwarf gold digger goes to the mine.")); - verify(this.stdOutMock, times(1)).println(eq("Dwarf cart operator goes to the mine.")); - verify(this.stdOutMock, times(1)).println(eq("Dwarven tunnel digger goes to the mine.")); + assertTrue(appender.logContains("Dwarf gold digger goes to the mine.")); + assertTrue(appender.logContains("Dwarf cart operator goes to the mine.")); + assertTrue(appender.logContains("Dwarven tunnel digger goes to the mine.")); // No other actions were invoked, so the workers shouldn't have done (printed) anything else - verifyNoMoreInteractions(this.stdOutMock); + assertEquals(6, appender.getLogSize()); // Now do some actual work, start digging gold! goldMine.digOutGold(); // Since we gave the dig command, every worker should be doing it's job ... - verify(this.stdOutMock, times(1)).println(eq("Dwarf gold digger digs for gold.")); - verify(this.stdOutMock, times(1)).println(eq("Dwarf cart operator moves gold chunks out of the mine.")); - verify(this.stdOutMock, times(1)).println(eq("Dwarven tunnel digger creates another promising tunnel.")); + assertTrue(appender.logContains("Dwarf gold digger digs for gold.")); + assertTrue(appender.logContains("Dwarf cart operator moves gold chunks out of the mine.")); + assertTrue(appender.logContains("Dwarven tunnel digger creates another promising tunnel.")); // Again, they shouldn't be doing anything else. - verifyNoMoreInteractions(this.stdOutMock); + assertEquals(9, appender.getLogSize()); // Enough gold, lets end the day. goldMine.endDay(); // Check if the workers go home ... - verify(this.stdOutMock, times(1)).println(eq("Dwarf gold digger goes home.")); - verify(this.stdOutMock, times(1)).println(eq("Dwarf cart operator goes home.")); - verify(this.stdOutMock, times(1)).println(eq("Dwarven tunnel digger goes home.")); + assertTrue(appender.logContains("Dwarf gold digger goes home.")); + assertTrue(appender.logContains("Dwarf cart operator goes home.")); + assertTrue(appender.logContains("Dwarven tunnel digger goes home.")); // ... and go to sleep. We need well rested workers the next day :) - verify(this.stdOutMock, times(1)).println(eq("Dwarf gold digger goes to sleep.")); - verify(this.stdOutMock, times(1)).println(eq("Dwarf cart operator goes to sleep.")); - verify(this.stdOutMock, times(1)).println(eq("Dwarven tunnel digger goes to sleep.")); + assertTrue(appender.logContains("Dwarf gold digger goes to sleep.")); + assertTrue(appender.logContains("Dwarf cart operator goes to sleep.")); + assertTrue(appender.logContains("Dwarven tunnel digger goes to sleep.")); // Every worker should be sleeping now, no other actions allowed - verifyNoMoreInteractions(this.stdOutMock); + assertEquals(15, appender.getLogSize()); } + private class InMemoryAppender extends AppenderBase { + + private List log = new LinkedList<>(); + + public InMemoryAppender() { + ((Logger) LoggerFactory.getLogger("root")).addAppender(this); + start(); + } + + @Override + protected void append(ILoggingEvent eventObject) { + log.add(eventObject); + } + + public int getLogSize() { + return log.size(); + } + + public boolean logContains(String message) { + return log.stream().anyMatch(event -> event.getFormattedMessage().equals(message)); + } + } + + } 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 f27bee170..c091cb1eb 100644 --- a/factory-kit/src/main/java/com/iluwatar/factorykit/App.java +++ b/factory-kit/src/main/java/com/iluwatar/factorykit/App.java @@ -22,6 +22,9 @@ */ package com.iluwatar.factorykit; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * Factory-kit is a creational pattern which defines a factory of immutable content * with separated builder and factory interfaces to deal with the problem of @@ -36,6 +39,9 @@ package com.iluwatar.factorykit; * be mapped explicitly with desired class type in the factory instance. */ public class App { + + private static final Logger LOGGER = LoggerFactory.getLogger(App.class); + /** * Program entry point. * @@ -49,6 +55,6 @@ public class App { builder.add(WeaponType.BOW, Bow::new); }); Weapon axe = factory.create(WeaponType.AXE); - System.out.println(axe); + LOGGER.info(axe.toString()); } } 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 cd7a6e6e7..a49d8bd32 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 @@ -22,6 +22,9 @@ */ package com.iluwatar.factory.method; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * * The Factory Method is a creational design pattern which uses factory methods to deal with the @@ -38,6 +41,8 @@ package com.iluwatar.factory.method; */ public class App { + private static final Logger LOGGER = LoggerFactory.getLogger(App.class); + private final Blacksmith blacksmith; /** @@ -70,8 +75,8 @@ public class App { private void manufactureWeapons() { Weapon weapon; weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR); - System.out.println(weapon); + LOGGER.info(weapon.toString()); weapon = blacksmith.manufactureWeapon(WeaponType.AXE); - System.out.println(weapon); + LOGGER.info(weapon.toString()); } } 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 debe99580..c2bccb851 100644 --- a/feature-toggle/src/main/java/com/iluwatar/featuretoggle/App.java +++ b/feature-toggle/src/main/java/com/iluwatar/featuretoggle/App.java @@ -27,6 +27,8 @@ import com.iluwatar.featuretoggle.pattern.Service; import com.iluwatar.featuretoggle.pattern.propertiesversion.PropertiesFeatureToggleVersion; import com.iluwatar.featuretoggle.user.User; import com.iluwatar.featuretoggle.user.UserGroup; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.Properties; @@ -45,6 +47,8 @@ import java.util.Properties; */ public class App { + private static final Logger LOGGER = LoggerFactory.getLogger(App.class); + /** * Block 1 shows the {@link PropertiesFeatureToggleVersion} being run with {@link Properties} setting the feature * toggle to enabled. @@ -70,7 +74,7 @@ public class App { properties.put("enhancedWelcome", true); Service service = new PropertiesFeatureToggleVersion(properties); final String welcomeMessage = service.getWelcomeMessage(new User("Jamie No Code")); - System.out.println(welcomeMessage); + LOGGER.info(welcomeMessage); // --------------------------------------------- @@ -78,7 +82,7 @@ public class App { turnedOff.put("enhancedWelcome", false); Service turnedOffService = new PropertiesFeatureToggleVersion(turnedOff); final String welcomeMessageturnedOff = turnedOffService.getWelcomeMessage(new User("Jamie No Code")); - System.out.println(welcomeMessageturnedOff); + LOGGER.info(welcomeMessageturnedOff); // -------------------------------------------- @@ -90,7 +94,7 @@ public class App { final String welcomeMessagePaidUser = service.getWelcomeMessage(paidUser); final String welcomeMessageFreeUser = service.getWelcomeMessage(freeUser); - System.out.println(welcomeMessageFreeUser); - System.out.println(welcomeMessagePaidUser); + LOGGER.info(welcomeMessageFreeUser); + LOGGER.info(welcomeMessagePaidUser); } } diff --git a/fluentinterface/src/main/java/com/iluwatar/fluentinterface/app/App.java b/fluentinterface/src/main/java/com/iluwatar/fluentinterface/app/App.java index 1be2b1e70..30678359d 100644 --- a/fluentinterface/src/main/java/com/iluwatar/fluentinterface/app/App.java +++ b/fluentinterface/src/main/java/com/iluwatar/fluentinterface/app/App.java @@ -35,6 +35,8 @@ import java.util.function.Predicate; import com.iluwatar.fluentinterface.fluentiterable.FluentIterable; import com.iluwatar.fluentinterface.fluentiterable.lazy.LazyFluentIterable; import com.iluwatar.fluentinterface.fluentiterable.simple.SimpleFluentIterable; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * The Fluent Interface pattern is useful when you want to provide an easy readable, flowing API. @@ -50,6 +52,8 @@ import com.iluwatar.fluentinterface.fluentiterable.simple.SimpleFluentIterable; */ public class App { + private static final Logger LOGGER = LoggerFactory.getLogger(App.class); + /** * Program entry point */ @@ -74,9 +78,7 @@ public class App { .fromCopyOf(integerList) .filter(number -> number % 2 == 0) .first() - .ifPresent( - evenNumber -> System.out.println(String.format("The first even number is: %d", - evenNumber))); + .ifPresent(evenNumber -> LOGGER.info("The first even number is: {}", evenNumber)); List transformedList = @@ -97,9 +99,7 @@ public class App { .filter(negatives()) .first(2) .last() - .ifPresent( - lastOfFirstTwo -> System.out.println(String.format( - "The last of the first two negatives is: %d", lastOfFirstTwo))); + .ifPresent(lastOfFirstTwo -> LOGGER.info("The last of the first two negatives is: {}", lastOfFirstTwo)); } private static Function transformToString() { @@ -126,6 +126,6 @@ public class App { joiner.add(iterator.next().toString()); } - System.out.println(joiner); + LOGGER.info(joiner.toString()); } } 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 cb351bfae..dd5405a02 100644 --- a/flux/src/main/java/com/iluwatar/flux/view/ContentView.java +++ b/flux/src/main/java/com/iluwatar/flux/view/ContentView.java @@ -25,6 +25,8 @@ package com.iluwatar.flux.view; import com.iluwatar.flux.action.Content; import com.iluwatar.flux.store.ContentStore; import com.iluwatar.flux.store.Store; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * @@ -33,6 +35,8 @@ import com.iluwatar.flux.store.Store; */ public class ContentView implements View { + private static final Logger LOGGER = LoggerFactory.getLogger(ContentView.class); + private Content content = Content.PRODUCTS; @Override @@ -44,6 +48,6 @@ public class ContentView implements View { @Override public void render() { - System.out.println(content.toString()); + LOGGER.info(content.toString()); } } 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 6cd9005dc..81d1e49d5 100644 --- a/flux/src/main/java/com/iluwatar/flux/view/MenuView.java +++ b/flux/src/main/java/com/iluwatar/flux/view/MenuView.java @@ -26,6 +26,8 @@ import com.iluwatar.flux.action.MenuItem; import com.iluwatar.flux.dispatcher.Dispatcher; import com.iluwatar.flux.store.MenuStore; import com.iluwatar.flux.store.Store; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * @@ -34,6 +36,8 @@ import com.iluwatar.flux.store.Store; */ public class MenuView implements View { + private static final Logger LOGGER = LoggerFactory.getLogger(MenuView.class); + private MenuItem selected = MenuItem.HOME; @Override @@ -47,9 +51,9 @@ public class MenuView implements View { public void render() { for (MenuItem item : MenuItem.values()) { if (selected.equals(item)) { - System.out.println(String.format("* %s", item.toString())); + LOGGER.info("* {}", item); } else { - System.out.println(item.toString()); + LOGGER.info(item.toString()); } } } diff --git a/flyweight/src/main/java/com/iluwatar/flyweight/AlchemistShop.java b/flyweight/src/main/java/com/iluwatar/flyweight/AlchemistShop.java index 507de7a6a..5cde4c248 100644 --- a/flyweight/src/main/java/com/iluwatar/flyweight/AlchemistShop.java +++ b/flyweight/src/main/java/com/iluwatar/flyweight/AlchemistShop.java @@ -22,6 +22,9 @@ */ package com.iluwatar.flyweight; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -33,6 +36,8 @@ import java.util.List; */ public class AlchemistShop { + private static final Logger LOGGER = LoggerFactory.getLogger(AlchemistShop.class); + private List topShelf; private List bottomShelf; @@ -88,13 +93,13 @@ public class AlchemistShop { */ public void enumerate() { - System.out.println("Enumerating top shelf potions\n"); + LOGGER.info("Enumerating top shelf potions\n"); for (Potion p : topShelf) { p.drink(); } - System.out.println("\nEnumerating bottom shelf potions\n"); + LOGGER.info("Enumerating bottom shelf potions\n"); for (Potion p : bottomShelf) { p.drink(); diff --git a/flyweight/src/main/java/com/iluwatar/flyweight/HealingPotion.java b/flyweight/src/main/java/com/iluwatar/flyweight/HealingPotion.java index 464675a61..e25107bdb 100644 --- a/flyweight/src/main/java/com/iluwatar/flyweight/HealingPotion.java +++ b/flyweight/src/main/java/com/iluwatar/flyweight/HealingPotion.java @@ -22,6 +22,9 @@ */ package com.iluwatar.flyweight; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * * HealingPotion @@ -29,8 +32,10 @@ package com.iluwatar.flyweight; */ public class HealingPotion implements Potion { + private static final Logger LOGGER = LoggerFactory.getLogger(HealingPotion.class); + @Override public void drink() { - System.out.println("You feel healed. (Potion=" + System.identityHashCode(this) + ")"); + LOGGER.info("You feel healed. (Potion={})", System.identityHashCode(this)); } } diff --git a/flyweight/src/main/java/com/iluwatar/flyweight/HolyWaterPotion.java b/flyweight/src/main/java/com/iluwatar/flyweight/HolyWaterPotion.java index b05b4af11..83a5ca6d1 100644 --- a/flyweight/src/main/java/com/iluwatar/flyweight/HolyWaterPotion.java +++ b/flyweight/src/main/java/com/iluwatar/flyweight/HolyWaterPotion.java @@ -22,6 +22,9 @@ */ package com.iluwatar.flyweight; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * * HolyWaterPotion @@ -29,8 +32,10 @@ package com.iluwatar.flyweight; */ public class HolyWaterPotion implements Potion { + private static final Logger LOGGER = LoggerFactory.getLogger(HolyWaterPotion.class); + @Override public void drink() { - System.out.println("You feel blessed. (Potion=" + System.identityHashCode(this) + ")"); + LOGGER.info("You feel blessed. (Potion={})", System.identityHashCode(this)); } } diff --git a/flyweight/src/main/java/com/iluwatar/flyweight/InvisibilityPotion.java b/flyweight/src/main/java/com/iluwatar/flyweight/InvisibilityPotion.java index 5aeb5d3a4..1e3087c4b 100644 --- a/flyweight/src/main/java/com/iluwatar/flyweight/InvisibilityPotion.java +++ b/flyweight/src/main/java/com/iluwatar/flyweight/InvisibilityPotion.java @@ -22,6 +22,9 @@ */ package com.iluwatar.flyweight; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * * InvisibilityPotion @@ -29,8 +32,10 @@ package com.iluwatar.flyweight; */ public class InvisibilityPotion implements Potion { + private static final Logger LOGGER = LoggerFactory.getLogger(InvisibilityPotion.class); + @Override public void drink() { - System.out.println("You become invisible. (Potion=" + System.identityHashCode(this) + ")"); + LOGGER.info("You become invisible. (Potion={})", System.identityHashCode(this)); } } diff --git a/flyweight/src/main/java/com/iluwatar/flyweight/PoisonPotion.java b/flyweight/src/main/java/com/iluwatar/flyweight/PoisonPotion.java index a9d13088e..83c32b192 100644 --- a/flyweight/src/main/java/com/iluwatar/flyweight/PoisonPotion.java +++ b/flyweight/src/main/java/com/iluwatar/flyweight/PoisonPotion.java @@ -22,6 +22,9 @@ */ package com.iluwatar.flyweight; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * * PoisonPotion @@ -29,8 +32,10 @@ package com.iluwatar.flyweight; */ public class PoisonPotion implements Potion { + private static final Logger LOGGER = LoggerFactory.getLogger(PoisonPotion.class); + @Override public void drink() { - System.out.println("Urgh! This is poisonous. (Potion=" + System.identityHashCode(this) + ")"); + LOGGER.info("Urgh! This is poisonous. (Potion={})", System.identityHashCode(this)); } } diff --git a/flyweight/src/main/java/com/iluwatar/flyweight/StrengthPotion.java b/flyweight/src/main/java/com/iluwatar/flyweight/StrengthPotion.java index 2c21e7df1..81f5a9d46 100644 --- a/flyweight/src/main/java/com/iluwatar/flyweight/StrengthPotion.java +++ b/flyweight/src/main/java/com/iluwatar/flyweight/StrengthPotion.java @@ -22,6 +22,9 @@ */ package com.iluwatar.flyweight; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * * StrengthPotion @@ -29,8 +32,10 @@ package com.iluwatar.flyweight; */ public class StrengthPotion implements Potion { + private static final Logger LOGGER = LoggerFactory.getLogger(StrengthPotion.class); + @Override public void drink() { - System.out.println("You feel strong. (Potion=" + System.identityHashCode(this) + ")"); + LOGGER.info("You feel strong. (Potion={})", System.identityHashCode(this)); } } 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 a7cf8ca27..ddd27d0e8 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 @@ -22,15 +22,20 @@ */ package com.iluwatar.front.controller; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * * View for archers. * */ public class ArcherView implements View { + + private static final Logger LOGGER = LoggerFactory.getLogger(ArcherView.class); @Override public void display() { - System.out.println("Displaying archers"); + LOGGER.info("Displaying archers"); } } 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 90e4c7896..f3b7e308e 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 @@ -22,6 +22,9 @@ */ package com.iluwatar.front.controller; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * * View for catapults. @@ -29,8 +32,10 @@ package com.iluwatar.front.controller; */ public class CatapultView implements View { + private static final Logger LOGGER = LoggerFactory.getLogger(CatapultView.class); + @Override public void display() { - System.out.println("Displaying catapults"); + LOGGER.info("Displaying catapults"); } } 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 cbfd4bd2e..00dbc582b 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 @@ -22,6 +22,9 @@ */ package com.iluwatar.front.controller; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * * View for errors. @@ -29,8 +32,10 @@ package com.iluwatar.front.controller; */ public class ErrorView implements View { + private static final Logger LOGGER = LoggerFactory.getLogger(ErrorView.class); + @Override public void display() { - System.out.println("Error 500"); + LOGGER.error("Error 500"); } } 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 c4d9ae625..0b5c9f593 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 @@ -22,6 +22,9 @@ */ package com.iluwatar.front.controller; +import com.iluwatar.front.controller.utils.InMemoryAppender; +import org.junit.After; +import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; @@ -30,9 +33,7 @@ import org.junit.runners.Parameterized.Parameters; import java.util.ArrayList; import java.util.List; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; -import static org.mockito.Mockito.verifyZeroInteractions; +import static org.junit.Assert.assertEquals; /** * Date: 12/13/15 - 1:39 PM @@ -40,7 +41,19 @@ import static org.mockito.Mockito.verifyZeroInteractions; * @author Jeroen Meulemeester */ @RunWith(Parameterized.class) -public class CommandTest extends StdOutTest { +public class CommandTest { + + private InMemoryAppender appender; + + @Before + public void setUp() { + appender = new InMemoryAppender(); + } + + @After + public void tearDown() { + appender.stop(); + } @Parameters public static List data() { @@ -75,10 +88,10 @@ public class CommandTest extends StdOutTest { @Test public void testDisplay() { final FrontController frontController = new FrontController(); - verifyZeroInteractions(getStdOutMock()); + assertEquals(0, appender.getLogSize()); frontController.handleRequest(request); - verify(getStdOutMock()).println(displayMessage); - verifyNoMoreInteractions(getStdOutMock()); + assertEquals(displayMessage, appender.getLastMessage()); + assertEquals(1, appender.getLogSize()); } } 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 0822ffcd0..46a26e6fb 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 @@ -22,6 +22,9 @@ */ package com.iluwatar.front.controller; +import com.iluwatar.front.controller.utils.InMemoryAppender; +import org.junit.After; +import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; @@ -30,9 +33,7 @@ import org.junit.runners.Parameterized.Parameters; import java.util.ArrayList; import java.util.List; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; -import static org.mockito.Mockito.verifyZeroInteractions; +import static org.junit.Assert.assertEquals; /** * Date: 12/13/15 - 1:39 PM @@ -40,7 +41,19 @@ import static org.mockito.Mockito.verifyZeroInteractions; * @author Jeroen Meulemeester */ @RunWith(Parameterized.class) -public class FrontControllerTest extends StdOutTest { +public class FrontControllerTest { + + private InMemoryAppender appender; + + @Before + public void setUp() { + appender = new InMemoryAppender(); + } + + @After + public void tearDown() { + appender.stop(); + } @Parameters public static List data() { @@ -74,10 +87,10 @@ public class FrontControllerTest extends StdOutTest { @Test public void testDisplay() { - verifyZeroInteractions(getStdOutMock()); + assertEquals(0, appender.getLogSize()); this.command.process(); - verify(getStdOutMock()).println(displayMessage); - verifyNoMoreInteractions(getStdOutMock()); + assertEquals(displayMessage, appender.getLastMessage()); + assertEquals(1, appender.getLogSize()); } } diff --git a/front-controller/src/test/java/com/iluwatar/front/controller/StdOutTest.java b/front-controller/src/test/java/com/iluwatar/front/controller/StdOutTest.java deleted file mode 100644 index bc32a1b3c..000000000 --- a/front-controller/src/test/java/com/iluwatar/front/controller/StdOutTest.java +++ /dev/null @@ -1,76 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014 Ilkka Seppälä - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package com.iluwatar.front.controller; - -import org.junit.After; -import org.junit.Before; - -import java.io.PrintStream; - -import static org.mockito.Mockito.mock; - -/** - * Date: 12/10/15 - 8:37 PM - * - * @author Jeroen Meulemeester - */ -public abstract class StdOutTest { - - /** - * The mocked standard out {@link PrintStream}, required since the actions of the views don't have - * any influence on any other accessible objects, except for writing to std-out using {@link - * System#out} - */ - private final PrintStream stdOutMock = mock(PrintStream.class); - - /** - * Keep the original std-out so it can be restored after the test - */ - private final PrintStream stdOutOrig = System.out; - - /** - * Inject the mocked std-out {@link PrintStream} into the {@link System} class before each test - */ - @Before - public void setUp() { - System.setOut(this.stdOutMock); - } - - /** - * Removed the mocked std-out {@link PrintStream} again from the {@link System} class - */ - @After - public void tearDown() { - System.setOut(this.stdOutOrig); - } - - /** - * Get the mocked stdOut {@link PrintStream} - * - * @return The stdOut print stream mock, renewed before each test - */ - final PrintStream getStdOutMock() { - return this.stdOutMock; - } - -} 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 cdabd66ef..bca070305 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 @@ -22,6 +22,9 @@ */ package com.iluwatar.front.controller; +import com.iluwatar.front.controller.utils.InMemoryAppender; +import org.junit.After; +import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; @@ -30,9 +33,7 @@ import org.junit.runners.Parameterized.Parameters; import java.util.ArrayList; import java.util.List; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; -import static org.mockito.Mockito.verifyZeroInteractions; +import static org.junit.Assert.assertEquals; /** * Date: 12/13/15 - 1:39 PM @@ -40,7 +41,19 @@ import static org.mockito.Mockito.verifyZeroInteractions; * @author Jeroen Meulemeester */ @RunWith(Parameterized.class) -public class ViewTest extends StdOutTest { +public class ViewTest { + + private InMemoryAppender appender; + + @Before + public void setUp() { + appender = new InMemoryAppender(); + } + + @After + public void tearDown() { + appender.stop(); + } @Parameters public static List data() { @@ -74,10 +87,10 @@ public class ViewTest extends StdOutTest { @Test public void testDisplay() { - verifyZeroInteractions(getStdOutMock()); + assertEquals(0, appender.getLogSize()); this.view.display(); - verify(getStdOutMock()).println(displayMessage); - verifyNoMoreInteractions(getStdOutMock()); + assertEquals(displayMessage, appender.getLastMessage()); + assertEquals(1, appender.getLogSize()); } -} \ No newline at end of file +} 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 new file mode 100644 index 000000000..1747deac5 --- /dev/null +++ b/front-controller/src/test/java/com/iluwatar/front/controller/utils/InMemoryAppender.java @@ -0,0 +1,54 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.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; + +public class InMemoryAppender extends AppenderBase { + + private List log = new LinkedList<>(); + + public InMemoryAppender() { + ((Logger) LoggerFactory.getLogger("root")).addAppender(this); + start(); + } + + @Override + protected void append(ILoggingEvent eventObject) { + log.add(eventObject); + } + + public String getLastMessage() { + return log.get(log.size() - 1).getFormattedMessage(); + } + + public int getLogSize() { + return log.size(); + } +} 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 17839bb32..3186b292a 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 @@ -22,6 +22,9 @@ */ package com.iluwatar.halfsynchalfasync; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.util.concurrent.LinkedBlockingQueue; /** @@ -66,6 +69,8 @@ import java.util.concurrent.LinkedBlockingQueue; */ public class App { + private static final Logger LOGGER = LoggerFactory.getLogger(App.class); + /** * Program entry point * @@ -128,7 +133,7 @@ public class App { @Override public void onPostCall(Long result) { // Handle the result of computation - System.out.println(result); + LOGGER.info(result.toString()); } @Override @@ -141,7 +146,7 @@ public class App { try { Thread.sleep(i); } catch (InterruptedException e) { - System.out.println(e); + LOGGER.error("Exception caught.", e); } return i * (i + 1) / 2; } diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/administration/ConsoleAdministration.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/administration/ConsoleAdministration.java index ea2f33699..e83521c22 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/administration/ConsoleAdministration.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/administration/ConsoleAdministration.java @@ -30,6 +30,8 @@ import com.iluwatar.hexagonal.domain.LotteryService; import com.iluwatar.hexagonal.module.LotteryModule; import com.iluwatar.hexagonal.mongo.MongoConnectionPropertiesLoader; import com.iluwatar.hexagonal.sampledata.SampleData; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.Scanner; @@ -38,6 +40,8 @@ import java.util.Scanner; */ public class ConsoleAdministration { + private static final Logger LOGGER = LoggerFactory.getLogger(ConsoleAdministration.class); + /** * Program entry point */ @@ -53,29 +57,29 @@ public class ConsoleAdministration { printMainMenu(); String cmd = readString(scanner); if (cmd.equals("1")) { - administartion.getAllSubmittedTickets().forEach((k,v)->System.out.println("Key: " + k + " Value: " + v)); + administartion.getAllSubmittedTickets().forEach((k,v)->LOGGER.info("Key: {}, Value: {}", k, v)); } else if (cmd.equals("2")) { LotteryNumbers numbers = administartion.performLottery(); - System.out.println("The winning numbers: " + numbers.getNumbersAsString()); - System.out.println("Time to reset the database for next round, eh?"); + LOGGER.info("The winning numbers: {}", numbers.getNumbersAsString()); + LOGGER.info("Time to reset the database for next round, eh?"); } else if (cmd.equals("3")) { administartion.resetLottery(); - System.out.println("The lottery ticket database was cleared."); + LOGGER.info("The lottery ticket database was cleared."); } else if (cmd.equals("4")) { exit = true; } else { - System.out.println("Unknown command: " + cmd); + LOGGER.info("Unknown command: {}", cmd); } } } private static void printMainMenu() { - System.out.println(""); - System.out.println("### Lottery Administration Console ###"); - System.out.println("(1) Show all submitted tickets"); - System.out.println("(2) Perform lottery draw"); - System.out.println("(3) Reset lottery ticket database"); - System.out.println("(4) Exit"); + LOGGER.info(""); + LOGGER.info("### Lottery Administration Console ###"); + LOGGER.info("(1) Show all submitted tickets"); + LOGGER.info("(2) Perform lottery draw"); + LOGGER.info("(3) Reset lottery ticket database"); + LOGGER.info("(4) Exit"); } private static String readString(Scanner scanner) { diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/eventlog/StdOutEventLog.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/eventlog/StdOutEventLog.java index 4150dd401..c63759e8e 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/eventlog/StdOutEventLog.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/eventlog/StdOutEventLog.java @@ -23,42 +23,42 @@ package com.iluwatar.hexagonal.eventlog; import com.iluwatar.hexagonal.domain.PlayerDetails; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * Standard output event log */ public class StdOutEventLog implements LotteryEventLog { + private static final Logger LOGGER = LoggerFactory.getLogger(StdOutEventLog.class); + @Override public void ticketSubmitted(PlayerDetails details) { - System.out.println(String.format("Lottery ticket for %s was submitted. Bank account %s was charged for 3 credits.", - details.getEmail(), details.getBankAccount())); + LOGGER.info("Lottery ticket for {} was submitted. Bank account {} was charged for 3 credits.", + details.getEmail(), details.getBankAccount()); } @Override public void ticketDidNotWin(PlayerDetails details) { - System.out.println(String.format("Lottery ticket for %s was checked and unfortunately did not win this time.", - details.getEmail())); + LOGGER.info("Lottery ticket for {} was checked and unfortunately did not win this time.", details.getEmail()); } @Override public void ticketWon(PlayerDetails details, int prizeAmount) { - System.out - .println(String.format("Lottery ticket for %s has won! The bank account %s was deposited with %d credits.", - details.getEmail(), details.getBankAccount(), prizeAmount)); + LOGGER.info("Lottery ticket for {} has won! The bank account {} was deposited with {} credits.", + details.getEmail(), details.getBankAccount(), prizeAmount); } @Override public void prizeError(PlayerDetails details, int prizeAmount) { - System.out - .println(String.format("Lottery ticket for %s has won! Unfortunately the bank credit transfer of %d failed.", - details.getEmail(), prizeAmount)); + LOGGER.error("Lottery ticket for {} has won! Unfortunately the bank credit transfer of {} failed.", + details.getEmail(), prizeAmount); } @Override public void ticketSubmitError(PlayerDetails details) { - System.out.println( - String.format("Lottery ticket for %s could not be submitted because the credit transfer of 3 credits failed.", - details.getEmail())); + LOGGER.error("Lottery ticket for {} could not be submitted because the credit transfer of 3 credits failed.", + details.getEmail()); } } diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/service/ConsoleLottery.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/service/ConsoleLottery.java index cc13d389d..077b0f235 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/service/ConsoleLottery.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/service/ConsoleLottery.java @@ -33,6 +33,8 @@ import com.iluwatar.hexagonal.domain.LotteryTicketId; import com.iluwatar.hexagonal.domain.PlayerDetails; import com.iluwatar.hexagonal.module.LotteryModule; import com.iluwatar.hexagonal.mongo.MongoConnectionPropertiesLoader; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.HashSet; import java.util.Optional; @@ -44,6 +46,7 @@ import java.util.Set; */ public class ConsoleLottery { + private static final Logger LOGGER = LoggerFactory.getLogger(ConsoleLottery.class); /** * Program entry point @@ -59,25 +62,25 @@ public class ConsoleLottery { printMainMenu(); String cmd = readString(scanner); if (cmd.equals("1")) { - System.out.println("What is the account number?"); + LOGGER.info("What is the account number?"); String account = readString(scanner); - System.out.println(String.format("The account %s has %d credits.", account, bank.getFunds(account))); + LOGGER.info("The account {} has {} credits.", account, bank.getFunds(account)); } else if (cmd.equals("2")) { - System.out.println("What is the account number?"); + LOGGER.info("What is the account number?"); String account = readString(scanner); - System.out.println("How many credits do you want to deposit?"); + LOGGER.info("How many credits do you want to deposit?"); String amount = readString(scanner); bank.setFunds(account, Integer.parseInt(amount)); - System.out.println(String.format("The account %s now has %d credits.", account, bank.getFunds(account))); + LOGGER.info("The account {} now has {} credits.", account, bank.getFunds(account)); } else if (cmd.equals("3")) { - System.out.println("What is your email address?"); + LOGGER.info("What is your email address?"); String email = readString(scanner); - System.out.println("What is your bank account number?"); + LOGGER.info("What is your bank account number?"); String account = readString(scanner); - System.out.println("What is your phone number?"); + LOGGER.info("What is your phone number?"); String phone = readString(scanner); PlayerDetails details = new PlayerDetails(email, account, phone); - System.out.println("Give 4 comma separated lottery numbers?"); + LOGGER.info("Give 4 comma separated lottery numbers?"); String numbers = readString(scanner); try { String[] parts = numbers.split(","); @@ -89,17 +92,17 @@ public class ConsoleLottery { LotteryTicket lotteryTicket = new LotteryTicket(new LotteryTicketId(), details, lotteryNumbers); Optional id = service.submitTicket(lotteryTicket); if (id.isPresent()) { - System.out.println("Submitted lottery ticket with id: " + id.get()); + LOGGER.info("Submitted lottery ticket with id: {}", id.get()); } else { - System.out.println("Failed submitting lottery ticket - please try again."); + LOGGER.info("Failed submitting lottery ticket - please try again."); } } catch (Exception e) { - System.out.println("Failed submitting lottery ticket - please try again."); + LOGGER.info("Failed submitting lottery ticket - please try again."); } } else if (cmd.equals("4")) { - System.out.println("What is the ID of the lottery ticket?"); + LOGGER.info("What is the ID of the lottery ticket?"); String id = readString(scanner); - System.out.println("Give the 4 comma separated winning numbers?"); + LOGGER.info("Give the 4 comma separated winning numbers?"); String numbers = readString(scanner); try { String[] parts = numbers.split(","); @@ -110,31 +113,31 @@ public class ConsoleLottery { LotteryTicketCheckResult result = service.checkTicketForPrize( new LotteryTicketId(Integer.parseInt(id)), LotteryNumbers.create(winningNumbers)); if (result.getResult().equals(LotteryTicketCheckResult.CheckResult.WIN_PRIZE)) { - System.out.println("Congratulations! The lottery ticket has won!"); + LOGGER.info("Congratulations! The lottery ticket has won!"); } else if (result.getResult().equals(LotteryTicketCheckResult.CheckResult.NO_PRIZE)) { - System.out.println("Unfortunately the lottery ticket did not win."); + LOGGER.info("Unfortunately the lottery ticket did not win."); } else { - System.out.println("Such lottery ticket has not been submitted."); + LOGGER.info("Such lottery ticket has not been submitted."); } } catch (Exception e) { - System.out.println("Failed checking the lottery ticket - please try again."); + LOGGER.info("Failed checking the lottery ticket - please try again."); } } else if (cmd.equals("5")) { exit = true; } else { - System.out.println("Unknown command"); + LOGGER.info("Unknown command"); } } } private static void printMainMenu() { - System.out.println(""); - System.out.println("### Lottery Service Console ###"); - System.out.println("(1) Query lottery account funds"); - System.out.println("(2) Add funds to lottery account"); - System.out.println("(3) Submit ticket"); - System.out.println("(4) Check ticket"); - System.out.println("(5) Exit"); + LOGGER.info(""); + LOGGER.info("### Lottery Service Console ###"); + LOGGER.info("(1) Query lottery account funds"); + LOGGER.info("(2) Add funds to lottery account"); + LOGGER.info("(3) Submit ticket"); + LOGGER.info("(4) Check ticket"); + LOGGER.info("(5) Exit"); } private static String readString(Scanner scanner) { diff --git a/interpreter/src/main/java/com/iluwatar/interpreter/App.java b/interpreter/src/main/java/com/iluwatar/interpreter/App.java index 708f06e6f..1cf732b0d 100644 --- a/interpreter/src/main/java/com/iluwatar/interpreter/App.java +++ b/interpreter/src/main/java/com/iluwatar/interpreter/App.java @@ -22,6 +22,9 @@ */ package com.iluwatar.interpreter; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.util.Stack; /** @@ -37,6 +40,8 @@ import java.util.Stack; */ public class App { + private static final Logger LOGGER = LoggerFactory.getLogger(App.class); + /** * * Program entry point. @@ -56,21 +61,21 @@ public class App { if (isOperator(s)) { Expression rightExpression = stack.pop(); Expression leftExpression = stack.pop(); - System.out.println(String.format("popped from stack left: %d right: %d", - leftExpression.interpret(), rightExpression.interpret())); + LOGGER.info("popped from stack left: {} right: {}", + leftExpression.interpret(), rightExpression.interpret()); Expression operator = getOperatorInstance(s, leftExpression, rightExpression); - System.out.println(String.format("operator: %s", operator)); + LOGGER.info("operator: {}", operator); int result = operator.interpret(); NumberExpression resultExpression = new NumberExpression(result); stack.push(resultExpression); - System.out.println(String.format("push result to stack: %d", resultExpression.interpret())); + LOGGER.info("push result to stack: {}", resultExpression.interpret()); } else { Expression i = new NumberExpression(s); stack.push(i); - System.out.println(String.format("push to stack: %d", i.interpret())); + LOGGER.info("push to stack: {}", i.interpret()); } } - System.out.println(String.format("result: %d", stack.pop().interpret())); + LOGGER.info("result: {}", stack.pop().interpret()); } public static boolean isOperator(String s) { diff --git a/iterator/src/main/java/com/iluwatar/iterator/App.java b/iterator/src/main/java/com/iluwatar/iterator/App.java index 8da0a7433..44bc1dacd 100644 --- a/iterator/src/main/java/com/iluwatar/iterator/App.java +++ b/iterator/src/main/java/com/iluwatar/iterator/App.java @@ -22,6 +22,9 @@ */ package com.iluwatar.iterator; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * * The Iterator pattern is a design pattern in which an iterator is used to traverse a container and @@ -34,6 +37,8 @@ package com.iluwatar.iterator; */ public class App { + private static final Logger LOGGER = LoggerFactory.getLogger(App.class); + /** * Program entry point * @@ -44,28 +49,28 @@ public class App { ItemIterator ringIterator = chest.iterator(ItemType.RING); while (ringIterator.hasNext()) { - System.out.println(ringIterator.next()); + LOGGER.info(ringIterator.next().toString()); } - System.out.println("----------"); + LOGGER.info("----------"); ItemIterator potionIterator = chest.iterator(ItemType.POTION); while (potionIterator.hasNext()) { - System.out.println(potionIterator.next()); + LOGGER.info(potionIterator.next().toString()); } - System.out.println("----------"); + LOGGER.info("----------"); ItemIterator weaponIterator = chest.iterator(ItemType.WEAPON); while (weaponIterator.hasNext()) { - System.out.println(weaponIterator.next()); + LOGGER.info(weaponIterator.next().toString()); } - System.out.println("----------"); + LOGGER.info("----------"); ItemIterator it = chest.iterator(ItemType.ANY); while (it.hasNext()) { - System.out.println(it.next()); + LOGGER.info(it.next().toString()); } } } diff --git a/layers/src/main/java/com/iluwatar/layers/CakeViewImpl.java b/layers/src/main/java/com/iluwatar/layers/CakeViewImpl.java index bc489e16e..bb636af7a 100644 --- a/layers/src/main/java/com/iluwatar/layers/CakeViewImpl.java +++ b/layers/src/main/java/com/iluwatar/layers/CakeViewImpl.java @@ -22,6 +22,9 @@ */ package com.iluwatar.layers; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * * View implementation for displaying cakes @@ -29,6 +32,8 @@ package com.iluwatar.layers; */ public class CakeViewImpl implements View { + private static final Logger LOGGER = LoggerFactory.getLogger(CakeViewImpl.class); + private CakeBakingService cakeBakingService; public CakeViewImpl(CakeBakingService cakeBakingService) { @@ -36,6 +41,6 @@ public class CakeViewImpl implements View { } public void render() { - cakeBakingService.getAllCakes().stream().forEach(cake -> System.out.println(cake)); + cakeBakingService.getAllCakes().stream().forEach(cake -> LOGGER.info(cake.toString())); } } diff --git a/layers/src/main/resources/logback.xml b/layers/src/main/resources/logback.xml new file mode 100644 index 000000000..e122ac350 --- /dev/null +++ b/layers/src/main/resources/logback.xml @@ -0,0 +1,57 @@ + + + + layers.log + + layers-%d.log + 5 + + + %-5p [%d{ISO8601,UTC}] %c: %m%n + + + + + + %-5p [%d{ISO8601,UTC}] %c: %m%n + + + + + + + + + + + + + + + + + + diff --git a/layers/src/test/java/com/iluwatar/layers/CakeViewImplTest.java b/layers/src/test/java/com/iluwatar/layers/CakeViewImplTest.java index a69aa23bb..3a9214ae1 100644 --- a/layers/src/test/java/com/iluwatar/layers/CakeViewImplTest.java +++ b/layers/src/test/java/com/iluwatar/layers/CakeViewImplTest.java @@ -22,11 +22,19 @@ */ package com.iluwatar.layers; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.AppenderBase; +import org.junit.After; +import org.junit.Before; import org.junit.Test; +import org.slf4j.LoggerFactory; import java.util.ArrayList; +import java.util.LinkedList; import java.util.List; +import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.*; /** @@ -34,7 +42,19 @@ import static org.mockito.Mockito.*; * * @author Jeroen Meulemeester */ -public class CakeViewImplTest extends StdOutTest { +public class CakeViewImplTest { + + private InMemoryAppender appender; + + @Before + public void setUp() { + appender = new InMemoryAppender(CakeViewImpl.class); + } + + @After + public void tearDown() { + appender.stop(); + } /** * Verify if the cake view renders the expected result @@ -56,11 +76,34 @@ public class CakeViewImplTest extends StdOutTest { final CakeViewImpl cakeView = new CakeViewImpl(bakingService); - verifyZeroInteractions(getStdOutMock()); + assertEquals(0, appender.getLogSize()); cakeView.render(); - verify(getStdOutMock(), times(1)).println(cake); + assertEquals(cake.toString(), appender.getLastMessage()); } + private class InMemoryAppender extends AppenderBase { + + private List log = new LinkedList<>(); + + public InMemoryAppender(Class clazz) { + ((Logger) LoggerFactory.getLogger(clazz)).addAppender(this); + start(); + } + + @Override + protected void append(ILoggingEvent eventObject) { + log.add(eventObject); + } + + public String getLastMessage() { + return log.get(log.size() - 1).getFormattedMessage(); + } + + public int getLogSize() { + return log.size(); + } + } + } diff --git a/layers/src/test/java/com/iluwatar/layers/StdOutTest.java b/layers/src/test/java/com/iluwatar/layers/StdOutTest.java deleted file mode 100644 index 3c94b178c..000000000 --- a/layers/src/test/java/com/iluwatar/layers/StdOutTest.java +++ /dev/null @@ -1,76 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014 Ilkka Seppälä - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package com.iluwatar.layers; - -import org.junit.After; -import org.junit.Before; - -import java.io.PrintStream; - -import static org.mockito.Mockito.mock; - -/** - * Date: 12/10/15 - 8:37 PM - * - * @author Jeroen Meulemeester - */ -public abstract class StdOutTest { - - /** - * The mocked standard out {@link PrintStream}, required since the actions of the views don't have - * any influence on any other accessible objects, except for writing to std-out using {@link - * System#out} - */ - private final PrintStream stdOutMock = mock(PrintStream.class); - - /** - * Keep the original std-out so it can be restored after the test - */ - private final PrintStream stdOutOrig = System.out; - - /** - * Inject the mocked std-out {@link PrintStream} into the {@link System} class before each test - */ - @Before - public void setUp() { - System.setOut(this.stdOutMock); - } - - /** - * Removed the mocked std-out {@link PrintStream} again from the {@link System} class - */ - @After - public void tearDown() { - System.setOut(this.stdOutOrig); - } - - /** - * Get the mocked stdOut {@link PrintStream} - * - * @return The stdOut print stream mock, renewed before each test - */ - final PrintStream getStdOutMock() { - return this.stdOutMock; - } - -} diff --git a/lazy-loading/src/main/java/com/iluwatar/lazy/loading/App.java b/lazy-loading/src/main/java/com/iluwatar/lazy/loading/App.java index 7a658a8c6..b33520243 100644 --- a/lazy-loading/src/main/java/com/iluwatar/lazy/loading/App.java +++ b/lazy-loading/src/main/java/com/iluwatar/lazy/loading/App.java @@ -22,6 +22,9 @@ */ package com.iluwatar.lazy.loading; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * * Lazy loading idiom defers object creation until needed. @@ -33,6 +36,9 @@ package com.iluwatar.lazy.loading; * */ public class App { + + private static final Logger LOGGER = LoggerFactory.getLogger(App.class); + /** * Program entry point * @@ -43,16 +49,16 @@ public class App { // Simple lazy loader - not thread safe HolderNaive holderNaive = new HolderNaive(); Heavy heavy = holderNaive.getHeavy(); - System.out.println("heavy=" + heavy); + LOGGER.info("heavy={}", heavy); // Thread safe lazy loader, but with heavy synchronization on each access HolderThreadSafe holderThreadSafe = new HolderThreadSafe(); Heavy another = holderThreadSafe.getHeavy(); - System.out.println("another=" + another); + LOGGER.info("another={}", another); // The most efficient lazy loader utilizing Java 8 features Java8Holder java8Holder = new Java8Holder(); Heavy next = java8Holder.getHeavy(); - System.out.println("next=" + next); + LOGGER.info("next={}", next); } } 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 57e8e263e..ad4eb3de2 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 @@ -22,6 +22,9 @@ */ package com.iluwatar.lazy.loading; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * * Heavy objects are expensive to create. @@ -29,16 +32,18 @@ package com.iluwatar.lazy.loading; */ public class Heavy { + private static final Logger LOGGER = LoggerFactory.getLogger(Heavy.class); + /** * Constructor */ public Heavy() { - System.out.println("Creating Heavy ..."); + LOGGER.info("Creating Heavy ..."); try { Thread.sleep(1000); } catch (InterruptedException e) { - e.printStackTrace(); + LOGGER.error("Exception caught.", e); } - System.out.println("... Heavy created"); + LOGGER.info("... Heavy created"); } } 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 75c65d1b9..0e3d2c718 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 @@ -22,6 +22,9 @@ */ package com.iluwatar.lazy.loading; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * * Simple implementation of the lazy loading idiom. However, this is not thread safe. @@ -29,13 +32,15 @@ package com.iluwatar.lazy.loading; */ public class HolderNaive { + private static final Logger LOGGER = LoggerFactory.getLogger(HolderNaive.class); + private Heavy heavy; /** * Constructor */ public HolderNaive() { - System.out.println("HolderNaive created"); + LOGGER.info("HolderNaive created"); } /** 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 c6e0fcfd9..35dd2e4f0 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 @@ -22,6 +22,9 @@ */ package com.iluwatar.lazy.loading; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * * Same as HolderNaive but with added synchronization. This implementation is thread safe, but each @@ -30,13 +33,15 @@ package com.iluwatar.lazy.loading; */ public class HolderThreadSafe { + private static final Logger LOGGER = LoggerFactory.getLogger(HolderThreadSafe.class); + private Heavy heavy; /** * Constructor */ public HolderThreadSafe() { - System.out.println("HolderThreadSafe created"); + LOGGER.info("HolderThreadSafe created"); } /** diff --git a/lazy-loading/src/main/java/com/iluwatar/lazy/loading/Java8Holder.java b/lazy-loading/src/main/java/com/iluwatar/lazy/loading/Java8Holder.java index e4ce394cc..95e8856c9 100644 --- a/lazy-loading/src/main/java/com/iluwatar/lazy/loading/Java8Holder.java +++ b/lazy-loading/src/main/java/com/iluwatar/lazy/loading/Java8Holder.java @@ -22,6 +22,9 @@ */ package com.iluwatar.lazy.loading; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.util.function.Supplier; /** @@ -32,10 +35,12 @@ import java.util.function.Supplier; */ public class Java8Holder { + private static final Logger LOGGER = LoggerFactory.getLogger(Java8Holder.class); + private Supplier heavy = () -> createAndCacheHeavy(); public Java8Holder() { - System.out.println("Java8Holder created"); + LOGGER.info("Java8Holder created"); } public Heavy getHeavy() { diff --git a/mediator/src/main/java/com/iluwatar/mediator/PartyMemberBase.java b/mediator/src/main/java/com/iluwatar/mediator/PartyMemberBase.java index 7d3ca3dbf..9d9b9cd2d 100644 --- a/mediator/src/main/java/com/iluwatar/mediator/PartyMemberBase.java +++ b/mediator/src/main/java/com/iluwatar/mediator/PartyMemberBase.java @@ -22,6 +22,9 @@ */ package com.iluwatar.mediator; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * * Abstract base class for party members. @@ -29,23 +32,25 @@ package com.iluwatar.mediator; */ public abstract class PartyMemberBase implements PartyMember { + private static final Logger LOGGER = LoggerFactory.getLogger(PartyMemberBase.class); + protected Party party; @Override public void joinedParty(Party party) { - System.out.println(this + " joins the party"); + LOGGER.info("{} joins the party", this); this.party = party; } @Override public void partyAction(Action action) { - System.out.println(this + " " + action.getDescription()); + LOGGER.info("{} {}", this, action.getDescription()); } @Override public void act(Action action) { if (party != null) { - System.out.println(this + " " + action.toString()); + LOGGER.info("{} {}", this, action); party.act(this, action); } } diff --git a/mediator/src/test/java/com/iluwatar/mediator/PartyMemberTest.java b/mediator/src/test/java/com/iluwatar/mediator/PartyMemberTest.java index 0bf43f9cd..e5f7e2719 100644 --- a/mediator/src/test/java/com/iluwatar/mediator/PartyMemberTest.java +++ b/mediator/src/test/java/com/iluwatar/mediator/PartyMemberTest.java @@ -22,22 +22,25 @@ */ package com.iluwatar.mediator; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.AppenderBase; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; +import org.slf4j.LoggerFactory; -import java.io.PrintStream; import java.util.Arrays; import java.util.Collection; +import java.util.LinkedList; +import java.util.List; import java.util.function.Supplier; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; -import static org.mockito.Mockito.verifyZeroInteractions; /** * Date: 12/19/15 - 10:13 PM @@ -57,34 +60,6 @@ public class PartyMemberTest { ); } - /** - * The mocked standard out {@link PrintStream}, required since some actions on a {@link - * PartyMember} have any influence on any other accessible objects, except for writing to std-out - * using {@link System#out} - */ - private final PrintStream stdOutMock = mock(PrintStream.class); - - /** - * Keep the original std-out so it can be restored after the test - */ - private final PrintStream stdOutOrig = System.out; - - /** - * Inject the mocked std-out {@link PrintStream} into the {@link System} class before each test - */ - @Before - public void setUp() { - System.setOut(this.stdOutMock); - } - - /** - * Removed the mocked std-out {@link PrintStream} again from the {@link System} class - */ - @After - public void tearDown() { - System.setOut(this.stdOutOrig); - } - /** * The factory, used to create a new instance of the tested party member */ @@ -99,6 +74,18 @@ public class PartyMemberTest { this.memberSupplier = memberSupplier; } + private InMemoryAppender appender; + + @Before + public void setUp() { + appender = new InMemoryAppender(PartyMemberBase.class); + } + + @After + public void tearDown() { + appender.stop(); + } + /** * Verify if a party action triggers the correct output to the std-Out */ @@ -108,10 +95,10 @@ public class PartyMemberTest { for (final Action action : Action.values()) { member.partyAction(action); - verify(this.stdOutMock).println(member.toString() + " " + action.getDescription()); + assertEquals(member.toString() + " " + action.getDescription(), appender.getLastMessage()); } - verifyNoMoreInteractions(this.stdOutMock); + assertEquals(Action.values().length, appender.getLogSize()); } /** @@ -122,19 +109,19 @@ public class PartyMemberTest { final PartyMember member = this.memberSupplier.get(); member.act(Action.GOLD); - verifyZeroInteractions(this.stdOutMock); + assertEquals(0, appender.getLogSize()); final Party party = mock(Party.class); member.joinedParty(party); - verify(this.stdOutMock).println(member.toString() + " joins the party"); + assertEquals(member.toString() + " joins the party", appender.getLastMessage()); for (final Action action : Action.values()) { member.act(action); - verify(this.stdOutMock).println(member.toString() + " " + action.toString()); + assertEquals(member.toString() + " " + action.toString(), appender.getLastMessage()); verify(party).act(member, action); } - verifyNoMoreInteractions(party, this.stdOutMock); + assertEquals(Action.values().length + 1, appender.getLogSize()); } /** @@ -147,4 +134,27 @@ public class PartyMemberTest { assertEquals(memberClass.getSimpleName(), member.toString()); } + private class InMemoryAppender extends AppenderBase { + private List log = new LinkedList<>(); + + public InMemoryAppender(Class clazz) { + ((Logger) LoggerFactory.getLogger(clazz)).addAppender(this); + start(); + } + + @Override + protected void append(ILoggingEvent eventObject) { + log.add(eventObject); + } + + public int getLogSize() { + return log.size(); + } + + public String getLastMessage() { + return log.get(log.size() - 1).getFormattedMessage(); + } + } + + } diff --git a/memento/src/main/java/com/iluwatar/memento/App.java b/memento/src/main/java/com/iluwatar/memento/App.java index e1ee349b1..c346b7941 100644 --- a/memento/src/main/java/com/iluwatar/memento/App.java +++ b/memento/src/main/java/com/iluwatar/memento/App.java @@ -22,6 +22,9 @@ */ package com.iluwatar.memento; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.util.Stack; /** @@ -45,6 +48,8 @@ import java.util.Stack; */ public class App { + private static final Logger LOGGER = LoggerFactory.getLogger(App.class); + /** * Program entry point */ @@ -52,22 +57,22 @@ public class App { Stack states = new Stack<>(); Star star = new Star(StarType.SUN, 10000000, 500000); - System.out.println(star); + LOGGER.info(star.toString()); states.add(star.getMemento()); star.timePasses(); - System.out.println(star); + LOGGER.info(star.toString()); states.add(star.getMemento()); star.timePasses(); - System.out.println(star); + LOGGER.info(star.toString()); states.add(star.getMemento()); star.timePasses(); - System.out.println(star); + LOGGER.info(star.toString()); states.add(star.getMemento()); star.timePasses(); - System.out.println(star); + LOGGER.info(star.toString()); while (states.size() > 0) { star.setMemento(states.pop()); - System.out.println(star); + LOGGER.info(star.toString()); } } } diff --git a/message-channel/src/main/java/com/iluwatar/message/channel/App.java b/message-channel/src/main/java/com/iluwatar/message/channel/App.java index dab04bd37..2e132213d 100644 --- a/message-channel/src/main/java/com/iluwatar/message/channel/App.java +++ b/message-channel/src/main/java/com/iluwatar/message/channel/App.java @@ -25,6 +25,8 @@ package com.iluwatar.message.channel; import org.apache.camel.CamelContext; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.impl.DefaultCamelContext; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * @@ -50,6 +52,8 @@ import org.apache.camel.impl.DefaultCamelContext; */ public class App { + private static final Logger LOGGER = LoggerFactory.getLogger(App.class); + /** * Program entry point */ @@ -66,7 +70,7 @@ public class App { }); context.start(); - context.getRoutes().stream().forEach(r -> System.out.println(r)); + context.getRoutes().stream().forEach(r -> LOGGER.info(r.toString())); context.stop(); } } 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 dd4361487..61815aab8 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 @@ -22,6 +22,9 @@ */ package com.iluwatar.model.view.controller; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * * GiantView displays the giant @@ -29,7 +32,9 @@ package com.iluwatar.model.view.controller; */ public class GiantView { + private static final Logger LOGGER = LoggerFactory.getLogger(GiantView.class); + public void displayGiant(GiantModel giant) { - System.out.println(giant); + LOGGER.info(giant.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 89d503d4e..9ea0ae96e 100644 --- a/model-view-controller/src/test/java/com/iluwatar/model/view/controller/GiantViewTest.java +++ b/model-view-controller/src/test/java/com/iluwatar/model/view/controller/GiantViewTest.java @@ -22,15 +22,19 @@ */ package com.iluwatar.model.view.controller; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.AppenderBase; import org.junit.After; import org.junit.Before; import org.junit.Test; +import org.slf4j.LoggerFactory; -import java.io.PrintStream; +import java.util.LinkedList; +import java.util.List; +import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; /** * Date: 12/20/15 - 2:04 PM @@ -39,32 +43,16 @@ import static org.mockito.Mockito.verifyNoMoreInteractions; */ public class GiantViewTest { - /** - * The mocked standard out {@link PrintStream}, required since the actions of the views don't have - * any influence on any other accessible objects, except for writing to std-out using {@link - * System#out} - */ - private final PrintStream stdOutMock = mock(PrintStream.class); + private InMemoryAppender appender; - /** - * Keep the original std-out so it can be restored after the test - */ - private final PrintStream stdOutOrig = System.out; - - /** - * Inject the mocked std-out {@link PrintStream} into the {@link System} class before each test - */ @Before public void setUp() { - System.setOut(this.stdOutMock); + appender = new InMemoryAppender(GiantView.class); } - /** - * Removed the mocked std-out {@link PrintStream} again from the {@link System} class - */ @After public void tearDown() { - System.setOut(this.stdOutOrig); + appender.stop(); } /** @@ -78,9 +66,29 @@ public class GiantViewTest { final GiantModel model = mock(GiantModel.class); view.displayGiant(model); - verify(this.stdOutMock).println(model); - verifyNoMoreInteractions(model, this.stdOutMock); - + assertEquals(model.toString(), appender.getLastMessage()); + assertEquals(1, appender.getLogSize()); } -} \ No newline at end of file + public class InMemoryAppender extends AppenderBase { + private List log = new LinkedList<>(); + + public InMemoryAppender(Class clazz) { + ((Logger) LoggerFactory.getLogger(clazz)).addAppender(this); + start(); + } + + @Override + protected void append(ILoggingEvent eventObject) { + log.add(eventObject); + } + + public String getLastMessage() { + return log.get(log.size() - 1).getMessage(); + } + + public int getLogSize() { + return log.size(); + } + } +} diff --git a/monad/src/main/java/com/iluwatar/monad/App.java b/monad/src/main/java/com/iluwatar/monad/App.java index 7b28fdcf8..e707156d6 100644 --- a/monad/src/main/java/com/iluwatar/monad/App.java +++ b/monad/src/main/java/com/iluwatar/monad/App.java @@ -22,6 +22,9 @@ */ package com.iluwatar.monad; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.util.Objects; import java.util.function.Function; import java.util.function.Predicate; @@ -42,6 +45,8 @@ import java.util.function.Predicate; */ public class App { + private static final Logger LOGGER = LoggerFactory.getLogger(App.class); + /** * Program entry point. * @@ -49,7 +54,7 @@ public class App { */ public static void main(String[] args) { User user = new User("user", 24, Sex.FEMALE, "foobar.com"); - System.out.println(Validator.of(user).validate(User::getName, Objects::nonNull, "name is null") + LOGGER.info(Validator.of(user).validate(User::getName, Objects::nonNull, "name is null") .validate(User::getName, name -> !name.isEmpty(), "name is empty") .validate(User::getEmail, email -> !email.contains("@"), "email doesn't containt '@'") .validate(User::getAge, age -> age > 20 && age < 30, "age isn't between...").get().toString()); diff --git a/monostate/src/main/java/com/iluwatar/monostate/Server.java b/monostate/src/main/java/com/iluwatar/monostate/Server.java index bf700a57a..86a4985cc 100644 --- a/monostate/src/main/java/com/iluwatar/monostate/Server.java +++ b/monostate/src/main/java/com/iluwatar/monostate/Server.java @@ -22,6 +22,9 @@ */ package com.iluwatar.monostate; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * * The Server class. Each Server sits behind a LoadBalancer which delegates the call to the servers @@ -29,6 +32,9 @@ package com.iluwatar.monostate; * */ public class Server { + + private static final Logger LOGGER = LoggerFactory.getLogger(Server.class); + public final String host; public final int port; public final int id; @@ -51,7 +57,7 @@ public class Server { } public void serve(Request request) { - System.out.println("Server ID " + id + " associated to host : " + getHost() + " and Port " - + getPort() + " Processed request with value " + request.value); + LOGGER.info("Server ID {} associated to host : {} and port {}. Processed request with value {}", + id, host, port, request.value); } } diff --git a/multiton/src/main/java/com/iluwatar/multiton/App.java b/multiton/src/main/java/com/iluwatar/multiton/App.java index 1ffd57a34..55cc8a2aa 100644 --- a/multiton/src/main/java/com/iluwatar/multiton/App.java +++ b/multiton/src/main/java/com/iluwatar/multiton/App.java @@ -22,6 +22,9 @@ */ package com.iluwatar.multiton; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * * Whereas Singleton design pattern introduces single globally accessible object the Multiton @@ -35,20 +38,22 @@ package com.iluwatar.multiton; */ public class App { + private static final Logger LOGGER = LoggerFactory.getLogger(App.class); + /** * Program entry point * * @param args command line args */ public static void main(String[] args) { - System.out.println("KHAMUL=" + Nazgul.getInstance(NazgulName.KHAMUL)); - System.out.println("MURAZOR=" + Nazgul.getInstance(NazgulName.MURAZOR)); - System.out.println("DWAR=" + Nazgul.getInstance(NazgulName.DWAR)); - System.out.println("JI_INDUR=" + Nazgul.getInstance(NazgulName.JI_INDUR)); - System.out.println("AKHORAHIL=" + Nazgul.getInstance(NazgulName.AKHORAHIL)); - System.out.println("HOARMURATH=" + Nazgul.getInstance(NazgulName.HOARMURATH)); - System.out.println("ADUNAPHEL=" + Nazgul.getInstance(NazgulName.ADUNAPHEL)); - System.out.println("REN=" + Nazgul.getInstance(NazgulName.REN)); - System.out.println("UVATHA=" + Nazgul.getInstance(NazgulName.UVATHA)); + LOGGER.info("KHAMUL={}", Nazgul.getInstance(NazgulName.KHAMUL)); + LOGGER.info("MURAZOR={}", Nazgul.getInstance(NazgulName.MURAZOR)); + LOGGER.info("DWAR={}", Nazgul.getInstance(NazgulName.DWAR)); + LOGGER.info("JI_INDUR={}", Nazgul.getInstance(NazgulName.JI_INDUR)); + LOGGER.info("AKHORAHIL={}", Nazgul.getInstance(NazgulName.AKHORAHIL)); + LOGGER.info("HOARMURATH={}", Nazgul.getInstance(NazgulName.HOARMURATH)); + LOGGER.info("ADUNAPHEL={}", Nazgul.getInstance(NazgulName.ADUNAPHEL)); + LOGGER.info("REN={}", Nazgul.getInstance(NazgulName.REN)); + LOGGER.info("UVATHA={}", Nazgul.getInstance(NazgulName.UVATHA)); } } 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 8a2aca41e..35c9d2a55 100644 --- a/mute-idiom/src/main/java/com/iluwatar/mute/App.java +++ b/mute-idiom/src/main/java/com/iluwatar/mute/App.java @@ -23,6 +23,9 @@ package com.iluwatar.mute; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.io.ByteArrayOutputStream; import java.io.IOException; import java.sql.SQLException; @@ -46,6 +49,8 @@ import java.sql.SQLException; */ public class App { + private static final Logger LOGGER = LoggerFactory.getLogger(App.class); + /** * Program entry point. * @@ -88,7 +93,7 @@ public class App { } private static void utilizeResource(Resource resource) throws SQLException { - System.out.println("Utilizing acquired resource: " + resource); + LOGGER.info("Utilizing acquired resource: {}", resource); } private static Resource acquireResource() throws SQLException { 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 58cbfe893..a7a010c3c 100644 --- a/mute-idiom/src/test/java/com/iluwatar/mute/MuteTest.java +++ b/mute-idiom/src/test/java/com/iluwatar/mute/MuteTest.java @@ -32,9 +32,13 @@ import java.io.PrintStream; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class MuteTest { + private static final Logger LOGGER = LoggerFactory.getLogger(MuteTest.class); + private static final String MESSAGE = "should not occur"; @Rule public ExpectedException exception = ExpectedException.none(); @@ -69,7 +73,7 @@ public class MuteTest { private void methodNotThrowingAnyException() { - System.out.println("Executed successfully"); + LOGGER.info("Executed successfully"); } private void methodThrowingException() throws Exception { diff --git a/mutex/src/main/java/com/iluwatar/mutex/Thief.java b/mutex/src/main/java/com/iluwatar/mutex/Thief.java index d2225876c..d31ec3fa8 100644 --- a/mutex/src/main/java/com/iluwatar/mutex/Thief.java +++ b/mutex/src/main/java/com/iluwatar/mutex/Thief.java @@ -22,12 +22,17 @@ */ package com.iluwatar.mutex; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * Thief is a class which continually tries to acquire a jar and take a bean * from it. When the jar is empty the thief stops. */ public class Thief extends Thread { + private static final Logger LOGGER = LoggerFactory.getLogger(Thief.class); + /** * The name of the thief. */ @@ -53,10 +58,10 @@ public class Thief extends Thread { while (jar.takeBean()) { beans = beans + 1; - System.out.println(name + " took a bean."); + LOGGER.info("{} took a bean.", name); } - System.out.println(name + " took " + beans + " beans."); + LOGGER.info("{} took {} beans.", name, beans); } } diff --git a/naked-objects/dom/log4j.properties b/naked-objects/dom/log4j.properties deleted file mode 100644 index ca165acc7..000000000 --- a/naked-objects/dom/log4j.properties +++ /dev/null @@ -1,41 +0,0 @@ -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. - -# LOG4J Configuration -# =================== - -# Basic logging goes to "datanucleus.log" -log4j.appender.A1=org.apache.log4j.FileAppender -log4j.appender.A1.File=datanucleus.log -log4j.appender.A1.layout=org.apache.log4j.PatternLayout -log4j.appender.A1.layout.ConversionPattern=%d{HH:mm:ss,SSS} (%t) %-5p [%c] - %m%n -#log4j.appender.A1.Threshold=INFO - -# Categories -# Each category can be set to a "level", and to direct to an appender - -# Default to DEBUG level for all DataNucleus categories -log4j.logger.DataNucleus = DEBUG, A1 - -log4j.category.com.mchange.v2.c3p0=INFO, A1 -log4j.category.com.mchange.v2.resourcepool=INFO, A1 -log4j.category.org.logicalcobwebs.proxool=INFO,A1 - - -# Hbase libs logging -log4j.category.org.apache.hadoop=INFO,A1 -log4j.category.org.apache.zookeeper=INFO,A1 \ No newline at end of file diff --git a/naked-objects/integtests/logging.properties b/naked-objects/integtests/logging.properties deleted file mode 100644 index b55249569..000000000 --- a/naked-objects/integtests/logging.properties +++ /dev/null @@ -1,111 +0,0 @@ -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. - - -# -# Isis uses log4j is used to provide system logging -# -log4j.rootCategory=INFO, Console - -# The console appender -log4j.appender.Console=org.apache.log4j.ConsoleAppender -log4j.appender.Console.target=System.out -log4j.appender.Console.layout=org.apache.log4j.PatternLayout -log4j.appender.Console.layout.ConversionPattern=%d{ABSOLUTE} [%-20c{1} %-10t %-5p] %m%n - -log4j.appender.File=org.apache.log4j.RollingFileAppender -log4j.appender.File.file=isis.log -log4j.appender.File.append=false -log4j.appender.File.layout=org.apache.log4j.PatternLayout -log4j.appender.File.layout.ConversionPattern=%d [%-20c{1} %-10t %-5p] %m%n - -log4j.appender.translations-po=org.apache.log4j.FileAppender -log4j.appender.translations-po.File=./translations.pot -log4j.appender.translations-po.Append=false -log4j.appender.translations-po.layout=org.apache.log4j.PatternLayout -log4j.appender.translations-po.layout.ConversionPattern=%m%n - -! turn on the internal log4j debugging flag so we can see what it is doing -#log4j.debug=true - - -# DataNucleus -# the first two log the DML and DDL (if set to DEBUG) -log4j.logger.DataNucleus.Datastore.Native=WARN, Console -log4j.logger.DataNucleus.Datastore.Schema=DEBUG, Console -# the remainder can probably be left to WARN -log4j.logger.DataNucleus.Persistence=WARN, Console -log4j.logger.DataNucleus.Transaction=WARN, Console -log4j.logger.DataNucleus.Connection=WARN, Console -log4j.logger.DataNucleus.Query=WARN, Console -log4j.logger.DataNucleus.Cache=WARN, Console -log4j.logger.DataNucleus.MetaData=WARN, Console -log4j.logger.DataNucleus.Datastore=WARN, Console -log4j.logger.DataNucleus.Datastore.Persist=WARN, Console -log4j.logger.DataNucleus.Datastore.Retrieve=WARN, Console -log4j.logger.DataNucleus.General=WARN, Console -log4j.logger.DataNucleus.Lifecycle=WARN, Console -log4j.logger.DataNucleus.ValueGeneration=WARN, Console -log4j.logger.DataNucleus.Enhancer=WARN, Console -log4j.logger.DataNucleus.SchemaTool=ERROR, Console -log4j.logger.DataNucleus.JDO=WARN, Console -log4j.logger.DataNucleus.JPA=ERROR, Console -log4j.logger.DataNucleus.JCA=WARN, Console -log4j.logger.DataNucleus.IDE=ERROR, Console - -log4j.additivity.DataNucleus.Datastore.Native=false -log4j.additivity.DataNucleus.Datastore.Schema=false -log4j.additivity.DataNucleus.Datastore.Persistence=false -log4j.additivity.DataNucleus.Datastore.Transaction=false -log4j.additivity.DataNucleus.Datastore.Connection=false -log4j.additivity.DataNucleus.Datastore.Query=false -log4j.additivity.DataNucleus.Datastore.Cache=false -log4j.additivity.DataNucleus.Datastore.MetaData=false -log4j.additivity.DataNucleus.Datastore.Datastore=false -log4j.additivity.DataNucleus.Datastore.Datastore.Persist=false -log4j.additivity.DataNucleus.Datastore.Datastore.Retrieve=false -log4j.additivity.DataNucleus.Datastore.General=false -log4j.additivity.DataNucleus.Datastore.Lifecycle=false -log4j.additivity.DataNucleus.Datastore.ValueGeneration=false -log4j.additivity.DataNucleus.Datastore.Enhancer=false -log4j.additivity.DataNucleus.Datastore.SchemaTool=false -log4j.additivity.DataNucleus.Datastore.JDO=false -log4j.additivity.DataNucleus.Datastore.JPA=false -log4j.additivity.DataNucleus.Datastore.JCA=false -log4j.additivity.DataNucleus.Datastore.IDE=false - - - - -# if using log4jdbc-remix as JDBC driver -#log4j.logger.jdbc.sqlonly=DEBUG, sql, Console -#log4j.additivity.jdbc.sqlonly=false -#log4j.logger.jdbc.resultsettable=DEBUG, jdbc, Console -#log4j.additivity.jdbc.resultsettable=false - -#log4j.logger.jdbc.audit=WARN,jdbc, Console -#log4j.additivity.jdbc.audit=false -#log4j.logger.jdbc.resultset=WARN,jdbc -#log4j.additivity.jdbc.resultset=false -#log4j.logger.jdbc.sqltiming=WARN,sqltiming -#log4j.additivity.jdbc.sqltiming=false -#log4j.logger.jdbc.connection=FATAL,connection -#log4j.additivity.jdbc.connection=false - - -log4j.logger.org.apache.isis.core.runtime.services.i18n.po.PoWriter=INFO,translations-po -log4j.additivity.org.apache.isis.core.runtime.services.i18n.po.PotWriter=false diff --git a/naked-objects/webapp/src/main/webapp/WEB-INF/logging.properties b/naked-objects/webapp/src/main/webapp/WEB-INF/logging.properties deleted file mode 100644 index 62fd8ea5e..000000000 --- a/naked-objects/webapp/src/main/webapp/WEB-INF/logging.properties +++ /dev/null @@ -1,187 +0,0 @@ -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. - - -# -# Isis uses log4j is used to provide system logging -# -log4j.rootCategory=INFO, Console -#log4j.rootCategory=DEBUG, Console - - -# The console appender -log4j.appender.Console=org.apache.log4j.ConsoleAppender -log4j.appender.Console.target=System.out -log4j.appender.Console.layout=org.apache.log4j.PatternLayout -log4j.appender.Console.layout.ConversionPattern=%d{ABSOLUTE} [%-20c{1} %-10t %-5p] %m%n - - -# The stderr appender -log4j.appender.Stderr=org.apache.log4j.ConsoleAppender -log4j.appender.Stderr.target=System.err -log4j.appender.Stderr.layout=org.apache.log4j.PatternLayout -log4j.appender.Stderr.layout.ConversionPattern=%d{ABSOLUTE} [%-20c{1} %-10t %-5p] %m%n - - -# other appenders -log4j.appender.File=org.apache.log4j.RollingFileAppender -log4j.appender.File.file=isis.log -log4j.appender.File.append=false -log4j.appender.File.layout=org.apache.log4j.PatternLayout -log4j.appender.File.layout.ConversionPattern=%d [%-20c{1} %-10t %-5p] %m%n - -log4j.appender.sql=org.apache.log4j.FileAppender -log4j.appender.sql.File=./logs/sql.log -log4j.appender.sql.Append=false -log4j.appender.sql.layout=org.apache.log4j.PatternLayout -log4j.appender.sql.layout.ConversionPattern=-----> %d{yyyy-MM-dd HH:mm:ss.SSS} %m%n%n - -log4j.appender.sqltiming=org.apache.log4j.FileAppender -log4j.appender.sqltiming.File=./logs/sqltiming.log -log4j.appender.sqltiming.Append=false -log4j.appender.sqltiming.layout=org.apache.log4j.PatternLayout -log4j.appender.sqltiming.layout.ConversionPattern=-----> %d{yyyy-MM-dd HH:mm:ss.SSS} %m%n%n - -log4j.appender.jdbc=org.apache.log4j.FileAppender -log4j.appender.jdbc.File=./logs/jdbc.log -log4j.appender.jdbc.Append=false -log4j.appender.jdbc.layout=org.apache.log4j.PatternLayout -log4j.appender.jdbc.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss.SSS} %m%n - -log4j.appender.connection=org.apache.log4j.FileAppender -log4j.appender.connection.File=./logs/connection.log -log4j.appender.connection.Append=false -log4j.appender.connection.layout=org.apache.log4j.PatternLayout -log4j.appender.connection.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss.SSS} %m%n - - - - -! turn on the internal log4j debugging flag so we can see what it is doing -#log4j.debug=true - - -# DataNucleus -# the first two log the DML and DDL (if set to DEBUG) -log4j.logger.DataNucleus.Datastore.Native=WARN, Console -log4j.logger.DataNucleus.Datastore.Schema=DEBUG, Console -# the remainder can probably be left to WARN -log4j.logger.DataNucleus.Persistence=WARN, Console -log4j.logger.DataNucleus.Transaction=WARN, Console -log4j.logger.DataNucleus.Connection=WARN, Console -log4j.logger.DataNucleus.Query=WARN, Console -log4j.logger.DataNucleus.Cache=WARN, Console -log4j.logger.DataNucleus.MetaData=WARN, Console -log4j.logger.DataNucleus.Datastore=WARN, Console -log4j.logger.DataNucleus.Datastore.Persist=WARN, Console -log4j.logger.DataNucleus.Datastore.Retrieve=WARN, Console -log4j.logger.DataNucleus.General=WARN, Console -log4j.logger.DataNucleus.Lifecycle=WARN, Console -log4j.logger.DataNucleus.ValueGeneration=WARN, Console -log4j.logger.DataNucleus.Enhancer=WARN, Console -log4j.logger.DataNucleus.SchemaTool=ERROR, Console -log4j.logger.DataNucleus.JDO=WARN, Console -log4j.logger.DataNucleus.JPA=ERROR, Console -log4j.logger.DataNucleus.JCA=WARN, Console -log4j.logger.DataNucleus.IDE=ERROR, Console - -log4j.additivity.DataNucleus.Datastore.Native=false -log4j.additivity.DataNucleus.Datastore.Schema=false -log4j.additivity.DataNucleus.Datastore.Persistence=false -log4j.additivity.DataNucleus.Datastore.Transaction=false -log4j.additivity.DataNucleus.Datastore.Connection=false -log4j.additivity.DataNucleus.Datastore.Query=false -log4j.additivity.DataNucleus.Datastore.Cache=false -log4j.additivity.DataNucleus.Datastore.MetaData=false -log4j.additivity.DataNucleus.Datastore.Datastore=false -log4j.additivity.DataNucleus.Datastore.Datastore.Persist=false -log4j.additivity.DataNucleus.Datastore.Datastore.Retrieve=false -log4j.additivity.DataNucleus.Datastore.General=false -log4j.additivity.DataNucleus.Datastore.Lifecycle=false -log4j.additivity.DataNucleus.Datastore.ValueGeneration=false -log4j.additivity.DataNucleus.Datastore.Enhancer=false -log4j.additivity.DataNucleus.Datastore.SchemaTool=false -log4j.additivity.DataNucleus.Datastore.JDO=false -log4j.additivity.DataNucleus.Datastore.JPA=false -log4j.additivity.DataNucleus.Datastore.JCA=false -log4j.additivity.DataNucleus.Datastore.IDE=false - - -# if using log4jdbc-remix as JDBC driver -#log4j.logger.jdbc.sqlonly=DEBUG, sql, Console -#log4j.additivity.jdbc.sqlonly=false -#log4j.logger.jdbc.resultsettable=DEBUG, jdbc, Console -#log4j.additivity.jdbc.resultsettable=false - -#log4j.logger.jdbc.audit=WARN,jdbc, Console -#log4j.additivity.jdbc.audit=false -#log4j.logger.jdbc.resultset=WARN,jdbc -#log4j.additivity.jdbc.resultset=false -#log4j.logger.jdbc.sqltiming=WARN,sqltiming -#log4j.additivity.jdbc.sqltiming=false -#log4j.logger.jdbc.connection=FATAL,connection -#log4j.additivity.jdbc.connection=false - - - -# track Isis/JDO lifecycle integration - -#log4j.logger.org.apache.isis.runtimes.dflt.objectstores.jdo.datanucleus.persistence.FrameworkSynchronizer=DEBUG, Console -#log4j.additivity.org.apache.isis.runtimes.dflt.objectstores.jdo.datanucleus.persistence.FrameworkSynchronizer=false - -#log4j.logger.org.apache.isis.objectstore.jdo.datanucleus.persistence.IsisLifecycleListener=DEBUG,Console -#log4j.additivity.org.apache.isis.objectstore.jdo.datanucleus.persistence.IsisLifecycleListener=false - - - - -# track Isis/Wicket lifecycle integration - -#log4j.logger.org.apache.isis.viewer.wicket.viewer.integration.wicket.WebRequestCycleForIsis=DEBUG, Console -#log4j.additivity.org.apache.isis.viewer.wicket.viewer.integration.wicket.WebRequestCycleForIsis=false - -#log4j.logger.org.apache.isis.viewer.wicket.viewer.integration.isis.IsisContextForWicket=INFO,Console -#log4j.additivity.org.apache.isis.viewer.wicket.viewer.integration.isis.IsisContextForWicket=false - - - - -# quieten some of the noisier classes in Isis' bootstrapping -log4j.logger.org.apache.isis.core.metamodel.specloader.specimpl.FacetedMethodsBuilder=WARN,Console -log4j.additivity.org.apache.isis.core.metamodel.specloader.specimpl.FacetedMethodsBuilder=false - -log4j.logger.org.apache.isis.core.metamodel.specloader.ServiceInitializer=WARN,Console -log4j.additivity.org.apache.isis.core.metamodel.specloader.ServiceInitializer=false - -log4j.logger.org.apache.isis.core.runtime.services.ServicesInstallerFromConfiguration=WARN,Console -log4j.additivity.org.apache.isis.core.runtime.services.ServicesInstallerFromConfiguration=false - -log4j.logger.org.apache.isis.core.commons.config.IsisConfigurationDefault=WARN,Console -log4j.additivity.org.apache.isis.core.commons.config.IsisConfigurationDefault=false - -log4j.logger.org.apache.isis.core.runtime.installers.InstallerLookupDefault=WARN,Console -log4j.additivity.org.apache.isis.core.runtime.installers.InstallerLookupDefault=false - - -# quieten Shiro -log4j.logger.org.apache.shiro.realm.AuthorizingRealm=WARN,Console -log4j.additivity.log4j.logger.org.apache.shiro.realm.AuthorizingRealm=false - - -# Application-specific logging -log4j.logger.dom.simple.SimpleObject=DEBUG, Stderr -log4j.additivity.dom.simple.SimpleObject=false \ No newline at end of file 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 46787ac96..c2fd66849 100644 --- a/null-object/src/main/java/com/iluwatar/nullobject/NodeImpl.java +++ b/null-object/src/main/java/com/iluwatar/nullobject/NodeImpl.java @@ -22,6 +22,9 @@ */ package com.iluwatar.nullobject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * * Implementation for binary tree's normal nodes. @@ -29,6 +32,8 @@ package com.iluwatar.nullobject; */ public class NodeImpl implements Node { + private static final Logger LOGGER = LoggerFactory.getLogger(NodeImpl.class); + private final String name; private final Node left; private final Node right; @@ -64,7 +69,7 @@ public class NodeImpl implements Node { @Override public void walk() { - System.out.println(name); + LOGGER.info(name); if (left.getTreeSize() > 0) { left.walk(); } 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 1375b8949..98168fc0a 100644 --- a/null-object/src/test/java/com/iluwatar/nullobject/NullNodeTest.java +++ b/null-object/src/test/java/com/iluwatar/nullobject/NullNodeTest.java @@ -23,19 +23,15 @@ package com.iluwatar.nullobject; import org.junit.Test; -import org.mockito.Mockito; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; +import static org.junit.Assert.*; /** * Date: 12/26/15 - 11:47 PM * * @author Jeroen Meulemeester */ -public class NullNodeTest extends StdOutTest { +public class NullNodeTest { /** * Verify if {@link NullNode#getInstance()} actually returns the same object instance @@ -59,7 +55,6 @@ public class NullNodeTest extends StdOutTest { @Test public void testWalk() throws Exception { NullNode.getInstance().walk(); - Mockito.verifyZeroInteractions(getStdOutMock()); } -} \ No newline at end of file +} diff --git a/null-object/src/test/java/com/iluwatar/nullobject/StdOutTest.java b/null-object/src/test/java/com/iluwatar/nullobject/StdOutTest.java deleted file mode 100644 index 0c0122132..000000000 --- a/null-object/src/test/java/com/iluwatar/nullobject/StdOutTest.java +++ /dev/null @@ -1,76 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014 Ilkka Seppälä - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package com.iluwatar.nullobject; - -import org.junit.After; -import org.junit.Before; - -import java.io.PrintStream; - -import static org.mockito.Mockito.mock; - -/** - * Date: 12/10/15 - 8:37 PM - * - * @author Jeroen Meulemeester - */ -public abstract class StdOutTest { - - /** - * The mocked standard out {@link PrintStream}, required since walking through the tree has no - * influence on any other accessible object, except for writing to std-out using {@link - * System#out} - */ - private final PrintStream stdOutMock = mock(PrintStream.class); - - /** - * Keep the original std-out so it can be restored after the test - */ - private final PrintStream stdOutOrig = System.out; - - /** - * Inject the mocked std-out {@link PrintStream} into the {@link System} class before each test - */ - @Before - public void setUp() { - System.setOut(this.stdOutMock); - } - - /** - * Removed the mocked std-out {@link PrintStream} again from the {@link System} class - */ - @After - public void tearDown() { - System.setOut(this.stdOutOrig); - } - - /** - * Get the mocked stdOut {@link PrintStream} - * - * @return The stdOut print stream mock, renewed before each test - */ - final PrintStream getStdOutMock() { - return this.stdOutMock; - } - -} 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 6c77cd236..2712b0356 100644 --- a/null-object/src/test/java/com/iluwatar/nullobject/TreeTest.java +++ b/null-object/src/test/java/com/iluwatar/nullobject/TreeTest.java @@ -22,20 +22,37 @@ */ package com.iluwatar.nullobject; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.AppenderBase; +import org.junit.After; +import org.junit.Before; import org.junit.Test; -import org.mockito.InOrder; -import org.mockito.Mockito; +import org.slf4j.LoggerFactory; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; +import java.util.LinkedList; +import java.util.List; + +import static org.junit.Assert.*; /** * Date: 12/26/15 - 11:44 PM * * @author Jeroen Meulemeester */ -public class TreeTest extends StdOutTest { +public class TreeTest { + + private InMemoryAppender appender; + + @Before + public void setUp() { + appender = new InMemoryAppender(); + } + + @After + public void tearDown() { + appender.stop(); + } /** * During the tests, the same tree structure will be used, shown below. End points will be @@ -79,15 +96,14 @@ public class TreeTest extends StdOutTest { public void testWalk() { TREE_ROOT.walk(); - final InOrder inOrder = Mockito.inOrder(getStdOutMock()); - inOrder.verify(getStdOutMock()).println("root"); - inOrder.verify(getStdOutMock()).println("level1_a"); - inOrder.verify(getStdOutMock()).println("level2_a"); - inOrder.verify(getStdOutMock()).println("level3_a"); - inOrder.verify(getStdOutMock()).println("level3_b"); - inOrder.verify(getStdOutMock()).println("level2_b"); - inOrder.verify(getStdOutMock()).println("level1_b"); - inOrder.verifyNoMoreInteractions(); + assertTrue(appender.logContains("root")); + assertTrue(appender.logContains("level1_a")); + assertTrue(appender.logContains("level2_a")); + assertTrue(appender.logContains("level3_a")); + assertTrue(appender.logContains("level3_b")); + assertTrue(appender.logContains("level2_b")); + assertTrue(appender.logContains("level1_b")); + assertEquals(7, appender.getLogSize()); } @Test @@ -120,4 +136,26 @@ public class TreeTest extends StdOutTest { assertSame(NullNode.getInstance(), level1.getLeft()); } + private class InMemoryAppender extends AppenderBase { + private List log = new LinkedList<>(); + + public InMemoryAppender() { + ((Logger) LoggerFactory.getLogger("root")).addAppender(this); + start(); + } + + @Override + protected void append(ILoggingEvent eventObject) { + log.add(eventObject); + } + + public boolean logContains(String message) { + return log.stream().anyMatch(event -> event.getMessage().equals(message)); + } + + public int getLogSize() { + return log.size(); + } + } + } diff --git a/object-pool/src/main/java/com/iluwatar/object/pool/App.java b/object-pool/src/main/java/com/iluwatar/object/pool/App.java index 66b3e3f90..b49dd70d7 100644 --- a/object-pool/src/main/java/com/iluwatar/object/pool/App.java +++ b/object-pool/src/main/java/com/iluwatar/object/pool/App.java @@ -22,6 +22,9 @@ */ package com.iluwatar.object.pool; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * * When it is necessary to work with a large number of objects that are particularly expensive to @@ -44,6 +47,8 @@ package com.iluwatar.object.pool; */ public class App { + private static final Logger LOGGER = LoggerFactory.getLogger(App.class); + /** * Program entry point * @@ -51,24 +56,24 @@ public class App { */ public static void main(String[] args) { OliphauntPool pool = new OliphauntPool(); - System.out.println(pool); + LOGGER.info(pool.toString()); Oliphaunt oliphaunt1 = pool.checkOut(); - System.out.println("Checked out " + oliphaunt1); - System.out.println(pool); + LOGGER.info("Checked out {}", oliphaunt1); + LOGGER.info(pool.toString()); Oliphaunt oliphaunt2 = pool.checkOut(); - System.out.println("Checked out " + oliphaunt2); + LOGGER.info("Checked out {}", oliphaunt2); Oliphaunt oliphaunt3 = pool.checkOut(); - System.out.println("Checked out " + oliphaunt3); - System.out.println(pool); - System.out.println("Checking in " + oliphaunt1); + LOGGER.info("Checked out {}", oliphaunt3); + LOGGER.info(pool.toString()); + LOGGER.info("Checking in {}", oliphaunt1); pool.checkIn(oliphaunt1); - System.out.println("Checking in " + oliphaunt2); + LOGGER.info("Checking in {}", oliphaunt2); pool.checkIn(oliphaunt2); - System.out.println(pool); + LOGGER.info(pool.toString()); Oliphaunt oliphaunt4 = pool.checkOut(); - System.out.println("Checked out " + oliphaunt4); + LOGGER.info("Checked out {}", oliphaunt4); Oliphaunt oliphaunt5 = pool.checkOut(); - System.out.println("Checked out " + oliphaunt5); - System.out.println(pool); + LOGGER.info("Checked out {}", oliphaunt5); + LOGGER.info(pool.toString()); } } diff --git a/observer/src/main/java/com/iluwatar/observer/App.java b/observer/src/main/java/com/iluwatar/observer/App.java index dcced00d4..d6a8e0df6 100644 --- a/observer/src/main/java/com/iluwatar/observer/App.java +++ b/observer/src/main/java/com/iluwatar/observer/App.java @@ -25,6 +25,8 @@ package com.iluwatar.observer; import com.iluwatar.observer.generic.GHobbits; import com.iluwatar.observer.generic.GOrcs; import com.iluwatar.observer.generic.GWeather; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * @@ -41,6 +43,8 @@ import com.iluwatar.observer.generic.GWeather; */ public class App { + private static final Logger LOGGER = LoggerFactory.getLogger(App.class); + /** * Program entry point * @@ -58,7 +62,7 @@ public class App { weather.timePasses(); // Generic observer inspired by Java Generics and Collection by Naftalin & Wadler - System.out.println("\n--Running generic version--"); + LOGGER.info("--Running generic version--"); GWeather gWeather = new GWeather(); gWeather.addObserver(new GOrcs()); gWeather.addObserver(new GHobbits()); diff --git a/observer/src/main/java/com/iluwatar/observer/Hobbits.java b/observer/src/main/java/com/iluwatar/observer/Hobbits.java index ed9636bd6..74ffee713 100644 --- a/observer/src/main/java/com/iluwatar/observer/Hobbits.java +++ b/observer/src/main/java/com/iluwatar/observer/Hobbits.java @@ -22,6 +22,9 @@ */ package com.iluwatar.observer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * * Hobbits @@ -29,20 +32,22 @@ package com.iluwatar.observer; */ public class Hobbits implements WeatherObserver { + private static final Logger LOGGER = LoggerFactory.getLogger(Hobbits.class); + @Override public void update(WeatherType currentWeather) { switch (currentWeather) { case COLD: - System.out.println("The hobbits are shivering in the cold weather."); + LOGGER.info("The hobbits are shivering in the cold weather."); break; case RAINY: - System.out.println("The hobbits look for cover from the rain."); + LOGGER.info("The hobbits look for cover from the rain."); break; case SUNNY: - System.out.println("The happy hobbits bade in the warm sun."); + LOGGER.info("The happy hobbits bade in the warm sun."); break; case WINDY: - System.out.println("The hobbits hold their hats tightly in the windy weather."); + LOGGER.info("The hobbits hold their hats tightly in the windy weather."); break; default: break; diff --git a/observer/src/main/java/com/iluwatar/observer/Orcs.java b/observer/src/main/java/com/iluwatar/observer/Orcs.java index ce9c09944..65ddc840f 100644 --- a/observer/src/main/java/com/iluwatar/observer/Orcs.java +++ b/observer/src/main/java/com/iluwatar/observer/Orcs.java @@ -22,6 +22,9 @@ */ package com.iluwatar.observer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * * Orcs @@ -29,20 +32,22 @@ package com.iluwatar.observer; */ public class Orcs implements WeatherObserver { + private static final Logger LOGGER = LoggerFactory.getLogger(Orcs.class); + @Override public void update(WeatherType currentWeather) { switch (currentWeather) { case COLD: - System.out.println("The orcs are freezing cold."); + LOGGER.info("The orcs are freezing cold."); break; case RAINY: - System.out.println("The orcs are dripping wet."); + LOGGER.info("The orcs are dripping wet."); break; case SUNNY: - System.out.println("The sun hurts the orcs' eyes."); + LOGGER.info("The sun hurts the orcs' eyes."); break; case WINDY: - System.out.println("The orc smell almost vanishes in the wind."); + LOGGER.info("The orc smell almost vanishes in the wind."); break; default: break; diff --git a/observer/src/main/java/com/iluwatar/observer/Weather.java b/observer/src/main/java/com/iluwatar/observer/Weather.java index f6aad3881..c89ffd366 100644 --- a/observer/src/main/java/com/iluwatar/observer/Weather.java +++ b/observer/src/main/java/com/iluwatar/observer/Weather.java @@ -22,6 +22,9 @@ */ package com.iluwatar.observer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.util.ArrayList; import java.util.List; @@ -33,6 +36,8 @@ import java.util.List; */ public class Weather { + private static final Logger LOGGER = LoggerFactory.getLogger(Weather.class); + private WeatherType currentWeather; private List observers; @@ -55,7 +60,7 @@ public class Weather { public void timePasses() { WeatherType[] enumValues = WeatherType.values(); currentWeather = enumValues[(currentWeather.ordinal() + 1) % enumValues.length]; - System.out.println("The weather changed to " + currentWeather + "."); + LOGGER.info("The weather changed to {}.", currentWeather); notifyObservers(); } diff --git a/observer/src/main/java/com/iluwatar/observer/generic/GHobbits.java b/observer/src/main/java/com/iluwatar/observer/generic/GHobbits.java index da84b9aab..f70a1a62e 100644 --- a/observer/src/main/java/com/iluwatar/observer/generic/GHobbits.java +++ b/observer/src/main/java/com/iluwatar/observer/generic/GHobbits.java @@ -23,6 +23,8 @@ package com.iluwatar.observer.generic; import com.iluwatar.observer.WeatherType; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * @@ -30,20 +32,23 @@ import com.iluwatar.observer.WeatherType; * */ public class GHobbits implements Race { + + private static final Logger LOGGER = LoggerFactory.getLogger(GHobbits.class); + @Override public void update(GWeather weather, WeatherType weatherType) { switch (weatherType) { case COLD: - System.out.println("The hobbits are shivering in the cold weather."); + LOGGER.info("The hobbits are shivering in the cold weather."); break; case RAINY: - System.out.println("The hobbits look for cover from the rain."); + LOGGER.info("The hobbits look for cover from the rain."); break; case SUNNY: - System.out.println("The happy hobbits bade in the warm sun."); + LOGGER.info("The happy hobbits bade in the warm sun."); break; case WINDY: - System.out.println("The hobbits hold their hats tightly in the windy weather."); + LOGGER.info("The hobbits hold their hats tightly in the windy weather."); break; default: break; diff --git a/observer/src/main/java/com/iluwatar/observer/generic/GOrcs.java b/observer/src/main/java/com/iluwatar/observer/generic/GOrcs.java index 9f41aa6cc..3171f4e7c 100644 --- a/observer/src/main/java/com/iluwatar/observer/generic/GOrcs.java +++ b/observer/src/main/java/com/iluwatar/observer/generic/GOrcs.java @@ -23,6 +23,8 @@ package com.iluwatar.observer.generic; import com.iluwatar.observer.WeatherType; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * @@ -31,20 +33,22 @@ import com.iluwatar.observer.WeatherType; */ public class GOrcs implements Race { + private static final Logger LOGGER = LoggerFactory.getLogger(GOrcs.class); + @Override public void update(GWeather weather, WeatherType weatherType) { switch (weatherType) { case COLD: - System.out.println("The orcs are freezing cold."); + LOGGER.info("The orcs are freezing cold."); break; case RAINY: - System.out.println("The orcs are dripping wet."); + LOGGER.info("The orcs are dripping wet."); break; case SUNNY: - System.out.println("The sun hurts the orcs' eyes."); + LOGGER.info("The sun hurts the orcs' eyes."); break; case WINDY: - System.out.println("The orc smell almost vanishes in the wind."); + LOGGER.info("The orc smell almost vanishes in the wind."); break; default: break; diff --git a/observer/src/main/java/com/iluwatar/observer/generic/GWeather.java b/observer/src/main/java/com/iluwatar/observer/generic/GWeather.java index 137000760..631da479e 100644 --- a/observer/src/main/java/com/iluwatar/observer/generic/GWeather.java +++ b/observer/src/main/java/com/iluwatar/observer/generic/GWeather.java @@ -23,6 +23,8 @@ package com.iluwatar.observer.generic; import com.iluwatar.observer.WeatherType; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * @@ -31,6 +33,8 @@ import com.iluwatar.observer.WeatherType; */ public class GWeather extends Observable { + private static final Logger LOGGER = LoggerFactory.getLogger(GWeather.class); + private WeatherType currentWeather; public GWeather() { @@ -43,7 +47,7 @@ public class GWeather extends Observable { public void timePasses() { WeatherType[] enumValues = WeatherType.values(); currentWeather = enumValues[(currentWeather.ordinal() + 1) % enumValues.length]; - System.out.println("The weather changed to " + currentWeather + "."); + LOGGER.info("The weather changed to {}.", currentWeather); notifyObservers(currentWeather); } } diff --git a/observer/src/test/java/com/iluwatar/observer/StdOutTest.java b/observer/src/test/java/com/iluwatar/observer/StdOutTest.java deleted file mode 100644 index afd870ae4..000000000 --- a/observer/src/test/java/com/iluwatar/observer/StdOutTest.java +++ /dev/null @@ -1,76 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014 Ilkka Seppälä - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package com.iluwatar.observer; - -import org.junit.After; -import org.junit.Before; - -import java.io.PrintStream; - -import static org.mockito.Mockito.mock; - -/** - * Date: 12/27/15 - 12:16 PM - * - * @author Jeroen Meulemeester - */ -public abstract class StdOutTest { - - /** - * The mocked standard out {@link PrintStream}, required since changes in the weather doesn't has - * any influence on any other accessible objects, except for writing to std-out using {@link - * System#out} - */ - private final PrintStream stdOutMock = mock(PrintStream.class); - - /** - * Keep the original std-out so it can be restored after the test - */ - private final PrintStream stdOutOrig = System.out; - - /** - * Inject the mocked std-out {@link PrintStream} into the {@link System} class before each test - */ - @Before - public void setUp() { - System.setOut(this.stdOutMock); - } - - /** - * Removed the mocked std-out {@link PrintStream} again from the {@link System} class - */ - @After - public void tearDown() { - System.setOut(this.stdOutOrig); - } - - /** - * Get the mocked stdOut {@link PrintStream} - * - * @return The stdOut print stream mock, renewed before each test - */ - protected final PrintStream getStdOutMock() { - return this.stdOutMock; - } - -} diff --git a/observer/src/test/java/com/iluwatar/observer/WeatherObserverTest.java b/observer/src/test/java/com/iluwatar/observer/WeatherObserverTest.java index a06c19952..1ccf4bf12 100644 --- a/observer/src/test/java/com/iluwatar/observer/WeatherObserverTest.java +++ b/observer/src/test/java/com/iluwatar/observer/WeatherObserverTest.java @@ -22,20 +22,33 @@ */ package com.iluwatar.observer; +import com.iluwatar.observer.utils.InMemoryAppender; +import org.junit.After; +import org.junit.Before; import org.junit.Test; import java.util.function.Supplier; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; -import static org.mockito.Mockito.verifyZeroInteractions; +import static org.junit.Assert.assertEquals; /** * Date: 12/27/15 - 11:44 AM * * @author Jeroen Meulemeester */ -public abstract class WeatherObserverTest extends StdOutTest { +public abstract class WeatherObserverTest { + + private InMemoryAppender appender; + + @Before + public void setUp() { + appender = new InMemoryAppender(); + } + + @After + public void tearDown() { + appender.stop(); + } /** * The observer instance factory @@ -71,11 +84,11 @@ public abstract class WeatherObserverTest extends Std @Test public void testObserver() { final O observer = this.factory.get(); - verifyZeroInteractions(getStdOutMock()); + assertEquals(0, appender.getLogSize()); observer.update(this.weather); - verify(getStdOutMock()).println(this.response); - verifyNoMoreInteractions(getStdOutMock()); + assertEquals(response, appender.getLastMessage()); + assertEquals(1, appender.getLogSize()); } -} \ No newline at end of file +} diff --git a/observer/src/test/java/com/iluwatar/observer/WeatherTest.java b/observer/src/test/java/com/iluwatar/observer/WeatherTest.java index 7a38e7137..9d53b2e23 100644 --- a/observer/src/test/java/com/iluwatar/observer/WeatherTest.java +++ b/observer/src/test/java/com/iluwatar/observer/WeatherTest.java @@ -22,9 +22,13 @@ */ package com.iluwatar.observer; +import com.iluwatar.observer.utils.InMemoryAppender; +import org.junit.After; +import org.junit.Before; import org.junit.Test; import org.mockito.InOrder; +import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -36,7 +40,19 @@ import static org.mockito.Mockito.verifyZeroInteractions; * * @author Jeroen Meulemeester */ -public class WeatherTest extends StdOutTest { +public class WeatherTest { + + private InMemoryAppender appender; + + @Before + public void setUp() { + appender = new InMemoryAppender(Weather.class); + } + + @After + public void tearDown() { + appender.stop(); + } /** * Add a {@link WeatherObserver}, verify if it gets notified of a weather change, remove the @@ -51,14 +67,15 @@ public class WeatherTest extends StdOutTest { verifyZeroInteractions(observer); weather.timePasses(); - verify(getStdOutMock()).println("The weather changed to rainy."); + assertEquals("The weather changed to rainy.", appender.getLastMessage()); verify(observer).update(WeatherType.RAINY); weather.removeObserver(observer); weather.timePasses(); - verify(getStdOutMock()).println("The weather changed to windy."); + assertEquals("The weather changed to windy.", appender.getLastMessage()); - verifyNoMoreInteractions(observer, getStdOutMock()); + verifyNoMoreInteractions(observer); + assertEquals(2, appender.getLogSize()); } /** @@ -70,7 +87,7 @@ public class WeatherTest extends StdOutTest { final Weather weather = new Weather(); weather.addObserver(observer); - final InOrder inOrder = inOrder(observer, getStdOutMock()); + final InOrder inOrder = inOrder(observer); final WeatherType[] weatherTypes = WeatherType.values(); for (int i = 1; i < 20; i++) { weather.timePasses(); @@ -80,4 +97,4 @@ public class WeatherTest extends StdOutTest { verifyNoMoreInteractions(observer); } -} \ No newline at end of file +} 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 758dbca8c..61d619a60 100644 --- a/observer/src/test/java/com/iluwatar/observer/generic/GWeatherTest.java +++ b/observer/src/test/java/com/iluwatar/observer/generic/GWeatherTest.java @@ -22,25 +22,35 @@ */ package com.iluwatar.observer.generic; -import com.iluwatar.observer.StdOutTest; import com.iluwatar.observer.WeatherObserver; import com.iluwatar.observer.WeatherType; - +import com.iluwatar.observer.utils.InMemoryAppender; +import org.junit.After; +import org.junit.Before; import org.junit.Test; import org.mockito.InOrder; -import static org.mockito.Mockito.inOrder; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; -import static org.mockito.Mockito.verifyZeroInteractions; +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.*; /** * Date: 12/27/15 - 11:08 AM * * @author Jeroen Meulemeester */ -public class GWeatherTest extends StdOutTest { +public class GWeatherTest { + + private InMemoryAppender appender; + + @Before + public void setUp() { + appender = new InMemoryAppender(GWeather.class); + } + + @After + public void tearDown() { + appender.stop(); + } /** * Add a {@link WeatherObserver}, verify if it gets notified of a weather change, remove the @@ -55,14 +65,15 @@ public class GWeatherTest extends StdOutTest { verifyZeroInteractions(observer); weather.timePasses(); - verify(getStdOutMock()).println("The weather changed to rainy."); + assertEquals("The weather changed to rainy.", appender.getLastMessage()); verify(observer).update(weather, WeatherType.RAINY); weather.removeObserver(observer); weather.timePasses(); - verify(getStdOutMock()).println("The weather changed to windy."); + assertEquals("The weather changed to windy.", appender.getLastMessage()); - verifyNoMoreInteractions(observer, getStdOutMock()); + verifyNoMoreInteractions(observer); + assertEquals(2, appender.getLogSize()); } /** @@ -74,7 +85,7 @@ public class GWeatherTest extends StdOutTest { final GWeather weather = new GWeather(); weather.addObserver(observer); - final InOrder inOrder = inOrder(observer, getStdOutMock()); + final InOrder inOrder = inOrder(observer); final WeatherType[] weatherTypes = WeatherType.values(); for (int i = 1; i < 20; i++) { weather.timePasses(); @@ -84,4 +95,4 @@ public class GWeatherTest extends StdOutTest { verifyNoMoreInteractions(observer); } -} \ No newline at end of file +} 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 33d8daaf5..d01d30992 100644 --- a/observer/src/test/java/com/iluwatar/observer/generic/ObserverTest.java +++ b/observer/src/test/java/com/iluwatar/observer/generic/ObserverTest.java @@ -22,23 +22,34 @@ */ package com.iluwatar.observer.generic; -import com.iluwatar.observer.StdOutTest; import com.iluwatar.observer.WeatherType; - +import com.iluwatar.observer.utils.InMemoryAppender; +import org.junit.After; +import org.junit.Before; import org.junit.Test; import java.util.function.Supplier; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; -import static org.mockito.Mockito.verifyZeroInteractions; +import static org.junit.Assert.assertEquals; /** * Date: 12/27/15 - 11:44 AM * * @author Jeroen Meulemeester */ -public abstract class ObserverTest extends StdOutTest { +public abstract class ObserverTest { + + private InMemoryAppender appender; + + @Before + public void setUp() { + appender = new InMemoryAppender(); + } + + @After + public void tearDown() { + appender.stop(); + } /** * The observer instance factory @@ -74,11 +85,11 @@ public abstract class ObserverTest extends StdOutTest { @Test public void testObserver() { final O observer = this.factory.get(); - verifyZeroInteractions(getStdOutMock()); + assertEquals(0, appender.getLogSize()); observer.update(null, this.weather); - verify(getStdOutMock()).println(this.response); - verifyNoMoreInteractions(getStdOutMock()); + assertEquals(this.response, appender.getLastMessage()); + assertEquals(1, appender.getLogSize()); } -} \ No newline at end of file +} diff --git a/observer/src/test/java/com/iluwatar/observer/utils/InMemoryAppender.java b/observer/src/test/java/com/iluwatar/observer/utils/InMemoryAppender.java new file mode 100644 index 000000000..4e6e49768 --- /dev/null +++ b/observer/src/test/java/com/iluwatar/observer/utils/InMemoryAppender.java @@ -0,0 +1,58 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.observer.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; + +public class InMemoryAppender extends AppenderBase { + private List log = new LinkedList<>(); + + public InMemoryAppender(Class clazz) { + ((Logger) LoggerFactory.getLogger(clazz)).addAppender(this); + start(); + } + + public InMemoryAppender() { + ((Logger) LoggerFactory.getLogger("root")).addAppender(this); + start(); + } + + @Override + protected void append(ILoggingEvent eventObject) { + log.add(eventObject); + } + + public int getLogSize() { + return log.size(); + } + + public String getLastMessage() { + return log.get(log.size() - 1).getFormattedMessage(); + } +} 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 c811225e1..6a586c52d 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 @@ -23,11 +23,15 @@ package com.iluwatar.poison.pill; import com.iluwatar.poison.pill.Message.Headers; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * Class responsible for receiving and handling submitted to the queue messages */ public class Consumer { + + private static final Logger LOGGER = LoggerFactory.getLogger(Consumer.class); private final MqSubscribePoint queue; private final String name; @@ -46,19 +50,18 @@ public class Consumer { try { msg = queue.take(); if (Message.POISON_PILL.equals(msg)) { - System.out.println(String.format("Consumer %s receive request to terminate.", name)); + LOGGER.info("Consumer {} receive request to terminate.", name); break; } } catch (InterruptedException e) { // allow thread to exit - System.err.println(e); + LOGGER.error("Exception caught.", e); return; } String sender = msg.getHeader(Headers.SENDER); String body = msg.getBody(); - System.out.println(String.format("Message [%s] from [%s] received by [%s]", body, sender, - name)); + LOGGER.info("Message [{}] from [{}] received by [{}]", body, sender, name); } } } 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 15dcad40e..af07ed679 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 @@ -25,6 +25,8 @@ package com.iluwatar.poison.pill; import java.util.Date; import com.iluwatar.poison.pill.Message.Headers; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * Class responsible for producing unit of work that can be expressed as message and submitted to @@ -32,6 +34,8 @@ import com.iluwatar.poison.pill.Message.Headers; */ public class Producer { + private static final Logger LOGGER = LoggerFactory.getLogger(Producer.class); + private final MqPublishPoint queue; private final String name; private boolean isStopped; @@ -62,7 +66,7 @@ public class Producer { queue.put(msg); } catch (InterruptedException e) { // allow thread to exit - System.err.println(e); + LOGGER.error("Exception caught.", e); } } @@ -75,7 +79,7 @@ public class Producer { queue.put(Message.POISON_PILL); } catch (InterruptedException e) { // allow thread to exit - System.err.println(e); + LOGGER.error("Exception caught.", e); } } } 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 01a5dfaa6..983287c3c 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 @@ -22,19 +22,38 @@ */ package com.iluwatar.poison.pill; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.AppenderBase; +import org.junit.After; +import org.junit.Before; import org.junit.Test; -import org.mockito.InOrder; +import org.slf4j.LoggerFactory; import java.time.LocalDateTime; +import java.util.LinkedList; +import java.util.List; -import static org.mockito.Mockito.inOrder; +import static org.junit.Assert.assertTrue; /** * Date: 12/27/15 - 9:45 PM * * @author Jeroen Meulemeester */ -public class ConsumerTest extends StdOutTest { +public class ConsumerTest { + + private InMemoryAppender appender; + + @Before + public void setUp() { + appender = new InMemoryAppender(Consumer.class); + } + + @After + public void tearDown() { + appender.stop(); + } @Test public void testConsume() throws Exception { @@ -52,12 +71,9 @@ public class ConsumerTest extends StdOutTest { new Consumer("NSA", queue).consume(); - final InOrder inOrder = inOrder(getStdOutMock()); - inOrder.verify(getStdOutMock()).println("Message [Hello!] from [you] received by [NSA]"); - inOrder.verify(getStdOutMock()).println("Message [Hi!] from [me] received by [NSA]"); - inOrder.verify(getStdOutMock()).println("Consumer NSA receive request to terminate."); - inOrder.verifyNoMoreInteractions(); - + assertTrue(appender.logContains("Message [Hello!] from [you] received by [NSA]")); + assertTrue(appender.logContains("Message [Hi!] from [me] received by [NSA]")); + assertTrue(appender.logContains("Consumer NSA receive request to terminate.")); } /** @@ -75,4 +91,22 @@ public class ConsumerTest extends StdOutTest { return msg; } -} \ No newline at end of file + private class InMemoryAppender extends AppenderBase { + private List log = new LinkedList<>(); + + public InMemoryAppender(Class clazz) { + ((Logger) LoggerFactory.getLogger(clazz)).addAppender(this); + start(); + } + + @Override + protected void append(ILoggingEvent eventObject) { + log.add(eventObject); + } + + public boolean logContains(String message) { + return log.stream().anyMatch(event -> event.getFormattedMessage().equals(message)); + } + } + +} diff --git a/poison-pill/src/test/java/com/iluwatar/poison/pill/StdOutTest.java b/poison-pill/src/test/java/com/iluwatar/poison/pill/StdOutTest.java deleted file mode 100644 index f1b3c4840..000000000 --- a/poison-pill/src/test/java/com/iluwatar/poison/pill/StdOutTest.java +++ /dev/null @@ -1,75 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014 Ilkka Seppälä - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package com.iluwatar.poison.pill; - -import org.junit.After; -import org.junit.Before; - -import java.io.PrintStream; - -import static org.mockito.Mockito.mock; - -/** - * Date: 12/10/15 - 8:37 PM - * - * @author Jeroen Meulemeester - */ -public abstract class StdOutTest { - - /** - * The mocked standard out {@link PrintStream}, required since some actions don't have any - * influence on accessible objects, except for writing to std-out using {@link System#out} - */ - private final PrintStream stdOutMock = mock(PrintStream.class); - - /** - * Keep the original std-out so it can be restored after the test - */ - private final PrintStream stdOutOrig = System.out; - - /** - * Inject the mocked std-out {@link PrintStream} into the {@link System} class before each test - */ - @Before - public void setUp() { - System.setOut(this.stdOutMock); - } - - /** - * Removed the mocked std-out {@link PrintStream} again from the {@link System} class - */ - @After - public void tearDown() { - System.setOut(this.stdOutOrig); - } - - /** - * Get the mocked stdOut {@link PrintStream} - * - * @return The stdOut print stream mock, renewed before each test - */ - final PrintStream getStdOutMock() { - return this.stdOutMock; - } - -} diff --git a/pom.xml b/pom.xml index b8440f664..adb95bef2 100644 --- a/pom.xml +++ b/pom.xml @@ -38,7 +38,6 @@ 0.7.2.201409121644 1.4 2.16.1 - 1.2.17 19.0 1.15.1 1.10.19 @@ -48,6 +47,8 @@ 1.4.1 4.0 3.3.0 + 1.7.21 + 1.1.7 abstract-factory @@ -210,11 +211,6 @@ ${mockito.version} test - - log4j - log4j - ${log4j.version} - com.google.guava guava @@ -251,6 +247,23 @@ + + + org.slf4j + slf4j-api + ${slf4j.version} + + + ch.qos.logback + logback-classic + ${logback.version} + + + ch.qos.logback + logback-core + ${logback.version} + + 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 b9d2ad09c..73bfb948f 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 @@ -22,6 +22,9 @@ */ package com.iluwatar.privateclassdata; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * * Immutable stew class, protected with Private Class Data pattern @@ -29,6 +32,8 @@ package com.iluwatar.privateclassdata; */ public class ImmutableStew { + private static final Logger LOGGER = LoggerFactory.getLogger(ImmutableStew.class); + private StewData data; public ImmutableStew(int numPotatoes, int numCarrots, int numMeat, int numPeppers) { @@ -39,8 +44,7 @@ public class ImmutableStew { * Mix the stew */ public void mix() { - System.out.println(String.format( - "Mixing the immutable stew we find: %d potatoes, %d carrots, %d meat and %d peppers", - data.getNumPotatoes(), data.getNumCarrots(), data.getNumMeat(), data.getNumPeppers())); + LOGGER.info("Mixing the immutable stew we find: {} potatoes, {} carrots, {} meat and {} peppers", + data.getNumPotatoes(), data.getNumCarrots(), data.getNumMeat(), data.getNumPeppers()); } } 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 9c9033018..665edf418 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 @@ -22,6 +22,9 @@ */ package com.iluwatar.privateclassdata; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * * Mutable stew class @@ -29,6 +32,8 @@ package com.iluwatar.privateclassdata; */ public class Stew { + private static final Logger LOGGER = LoggerFactory.getLogger(Stew.class); + private int numPotatoes; private int numCarrots; private int numMeat; @@ -48,16 +53,15 @@ public class Stew { * Mix the stew */ public void mix() { - System.out.println(String.format( - "Mixing the stew we find: %d potatoes, %d carrots, %d meat and %d peppers", numPotatoes, - numCarrots, numMeat, numPeppers)); + LOGGER.info("Mixing the stew we find: {} potatoes, {} carrots, {} meat and {} peppers", + numPotatoes, numCarrots, numMeat, numPeppers); } /** * Taste the stew */ public void taste() { - System.out.println("Tasting the stew"); + LOGGER.info("Tasting the stew"); if (numPotatoes > 0) { numPotatoes--; } 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 58867d303..431375ef7 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 @@ -22,18 +22,31 @@ */ package com.iluwatar.privateclassdata; +import com.iluwatar.privateclassdata.utils.InMemoryAppender; +import org.junit.After; +import org.junit.Before; import org.junit.Test; -import org.mockito.InOrder; -import static org.mockito.Mockito.inOrder; -import static org.mockito.Mockito.verify; +import static org.junit.Assert.assertEquals; /** * Date: 12/27/15 - 10:46 PM * * @author Jeroen Meulemeester */ -public class ImmutableStewTest extends StdOutTest { +public class ImmutableStewTest { + + private InMemoryAppender appender; + + @Before + public void setUp() { + appender = new InMemoryAppender(); + } + + @After + public void tearDown() { + appender.stop(); + } /** * Verify if mixing the stew doesn't change the internal state @@ -41,15 +54,14 @@ public class ImmutableStewTest extends StdOutTest { @Test public void testMix() { final Stew stew = new Stew(1, 2, 3, 4); - final String message = "Mixing the stew we find: 1 potatoes, 2 carrots, 3 meat and 4 peppers"; + final String expectedMessage = "Mixing the stew we find: 1 potatoes, 2 carrots, 3 meat and 4 peppers"; - final InOrder inOrder = inOrder(getStdOutMock()); for (int i = 0; i < 20; i++) { stew.mix(); - inOrder.verify(getStdOutMock()).println(message); + assertEquals(expectedMessage, appender.getLastMessage()); } - inOrder.verifyNoMoreInteractions(); + assertEquals(20, appender.getLogSize()); } /** @@ -60,15 +72,12 @@ public class ImmutableStewTest extends StdOutTest { final Stew stew = new Stew(1, 2, 3, 4); stew.mix(); - verify(getStdOutMock()) - .println("Mixing the stew we find: 1 potatoes, 2 carrots, 3 meat and 4 peppers"); + assertEquals("Mixing the stew we find: 1 potatoes, 2 carrots, 3 meat and 4 peppers", appender.getLastMessage()); stew.taste(); - verify(getStdOutMock()).println("Tasting the stew"); + assertEquals("Tasting the stew", appender.getLastMessage()); stew.mix(); - verify(getStdOutMock()) - .println("Mixing the stew we find: 0 potatoes, 1 carrots, 2 meat and 3 peppers"); - + assertEquals("Mixing the stew we find: 0 potatoes, 1 carrots, 2 meat and 3 peppers", appender.getLastMessage()); } -} \ No newline at end of file +} diff --git a/private-class-data/src/test/java/com/iluwatar/privateclassdata/StdOutTest.java b/private-class-data/src/test/java/com/iluwatar/privateclassdata/StdOutTest.java deleted file mode 100644 index f90551020..000000000 --- a/private-class-data/src/test/java/com/iluwatar/privateclassdata/StdOutTest.java +++ /dev/null @@ -1,75 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014 Ilkka Seppälä - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package com.iluwatar.privateclassdata; - -import org.junit.After; -import org.junit.Before; - -import java.io.PrintStream; - -import static org.mockito.Mockito.mock; - -/** - * Date: 12/10/15 - 8:37 PM - * - * @author Jeroen Meulemeester - */ -public abstract class StdOutTest { - - /** - * The mocked standard out {@link PrintStream}, required since some actions don't have any - * influence on accessible objects, except for writing to std-out using {@link System#out} - */ - private final PrintStream stdOutMock = mock(PrintStream.class); - - /** - * Keep the original std-out so it can be restored after the test - */ - private final PrintStream stdOutOrig = System.out; - - /** - * Inject the mocked std-out {@link PrintStream} into the {@link System} class before each test - */ - @Before - public void setUp() { - System.setOut(this.stdOutMock); - } - - /** - * Removed the mocked std-out {@link PrintStream} again from the {@link System} class - */ - @After - public void tearDown() { - System.setOut(this.stdOutOrig); - } - - /** - * Get the mocked stdOut {@link PrintStream} - * - * @return The stdOut print stream mock, renewed before each test - */ - final PrintStream getStdOutMock() { - return this.stdOutMock; - } - -} 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 a894e4ae0..f2e3c5fad 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 @@ -22,17 +22,31 @@ */ package com.iluwatar.privateclassdata; +import com.iluwatar.privateclassdata.utils.InMemoryAppender; +import org.junit.After; +import org.junit.Before; import org.junit.Test; -import org.mockito.InOrder; -import static org.mockito.Mockito.inOrder; +import static org.junit.Assert.assertEquals; /** * Date: 12/27/15 - 10:46 PM * * @author Jeroen Meulemeester */ -public class StewTest extends StdOutTest { +public class StewTest { + + private InMemoryAppender appender; + + @Before + public void setUp() { + appender = new InMemoryAppender(); + } + + @After + public void tearDown() { + appender.stop(); + } /** * Verify if mixing the stew doesn't change the internal state @@ -43,13 +57,12 @@ public class StewTest extends StdOutTest { final String expectedMessage = "Mixing the immutable stew we find: 1 potatoes, " + "2 carrots, 3 meat and 4 peppers"; - final InOrder inOrder = inOrder(getStdOutMock()); for (int i = 0; i < 20; i++) { stew.mix(); - inOrder.verify(getStdOutMock()).println(expectedMessage); + assertEquals(expectedMessage, appender.getLastMessage()); } - inOrder.verifyNoMoreInteractions(); + assertEquals(20, appender.getLogSize()); } -} \ No newline at end of file +} 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 new file mode 100644 index 000000000..4b2def101 --- /dev/null +++ b/private-class-data/src/test/java/com/iluwatar/privateclassdata/utils/InMemoryAppender.java @@ -0,0 +1,53 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.privateclassdata.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; + +public class InMemoryAppender extends AppenderBase { + private List log = new LinkedList<>(); + + public InMemoryAppender() { + ((Logger) LoggerFactory.getLogger("root")).addAppender(this); + start(); + } + + @Override + protected void append(ILoggingEvent eventObject) { + log.add(eventObject); + } + + public int getLogSize() { + return log.size(); + } + + public String getLastMessage() { + return log.get(log.size() - 1).getFormattedMessage(); + } +} 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 42f6dfa79..dca2457c4 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 @@ -22,6 +22,9 @@ */ package com.iluwatar.producer.consumer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; @@ -37,6 +40,8 @@ import java.util.concurrent.TimeUnit; */ public class App { + private static final Logger LOGGER = LoggerFactory.getLogger(App.class); + /** * Program entry point * @@ -72,7 +77,7 @@ public class App { executorService.awaitTermination(10, TimeUnit.SECONDS); executorService.shutdownNow(); } catch (InterruptedException e) { - System.out.println("Error waiting for ExecutorService shutdown"); + LOGGER.error("Error waiting for 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 f1fa920f3..880b76ba5 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 @@ -22,11 +22,16 @@ */ package com.iluwatar.producer.consumer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * Class responsible for consume the {@link Item} produced by {@link Producer} */ public class Consumer { + private static final Logger LOGGER = LoggerFactory.getLogger(Consumer.class); + private final ItemQueue queue; private final String name; @@ -42,8 +47,7 @@ public class Consumer { public void consume() throws InterruptedException { Item item = queue.take(); - System.out.println(String.format("Consumer [%s] consume item [%s] produced by [%s]", name, - item.getId(), item.getProducer())); + LOGGER.info("Consumer [{}] consume item [{}] produced by [{}]", name, item.getId(), item.getProducer()); } } 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 2ca547a0b..dd725df75 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 @@ -23,18 +23,15 @@ package com.iluwatar.producer.consumer; import org.junit.Test; -import org.mockito.InOrder; -import static org.mockito.Mockito.inOrder; -import static org.mockito.Mockito.reset; -import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.*; /** * Date: 12/27/15 - 11:01 PM * * @author Jeroen Meulemeester */ -public class ConsumerTest extends StdOutTest { +public class ConsumerTest { private static final int ITEM_COUNT = 5; @@ -48,14 +45,11 @@ public class ConsumerTest extends StdOutTest { reset(queue); // Don't count the preparation above as interactions with the queue final Consumer consumer = new Consumer("consumer", queue); - final InOrder inOrder = inOrder(getStdOutMock()); for (int id = 0; id < ITEM_COUNT; id++) { consumer.consume(); - inOrder.verify(getStdOutMock()) - .println("Consumer [consumer] consume item [" + id + "] produced by [producer]"); } - inOrder.verifyNoMoreInteractions(); + verify(queue, times(ITEM_COUNT)).take(); } } diff --git a/producer-consumer/src/test/java/com/iluwatar/producer/consumer/StdOutTest.java b/producer-consumer/src/test/java/com/iluwatar/producer/consumer/StdOutTest.java deleted file mode 100644 index 1e1c41f75..000000000 --- a/producer-consumer/src/test/java/com/iluwatar/producer/consumer/StdOutTest.java +++ /dev/null @@ -1,75 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014 Ilkka Seppälä - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package com.iluwatar.producer.consumer; - -import org.junit.After; -import org.junit.Before; - -import java.io.PrintStream; - -import static org.mockito.Mockito.mock; - -/** - * Date: 12/10/15 - 8:37 PM - * - * @author Jeroen Meulemeester - */ -public abstract class StdOutTest { - - /** - * The mocked standard out {@link PrintStream}, required since some actions don't have any - * influence on accessible objects, except for writing to std-out using {@link System#out} - */ - private final PrintStream stdOutMock = mock(PrintStream.class); - - /** - * Keep the original std-out so it can be restored after the test - */ - private final PrintStream stdOutOrig = System.out; - - /** - * Inject the mocked std-out {@link PrintStream} into the {@link System} class before each test - */ - @Before - public void setUp() { - System.setOut(this.stdOutMock); - } - - /** - * Removed the mocked std-out {@link PrintStream} again from the {@link System} class - */ - @After - public void tearDown() { - System.setOut(this.stdOutOrig); - } - - /** - * Get the mocked stdOut {@link PrintStream} - * - * @return The stdOut print stream mock, renewed before each test - */ - final PrintStream getStdOutMock() { - return this.stdOutMock; - } - -} diff --git a/promise/src/main/java/com/iluwatar/promise/App.java b/promise/src/main/java/com/iluwatar/promise/App.java index 672c20bfa..7e1f174ef 100644 --- a/promise/src/main/java/com/iluwatar/promise/App.java +++ b/promise/src/main/java/com/iluwatar/promise/App.java @@ -21,6 +21,9 @@ * THE SOFTWARE. */ package com.iluwatar.promise; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CountDownLatch; @@ -60,6 +63,8 @@ import java.util.concurrent.Executors; */ public class App { + private static final Logger LOGGER = LoggerFactory.getLogger(App.class); + private static final String DEFAULT_URL = "https://raw.githubusercontent.com/iluwatar/java-design-patterns/Promise/promise/README.md"; private final ExecutorService executor; private final CountDownLatch stopLatch; @@ -98,7 +103,7 @@ public class App { lowestFrequencyChar() .thenAccept( charFrequency -> { - System.out.println("Char with lowest frequency is: " + charFrequency); + LOGGER.info("Char with lowest frequency is: {}", charFrequency); taskCompleted(); } ); @@ -112,7 +117,7 @@ public class App { countLines() .thenAccept( count -> { - System.out.println("Line count is: " + count); + LOGGER.info("Line count is: {}", count); taskCompleted(); } ); diff --git a/promise/src/main/java/com/iluwatar/promise/Utility.java b/promise/src/main/java/com/iluwatar/promise/Utility.java index d451600a3..769a6fcd1 100644 --- a/promise/src/main/java/com/iluwatar/promise/Utility.java +++ b/promise/src/main/java/com/iluwatar/promise/Utility.java @@ -22,6 +22,9 @@ */ package com.iluwatar.promise; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.io.BufferedReader; import java.io.File; import java.io.FileReader; @@ -38,6 +41,8 @@ import java.util.Map.Entry; public class Utility { + private static final Logger LOGGER = LoggerFactory.getLogger(Utility.class); + /** * Calculates character frequency of the file provided. * @param fileLocation location of the file. @@ -104,7 +109,7 @@ public class Utility { * @return the absolute path of the file downloaded. */ public static String downloadFile(String urlString) throws MalformedURLException, IOException { - System.out.println("Downloading contents from url: " + urlString); + LOGGER.info("Downloading contents from url: {}", urlString); URL url = new URL(urlString); File file = File.createTempFile("promise_pattern", null); try (Reader reader = new InputStreamReader(url.openStream()); @@ -114,7 +119,7 @@ public class Utility { writer.write(line); writer.write("\n"); } - System.out.println("File downloaded at: " + file.getAbsolutePath()); + LOGGER.info("File downloaded at: {}", file.getAbsolutePath()); return file.getAbsolutePath(); } catch (IOException ex) { throw ex; diff --git a/property/src/main/java/com/iluwatar/property/App.java b/property/src/main/java/com/iluwatar/property/App.java index e3f7cc92b..576bada18 100644 --- a/property/src/main/java/com/iluwatar/property/App.java +++ b/property/src/main/java/com/iluwatar/property/App.java @@ -23,6 +23,8 @@ package com.iluwatar.property; import com.iluwatar.property.Character.Type; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * @@ -39,6 +41,8 @@ import com.iluwatar.property.Character.Type; */ public class App { + private static final Logger LOGGER = LoggerFactory.getLogger(App.class); + /** * Program entry point * @@ -67,16 +71,16 @@ public class App { /* usage */ Character mag = new Character("Player_1", mageProto); mag.set(Stats.ARMOR, 8); - System.out.println(mag); + LOGGER.info(mag.toString()); Character warrior = new Character("Player_2", warProto); - System.out.println(warrior); + LOGGER.info(warrior.toString()); Character rogue = new Character("Player_3", rogueProto); - System.out.println(rogue); + LOGGER.info(rogue.toString()); Character rogueDouble = new Character("Player_4", rogue); rogueDouble.set(Stats.ATTACK_POWER, 12); - System.out.println(rogueDouble); + LOGGER.info(rogueDouble.toString()); } } diff --git a/prototype/src/main/java/com/iluwatar/prototype/App.java b/prototype/src/main/java/com/iluwatar/prototype/App.java index cb04ec5f2..bb98194ce 100644 --- a/prototype/src/main/java/com/iluwatar/prototype/App.java +++ b/prototype/src/main/java/com/iluwatar/prototype/App.java @@ -22,6 +22,9 @@ */ package com.iluwatar.prototype; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * * The Prototype pattern is a creational design pattern in software development. It is used when the @@ -36,6 +39,8 @@ package com.iluwatar.prototype; */ public class App { + private static final Logger LOGGER = LoggerFactory.getLogger(App.class); + /** * Program entry point * @@ -51,16 +56,16 @@ public class App { mage = factory.createMage(); warlord = factory.createWarlord(); beast = factory.createBeast(); - System.out.println(mage); - System.out.println(warlord); - System.out.println(beast); + LOGGER.info(mage.toString()); + LOGGER.info(warlord.toString()); + LOGGER.info(beast.toString()); factory = new HeroFactoryImpl(new OrcMage(), new OrcWarlord(), new OrcBeast()); mage = factory.createMage(); warlord = factory.createWarlord(); beast = factory.createBeast(); - System.out.println(mage); - System.out.println(warlord); - System.out.println(beast); + LOGGER.info(mage.toString()); + LOGGER.info(warlord.toString()); + LOGGER.info(beast.toString()); } } diff --git a/proxy/src/main/java/com/iluwatar/proxy/WizardTower.java b/proxy/src/main/java/com/iluwatar/proxy/WizardTower.java index 573d38374..d5daab305 100644 --- a/proxy/src/main/java/com/iluwatar/proxy/WizardTower.java +++ b/proxy/src/main/java/com/iluwatar/proxy/WizardTower.java @@ -22,6 +22,9 @@ */ package com.iluwatar.proxy; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * * The object to be proxyed. @@ -29,8 +32,10 @@ package com.iluwatar.proxy; */ public class WizardTower { + private static final Logger LOGGER = LoggerFactory.getLogger(WizardTower.class); + public void enter(Wizard wizard) { - System.out.println(wizard + " enters the tower."); + LOGGER.info("{} enters the tower.", wizard); } } diff --git a/proxy/src/main/java/com/iluwatar/proxy/WizardTowerProxy.java b/proxy/src/main/java/com/iluwatar/proxy/WizardTowerProxy.java index 985184afe..1048724d4 100644 --- a/proxy/src/main/java/com/iluwatar/proxy/WizardTowerProxy.java +++ b/proxy/src/main/java/com/iluwatar/proxy/WizardTowerProxy.java @@ -22,6 +22,9 @@ */ package com.iluwatar.proxy; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * * The proxy controlling access to the {@link WizardTower}. @@ -29,6 +32,8 @@ package com.iluwatar.proxy; */ public class WizardTowerProxy extends WizardTower { + private static final Logger LOGGER = LoggerFactory.getLogger(WizardTowerProxy.class); + private static final int NUM_WIZARDS_ALLOWED = 3; private int numWizards; @@ -39,7 +44,7 @@ public class WizardTowerProxy extends WizardTower { super.enter(wizard); numWizards++; } else { - System.out.println(wizard + " is not allowed to enter!"); + LOGGER.info("{} is not allowed to enter!", wizard); } } } diff --git a/proxy/src/test/java/com/iluwatar/proxy/StdOutTest.java b/proxy/src/test/java/com/iluwatar/proxy/StdOutTest.java deleted file mode 100644 index 48831444a..000000000 --- a/proxy/src/test/java/com/iluwatar/proxy/StdOutTest.java +++ /dev/null @@ -1,75 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014 Ilkka Seppälä - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package com.iluwatar.proxy; - -import org.junit.After; -import org.junit.Before; - -import java.io.PrintStream; - -import static org.mockito.Mockito.mock; - -/** - * Date: 12/10/15 - 8:37 PM - * - * @author Jeroen Meulemeester - */ -public abstract class StdOutTest { - - /** - * The mocked standard out {@link PrintStream}, required since some actions don't have any - * influence on accessible objects, except for writing to std-out using {@link System#out} - */ - private final PrintStream stdOutMock = mock(PrintStream.class); - - /** - * Keep the original std-out so it can be restored after the test - */ - private final PrintStream stdOutOrig = System.out; - - /** - * Inject the mocked std-out {@link PrintStream} into the {@link System} class before each test - */ - @Before - public void setUp() { - System.setOut(this.stdOutMock); - } - - /** - * Removed the mocked std-out {@link PrintStream} again from the {@link System} class - */ - @After - public void tearDown() { - System.setOut(this.stdOutOrig); - } - - /** - * Get the mocked stdOut {@link PrintStream} - * - * @return The stdOut print stream mock, renewed before each test - */ - final PrintStream getStdOutMock() { - return this.stdOutMock; - } - -} diff --git a/proxy/src/test/java/com/iluwatar/proxy/WizardTowerProxyTest.java b/proxy/src/test/java/com/iluwatar/proxy/WizardTowerProxyTest.java index b87b7a0bc..921624f63 100644 --- a/proxy/src/test/java/com/iluwatar/proxy/WizardTowerProxyTest.java +++ b/proxy/src/test/java/com/iluwatar/proxy/WizardTowerProxyTest.java @@ -22,17 +22,32 @@ */ package com.iluwatar.proxy; +import com.iluwatar.proxy.utils.InMemoryAppender; +import org.junit.After; +import org.junit.Before; import org.junit.Test; -import org.mockito.InOrder; -import static org.mockito.Mockito.inOrder; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; /** * Date: 12/28/15 - 9:18 PM * * @author Jeroen Meulemeester */ -public class WizardTowerProxyTest extends StdOutTest { +public class WizardTowerProxyTest { + + private InMemoryAppender appender; + + @Before + public void setUp() { + appender = new InMemoryAppender(); + } + + @After + public void tearDown() { + appender.stop(); + } @Test public void testEnter() throws Exception { @@ -48,13 +63,11 @@ public class WizardTowerProxyTest extends StdOutTest { tower.enter(wizard); } - final InOrder inOrder = inOrder(getStdOutMock()); - inOrder.verify(getStdOutMock()).println("Gandalf enters the tower."); - inOrder.verify(getStdOutMock()).println("Dumbledore enters the tower."); - inOrder.verify(getStdOutMock()).println("Oz enters the tower."); - inOrder.verify(getStdOutMock()).println("Merlin is not allowed to enter!"); - inOrder.verifyNoMoreInteractions(); - + assertTrue(appender.logContains("Gandalf enters the tower.")); + assertTrue(appender.logContains("Dumbledore enters the tower.")); + assertTrue(appender.logContains("Oz enters the tower.")); + assertTrue(appender.logContains("Merlin is not allowed to enter!")); + assertEquals(4, appender.getLogSize()); } -} \ No newline at end of file +} diff --git a/proxy/src/test/java/com/iluwatar/proxy/WizardTowerTest.java b/proxy/src/test/java/com/iluwatar/proxy/WizardTowerTest.java index 9996434f5..ab56115ca 100644 --- a/proxy/src/test/java/com/iluwatar/proxy/WizardTowerTest.java +++ b/proxy/src/test/java/com/iluwatar/proxy/WizardTowerTest.java @@ -22,17 +22,32 @@ */ package com.iluwatar.proxy; +import com.iluwatar.proxy.utils.InMemoryAppender; +import org.junit.After; +import org.junit.Before; import org.junit.Test; -import org.mockito.InOrder; -import static org.mockito.Mockito.inOrder; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; /** * Date: 12/28/15 - 9:18 PM * * @author Jeroen Meulemeester */ -public class WizardTowerTest extends StdOutTest { +public class WizardTowerTest { + + private InMemoryAppender appender; + + @Before + public void setUp() { + appender = new InMemoryAppender(WizardTower.class); + } + + @After + public void tearDown() { + appender.stop(); + } @Test public void testEnter() throws Exception { @@ -48,13 +63,11 @@ public class WizardTowerTest extends StdOutTest { tower.enter(wizard); } - final InOrder inOrder = inOrder(getStdOutMock()); - inOrder.verify(getStdOutMock()).println("Gandalf enters the tower."); - inOrder.verify(getStdOutMock()).println("Dumbledore enters the tower."); - inOrder.verify(getStdOutMock()).println("Oz enters the tower."); - inOrder.verify(getStdOutMock()).println("Merlin enters the tower."); - inOrder.verifyNoMoreInteractions(); - + assertTrue(appender.logContains("Gandalf enters the tower.")); + assertTrue(appender.logContains("Dumbledore enters the tower.")); + assertTrue(appender.logContains("Oz enters the tower.")); + assertTrue(appender.logContains("Merlin enters the tower.")); + assertEquals(4, appender.getLogSize()); } -} \ No newline at end of file +} diff --git a/proxy/src/test/java/com/iluwatar/proxy/utils/InMemoryAppender.java b/proxy/src/test/java/com/iluwatar/proxy/utils/InMemoryAppender.java new file mode 100644 index 000000000..857d3e548 --- /dev/null +++ b/proxy/src/test/java/com/iluwatar/proxy/utils/InMemoryAppender.java @@ -0,0 +1,58 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.proxy.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; + +public class InMemoryAppender extends AppenderBase { + private List log = new LinkedList<>(); + + public InMemoryAppender(Class clazz) { + ((Logger) LoggerFactory.getLogger(clazz)).addAppender(this); + start(); + } + + public InMemoryAppender() { + ((Logger) LoggerFactory.getLogger("root")).addAppender(this); + start(); + } + + @Override + protected void append(ILoggingEvent eventObject) { + log.add(eventObject); + } + + public boolean logContains(String message) { + return log.stream().anyMatch(event -> event.getFormattedMessage().equals(message)); + } + + public int getLogSize() { + return log.size(); + } +} diff --git a/publish-subscribe/src/main/java/com/iluwatar/publish/subscribe/App.java b/publish-subscribe/src/main/java/com/iluwatar/publish/subscribe/App.java index c4e423b04..ff66e4e58 100644 --- a/publish-subscribe/src/main/java/com/iluwatar/publish/subscribe/App.java +++ b/publish-subscribe/src/main/java/com/iluwatar/publish/subscribe/App.java @@ -26,6 +26,8 @@ import org.apache.camel.CamelContext; import org.apache.camel.ProducerTemplate; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.impl.DefaultCamelContext; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * @@ -48,6 +50,8 @@ import org.apache.camel.impl.DefaultCamelContext; */ public class App { + private static final Logger LOGGER = LoggerFactory.getLogger(App.class); + /** * Program entry point */ @@ -61,7 +65,7 @@ public class App { }); ProducerTemplate template = context.createProducerTemplate(); context.start(); - context.getRoutes().stream().forEach(r -> System.out.println(r)); + context.getRoutes().stream().forEach(r -> LOGGER.info(r.toString())); template.sendBody("direct:origin", "Hello from origin"); context.stop(); } diff --git a/publish-subscribe/src/main/resources/logback.xml b/publish-subscribe/src/main/resources/logback.xml new file mode 100644 index 000000000..95bed0150 --- /dev/null +++ b/publish-subscribe/src/main/resources/logback.xml @@ -0,0 +1,52 @@ + + + + publish-subscribe.log + + publish-subscribe-%d.log + 5 + + + %-5p [%d{ISO8601,UTC}] %c: %m%n + + + + + + %-5p [%d{ISO8601,UTC}] %c: %m%n + + + + + + + + + + + + + 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 29c2f83fa..77e4e1f4f 100644 --- a/reactor/src/main/java/com/iluwatar/reactor/app/AppClient.java +++ b/reactor/src/main/java/com/iluwatar/reactor/app/AppClient.java @@ -22,6 +22,9 @@ */ package com.iluwatar.reactor.app; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; @@ -41,6 +44,9 @@ import java.util.concurrent.TimeUnit; * requests to Reactor. */ public class AppClient { + + private static final Logger LOGGER = LoggerFactory.getLogger(AppClient.class); + private final ExecutorService service = Executors.newFixedThreadPool(4); /** @@ -126,9 +132,9 @@ public class AppClient { byte[] data = new byte[1024]; int read = inputStream.read(data, 0, data.length); if (read == 0) { - System.out.println("Read zero bytes"); + LOGGER.info("Read zero bytes"); } else { - System.out.println(new String(data, 0, read)); + LOGGER.info(new String(data, 0, read)); } artificialDelayOf(100); @@ -171,9 +177,9 @@ public class AppClient { DatagramPacket reply = new DatagramPacket(data, data.length); socket.receive(reply); if (reply.getLength() == 0) { - System.out.println("Read zero bytes"); + LOGGER.info("Read zero bytes"); } else { - System.out.println(new String(reply.getData(), 0, reply.getLength())); + LOGGER.info(new String(reply.getData(), 0, reply.getLength())); } artificialDelayOf(100); 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 ab2bcfb1a..e1095d34e 100644 --- a/reactor/src/main/java/com/iluwatar/reactor/app/LoggingHandler.java +++ b/reactor/src/main/java/com/iluwatar/reactor/app/LoggingHandler.java @@ -28,6 +28,8 @@ import java.nio.channels.SelectionKey; import com.iluwatar.reactor.framework.AbstractNioChannel; import com.iluwatar.reactor.framework.ChannelHandler; import com.iluwatar.reactor.framework.NioDatagramChannel.DatagramPacket; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * Logging server application logic. It logs the incoming requests on standard console and returns a @@ -35,6 +37,8 @@ import com.iluwatar.reactor.framework.NioDatagramChannel.DatagramPacket; */ public class LoggingHandler implements ChannelHandler { + private static final Logger LOGGER = LoggerFactory.getLogger(LoggingHandler.class); + private static final byte[] ACK = "Data logged successfully".getBytes(); /** @@ -76,6 +80,6 @@ public class LoggingHandler implements ChannelHandler { private static void doLogging(ByteBuffer data) { // assuming UTF-8 :( - System.out.println(new String(data.array(), 0, data.limit())); + LOGGER.info(new String(data.array(), 0, data.limit())); } } 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 4e493163f..52d2d68b0 100644 --- a/reactor/src/main/java/com/iluwatar/reactor/framework/NioDatagramChannel.java +++ b/reactor/src/main/java/com/iluwatar/reactor/framework/NioDatagramChannel.java @@ -22,6 +22,9 @@ */ package com.iluwatar.reactor.framework; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; @@ -35,6 +38,8 @@ import java.nio.channels.SelectionKey; */ public class NioDatagramChannel extends AbstractNioChannel { + private static final Logger LOGGER = LoggerFactory.getLogger(NioDatagramChannel.class); + private final int port; /** @@ -99,7 +104,7 @@ public class NioDatagramChannel extends AbstractNioChannel { public void bind() throws IOException { getJavaChannel().socket().bind(new InetSocketAddress(InetAddress.getLocalHost(), port)); getJavaChannel().configureBlocking(false); - System.out.println("Bound UDP socket at port: " + port); + LOGGER.info("Bound UDP socket at port: {}", port); } /** 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 3d5ebf5a0..0facf1935 100644 --- a/reactor/src/main/java/com/iluwatar/reactor/framework/NioReactor.java +++ b/reactor/src/main/java/com/iluwatar/reactor/framework/NioReactor.java @@ -22,6 +22,9 @@ */ package com.iluwatar.reactor.framework; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.io.IOException; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; @@ -53,6 +56,8 @@ import java.util.concurrent.TimeUnit; */ public class NioReactor { + private static final Logger LOGGER = LoggerFactory.getLogger(NioReactor.class); + private final Selector selector; private final Dispatcher dispatcher; /** @@ -86,7 +91,7 @@ public class NioReactor { public void start() throws IOException { reactorMain.execute(() -> { try { - System.out.println("Reactor started, waiting for events..."); + LOGGER.info("Reactor started, waiting for events..."); eventLoop(); } catch (IOException e) { e.printStackTrace(); 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 c7d67fd13..d1c6bb62a 100644 --- a/reactor/src/main/java/com/iluwatar/reactor/framework/NioServerSocketChannel.java +++ b/reactor/src/main/java/com/iluwatar/reactor/framework/NioServerSocketChannel.java @@ -22,6 +22,9 @@ */ package com.iluwatar.reactor.framework; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; @@ -36,6 +39,8 @@ import java.nio.channels.SocketChannel; */ public class NioServerSocketChannel extends AbstractNioChannel { + private static final Logger LOGGER = LoggerFactory.getLogger(NioServerSocketChannel.class); + private final int port; /** @@ -96,7 +101,7 @@ public class NioServerSocketChannel extends AbstractNioChannel { ((ServerSocketChannel) getJavaChannel()).socket().bind( new InetSocketAddress(InetAddress.getLocalHost(), port)); ((ServerSocketChannel) getJavaChannel()).configureBlocking(false); - System.out.println("Bound TCP socket at port: " + port); + LOGGER.info("Bound TCP socket at port: {}", port); } /** diff --git a/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/App.java b/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/App.java index fd5d28ed5..90f7d5e59 100644 --- a/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/App.java +++ b/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/App.java @@ -23,6 +23,9 @@ package com.iluwatar.reader.writer.lock; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; @@ -48,6 +51,8 @@ import java.util.stream.IntStream; */ public class App { + private static final Logger LOGGER = LoggerFactory.getLogger(App.class); + /** * Program entry point * @@ -71,7 +76,7 @@ public class App { try { executeService.awaitTermination(5, TimeUnit.SECONDS); } catch (InterruptedException e) { - System.out.println("Error waiting for ExecutorService shutdown"); + LOGGER.error("Error waiting for ExecutorService shutdown"); } } diff --git a/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/Reader.java b/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/Reader.java index 2b837b341..644772bf1 100644 --- a/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/Reader.java +++ b/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/Reader.java @@ -22,6 +22,9 @@ */ package com.iluwatar.reader.writer.lock; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.util.concurrent.locks.Lock; /** @@ -29,6 +32,8 @@ import java.util.concurrent.locks.Lock; */ public class Reader implements Runnable { + private static final Logger LOGGER = LoggerFactory.getLogger(Reader.class); + private Lock readLock; private String name; @@ -55,8 +60,8 @@ public class Reader implements Runnable { * */ public void read() throws InterruptedException { - System.out.println(name + " begin"); + LOGGER.info("{} begin", name); Thread.sleep(250); - System.out.println(name + " finish"); + LOGGER.info("{} finish", name); } } diff --git a/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/Writer.java b/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/Writer.java index fc3c3bb88..ce946f74f 100644 --- a/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/Writer.java +++ b/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/Writer.java @@ -22,6 +22,9 @@ */ package com.iluwatar.reader.writer.lock; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.util.concurrent.locks.Lock; /** @@ -29,6 +32,8 @@ import java.util.concurrent.locks.Lock; */ public class Writer implements Runnable { + private static final Logger LOGGER = LoggerFactory.getLogger(Writer.class); + private Lock writeLock; private String name; @@ -55,8 +60,8 @@ public class Writer implements Runnable { * Simulate the write operation */ public void write() throws InterruptedException { - System.out.println(name + " begin"); + LOGGER.info("{} begin", name); Thread.sleep(250); - System.out.println(name + " finish"); + LOGGER.info("{} finish", name); } } diff --git a/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/ReaderAndWriterTest.java b/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/ReaderAndWriterTest.java index a2496a3c0..7d0ac70bf 100644 --- a/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/ReaderAndWriterTest.java +++ b/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/ReaderAndWriterTest.java @@ -23,21 +23,37 @@ package com.iluwatar.reader.writer.lock; -import static org.mockito.Mockito.inOrder; +import com.iluwatar.reader.writer.lock.utils.InMemoryAppender; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; -import org.junit.Test; -import org.mockito.InOrder; +import static org.junit.Assert.assertTrue; /** * @author hongshuwei@gmail.com */ -public class ReaderAndWriterTest extends StdOutTest { +public class ReaderAndWriterTest { + private InMemoryAppender appender; + @Before + public void setUp() { + appender = new InMemoryAppender(); + } + + @After + public void tearDown() { + appender.stop(); + } + + private static final Logger LOGGER = LoggerFactory.getLogger(ReaderAndWriterTest.class); /** * Verify reader and writer can only get the lock to read and write orderly @@ -60,14 +76,13 @@ public class ReaderAndWriterTest extends StdOutTest { try { executeService.awaitTermination(10, TimeUnit.SECONDS); } catch (InterruptedException e) { - System.out.println("Error waiting for ExecutorService shutdown"); + LOGGER.error("Error waiting for ExecutorService shutdown", e); } - final InOrder inOrder = inOrder(getStdOutMock()); - inOrder.verify(getStdOutMock()).println("Reader 1 begin"); - inOrder.verify(getStdOutMock()).println("Reader 1 finish"); - inOrder.verify(getStdOutMock()).println("Writer 1 begin"); - inOrder.verify(getStdOutMock()).println("Writer 1 finish"); + assertTrue(appender.logContains("Reader 1 begin")); + assertTrue(appender.logContains("Reader 1 finish")); + assertTrue(appender.logContains("Writer 1 begin")); + assertTrue(appender.logContains("Writer 1 finish")); } /** @@ -91,14 +106,13 @@ public class ReaderAndWriterTest extends StdOutTest { try { executeService.awaitTermination(10, TimeUnit.SECONDS); } catch (InterruptedException e) { - System.out.println("Error waiting for ExecutorService shutdown"); + LOGGER.error("Error waiting for ExecutorService shutdown", e); } - final InOrder inOrder = inOrder(getStdOutMock()); - inOrder.verify(getStdOutMock()).println("Writer 1 begin"); - inOrder.verify(getStdOutMock()).println("Writer 1 finish"); - inOrder.verify(getStdOutMock()).println("Reader 1 begin"); - inOrder.verify(getStdOutMock()).println("Reader 1 finish"); + assertTrue(appender.logContains("Writer 1 begin")); + assertTrue(appender.logContains("Writer 1 finish")); + assertTrue(appender.logContains("Reader 1 begin")); + assertTrue(appender.logContains("Reader 1 finish")); } } diff --git a/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/ReaderTest.java b/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/ReaderTest.java index 7d51e977c..9830eda67 100644 --- a/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/ReaderTest.java +++ b/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/ReaderTest.java @@ -22,20 +22,38 @@ */ package com.iluwatar.reader.writer.lock; -import static org.mockito.Mockito.inOrder; -import static org.mockito.Mockito.spy; +import com.iluwatar.reader.writer.lock.utils.InMemoryAppender; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; -import org.junit.Test; -import org.mockito.InOrder; +import static junit.framework.TestCase.assertTrue; +import static org.mockito.Mockito.spy; /** * @author hongshuwei@gmail.com */ -public class ReaderTest extends StdOutTest { +public class ReaderTest { + + private InMemoryAppender appender; + + @Before + public void setUp() { + appender = new InMemoryAppender(Reader.class); + } + + @After + public void tearDown() { + appender.stop(); + } + + private static final Logger LOGGER = LoggerFactory.getLogger(ReaderTest.class); /** * Verify that multiple readers can get the read lock concurrently @@ -57,16 +75,14 @@ public class ReaderTest extends StdOutTest { try { executeService.awaitTermination(10, TimeUnit.SECONDS); } catch (InterruptedException e) { - System.out.println("Error waiting for ExecutorService shutdown"); + LOGGER.error("Error waiting for ExecutorService shutdown", e); } // Read operation will hold the read lock 250 milliseconds, so here we prove that multiple reads // can be performed in the same time. - final InOrder inOrder = inOrder(getStdOutMock()); - inOrder.verify(getStdOutMock()).println("Reader 1 begin"); - inOrder.verify(getStdOutMock()).println("Reader 2 begin"); - inOrder.verify(getStdOutMock()).println("Reader 1 finish"); - inOrder.verify(getStdOutMock()).println("Reader 2 finish"); - + assertTrue(appender.logContains("Reader 1 begin")); + assertTrue(appender.logContains("Reader 2 begin")); + assertTrue(appender.logContains("Reader 1 finish")); + assertTrue(appender.logContains("Reader 2 finish")); } } diff --git a/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/StdOutTest.java b/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/StdOutTest.java deleted file mode 100644 index 7a1af09c0..000000000 --- a/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/StdOutTest.java +++ /dev/null @@ -1,76 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014 Ilkka Seppälä - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -package com.iluwatar.reader.writer.lock; - -import org.junit.After; -import org.junit.Before; - -import java.io.PrintStream; - -import static org.mockito.Mockito.mock; - -/** - * Date: 12/10/15 - 8:37 PM - * - * @author Jeroen Meulemeester - */ -public abstract class StdOutTest { - - /** - * The mocked standard out {@link PrintStream}, required since some actions don't have any - * influence on accessible objects, except for writing to std-out using {@link System#out} - */ - private final PrintStream stdOutMock = mock(PrintStream.class); - - /** - * Keep the original std-out so it can be restored after the test - */ - private final PrintStream stdOutOrig = System.out; - - /** - * Inject the mocked std-out {@link PrintStream} into the {@link System} class before each test - */ - @Before - public void setUp() { - System.setOut(this.stdOutMock); - } - - /** - * Removed the mocked std-out {@link PrintStream} again from the {@link System} class - */ - @After - public void tearDown() { - System.setOut(this.stdOutOrig); - } - - /** - * Get the mocked stdOut {@link PrintStream} - * - * @return The stdOut print stream mock, renewed before each test - */ - final PrintStream getStdOutMock() { - return this.stdOutMock; - } - -} diff --git a/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/WriterTest.java b/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/WriterTest.java index 765c491ff..4bf6d0747 100644 --- a/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/WriterTest.java +++ b/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/WriterTest.java @@ -22,20 +22,38 @@ */ package com.iluwatar.reader.writer.lock; -import static org.mockito.Mockito.inOrder; -import static org.mockito.Mockito.spy; +import com.iluwatar.reader.writer.lock.utils.InMemoryAppender; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; -import org.junit.Test; -import org.mockito.InOrder; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.spy; /** * @author hongshuwei@gmail.com */ -public class WriterTest extends StdOutTest { +public class WriterTest { + + private InMemoryAppender appender; + + @Before + public void setUp() { + appender = new InMemoryAppender(Writer.class); + } + + @After + public void tearDown() { + appender.stop(); + } + + private static final Logger LOGGER = LoggerFactory.getLogger(WriterTest.class); /** * Verify that multiple writers will get the lock in order. @@ -58,15 +76,14 @@ public class WriterTest extends StdOutTest { try { executeService.awaitTermination(10, TimeUnit.SECONDS); } catch (InterruptedException e) { - System.out.println("Error waiting for ExecutorService shutdown"); + LOGGER.error("Error waiting for ExecutorService shutdown", e); } // Write operation will hold the write lock 250 milliseconds, so here we verify that when two // writer execute concurrently, the second writer can only writes only when the first one is // finished. - final InOrder inOrder = inOrder(getStdOutMock()); - inOrder.verify(getStdOutMock()).println("Writer 1 begin"); - inOrder.verify(getStdOutMock()).println("Writer 1 finish"); - inOrder.verify(getStdOutMock()).println("Writer 2 begin"); - inOrder.verify(getStdOutMock()).println("Writer 2 finish"); + assertTrue(appender.logContains("Writer 1 begin")); + assertTrue(appender.logContains("Writer 1 finish")); + assertTrue(appender.logContains("Writer 2 begin")); + assertTrue(appender.logContains("Writer 2 finish")); } } diff --git a/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/utils/InMemoryAppender.java b/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/utils/InMemoryAppender.java new file mode 100644 index 000000000..44fcb084b --- /dev/null +++ b/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/utils/InMemoryAppender.java @@ -0,0 +1,54 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.reader.writer.lock.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; + +public class InMemoryAppender extends AppenderBase { + private List log = new LinkedList<>(); + + public InMemoryAppender(Class clazz) { + ((Logger) LoggerFactory.getLogger(clazz)).addAppender(this); + start(); + } + + public InMemoryAppender() { + ((Logger) LoggerFactory.getLogger("root")).addAppender(this); + start(); + } + + @Override + protected void append(ILoggingEvent eventObject) { + log.add(eventObject); + } + + public boolean logContains(String message) { + return log.stream().anyMatch(event -> event.getFormattedMessage().equals(message)); + } +} diff --git a/repository/src/main/java/com/iluwatar/repository/App.java b/repository/src/main/java/com/iluwatar/repository/App.java index 2807ae7ca..ab61852d2 100644 --- a/repository/src/main/java/com/iluwatar/repository/App.java +++ b/repository/src/main/java/com/iluwatar/repository/App.java @@ -24,6 +24,8 @@ package com.iluwatar.repository; import java.util.List; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.context.support.ClassPathXmlApplicationContext; /** @@ -43,6 +45,8 @@ import org.springframework.context.support.ClassPathXmlApplicationContext; */ public class App { + private static final Logger LOGGER = LoggerFactory.getLogger(App.class); + /** * Program entry point * @@ -67,12 +71,12 @@ public class App { repository.save(terry); // Count Person records - System.out.println("Count Person records: " + repository.count()); + LOGGER.info("Count Person records: {}", repository.count()); // Print all records List persons = (List) repository.findAll(); for (Person person : persons) { - System.out.println(person); + LOGGER.info(person.toString()); } // Update Person @@ -80,24 +84,24 @@ public class App { nasta.setSurname("Spotakova"); repository.save(nasta); - System.out.println("Find by id 2: " + repository.findOne(2L)); + LOGGER.info("Find by id 2: {}", repository.findOne(2L)); // Remove record from Person repository.delete(2L); // count records - System.out.println("Count Person records: " + repository.count()); + LOGGER.info("Count Person records: {}", repository.count()); // find by name Person p = repository.findOne(new PersonSpecifications.NameEqualSpec("John")); - System.out.println("Find by John is " + p); + LOGGER.info("Find by John is {}", p); // find by age persons = repository.findAll(new PersonSpecifications.AgeBetweenSpec(20, 40)); - System.out.println("Find Person with age between 20,40: "); + LOGGER.info("Find Person with age between 20,40: "); for (Person person : persons) { - System.out.println(person); + LOGGER.info(person.toString()); } repository.deleteAll(); diff --git a/repository/src/main/java/com/iluwatar/repository/AppConfig.java b/repository/src/main/java/com/iluwatar/repository/AppConfig.java index 3e7093358..09f6753bb 100644 --- a/repository/src/main/java/com/iluwatar/repository/AppConfig.java +++ b/repository/src/main/java/com/iluwatar/repository/AppConfig.java @@ -30,6 +30,8 @@ import javax.sql.DataSource; import org.apache.commons.dbcp.BasicDataSource; import org.hibernate.jpa.HibernatePersistenceProvider; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; @@ -44,6 +46,8 @@ import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; @EnableJpaRepositories public class AppConfig { + private static final Logger LOGGER = LoggerFactory.getLogger(AppConfig.class); + /** * Creation of H2 db * @@ -117,12 +121,12 @@ public class AppConfig { repository.save(terry); // Count Person records - System.out.println("Count Person records: " + repository.count()); + LOGGER.info("Count Person records: {}", repository.count()); // Print all records List persons = (List) repository.findAll(); for (Person person : persons) { - System.out.println(person); + LOGGER.info(person.toString()); } // Update Person @@ -130,24 +134,24 @@ public class AppConfig { nasta.setSurname("Spotakova"); repository.save(nasta); - System.out.println("Find by id 2: " + repository.findOne(2L)); + LOGGER.info("Find by id 2: {}", repository.findOne(2L)); // Remove record from Person repository.delete(2L); // count records - System.out.println("Count Person records: " + repository.count()); + LOGGER.info("Count Person records: {}", repository.count()); // find by name Person p = repository.findOne(new PersonSpecifications.NameEqualSpec("John")); - System.out.println("Find by John is " + p); + LOGGER.info("Find by John is {}", p); // find by age persons = repository.findAll(new PersonSpecifications.AgeBetweenSpec(20, 40)); - System.out.println("Find Person with age between 20,40: "); + LOGGER.info("Find Person with age between 20,40: "); for (Person person : persons) { - System.out.println(person); + LOGGER.info(person.toString()); } context.close(); diff --git a/repository/src/main/resources/logback.xml b/repository/src/main/resources/logback.xml new file mode 100644 index 000000000..1b8cc5678 --- /dev/null +++ b/repository/src/main/resources/logback.xml @@ -0,0 +1,52 @@ + + + + repository.log + + repository-%d.log + 5 + + + %-5p [%d{ISO8601,UTC}] %c: %m%n + + + + + + %-5p [%d{ISO8601,UTC}] %c: %m%n + + + + + + + + + + + + + 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 413fb0eab..bb722a36d 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 @@ -22,6 +22,9 @@ */ package com.iluwatar.resource.acquisition.is.initialization; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * * Resource Acquisition Is Initialization pattern was developed for exception safe resource @@ -44,17 +47,19 @@ package com.iluwatar.resource.acquisition.is.initialization; */ public class App { + private static final Logger LOGGER = LoggerFactory.getLogger(App.class); + /** * Program entry point */ public static void main(String[] args) throws Exception { try (SlidingDoor slidingDoor = new SlidingDoor()) { - System.out.println("Walking in."); + LOGGER.info("Walking in."); } try (TreasureChest treasureChest = new TreasureChest()) { - System.out.println("Looting contents."); + LOGGER.info("Looting contents."); } } } 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 3a1a35f2d..ac8512d15 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 @@ -22,6 +22,9 @@ */ package com.iluwatar.resource.acquisition.is.initialization; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * * SlidingDoor resource @@ -29,12 +32,14 @@ package com.iluwatar.resource.acquisition.is.initialization; */ public class SlidingDoor implements AutoCloseable { + private static final Logger LOGGER = LoggerFactory.getLogger(SlidingDoor.class); + public SlidingDoor() { - System.out.println("Sliding door opens."); + LOGGER.info("Sliding door opens."); } @Override public void close() throws Exception { - System.out.println("Sliding door closes."); + LOGGER.info("Sliding door closes."); } } 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 e7b7ebab6..f020b5fa3 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 @@ -22,6 +22,9 @@ */ package com.iluwatar.resource.acquisition.is.initialization; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.io.Closeable; import java.io.IOException; @@ -32,12 +35,14 @@ import java.io.IOException; */ public class TreasureChest implements Closeable { + private static final Logger LOGGER = LoggerFactory.getLogger(TreasureChest.class); + public TreasureChest() { - System.out.println("Treasure chest opens."); + LOGGER.info("Treasure chest opens."); } @Override public void close() throws IOException { - System.out.println("Treasure chest closes."); + LOGGER.info("Treasure chest closes."); } } 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 55bdaf19c..638b06ecc 100644 --- a/resource-acquisition-is-initialization/src/test/java/com/iluwatar/resource/acquisition/is/initialization/ClosableTest.java +++ b/resource-acquisition-is-initialization/src/test/java/com/iluwatar/resource/acquisition/is/initialization/ClosableTest.java @@ -22,28 +22,64 @@ */ package com.iluwatar.resource.acquisition.is.initialization; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.AppenderBase; +import org.junit.After; +import org.junit.Before; import org.junit.Test; -import org.mockito.InOrder; +import org.slf4j.LoggerFactory; -import static org.mockito.Mockito.inOrder; +import java.util.LinkedList; +import java.util.List; + +import static org.junit.Assert.assertTrue; /** * Date: 12/28/15 - 9:31 PM * * @author Jeroen Meulemeester */ -public class ClosableTest extends StdOutTest { +public class ClosableTest { + + private InMemoryAppender appender; + + @Before + public void setUp() { + appender = new InMemoryAppender(); + } + + @After + public void tearDown() { + appender.stop(); + } @Test public void testOpenClose() throws Exception { - final InOrder inOrder = inOrder(getStdOutMock()); try (final SlidingDoor door = new SlidingDoor(); final TreasureChest chest = new TreasureChest()) { - inOrder.verify(getStdOutMock()).println("Sliding door opens."); - inOrder.verify(getStdOutMock()).println("Treasure chest opens."); + assertTrue(appender.logContains("Sliding door opens.")); + assertTrue(appender.logContains("Treasure chest opens.")); } - inOrder.verify(getStdOutMock()).println("Treasure chest closes."); - inOrder.verify(getStdOutMock()).println("Sliding door closes."); - inOrder.verifyNoMoreInteractions(); + assertTrue(appender.logContains("Treasure chest closes.")); + assertTrue(appender.logContains("Sliding door closes.")); } -} \ No newline at end of file + public class InMemoryAppender extends AppenderBase { + private List log = new LinkedList<>(); + + public InMemoryAppender() { + ((Logger) LoggerFactory.getLogger("root")).addAppender(this); + start(); + } + + @Override + protected void append(ILoggingEvent eventObject) { + log.add(eventObject); + } + + public boolean logContains(String message) { + return log.stream().anyMatch(event -> event.getMessage().equals(message)); + } + } + +} diff --git a/resource-acquisition-is-initialization/src/test/java/com/iluwatar/resource/acquisition/is/initialization/StdOutTest.java b/resource-acquisition-is-initialization/src/test/java/com/iluwatar/resource/acquisition/is/initialization/StdOutTest.java deleted file mode 100644 index 42cb42e6b..000000000 --- a/resource-acquisition-is-initialization/src/test/java/com/iluwatar/resource/acquisition/is/initialization/StdOutTest.java +++ /dev/null @@ -1,75 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014 Ilkka Seppälä - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package com.iluwatar.resource.acquisition.is.initialization; - -import org.junit.After; -import org.junit.Before; - -import java.io.PrintStream; - -import static org.mockito.Mockito.mock; - -/** - * Date: 12/10/15 - 8:37 PM - * - * @author Jeroen Meulemeester - */ -public abstract class StdOutTest { - - /** - * The mocked standard out {@link PrintStream}, required since some actions don't have any - * influence on accessible objects, except for writing to std-out using {@link System#out} - */ - private final PrintStream stdOutMock = mock(PrintStream.class); - - /** - * Keep the original std-out so it can be restored after the test - */ - private final PrintStream stdOutOrig = System.out; - - /** - * Inject the mocked std-out {@link PrintStream} into the {@link System} class before each test - */ - @Before - public void setUp() { - System.setOut(this.stdOutMock); - } - - /** - * Removed the mocked std-out {@link PrintStream} again from the {@link System} class - */ - @After - public void tearDown() { - System.setOut(this.stdOutOrig); - } - - /** - * Get the mocked stdOut {@link PrintStream} - * - * @return The stdOut print stream mock, renewed before each test - */ - final PrintStream getStdOutMock() { - return this.stdOutMock; - } - -} diff --git a/semaphore/src/main/java/com/iluwatar/semaphore/Customer.java b/semaphore/src/main/java/com/iluwatar/semaphore/Customer.java index 0a4713438..e0546edbe 100644 --- a/semaphore/src/main/java/com/iluwatar/semaphore/Customer.java +++ b/semaphore/src/main/java/com/iluwatar/semaphore/Customer.java @@ -22,12 +22,17 @@ */ package com.iluwatar.semaphore; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * A Customer attempts to repeatedly take Fruit from the FruitShop by * taking Fruit from FruitBowl instances. */ public class Customer extends Thread { + private static final Logger LOGGER = LoggerFactory.getLogger(Customer.class); + /** * Name of the Customer. */ @@ -63,13 +68,13 @@ public class Customer extends Thread { Fruit fruit; if (bowl != null && (fruit = bowl.take()) != null) { - System.out.println(name + " took an " + fruit); + LOGGER.info("{} took an {}", name, fruit); fruitBowl.put(fruit); fruitShop.returnBowl(bowl); } } - - System.out.println(name + " took " + fruitBowl); + + LOGGER.info("{} took {}", name, fruitBowl); } diff --git a/servant/src/main/java/com/iluwatar/servant/App.java b/servant/src/main/java/com/iluwatar/servant/App.java index 92829441d..aeb379846 100644 --- a/servant/src/main/java/com/iluwatar/servant/App.java +++ b/servant/src/main/java/com/iluwatar/servant/App.java @@ -22,6 +22,9 @@ */ package com.iluwatar.servant; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.util.ArrayList; @@ -35,6 +38,8 @@ import java.util.ArrayList; */ public class App { + private static final Logger LOGGER = LoggerFactory.getLogger(App.class); + static Servant jenkins = new Servant("Jenkins"); static Servant travis = new Servant("Travis"); @@ -73,9 +78,9 @@ public class App { // check your luck if (servant.checkIfYouWillBeHanged(guests)) { - System.out.println(servant.name + " will live another day"); + LOGGER.info("{} will live another day", servant.name); } else { - System.out.println("Poor " + servant.name + ". His days are numbered"); + LOGGER.info("Poor {}. His days are numbered", servant.name); } } } 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 8282d800c..bf15c5885 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 @@ -35,6 +35,8 @@ import com.iluwatar.servicelayer.spellbook.SpellbookDaoImpl; import com.iluwatar.servicelayer.wizard.Wizard; import com.iluwatar.servicelayer.wizard.WizardDao; import com.iluwatar.servicelayer.wizard.WizardDaoImpl; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** @@ -57,6 +59,8 @@ import com.iluwatar.servicelayer.wizard.WizardDaoImpl; */ public class App { + private static final Logger LOGGER = LoggerFactory.getLogger(App.class); + /** * Program entry point * @@ -180,27 +184,27 @@ public class App { public static void queryData() { MagicService service = new MagicServiceImpl(new WizardDaoImpl(), new SpellbookDaoImpl(), new SpellDaoImpl()); - System.out.println("Enumerating all wizards"); + LOGGER.info("Enumerating all wizards"); for (Wizard w : service.findAllWizards()) { - System.out.println(w.getName()); + LOGGER.info(w.getName()); } - System.out.println("Enumerating all spellbooks"); + LOGGER.info("Enumerating all spellbooks"); for (Spellbook s : service.findAllSpellbooks()) { - System.out.println(s.getName()); + LOGGER.info(s.getName()); } - System.out.println("Enumerating all spells"); + LOGGER.info("Enumerating all spells"); for (Spell s : service.findAllSpells()) { - System.out.println(s.getName()); + LOGGER.info(s.getName()); } - System.out.println("Find wizards with spellbook 'Book of Idores'"); + LOGGER.info("Find wizards with spellbook 'Book of Idores'"); List wizardsWithSpellbook = service.findWizardsWithSpellbook("Book of Idores"); for (Wizard w : wizardsWithSpellbook) { - System.out.println(String.format("%s has 'Book of Idores'", w.getName())); + LOGGER.info("{} has 'Book of Idores'", w.getName()); } - System.out.println("Find wizards with spell 'Fireball'"); + LOGGER.info("Find wizards with spell 'Fireball'"); List wizardsWithSpell = service.findWizardsWithSpell("Fireball"); for (Wizard w : wizardsWithSpell) { - System.out.println(String.format("%s has 'Fireball'", w.getName())); + LOGGER.info("{} has 'Fireball'", w.getName()); } } } 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 b30b97b65..9fc3047b5 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 @@ -28,12 +28,16 @@ import com.iluwatar.servicelayer.wizard.Wizard; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * Produces the Hibernate {@link SessionFactory}. */ public final class HibernateUtil { + private static final Logger LOGGER = LoggerFactory.getLogger(HibernateUtil.class); + /** * The cached session factory */ @@ -56,10 +60,10 @@ public final class HibernateUtil { .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", "true") + .setProperty("hibernate.show_sql", "false") .setProperty("hibernate.hbm2ddl.auto", "create-drop").buildSessionFactory(); } catch (Throwable ex) { - System.err.println("Initial SessionFactory creation failed." + ex); + LOGGER.error("Initial SessionFactory creation failed.", ex); throw new ExceptionInInitializerError(ex); } } diff --git a/service-layer/src/main/resources/logback.xml b/service-layer/src/main/resources/logback.xml new file mode 100644 index 000000000..e02933e70 --- /dev/null +++ b/service-layer/src/main/resources/logback.xml @@ -0,0 +1,57 @@ + + + + service-layer.log + + service-layer-%d.log + 5 + + + %-5p [%d{ISO8601,UTC}] %c: %m%n + + + + + + %-5p [%d{ISO8601,UTC}] %c: %m%n + + + + + + + + + + + + + + + + + + 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 8063fc818..134eb6d89 100644 --- a/service-locator/src/main/java/com/iluwatar/servicelocator/InitContext.java +++ b/service-locator/src/main/java/com/iluwatar/servicelocator/InitContext.java @@ -22,6 +22,9 @@ */ package com.iluwatar.servicelocator; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * 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 @@ -30,6 +33,8 @@ package com.iluwatar.servicelocator; */ public class InitContext { + private static final Logger LOGGER = LoggerFactory.getLogger(InitContext.class); + /** * Perform the lookup based on the service name. The returned object will need to be casted into a * {@link Service} @@ -39,10 +44,10 @@ public class InitContext { */ public Object lookup(String serviceName) { if (serviceName.equals("jndi/serviceA")) { - System.out.println("Looking up service A and creating new service for A"); + LOGGER.info("Looking up service A and creating new service for A"); return new ServiceImpl("jndi/serviceA"); } else if (serviceName.equals("jndi/serviceB")) { - System.out.println("Looking up service B and creating new service for B"); + LOGGER.info("Looking up service B and creating new service for B"); return new ServiceImpl("jndi/serviceB"); } else { return null; 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 7e2169fcb..89b2a6638 100644 --- a/service-locator/src/main/java/com/iluwatar/servicelocator/ServiceCache.java +++ b/service-locator/src/main/java/com/iluwatar/servicelocator/ServiceCache.java @@ -22,6 +22,9 @@ */ package com.iluwatar.servicelocator; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.util.HashMap; import java.util.Map; @@ -35,6 +38,8 @@ import java.util.Map; */ public class ServiceCache { + private static final Logger LOGGER = LoggerFactory.getLogger(ServiceCache.class); + private final Map serviceCache; public ServiceCache() { @@ -52,8 +57,8 @@ public class ServiceCache { for (String serviceJndiName : serviceCache.keySet()) { if (serviceJndiName.equals(serviceName)) { cachedService = serviceCache.get(serviceJndiName); - System.out.println("(cache call) Fetched service " + cachedService.getName() + "(" - + cachedService.getId() + ") from cache... !"); + LOGGER.info("(cache call) Fetched service {}({}) from cache... !", + cachedService.getName(), cachedService.getId()); } } return cachedService; 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 543fb8480..328926ce2 100644 --- a/service-locator/src/main/java/com/iluwatar/servicelocator/ServiceImpl.java +++ b/service-locator/src/main/java/com/iluwatar/servicelocator/ServiceImpl.java @@ -22,6 +22,9 @@ */ package com.iluwatar.servicelocator; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * 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 @@ -31,6 +34,8 @@ package com.iluwatar.servicelocator; */ public class ServiceImpl implements Service { + private static final Logger LOGGER = LoggerFactory.getLogger(ServiceImpl.class); + private final String serviceName; private final int id; @@ -57,6 +62,6 @@ public class ServiceImpl implements Service { @Override public void execute() { - System.out.println("Service " + getName() + " is now executing with id " + getId()); + LOGGER.info("Service {} is now executing with id {}", getName(), getId()); } } diff --git a/singleton/src/main/java/com/iluwatar/singleton/App.java b/singleton/src/main/java/com/iluwatar/singleton/App.java index 4b505085a..31dcd1803 100644 --- a/singleton/src/main/java/com/iluwatar/singleton/App.java +++ b/singleton/src/main/java/com/iluwatar/singleton/App.java @@ -22,6 +22,9 @@ */ package com.iluwatar.singleton; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * Singleton pattern ensures that the class can have only one existing instance per Java classloader * instance and provides global access to it. @@ -60,6 +63,8 @@ package com.iluwatar.singleton; */ public class App { + private static final Logger LOGGER = LoggerFactory.getLogger(App.class); + /** * Program entry point. * @@ -70,35 +75,35 @@ public class App { // eagerly initialized singleton IvoryTower ivoryTower1 = IvoryTower.getInstance(); IvoryTower ivoryTower2 = IvoryTower.getInstance(); - System.out.println("ivoryTower1=" + ivoryTower1); - System.out.println("ivoryTower2=" + ivoryTower2); + LOGGER.info("ivoryTower1={}", ivoryTower1); + LOGGER.info("ivoryTower2={}", ivoryTower2); // lazily initialized singleton ThreadSafeLazyLoadedIvoryTower threadSafeIvoryTower1 = ThreadSafeLazyLoadedIvoryTower.getInstance(); ThreadSafeLazyLoadedIvoryTower threadSafeIvoryTower2 = ThreadSafeLazyLoadedIvoryTower.getInstance(); - System.out.println("threadSafeIvoryTower1=" + threadSafeIvoryTower1); - System.out.println("threadSafeIvoryTower2=" + threadSafeIvoryTower2); + LOGGER.info("threadSafeIvoryTower1={}", threadSafeIvoryTower1); + LOGGER.info("threadSafeIvoryTower2={}", threadSafeIvoryTower2); // enum singleton EnumIvoryTower enumIvoryTower1 = EnumIvoryTower.INSTANCE; EnumIvoryTower enumIvoryTower2 = EnumIvoryTower.INSTANCE; - System.out.println("enumIvoryTower1=" + enumIvoryTower1); - System.out.println("enumIvoryTower2=" + enumIvoryTower2); + LOGGER.info("enumIvoryTower1={}", enumIvoryTower1); + LOGGER.info("enumIvoryTower2={}", enumIvoryTower2); // double checked locking ThreadSafeDoubleCheckLocking dcl1 = ThreadSafeDoubleCheckLocking.getInstance(); - System.out.println(dcl1); + LOGGER.info(dcl1.toString()); ThreadSafeDoubleCheckLocking dcl2 = ThreadSafeDoubleCheckLocking.getInstance(); - System.out.println(dcl2); + LOGGER.info(dcl2.toString()); // initialize on demand holder idiom InitializingOnDemandHolderIdiom demandHolderIdiom = InitializingOnDemandHolderIdiom.getInstance(); - System.out.println(demandHolderIdiom); + LOGGER.info(demandHolderIdiom.toString()); InitializingOnDemandHolderIdiom demandHolderIdiom2 = InitializingOnDemandHolderIdiom.getInstance(); - System.out.println(demandHolderIdiom2); + LOGGER.info(demandHolderIdiom2.toString()); } } 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 7cbd38470..7e85d2713 100644 --- a/specification/src/main/java/com/iluwatar/specification/app/App.java +++ b/specification/src/main/java/com/iluwatar/specification/app/App.java @@ -37,6 +37,8 @@ import com.iluwatar.specification.property.Color; import com.iluwatar.specification.property.Movement; import com.iluwatar.specification.selector.ColorSelector; import com.iluwatar.specification.selector.MovementSelector; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * @@ -52,6 +54,8 @@ import com.iluwatar.specification.selector.MovementSelector; * */ public class App { + + private static final Logger LOGGER = LoggerFactory.getLogger(App.class); /** * Program entry point @@ -62,22 +66,22 @@ public class App { Arrays.asList(new Goblin(), new Octopus(), new Dragon(), new Shark(), new Troll(), new KillerBee()); // find all walking creatures - System.out.println("Find all walking creatures"); + LOGGER.info("Find all walking creatures"); List walkingCreatures = creatures.stream().filter(new MovementSelector(Movement.WALKING)) .collect(Collectors.toList()); - walkingCreatures.stream().forEach(System.out::println); + walkingCreatures.stream().forEach(c -> LOGGER.info(c.toString())); // find all dark creatures - System.out.println("Find all dark creatures"); + LOGGER.info("Find all dark creatures"); List darkCreatures = creatures.stream().filter(new ColorSelector(Color.DARK)).collect(Collectors.toList()); - darkCreatures.stream().forEach(System.out::println); + darkCreatures.stream().forEach(c -> LOGGER.info(c.toString())); // find all red and flying creatures - System.out.println("Find all red and flying creatures"); + LOGGER.info("Find all red and flying creatures"); List redAndFlyingCreatures = creatures.stream() .filter(new ColorSelector(Color.RED).and(new MovementSelector(Movement.FLYING))) .collect(Collectors.toList()); - redAndFlyingCreatures.stream().forEach(System.out::println); + redAndFlyingCreatures.stream().forEach(c -> LOGGER.info(c.toString())); } } diff --git a/state/src/main/java/com/iluwatar/state/AngryState.java b/state/src/main/java/com/iluwatar/state/AngryState.java index c58f85ae1..3ebbed142 100644 --- a/state/src/main/java/com/iluwatar/state/AngryState.java +++ b/state/src/main/java/com/iluwatar/state/AngryState.java @@ -22,6 +22,9 @@ */ package com.iluwatar.state; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * * Angry state. @@ -29,6 +32,8 @@ package com.iluwatar.state; */ public class AngryState implements State { + private static final Logger LOGGER = LoggerFactory.getLogger(AngryState.class); + private Mammoth mammoth; public AngryState(Mammoth mammoth) { @@ -37,12 +42,12 @@ public class AngryState implements State { @Override public void observe() { - System.out.println(String.format("%s is furious!", mammoth)); + LOGGER.info("{} is furious!", mammoth); } @Override public void onEnterState() { - System.out.println(String.format("%s gets angry!", mammoth)); + LOGGER.info("{} gets angry!", mammoth); } } diff --git a/state/src/main/java/com/iluwatar/state/PeacefulState.java b/state/src/main/java/com/iluwatar/state/PeacefulState.java index 23f4e893c..870298632 100644 --- a/state/src/main/java/com/iluwatar/state/PeacefulState.java +++ b/state/src/main/java/com/iluwatar/state/PeacefulState.java @@ -22,6 +22,9 @@ */ package com.iluwatar.state; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * * Peaceful state. @@ -29,6 +32,8 @@ package com.iluwatar.state; */ public class PeacefulState implements State { + private static final Logger LOGGER = LoggerFactory.getLogger(PeacefulState.class); + private Mammoth mammoth; public PeacefulState(Mammoth mammoth) { @@ -37,12 +42,12 @@ public class PeacefulState implements State { @Override public void observe() { - System.out.println(String.format("%s is calm and peaceful.", mammoth)); + LOGGER.info("{} is calm and peaceful.", mammoth); } @Override public void onEnterState() { - System.out.println(String.format("%s calms down.", mammoth)); + LOGGER.info("{} calms down.", mammoth); } } diff --git a/state/src/test/java/com/iluwatar/state/MammothTest.java b/state/src/test/java/com/iluwatar/state/MammothTest.java index 4fe37bfd1..be4c0d892 100644 --- a/state/src/test/java/com/iluwatar/state/MammothTest.java +++ b/state/src/test/java/com/iluwatar/state/MammothTest.java @@ -22,17 +22,19 @@ */ package com.iluwatar.state; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.AppenderBase; import org.junit.After; import org.junit.Before; import org.junit.Test; -import org.mockito.InOrder; -import org.mockito.Mockito; +import org.slf4j.LoggerFactory; -import java.io.PrintStream; +import java.util.LinkedList; +import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; -import static org.mockito.Mockito.mock; /** * Date: 12/29/15 - 8:27 PM @@ -41,31 +43,16 @@ import static org.mockito.Mockito.mock; */ public class MammothTest { - /** - * The mocked standard out {@link PrintStream}, required since some actions don't have any - * influence on accessible objects, except for writing to std-out using {@link System#out} - */ - private final PrintStream stdOutMock = mock(PrintStream.class); + private InMemoryAppender appender; - /** - * Keep the original std-out so it can be restored after the test - */ - private final PrintStream stdOutOrig = System.out; - - /** - * Inject the mocked std-out {@link PrintStream} into the {@link System} class before each test - */ @Before public void setUp() { - System.setOut(this.stdOutMock); + appender = new InMemoryAppender(); } - /** - * Removed the mocked std-out {@link PrintStream} again from the {@link System} class - */ @After public void tearDown() { - System.setOut(this.stdOutOrig); + appender.stop(); } /** @@ -74,28 +61,27 @@ public class MammothTest { */ @Test public void testTimePasses() { - final InOrder inOrder = Mockito.inOrder(this.stdOutMock); final Mammoth mammoth = new Mammoth(); mammoth.observe(); - inOrder.verify(this.stdOutMock).println("The mammoth is calm and peaceful."); - inOrder.verifyNoMoreInteractions(); + assertEquals("The mammoth is calm and peaceful.", appender.getLastMessage()); + assertEquals(1 , appender.getLogSize()); mammoth.timePasses(); - inOrder.verify(this.stdOutMock).println("The mammoth gets angry!"); - inOrder.verifyNoMoreInteractions(); + assertEquals("The mammoth gets angry!", appender.getLastMessage()); + assertEquals(2 , appender.getLogSize()); mammoth.observe(); - inOrder.verify(this.stdOutMock).println("The mammoth is furious!"); - inOrder.verifyNoMoreInteractions(); + assertEquals("The mammoth is furious!", appender.getLastMessage()); + assertEquals(3 , appender.getLogSize()); mammoth.timePasses(); - inOrder.verify(this.stdOutMock).println("The mammoth calms down."); - inOrder.verifyNoMoreInteractions(); + assertEquals("The mammoth calms down.", appender.getLastMessage()); + assertEquals(4 , appender.getLogSize()); mammoth.observe(); - inOrder.verify(this.stdOutMock).println("The mammoth is calm and peaceful."); - inOrder.verifyNoMoreInteractions(); + assertEquals("The mammoth is calm and peaceful.", appender.getLastMessage()); + assertEquals(5 , appender.getLogSize()); } @@ -109,4 +95,26 @@ public class MammothTest { assertEquals("The mammoth", toString); } -} \ No newline at end of file + private class InMemoryAppender extends AppenderBase { + private List log = new LinkedList<>(); + + public InMemoryAppender() { + ((Logger) LoggerFactory.getLogger("root")).addAppender(this); + start(); + } + + @Override + protected void append(ILoggingEvent eventObject) { + log.add(eventObject); + } + + public int getLogSize() { + return log.size(); + } + + public String getLastMessage() { + return log.get(log.size() - 1).getFormattedMessage(); + } + } + +} 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 aeb759ba8..fe5c5a8cd 100644 --- a/step-builder/src/main/java/com/iluwatar/stepbuilder/App.java +++ b/step-builder/src/main/java/com/iluwatar/stepbuilder/App.java @@ -22,6 +22,9 @@ */ package com.iluwatar.stepbuilder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * Step Builder Pattern * @@ -56,6 +59,8 @@ package com.iluwatar.stepbuilder; */ public class App { + private static final Logger LOGGER = LoggerFactory.getLogger(App.class); + /** * Program entry point * @@ -67,18 +72,18 @@ public class App { CharacterStepBuilder.newBuilder().name("Amberjill").fighterClass("Paladin") .withWeapon("Sword").noAbilities().build(); - System.out.println(warrior); + LOGGER.info(warrior.toString()); Character mage = CharacterStepBuilder.newBuilder().name("Riobard").wizardClass("Sorcerer") .withSpell("Fireball").withAbility("Fire Aura").withAbility("Teleport") .noMoreAbilities().build(); - System.out.println(mage); + LOGGER.info(mage.toString()); Character thief = CharacterStepBuilder.newBuilder().name("Desmond").fighterClass("Rogue").noWeapon().build(); - System.out.println(thief); + LOGGER.info(thief.toString()); } } diff --git a/strategy/src/main/java/com/iluwatar/strategy/App.java b/strategy/src/main/java/com/iluwatar/strategy/App.java index be8826fe3..28485701c 100644 --- a/strategy/src/main/java/com/iluwatar/strategy/App.java +++ b/strategy/src/main/java/com/iluwatar/strategy/App.java @@ -22,6 +22,9 @@ */ package com.iluwatar.strategy; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * * The Strategy pattern (also known as the policy pattern) is a software design pattern that enables @@ -37,6 +40,8 @@ package com.iluwatar.strategy; */ public class App { + private static final Logger LOGGER = LoggerFactory.getLogger(App.class); + /** * Program entry point * @@ -44,27 +49,27 @@ public class App { */ public static void main(String[] args) { // GoF Strategy pattern - System.out.println("Green dragon spotted ahead!"); + LOGGER.info("Green dragon spotted ahead!"); DragonSlayer dragonSlayer = new DragonSlayer(new MeleeStrategy()); dragonSlayer.goToBattle(); - System.out.println("Red dragon emerges."); + LOGGER.info("Red dragon emerges."); dragonSlayer.changeStrategy(new ProjectileStrategy()); dragonSlayer.goToBattle(); - System.out.println("Black dragon lands before you."); + LOGGER.info("Black dragon lands before you."); dragonSlayer.changeStrategy(new SpellStrategy()); dragonSlayer.goToBattle(); // Java 8 Strategy pattern - System.out.println("Green dragon spotted ahead!"); + LOGGER.info("Green dragon spotted ahead!"); dragonSlayer = new DragonSlayer( - () -> System.out.println("With your Excalibur you severe the dragon's head!")); + () -> LOGGER.info("With your Excalibur you severe the dragon's head!")); dragonSlayer.goToBattle(); - System.out.println("Red dragon emerges."); - dragonSlayer.changeStrategy(() -> System.out.println( + 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.goToBattle(); - System.out.println("Black dragon lands before you."); - dragonSlayer.changeStrategy(() -> System.out.println( + LOGGER.info("Black dragon lands before you."); + dragonSlayer.changeStrategy(() -> LOGGER.info( "You cast the spell of disintegration and the dragon vaporizes in a pile of dust!")); dragonSlayer.goToBattle(); } diff --git a/strategy/src/main/java/com/iluwatar/strategy/MeleeStrategy.java b/strategy/src/main/java/com/iluwatar/strategy/MeleeStrategy.java index d17ff9041..d67f8b559 100644 --- a/strategy/src/main/java/com/iluwatar/strategy/MeleeStrategy.java +++ b/strategy/src/main/java/com/iluwatar/strategy/MeleeStrategy.java @@ -22,6 +22,9 @@ */ package com.iluwatar.strategy; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * * Melee strategy. @@ -29,8 +32,10 @@ package com.iluwatar.strategy; */ public class MeleeStrategy implements DragonSlayingStrategy { + private static final Logger LOGGER = LoggerFactory.getLogger(MeleeStrategy.class); + @Override public void execute() { - System.out.println("With your Excalibur you sever the dragon's head!"); + 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 7cd731167..ea88fdc8b 100644 --- a/strategy/src/main/java/com/iluwatar/strategy/ProjectileStrategy.java +++ b/strategy/src/main/java/com/iluwatar/strategy/ProjectileStrategy.java @@ -22,6 +22,9 @@ */ package com.iluwatar.strategy; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * * Projectile strategy. @@ -29,9 +32,10 @@ package com.iluwatar.strategy; */ public class ProjectileStrategy implements DragonSlayingStrategy { + private static final Logger LOGGER = LoggerFactory.getLogger(ProjectileStrategy.class); + @Override public void execute() { - System.out - .println("You shoot the dragon with the magical crossbow and it falls dead on the ground!"); + 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 6309ed31b..3264799bf 100644 --- a/strategy/src/main/java/com/iluwatar/strategy/SpellStrategy.java +++ b/strategy/src/main/java/com/iluwatar/strategy/SpellStrategy.java @@ -22,6 +22,9 @@ */ package com.iluwatar.strategy; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * * Spell strategy. @@ -29,10 +32,11 @@ package com.iluwatar.strategy; */ public class SpellStrategy implements DragonSlayingStrategy { + private static final Logger LOGGER = LoggerFactory.getLogger(SpellStrategy.class); + @Override public void execute() { - System.out - .println("You cast the spell of disintegration and the dragon vaporizes in a pile of dust!"); + 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/DragonSlayingStrategyTest.java b/strategy/src/test/java/com/iluwatar/strategy/DragonSlayingStrategyTest.java index 35f4c1a82..d04e0f5c1 100644 --- a/strategy/src/test/java/com/iluwatar/strategy/DragonSlayingStrategyTest.java +++ b/strategy/src/test/java/com/iluwatar/strategy/DragonSlayingStrategyTest.java @@ -22,19 +22,22 @@ */ package com.iluwatar.strategy; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.AppenderBase; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; +import org.slf4j.LoggerFactory; -import java.io.PrintStream; import java.util.Arrays; import java.util.Collection; +import java.util.LinkedList; +import java.util.List; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.junit.Assert.assertEquals; /** * Date: 12/29/15 - 10:58 PM @@ -71,20 +74,22 @@ public class DragonSlayingStrategyTest { private final DragonSlayingStrategy strategy; /** - * The expected action on the std-out + * The expected action in the log */ private final String expectedResult; - /** - * The mocked standard out {@link PrintStream}, required since some actions don't have any - * influence on accessible objects, except for writing to std-out using {@link System#out} - */ - private final PrintStream stdOutMock = mock(PrintStream.class); + private InMemoryAppender appender; + + @Before + public void setUp() { + appender = new InMemoryAppender(); + } + + @After + public void tearDown() { + appender.stop(); + } - /** - * Keep the original std-out so it can be restored after the test - */ - private final PrintStream stdOutOrig = System.out; /** * Create a new test instance for the given strategy @@ -97,30 +102,35 @@ public class DragonSlayingStrategyTest { this.expectedResult = expectedResult; } - /** - * Inject the mocked std-out {@link PrintStream} into the {@link System} class before each test - */ - @Before - public void setUp() { - System.setOut(this.stdOutMock); - } - - /** - * Removed the mocked std-out {@link PrintStream} again from the {@link System} class - */ - @After - public void tearDown() { - System.setOut(this.stdOutOrig); - } - /** * Test if executing the strategy gives the correct response */ @Test public void testExecute() { this.strategy.execute(); - verify(this.stdOutMock).println(this.expectedResult); - verifyNoMoreInteractions(this.stdOutMock); + assertEquals(this.expectedResult, appender.getLastMessage()); + assertEquals(1, appender.getLogSize()); } -} \ No newline at end of file + private class InMemoryAppender extends AppenderBase { + private List log = new LinkedList<>(); + + public InMemoryAppender() { + ((Logger) LoggerFactory.getLogger("root")).addAppender(this); + start(); + } + + @Override + protected void append(ILoggingEvent eventObject) { + log.add(eventObject); + } + + public int getLogSize() { + return log.size(); + } + + public String getLastMessage() { + return log.get(log.size() - 1).getFormattedMessage(); + } + } +} 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 7a78576a1..49cbbd7dc 100644 --- a/template-method/src/main/java/com/iluwatar/templatemethod/HitAndRunMethod.java +++ b/template-method/src/main/java/com/iluwatar/templatemethod/HitAndRunMethod.java @@ -22,6 +22,9 @@ */ package com.iluwatar.templatemethod; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * * HitAndRunMethod implementation of {@link StealingMethod}. @@ -29,6 +32,8 @@ package com.iluwatar.templatemethod; */ public class HitAndRunMethod extends StealingMethod { + private static final Logger LOGGER = LoggerFactory.getLogger(HitAndRunMethod.class); + @Override protected String pickTarget() { return "old goblin woman"; @@ -36,11 +41,11 @@ public class HitAndRunMethod extends StealingMethod { @Override protected void confuseTarget(String target) { - System.out.println("Approach the " + target + " from behind."); + LOGGER.info("Approach the {} from behind.", target); } @Override protected void stealTheItem(String target) { - System.out.println("Grab the handbag and run away fast!"); + LOGGER.info("Grab the handbag and run away fast!"); } } 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 c8c584cdd..85896d922 100644 --- a/template-method/src/main/java/com/iluwatar/templatemethod/StealingMethod.java +++ b/template-method/src/main/java/com/iluwatar/templatemethod/StealingMethod.java @@ -22,6 +22,9 @@ */ package com.iluwatar.templatemethod; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * * StealingMethod defines skeleton for the algorithm. @@ -29,6 +32,8 @@ package com.iluwatar.templatemethod; */ public abstract class StealingMethod { + private static final Logger LOGGER = LoggerFactory.getLogger(StealingMethod.class); + protected abstract String pickTarget(); protected abstract void confuseTarget(String target); @@ -40,7 +45,7 @@ public abstract class StealingMethod { */ public void steal() { String target = pickTarget(); - System.out.println("The target has been chosen as " + target + "."); + 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 4fdb5d758..c7855fe4e 100644 --- a/template-method/src/main/java/com/iluwatar/templatemethod/SubtleMethod.java +++ b/template-method/src/main/java/com/iluwatar/templatemethod/SubtleMethod.java @@ -22,6 +22,9 @@ */ package com.iluwatar.templatemethod; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * * SubtleMethod implementation of {@link StealingMethod}. @@ -29,6 +32,8 @@ package com.iluwatar.templatemethod; */ public class SubtleMethod extends StealingMethod { + private static final Logger LOGGER = LoggerFactory.getLogger(SubtleMethod.class); + @Override protected String pickTarget() { return "shop keeper"; @@ -36,11 +41,11 @@ public class SubtleMethod extends StealingMethod { @Override protected void confuseTarget(String target) { - System.out.println("Approach the " + target + " with tears running and hug him!"); + LOGGER.info("Approach the {} with tears running and hug him!", target); } @Override protected void stealTheItem(String target) { - System.out.println("While in close contact grab the " + target + "'s wallet."); + LOGGER.info("While in close contact grab the {}'s wallet.", target); } } 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 e0cb90d42..0ea337f93 100644 --- a/template-method/src/test/java/com/iluwatar/templatemethod/StealingMethodTest.java +++ b/template-method/src/test/java/com/iluwatar/templatemethod/StealingMethodTest.java @@ -22,19 +22,19 @@ */ package com.iluwatar.templatemethod; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.AppenderBase; import org.junit.After; import org.junit.Before; import org.junit.Test; -import org.mockito.InOrder; +import org.slf4j.LoggerFactory; -import java.io.PrintStream; +import java.util.LinkedList; +import java.util.List; import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.inOrder; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; -import static org.mockito.Mockito.verifyZeroInteractions; +import static org.junit.Assert.assertTrue; /** * Date: 12/30/15 - 18:12 PM @@ -43,6 +43,18 @@ import static org.mockito.Mockito.verifyZeroInteractions; */ public abstract class StealingMethodTest { + private InMemoryAppender appender; + + @Before + public void setUp() { + appender = new InMemoryAppender(); + } + + @After + public void tearDown() { + appender.stop(); + } + /** * The tested stealing method */ @@ -68,17 +80,6 @@ public abstract class StealingMethodTest { */ private final String expectedStealMethod; - /** - * The mocked standard out {@link PrintStream}, required since some actions don't have any - * influence on accessible objects, except for writing to std-out using {@link System#out} - */ - private final PrintStream stdOutMock = mock(PrintStream.class); - - /** - * Keep the original std-out so it can be restored after the test - */ - private final PrintStream stdOutOrig = System.out; - /** * Create a new test for the given stealing method, together with the expected results * @@ -98,22 +99,6 @@ public abstract class StealingMethodTest { this.expectedStealMethod = expectedStealMethod; } - /** - * Inject the mocked std-out {@link PrintStream} into the {@link System} class before each test - */ - @Before - public void setUp() { - System.setOut(this.stdOutMock); - } - - /** - * Removed the mocked std-out {@link PrintStream} again from the {@link System} class - */ - @After - public void tearDown() { - System.setOut(this.stdOutOrig); - } - /** * Verify if the thief picks the correct target */ @@ -127,11 +112,11 @@ public abstract class StealingMethodTest { */ @Test public void testConfuseTarget() { - verifyZeroInteractions(this.stdOutMock); + assertEquals(0, appender.getLogSize()); this.method.confuseTarget(this.expectedTarget); - verify(this.stdOutMock).println(this.expectedConfuseMethod); - verifyNoMoreInteractions(this.stdOutMock); + assertEquals(this.expectedConfuseMethod, appender.getLastMessage()); + assertEquals(1, appender.getLogSize()); } /** @@ -139,11 +124,11 @@ public abstract class StealingMethodTest { */ @Test public void testStealTheItem() { - verifyZeroInteractions(this.stdOutMock); + assertEquals(0, appender.getLogSize()); this.method.stealTheItem(this.expectedTarget); - verify(this.stdOutMock).println(this.expectedStealMethod); - verifyNoMoreInteractions(this.stdOutMock); + assertEquals(this.expectedStealMethod, appender.getLastMessage()); + assertEquals(1, appender.getLogSize()); } /** @@ -151,14 +136,37 @@ public abstract class StealingMethodTest { */ @Test public void testSteal() { - final InOrder inOrder = inOrder(this.stdOutMock); - this.method.steal(); - inOrder.verify(this.stdOutMock).println(this.expectedTargetResult); - inOrder.verify(this.stdOutMock).println(this.expectedConfuseMethod); - inOrder.verify(this.stdOutMock).println(this.expectedStealMethod); - inOrder.verifyNoMoreInteractions(); + assertTrue(appender.logContains(this.expectedTargetResult)); + assertTrue(appender.logContains(this.expectedConfuseMethod)); + assertTrue(appender.logContains(this.expectedStealMethod)); + assertEquals(3, appender.getLogSize()); } -} \ No newline at end of file + private class InMemoryAppender extends AppenderBase { + private List log = new LinkedList<>(); + + public InMemoryAppender() { + ((Logger) LoggerFactory.getLogger("root")).addAppender(this); + start(); + } + + @Override + protected void append(ILoggingEvent eventObject) { + log.add(eventObject); + } + + public int getLogSize() { + return log.size(); + } + + public String getLastMessage() { + return log.get(log.size() - 1).getFormattedMessage(); + } + + public boolean logContains(String message) { + return log.stream().anyMatch(event -> event.getFormattedMessage().equals(message)); + } + } +} diff --git a/thread-pool/src/main/java/com/iluwatar/threadpool/App.java b/thread-pool/src/main/java/com/iluwatar/threadpool/App.java index 16fbca35a..20d773c82 100644 --- a/thread-pool/src/main/java/com/iluwatar/threadpool/App.java +++ b/thread-pool/src/main/java/com/iluwatar/threadpool/App.java @@ -22,6 +22,9 @@ */ package com.iluwatar.threadpool; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; @@ -43,6 +46,8 @@ import java.util.concurrent.Executors; * */ public class App { + + private static final Logger LOGGER = LoggerFactory.getLogger(App.class); /** * Program entry point @@ -51,7 +56,7 @@ public class App { */ public static void main(String[] args) { - System.out.println("Program started"); + LOGGER.info("Program started"); // Create a list of tasks to be executed List tasks = new ArrayList<>(); @@ -89,6 +94,6 @@ public class App { while (!executor.isTerminated()) { Thread.yield(); } - System.out.println("Program finished"); + LOGGER.info("Program finished"); } } diff --git a/thread-pool/src/main/java/com/iluwatar/threadpool/Worker.java b/thread-pool/src/main/java/com/iluwatar/threadpool/Worker.java index 1354cab41..1740b289e 100644 --- a/thread-pool/src/main/java/com/iluwatar/threadpool/Worker.java +++ b/thread-pool/src/main/java/com/iluwatar/threadpool/Worker.java @@ -22,6 +22,9 @@ */ package com.iluwatar.threadpool; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * * Worker implements {@link Runnable} and thus can be executed by {@link ExecutorService} @@ -29,6 +32,8 @@ package com.iluwatar.threadpool; */ public class Worker implements Runnable { + private static final Logger LOGGER = LoggerFactory.getLogger(Worker.class); + private final Task task; public Worker(final Task task) { @@ -37,8 +42,7 @@ public class Worker implements Runnable { @Override public void run() { - System.out.println(String.format("%s processing %s", Thread.currentThread().getName(), - task.toString())); + LOGGER.info("{} processing {}", Thread.currentThread().getName(), task.toString()); try { Thread.sleep(task.getTimeMs()); } catch (InterruptedException e) { 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 066b6e737..14ebcab40 100644 --- a/tolerant-reader/src/main/java/com/iluwatar/tolerantreader/App.java +++ b/tolerant-reader/src/main/java/com/iluwatar/tolerantreader/App.java @@ -22,6 +22,9 @@ */ package com.iluwatar.tolerantreader; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.io.IOException; /** @@ -41,31 +44,33 @@ import java.io.IOException; */ public class App { + private static final Logger LOGGER = LoggerFactory.getLogger(App.class); + /** * Program entry point */ public static void main(String[] args) throws IOException, ClassNotFoundException { // Write V1 RainbowFish fishV1 = new RainbowFish("Zed", 10, 11, 12); - System.out.println(String.format("fishV1 name=%s age=%d length=%d weight=%d", 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 RainbowFish deserializedFishV1 = RainbowFishSerializer.readV1("fish1.out"); - System.out.println(String.format("deserializedFishV1 name=%s age=%d length=%d weight=%d", + LOGGER.info("deserializedFishV1 name={} age={} length={} weight={}", deserializedFishV1.getName(), deserializedFishV1.getAge(), - deserializedFishV1.getLengthMeters(), deserializedFishV1.getWeightTons())); + deserializedFishV1.getLengthMeters(), deserializedFishV1.getWeightTons()); // Write V2 RainbowFishV2 fishV2 = new RainbowFishV2("Scar", 5, 12, 15, true, true, true); - System.out.println(String.format( - "fishV2 name=%s age=%d length=%d weight=%d sleeping=%b hungry=%b angry=%b", + LOGGER.info( + "fishV2 name={} age={} length={} weight={} sleeping={} hungry={} angry={}", fishV2.getName(), fishV2.getAge(), fishV2.getLengthMeters(), fishV2.getWeightTons(), - fishV2.getHungry(), fishV2.getAngry(), fishV2.getSleeping())); + fishV2.getHungry(), fishV2.getAngry(), fishV2.getSleeping()); RainbowFishSerializer.writeV2(fishV2, "fish2.out"); // Read V2 with V1 method RainbowFish deserializedFishV2 = RainbowFishSerializer.readV1("fish2.out"); - System.out.println(String.format("deserializedFishV2 name=%s age=%d length=%d weight=%d", + LOGGER.info("deserializedFishV2 name={} age={} length={} weight={}", deserializedFishV2.getName(), deserializedFishV2.getAge(), - deserializedFishV2.getLengthMeters(), deserializedFishV2.getWeightTons())); + deserializedFishV2.getLengthMeters(), deserializedFishV2.getWeightTons()); } } diff --git a/twin/src/main/java/com/iluwatar/twin/BallItem.java b/twin/src/main/java/com/iluwatar/twin/BallItem.java index 0188b5731..0c47bc91c 100644 --- a/twin/src/main/java/com/iluwatar/twin/BallItem.java +++ b/twin/src/main/java/com/iluwatar/twin/BallItem.java @@ -23,6 +23,9 @@ package com.iluwatar.twin; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * This class represents a Ball which extends {@link GameItem} and implements the logic for ball * item, like move and draw. It hold a reference of {@link BallThread} to delegate the suspend and @@ -30,6 +33,8 @@ package com.iluwatar.twin; */ public class BallItem extends GameItem { + private static final Logger LOGGER = LoggerFactory.getLogger(BallItem.class); + private boolean isSuspended; private BallThread twin; @@ -41,11 +46,11 @@ public class BallItem extends GameItem { @Override public void doDraw() { - System.out.println("doDraw"); + LOGGER.info("doDraw"); } public void move() { - System.out.println("move"); + LOGGER.info("move"); } @Override diff --git a/twin/src/main/java/com/iluwatar/twin/BallThread.java b/twin/src/main/java/com/iluwatar/twin/BallThread.java index 194d85b06..6dea979be 100644 --- a/twin/src/main/java/com/iluwatar/twin/BallThread.java +++ b/twin/src/main/java/com/iluwatar/twin/BallThread.java @@ -23,6 +23,9 @@ package com.iluwatar.twin; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * This class is a UI thread for drawing the {@link BallItem}, and provide the method for suspend * and resume. It hold the reference of {@link BallItem} to delegate the draw task. @@ -31,6 +34,8 @@ package com.iluwatar.twin; public class BallThread extends Thread { + private static final Logger LOGGER = LoggerFactory.getLogger(BallThread.class); + private BallItem twin; private volatile boolean isSuspended; @@ -61,12 +66,12 @@ public class BallThread extends Thread { public void suspendMe() { isSuspended = true; - System.out.println("Begin to suspend BallThread"); + LOGGER.info("Begin to suspend BallThread"); } public void resumeMe() { isSuspended = false; - System.out.println("Begin to resume BallThread"); + LOGGER.info("Begin to resume BallThread"); } public void stopMe() { diff --git a/twin/src/main/java/com/iluwatar/twin/GameItem.java b/twin/src/main/java/com/iluwatar/twin/GameItem.java index 08d7dcce7..da2cef7a2 100644 --- a/twin/src/main/java/com/iluwatar/twin/GameItem.java +++ b/twin/src/main/java/com/iluwatar/twin/GameItem.java @@ -24,16 +24,21 @@ package com.iluwatar.twin; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * GameItem is a common class which provides some common methods for game object. */ public abstract class GameItem { + private static final Logger LOGGER = LoggerFactory.getLogger(GameItem.class); + /** * Template method, do some common logic before draw */ public void draw() { - System.out.println("draw"); + LOGGER.info("draw"); doDraw(); } diff --git a/twin/src/test/java/com/iluwatar/twin/BallItemTest.java b/twin/src/test/java/com/iluwatar/twin/BallItemTest.java index 4bb9a2111..439a64da1 100644 --- a/twin/src/test/java/com/iluwatar/twin/BallItemTest.java +++ b/twin/src/test/java/com/iluwatar/twin/BallItemTest.java @@ -22,20 +22,40 @@ */ package com.iluwatar.twin; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.AppenderBase; +import org.junit.After; +import org.junit.Before; import org.junit.Test; import org.mockito.InOrder; +import org.slf4j.LoggerFactory; -import static org.mockito.Mockito.inOrder; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; +import java.util.LinkedList; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.*; /** * Date: 12/30/15 - 18:44 PM * * @author Jeroen Meulemeester */ -public class BallItemTest extends StdOutTest { +public class BallItemTest { + + private InMemoryAppender appender; + + @Before + public void setUp() { + appender = new InMemoryAppender(); + } + + @After + public void tearDown() { + appender.stop(); + } @Test public void testClick() { @@ -63,10 +83,11 @@ public class BallItemTest extends StdOutTest { ballItem.setTwin(ballThread); ballItem.draw(); - verify(getStdOutMock()).println("draw"); - verify(getStdOutMock()).println("doDraw"); + assertTrue(appender.logContains("draw")); + assertTrue(appender.logContains("doDraw")); - verifyNoMoreInteractions(ballThread, getStdOutMock()); + verifyNoMoreInteractions(ballThread); + assertEquals(2, appender.getLogSize()); } @Test @@ -76,9 +97,32 @@ public class BallItemTest extends StdOutTest { ballItem.setTwin(ballThread); ballItem.move(); - verify(getStdOutMock()).println("move"); + assertTrue(appender.logContains("move")); - verifyNoMoreInteractions(ballThread, getStdOutMock()); + verifyNoMoreInteractions(ballThread); + assertEquals(1, appender.getLogSize()); } -} \ No newline at end of file + public class InMemoryAppender extends AppenderBase { + private List log = new LinkedList<>(); + + public InMemoryAppender() { + ((Logger) LoggerFactory.getLogger("root")).addAppender(this); + start(); + } + + @Override + protected void append(ILoggingEvent eventObject) { + log.add(eventObject); + } + + public boolean logContains(String message) { + return log.stream().anyMatch(event -> event.getMessage().equals(message)); + } + + public int getLogSize() { + return log.size(); + } + } + +} diff --git a/twin/src/test/java/com/iluwatar/twin/StdOutTest.java b/twin/src/test/java/com/iluwatar/twin/StdOutTest.java deleted file mode 100644 index b3baf8abd..000000000 --- a/twin/src/test/java/com/iluwatar/twin/StdOutTest.java +++ /dev/null @@ -1,75 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014 Ilkka Seppälä - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package com.iluwatar.twin; - -import org.junit.After; -import org.junit.Before; - -import java.io.PrintStream; - -import static org.mockito.Mockito.mock; - -/** - * Date: 12/10/15 - 8:37 PM - * - * @author Jeroen Meulemeester - */ -public abstract class StdOutTest { - - /** - * The mocked standard out {@link PrintStream}, required since some actions don't have any - * influence on accessible objects, except for writing to std-out using {@link System#out} - */ - private final PrintStream stdOutMock = mock(PrintStream.class); - - /** - * Keep the original std-out so it can be restored after the test - */ - private final PrintStream stdOutOrig = System.out; - - /** - * Inject the mocked std-out {@link PrintStream} into the {@link System} class before each test - */ - @Before - public void setUp() { - System.setOut(this.stdOutMock); - } - - /** - * Removed the mocked std-out {@link PrintStream} again from the {@link System} class - */ - @After - public void tearDown() { - System.setOut(this.stdOutOrig); - } - - /** - * Get the mocked stdOut {@link PrintStream} - * - * @return The stdOut print stream mock, renewed before each test - */ - final PrintStream getStdOutMock() { - return this.stdOutMock; - } - -} 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 1e943d054..238258441 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 @@ -22,6 +22,9 @@ */ package com.iluwatar.value.object; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * A Value Object are objects which follow value semantics rather than reference semantics. This * means value objects' equality are not based on identity. Two value objects are equal when they @@ -38,6 +41,9 @@ package com.iluwatar.value.object; * Colebourne's term VALJO : http://blog.joda.org/2014/03/valjos-value-java-objects.html */ public class App { + + private static final Logger LOGGER = LoggerFactory.getLogger(App.class); + /** * This practice creates three HeroStats(Value object) and checks equality between those. */ @@ -46,9 +52,9 @@ public class App { HeroStat statB = HeroStat.valueOf(10, 5, 0); HeroStat statC = HeroStat.valueOf(5, 1, 8); - System.out.println(statA.toString()); + LOGGER.info(statA.toString()); - System.out.println("Is statA and statB equal : " + statA.equals(statB)); - System.out.println("Is statA and statC equal : " + statA.equals(statC)); + LOGGER.info("Is statA and statB equal : {}", statA.equals(statB)); + LOGGER.info("Is statA and statC equal : {}", statA.equals(statC)); } } diff --git a/visitor/src/main/java/com/iluwatar/visitor/CommanderVisitor.java b/visitor/src/main/java/com/iluwatar/visitor/CommanderVisitor.java index 6e54c7861..466c12f51 100644 --- a/visitor/src/main/java/com/iluwatar/visitor/CommanderVisitor.java +++ b/visitor/src/main/java/com/iluwatar/visitor/CommanderVisitor.java @@ -22,6 +22,9 @@ */ package com.iluwatar.visitor; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * * CommanderVisitor @@ -29,6 +32,8 @@ package com.iluwatar.visitor; */ public class CommanderVisitor implements UnitVisitor { + private static final Logger LOGGER = LoggerFactory.getLogger(CommanderVisitor.class); + @Override public void visitSoldier(Soldier soldier) { // Do nothing @@ -41,6 +46,6 @@ public class CommanderVisitor implements UnitVisitor { @Override public void visitCommander(Commander commander) { - System.out.println("Good to see you " + commander); + LOGGER.info("Good to see you {}", commander); } } diff --git a/visitor/src/main/java/com/iluwatar/visitor/SergeantVisitor.java b/visitor/src/main/java/com/iluwatar/visitor/SergeantVisitor.java index 4fca0a5bd..aa06cb2ad 100644 --- a/visitor/src/main/java/com/iluwatar/visitor/SergeantVisitor.java +++ b/visitor/src/main/java/com/iluwatar/visitor/SergeantVisitor.java @@ -22,6 +22,9 @@ */ package com.iluwatar.visitor; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * * SergeantVisitor @@ -29,6 +32,8 @@ package com.iluwatar.visitor; */ public class SergeantVisitor implements UnitVisitor { + private static final Logger LOGGER = LoggerFactory.getLogger(SergeantVisitor.class); + @Override public void visitSoldier(Soldier soldier) { // Do nothing @@ -36,7 +41,7 @@ public class SergeantVisitor implements UnitVisitor { @Override public void visitSergeant(Sergeant sergeant) { - System.out.println("Hello " + sergeant); + LOGGER.info("Hello {}", sergeant); } @Override diff --git a/visitor/src/main/java/com/iluwatar/visitor/SoldierVisitor.java b/visitor/src/main/java/com/iluwatar/visitor/SoldierVisitor.java index fff24f699..0907a2531 100644 --- a/visitor/src/main/java/com/iluwatar/visitor/SoldierVisitor.java +++ b/visitor/src/main/java/com/iluwatar/visitor/SoldierVisitor.java @@ -22,6 +22,9 @@ */ package com.iluwatar.visitor; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * * SoldierVisitor @@ -29,9 +32,11 @@ package com.iluwatar.visitor; */ public class SoldierVisitor implements UnitVisitor { + private static final Logger LOGGER = LoggerFactory.getLogger(SoldierVisitor.class); + @Override public void visitSoldier(Soldier soldier) { - System.out.println("Greetings " + soldier); + LOGGER.info("Greetings {}", soldier); } @Override diff --git a/visitor/src/test/java/com/iluwatar/visitor/StdOutTest.java b/visitor/src/test/java/com/iluwatar/visitor/StdOutTest.java deleted file mode 100644 index 075f235f5..000000000 --- a/visitor/src/test/java/com/iluwatar/visitor/StdOutTest.java +++ /dev/null @@ -1,75 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014 Ilkka Seppälä - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package com.iluwatar.visitor; - -import org.junit.After; -import org.junit.Before; - -import java.io.PrintStream; - -import static org.mockito.Mockito.mock; - -/** - * Date: 12/10/15 - 8:37 PM - * - * @author Jeroen Meulemeester - */ -public abstract class StdOutTest { - - /** - * The mocked standard out {@link PrintStream}, required since some actions don't have any - * influence on accessible objects, except for writing to std-out using {@link System#out} - */ - private final PrintStream stdOutMock = mock(PrintStream.class); - - /** - * Keep the original std-out so it can be restored after the test - */ - private final PrintStream stdOutOrig = System.out; - - /** - * Inject the mocked std-out {@link PrintStream} into the {@link System} class before each test - */ - @Before - public void setUp() { - System.setOut(this.stdOutMock); - } - - /** - * Removed the mocked std-out {@link PrintStream} again from the {@link System} class - */ - @After - public void tearDown() { - System.setOut(this.stdOutOrig); - } - - /** - * Get the mocked stdOut {@link PrintStream} - * - * @return The stdOut print stream mock, renewed before each test - */ - final PrintStream getStdOutMock() { - return this.stdOutMock; - } - -} diff --git a/visitor/src/test/java/com/iluwatar/visitor/VisitorTest.java b/visitor/src/test/java/com/iluwatar/visitor/VisitorTest.java index 4a131bbf2..a0c8b4eea 100644 --- a/visitor/src/test/java/com/iluwatar/visitor/VisitorTest.java +++ b/visitor/src/test/java/com/iluwatar/visitor/VisitorTest.java @@ -22,19 +22,38 @@ */ package com.iluwatar.visitor; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.AppenderBase; +import org.junit.After; +import org.junit.Before; import org.junit.Test; +import org.slf4j.LoggerFactory; +import java.util.LinkedList; +import java.util.List; import java.util.Optional; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.junit.Assert.assertEquals; /** * Date: 12/30/15 - 18:59 PM * * @author Jeroen Meulemeester */ -public abstract class VisitorTest extends StdOutTest { +public abstract class VisitorTest { + + private InMemoryAppender appender; + + @Before + public void setUp() { + appender = new InMemoryAppender(); + } + + @After + public void tearDown() { + appender.stop(); + } /** * The tested visitor instance @@ -76,27 +95,48 @@ public abstract class VisitorTest extends StdOutTest { public void testVisitCommander() { this.visitor.visitCommander(new Commander()); if (this.commanderResponse.isPresent()) { - verify(getStdOutMock()).println(this.commanderResponse.get()); + assertEquals(this.commanderResponse.get(), appender.getLastMessage()); + assertEquals(1, appender.getLogSize()); } - verifyNoMoreInteractions(getStdOutMock()); } @Test public void testVisitSergeant() { this.visitor.visitSergeant(new Sergeant()); if (this.sergeantResponse.isPresent()) { - verify(getStdOutMock()).println(this.sergeantResponse.get()); + assertEquals(this.sergeantResponse.get(), appender.getLastMessage()); + assertEquals(1, appender.getLogSize()); } - verifyNoMoreInteractions(getStdOutMock()); } @Test public void testVisitSoldier() { this.visitor.visitSoldier(new Soldier()); if (this.soldierResponse.isPresent()) { - verify(getStdOutMock()).println(this.soldierResponse.get()); + assertEquals(this.soldierResponse.get(), appender.getLastMessage()); + assertEquals(1, appender.getLogSize()); } - verifyNoMoreInteractions(getStdOutMock()); } + private class InMemoryAppender extends AppenderBase { + private List log = new LinkedList<>(); + + public InMemoryAppender() { + ((Logger) LoggerFactory.getLogger("root")).addAppender(this); + start(); + } + + @Override + protected void append(ILoggingEvent eventObject) { + log.add(eventObject); + } + + public int getLogSize() { + return log.size(); + } + + public String getLastMessage() { + return log.get(log.size() - 1).getFormattedMessage(); + } + } }