From cec9a99410a0544ff0f1a5853443ef9dcff0a9e7 Mon Sep 17 00:00:00 2001 From: Ilkka Seppala Date: Fri, 25 Dec 2015 23:49:28 +0200 Subject: [PATCH] Adjust checkstyle rules. Make checkstyle fail the build when violations are found. Correct all current checkstyle violations. --- .../com/iluwatar/abstractfactory/App.java | 85 +++++---- .../iluwatar/async/method/invocation/App.java | 47 ++--- .../async/method/invocation/AsyncResult.java | 2 - .../invocation/ThreadAsyncExecutor.java | 24 +-- .../invocation/ThreadAsyncExecutorTest.java | 76 ++++---- .../main/java/com/iluwatar/builder/Hero.java | 3 + .../business/delegate/BusinessDelegate.java | 26 +-- .../main/java/com/iluwatar/caching/App.java | 4 +- .../java/com/iluwatar/caching/AppManager.java | 23 ++- .../java/com/iluwatar/caching/CacheStore.java | 89 +++++---- .../{DBManager.java => DbManager.java} | 53 ++++-- .../caching/{LRUCache.java => LruCache.java} | 65 ++++--- .../com/iluwatar/caching/UserAccount.java | 19 +- .../java/com/iluwatar/caching/AppTest.java | 2 +- .../main/java/com/iluwatar/callback/App.java | 3 + .../main/java/com/iluwatar/callback/Task.java | 3 + .../com/iluwatar/chain/RequestHandler.java | 3 + checkstyle.xml | 75 ++------ .../java/com/iluwatar/command/Target.java | 3 + .../java/com/iluwatar/command/Wizard.java | 9 + .../iluwatar/composite/LetterComposite.java | 3 + .../java/com/iluwatar/composite/Sentence.java | 3 + .../java/com/iluwatar/composite/Word.java | 3 + dao/src/main/java/com/iluwatar/dao/App.java | 12 +- .../main/java/com/iluwatar/dao/Customer.java | 6 +- dao/src/main/resources/log4j.xml | 20 +-- .../iluwatar/doublechecked/locking/App.java | 2 +- .../doublechecked/locking/Inventory.java | 6 + .../doublechecked/locking/InventoryTest.java | 4 +- .../java/com/iluwatar/doubledispatch/App.java | 30 ++-- .../iluwatar/doubledispatch/Rectangle.java | 3 + .../doubledispatch/CollisionTest.java | 12 +- .../event/aggregator/EventEmitterTest.java | 62 +++---- .../event/aggregator/KingsHandTest.java | 2 +- .../java/com/iluwatar/execute/around/App.java | 3 - .../execute/around/SimpleFileWriter.java | 3 + .../execute/around/SimpleFileWriterTest.java | 6 +- .../facade/DwarvenGoldmineFacade.java | 3 + .../iluwatar/facade/DwarvenMineWorker.java | 3 + .../com/iluwatar/fluentinterface/app/App.java | 19 +- .../lazy/DecoratingIterator.java | 4 - .../simple/SimpleFluentIterable.java | 10 +- .../fluentiterable/FluentIterableTest.java | 2 +- .../iluwatar/flux/dispatcher/Dispatcher.java | 3 + .../com/iluwatar/flyweight/AlchemistShop.java | 6 + .../com/iluwatar/front/controller/App.java | 40 +++-- .../controller/ApplicationException.java | 8 +- .../front/controller/ArcherCommand.java | 8 +- .../iluwatar/front/controller/ArcherView.java | 8 +- .../front/controller/CatapultCommand.java | 8 +- .../front/controller/CatapultView.java | 8 +- .../iluwatar/front/controller/Command.java | 4 +- .../iluwatar/front/controller/ErrorView.java | 8 +- .../front/controller/FrontController.java | 52 +++--- .../front/controller/UnknownCommand.java | 8 +- .../com/iluwatar/front/controller/View.java | 2 +- .../iluwatar/front/controller/AppTest.java | 12 +- .../controller/ApplicationExceptionTest.java | 4 +- .../com/iluwatar/halfsynchalfasync/App.java | 15 +- .../intercepting/filter/AddressFilter.java | 3 +- .../iluwatar/intercepting/filter/Client.java | 6 +- .../iluwatar/intercepting/filter/Filter.java | 9 - .../intercepting/filter/FilterChain.java | 9 + .../iluwatar/intercepting/filter/Order.java | 3 + .../iluwatar/intercepting/filter/Target.java | 6 +- .../intercepting/filter/FilterTest.java | 3 + .../java/com/iluwatar/interpreter/App.java | 6 +- .../iluwatar/interpreter/ExpressionTest.java | 6 +- .../main/java/com/iluwatar/iterator/App.java | 8 +- .../com/iluwatar/iterator/TreasureChest.java | 10 +- .../iterator/TreasureChestItemIterator.java | 3 + .../iluwatar/iterator/TreasureChestTest.java | 2 +- .../main/java/com/iluwatar/layers/App.java | 42 +++-- .../iluwatar/layers/CakeBakingService.java | 13 -- .../java/com/iluwatar/layers/CakeInfo.java | 9 + .../com/iluwatar/layers/CakeLayerInfo.java | 6 + .../com/iluwatar/layers/CakeToppingInfo.java | 6 + .../main/resources/META-INF/persistence.xml | 6 +- .../src/main/resources/applicationContext.xml | 67 ++++--- .../java/com/iluwatar/lazy/loading/Heavy.java | 3 + .../iluwatar/lazy/loading/HolderNaive.java | 6 + .../lazy/loading/HolderThreadSafe.java | 6 + .../iluwatar/lazy/loading/Java8Holder.java | 2 +- .../main/java/com/iluwatar/memento/App.java | 3 + .../main/java/com/iluwatar/memento/Star.java | 6 + .../com/iluwatar/message/channel/App.java | 3 - .../model/view/presenter/FileLoader.java | 4 +- .../view/presenter/FileSelectorJFrame.java | 16 +- .../view/presenter/FileSelectorPresenter.java | 7 +- .../presenter/FileSelectorPresenterTest.java | 15 +- .../com/iluwatar/monostate/LoadBalancer.java | 6 + .../java/com/iluwatar/monostate/Server.java | 3 + .../dom/app/homepage/HomePageService.java | 4 +- .../dom/modules/simple/SimpleObjects.java | 5 +- .../modules/simple/SimpleObjectCreate.java | 2 - .../scenarios/RecreateSimpleObjects.java | 8 +- .../bootstrap/SimpleAppSystemInitializer.java | 3 + .../modules/simple/SimpleObjectGlue.java | 4 +- .../integtests/tests/SimpleAppIntegTest.java | 14 +- .../modules/simple/SimpleObjectIntegTest.java | 153 ++++++++-------- .../simple/SimpleObjectsIntegTest.java | 170 +++++++++--------- .../domainapp/webapp/SimpleApplication.java | 3 +- .../com/iluwatar/nullobject/NodeImpl.java | 3 + .../com/iluwatar/object/pool/ObjectPool.java | 5 +- .../com/iluwatar/object/pool/Oliphaunt.java | 3 + .../java/com/iluwatar/observer/Weather.java | 3 + .../iluwatar/observer/generic/GWeather.java | 3 + .../iluwatar/observer/generic/Observable.java | 3 + .../iluwatar/observer/generic/Observer.java | 4 - .../com/iluwatar/poison/pill/Consumer.java | 7 +- .../iluwatar/poison/pill/MessageQueue.java | 2 +- ...QPublishPoint.java => MqPublishPoint.java} | 2 +- ...scribePoint.java => MqSubscribePoint.java} | 2 +- .../com/iluwatar/poison/pill/Producer.java | 13 +- pom.xml | 2 +- .../privateclassdata/ImmutableStew.java | 3 + .../com/iluwatar/privateclassdata/Stew.java | 9 + .../iluwatar/privateclassdata/StewData.java | 3 + .../com/iluwatar/producer/consumer/App.java | 17 +- .../iluwatar/producer/consumer/Consumer.java | 3 + .../iluwatar/producer/consumer/Producer.java | 3 + .../java/com/iluwatar/property/Character.java | 6 + .../iluwatar/prototype/HeroFactoryImpl.java | 12 ++ .../src/main/java/com/iluwatar/proxy/App.java | 3 + .../com/iluwatar/publish/subscribe/App.java | 4 - .../java/com/iluwatar/reactor/app/App.java | 2 - .../com/iluwatar/reactor/app/AppClient.java | 16 +- .../reactor/framework/AbstractNioChannel.java | 1 + .../reactor/framework/NioReactor.java | 81 +++++---- .../com/iluwatar/repository/AppConfig.java | 7 +- .../java/com/iluwatar/repository/Person.java | 33 ++-- .../repository/PersonSpecifications.java | 7 + .../main/resources/META-INF/persistence.xml | 6 +- .../src/main/resources/applicationContext.xml | 66 ++++--- .../AnnotationBasedRepositoryTest.java | 4 +- .../iluwatar/repository/AppConfigTest.java | 5 +- .../iluwatar/repository/RepositoryTest.java | 4 +- .../acquisition/is/initialization/App.java | 3 - .../main/java/com/iluwatar/servant/App.java | 14 +- .../main/java/com/iluwatar/servant/King.java | 6 +- .../main/java/com/iluwatar/servant/Queen.java | 3 +- .../java/com/iluwatar/servant/Servant.java | 14 +- .../com/iluwatar/servicelayer/app/App.java | 6 + .../servicelayer/common/DaoBaseImpl.java | 15 +- .../servicelayer/hibernate/HibernateUtil.java | 6 +- .../servicelayer/magic/MagicServiceImpl.java | 3 + .../servicelayer/spell/SpellDaoImpl.java | 3 +- .../spellbook/SpellbookDaoImpl.java | 3 +- .../servicelayer/wizard/WizardDaoImpl.java | 3 +- .../iluwatar/servicelocator/ServiceImpl.java | 3 + .../com/iluwatar/singleton/IvoryTower.java | 4 +- .../ThreadSafeDoubleCheckLocking.java | 10 +- .../ThreadSafeLazyLoadedIvoryTower.java | 2 +- .../LazyLoadedSingletonThreadSafetyTest.java | 20 ++- .../com/iluwatar/specification/app/App.java | 3 + .../creature/AbstractCreature.java | 3 + .../src/main/java/com/iluwatar/state/App.java | 3 + .../main/java/com/iluwatar/state/Mammoth.java | 3 + .../java/com/iluwatar/stepbuilder/App.java | 2 +- .../templatemethod/StealingMethod.java | 3 + .../java/com/iluwatar/tolerantreader/App.java | 3 + .../iluwatar/tolerantreader/RainbowFish.java | 3 + .../tolerantreader/RainbowFishSerializer.java | 13 -- .../tolerantreader/RainbowFishV2.java | 3 + .../java/com/iluwatar/twin/BallThread.java | 3 + .../main/java/com/iluwatar/twin/GameItem.java | 3 - .../main/java/com/iluwatar/visitor/Unit.java | 3 + 167 files changed, 1242 insertions(+), 969 deletions(-) rename caching/src/main/java/com/iluwatar/caching/{DBManager.java => DbManager.java} (73%) rename caching/src/main/java/com/iluwatar/caching/{LRUCache.java => LruCache.java} (70%) rename poison-pill/src/main/java/com/iluwatar/poison/pill/{MQPublishPoint.java => MqPublishPoint.java} (81%) rename poison-pill/src/main/java/com/iluwatar/poison/pill/{MQSubscribePoint.java => MqSubscribePoint.java} (80%) 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 9a32a091a..cdde3bd8f 100644 --- a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/App.java +++ b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/App.java @@ -1,20 +1,18 @@ package com.iluwatar.abstractfactory; - /** * - * The Abstract Factory pattern provides a way to encapsulate a group of individual factories that - * have a common theme without specifying their concrete classes. In normal usage, the client - * software creates a concrete implementation of the abstract factory and then uses the generic - * interface of the factory to create the concrete objects that are part of the theme. The client - * does not know (or care) which concrete objects it gets from each of these internal factories, - * since it uses only the generic interfaces of their products. This pattern separates the details - * of implementation of a set of objects from their general usage and relies on object composition, - * as object creation is implemented in methods exposed in the factory interface. + * The Abstract Factory pattern provides a way to encapsulate a group of individual factories that have a common theme + * without specifying their concrete classes. In normal usage, the client software creates a concrete implementation of + * the abstract factory and then uses the generic interface of the factory to create the concrete objects that are part + * of the theme. The client does not know (or care) which concrete objects it gets from each of these internal + * factories, since it uses only the generic interfaces of their products. This pattern separates the details of + * implementation of a set of objects from their general usage and relies on object composition, as object creation is + * implemented in methods exposed in the factory interface. *

- * The essence of the Abstract Factory pattern is a factory interface ({@link KingdomFactory}) and - * its implementations ({@link ElfKingdomFactory}, {@link OrcKingdomFactory}). The example uses both - * concrete implementations to create a king, a castle and an army. + * The essence of the Abstract Factory pattern is a factory interface ({@link KingdomFactory}) and its implementations ( + * {@link ElfKingdomFactory}, {@link OrcKingdomFactory}). The example uses both concrete implementations to create a + * king, a castle and an army. * */ public class App { @@ -23,11 +21,8 @@ public class App { private Castle castle; private Army army; - /** * Creates kingdom - * - * @param factory */ public void createKingdom(final KingdomFactory factory) { setKing(factory.createKing()); @@ -47,14 +42,6 @@ public class App { return factory.createKing(); } - Castle getCastle(final KingdomFactory factory) { - return factory.createCastle(); - } - - Army getArmy(final KingdomFactory factory) { - return factory.createArmy(); - } - public King getKing() { return king; } @@ -62,6 +49,10 @@ public class App { private void setKing(final King king) { this.king = king; } + + Castle getCastle(final KingdomFactory factory) { + return factory.createCastle(); + } public Castle getCastle() { return castle; @@ -70,6 +61,10 @@ public class App { private void setCastle(final Castle castle) { this.castle = castle; } + + Army getArmy(final KingdomFactory factory) { + return factory.createArmy(); + } public Army getArmy() { return army; @@ -79,32 +74,32 @@ public class App { this.army = army; } - /** * Program entry point * - * @param args command line args + * @param args + * command line args */ public static void main(String[] args) { - - App app = new App(); - - System.out.println("Elf Kingdom"); - KingdomFactory elfKingdomFactory; - elfKingdomFactory = app.getElfKingdomFactory(); - app.createKingdom(elfKingdomFactory); - System.out.println(app.getArmy().getDescription()); - System.out.println(app.getCastle().getDescription()); - System.out.println(app.getKing().getDescription()); - - System.out.println("\nOrc Kingdom"); - KingdomFactory orcKingdomFactory; - orcKingdomFactory = app.getOrcKingdomFactory(); - app.createKingdom(orcKingdomFactory); - System.out.println(app.getArmy().getDescription()); - System.out.println(app.getCastle().getDescription()); - System.out.println(app.getKing().getDescription()); - + + App app = new App(); + + System.out.println("Elf Kingdom"); + KingdomFactory elfKingdomFactory; + elfKingdomFactory = app.getElfKingdomFactory(); + app.createKingdom(elfKingdomFactory); + System.out.println(app.getArmy().getDescription()); + System.out.println(app.getCastle().getDescription()); + System.out.println(app.getKing().getDescription()); + + System.out.println("\nOrc Kingdom"); + KingdomFactory orcKingdomFactory; + orcKingdomFactory = app.getOrcKingdomFactory(); + app.createKingdom(orcKingdomFactory); + System.out.println(app.getArmy().getDescription()); + System.out.println(app.getCastle().getDescription()); + System.out.println(app.getKing().getDescription()); + } - + } 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 0b8ee3649..6f2d4a8fc 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 @@ -4,24 +4,23 @@ import java.util.concurrent.Callable; /** * This application demonstrates the async method invocation pattern. Key parts of the pattern are - * AsyncResult which is an intermediate container for an asynchronously evaluated - * value, AsyncCallback which can be provided to be executed on task completion and - * AsyncExecutor that manages the execution of the async tasks. + * AsyncResult which is an intermediate container for an asynchronously evaluated value, + * AsyncCallback which can be provided to be executed on task completion and AsyncExecutor + * that manages the execution of the async tasks. *

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

- * Noteworthy difference of thread usage between the async results and callbacks is that the async - * results are collected in the main thread but the callbacks are executed within the worker - * threads. This should be noted when working with thread pools. + * Noteworthy difference of thread usage between the async results and callbacks is that the async results are collected + * in the main thread but the callbacks are executed within the worker threads. This should be noted when working with + * thread pools. *

- * Java provides its own implementations of async method invocation pattern. FutureTask, - * CompletableFuture and ExecutorService are the real world implementations of this pattern. But due - * to the nature of parallel programming, the implementations are not trivial. This example does not - * take all possible scenarios into account but rather provides a simple version that helps to - * understand the pattern. + * Java provides its own implementations of async method invocation pattern. FutureTask, CompletableFuture and + * ExecutorService are the real world implementations of this pattern. But due to the nature of parallel programming, + * the implementations are not trivial. This example does not take all possible scenarios into account but rather + * provides a simple version that helps to understand the pattern. * * @see AsyncResult * @see AsyncCallback @@ -33,6 +32,9 @@ import java.util.concurrent.Callable; */ public class App { + /** + * Program entry point + */ public static void main(String[] args) throws Exception { // construct a new executor that will run async tasks AsyncExecutor executor = new ThreadAsyncExecutor(); @@ -41,10 +43,8 @@ public class App { AsyncResult asyncResult1 = executor.startProcess(lazyval(10, 500)); AsyncResult asyncResult2 = executor.startProcess(lazyval("test", 300)); AsyncResult asyncResult3 = executor.startProcess(lazyval(50L, 700)); - AsyncResult asyncResult4 = - executor.startProcess(lazyval(20, 400), callback("Callback result 4")); - AsyncResult asyncResult5 = - executor.startProcess(lazyval("callback", 600), callback("Callback result 5")); + AsyncResult asyncResult4 = executor.startProcess(lazyval(20, 400), callback("Callback result 4")); + AsyncResult asyncResult5 = executor.startProcess(lazyval("callback", 600), callback("Callback result 5")); // emulate processing in the current thread while async tasks are running in their own threads Thread.sleep(350); // Oh boy I'm working hard here @@ -66,8 +66,10 @@ public class App { /** * Creates a callable that lazily evaluates to given value with artificial delay. * - * @param value value to evaluate - * @param delayMillis artificial delay in milliseconds + * @param value + * value to evaluate + * @param delayMillis + * artificial delay in milliseconds * @return new callable for lazy evaluation */ private static Callable lazyval(T value, long delayMillis) { @@ -81,7 +83,8 @@ public class App { /** * Creates a simple callback that logs the complete status of the async result. * - * @param name callback name + * @param name + * callback name * @return new async callback */ private static AsyncCallback callback(String name) { diff --git a/async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/AsyncResult.java b/async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/AsyncResult.java index 6d77df8ec..d64180dad 100644 --- a/async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/AsyncResult.java +++ b/async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/AsyncResult.java @@ -5,8 +5,6 @@ import java.util.concurrent.ExecutionException; /** * * AsyncResult interface - * - * @param */ public interface AsyncResult { diff --git a/async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/ThreadAsyncExecutor.java b/async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/ThreadAsyncExecutor.java index 300934562..e935f9626 100644 --- a/async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/ThreadAsyncExecutor.java +++ b/async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/ThreadAsyncExecutor.java @@ -29,13 +29,12 @@ public class ThreadAsyncExecutor implements AsyncExecutor { } catch (Exception ex) { result.setException(ex); } - }, "executor-" + idx.incrementAndGet()).start(); + } , "executor-" + idx.incrementAndGet()).start(); return result; } @Override - public T endProcess(AsyncResult asyncResult) throws ExecutionException, - InterruptedException { + public T endProcess(AsyncResult asyncResult) throws ExecutionException, InterruptedException { if (asyncResult.isCompleted()) { return asyncResult.getValue(); } else { @@ -45,9 +44,8 @@ public class ThreadAsyncExecutor implements AsyncExecutor { } /** - * Simple implementation of async result that allows completing it successfully with a value or - * exceptionally with an exception. A really simplified version from its real life cousins - * FutureTask and CompletableFuture. + * Simple implementation of async result that allows completing it successfully with a value or exceptionally with an + * exception. A really simplified version from its real life cousins FutureTask and CompletableFuture. * * @see java.util.concurrent.FutureTask * @see java.util.concurrent.CompletableFuture @@ -71,10 +69,11 @@ public class ThreadAsyncExecutor implements AsyncExecutor { } /** - * Sets the value from successful execution and executes callback if available. Notifies any - * thread waiting for completion. + * Sets the value from successful execution and executes callback if available. Notifies any thread waiting for + * completion. * - * @param value value of the evaluated task + * @param value + * value of the evaluated task */ void setValue(T value) { this.value = value; @@ -86,10 +85,11 @@ public class ThreadAsyncExecutor implements AsyncExecutor { } /** - * Sets the exception from failed execution and executes callback if available. Notifies any - * thread waiting for completion. + * Sets the exception from failed execution and executes callback if available. Notifies any thread waiting for + * completion. * - * @param exception exception of the failed task + * @param exception + * exception of the failed task */ void setException(Exception exception) { this.exception = exception; diff --git a/async-method-invocation/src/test/java/com/iluwatar/async/method/invocation/ThreadAsyncExecutorTest.java b/async-method-invocation/src/test/java/com/iluwatar/async/method/invocation/ThreadAsyncExecutorTest.java index 440e47552..f5727b1e8 100644 --- a/async-method-invocation/src/test/java/com/iluwatar/async/method/invocation/ThreadAsyncExecutorTest.java +++ b/async-method-invocation/src/test/java/com/iluwatar/async/method/invocation/ThreadAsyncExecutorTest.java @@ -55,8 +55,7 @@ public class ThreadAsyncExecutorTest { } /** - * Test used to verify the happy path of - * {@link ThreadAsyncExecutor#startProcess(Callable, AsyncCallback)} + * Test used to verify the happy path of {@link ThreadAsyncExecutor#startProcess(Callable, AsyncCallback)} */ @Test(timeout = 3000) public void testSuccessfulTaskWithCallback() throws Exception { @@ -77,8 +76,7 @@ public class ThreadAsyncExecutorTest { verify(task, times(1)).call(); // ... same for the callback, we expect our object - final ArgumentCaptor> optionalCaptor = ArgumentCaptor - .forClass((Class) Optional.class); + final ArgumentCaptor> optionalCaptor = ArgumentCaptor.forClass((Class) Optional.class); verify(callback, times(1)).onComplete(eq(result), optionalCaptor.capture()); final Optional optionalException = optionalCaptor.getValue(); @@ -90,8 +88,8 @@ public class ThreadAsyncExecutorTest { } /** - * Test used to verify the happy path of {@link ThreadAsyncExecutor#startProcess(Callable)} when a - * task takes a while to execute + * Test used to verify the happy path of {@link ThreadAsyncExecutor#startProcess(Callable)} when a task takes a while + * to execute */ @Test(timeout = 5000) public void testLongRunningTaskWithoutCallback() throws Exception { @@ -101,9 +99,9 @@ public class ThreadAsyncExecutorTest { final Object result = new Object(); final Callable task = mock(Callable.class); when(task.call()).thenAnswer(i -> { - Thread.sleep(1500); - return result; - }); + Thread.sleep(1500); + return result; + }); final AsyncResult asyncResult = executor.startProcess(task); assertNotNull(asyncResult); @@ -111,8 +109,7 @@ public class ThreadAsyncExecutorTest { try { asyncResult.getValue(); - fail( - "Expected IllegalStateException when calling AsyncResult#getValue on a non-completed task"); + fail("Expected IllegalStateException when calling AsyncResult#getValue on a non-completed task"); } catch (IllegalStateException e) { assertNotNull(e.getMessage()); } @@ -130,9 +127,8 @@ public class ThreadAsyncExecutorTest { } /** - * Test used to verify the happy path of - * {@link ThreadAsyncExecutor#startProcess(Callable, AsyncCallback)} when a task takes a while to - * execute + * Test used to verify the happy path of {@link ThreadAsyncExecutor#startProcess(Callable, AsyncCallback)} when a task + * takes a while to execute */ @Test(timeout = 5000) public void testLongRunningTaskWithCallback() throws Exception { @@ -142,9 +138,9 @@ public class ThreadAsyncExecutorTest { final Object result = new Object(); final Callable task = mock(Callable.class); when(task.call()).thenAnswer(i -> { - Thread.sleep(1500); - return result; - }); + Thread.sleep(1500); + return result; + }); final AsyncCallback callback = mock(AsyncCallback.class); final AsyncResult asyncResult = executor.startProcess(task, callback); @@ -155,8 +151,7 @@ public class ThreadAsyncExecutorTest { try { asyncResult.getValue(); - fail( - "Expected IllegalStateException when calling AsyncResult#getValue on a non-completed task"); + fail("Expected IllegalStateException when calling AsyncResult#getValue on a non-completed task"); } catch (IllegalStateException e) { assertNotNull(e.getMessage()); } @@ -164,8 +159,7 @@ public class ThreadAsyncExecutorTest { // Our task should only execute once, but it can take a while ... verify(task, timeout(3000).times(1)).call(); - final ArgumentCaptor> optionalCaptor = ArgumentCaptor - .forClass((Class) Optional.class); + final ArgumentCaptor> optionalCaptor = ArgumentCaptor.forClass((Class) Optional.class); verify(callback, timeout(3000).times(1)).onComplete(eq(result), optionalCaptor.capture()); final Optional optionalException = optionalCaptor.getValue(); @@ -182,9 +176,8 @@ public class ThreadAsyncExecutorTest { } /** - * Test used to verify the happy path of {@link ThreadAsyncExecutor#startProcess(Callable)} when a - * task takes a while to execute, while waiting on the result using - * {@link ThreadAsyncExecutor#endProcess(AsyncResult)} + * Test used to verify the happy path of {@link ThreadAsyncExecutor#startProcess(Callable)} when a task takes a while + * to execute, while waiting on the result using {@link ThreadAsyncExecutor#endProcess(AsyncResult)} */ @Test(timeout = 5000) public void testEndProcess() throws Exception { @@ -194,9 +187,9 @@ public class ThreadAsyncExecutorTest { final Object result = new Object(); final Callable task = mock(Callable.class); when(task.call()).thenAnswer(i -> { - Thread.sleep(1500); - return result; - }); + Thread.sleep(1500); + return result; + }); final AsyncResult asyncResult = executor.startProcess(task); assertNotNull(asyncResult); @@ -204,8 +197,7 @@ public class ThreadAsyncExecutorTest { try { asyncResult.getValue(); - fail( - "Expected IllegalStateException when calling AsyncResult#getValue on a non-completed task"); + fail("Expected IllegalStateException when calling AsyncResult#getValue on a non-completed task"); } catch (IllegalStateException e) { assertNotNull(e.getMessage()); } @@ -220,8 +212,7 @@ public class ThreadAsyncExecutorTest { } /** - * Test used to verify the behaviour of {@link ThreadAsyncExecutor#startProcess(Callable)} when - * the callable is 'null' + * Test used to verify the behaviour of {@link ThreadAsyncExecutor#startProcess(Callable)} when the callable is 'null' */ @Test(timeout = 3000) public void testNullTask() throws Exception { @@ -229,8 +220,7 @@ public class ThreadAsyncExecutorTest { final ThreadAsyncExecutor executor = new ThreadAsyncExecutor(); final AsyncResult asyncResult = executor.startProcess(null); - assertNotNull("The AsyncResult should not be 'null', even though the task was 'null'.", - asyncResult); + assertNotNull("The AsyncResult should not be 'null', even though the task was 'null'.", asyncResult); asyncResult.await(); // Prevent timing issues, and wait until the result is available assertTrue(asyncResult.isCompleted()); @@ -246,9 +236,8 @@ public class ThreadAsyncExecutorTest { } /** - * Test used to verify the behaviour of - * {@link ThreadAsyncExecutor#startProcess(Callable, AsyncCallback)} when the callable is 'null', - * but the asynchronous callback is provided + * Test used to verify the behaviour of {@link ThreadAsyncExecutor#startProcess(Callable, AsyncCallback)} when the + * callable is 'null', but the asynchronous callback is provided */ @Test(timeout = 3000) public void testNullTaskWithCallback() throws Exception { @@ -257,13 +246,11 @@ public class ThreadAsyncExecutorTest { final AsyncCallback callback = mock(AsyncCallback.class); final AsyncResult asyncResult = executor.startProcess(null, callback); - assertNotNull("The AsyncResult should not be 'null', even though the task was 'null'.", - asyncResult); + assertNotNull("The AsyncResult should not be 'null', even though the task was 'null'.", asyncResult); asyncResult.await(); // Prevent timing issues, and wait until the result is available assertTrue(asyncResult.isCompleted()); - final ArgumentCaptor> optionalCaptor = ArgumentCaptor - .forClass((Class) Optional.class); + final ArgumentCaptor> optionalCaptor = ArgumentCaptor.forClass((Class) Optional.class); verify(callback, times(1)).onComplete(Matchers.isNull(), optionalCaptor.capture()); final Optional optionalException = optionalCaptor.getValue(); @@ -286,9 +273,8 @@ public class ThreadAsyncExecutorTest { } /** - * Test used to verify the behaviour of - * {@link ThreadAsyncExecutor#startProcess(Callable, AsyncCallback)} when both the callable and - * the asynchronous callback are 'null' + * Test used to verify the behaviour of {@link ThreadAsyncExecutor#startProcess(Callable, AsyncCallback)} when both + * the callable and the asynchronous callback are 'null' */ @Test(timeout = 3000) public void testNullTaskWithNullCallback() throws Exception { @@ -296,9 +282,7 @@ public class ThreadAsyncExecutorTest { final ThreadAsyncExecutor executor = new ThreadAsyncExecutor(); final AsyncResult asyncResult = executor.startProcess(null, null); - assertNotNull( - "The AsyncResult should not be 'null', even though the task and callback were 'null'.", - asyncResult); + assertNotNull("The AsyncResult should not be 'null', even though the task and callback were 'null'.", asyncResult); asyncResult.await(); // Prevent timing issues, and wait until the result is available assertTrue(asyncResult.isCompleted()); diff --git a/builder/src/main/java/com/iluwatar/builder/Hero.java b/builder/src/main/java/com/iluwatar/builder/Hero.java index 54be11ea3..cf7289d51 100644 --- a/builder/src/main/java/com/iluwatar/builder/Hero.java +++ b/builder/src/main/java/com/iluwatar/builder/Hero.java @@ -93,6 +93,9 @@ public class Hero { private Armor armor; private Weapon weapon; + /** + * Constructor + */ public HeroBuilder(Profession profession, String name) { if (profession == null || name == null) { throw new IllegalArgumentException("profession and name can not be null"); diff --git a/business-delegate/src/main/java/com/iluwatar/business/delegate/BusinessDelegate.java b/business-delegate/src/main/java/com/iluwatar/business/delegate/BusinessDelegate.java index a3c9a00e7..7fb709bcf 100644 --- a/business-delegate/src/main/java/com/iluwatar/business/delegate/BusinessDelegate.java +++ b/business-delegate/src/main/java/com/iluwatar/business/delegate/BusinessDelegate.java @@ -5,20 +5,20 @@ package com.iluwatar.business.delegate; */ public class BusinessDelegate { - private BusinessLookup lookupService; - private BusinessService businessService; - private ServiceType serviceType; + private BusinessLookup lookupService; + private BusinessService businessService; + private ServiceType serviceType; - public void setLookupService(BusinessLookup businessLookup) { - this.lookupService = businessLookup; - } + public void setLookupService(BusinessLookup businessLookup) { + this.lookupService = businessLookup; + } - public void setServiceType(ServiceType serviceType) { - this.serviceType = serviceType; - } + public void setServiceType(ServiceType serviceType) { + this.serviceType = serviceType; + } - public void doTask() { - businessService = lookupService.getBusinessService(serviceType); - businessService.doProcessing(); - } + public void doTask() { + businessService = lookupService.getBusinessService(serviceType); + businessService.doProcessing(); + } } diff --git a/caching/src/main/java/com/iluwatar/caching/App.java b/caching/src/main/java/com/iluwatar/caching/App.java index c7f55db70..8dcef95ce 100644 --- a/caching/src/main/java/com/iluwatar/caching/App.java +++ b/caching/src/main/java/com/iluwatar/caching/App.java @@ -21,7 +21,7 @@ package com.iluwatar.caching; * application data. The cache itself is implemented as an internal (Java) data structure. It adopts * a Least-Recently-Used (LRU) strategy for evicting data from itself when its full. The three * strategies are individually tested. The testing of the cache is restricted towards saving and - * querying of user accounts from the underlying data store ( {@link DBManager}). The main class ( + * querying of user accounts from the underlying data store ( {@link DbManager}). The main class ( * {@link App} is not aware of the underlying mechanics of the application (i.e. save and query) and * whether the data is coming from the cache or the DB (i.e. separation of concern). The AppManager * ({@link AppManager}) handles the transaction of data to-and-from the underlying data store @@ -43,7 +43,7 @@ public class App { * @param args command line args */ public static void main(String[] args) { - AppManager.initDB(false); // VirtualDB (instead of MongoDB) was used in running the JUnit tests + AppManager.initDb(false); // VirtualDB (instead of MongoDB) was used in running the JUnit tests // and the App class to avoid Maven compilation errors. Set flag to // true to run the tests with MongoDB (provided that MongoDB is // installed and socket connection is open). diff --git a/caching/src/main/java/com/iluwatar/caching/AppManager.java b/caching/src/main/java/com/iluwatar/caching/AppManager.java index 08132e327..925320cd6 100644 --- a/caching/src/main/java/com/iluwatar/caching/AppManager.java +++ b/caching/src/main/java/com/iluwatar/caching/AppManager.java @@ -21,18 +21,21 @@ public class AppManager { * data storage or a simple Java data structure to (temporarily) store the data/objects during * runtime. */ - public static void initDB(boolean useMongoDB) { - if (useMongoDB) { + public static void initDb(boolean useMongoDb) { + if (useMongoDb) { try { - DBManager.connect(); + DbManager.connect(); } catch (ParseException e) { e.printStackTrace(); } } else { - DBManager.createVirtualDB(); + DbManager.createVirtualDb(); } } + /** + * Initialize caching policy + */ public static void initCachingPolicy(CachingPolicy policy) { cachingPolicy = policy; if (cachingPolicy == CachingPolicy.BEHIND) { @@ -50,15 +53,21 @@ public class AppManager { CacheStore.initCapacity(capacity); } - public static UserAccount find(String userID) { + /** + * Find user account + */ + public static UserAccount find(String userId) { if (cachingPolicy == CachingPolicy.THROUGH || cachingPolicy == CachingPolicy.AROUND) { - return CacheStore.readThrough(userID); + return CacheStore.readThrough(userId); } else if (cachingPolicy == CachingPolicy.BEHIND) { - return CacheStore.readThroughWithWriteBackPolicy(userID); + return CacheStore.readThroughWithWriteBackPolicy(userId); } return null; } + /** + * Save user account + */ public static void save(UserAccount userAccount) { if (cachingPolicy == CachingPolicy.THROUGH) { CacheStore.writeThrough(userAccount); diff --git a/caching/src/main/java/com/iluwatar/caching/CacheStore.java b/caching/src/main/java/com/iluwatar/caching/CacheStore.java index 2041ac14f..95278c746 100644 --- a/caching/src/main/java/com/iluwatar/caching/CacheStore.java +++ b/caching/src/main/java/com/iluwatar/caching/CacheStore.java @@ -9,73 +9,96 @@ import java.util.ArrayList; */ public class CacheStore { - static LRUCache cache = null; + static LruCache cache = null; + /** + * Init cache capacity + */ public static void initCapacity(int capacity) { - if (null == cache) - cache = new LRUCache(capacity); - else + if (null == cache) { + cache = new LruCache(capacity); + } else { cache.setCapacity(capacity); + } } - public static UserAccount readThrough(String userID) { - if (cache.contains(userID)) { + /** + * Get user account using read-through cache + */ + public static UserAccount readThrough(String userId) { + if (cache.contains(userId)) { System.out.println("# Cache Hit!"); - return cache.get(userID); + return cache.get(userId); } System.out.println("# Cache Miss!"); - UserAccount userAccount = DBManager.readFromDB(userID); - cache.set(userID, userAccount); + UserAccount userAccount = DbManager.readFromDb(userId); + cache.set(userId, userAccount); return userAccount; } + /** + * Get user account using write-through cache + */ public static void writeThrough(UserAccount userAccount) { - if (cache.contains(userAccount.getUserID())) { - DBManager.updateDB(userAccount); + if (cache.contains(userAccount.getUserId())) { + DbManager.updateDb(userAccount); } else { - DBManager.writeToDB(userAccount); + DbManager.writeToDb(userAccount); } - cache.set(userAccount.getUserID(), userAccount); + cache.set(userAccount.getUserId(), userAccount); } + /** + * Get user account using write-around cache + */ public static void writeAround(UserAccount userAccount) { - if (cache.contains(userAccount.getUserID())) { - DBManager.updateDB(userAccount); - cache.invalidate(userAccount.getUserID()); // Cache data has been updated -- remove older + if (cache.contains(userAccount.getUserId())) { + DbManager.updateDb(userAccount); + cache.invalidate(userAccount.getUserId()); // Cache data has been updated -- remove older // version from cache. } else { - DBManager.writeToDB(userAccount); + DbManager.writeToDb(userAccount); } } - public static UserAccount readThroughWithWriteBackPolicy(String userID) { - if (cache.contains(userID)) { + /** + * Get user account using read-through cache with write-back policy + */ + public static UserAccount readThroughWithWriteBackPolicy(String userId) { + if (cache.contains(userId)) { System.out.println("# Cache Hit!"); - return cache.get(userID); + return cache.get(userId); } System.out.println("# Cache Miss!"); - UserAccount userAccount = DBManager.readFromDB(userID); + UserAccount userAccount = DbManager.readFromDb(userId); if (cache.isFull()) { System.out.println("# Cache is FULL! Writing LRU data to DB..."); - UserAccount toBeWrittenToDB = cache.getLRUData(); - DBManager.upsertDB(toBeWrittenToDB); + UserAccount toBeWrittenToDb = cache.getLruData(); + DbManager.upsertDb(toBeWrittenToDb); } - cache.set(userID, userAccount); + cache.set(userId, userAccount); return userAccount; } + /** + * Set user account + */ public static void writeBehind(UserAccount userAccount) { - if (cache.isFull() && !cache.contains(userAccount.getUserID())) { + if (cache.isFull() && !cache.contains(userAccount.getUserId())) { System.out.println("# Cache is FULL! Writing LRU data to DB..."); - UserAccount toBeWrittenToDB = cache.getLRUData(); - DBManager.upsertDB(toBeWrittenToDB); + UserAccount toBeWrittenToDb = cache.getLruData(); + DbManager.upsertDb(toBeWrittenToDb); } - cache.set(userAccount.getUserID(), userAccount); + cache.set(userAccount.getUserId(), userAccount); } + /** + * Clears cache + */ public static void clearCache() { - if (null != cache) + if (null != cache) { cache.clear(); + } } /** @@ -83,14 +106,18 @@ public class CacheStore { */ public static void flushCache() { System.out.println("# flushCache..."); - if (null == cache) + if (null == cache) { return; + } ArrayList listOfUserAccounts = cache.getCacheDataInListForm(); for (UserAccount userAccount : listOfUserAccounts) { - DBManager.upsertDB(userAccount); + DbManager.upsertDb(userAccount); } } + /** + * Print user accounts + */ public static String print() { ArrayList listOfUserAccounts = cache.getCacheDataInListForm(); StringBuilder sb = new StringBuilder(); diff --git a/caching/src/main/java/com/iluwatar/caching/DBManager.java b/caching/src/main/java/com/iluwatar/caching/DbManager.java similarity index 73% rename from caching/src/main/java/com/iluwatar/caching/DBManager.java rename to caching/src/main/java/com/iluwatar/caching/DbManager.java index 07a5daeac..499ad5c3c 100644 --- a/caching/src/main/java/com/iluwatar/caching/DBManager.java +++ b/caching/src/main/java/com/iluwatar/caching/DbManager.java @@ -21,7 +21,7 @@ import com.mongodb.client.model.UpdateOptions; * during runtime (createVirtualDB()).

* */ -public class DBManager { +public class DbManager { private static MongoClient mongoClient; private static MongoDatabase db; @@ -29,21 +29,31 @@ public class DBManager { private static HashMap virtualDB; - public static void createVirtualDB() { + /** + * Create DB + */ + public static void createVirtualDb() { useMongoDB = false; virtualDB = new HashMap(); } + /** + * Connect to DB + */ public static void connect() throws ParseException { useMongoDB = true; mongoClient = new MongoClient(); db = mongoClient.getDatabase("test"); } - public static UserAccount readFromDB(String userID) { + /** + * Read user account from DB + */ + public static UserAccount readFromDb(String userId) { if (!useMongoDB) { - if (virtualDB.containsKey(userID)) - return virtualDB.get(userID); + if (virtualDB.containsKey(userId)) { + return virtualDB.get(userId); + } return null; } if (null == db) { @@ -54,18 +64,22 @@ public class DBManager { } } FindIterable iterable = - db.getCollection("user_accounts").find(new Document("userID", userID)); - if (iterable == null) + db.getCollection("user_accounts").find(new Document("userID", userId)); + if (iterable == null) { return null; + } Document doc = iterable.first(); UserAccount userAccount = - new UserAccount(userID, doc.getString("userName"), doc.getString("additionalInfo")); + new UserAccount(userId, doc.getString("userName"), doc.getString("additionalInfo")); return userAccount; } - public static void writeToDB(UserAccount userAccount) { + /** + * Write user account to DB + */ + public static void writeToDb(UserAccount userAccount) { if (!useMongoDB) { - virtualDB.put(userAccount.getUserID(), userAccount); + virtualDB.put(userAccount.getUserId(), userAccount); return; } if (null == db) { @@ -76,13 +90,16 @@ public class DBManager { } } db.getCollection("user_accounts").insertOne( - new Document("userID", userAccount.getUserID()).append("userName", + new Document("userID", userAccount.getUserId()).append("userName", userAccount.getUserName()).append("additionalInfo", userAccount.getAdditionalInfo())); } - public static void updateDB(UserAccount userAccount) { + /** + * Update DB + */ + public static void updateDb(UserAccount userAccount) { if (!useMongoDB) { - virtualDB.put(userAccount.getUserID(), userAccount); + virtualDB.put(userAccount.getUserId(), userAccount); return; } if (null == db) { @@ -93,7 +110,7 @@ public class DBManager { } } db.getCollection("user_accounts").updateOne( - new Document("userID", userAccount.getUserID()), + new Document("userID", userAccount.getUserId()), new Document("$set", new Document("userName", userAccount.getUserName()).append( "additionalInfo", userAccount.getAdditionalInfo()))); } @@ -102,9 +119,9 @@ public class DBManager { * * Insert data into DB if it does not exist. Else, update it. */ - public static void upsertDB(UserAccount userAccount) { + public static void upsertDb(UserAccount userAccount) { if (!useMongoDB) { - virtualDB.put(userAccount.getUserID(), userAccount); + virtualDB.put(userAccount.getUserId(), userAccount); return; } if (null == db) { @@ -115,8 +132,8 @@ public class DBManager { } } db.getCollection("user_accounts").updateOne( - new Document("userID", userAccount.getUserID()), - new Document("$set", new Document("userID", userAccount.getUserID()).append("userName", + new Document("userID", userAccount.getUserId()), + new Document("$set", new Document("userID", userAccount.getUserId()).append("userName", userAccount.getUserName()).append("additionalInfo", userAccount.getAdditionalInfo())), new UpdateOptions().upsert(true)); } diff --git a/caching/src/main/java/com/iluwatar/caching/LRUCache.java b/caching/src/main/java/com/iluwatar/caching/LruCache.java similarity index 70% rename from caching/src/main/java/com/iluwatar/caching/LRUCache.java rename to caching/src/main/java/com/iluwatar/caching/LruCache.java index 872f97256..e20275a40 100644 --- a/caching/src/main/java/com/iluwatar/caching/LRUCache.java +++ b/caching/src/main/java/com/iluwatar/caching/LruCache.java @@ -12,16 +12,16 @@ import java.util.HashMap; * LRU data is always at the end of the list. * */ -public class LRUCache { +public class LruCache { class Node { - String userID; + String userId; UserAccount userAccount; Node previous; Node next; - public Node(String userID, UserAccount userAccount) { - this.userID = userID; + public Node(String userId, UserAccount userAccount) { + this.userId = userId; this.userAccount = userAccount; } } @@ -31,13 +31,16 @@ public class LRUCache { Node head = null; Node end = null; - public LRUCache(int capacity) { + public LruCache(int capacity) { this.capacity = capacity; } - public UserAccount get(String userID) { - if (cache.containsKey(userID)) { - Node node = cache.get(userID); + /** + * Get user account + */ + public UserAccount get(String userId) { + if (cache.containsKey(userId)) { + Node node = cache.get(userId); remove(node); setHead(node); return node.userAccount; @@ -69,52 +72,63 @@ public class LRUCache { public void setHead(Node node) { node.next = head; node.previous = null; - if (head != null) + if (head != null) { head.previous = node; + } head = node; - if (end == null) + if (end == null) { end = head; + } } - public void set(String userID, UserAccount userAccount) { - if (cache.containsKey(userID)) { - Node old = cache.get(userID); + /** + * Set user account + */ + public void set(String userId, UserAccount userAccount) { + if (cache.containsKey(userId)) { + Node old = cache.get(userId); old.userAccount = userAccount; remove(old); setHead(old); } else { - Node newNode = new Node(userID, userAccount); + Node newNode = new Node(userId, userAccount); if (cache.size() >= capacity) { - System.out.println("# Cache is FULL! Removing " + end.userID + " from cache..."); - cache.remove(end.userID); // remove LRU data from cache. + System.out.println("# Cache is FULL! Removing " + end.userId + " from cache..."); + cache.remove(end.userId); // remove LRU data from cache. remove(end); setHead(newNode); } else { setHead(newNode); } - cache.put(userID, newNode); + cache.put(userId, newNode); } } - public boolean contains(String userID) { - return cache.containsKey(userID); + public boolean contains(String userId) { + return cache.containsKey(userId); } - public void invalidate(String userID) { - System.out.println("# " + userID + " has been updated! Removing older version from cache..."); - Node toBeRemoved = cache.get(userID); + /** + * Invalidate cache for user + */ + public void invalidate(String userId) { + System.out.println("# " + userId + " has been updated! Removing older version from cache..."); + Node toBeRemoved = cache.get(userId); remove(toBeRemoved); - cache.remove(userID); + cache.remove(userId); } public boolean isFull() { return cache.size() >= capacity; } - public UserAccount getLRUData() { + public UserAccount getLruData() { return end.userAccount; } + /** + * Clear cache + */ public void clear() { head = null; end = null; @@ -135,6 +149,9 @@ public class LRUCache { return listOfCacheData; } + /** + * Set cache capacity + */ public void setCapacity(int newCapacity) { if (capacity > newCapacity) { clear(); // Behavior can be modified to accommodate for decrease in cache size. For now, we'll diff --git a/caching/src/main/java/com/iluwatar/caching/UserAccount.java b/caching/src/main/java/com/iluwatar/caching/UserAccount.java index eff0878ad..0e281c429 100644 --- a/caching/src/main/java/com/iluwatar/caching/UserAccount.java +++ b/caching/src/main/java/com/iluwatar/caching/UserAccount.java @@ -6,22 +6,25 @@ package com.iluwatar.caching; * */ public class UserAccount { - private String userID; + private String userId; private String userName; private String additionalInfo; - public UserAccount(String userID, String userName, String additionalInfo) { - this.userID = userID; + /** + * Constructor + */ + public UserAccount(String userId, String userName, String additionalInfo) { + this.userId = userId; this.userName = userName; this.additionalInfo = additionalInfo; } - public String getUserID() { - return userID; + public String getUserId() { + return userId; } - public void setUserID(String userID) { - this.userID = userID; + public void setUserId(String userId) { + this.userId = userId; } public String getUserName() { @@ -42,6 +45,6 @@ public class UserAccount { @Override public String toString() { - return userID + ", " + userName + ", " + additionalInfo; + return userId + ", " + userName + ", " + additionalInfo; } } diff --git a/caching/src/test/java/com/iluwatar/caching/AppTest.java b/caching/src/test/java/com/iluwatar/caching/AppTest.java index ce5cddf08..35917da1c 100644 --- a/caching/src/test/java/com/iluwatar/caching/AppTest.java +++ b/caching/src/test/java/com/iluwatar/caching/AppTest.java @@ -16,7 +16,7 @@ public class AppTest { */ @Before public void setUp() { - AppManager.initDB(false); // VirtualDB (instead of MongoDB) was used in running the JUnit tests + AppManager.initDb(false); // VirtualDB (instead of MongoDB) was used in running the JUnit tests // to avoid Maven compilation errors. Set flag to true to run the // tests with MongoDB (provided that MongoDB is installed and socket // connection is open). diff --git a/callback/src/main/java/com/iluwatar/callback/App.java b/callback/src/main/java/com/iluwatar/callback/App.java index 81cb16f73..bc8b08cf0 100644 --- a/callback/src/main/java/com/iluwatar/callback/App.java +++ b/callback/src/main/java/com/iluwatar/callback/App.java @@ -9,6 +9,9 @@ package com.iluwatar.callback; */ public class App { + /** + * Program entry point + */ public static void main(String[] args) { Task task = new SimpleTask(); Callback callback = new Callback() { diff --git a/callback/src/main/java/com/iluwatar/callback/Task.java b/callback/src/main/java/com/iluwatar/callback/Task.java index d3be6c7a0..83e2cd4df 100644 --- a/callback/src/main/java/com/iluwatar/callback/Task.java +++ b/callback/src/main/java/com/iluwatar/callback/Task.java @@ -7,6 +7,9 @@ package com.iluwatar.callback; */ public abstract class Task { + /** + * Execute with callback + */ public final void executeWith(Callback callback) { execute(); if (callback != null) { diff --git a/chain/src/main/java/com/iluwatar/chain/RequestHandler.java b/chain/src/main/java/com/iluwatar/chain/RequestHandler.java index fd58b9ea8..12db1f51c 100644 --- a/chain/src/main/java/com/iluwatar/chain/RequestHandler.java +++ b/chain/src/main/java/com/iluwatar/chain/RequestHandler.java @@ -13,6 +13,9 @@ public abstract class RequestHandler { this.next = next; } + /** + * Request handler + */ public void handleRequest(Request req) { if (next != null) { next.handleRequest(req); diff --git a/checkstyle.xml b/checkstyle.xml index 0ff943d95..6d969afde 100644 --- a/checkstyle.xml +++ b/checkstyle.xml @@ -25,8 +25,10 @@ + + - + @@ -48,7 +50,7 @@ - + @@ -61,7 +63,7 @@ - + @@ -86,9 +88,6 @@ - - - @@ -97,42 +96,19 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + - - - - - - - @@ -180,11 +148,6 @@ - - - - @@ -195,7 +158,7 @@ - + diff --git a/command/src/main/java/com/iluwatar/command/Target.java b/command/src/main/java/com/iluwatar/command/Target.java index e12f758ff..731fe4d1f 100644 --- a/command/src/main/java/com/iluwatar/command/Target.java +++ b/command/src/main/java/com/iluwatar/command/Target.java @@ -30,6 +30,9 @@ public abstract class Target { @Override public abstract String toString(); + /** + * Print status + */ public void printStatus() { System.out.println(String.format("%s, [size=%s] [visibility=%s]", 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 edef8d3a9..fb6407c74 100644 --- a/command/src/main/java/com/iluwatar/command/Wizard.java +++ b/command/src/main/java/com/iluwatar/command/Wizard.java @@ -15,12 +15,18 @@ public class Wizard { public Wizard() {} + /** + * Cast spell + */ public void castSpell(Command command, Target target) { System.out.println(this + " casts " + command + " at " + target); command.execute(target); undoStack.offerLast(command); } + /** + * Undo last spell + */ public void undoLastSpell() { if (!undoStack.isEmpty()) { Command previousSpell = undoStack.pollLast(); @@ -30,6 +36,9 @@ public class Wizard { } } + /** + * Redo last spell + */ public void redoLastSpell() { if (!redoStack.isEmpty()) { Command previousSpell = redoStack.pollLast(); diff --git a/composite/src/main/java/com/iluwatar/composite/LetterComposite.java b/composite/src/main/java/com/iluwatar/composite/LetterComposite.java index 1fdf4fdb6..39655fa37 100644 --- a/composite/src/main/java/com/iluwatar/composite/LetterComposite.java +++ b/composite/src/main/java/com/iluwatar/composite/LetterComposite.java @@ -24,6 +24,9 @@ public abstract class LetterComposite { protected abstract void printThisAfter(); + /** + * Print + */ public void print() { printThisBefore(); for (LetterComposite letter : children) { diff --git a/composite/src/main/java/com/iluwatar/composite/Sentence.java b/composite/src/main/java/com/iluwatar/composite/Sentence.java index e6c626ea2..03f0c6949 100644 --- a/composite/src/main/java/com/iluwatar/composite/Sentence.java +++ b/composite/src/main/java/com/iluwatar/composite/Sentence.java @@ -9,6 +9,9 @@ import java.util.List; */ public class Sentence extends LetterComposite { + /** + * Constructor + */ public Sentence(List words) { for (Word w : words) { this.add(w); diff --git a/composite/src/main/java/com/iluwatar/composite/Word.java b/composite/src/main/java/com/iluwatar/composite/Word.java index 3060b0a1b..98c5f0b0d 100644 --- a/composite/src/main/java/com/iluwatar/composite/Word.java +++ b/composite/src/main/java/com/iluwatar/composite/Word.java @@ -9,6 +9,9 @@ import java.util.List; */ public class Word extends LetterComposite { + /** + * Constructor + */ public Word(List letters) { for (Letter l : letters) { this.add(l); diff --git a/dao/src/main/java/com/iluwatar/dao/App.java b/dao/src/main/java/com/iluwatar/dao/App.java index 2e115d8ce..a9351689d 100644 --- a/dao/src/main/java/com/iluwatar/dao/App.java +++ b/dao/src/main/java/com/iluwatar/dao/App.java @@ -21,7 +21,7 @@ import org.apache.log4j.Logger; */ public class App { - private static Logger LOGGER = Logger.getLogger(App.class); + private static Logger log = Logger.getLogger(App.class); /** * Program entry point. @@ -30,17 +30,17 @@ public class App { */ public static void main(final String[] args) { final CustomerDaoImpl customerDao = new CustomerDaoImpl(generateSampleCustomers()); - LOGGER.info("customerDao.getAllCustomers(): " + customerDao.getAllCustomers()); - LOGGER.info("customerDao.getCusterById(2): " + customerDao.getCustomerById(2)); + log.info("customerDao.getAllCustomers(): " + customerDao.getAllCustomers()); + log.info("customerDao.getCusterById(2): " + customerDao.getCustomerById(2)); final Customer customer = new Customer(4, "Dan", "Danson"); customerDao.addCustomer(customer); - LOGGER.info("customerDao.getAllCustomers(): " + customerDao.getAllCustomers()); + log.info("customerDao.getAllCustomers(): " + customerDao.getAllCustomers()); customer.setFirstName("Daniel"); customer.setLastName("Danielson"); customerDao.updateCustomer(customer); - LOGGER.info("customerDao.getAllCustomers(): " + customerDao.getAllCustomers()); + log.info("customerDao.getAllCustomers(): " + customerDao.getAllCustomers()); customerDao.deleteCustomer(customer); - LOGGER.info("customerDao.getAllCustomers(): " + customerDao.getAllCustomers()); + log.info("customerDao.getAllCustomers(): " + customerDao.getAllCustomers()); } /** diff --git a/dao/src/main/java/com/iluwatar/dao/Customer.java b/dao/src/main/java/com/iluwatar/dao/Customer.java index e6d7f7763..3d782016b 100644 --- a/dao/src/main/java/com/iluwatar/dao/Customer.java +++ b/dao/src/main/java/com/iluwatar/dao/Customer.java @@ -11,6 +11,9 @@ public class Customer { private String firstName; private String lastName; + /** + * Constructor + */ public Customer(final int id, final String firstName, final String lastName) { this.id = id; this.firstName = firstName; @@ -54,8 +57,9 @@ public class Customer { isEqual = true; } else if (o != null && (getClass() == o.getClass())) { final Customer customer = (Customer) o; - if (getId() == customer.getId()) + if (getId() == customer.getId()) { isEqual = true; + } } return isEqual; } diff --git a/dao/src/main/resources/log4j.xml b/dao/src/main/resources/log4j.xml index 136817f50..906e37170 100644 --- a/dao/src/main/resources/log4j.xml +++ b/dao/src/main/resources/log4j.xml @@ -1,17 +1,17 @@ + xmlns:log4j='http://jakarta.apache.org/log4j/'> - - - - - + + + + + - - - - + + + + \ No newline at end of file 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 0cc62c995..79bf6aefd 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 @@ -28,7 +28,7 @@ public class App { ExecutorService executorService = Executors.newFixedThreadPool(3); for (int i = 0; i < 3; i++) { executorService.execute(() -> { - while (inventory.addItem(new Item())); + while (inventory.addItem(new Item())) {}; }); } 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 0a17ac13d..1011b78b4 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 @@ -17,12 +17,18 @@ public class Inventory { private final List items; private final Lock lock; + /** + * Constructor + */ public Inventory(int inventorySize) { this.inventorySize = inventorySize; this.items = new ArrayList<>(inventorySize); this.lock = new ReentrantLock(); } + /** + * Add item + */ public boolean addItem(Item item) { if (items.size() < inventorySize) { lock.lock(); 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 1bc43263f..0b7b6dabc 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 @@ -77,8 +77,8 @@ public class InventoryTest { final ExecutorService executorService = Executors.newFixedThreadPool(THREAD_COUNT); for (int i = 0; i < THREAD_COUNT; i++) { executorService.execute(() -> { - while (inventory.addItem(new Item())) ; - }); + while (inventory.addItem(new Item())) {}; + }); } // Wait until all threads have finished 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 6514feb7f..98e19b770 100644 --- a/double-dispatch/src/main/java/com/iluwatar/doubledispatch/App.java +++ b/double-dispatch/src/main/java/com/iluwatar/doubledispatch/App.java @@ -5,22 +5,20 @@ import java.util.List; /** * - * When a message with a parameter is sent to an object, the resultant behaviour is defined by the - * implementation of that method in the receiver. Sometimes the behaviour must also be determined by - * the type of the parameter. + * When a message with a parameter is sent to an object, the resultant behaviour is defined by the implementation of + * that method in the receiver. Sometimes the behaviour must also be determined by the type of the parameter. *

- * One way to implement this would be to create multiple instanceof-checks for the methods - * parameter. However, this creates a maintenance issue. When new types are added we would also need - * to change the method's implementation and add a new instanceof-check. This violates the single - * responsibility principle - a class should have only one reason to change. + * One way to implement this would be to create multiple instanceof-checks for the methods parameter. However, this + * creates a maintenance issue. When new types are added we would also need to change the method's implementation and + * add a new instanceof-check. This violates the single responsibility principle - a class should have only one reason + * to change. *

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

- * In this example we have hierarchy of objects ({@link GameObject}) that can collide to each other. - * Each object has its own coordinates which are checked against the other objects' coordinates. If - * there is an overlap, then the objects collide utilizing the Double Dispatch pattern. + * In this example we have hierarchy of objects ({@link GameObject}) that can collide to each other. Each object has its + * own coordinates which are checked against the other objects' coordinates. If there is an overlap, then the objects + * collide utilizing the Double Dispatch pattern. * */ public class App { @@ -28,7 +26,8 @@ public class App { /** * Program entry point * - * @param args command line args + * @param args + * command line args */ public static void main(String[] args) { // initialize game objects and print their status @@ -42,8 +41,9 @@ public class App { // collision check objects.stream().forEach(o1 -> objects.stream().forEach(o2 -> { - if (o1 != o2 && o1.intersectsWith(o2)) + if (o1 != o2 && o1.intersectsWith(o2)) { o1.collision(o2); + } })); System.out.println(""); diff --git a/double-dispatch/src/main/java/com/iluwatar/doubledispatch/Rectangle.java b/double-dispatch/src/main/java/com/iluwatar/doubledispatch/Rectangle.java index db26265cc..e1e3eab7b 100644 --- a/double-dispatch/src/main/java/com/iluwatar/doubledispatch/Rectangle.java +++ b/double-dispatch/src/main/java/com/iluwatar/doubledispatch/Rectangle.java @@ -12,6 +12,9 @@ public class Rectangle { private int right; private int bottom; + /** + * Constructor + */ public Rectangle(int left, int top, int right, int bottom) { this.left = left; this.top = top; 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 5a3366e4e..6792a5d37 100644 --- a/double-dispatch/src/test/java/com/iluwatar/doubledispatch/CollisionTest.java +++ b/double-dispatch/src/test/java/com/iluwatar/doubledispatch/CollisionTest.java @@ -107,9 +107,9 @@ 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!" : - "Expected [" + targetName + "] not to be on fire after colliding with [" + otherName + "] but it was!"; + 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()); } @@ -126,9 +126,9 @@ public abstract class CollisionTest { final String targetName = target.getClass().getSimpleName(); 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 + "] not to be damaged after colliding with [" + otherName + "] but it was!"; + final String errorMessage = expectedDamage + ? "Expected [" + targetName + "] to be damaged after colliding with [" + otherName + "] but it was not!" + : "Expected [" + targetName + "] not to be damaged after colliding with [" + otherName + "] but it was!"; assertEquals(errorMessage, expectedDamage, target.isDamaged()); } diff --git a/event-aggregator/src/test/java/com/iluwatar/event/aggregator/EventEmitterTest.java b/event-aggregator/src/test/java/com/iluwatar/event/aggregator/EventEmitterTest.java index 09acf7442..bd13bd248 100644 --- a/event-aggregator/src/test/java/com/iluwatar/event/aggregator/EventEmitterTest.java +++ b/event-aggregator/src/test/java/com/iluwatar/event/aggregator/EventEmitterTest.java @@ -63,6 +63,37 @@ public abstract class EventEmitterTest { testAllDaysWithDefaultObserver(specialDay, event); } + /** + * Pass each week of the day, day by day to the event emitter and verify of the given observers + * received the correct event on the special day. + * + * @param specialDay The special day on which an event is emitted + * @param event The expected event emitted by the test object + * @param emitter The event emitter + * @param observers The registered observer mocks + */ + private void testAllDays(final Weekday specialDay, final Event event, final E emitter, + final EventObserver... observers) { + + for (final Weekday weekday : Weekday.values()) { + // Pass each week of the day, day by day to the event emitter + emitter.timePasses(weekday); + + if (weekday == specialDay) { + // On a special day, every observer should have received the event + for (final EventObserver observer : observers) { + verify(observer, times(1)).onEvent(eq(event)); + } + } else { + // On any other normal day, the observers should have received nothing at all + verifyZeroInteractions(observers); + } + } + + // The observers should not have received any additional events after the week + verifyNoMoreInteractions(observers); + } + /** * Go over every day of the month, and check if the event is emitted on the given day. Use an * event emitter without a default observer @@ -99,35 +130,4 @@ public abstract class EventEmitterTest { testAllDays(specialDay, event, emitter, defaultObserver, observer1, observer2); } - /** - * Pass each week of the day, day by day to the event emitter and verify of the given observers - * received the correct event on the special day. - * - * @param specialDay The special day on which an event is emitted - * @param event The expected event emitted by the test object - * @param emitter The event emitter - * @param observers The registered observer mocks - */ - private void testAllDays(final Weekday specialDay, final Event event, final E emitter, - final EventObserver... observers) { - - for (final Weekday weekday : Weekday.values()) { - // Pass each week of the day, day by day to the event emitter - emitter.timePasses(weekday); - - if (weekday == specialDay) { - // On a special day, every observer should have received the event - for (final EventObserver observer : observers) { - verify(observer, times(1)).onEvent(eq(event)); - } - } else { - // On any other normal day, the observers should have received nothing at all - verifyZeroInteractions(observers); - } - } - - // The observers should not have received any additional events after the week - verifyNoMoreInteractions(observers); - } - } diff --git a/event-aggregator/src/test/java/com/iluwatar/event/aggregator/KingsHandTest.java b/event-aggregator/src/test/java/com/iluwatar/event/aggregator/KingsHandTest.java index 992ee4cf5..edec65b65 100644 --- a/event-aggregator/src/test/java/com/iluwatar/event/aggregator/KingsHandTest.java +++ b/event-aggregator/src/test/java/com/iluwatar/event/aggregator/KingsHandTest.java @@ -24,7 +24,7 @@ public class KingsHandTest extends EventEmitterTest { } /** - * The {@link KingsHand} is both an {@EventEmitter} as an {@link EventObserver} so verify if every + * The {@link KingsHand} is both an {@link EventEmitter} as an {@link EventObserver} so verify if every * event received is passed up to it's superior, in most cases {@link KingJoffrey} but now just a * mocked observer. */ diff --git a/execute-around/src/main/java/com/iluwatar/execute/around/App.java b/execute-around/src/main/java/com/iluwatar/execute/around/App.java index 4a0648dbe..4695b8df5 100644 --- a/execute-around/src/main/java/com/iluwatar/execute/around/App.java +++ b/execute-around/src/main/java/com/iluwatar/execute/around/App.java @@ -17,9 +17,6 @@ public class App { /** * Program entry point - * - * @param args command line args - * @throws IOException */ public static void main(String[] args) throws IOException { diff --git a/execute-around/src/main/java/com/iluwatar/execute/around/SimpleFileWriter.java b/execute-around/src/main/java/com/iluwatar/execute/around/SimpleFileWriter.java index be89ff9ce..e1a9073ef 100644 --- a/execute-around/src/main/java/com/iluwatar/execute/around/SimpleFileWriter.java +++ b/execute-around/src/main/java/com/iluwatar/execute/around/SimpleFileWriter.java @@ -11,6 +11,9 @@ import java.io.IOException; */ public class SimpleFileWriter { + /** + * Constructor + */ public SimpleFileWriter(String filename, FileWriterAction action) throws IOException { FileWriter writer = new FileWriter(filename); try { diff --git a/execute-around/src/test/java/com/iluwatar/execute/around/SimpleFileWriterTest.java b/execute-around/src/test/java/com/iluwatar/execute/around/SimpleFileWriterTest.java index 168026b65..0c959a716 100644 --- a/execute-around/src/test/java/com/iluwatar/execute/around/SimpleFileWriterTest.java +++ b/execute-around/src/test/java/com/iluwatar/execute/around/SimpleFileWriterTest.java @@ -65,11 +65,11 @@ public class SimpleFileWriterTest { * Verify if an {@link IOException} during the write ripples through */ @Test(expected = IOException.class) - public void testIOException() throws Exception { + public void testIoException() throws Exception { final File temporaryFile = this.testFolder.newFile(); new SimpleFileWriter(temporaryFile.getPath(), writer -> { - throw new IOException(""); - }); + throw new IOException(""); + }); } } diff --git a/facade/src/main/java/com/iluwatar/facade/DwarvenGoldmineFacade.java b/facade/src/main/java/com/iluwatar/facade/DwarvenGoldmineFacade.java index d6b653eaa..fd37e40c5 100644 --- a/facade/src/main/java/com/iluwatar/facade/DwarvenGoldmineFacade.java +++ b/facade/src/main/java/com/iluwatar/facade/DwarvenGoldmineFacade.java @@ -16,6 +16,9 @@ public class DwarvenGoldmineFacade { private final List workers; + /** + * Constructor + */ public DwarvenGoldmineFacade() { workers = new ArrayList<>(); workers.add(new DwarvenGoldDigger()); diff --git a/facade/src/main/java/com/iluwatar/facade/DwarvenMineWorker.java b/facade/src/main/java/com/iluwatar/facade/DwarvenMineWorker.java index d329fe84b..3190c9365 100644 --- a/facade/src/main/java/com/iluwatar/facade/DwarvenMineWorker.java +++ b/facade/src/main/java/com/iluwatar/facade/DwarvenMineWorker.java @@ -46,6 +46,9 @@ public abstract class DwarvenMineWorker { } } + /** + * Perform actions + */ public void action(Action... actions) { for (Action action : actions) { action(action); 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 bdff83e17..cb5254f91 100644 --- a/fluentinterface/src/main/java/com/iluwatar/fluentinterface/app/App.java +++ b/fluentinterface/src/main/java/com/iluwatar/fluentinterface/app/App.java @@ -1,15 +1,19 @@ package com.iluwatar.fluentinterface.app; +import static java.lang.String.valueOf; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; +import java.util.StringJoiner; +import java.util.function.Function; +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 java.util.*; -import java.util.function.Function; -import java.util.function.Predicate; - -import static java.lang.String.valueOf; - /** * The Fluent Interface pattern is useful when you want to provide an easy readable, flowing API. * Those interfaces tend to mimic domain specific languages, so they can nearly be read as human @@ -24,6 +28,9 @@ import static java.lang.String.valueOf; */ public class App { + /** + * Program entry point + */ public static void main(String[] args) { List integerList = new ArrayList<>(); diff --git a/fluentinterface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/lazy/DecoratingIterator.java b/fluentinterface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/lazy/DecoratingIterator.java index e80356d8e..dae300c4e 100644 --- a/fluentinterface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/lazy/DecoratingIterator.java +++ b/fluentinterface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/lazy/DecoratingIterator.java @@ -5,8 +5,6 @@ import java.util.Iterator; /** * This class is used to realize LazyFluentIterables. It decorates a given iterator. Does not * support consecutive hasNext() calls. - * - * @param */ public abstract class DecoratingIterator implements Iterator { @@ -16,8 +14,6 @@ public abstract class DecoratingIterator implements Iterator { /** * Creates an iterator that decorates the given iterator. - * - * @param fromIterator */ public DecoratingIterator(Iterator fromIterator) { this.fromIterator = fromIterator; diff --git a/fluentinterface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/simple/SimpleFluentIterable.java b/fluentinterface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/simple/SimpleFluentIterable.java index 19283152e..ef1859529 100644 --- a/fluentinterface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/simple/SimpleFluentIterable.java +++ b/fluentinterface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/simple/SimpleFluentIterable.java @@ -1,12 +1,16 @@ package com.iluwatar.fluentinterface.fluentiterable.simple; -import com.iluwatar.fluentinterface.fluentiterable.FluentIterable; - -import java.util.*; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Optional; +import java.util.Spliterator; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; +import com.iluwatar.fluentinterface.fluentiterable.FluentIterable; + /** * This is a simple implementation of the FluentIterable interface. It evaluates all chained * operations eagerly. This implementation would be costly to be utilized in real applications. diff --git a/fluentinterface/src/test/java/com/iluwatar/fluentinterface/fluentiterable/FluentIterableTest.java b/fluentinterface/src/test/java/com/iluwatar/fluentinterface/fluentiterable/FluentIterableTest.java index 7d4cb0530..9159e90b0 100644 --- a/fluentinterface/src/test/java/com/iluwatar/fluentinterface/fluentiterable/FluentIterableTest.java +++ b/fluentinterface/src/test/java/com/iluwatar/fluentinterface/fluentiterable/FluentIterableTest.java @@ -26,7 +26,7 @@ import static org.mockito.Mockito.verifyNoMoreInteractions; public abstract class FluentIterableTest { /** - * Create a new {@link FluentIterable} from the given integers + * Create a new {@link FluentIterable} from the given integers * * @param integers The integers * @return The new iterable, use for testing diff --git a/flux/src/main/java/com/iluwatar/flux/dispatcher/Dispatcher.java b/flux/src/main/java/com/iluwatar/flux/dispatcher/Dispatcher.java index 26c836b0e..1ff624e11 100644 --- a/flux/src/main/java/com/iluwatar/flux/dispatcher/Dispatcher.java +++ b/flux/src/main/java/com/iluwatar/flux/dispatcher/Dispatcher.java @@ -31,6 +31,9 @@ public class Dispatcher { stores.add(store); } + /** + * Menu item selected handler + */ public void menuItemSelected(MenuItem menuItem) { dispatchAction(new MenuAction(menuItem)); switch (menuItem) { diff --git a/flyweight/src/main/java/com/iluwatar/flyweight/AlchemistShop.java b/flyweight/src/main/java/com/iluwatar/flyweight/AlchemistShop.java index a48abbcb0..8418e01e6 100644 --- a/flyweight/src/main/java/com/iluwatar/flyweight/AlchemistShop.java +++ b/flyweight/src/main/java/com/iluwatar/flyweight/AlchemistShop.java @@ -14,6 +14,9 @@ public class AlchemistShop { private List topShelf; private List bottomShelf; + /** + * Constructor + */ public AlchemistShop() { topShelf = new ArrayList<>(); bottomShelf = new ArrayList<>(); @@ -58,6 +61,9 @@ public class AlchemistShop { return Collections.unmodifiableList(this.bottomShelf); } + /** + * Enumerate potions + */ public void enumerate() { System.out.println("Enumerating top shelf potions\n"); diff --git a/front-controller/src/main/java/com/iluwatar/front/controller/App.java b/front-controller/src/main/java/com/iluwatar/front/controller/App.java index 18a92d37d..1beac119c 100644 --- a/front-controller/src/main/java/com/iluwatar/front/controller/App.java +++ b/front-controller/src/main/java/com/iluwatar/front/controller/App.java @@ -2,32 +2,34 @@ package com.iluwatar.front.controller; /** * - * The Front Controller is a presentation tier pattern. Essentially it defines a - * controller that handles all requests for a web site. + * The Front Controller is a presentation tier pattern. Essentially it defines a controller that + * handles all requests for a web site. *

- * The Front Controller pattern consolidates request handling through a single handler - * object ({@link FrontController}). This object can carry out the common the behavior such as + * The Front Controller pattern consolidates request handling through a single handler object ( + * {@link FrontController}). This object can carry out the common the behavior such as * authorization, request logging and routing requests to corresponding views. *

- * Typically the requests are mapped to command objects ({@link Command}) which then display - * the correct view ({@link View}). + * Typically the requests are mapped to command objects ({@link Command}) which then display the + * correct view ({@link View}). *

* In this example we have implemented two views: {@link ArcherView} and {@link CatapultView}. These - * are displayed by sending correct request to the {@link FrontController} object. For example, - * the {@link ArcherView} gets displayed when {@link FrontController} receives request "Archer". When + * are displayed by sending correct request to the {@link FrontController} object. For example, the + * {@link ArcherView} gets displayed when {@link FrontController} receives request "Archer". When * the request is unknown, we display the error view ({@link ErrorView}). * */ public class App { - - /** - * Program entry point - * @param args command line args - */ - public static void main(String[] args) { - FrontController controller = new FrontController(); - controller.handleRequest("Archer"); - controller.handleRequest("Catapult"); - controller.handleRequest("foobar"); - } + + /** + * Program entry point + * + * @param args + * command line args + */ + public static void main(String[] args) { + FrontController controller = new FrontController(); + controller.handleRequest("Archer"); + controller.handleRequest("Catapult"); + controller.handleRequest("foobar"); + } } diff --git a/front-controller/src/main/java/com/iluwatar/front/controller/ApplicationException.java b/front-controller/src/main/java/com/iluwatar/front/controller/ApplicationException.java index b3963d8e9..bb44d34f0 100644 --- a/front-controller/src/main/java/com/iluwatar/front/controller/ApplicationException.java +++ b/front-controller/src/main/java/com/iluwatar/front/controller/ApplicationException.java @@ -7,9 +7,9 @@ package com.iluwatar.front.controller; */ public class ApplicationException extends RuntimeException { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - public ApplicationException(Throwable cause) { - super(cause); - } + public ApplicationException(Throwable cause) { + super(cause); + } } diff --git a/front-controller/src/main/java/com/iluwatar/front/controller/ArcherCommand.java b/front-controller/src/main/java/com/iluwatar/front/controller/ArcherCommand.java index 117aa0c8c..8396d5cfc 100644 --- a/front-controller/src/main/java/com/iluwatar/front/controller/ArcherCommand.java +++ b/front-controller/src/main/java/com/iluwatar/front/controller/ArcherCommand.java @@ -7,8 +7,8 @@ package com.iluwatar.front.controller; */ public class ArcherCommand implements Command { - @Override - public void process() { - new ArcherView().display(); - } + @Override + public void process() { + new ArcherView().display(); + } } 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 d8cae33c1..d16fe8b71 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 @@ -7,8 +7,8 @@ package com.iluwatar.front.controller; */ public class ArcherView implements View { - @Override - public void display() { - System.out.println("Displaying archers"); - } + @Override + public void display() { + System.out.println("Displaying archers"); + } } diff --git a/front-controller/src/main/java/com/iluwatar/front/controller/CatapultCommand.java b/front-controller/src/main/java/com/iluwatar/front/controller/CatapultCommand.java index fae5d1753..b5ad9e37c 100644 --- a/front-controller/src/main/java/com/iluwatar/front/controller/CatapultCommand.java +++ b/front-controller/src/main/java/com/iluwatar/front/controller/CatapultCommand.java @@ -7,8 +7,8 @@ package com.iluwatar.front.controller; */ public class CatapultCommand implements Command { - @Override - public void process() { - new CatapultView().display(); - } + @Override + public void process() { + new CatapultView().display(); + } } 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 9ad94d522..161b4ed4e 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 @@ -7,8 +7,8 @@ package com.iluwatar.front.controller; */ public class CatapultView implements View { - @Override - public void display() { - System.out.println("Displaying catapults"); - } + @Override + public void display() { + System.out.println("Displaying catapults"); + } } diff --git a/front-controller/src/main/java/com/iluwatar/front/controller/Command.java b/front-controller/src/main/java/com/iluwatar/front/controller/Command.java index 95bd00129..2ad41a629 100644 --- a/front-controller/src/main/java/com/iluwatar/front/controller/Command.java +++ b/front-controller/src/main/java/com/iluwatar/front/controller/Command.java @@ -6,6 +6,6 @@ package com.iluwatar.front.controller; * */ public interface Command { - - void process(); + + void process(); } 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 04c31dd34..c1045c821 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 @@ -7,8 +7,8 @@ package com.iluwatar.front.controller; */ public class ErrorView implements View { - @Override - public void display() { - System.out.println("Error 500"); - } + @Override + public void display() { + System.out.println("Error 500"); + } } diff --git a/front-controller/src/main/java/com/iluwatar/front/controller/FrontController.java b/front-controller/src/main/java/com/iluwatar/front/controller/FrontController.java index 0c6c132f2..6b84d7f78 100644 --- a/front-controller/src/main/java/com/iluwatar/front/controller/FrontController.java +++ b/front-controller/src/main/java/com/iluwatar/front/controller/FrontController.java @@ -2,33 +2,33 @@ package com.iluwatar.front.controller; /** * - * FrontController is the handler class that takes in all the requests and - * renders the correct response. + * FrontController is the handler class that takes in all the requests and renders the correct + * response. * */ public class FrontController { - - public void handleRequest(String request) { - Command command = getCommand(request); - command.process(); - } - - private Command getCommand(String request) { - Class commandClass = getCommandClass(request); - try { - return (Command) commandClass.newInstance(); - } catch (Exception e) { - throw new ApplicationException(e); - } - } - - private Class getCommandClass(String request) { - Class result; - try { - result = Class.forName("com.iluwatar.front.controller." + request + "Command"); - } catch (ClassNotFoundException e) { - result = UnknownCommand.class; - } - return result; - } + + public void handleRequest(String request) { + Command command = getCommand(request); + command.process(); + } + + private Command getCommand(String request) { + Class commandClass = getCommandClass(request); + try { + return (Command) commandClass.newInstance(); + } catch (Exception e) { + throw new ApplicationException(e); + } + } + + private Class getCommandClass(String request) { + Class result; + try { + result = Class.forName("com.iluwatar.front.controller." + request + "Command"); + } catch (ClassNotFoundException e) { + result = UnknownCommand.class; + } + return result; + } } diff --git a/front-controller/src/main/java/com/iluwatar/front/controller/UnknownCommand.java b/front-controller/src/main/java/com/iluwatar/front/controller/UnknownCommand.java index f8f93e7e0..d800d4db0 100644 --- a/front-controller/src/main/java/com/iluwatar/front/controller/UnknownCommand.java +++ b/front-controller/src/main/java/com/iluwatar/front/controller/UnknownCommand.java @@ -7,8 +7,8 @@ package com.iluwatar.front.controller; */ public class UnknownCommand implements Command { - @Override - public void process() { - new ErrorView().display(); - } + @Override + public void process() { + new ErrorView().display(); + } } diff --git a/front-controller/src/main/java/com/iluwatar/front/controller/View.java b/front-controller/src/main/java/com/iluwatar/front/controller/View.java index 29c5f0fcb..55bb187ce 100644 --- a/front-controller/src/main/java/com/iluwatar/front/controller/View.java +++ b/front-controller/src/main/java/com/iluwatar/front/controller/View.java @@ -7,5 +7,5 @@ package com.iluwatar.front.controller; */ public interface View { - void display(); + void display(); } diff --git a/front-controller/src/test/java/com/iluwatar/front/controller/AppTest.java b/front-controller/src/test/java/com/iluwatar/front/controller/AppTest.java index 2c28aa8ce..f858a797d 100644 --- a/front-controller/src/test/java/com/iluwatar/front/controller/AppTest.java +++ b/front-controller/src/test/java/com/iluwatar/front/controller/AppTest.java @@ -10,10 +10,10 @@ import com.iluwatar.front.controller.App; * */ public class AppTest { - - @Test - public void test() { - String[] args = {}; - App.main(args); - } + + @Test + public void test() { + String[] args = {}; + App.main(args); + } } diff --git a/front-controller/src/test/java/com/iluwatar/front/controller/ApplicationExceptionTest.java b/front-controller/src/test/java/com/iluwatar/front/controller/ApplicationExceptionTest.java index 18bdf0d13..4b038cfda 100644 --- a/front-controller/src/test/java/com/iluwatar/front/controller/ApplicationExceptionTest.java +++ b/front-controller/src/test/java/com/iluwatar/front/controller/ApplicationExceptionTest.java @@ -1,8 +1,8 @@ package com.iluwatar.front.controller; -import org.junit.Test; +import static org.junit.Assert.assertSame; -import static org.junit.Assert.*; +import org.junit.Test; /** * Date: 12/13/15 - 1:35 PM 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 80f2eefb2..b67b602ca 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 @@ -21,17 +21,15 @@ import java.util.concurrent.LinkedBlockingQueue; * *

* APPLICABILITY
- *

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

* IMPLEMENTATION
@@ -121,6 +119,7 @@ public class App { try { Thread.sleep(i); } catch (InterruptedException e) { + System.out.println(e); } return (i) * (i + 1) / 2; } diff --git a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/AddressFilter.java b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/AddressFilter.java index c1aa0780b..38a762483 100644 --- a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/AddressFilter.java +++ b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/AddressFilter.java @@ -14,7 +14,8 @@ public class AddressFilter extends AbstractFilter { String result = super.execute(order); if (order.getAddress() == null || order.getAddress().isEmpty()) { return result + "Invalid address! "; - } else + } else { return result; + } } } diff --git a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Client.java b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Client.java index 02499ed0a..5934da75c 100644 --- a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Client.java +++ b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Client.java @@ -32,8 +32,12 @@ public class Client extends JFrame { private JLabel jl; private JTextField[] jtFields; private JTextArea[] jtAreas; - private JButton clearButton, processButton; + private JButton clearButton; + private JButton processButton; + /** + * Constructor + */ public Client() { super("Client System"); setDefaultCloseOperation(EXIT_ON_CLOSE); diff --git a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Filter.java b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Filter.java index 9496bde36..a1ea5b4ee 100644 --- a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Filter.java +++ b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Filter.java @@ -11,30 +11,21 @@ public interface Filter { /** * Execute order processing filter. - * - * @param order - * @return empty string on success, otherwise error message. */ String execute(Order order); /** * Set next filter in chain after this. - * - * @param filter */ void setNext(Filter filter); /** * Get next filter in chain after this. - * - * @return */ Filter getNext(); /** * Get last filter in the chain. - * - * @return */ Filter getLast(); } diff --git a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/FilterChain.java b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/FilterChain.java index 987678cc7..b180579d2 100644 --- a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/FilterChain.java +++ b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/FilterChain.java @@ -12,10 +12,16 @@ public class FilterChain { private final Target target; + /** + * Constructor + */ public FilterChain(Target target) { this.target = target; } + /** + * Adds filter + */ public void addFilter(Filter filter) { if (chain == null) { chain = filter; @@ -24,6 +30,9 @@ public class FilterChain { } } + /** + * Execute filter chain + */ public String execute(Order order) { if (chain != null) { return chain.execute(order); diff --git a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Order.java b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Order.java index 5b30fee35..53d1a3dd9 100644 --- a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Order.java +++ b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Order.java @@ -14,6 +14,9 @@ public class Order { public Order() {} + /** + * Constructor + */ public Order(String name, String contactNumber, String address, String depositNumber, String order) { this.name = name; this.contactNumber = contactNumber; diff --git a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Target.java b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Target.java index cb96cd6e0..ffb13c160 100644 --- a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Target.java +++ b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Target.java @@ -29,6 +29,9 @@ public class Target extends JFrame { private DefaultTableModel dtm; private JButton del; + /** + * Constructor + */ public Target() { super("Order System"); setDefaultCloseOperation(EXIT_ON_CLOSE); @@ -67,8 +70,9 @@ public class Target extends JFrame { @Override public void actionPerformed(ActionEvent e) { int temp = jt.getSelectedRow(); - if (temp == -1) + if (temp == -1) { return; + } int temp2 = jt.getSelectedRowCount(); for (int i = 0; i < temp2; i++) { dtm.removeRow(temp); diff --git a/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/FilterTest.java b/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/FilterTest.java index f15760f08..71d9bf250 100644 --- a/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/FilterTest.java +++ b/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/FilterTest.java @@ -73,6 +73,9 @@ public class FilterTest { private final Order order; private final String result; + /** + * Constructor + */ public FilterTest(Filter filter, Order order, String result) { this.filter = filter; this.order = order; diff --git a/interpreter/src/main/java/com/iluwatar/interpreter/App.java b/interpreter/src/main/java/com/iluwatar/interpreter/App.java index 2f88951f1..e4e238c15 100644 --- a/interpreter/src/main/java/com/iluwatar/interpreter/App.java +++ b/interpreter/src/main/java/com/iluwatar/interpreter/App.java @@ -55,6 +55,9 @@ public class App { return s.equals("+") || s.equals("-") || s.equals("*"); } + /** + * Get expression for string + */ public static Expression getOperatorInstance(String s, Expression left, Expression right) { switch (s) { case "+": @@ -63,7 +66,8 @@ public class App { return new MinusExpression(left, right); case "*": return new MultiplyExpression(left, right); + default: + return new MultiplyExpression(left, right); } - return null; } } diff --git a/interpreter/src/test/java/com/iluwatar/interpreter/ExpressionTest.java b/interpreter/src/test/java/com/iluwatar/interpreter/ExpressionTest.java index 2cdee9966..150596cd8 100644 --- a/interpreter/src/test/java/com/iluwatar/interpreter/ExpressionTest.java +++ b/interpreter/src/test/java/com/iluwatar/interpreter/ExpressionTest.java @@ -27,9 +27,9 @@ public abstract class ExpressionTest { for (int i = -10; i < 10; i++) { for (int j = -10; j < 10; j++) { testData.add(new Object[]{ - new NumberExpression(i), - new NumberExpression(j), - resultCalc.apply(i, j) + new NumberExpression(i), + new NumberExpression(j), + resultCalc.apply(i, j) }); } } diff --git a/iterator/src/main/java/com/iluwatar/iterator/App.java b/iterator/src/main/java/com/iluwatar/iterator/App.java index c9c5fa521..467040ca6 100644 --- a/iterator/src/main/java/com/iluwatar/iterator/App.java +++ b/iterator/src/main/java/com/iluwatar/iterator/App.java @@ -20,28 +20,28 @@ public class App { public static void main(String[] args) { TreasureChest chest = new TreasureChest(); - ItemIterator ringIterator = chest.Iterator(ItemType.RING); + ItemIterator ringIterator = chest.iterator(ItemType.RING); while (ringIterator.hasNext()) { System.out.println(ringIterator.next()); } System.out.println("----------"); - ItemIterator potionIterator = chest.Iterator(ItemType.POTION); + ItemIterator potionIterator = chest.iterator(ItemType.POTION); while (potionIterator.hasNext()) { System.out.println(potionIterator.next()); } System.out.println("----------"); - ItemIterator weaponIterator = chest.Iterator(ItemType.WEAPON); + ItemIterator weaponIterator = chest.iterator(ItemType.WEAPON); while (weaponIterator.hasNext()) { System.out.println(weaponIterator.next()); } System.out.println("----------"); - ItemIterator it = chest.Iterator(ItemType.ANY); + ItemIterator it = chest.iterator(ItemType.ANY); while (it.hasNext()) { System.out.println(it.next()); } diff --git a/iterator/src/main/java/com/iluwatar/iterator/TreasureChest.java b/iterator/src/main/java/com/iluwatar/iterator/TreasureChest.java index 02496e33c..6b5c54a5a 100644 --- a/iterator/src/main/java/com/iluwatar/iterator/TreasureChest.java +++ b/iterator/src/main/java/com/iluwatar/iterator/TreasureChest.java @@ -12,6 +12,9 @@ public class TreasureChest { private List items; + /** + * Constructor + */ public TreasureChest() { items = new ArrayList<>(); items.add(new Item(ItemType.POTION, "Potion of courage")); @@ -26,10 +29,13 @@ public class TreasureChest { items.add(new Item(ItemType.WEAPON, "Dagger of poison")); } - ItemIterator Iterator(ItemType type) { - return new TreasureChestItemIterator(this, type); + ItemIterator iterator(ItemType itemType) { + return new TreasureChestItemIterator(this, itemType); } + /** + * Get all items + */ public List getItems() { ArrayList list = new ArrayList<>(); list.addAll(items); diff --git a/iterator/src/main/java/com/iluwatar/iterator/TreasureChestItemIterator.java b/iterator/src/main/java/com/iluwatar/iterator/TreasureChestItemIterator.java index 39c12ab44..a8303f308 100644 --- a/iterator/src/main/java/com/iluwatar/iterator/TreasureChestItemIterator.java +++ b/iterator/src/main/java/com/iluwatar/iterator/TreasureChestItemIterator.java @@ -13,6 +13,9 @@ public class TreasureChestItemIterator implements ItemIterator { private int idx; private ItemType type; + /** + * Constructor + */ public TreasureChestItemIterator(TreasureChest chest, ItemType type) { this.chest = chest; this.type = type; diff --git a/iterator/src/test/java/com/iluwatar/iterator/TreasureChestTest.java b/iterator/src/test/java/com/iluwatar/iterator/TreasureChestTest.java index a32066ea8..a2102a2e2 100644 --- a/iterator/src/test/java/com/iluwatar/iterator/TreasureChestTest.java +++ b/iterator/src/test/java/com/iluwatar/iterator/TreasureChestTest.java @@ -60,7 +60,7 @@ public class TreasureChestTest { @Test public void testIterator() { final TreasureChest chest = new TreasureChest(); - final ItemIterator iterator = chest.Iterator(expectedItem.getType()); + final ItemIterator iterator = chest.iterator(expectedItem.getType()); assertNotNull(iterator); while (iterator.hasNext()) { diff --git a/layers/src/main/java/com/iluwatar/layers/App.java b/layers/src/main/java/com/iluwatar/layers/App.java index d175553f7..ecb532510 100644 --- a/layers/src/main/java/com/iluwatar/layers/App.java +++ b/layers/src/main/java/com/iluwatar/layers/App.java @@ -4,31 +4,31 @@ import java.util.Arrays; /** * - * Layers is an architectural style where software responsibilities are divided among the different - * layers of the application. + * Layers is an architectural style where software responsibilities are divided among the different layers of the + * application. *

- * This example demonstrates a traditional 3-layer architecture consisting of data access layer, - * business layer and presentation layer. + * This example demonstrates a traditional 3-layer architecture consisting of data access layer, business layer and + * presentation layer. *

- * The data access layer is formed of Spring Data repositories CakeDao, - * CakeToppingDao and CakeLayerDao. The repositories can be used for CRUD - * operations on cakes, cake toppings and cake layers respectively. + * The data access layer is formed of Spring Data repositories CakeDao, CakeToppingDao and + * CakeLayerDao. The repositories can be used for CRUD operations on cakes, cake toppings and cake layers + * respectively. *

- * The business layer is built on top of the data access layer. CakeBakingService - * offers methods to retrieve available cake toppings and cake layers and baked cakes. Also the - * service is used to create new cakes out of cake toppings and cake layers. + * The business layer is built on top of the data access layer. CakeBakingService offers methods to + * retrieve available cake toppings and cake layers and baked cakes. Also the service is used to create new cakes out of + * cake toppings and cake layers. *

- * The presentation layer is built on the business layer and in this example it simply lists the - * cakes that have been baked. + * The presentation layer is built on the business layer and in this example it simply lists the cakes that have been + * baked. *

- * We have applied so called strict layering which means that the layers can only access the classes - * directly beneath them. This leads the solution to create an additional set of DTOs ( - * CakeInfo, CakeToppingInfo, CakeLayerInfo) to translate - * data between layers. In other words, CakeBakingService cannot return entities ( - * Cake, CakeTopping, CakeLayer) directly since these reside - * on data access layer but instead translates these into business layer DTOs (CakeInfo, CakeToppingInfo, CakeLayerInfo) and returns them instead. This way - * the presentation layer does not have any knowledge of other layers than the business layer and - * thus is not affected by changes to them. + * We have applied so called strict layering which means that the layers can only access the classes directly beneath + * them. This leads the solution to create an additional set of DTOs ( CakeInfo, + * CakeToppingInfo, CakeLayerInfo) to translate data between layers. In other words, + * CakeBakingService cannot return entities ( Cake, CakeTopping, + * CakeLayer) directly since these reside on data access layer but instead translates these into business + * layer DTOs (CakeInfo, CakeToppingInfo, CakeLayerInfo) and returns them + * instead. This way the presentation layer does not have any knowledge of other layers than the business layer and thus + * is not affected by changes to them. * * @see Cake * @see CakeTopping @@ -63,8 +63,6 @@ public class App { /** * Initializes the example data - * - * @param cakeBakingService */ private static void initializeData(CakeBakingService cakeBakingService) { cakeBakingService.saveNewLayer(new CakeLayerInfo("chocolate", 1200)); diff --git a/layers/src/main/java/com/iluwatar/layers/CakeBakingService.java b/layers/src/main/java/com/iluwatar/layers/CakeBakingService.java index 80bd3438b..adfa585d6 100644 --- a/layers/src/main/java/com/iluwatar/layers/CakeBakingService.java +++ b/layers/src/main/java/com/iluwatar/layers/CakeBakingService.java @@ -11,44 +11,31 @@ public interface CakeBakingService { /** * Bakes new cake according to parameters - * - * @param cakeInfo - * @throws CakeBakingException */ void bakeNewCake(CakeInfo cakeInfo) throws CakeBakingException; /** * Get all cakes - * - * @return */ List getAllCakes(); /** * Store new cake topping - * - * @param toppingInfo */ void saveNewTopping(CakeToppingInfo toppingInfo); /** * Get available cake toppings - * - * @return */ List getAvailableToppings(); /** * Add new cake layer - * - * @param layerInfo */ void saveNewLayer(CakeLayerInfo layerInfo); /** * Get available cake layers - * - * @return */ List getAvailableLayers(); } diff --git a/layers/src/main/java/com/iluwatar/layers/CakeInfo.java b/layers/src/main/java/com/iluwatar/layers/CakeInfo.java index f60ee9a14..6ae5008f0 100644 --- a/layers/src/main/java/com/iluwatar/layers/CakeInfo.java +++ b/layers/src/main/java/com/iluwatar/layers/CakeInfo.java @@ -14,18 +14,27 @@ public class CakeInfo { public final CakeToppingInfo cakeToppingInfo; public final List cakeLayerInfos; + /** + * Constructor + */ public CakeInfo(Long id, CakeToppingInfo cakeToppingInfo, List cakeLayerInfos) { this.id = Optional.of(id); this.cakeToppingInfo = cakeToppingInfo; this.cakeLayerInfos = cakeLayerInfos; } + /** + * Constructor + */ public CakeInfo(CakeToppingInfo cakeToppingInfo, List cakeLayerInfos) { this.id = Optional.empty(); this.cakeToppingInfo = cakeToppingInfo; this.cakeLayerInfos = cakeLayerInfos; } + /** + * Calculate calories + */ public int calculateTotalCalories() { int total = cakeToppingInfo != null ? cakeToppingInfo.calories : 0; total += cakeLayerInfos.stream().mapToInt(c -> c.calories).sum(); diff --git a/layers/src/main/java/com/iluwatar/layers/CakeLayerInfo.java b/layers/src/main/java/com/iluwatar/layers/CakeLayerInfo.java index 3dff379da..339a61b4e 100644 --- a/layers/src/main/java/com/iluwatar/layers/CakeLayerInfo.java +++ b/layers/src/main/java/com/iluwatar/layers/CakeLayerInfo.java @@ -13,12 +13,18 @@ public class CakeLayerInfo { public final String name; public final int calories; + /** + * Constructor + */ public CakeLayerInfo(Long id, String name, int calories) { this.id = Optional.of(id); this.name = name; this.calories = calories; } + /** + * Constructor + */ public CakeLayerInfo(String name, int calories) { this.id = Optional.empty(); this.name = name; diff --git a/layers/src/main/java/com/iluwatar/layers/CakeToppingInfo.java b/layers/src/main/java/com/iluwatar/layers/CakeToppingInfo.java index 4e432ec44..726d597d2 100644 --- a/layers/src/main/java/com/iluwatar/layers/CakeToppingInfo.java +++ b/layers/src/main/java/com/iluwatar/layers/CakeToppingInfo.java @@ -13,12 +13,18 @@ public class CakeToppingInfo { public final String name; public final int calories; + /** + * Constructor + */ public CakeToppingInfo(Long id, String name, int calories) { this.id = Optional.of(id); this.name = name; this.calories = calories; } + /** + * Constructor + */ public CakeToppingInfo(String name, int calories) { this.id = Optional.empty(); this.name = name; diff --git a/layers/src/main/resources/META-INF/persistence.xml b/layers/src/main/resources/META-INF/persistence.xml index d94d8582b..96856e1b9 100644 --- a/layers/src/main/resources/META-INF/persistence.xml +++ b/layers/src/main/resources/META-INF/persistence.xml @@ -1,8 +1,8 @@ + xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"> - + \ No newline at end of file diff --git a/layers/src/main/resources/applicationContext.xml b/layers/src/main/resources/applicationContext.xml index 0c908ad2e..6b3bc466d 100644 --- a/layers/src/main/resources/applicationContext.xml +++ b/layers/src/main/resources/applicationContext.xml @@ -1,42 +1,39 @@ - + - + - + - - - + + + - - - - - - + + + + + + - - - - - - - - - - - - - - + + + + + + + + + + + + + + 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 25e46d8b9..dabd8c313 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 @@ -7,6 +7,9 @@ package com.iluwatar.lazy.loading; */ public class Heavy { + /** + * Constructor + */ public Heavy() { System.out.println("Creating Heavy ..."); try { diff --git a/lazy-loading/src/main/java/com/iluwatar/lazy/loading/HolderNaive.java b/lazy-loading/src/main/java/com/iluwatar/lazy/loading/HolderNaive.java index 132ebaa5f..f78005c73 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 @@ -9,10 +9,16 @@ public class HolderNaive { private Heavy heavy; + /** + * Constructor + */ public HolderNaive() { System.out.println("HolderNaive created"); } + /** + * Get heavy object + */ public Heavy getHeavy() { if (heavy == null) { heavy = new Heavy(); diff --git a/lazy-loading/src/main/java/com/iluwatar/lazy/loading/HolderThreadSafe.java b/lazy-loading/src/main/java/com/iluwatar/lazy/loading/HolderThreadSafe.java index d2b15a3af..56074846e 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 @@ -10,10 +10,16 @@ public class HolderThreadSafe { private Heavy heavy; + /** + * Constructor + */ public HolderThreadSafe() { System.out.println("HolderThreadSafe created"); } + /** + * Get heavy object + */ public synchronized Heavy getHeavy() { if (heavy == null) { heavy = new Heavy(); 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 da021e014..aa86e3b34 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 @@ -5,7 +5,7 @@ import java.util.function.Supplier; /** * * This lazy loader is thread safe and more efficient than {@link HolderThreadSafe}. It utilizes - * Java 8 functional interface {@link Supplier} as {@link Heavy} factory. + * Java 8 functional interface {@link Supplier} as {@link Heavy} factory. * */ public class Java8Holder { diff --git a/memento/src/main/java/com/iluwatar/memento/App.java b/memento/src/main/java/com/iluwatar/memento/App.java index c99894680..e08e9a106 100644 --- a/memento/src/main/java/com/iluwatar/memento/App.java +++ b/memento/src/main/java/com/iluwatar/memento/App.java @@ -23,6 +23,9 @@ import java.util.Stack; */ public class App { + /** + * Program entry point + */ public static void main(String[] args) { Stack states = new Stack<>(); diff --git a/memento/src/main/java/com/iluwatar/memento/Star.java b/memento/src/main/java/com/iluwatar/memento/Star.java index b4ec1c669..f67edfd15 100644 --- a/memento/src/main/java/com/iluwatar/memento/Star.java +++ b/memento/src/main/java/com/iluwatar/memento/Star.java @@ -11,12 +11,18 @@ public class Star { private int ageYears; private int massTons; + /** + * Constructor + */ public Star(StarType startType, int startAge, int startMass) { this.type = startType; this.ageYears = startAge; this.massTons = startMass; } + /** + * Makes time pass for the star + */ public void timePasses() { ageYears *= 2; massTons *= 8; 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 a41dd74dc..b0aeb690f 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 @@ -30,9 +30,6 @@ public class App { /** * Program entry point - * - * @param args command line args - * @throws Exception */ public static void main(String[] args) throws Exception { CamelContext context = new DefaultCamelContext(); diff --git a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileLoader.java b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileLoader.java index d04f284ac..0cf4f8c34 100644 --- a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileLoader.java +++ b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileLoader.java @@ -39,9 +39,7 @@ public class FileLoader { br.close(); return sb.toString(); - } - - catch (Exception e) { + } catch (Exception e) { e.printStackTrace(); } diff --git a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorJFrame.java b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorJFrame.java index 02cb2703a..6f220cffb 100644 --- a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorJFrame.java +++ b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorJFrame.java @@ -26,7 +26,7 @@ public class FileSelectorJFrame extends JFrame implements FileSelectorView, Acti /** * The "OK" button for loading the file. */ - private JButton OK; + private JButton ok; /** * The cancel button. @@ -121,10 +121,10 @@ public class FileSelectorJFrame extends JFrame implements FileSelectorView, Acti /* * Add the OK button. */ - this.OK = new JButton("OK"); - this.panel.add(OK); - this.OK.setBounds(250, 50, 100, 25); - this.OK.addActionListener(this); + this.ok = new JButton("OK"); + this.panel.add(ok); + this.ok.setBounds(250, 50, 100, 25); + this.ok.addActionListener(this); /* * Add the cancel button. @@ -140,13 +140,11 @@ public class FileSelectorJFrame extends JFrame implements FileSelectorView, Acti @Override public void actionPerformed(ActionEvent e) { - if (e.getSource() == this.OK) { + if (e.getSource() == this.ok) { this.fileName = this.input.getText(); presenter.fileNameChanged(); presenter.confirmed(); - } - - else if (e.getSource() == this.cancel) { + } else if (e.getSource() == this.cancel) { presenter.cancelled(); } } diff --git a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorPresenter.java b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorPresenter.java index 133d8555d..f38dc2655 100644 --- a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorPresenter.java +++ b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorPresenter.java @@ -51,6 +51,9 @@ public class FileSelectorPresenter { loader.setFileName(view.getFileName()); } + /** + * Ok button handler + */ public void confirmed() { if (loader.getFileName() == null || loader.getFileName().equals("")) { view.showMessage("Please give the name of the file first!"); @@ -60,9 +63,7 @@ public class FileSelectorPresenter { if (loader.fileExists()) { String data = loader.loadData(); view.displayData(data); - } - - else { + } else { view.showMessage("The file specified does not exist."); } } diff --git a/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/FileSelectorPresenterTest.java b/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/FileSelectorPresenterTest.java index dfdcba31b..ba371525a 100644 --- a/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/FileSelectorPresenterTest.java +++ b/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/FileSelectorPresenterTest.java @@ -1,14 +1,13 @@ package com.iluwatar.model.view.presenter; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Test; -import com.iluwatar.model.view.presenter.FileLoader; -import com.iluwatar.model.view.presenter.FileSelectorPresenter; -import com.iluwatar.model.view.presenter.FileSelectorStub; - /** * This test case is responsible for testing our application by taking advantage of the * Model-View-Controller architectural pattern. @@ -57,13 +56,13 @@ public class FileSelectorPresenterTest { */ @Test public void updateFileNameToLoader() { - String EXPECTED_FILE = "Stamatis"; - stub.setFileName(EXPECTED_FILE); + String expectedFile = "Stamatis"; + stub.setFileName(expectedFile); presenter.start(); presenter.fileNameChanged(); - assertEquals(EXPECTED_FILE, loader.getFileName()); + assertEquals(expectedFile, loader.getFileName()); } /** diff --git a/monostate/src/main/java/com/iluwatar/monostate/LoadBalancer.java b/monostate/src/main/java/com/iluwatar/monostate/LoadBalancer.java index b81e44251..429eda73e 100644 --- a/monostate/src/main/java/com/iluwatar/monostate/LoadBalancer.java +++ b/monostate/src/main/java/com/iluwatar/monostate/LoadBalancer.java @@ -24,6 +24,9 @@ public class LoadBalancer { servers.add(new Server("localhost", 8084, ++id)); } + /** + * Add new server + */ public final void addServer(Server server) { synchronized (servers) { servers.add(server); @@ -39,6 +42,9 @@ public class LoadBalancer { return lastServedId; } + /** + * Handle request + */ public void serverequest(Request request) { if (lastServedId >= servers.size()) { lastServedId = 0; diff --git a/monostate/src/main/java/com/iluwatar/monostate/Server.java b/monostate/src/main/java/com/iluwatar/monostate/Server.java index f48f4ad0f..21794de42 100644 --- a/monostate/src/main/java/com/iluwatar/monostate/Server.java +++ b/monostate/src/main/java/com/iluwatar/monostate/Server.java @@ -11,6 +11,9 @@ public class Server { public final int port; public final int id; + /** + * Constructor + */ public Server(String host, int port, int id) { this.host = host; this.port = port; diff --git a/naked-objects/dom/src/main/java/domainapp/dom/app/homepage/HomePageService.java b/naked-objects/dom/src/main/java/domainapp/dom/app/homepage/HomePageService.java index 6769f95dd..fa1e74048 100644 --- a/naked-objects/dom/src/main/java/domainapp/dom/app/homepage/HomePageService.java +++ b/naked-objects/dom/src/main/java/domainapp/dom/app/homepage/HomePageService.java @@ -21,9 +21,7 @@ import org.apache.isis.applib.annotation.HomePage; import org.apache.isis.applib.annotation.NatureOfService; import org.apache.isis.applib.annotation.SemanticsOf; -@DomainService(nature = NatureOfService.VIEW_CONTRIBUTIONS_ONLY // trick to suppress the actions - // from the top-level menu -) +@DomainService(nature = NatureOfService.VIEW_CONTRIBUTIONS_ONLY) public class HomePageService { // region > homePage (action) diff --git a/naked-objects/dom/src/main/java/domainapp/dom/modules/simple/SimpleObjects.java b/naked-objects/dom/src/main/java/domainapp/dom/modules/simple/SimpleObjects.java index 5e4642455..849f01c5d 100644 --- a/naked-objects/dom/src/main/java/domainapp/dom/modules/simple/SimpleObjects.java +++ b/naked-objects/dom/src/main/java/domainapp/dom/modules/simple/SimpleObjects.java @@ -69,9 +69,12 @@ public class SimpleObjects { } } + /** + * Create simple object + */ @Action(domainEvent = CreateDomainEvent.class) @MemberOrder(sequence = "3") - public SimpleObject create(final @ParameterLayout(named = "Name") String name) { + public SimpleObject create(@ParameterLayout(named = "Name") final String name) { final SimpleObject obj = container.newTransientInstance(SimpleObject.class); obj.setName(name); container.persistIfNotAlready(obj); diff --git a/naked-objects/fixture/src/main/java/domainapp/fixture/modules/simple/SimpleObjectCreate.java b/naked-objects/fixture/src/main/java/domainapp/fixture/modules/simple/SimpleObjectCreate.java index 2918fe7f6..266529c74 100644 --- a/naked-objects/fixture/src/main/java/domainapp/fixture/modules/simple/SimpleObjectCreate.java +++ b/naked-objects/fixture/src/main/java/domainapp/fixture/modules/simple/SimpleObjectCreate.java @@ -45,8 +45,6 @@ public class SimpleObjectCreate extends FixtureScript { /** * The created simple object (output). - * - * @return */ public SimpleObject getSimpleObject() { return simpleObject; diff --git a/naked-objects/fixture/src/main/java/domainapp/fixture/scenarios/RecreateSimpleObjects.java b/naked-objects/fixture/src/main/java/domainapp/fixture/scenarios/RecreateSimpleObjects.java index c978e0b82..c82ef8498 100644 --- a/naked-objects/fixture/src/main/java/domainapp/fixture/scenarios/RecreateSimpleObjects.java +++ b/naked-objects/fixture/src/main/java/domainapp/fixture/scenarios/RecreateSimpleObjects.java @@ -29,7 +29,7 @@ import domainapp.fixture.modules.simple.SimpleObjectsTearDown; public class RecreateSimpleObjects extends FixtureScript { - public final List NAMES = Collections.unmodifiableList(Arrays.asList("Foo", "Bar", "Baz", + public final List names = Collections.unmodifiableList(Arrays.asList("Foo", "Bar", "Baz", "Frodo", "Froyo", "Fizz", "Bip", "Bop", "Bang", "Boo")); public RecreateSimpleObjects() { @@ -72,9 +72,9 @@ public class RecreateSimpleObjects extends FixtureScript { final int number = defaultParam("number", ec, 3); // validate - if (number < 0 || number > NAMES.size()) { + if (number < 0 || number > names.size()) { throw new IllegalArgumentException(String.format("number must be in range [0,%d)", - NAMES.size())); + names.size())); } // @@ -83,7 +83,7 @@ public class RecreateSimpleObjects extends FixtureScript { ec.executeChild(this, new SimpleObjectsTearDown()); for (int i = 0; i < number; i++) { - final SimpleObjectCreate fs = new SimpleObjectCreate().setName(NAMES.get(i)); + final SimpleObjectCreate fs = new SimpleObjectCreate().setName(names.get(i)); ec.executeChild(this, fs.getName(), fs); simpleObjects.add(fs.getSimpleObject()); } diff --git a/naked-objects/integtests/src/test/java/domainapp/integtests/bootstrap/SimpleAppSystemInitializer.java b/naked-objects/integtests/src/test/java/domainapp/integtests/bootstrap/SimpleAppSystemInitializer.java index c617915f1..0384b0eb4 100644 --- a/naked-objects/integtests/src/test/java/domainapp/integtests/bootstrap/SimpleAppSystemInitializer.java +++ b/naked-objects/integtests/src/test/java/domainapp/integtests/bootstrap/SimpleAppSystemInitializer.java @@ -21,6 +21,9 @@ import org.apache.isis.objectstore.jdo.datanucleus.IsisConfigurationForJdoIntegT public class SimpleAppSystemInitializer { + /** + * Init test system + */ public static void initIsft() { IsisSystemForTest isft = IsisSystemForTest.getElseNull(); if (isft == null) { diff --git a/naked-objects/integtests/src/test/java/domainapp/integtests/specglue/modules/simple/SimpleObjectGlue.java b/naked-objects/integtests/src/test/java/domainapp/integtests/specglue/modules/simple/SimpleObjectGlue.java index ef6012919..2ea375b4a 100644 --- a/naked-objects/integtests/src/test/java/domainapp/integtests/specglue/modules/simple/SimpleObjectGlue.java +++ b/naked-objects/integtests/src/test/java/domainapp/integtests/specglue/modules/simple/SimpleObjectGlue.java @@ -29,7 +29,7 @@ import static org.junit.Assert.assertThat; public class SimpleObjectGlue extends CukeGlueAbstract { @Given("^there are.* (\\d+) simple objects$") - public void there_are_N_simple_objects(int n) throws Throwable { + public void thereAreNumSimpleObjects(int n) throws Throwable { try { final List findAll = service(SimpleObjects.class).listAll(); assertThat(findAll.size(), is(n)); @@ -41,7 +41,7 @@ public class SimpleObjectGlue extends CukeGlueAbstract { } @When("^I create a new simple object$") - public void I_create_a_new_simple_object() throws Throwable { + public void createNewSimpleObject() throws Throwable { service(SimpleObjects.class).create(UUID.randomUUID().toString()); } diff --git a/naked-objects/integtests/src/test/java/domainapp/integtests/tests/SimpleAppIntegTest.java b/naked-objects/integtests/src/test/java/domainapp/integtests/tests/SimpleAppIntegTest.java index 3ceef4e63..7a7ad91b2 100644 --- a/naked-objects/integtests/src/test/java/domainapp/integtests/tests/SimpleAppIntegTest.java +++ b/naked-objects/integtests/src/test/java/domainapp/integtests/tests/SimpleAppIntegTest.java @@ -27,13 +27,13 @@ import domainapp.integtests.bootstrap.SimpleAppSystemInitializer; public abstract class SimpleAppIntegTest extends IntegrationTestAbstract { - @BeforeClass - public static void initClass() { - org.apache.log4j.PropertyConfigurator.configure("logging.properties"); - SimpleAppSystemInitializer.initIsft(); + @BeforeClass + public static void initClass() { + org.apache.log4j.PropertyConfigurator.configure("logging.properties"); + SimpleAppSystemInitializer.initIsft(); - // instantiating will install onto ThreadLocal - new ScenarioExecutionForIntegration(); - } + // instantiating will install onto ThreadLocal + new ScenarioExecutionForIntegration(); + } } diff --git a/naked-objects/integtests/src/test/java/domainapp/integtests/tests/modules/simple/SimpleObjectIntegTest.java b/naked-objects/integtests/src/test/java/domainapp/integtests/tests/modules/simple/SimpleObjectIntegTest.java index 610136bb8..872aff7a3 100644 --- a/naked-objects/integtests/src/test/java/domainapp/integtests/tests/modules/simple/SimpleObjectIntegTest.java +++ b/naked-objects/integtests/src/test/java/domainapp/integtests/tests/modules/simple/SimpleObjectIntegTest.java @@ -35,87 +35,86 @@ import static org.assertj.core.api.Assertions.assertThat; public class SimpleObjectIntegTest extends SimpleAppIntegTest { + @Inject + FixtureScripts fixtureScripts; + + RecreateSimpleObjects fs; + SimpleObject simpleObjectPojo; + SimpleObject simpleObjectWrapped; + + @Before + public void setUp() throws Exception { + // given + fs = new RecreateSimpleObjects().setNumber(1); + fixtureScripts.runFixtureScript(fs, null); + + simpleObjectPojo = fs.getSimpleObjects().get(0); + + assertThat(simpleObjectPojo).isNotNull(); + simpleObjectWrapped = wrap(simpleObjectPojo); + } + + public static class Name extends SimpleObjectIntegTest { + + @Test + public void accessible() throws Exception { + // when + final String name = simpleObjectWrapped.getName(); + // then + assertThat(name).isEqualTo(fs.names.get(0)); + } + + @Test + public void cannotBeUpdatedDirectly() throws Exception { + + // expect + expectedExceptions.expect(DisabledException.class); + + // when + simpleObjectWrapped.setName("new name"); + } + } + + public static class UpdateName extends SimpleObjectIntegTest { + + @Test + public void happyCase() throws Exception { + + // when + simpleObjectWrapped.updateName("new name"); + + // then + assertThat(simpleObjectWrapped.getName()).isEqualTo("new name"); + } + + @Test + public void failsValidation() throws Exception { + + // expect + expectedExceptions.expect(InvalidException.class); + expectedExceptions.expectMessage("Exclamation mark is not allowed"); + + // when + simpleObjectWrapped.updateName("new name!"); + } + } + + public static class Title extends SimpleObjectIntegTest { + @Inject - FixtureScripts fixtureScripts; + DomainObjectContainer container; - RecreateSimpleObjects fs; - SimpleObject simpleObjectPojo; - SimpleObject simpleObjectWrapped; + @Test + public void interpolatesName() throws Exception { - @Before - public void setUp() throws Exception { - // given - fs = new RecreateSimpleObjects().setNumber(1); - fixtureScripts.runFixtureScript(fs, null); + // given + final String name = simpleObjectWrapped.getName(); - simpleObjectPojo = fs.getSimpleObjects().get(0); + // when + final String title = container.titleOf(simpleObjectWrapped); - assertThat(simpleObjectPojo).isNotNull(); - simpleObjectWrapped = wrap(simpleObjectPojo); - } - - public static class Name extends SimpleObjectIntegTest { - - @Test - public void accessible() throws Exception { - // when - final String name = simpleObjectWrapped.getName(); - // then - assertThat(name).isEqualTo(fs.NAMES.get(0)); - } - - @Test - public void cannotBeUpdatedDirectly() throws Exception { - - // expect - expectedExceptions.expect(DisabledException.class); - - // when - simpleObjectWrapped.setName("new name"); - } - } - - public static class UpdateName extends SimpleObjectIntegTest { - - @Test - public void happyCase() throws Exception { - - // when - simpleObjectWrapped.updateName("new name"); - - // then - assertThat(simpleObjectWrapped.getName()).isEqualTo("new name"); - } - - @Test - public void failsValidation() throws Exception { - - // expect - expectedExceptions.expect(InvalidException.class); - expectedExceptions.expectMessage("Exclamation mark is not allowed"); - - // when - simpleObjectWrapped.updateName("new name!"); - } - } - - - public static class Title extends SimpleObjectIntegTest { - - @Inject - DomainObjectContainer container; - - @Test - public void interpolatesName() throws Exception { - - // given - final String name = simpleObjectWrapped.getName(); - - // when - final String title = container.titleOf(simpleObjectWrapped); - - // then - assertThat(title).isEqualTo("Object: " + name); - } + // then + assertThat(title).isEqualTo("Object: " + name); } + } } \ No newline at end of file diff --git a/naked-objects/integtests/src/test/java/domainapp/integtests/tests/modules/simple/SimpleObjectsIntegTest.java b/naked-objects/integtests/src/test/java/domainapp/integtests/tests/modules/simple/SimpleObjectsIntegTest.java index fd3b0ff46..332213542 100644 --- a/naked-objects/integtests/src/test/java/domainapp/integtests/tests/modules/simple/SimpleObjectsIntegTest.java +++ b/naked-objects/integtests/src/test/java/domainapp/integtests/tests/modules/simple/SimpleObjectsIntegTest.java @@ -42,102 +42,102 @@ import static org.assertj.core.api.Assertions.assertThat; public class SimpleObjectsIntegTest extends SimpleAppIntegTest { - @Inject - FixtureScripts fixtureScripts; - @Inject - SimpleObjects simpleObjects; + @Inject + FixtureScripts fixtureScripts; + @Inject + SimpleObjects simpleObjects; - public static class ListAll extends SimpleObjectsIntegTest { + public static class ListAll extends SimpleObjectsIntegTest { - @Test - public void happyCase() throws Exception { + @Test + public void happyCase() throws Exception { - // given - RecreateSimpleObjects fs = new RecreateSimpleObjects(); - fixtureScripts.runFixtureScript(fs, null); - nextTransaction(); + // given + RecreateSimpleObjects fs = new RecreateSimpleObjects(); + fixtureScripts.runFixtureScript(fs, null); + nextTransaction(); - // when - final List all = wrap(simpleObjects).listAll(); + // when + final List all = wrap(simpleObjects).listAll(); - // then - assertThat(all).hasSize(fs.getSimpleObjects().size()); + // then + assertThat(all).hasSize(fs.getSimpleObjects().size()); - SimpleObject simpleObject = wrap(all.get(0)); - assertThat(simpleObject.getName()).isEqualTo(fs.getSimpleObjects().get(0).getName()); - } - - @Test - public void whenNone() throws Exception { - - // given - FixtureScript fs = new SimpleObjectsTearDown(); - fixtureScripts.runFixtureScript(fs, null); - nextTransaction(); - - // when - final List all = wrap(simpleObjects).listAll(); - - // then - assertThat(all).hasSize(0); - } + SimpleObject simpleObject = wrap(all.get(0)); + assertThat(simpleObject.getName()).isEqualTo(fs.getSimpleObjects().get(0).getName()); } - public static class Create extends SimpleObjectsIntegTest { + @Test + public void whenNone() throws Exception { - @Test - public void happyCase() throws Exception { + // given + FixtureScript fs = new SimpleObjectsTearDown(); + fixtureScripts.runFixtureScript(fs, null); + nextTransaction(); - // given - FixtureScript fs = new SimpleObjectsTearDown(); - fixtureScripts.runFixtureScript(fs, null); - nextTransaction(); + // when + final List all = wrap(simpleObjects).listAll(); - // when - wrap(simpleObjects).create("Faz"); - - // then - final List all = wrap(simpleObjects).listAll(); - assertThat(all).hasSize(1); - } - - @Test - public void whenAlreadyExists() throws Exception { - - // given - FixtureScript fs = new SimpleObjectsTearDown(); - fixtureScripts.runFixtureScript(fs, null); - nextTransaction(); - wrap(simpleObjects).create("Faz"); - nextTransaction(); - - // then - expectedExceptions.expectCause(causalChainContains(SQLIntegrityConstraintViolationException.class)); - - // when - wrap(simpleObjects).create("Faz"); - nextTransaction(); - } - - private static Matcher causalChainContains(final Class cls) { - return new TypeSafeMatcher() { - @Override - protected boolean matchesSafely(Throwable item) { - final List causalChain = Throwables.getCausalChain(item); - for (Throwable throwable : causalChain) { - if(cls.isAssignableFrom(throwable.getClass())){ - return true; - } - } - return false; - } - - @Override - public void describeTo(Description description) { - description.appendText("exception with causal chain containing " + cls.getSimpleName()); - } - }; - } + // then + assertThat(all).hasSize(0); } + } + + public static class Create extends SimpleObjectsIntegTest { + + @Test + public void happyCase() throws Exception { + + // given + FixtureScript fs = new SimpleObjectsTearDown(); + fixtureScripts.runFixtureScript(fs, null); + nextTransaction(); + + // when + wrap(simpleObjects).create("Faz"); + + // then + final List all = wrap(simpleObjects).listAll(); + assertThat(all).hasSize(1); + } + + @Test + public void whenAlreadyExists() throws Exception { + + // given + FixtureScript fs = new SimpleObjectsTearDown(); + fixtureScripts.runFixtureScript(fs, null); + nextTransaction(); + wrap(simpleObjects).create("Faz"); + nextTransaction(); + + // then + expectedExceptions.expectCause(causalChainContains(SQLIntegrityConstraintViolationException.class)); + + // when + wrap(simpleObjects).create("Faz"); + nextTransaction(); + } + + private static Matcher causalChainContains(final Class cls) { + return new TypeSafeMatcher() { + @Override + protected boolean matchesSafely(Throwable item) { + final List causalChain = Throwables.getCausalChain(item); + for (Throwable throwable : causalChain) { + if (cls.isAssignableFrom(throwable.getClass())) { + return true; + } + } + return false; + } + + @Override + public void describeTo(Description description) { + description.appendText("exception with causal chain containing " + cls.getSimpleName()); + } + }; + } + } } \ No newline at end of file diff --git a/naked-objects/webapp/src/main/java/domainapp/webapp/SimpleApplication.java b/naked-objects/webapp/src/main/java/domainapp/webapp/SimpleApplication.java index c7bbd8c80..a292a7779 100644 --- a/naked-objects/webapp/src/main/java/domainapp/webapp/SimpleApplication.java +++ b/naked-objects/webapp/src/main/java/domainapp/webapp/SimpleApplication.java @@ -74,7 +74,7 @@ public class SimpleApplication extends IsisWicketApplication { *

* for demos only, obvious. */ - private final static boolean DEMO_MODE_USING_CREDENTIALS_AS_QUERYARGS = false; + private static final boolean DEMO_MODE_USING_CREDENTIALS_AS_QUERYARGS = false; @Override @@ -116,6 +116,7 @@ public class SimpleApplication extends IsisWicketApplication { servletRequest.getSession().invalidate(); } } catch (Exception e) { + System.out.println(e); } WebRequest request = super.newWebRequest(servletRequest, filterPath); return request; 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 5de258890..4478b9bfa 100644 --- a/null-object/src/main/java/com/iluwatar/nullobject/NodeImpl.java +++ b/null-object/src/main/java/com/iluwatar/nullobject/NodeImpl.java @@ -11,6 +11,9 @@ public class NodeImpl implements Node { private final Node left; private final Node right; + /** + * Constructor + */ public NodeImpl(String name, Node left, Node right) { this.name = name; this.left = left; diff --git a/object-pool/src/main/java/com/iluwatar/object/pool/ObjectPool.java b/object-pool/src/main/java/com/iluwatar/object/pool/ObjectPool.java index 79d7d6345..d85955f0a 100644 --- a/object-pool/src/main/java/com/iluwatar/object/pool/ObjectPool.java +++ b/object-pool/src/main/java/com/iluwatar/object/pool/ObjectPool.java @@ -5,8 +5,6 @@ import java.util.HashSet; /** * * Generic object pool - * - * @param */ public abstract class ObjectPool { @@ -15,6 +13,9 @@ public abstract class ObjectPool { protected abstract T create(); + /** + * Checkout object from pool + */ public synchronized T checkOut() { if (available.size() <= 0) { available.add(create()); diff --git a/object-pool/src/main/java/com/iluwatar/object/pool/Oliphaunt.java b/object-pool/src/main/java/com/iluwatar/object/pool/Oliphaunt.java index aeefd6b3a..f3923fff5 100644 --- a/object-pool/src/main/java/com/iluwatar/object/pool/Oliphaunt.java +++ b/object-pool/src/main/java/com/iluwatar/object/pool/Oliphaunt.java @@ -11,6 +11,9 @@ public class Oliphaunt { private final int id; + /** + * Constructor + */ public Oliphaunt() { id = counter++; try { diff --git a/observer/src/main/java/com/iluwatar/observer/Weather.java b/observer/src/main/java/com/iluwatar/observer/Weather.java index 634953945..4e04143a2 100644 --- a/observer/src/main/java/com/iluwatar/observer/Weather.java +++ b/observer/src/main/java/com/iluwatar/observer/Weather.java @@ -27,6 +27,9 @@ public class Weather { observers.remove(obs); } + /** + * Makes time pass for weather + */ public void timePasses() { WeatherType[] enumValues = WeatherType.values(); currentWeather = enumValues[(currentWeather.ordinal() + 1) % enumValues.length]; 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 9d1c6ed07..d503c8421 100644 --- a/observer/src/main/java/com/iluwatar/observer/generic/GWeather.java +++ b/observer/src/main/java/com/iluwatar/observer/generic/GWeather.java @@ -15,6 +15,9 @@ public class GWeather extends Observable { currentWeather = WeatherType.SUNNY; } + /** + * Makes time pass for weather + */ public void timePasses() { WeatherType[] enumValues = WeatherType.values(); currentWeather = enumValues[(currentWeather.ordinal() + 1) % enumValues.length]; diff --git a/observer/src/main/java/com/iluwatar/observer/generic/Observable.java b/observer/src/main/java/com/iluwatar/observer/generic/Observable.java index f1ad2dca6..f3b3c7dbb 100644 --- a/observer/src/main/java/com/iluwatar/observer/generic/Observable.java +++ b/observer/src/main/java/com/iluwatar/observer/generic/Observable.java @@ -22,6 +22,9 @@ public abstract class Observable, O extends Observ this.observers.add(observer); } + /** + * Notify observers + */ @SuppressWarnings("unchecked") public void notifyObservers(A argument) { for (O observer : observers) { diff --git a/observer/src/main/java/com/iluwatar/observer/generic/Observer.java b/observer/src/main/java/com/iluwatar/observer/generic/Observer.java index b01955419..34b9ac359 100644 --- a/observer/src/main/java/com/iluwatar/observer/generic/Observer.java +++ b/observer/src/main/java/com/iluwatar/observer/generic/Observer.java @@ -3,10 +3,6 @@ package com.iluwatar.observer.generic; /** * * Observer - * - * @param - * @param - * @param */ public interface Observer, O extends Observer, A> { 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 ff06d7d5b..a305c010c 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 @@ -7,14 +7,17 @@ import com.iluwatar.poison.pill.Message.Headers; */ public class Consumer { - private final MQSubscribePoint queue; + private final MqSubscribePoint queue; private final String name; - public Consumer(String name, MQSubscribePoint queue) { + public Consumer(String name, MqSubscribePoint queue) { this.name = name; this.queue = queue; } + /** + * Consume message + */ public void consume() { while (true) { Message msg; diff --git a/poison-pill/src/main/java/com/iluwatar/poison/pill/MessageQueue.java b/poison-pill/src/main/java/com/iluwatar/poison/pill/MessageQueue.java index 99231ab51..aa0d3699d 100644 --- a/poison-pill/src/main/java/com/iluwatar/poison/pill/MessageQueue.java +++ b/poison-pill/src/main/java/com/iluwatar/poison/pill/MessageQueue.java @@ -3,6 +3,6 @@ package com.iluwatar.poison.pill; /** * Represents abstraction of channel (or pipe) that bounds {@link Producer} and {@link Consumer} */ -public interface MessageQueue extends MQPublishPoint, MQSubscribePoint { +public interface MessageQueue extends MqPublishPoint, MqSubscribePoint { } diff --git a/poison-pill/src/main/java/com/iluwatar/poison/pill/MQPublishPoint.java b/poison-pill/src/main/java/com/iluwatar/poison/pill/MqPublishPoint.java similarity index 81% rename from poison-pill/src/main/java/com/iluwatar/poison/pill/MQPublishPoint.java rename to poison-pill/src/main/java/com/iluwatar/poison/pill/MqPublishPoint.java index a266d9f4d..74ed43e33 100644 --- a/poison-pill/src/main/java/com/iluwatar/poison/pill/MQPublishPoint.java +++ b/poison-pill/src/main/java/com/iluwatar/poison/pill/MqPublishPoint.java @@ -3,7 +3,7 @@ package com.iluwatar.poison.pill; /** * Endpoint to publish {@link Message} to queue */ -public interface MQPublishPoint { +public interface MqPublishPoint { public void put(Message msg) throws InterruptedException; } diff --git a/poison-pill/src/main/java/com/iluwatar/poison/pill/MQSubscribePoint.java b/poison-pill/src/main/java/com/iluwatar/poison/pill/MqSubscribePoint.java similarity index 80% rename from poison-pill/src/main/java/com/iluwatar/poison/pill/MQSubscribePoint.java rename to poison-pill/src/main/java/com/iluwatar/poison/pill/MqSubscribePoint.java index c093b1412..ed7624116 100644 --- a/poison-pill/src/main/java/com/iluwatar/poison/pill/MQSubscribePoint.java +++ b/poison-pill/src/main/java/com/iluwatar/poison/pill/MqSubscribePoint.java @@ -3,7 +3,7 @@ package com.iluwatar.poison.pill; /** * Endpoint to retrieve {@link Message} from queue */ -public interface MQSubscribePoint { +public interface MqSubscribePoint { public Message take() throws InterruptedException; } diff --git a/poison-pill/src/main/java/com/iluwatar/poison/pill/Producer.java b/poison-pill/src/main/java/com/iluwatar/poison/pill/Producer.java index ecde39e35..5405de869 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 @@ -10,16 +10,22 @@ import com.iluwatar.poison.pill.Message.Headers; */ public class Producer { - private final MQPublishPoint queue; + private final MqPublishPoint queue; private final String name; private boolean isStopped; - public Producer(String name, MQPublishPoint queue) { + /** + * Constructor + */ + public Producer(String name, MqPublishPoint queue) { this.name = name; this.queue = queue; this.isStopped = false; } + /** + * Send message to queue + */ public void send(String body) { if (isStopped) { throw new IllegalStateException(String.format( @@ -38,6 +44,9 @@ public class Producer { } } + /** + * Stop system by sending poison pill + */ public void stop() { isStopped = true; try { diff --git a/pom.xml b/pom.xml index 724b058f1..1285c8108 100644 --- a/pom.xml +++ b/pom.xml @@ -244,7 +244,7 @@ org.apache.maven.plugins maven-checkstyle-plugin - 2.15 + 2.17 validate 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 599a80407..849c2413c 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 @@ -13,6 +13,9 @@ public class ImmutableStew { data = new StewData(numPotatoes, numCarrots, numMeat, numPeppers); } + /** + * 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", 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 9deb32e16..2efd0b4ee 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 @@ -12,6 +12,9 @@ public class Stew { private int numMeat; private int numPeppers; + /** + * Constructor + */ public Stew(int numPotatoes, int numCarrots, int numMeat, int numPeppers) { this.numPotatoes = numPotatoes; this.numCarrots = numCarrots; @@ -19,12 +22,18 @@ public class Stew { this.numPeppers = numPeppers; } + /** + * 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)); } + /** + * Taste the stew + */ public void taste() { System.out.println("Tasting the stew"); if (numPotatoes > 0) { diff --git a/private-class-data/src/main/java/com/iluwatar/privateclassdata/StewData.java b/private-class-data/src/main/java/com/iluwatar/privateclassdata/StewData.java index 23d54ccf4..0bd62ada3 100644 --- a/private-class-data/src/main/java/com/iluwatar/privateclassdata/StewData.java +++ b/private-class-data/src/main/java/com/iluwatar/privateclassdata/StewData.java @@ -12,6 +12,9 @@ public class StewData { private int numMeat; private int numPeppers; + /** + * Constructor + */ public StewData(int numPotatoes, int numCarrots, int numMeat, int numPeppers) { this.numPotatoes = numPotatoes; this.numCarrots = numCarrots; 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 50d94d92f..63cae9413 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 @@ -5,14 +5,12 @@ import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; /** - * Producer Consumer Design pattern is a classic concurrency or threading pattern which reduces - * coupling between Producer and Consumer by separating Identification of work with Execution of - * Work. + * Producer Consumer Design pattern is a classic concurrency or threading pattern which reduces coupling between + * Producer and Consumer by separating Identification of work with Execution of Work. *

- * In producer consumer design pattern a shared queue is used to control the flow and this - * separation allows you to code producer and consumer separately. It also addresses the issue of - * different timing require to produce item or consuming item. by using producer consumer pattern - * both Producer and Consumer Thread can work with different speed. + * In producer consumer design pattern a shared queue is used to control the flow and this separation allows you to code + * producer and consumer separately. It also addresses the issue of different timing require to produce item or + * consuming item. by using producer consumer pattern both Producer and Consumer Thread can work with different speed. * */ public class App { @@ -20,7 +18,8 @@ public class App { /** * Program entry point * - * @param args command line args + * @param args + * command line args */ public static void main(String[] args) { @@ -35,7 +34,7 @@ public class App { producer.produce(); } }); - }; + } for (int i = 0; i < 3; i++) { final Consumer consumer = new Consumer("Consumer_" + i, queue); 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 8bb3b75b6..ff63ab41b 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 @@ -14,6 +14,9 @@ public class Consumer { this.queue = queue; } + /** + * Consume item from the queue + */ public void consume() throws InterruptedException { Item item = queue.take(); diff --git a/producer-consumer/src/main/java/com/iluwatar/producer/consumer/Producer.java b/producer-consumer/src/main/java/com/iluwatar/producer/consumer/Producer.java index 40e71c607..8b122a5fc 100644 --- a/producer-consumer/src/main/java/com/iluwatar/producer/consumer/Producer.java +++ b/producer-consumer/src/main/java/com/iluwatar/producer/consumer/Producer.java @@ -19,6 +19,9 @@ public class Producer { this.queue = queue; } + /** + * Put item in the queue + */ public void produce() throws InterruptedException { Item item = new Item(name, itemId++); diff --git a/property/src/main/java/com/iluwatar/property/Character.java b/property/src/main/java/com/iluwatar/property/Character.java index 10b8f495d..50e564623 100644 --- a/property/src/main/java/com/iluwatar/property/Character.java +++ b/property/src/main/java/com/iluwatar/property/Character.java @@ -18,6 +18,9 @@ public class Character implements Prototype { private String name; private Type type; + /** + * Constructor + */ public Character() { this.prototype = new Prototype() { // Null-value object @Override @@ -43,6 +46,9 @@ public class Character implements Prototype { this.prototype = prototype; } + /** + * Constructor + */ public Character(String name, Character prototype) { this.name = name; this.type = prototype.type; diff --git a/prototype/src/main/java/com/iluwatar/prototype/HeroFactoryImpl.java b/prototype/src/main/java/com/iluwatar/prototype/HeroFactoryImpl.java index 4c5a60bcd..85792104d 100644 --- a/prototype/src/main/java/com/iluwatar/prototype/HeroFactoryImpl.java +++ b/prototype/src/main/java/com/iluwatar/prototype/HeroFactoryImpl.java @@ -11,12 +11,18 @@ public class HeroFactoryImpl implements HeroFactory { private Warlord warlord; private Beast beast; + /** + * Constructor + */ public HeroFactoryImpl(Mage mage, Warlord warlord, Beast beast) { this.mage = mage; this.warlord = warlord; this.beast = beast; } + /** + * Create mage + */ public Mage createMage() { try { return mage.clone(); @@ -25,6 +31,9 @@ public class HeroFactoryImpl implements HeroFactory { } } + /** + * Create warlord + */ public Warlord createWarlord() { try { return warlord.clone(); @@ -33,6 +42,9 @@ public class HeroFactoryImpl implements HeroFactory { } } + /** + * Create beast + */ public Beast createBeast() { try { return beast.clone(); diff --git a/proxy/src/main/java/com/iluwatar/proxy/App.java b/proxy/src/main/java/com/iluwatar/proxy/App.java index 25a903e41..837424f28 100644 --- a/proxy/src/main/java/com/iluwatar/proxy/App.java +++ b/proxy/src/main/java/com/iluwatar/proxy/App.java @@ -18,6 +18,9 @@ package com.iluwatar.proxy; */ public class App { + /** + * Program entry point + */ public static void main(String[] args) { WizardTowerProxy tower = new WizardTowerProxy(); 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 30f982ed1..f80dd1ad1 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 @@ -28,10 +28,6 @@ public class App { /** * Program entry point - * - * @param args - * command line args - * @throws Exception */ public static void main(String[] args) throws Exception { CamelContext context = new DefaultCamelContext(); diff --git a/reactor/src/main/java/com/iluwatar/reactor/app/App.java b/reactor/src/main/java/com/iluwatar/reactor/app/App.java index 2c49d9001..d074c9b19 100644 --- a/reactor/src/main/java/com/iluwatar/reactor/app/App.java +++ b/reactor/src/main/java/com/iluwatar/reactor/app/App.java @@ -80,8 +80,6 @@ public class App { /** * App entry. - * - * @throws IOException */ public static void main(String[] args) throws IOException { new App(new ThreadPoolDispatcher(2)).start(); 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 ee25b0be0..13cdd70e1 100644 --- a/reactor/src/main/java/com/iluwatar/reactor/app/AppClient.java +++ b/reactor/src/main/java/com/iluwatar/reactor/app/AppClient.java @@ -37,10 +37,10 @@ public class AppClient { * @throws IOException if any I/O error occurs. */ public void start() throws IOException { - service.execute(new TCPLoggingClient("Client 1", 6666)); - service.execute(new TCPLoggingClient("Client 2", 6667)); - service.execute(new UDPLoggingClient("Client 3", 6668)); - service.execute(new UDPLoggingClient("Client 4", 6668)); + service.execute(new TcpLoggingClient("Client 1", 6666)); + service.execute(new TcpLoggingClient("Client 2", 6667)); + service.execute(new UdpLoggingClient("Client 3", 6668)); + service.execute(new UdpLoggingClient("Client 4", 6668)); } /** @@ -69,7 +69,7 @@ public class AppClient { /** * A logging client that sends requests to Reactor on TCP socket. */ - static class TCPLoggingClient implements Runnable { + static class TcpLoggingClient implements Runnable { private final int serverPort; private final String clientName; @@ -80,7 +80,7 @@ public class AppClient { * @param clientName the name of the client to be sent in logging requests. * @param port the port on which client will send logging requests. */ - public TCPLoggingClient(String clientName, int serverPort) { + public TcpLoggingClient(String clientName, int serverPort) { this.clientName = clientName; this.serverPort = serverPort; } @@ -118,7 +118,7 @@ public class AppClient { /** * A logging client that sends requests to Reactor on UDP socket. */ - static class UDPLoggingClient implements Runnable { + static class UdpLoggingClient implements Runnable { private final String clientName; private final InetSocketAddress remoteAddress; @@ -129,7 +129,7 @@ public class AppClient { * @param port the port on which client will send logging requests. * @throws UnknownHostException if localhost is unknown */ - public UDPLoggingClient(String clientName, int port) throws UnknownHostException { + public UdpLoggingClient(String clientName, int port) throws UnknownHostException { this.clientName = clientName; this.remoteAddress = new InetSocketAddress(InetAddress.getLocalHost(), port); } diff --git a/reactor/src/main/java/com/iluwatar/reactor/framework/AbstractNioChannel.java b/reactor/src/main/java/com/iluwatar/reactor/framework/AbstractNioChannel.java index df08426d0..cd1318c89 100644 --- a/reactor/src/main/java/com/iluwatar/reactor/framework/AbstractNioChannel.java +++ b/reactor/src/main/java/com/iluwatar/reactor/framework/AbstractNioChannel.java @@ -131,6 +131,7 @@ public abstract class AbstractNioChannel { * channel.write(buffer, key); * } * + * * * @param data the data to be written on underlying channel. * @param key the key which is writable. 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 16c13e5f9..271a6975d 100644 --- a/reactor/src/main/java/com/iluwatar/reactor/framework/NioReactor.java +++ b/reactor/src/main/java/com/iluwatar/reactor/framework/NioReactor.java @@ -14,40 +14,41 @@ import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; /** - * This class acts as Synchronous Event De-multiplexer and Initiation Dispatcher of Reactor pattern. - * Multiple handles i.e. {@link AbstractNioChannel}s can be registered to the reactor and it blocks - * for events from all these handles. Whenever an event occurs on any of the registered handles, it - * synchronously de-multiplexes the event which can be any of read, write or accept, and dispatches - * the event to the appropriate {@link ChannelHandler} using the {@link Dispatcher}. + * This class acts as Synchronous Event De-multiplexer and Initiation Dispatcher of Reactor pattern. Multiple handles + * i.e. {@link AbstractNioChannel}s can be registered to the reactor and it blocks for events from all these handles. + * Whenever an event occurs on any of the registered handles, it synchronously de-multiplexes the event which can be any + * of read, write or accept, and dispatches the event to the appropriate {@link ChannelHandler} using the + * {@link Dispatcher}. * *

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

- * NOTE: This is one of the ways to implement NIO reactor and it does not take care of all possible - * edge cases which are required in a real application. This implementation is meant to demonstrate - * the fundamental concepts that lie behind Reactor pattern. + * NOTE: This is one of the ways to implement NIO reactor and it does not take care of all possible edge cases which are + * required in a real application. This implementation is meant to demonstrate the fundamental concepts that lie behind + * Reactor pattern. */ public class NioReactor { private final Selector selector; private final Dispatcher dispatcher; /** - * All the work of altering the SelectionKey operations and Selector operations are performed in - * the context of main event loop of reactor. So when any channel needs to change its readability - * or writability, a new command is added in the command queue and then the event loop picks up - * the command and executes it in next iteration. + * All the work of altering the SelectionKey operations and Selector operations are performed in the context of main + * event loop of reactor. So when any channel needs to change its readability or writability, a new command is added + * in the command queue and then the event loop picks up the command and executes it in next iteration. */ private final Queue pendingCommands = new ConcurrentLinkedQueue<>(); private final ExecutorService reactorMain = Executors.newSingleThreadExecutor(); /** - * Creates a reactor which will use provided {@code dispatcher} to dispatch events. The - * application can provide various implementations of dispatcher which suits its needs. + * Creates a reactor which will use provided {@code dispatcher} to dispatch events. The application can provide + * various implementations of dispatcher which suits its needs. * - * @param dispatcher a non-null dispatcher used to dispatch events on registered channels. - * @throws IOException if any I/O error occurs. + * @param dispatcher + * a non-null dispatcher used to dispatch events on registered channels. + * @throws IOException + * if any I/O error occurs. */ public NioReactor(Dispatcher dispatcher) throws IOException { this.dispatcher = dispatcher; @@ -57,7 +58,8 @@ public class NioReactor { /** * Starts the reactor event loop in a new thread. * - * @throws IOException if any I/O error occurs. + * @throws IOException + * if any I/O error occurs. */ public void start() throws IOException { reactorMain.execute(() -> { @@ -73,8 +75,10 @@ public class NioReactor { /** * Stops the reactor and related resources such as dispatcher. * - * @throws InterruptedException if interrupted while stopping the reactor. - * @throws IOException if any I/O error occurs. + * @throws InterruptedException + * if interrupted while stopping the reactor. + * @throws IOException + * if any I/O error occurs. */ public void stop() throws InterruptedException, IOException { reactorMain.shutdownNow(); @@ -84,15 +88,15 @@ public class NioReactor { } /** - * Registers a new channel (handle) with this reactor. Reactor will start waiting for events on - * this channel and notify of any events. While registering the channel the reactor uses - * {@link AbstractNioChannel#getInterestedOps()} to know about the interested operation of this - * channel. + * Registers a new channel (handle) with this reactor. Reactor will start waiting for events on this channel and + * notify of any events. While registering the channel the reactor uses {@link AbstractNioChannel#getInterestedOps()} + * to know about the interested operation of this channel. * - * @param channel a new channel on which reactor will wait for events. The channel must be bound - * prior to being registered. + * @param channel + * a new channel on which reactor will wait for events. The channel must be bound prior to being registered. * @return this - * @throws IOException if any I/O error occurs. + * @throws IOException + * if any I/O error occurs. */ public NioReactor registerChannel(AbstractNioChannel channel) throws IOException { SelectionKey key = channel.getJavaChannel().register(selector, channel.getInterestedOps()); @@ -113,8 +117,8 @@ public class NioReactor { processPendingCommands(); /* - * Synchronous event de-multiplexing happens here, this is blocking call which returns when it - * is possible to initiate non-blocking operation on any of the registered channels. + * Synchronous event de-multiplexing happens here, this is blocking call which returns when it is possible to + * initiate non-blocking operation on any of the registered channels. */ selector.select(); @@ -147,8 +151,8 @@ public class NioReactor { } /* - * Initiation dispatcher logic, it checks the type of event and notifier application specific - * event handler to handle the event. + * Initiation dispatcher logic, it checks the type of event and notifier application specific event handler to handle + * the event. */ private void processKey(SelectionKey key) throws IOException { if (key.isAcceptable()) { @@ -196,14 +200,15 @@ public class NioReactor { } /** - * Queues the change of operations request of a channel, which will change the interested - * operations of the channel sometime in future. + * Queues the change of operations request of a channel, which will change the interested operations of the channel + * sometime in future. *

- * This is a non-blocking method and does not guarantee that the operations have changed when this - * method returns. + * This is a non-blocking method and does not guarantee that the operations have changed when this method returns. * - * @param key the key for which operations have to be changed. - * @param interestedOps the new interest operations. + * @param key + * the key for which operations have to be changed. + * @param interestedOps + * the new interest operations. */ public void changeOps(SelectionKey key, int interestedOps) { pendingCommands.add(new ChangeKeyOpsCommand(key, interestedOps)); diff --git a/repository/src/main/java/com/iluwatar/repository/AppConfig.java b/repository/src/main/java/com/iluwatar/repository/AppConfig.java index cca09d8aa..62b9a4c04 100644 --- a/repository/src/main/java/com/iluwatar/repository/AppConfig.java +++ b/repository/src/main/java/com/iluwatar/repository/AppConfig.java @@ -39,8 +39,6 @@ public class AppConfig { /** * Factory to create a especific instance of Entity Manager - * - * @return */ @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory() { @@ -55,8 +53,6 @@ public class AppConfig { /** * Properties for Jpa - * - * @return */ private Properties jpaProperties() { Properties properties = new Properties(); @@ -65,6 +61,9 @@ public class AppConfig { return properties; } + /** + * Get transaction manager + */ @Bean public JpaTransactionManager transactionManager() throws SQLException { JpaTransactionManager transactionManager = new JpaTransactionManager(); diff --git a/repository/src/main/java/com/iluwatar/repository/Person.java b/repository/src/main/java/com/iluwatar/repository/Person.java index ca4013b54..04d65a6d0 100644 --- a/repository/src/main/java/com/iluwatar/repository/Person.java +++ b/repository/src/main/java/com/iluwatar/repository/Person.java @@ -23,6 +23,9 @@ public class Person { public Person() { } + /** + * Constructor + */ public Person(String name, String surname, int age) { this.name = name; this.surname = surname; @@ -80,30 +83,40 @@ public class Person { @Override public boolean equals(Object obj) { - if (this == obj) + if (this == obj) { return true; - if (obj == null) + } + if (obj == null) { return false; - if (getClass() != obj.getClass()) + } + if (getClass() != obj.getClass()) { return false; + } Person other = (Person) obj; - if (age != other.age) + if (age != other.age) { return false; + } if (id == null) { - if (other.id != null) + if (other.id != null) { return false; - } else if (!id.equals(other.id)) + } + } else if (!id.equals(other.id)) { return false; + } if (name == null) { - if (other.name != null) + if (other.name != null) { return false; - } else if (!name.equals(other.name)) + } + } else if (!name.equals(other.name)) { return false; + } if (surname == null) { - if (other.surname != null) + if (other.surname != null) { return false; - } else if (!surname.equals(other.surname)) + } + } else if (!surname.equals(other.surname)) { return false; + } return true; } diff --git a/repository/src/main/java/com/iluwatar/repository/PersonSpecifications.java b/repository/src/main/java/com/iluwatar/repository/PersonSpecifications.java index ce9842dff..fa96f3ca6 100644 --- a/repository/src/main/java/com/iluwatar/repository/PersonSpecifications.java +++ b/repository/src/main/java/com/iluwatar/repository/PersonSpecifications.java @@ -32,6 +32,10 @@ public class PersonSpecifications { } + /** + * Name specification + * + */ public static class NameEqualSpec implements Specification { public String name; @@ -40,6 +44,9 @@ public class PersonSpecifications { this.name = name; } + /** + * Get predicate + */ public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder cb) { return cb.equal(root.get("name"), this.name); diff --git a/repository/src/main/resources/META-INF/persistence.xml b/repository/src/main/resources/META-INF/persistence.xml index 0aded0dbd..00767fbc2 100644 --- a/repository/src/main/resources/META-INF/persistence.xml +++ b/repository/src/main/resources/META-INF/persistence.xml @@ -1,8 +1,8 @@ + xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"> - + diff --git a/repository/src/main/resources/applicationContext.xml b/repository/src/main/resources/applicationContext.xml index 9322c9f64..ed03aba0a 100644 --- a/repository/src/main/resources/applicationContext.xml +++ b/repository/src/main/resources/applicationContext.xml @@ -1,39 +1,37 @@ - + - - - - - + - - - - - - + + + - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + diff --git a/repository/src/test/java/com/iluwatar/repository/AnnotationBasedRepositoryTest.java b/repository/src/test/java/com/iluwatar/repository/AnnotationBasedRepositoryTest.java index 6f8746aa6..682d2021f 100644 --- a/repository/src/test/java/com/iluwatar/repository/AnnotationBasedRepositoryTest.java +++ b/repository/src/test/java/com/iluwatar/repository/AnnotationBasedRepositoryTest.java @@ -90,8 +90,8 @@ public class AnnotationBasedRepositoryTest { assertEquals(3, persons.size()); assertTrue(persons.stream().allMatch((item) -> { - return item.getAge() > 20 && item.getAge() < 40; - })); + return item.getAge() > 20 && item.getAge() < 40; + })); } @Test diff --git a/repository/src/test/java/com/iluwatar/repository/AppConfigTest.java b/repository/src/test/java/com/iluwatar/repository/AppConfigTest.java index 49e684bf1..17393f2ff 100644 --- a/repository/src/test/java/com/iluwatar/repository/AppConfigTest.java +++ b/repository/src/test/java/com/iluwatar/repository/AppConfigTest.java @@ -1,6 +1,7 @@ package com.iluwatar.repository; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; import java.sql.ResultSet; import java.sql.SQLException; @@ -36,8 +37,6 @@ public class AppConfigTest { /** * Test for correct query execution - * - * @throws SQLException */ @Test @Transactional diff --git a/repository/src/test/java/com/iluwatar/repository/RepositoryTest.java b/repository/src/test/java/com/iluwatar/repository/RepositoryTest.java index 3d6708815..9eb6b4723 100644 --- a/repository/src/test/java/com/iluwatar/repository/RepositoryTest.java +++ b/repository/src/test/java/com/iluwatar/repository/RepositoryTest.java @@ -88,8 +88,8 @@ public class RepositoryTest { assertEquals(3, persons.size()); assertTrue(persons.stream().allMatch((item) -> { - return item.getAge() > 20 && item.getAge() < 40; - })); + return item.getAge() > 20 && item.getAge() < 40; + })); } @Test 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 32cd3792e..f734432af 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 @@ -24,9 +24,6 @@ public class App { /** * Program entry point - * - * @param args command line args - * @throws Exception */ public static void main(String[] args) throws Exception { diff --git a/servant/src/main/java/com/iluwatar/servant/App.java b/servant/src/main/java/com/iluwatar/servant/App.java index 42babbc1d..cb5a63fa5 100644 --- a/servant/src/main/java/com/iluwatar/servant/App.java +++ b/servant/src/main/java/com/iluwatar/servant/App.java @@ -18,15 +18,13 @@ public class App { /** * Program entry point - * - * @param args */ public static void main(String[] args) { scenario(jenkins, 1); scenario(travis, 0); } - /* + /** * Can add a List with enum Actions for variable scenarios */ public static void scenario(Servant servant, int compliment) { @@ -44,16 +42,18 @@ public class App { servant.giveWine(k); servant.giveWine(q); // compliment - servant.GiveCompliments(guests.get(compliment)); + servant.giveCompliments(guests.get(compliment)); // outcome of the night - for (Royalty r : guests) + for (Royalty r : guests) { r.changeMood(); + } // check your luck - if (servant.checkIfYouWillBeHanged(guests)) + if (servant.checkIfYouWillBeHanged(guests)) { System.out.println(servant.name + " will live another day"); - else + } else { System.out.println("Poor " + servant.name + ". His days are numbered"); + } } } diff --git a/servant/src/main/java/com/iluwatar/servant/King.java b/servant/src/main/java/com/iluwatar/servant/King.java index 5e931c149..ab99252ad 100644 --- a/servant/src/main/java/com/iluwatar/servant/King.java +++ b/servant/src/main/java/com/iluwatar/servant/King.java @@ -28,10 +28,12 @@ public class King implements Royalty { @Override public void changeMood() { - if (!isHungry && isDrunk) + if (!isHungry && isDrunk) { isHappy = true; - if (complimentReceived) + } + if (complimentReceived) { isHappy = false; + } } @Override diff --git a/servant/src/main/java/com/iluwatar/servant/Queen.java b/servant/src/main/java/com/iluwatar/servant/Queen.java index db5446d34..cc33ab470 100644 --- a/servant/src/main/java/com/iluwatar/servant/Queen.java +++ b/servant/src/main/java/com/iluwatar/servant/Queen.java @@ -29,8 +29,9 @@ public class Queen implements Royalty { @Override public void changeMood() { - if (complimentReceived && isFlirty && isDrunk) + if (complimentReceived && isFlirty && isDrunk) { isHappy = true; + } } @Override diff --git a/servant/src/main/java/com/iluwatar/servant/Servant.java b/servant/src/main/java/com/iluwatar/servant/Servant.java index 987bf8791..dbb623331 100644 --- a/servant/src/main/java/com/iluwatar/servant/Servant.java +++ b/servant/src/main/java/com/iluwatar/servant/Servant.java @@ -11,6 +11,9 @@ public class Servant { public String name; + /** + * Constructor + */ public Servant(String name) { this.name = name; } @@ -23,15 +26,20 @@ public class Servant { r.getDrink(); } - public void GiveCompliments(Royalty r) { + public void giveCompliments(Royalty r) { r.receiveCompliments(); } + /** + * Check if we will be hanged + */ public boolean checkIfYouWillBeHanged(ArrayList tableGuests) { boolean anotherDay = true; - for (Royalty r : tableGuests) - if (!r.getMood()) + for (Royalty r : tableGuests) { + if (!r.getMood()) { anotherDay = false; + } + } return anotherDay; } 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 a7053165d..ab0d3f9a0 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 @@ -47,6 +47,9 @@ public class App { queryData(); } + /** + * Initialize data + */ public static void initData() { // spells Spell spell1 = new Spell("Ice dart"); @@ -149,6 +152,9 @@ public class App { wizardDao.merge(wizard4); } + /** + * Query the data + */ public static void queryData() { MagicService service = new MagicServiceImpl(new WizardDaoImpl(), new SpellbookDaoImpl(), new SpellDaoImpl()); diff --git a/service-layer/src/main/java/com/iluwatar/servicelayer/common/DaoBaseImpl.java b/service-layer/src/main/java/com/iluwatar/servicelayer/common/DaoBaseImpl.java index eae9286fa..2665ff858 100644 --- a/service-layer/src/main/java/com/iluwatar/servicelayer/common/DaoBaseImpl.java +++ b/service-layer/src/main/java/com/iluwatar/servicelayer/common/DaoBaseImpl.java @@ -39,8 +39,9 @@ public abstract class DaoBaseImpl implements Dao { result = (E) criteria.uniqueResult(); tx.commit(); } catch (Exception e) { - if (tx != null) + if (tx != null) { tx.rollback(); + } throw e; } finally { session.close(); @@ -57,8 +58,9 @@ public abstract class DaoBaseImpl implements Dao { session.persist(entity); tx.commit(); } catch (Exception e) { - if (tx != null) + if (tx != null) { tx.rollback(); + } throw e; } finally { session.close(); @@ -75,8 +77,9 @@ public abstract class DaoBaseImpl implements Dao { result = (E) session.merge(entity); tx.commit(); } catch (Exception e) { - if (tx != null) + if (tx != null) { tx.rollback(); + } throw e; } finally { session.close(); @@ -93,8 +96,9 @@ public abstract class DaoBaseImpl implements Dao { session.delete(entity); tx.commit(); } catch (Exception e) { - if (tx != null) + if (tx != null) { tx.rollback(); + } throw e; } finally { session.close(); @@ -111,8 +115,9 @@ public abstract class DaoBaseImpl implements Dao { Criteria criteria = session.createCriteria(persistentClass); result = criteria.list(); } catch (Exception e) { - if (tx != null) + if (tx != null) { tx.rollback(); + } throw e; } finally { session.close(); 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 9d1aec488..fce6fb873 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 @@ -14,11 +14,11 @@ import com.iluwatar.servicelayer.wizard.Wizard; */ public class HibernateUtil { - private static final SessionFactory sessionFactory; + private static final SessionFactory SESSION_FACTORY; static { try { - sessionFactory = + SESSION_FACTORY = new Configuration().addAnnotatedClass(Wizard.class).addAnnotatedClass(Spellbook.class) .addAnnotatedClass(Spell.class) .setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect") @@ -33,6 +33,6 @@ public class HibernateUtil { } public static SessionFactory getSessionFactory() { - return sessionFactory; + return SESSION_FACTORY; } } diff --git a/service-layer/src/main/java/com/iluwatar/servicelayer/magic/MagicServiceImpl.java b/service-layer/src/main/java/com/iluwatar/servicelayer/magic/MagicServiceImpl.java index f46f55184..cda3fe58d 100644 --- a/service-layer/src/main/java/com/iluwatar/servicelayer/magic/MagicServiceImpl.java +++ b/service-layer/src/main/java/com/iluwatar/servicelayer/magic/MagicServiceImpl.java @@ -21,6 +21,9 @@ public class MagicServiceImpl implements MagicService { private SpellbookDao spellbookDao; private SpellDao spellDao; + /** + * Constructor + */ public MagicServiceImpl(WizardDao wizardDao, SpellbookDao spellbookDao, SpellDao spellDao) { this.wizardDao = wizardDao; this.spellbookDao = spellbookDao; diff --git a/service-layer/src/main/java/com/iluwatar/servicelayer/spell/SpellDaoImpl.java b/service-layer/src/main/java/com/iluwatar/servicelayer/spell/SpellDaoImpl.java index f5f017625..66d06448b 100644 --- a/service-layer/src/main/java/com/iluwatar/servicelayer/spell/SpellDaoImpl.java +++ b/service-layer/src/main/java/com/iluwatar/servicelayer/spell/SpellDaoImpl.java @@ -27,8 +27,9 @@ public class SpellDaoImpl extends DaoBaseImpl implements SpellDao { result.getSpellbook().getWizards().size(); tx.commit(); } catch (Exception e) { - if (tx != null) + if (tx != null) { tx.rollback(); + } throw e; } finally { session.close(); diff --git a/service-layer/src/main/java/com/iluwatar/servicelayer/spellbook/SpellbookDaoImpl.java b/service-layer/src/main/java/com/iluwatar/servicelayer/spellbook/SpellbookDaoImpl.java index 1de82d4a9..842764056 100644 --- a/service-layer/src/main/java/com/iluwatar/servicelayer/spellbook/SpellbookDaoImpl.java +++ b/service-layer/src/main/java/com/iluwatar/servicelayer/spellbook/SpellbookDaoImpl.java @@ -28,8 +28,9 @@ public class SpellbookDaoImpl extends DaoBaseImpl implements Spellboo result.getWizards().size(); tx.commit(); } catch (Exception e) { - if (tx != null) + if (tx != null) { tx.rollback(); + } throw e; } finally { session.close(); diff --git a/service-layer/src/main/java/com/iluwatar/servicelayer/wizard/WizardDaoImpl.java b/service-layer/src/main/java/com/iluwatar/servicelayer/wizard/WizardDaoImpl.java index ad89dd28a..9ff36edef 100644 --- a/service-layer/src/main/java/com/iluwatar/servicelayer/wizard/WizardDaoImpl.java +++ b/service-layer/src/main/java/com/iluwatar/servicelayer/wizard/WizardDaoImpl.java @@ -30,8 +30,9 @@ public class WizardDaoImpl extends DaoBaseImpl implements WizardDao { } tx.commit(); } catch (Exception e) { - if (tx != null) + if (tx != null) { tx.rollback(); + } throw e; } finally { session.close(); 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 f2d338cdc..f2dd31221 100644 --- a/service-locator/src/main/java/com/iluwatar/servicelocator/ServiceImpl.java +++ b/service-locator/src/main/java/com/iluwatar/servicelocator/ServiceImpl.java @@ -12,6 +12,9 @@ public class ServiceImpl implements Service { private final String serviceName; private final int id; + /** + * Constructor + */ public ServiceImpl(String serviceName) { // set the service name this.serviceName = serviceName; diff --git a/singleton/src/main/java/com/iluwatar/singleton/IvoryTower.java b/singleton/src/main/java/com/iluwatar/singleton/IvoryTower.java index 585b11e61..f8b7e170f 100644 --- a/singleton/src/main/java/com/iluwatar/singleton/IvoryTower.java +++ b/singleton/src/main/java/com/iluwatar/singleton/IvoryTower.java @@ -8,7 +8,7 @@ public final class IvoryTower { /** * Static to class instance of the class. */ - private static final IvoryTower instance = new IvoryTower(); + private static final IvoryTower INSTANCE = new IvoryTower(); /** * Private constructor so nobody can instantiate the class. @@ -21,6 +21,6 @@ public final class IvoryTower { * @return instance of the singleton. */ public static IvoryTower getInstance() { - return instance; + return INSTANCE; } } diff --git a/singleton/src/main/java/com/iluwatar/singleton/ThreadSafeDoubleCheckLocking.java b/singleton/src/main/java/com/iluwatar/singleton/ThreadSafeDoubleCheckLocking.java index 1aca15b30..ab39a652d 100644 --- a/singleton/src/main/java/com/iluwatar/singleton/ThreadSafeDoubleCheckLocking.java +++ b/singleton/src/main/java/com/iluwatar/singleton/ThreadSafeDoubleCheckLocking.java @@ -11,14 +11,14 @@ package com.iluwatar.singleton; */ public class ThreadSafeDoubleCheckLocking { - private static volatile ThreadSafeDoubleCheckLocking INSTANCE; + private static volatile ThreadSafeDoubleCheckLocking instance; /** * private constructor to prevent client from instantiating. */ private ThreadSafeDoubleCheckLocking() { // to prevent instantiating by Reflection call - if (INSTANCE != null) { + if (instance != null) { throw new IllegalStateException("Already initialized."); } } @@ -31,12 +31,12 @@ public class ThreadSafeDoubleCheckLocking { public static ThreadSafeDoubleCheckLocking getInstance() { // local variable increases performance by 25 percent // Joshua Bloch "Effective Java, Second Edition", p. 283-284 - ThreadSafeDoubleCheckLocking result = INSTANCE; + ThreadSafeDoubleCheckLocking result = instance; if (result == null) { synchronized (ThreadSafeDoubleCheckLocking.class) { - result = INSTANCE; + result = instance; if (result == null) { - INSTANCE = result = new ThreadSafeDoubleCheckLocking(); + instance = result = new ThreadSafeDoubleCheckLocking(); } } } diff --git a/singleton/src/main/java/com/iluwatar/singleton/ThreadSafeLazyLoadedIvoryTower.java b/singleton/src/main/java/com/iluwatar/singleton/ThreadSafeLazyLoadedIvoryTower.java index 98281b4c8..e67922016 100644 --- a/singleton/src/main/java/com/iluwatar/singleton/ThreadSafeLazyLoadedIvoryTower.java +++ b/singleton/src/main/java/com/iluwatar/singleton/ThreadSafeLazyLoadedIvoryTower.java @@ -16,7 +16,7 @@ public class ThreadSafeLazyLoadedIvoryTower { /** * The instance gets created only when it is called for first time. Lazy-loading */ - public synchronized static ThreadSafeLazyLoadedIvoryTower getInstance() { + public static synchronized ThreadSafeLazyLoadedIvoryTower getInstance() { if (instance == null) { instance = new ThreadSafeLazyLoadedIvoryTower(); diff --git a/singleton/src/test/java/com/iluwatar/singleton/LazyLoadedSingletonThreadSafetyTest.java b/singleton/src/test/java/com/iluwatar/singleton/LazyLoadedSingletonThreadSafetyTest.java index 3afc1bf14..24cd7cf4b 100644 --- a/singleton/src/test/java/com/iluwatar/singleton/LazyLoadedSingletonThreadSafetyTest.java +++ b/singleton/src/test/java/com/iluwatar/singleton/LazyLoadedSingletonThreadSafetyTest.java @@ -1,13 +1,17 @@ package com.iluwatar.singleton; -import org.junit.Test; +import static org.junit.Assert.assertEquals; import java.util.ArrayList; import java.util.Collections; import java.util.List; -import java.util.concurrent.*; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; -import static org.junit.Assert.assertEquals; +import org.junit.Test; /** * This class provides several test case that test singleton construction. @@ -29,7 +33,7 @@ public class LazyLoadedSingletonThreadSafetyTest { } @Test - public void test_MultipleCallsReturnTheSameObjectInSameThread() { + public void testMultipleCallsReturnTheSameObjectInSameThread() { // Create several instances in the same calling thread ThreadSafeLazyLoadedIvoryTower instance1 = ThreadSafeLazyLoadedIvoryTower.getInstance(); ThreadSafeLazyLoadedIvoryTower instance2 = ThreadSafeLazyLoadedIvoryTower.getInstance(); @@ -42,9 +46,10 @@ public class LazyLoadedSingletonThreadSafetyTest { } @Test - public void test_MultipleCallsReturnTheSameObjectInDifferentThreads() + public void testMultipleCallsReturnTheSameObjectInDifferentThreads() throws InterruptedException, ExecutionException { - {// create several threads and inside each callable instantiate the singleton class + { + // create several threads and inside each callable instantiate the singleton class ExecutorService executorService = Executors.newSingleThreadExecutor(); List> threadList = new ArrayList<>(); @@ -63,7 +68,8 @@ public class LazyLoadedSingletonThreadSafetyTest { // tidy up the executor executorService.shutdown(); } - {// now check the contents that were added to threadObjects by each thread + { + // now check the contents that were added to threadObjects by each thread assertEquals(NUM_THREADS, threadObjects.size()); assertEquals(threadObjects.get(0), threadObjects.get(1)); assertEquals(threadObjects.get(1), threadObjects.get(2)); 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 d755d6c2e..373a24f92 100644 --- a/specification/src/main/java/com/iluwatar/specification/app/App.java +++ b/specification/src/main/java/com/iluwatar/specification/app/App.java @@ -31,6 +31,9 @@ import com.iluwatar.specification.selector.MovementSelector; */ public class App { + /** + * Program entry point + */ public static void main(String[] args) { // initialize creatures list List creatures = diff --git a/specification/src/main/java/com/iluwatar/specification/creature/AbstractCreature.java b/specification/src/main/java/com/iluwatar/specification/creature/AbstractCreature.java index 2ec3ccf55..f02befb73 100644 --- a/specification/src/main/java/com/iluwatar/specification/creature/AbstractCreature.java +++ b/specification/src/main/java/com/iluwatar/specification/creature/AbstractCreature.java @@ -16,6 +16,9 @@ public abstract class AbstractCreature implements Creature { private Movement movement; private Color color; + /** + * Constructor + */ public AbstractCreature(String name, Size size, Movement movement, Color color) { this.name = name; this.size = size; diff --git a/state/src/main/java/com/iluwatar/state/App.java b/state/src/main/java/com/iluwatar/state/App.java index 2013466e0..63b59ad59 100644 --- a/state/src/main/java/com/iluwatar/state/App.java +++ b/state/src/main/java/com/iluwatar/state/App.java @@ -13,6 +13,9 @@ package com.iluwatar.state; */ public class App { + /** + * Program entry point + */ public static void main(String[] args) { Mammoth mammoth = new Mammoth(); diff --git a/state/src/main/java/com/iluwatar/state/Mammoth.java b/state/src/main/java/com/iluwatar/state/Mammoth.java index 8269ecb3d..92f4d7188 100644 --- a/state/src/main/java/com/iluwatar/state/Mammoth.java +++ b/state/src/main/java/com/iluwatar/state/Mammoth.java @@ -13,6 +13,9 @@ public class Mammoth { state = new PeacefulState(this); } + /** + * Makes time pass for the mammoth + */ public void timePasses() { if (state.getClass().equals(PeacefulState.class)) { changeStateTo(new AngryState(this)); 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 3bf7b9a68..a839cd49e 100644 --- a/step-builder/src/main/java/com/iluwatar/stepbuilder/App.java +++ b/step-builder/src/main/java/com/iluwatar/stepbuilder/App.java @@ -11,7 +11,7 @@ package com.iluwatar.stepbuilder; * methods available, NO build method until is the right time to build the object. * *

- * Implementation
+ * Implementation *