From 50467c9e76a45cd6dd40161ac6466d9ee9e94eab Mon Sep 17 00:00:00 2001 From: Anurag Agarwal Date: Thu, 14 Nov 2019 11:12:05 +0530 Subject: [PATCH] Java 11 migration: patterns (t-v) (#1085) * Moves visitor pattern to java 11 * Moves value-object pattern to java 11 * Moves unit-of-work pattern to java 11 * Moves typeobjectpattern pattern to java 11 * Moves twin pattern to java 11 * Moves trampoline pattern to java 11 * Moves tolerant-reader pattern to java 11 * Moves tls pattern to java 11 * Moves throttling pattern to java 11 * Moves thread-pool pattern to java 11 * Moves template-method pattern to java 11 --- .../com/iluwatar/templatemethod/AppTest.java | 5 +- .../templatemethod/HalflingThiefTest.java | 14 +-- .../templatemethod/StealingMethodTest.java | 7 +- .../java/com/iluwatar/threadpool/App.java | 7 +- .../java/com/iluwatar/threadpool/AppTest.java | 6 +- .../com/iluwatar/threadpool/TaskTest.java | 33 +++---- .../com/iluwatar/threadpool/WorkerTest.java | 8 +- .../java/com/iluwatar/throttling/App.java | 7 +- .../com/iluwatar/throttling/CallsCount.java | 4 +- .../java/com/iluwatar/throttling/AppTest.java | 3 +- .../iluwatar/throttling/B2BServiceTest.java | 19 ++-- .../com/iluwatar/throttling/TenantTest.java | 7 +- tls/src/main/java/com/iluwatar/tls/App.java | 44 ++++----- .../com/iluwatar/tls/DateFormatCallable.java | 19 ++-- .../main/java/com/iluwatar/tls/Result.java | 4 +- .../test/java/com/iluwatar/tls/AppTest.java | 8 +- .../iluwatar/tls/DateFormatCallableTest.java | 82 ++++++++-------- ...FormatCallableTestIncorrectDateFormat.java | 63 ++++++------ .../DateFormatCallableTestMultiThread.java | 98 +++++++++---------- .../tolerantreader/RainbowFishSerializer.java | 11 ++- .../com/iluwatar/tolerantreader/AppTest.java | 14 +-- .../RainbowFishSerializerTest.java | 17 ++-- .../tolerantreader/RainbowFishTest.java | 6 +- .../tolerantreader/RainbowFishV2Test.java | 6 +- .../com/iluwatar/trampoline/Trampoline.java | 6 +- .../iluwatar/trampoline/TrampolineApp.java | 2 +- .../trampoline/TrampolineAppTest.java | 10 +- .../test/java/com/iluwatar/twin/AppTest.java | 5 +- .../java/com/iluwatar/twin/BallItemTest.java | 22 ++--- .../com/iluwatar/twin/BallThreadTest.java | 24 +++-- .../com/iluwatar/typeobject/CandyGame.java | 25 +++-- .../com/iluwatar/typeobject/CellPool.java | 5 +- .../com/iluwatar/typeobject/JsonParser.java | 20 ++-- .../iluwatar/typeobject/CandyGameTest.java | 26 ++--- .../com/iluwatar/typeobject/CellPoolTest.java | 9 +- .../com/iluwatar/typeobject/CellTest.java | 21 ++-- .../java/com/iluwatar/unitofwork/AppTest.java | 5 +- .../unitofwork/StudentRepositoryTest.java | 38 +++---- .../com/iluwatar/value/object/AppTest.java | 3 +- .../iluwatar/value/object/HeroStatTest.java | 14 ++- .../main/java/com/iluwatar/visitor/App.java | 14 +-- .../main/java/com/iluwatar/visitor/Unit.java | 6 +- .../java/com/iluwatar/visitor/AppTest.java | 3 +- .../java/com/iluwatar/visitor/UnitTest.java | 9 +- .../com/iluwatar/visitor/VisitorTest.java | 16 +-- 45 files changed, 366 insertions(+), 409 deletions(-) diff --git a/template-method/src/test/java/com/iluwatar/templatemethod/AppTest.java b/template-method/src/test/java/com/iluwatar/templatemethod/AppTest.java index d20ac061c11..e70e8a78ff9 100644 --- a/template-method/src/test/java/com/iluwatar/templatemethod/AppTest.java +++ b/template-method/src/test/java/com/iluwatar/templatemethod/AppTest.java @@ -26,15 +26,12 @@ import org.junit.jupiter.api.Test; /** - * * Application test - * */ public class AppTest { @Test public void test() { - String[] args = {}; - App.main(args); + App.main(new String[]{}); } } diff --git a/template-method/src/test/java/com/iluwatar/templatemethod/HalflingThiefTest.java b/template-method/src/test/java/com/iluwatar/templatemethod/HalflingThiefTest.java index a040afe83b0..952705756aa 100644 --- a/template-method/src/test/java/com/iluwatar/templatemethod/HalflingThiefTest.java +++ b/template-method/src/test/java/com/iluwatar/templatemethod/HalflingThiefTest.java @@ -23,12 +23,12 @@ package com.iluwatar.templatemethod; -import org.junit.jupiter.api.Test; - import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; +import org.junit.jupiter.api.Test; + /** * Date: 12/29/15 - 18:15 PM * @@ -41,8 +41,8 @@ public class HalflingThiefTest { */ @Test public void testSteal() { - final StealingMethod method = mock(StealingMethod.class); - final HalflingThief thief = new HalflingThief(method); + final var method = mock(StealingMethod.class); + final var thief = new HalflingThief(method); thief.steal(); verify(method).steal(); @@ -55,13 +55,13 @@ public void testSteal() { */ @Test public void testChangeMethod() { - final StealingMethod initialMethod = mock(StealingMethod.class); - final HalflingThief thief = new HalflingThief(initialMethod); + final var initialMethod = mock(StealingMethod.class); + final var thief = new HalflingThief(initialMethod); thief.steal(); verify(initialMethod).steal(); - final StealingMethod newMethod = mock(StealingMethod.class); + final var newMethod = mock(StealingMethod.class); thief.changeMethod(newMethod); thief.steal(); diff --git a/template-method/src/test/java/com/iluwatar/templatemethod/StealingMethodTest.java b/template-method/src/test/java/com/iluwatar/templatemethod/StealingMethodTest.java index 19b36fa1f87..ba6030da480 100644 --- a/template-method/src/test/java/com/iluwatar/templatemethod/StealingMethodTest.java +++ b/template-method/src/test/java/com/iluwatar/templatemethod/StealingMethodTest.java @@ -23,6 +23,9 @@ package com.iluwatar.templatemethod; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.AppenderBase; @@ -33,11 +36,9 @@ import org.junit.jupiter.api.Test; import org.slf4j.LoggerFactory; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - /** * Date: 12/30/15 - 18:12 PM + * * @param Type of StealingMethod * @author Jeroen Meulemeester */ diff --git a/thread-pool/src/main/java/com/iluwatar/threadpool/App.java b/thread-pool/src/main/java/com/iluwatar/threadpool/App.java index 0d5ee23f580..cc3c4cb18d5 100644 --- a/thread-pool/src/main/java/com/iluwatar/threadpool/App.java +++ b/thread-pool/src/main/java/com/iluwatar/threadpool/App.java @@ -56,7 +56,7 @@ public static void main(String[] args) { LOGGER.info("Program started"); // Create a list of tasks to be executed - List tasks = List.of( + var tasks = List.of( new PotatoPeelingTask(3), new PotatoPeelingTask(6), new CoffeeMakingTask(2), @@ -82,10 +82,7 @@ public static void main(String[] args) { // Allocate new worker for each task // The worker is executed when a thread becomes // available in the thread pool - for (int i = 0; i < tasks.size(); i++) { - var worker = new Worker(tasks.get(i)); - executor.execute(worker); - } + tasks.stream().map(Worker::new).forEach(executor::execute); // All tasks were executed, now shutdown executor.shutdown(); while (!executor.isTerminated()) { diff --git a/thread-pool/src/test/java/com/iluwatar/threadpool/AppTest.java b/thread-pool/src/test/java/com/iluwatar/threadpool/AppTest.java index 12a5d227088..ca6dc30e4cb 100644 --- a/thread-pool/src/test/java/com/iluwatar/threadpool/AppTest.java +++ b/thread-pool/src/test/java/com/iluwatar/threadpool/AppTest.java @@ -27,15 +27,13 @@ /** * Application test - * - * @author ilkka * + * @author ilkka */ public class AppTest { @Test public void test() { - String[] args = {}; - App.main(args); + App.main(new String[]{}); } } diff --git a/thread-pool/src/test/java/com/iluwatar/threadpool/TaskTest.java b/thread-pool/src/test/java/com/iluwatar/threadpool/TaskTest.java index b9d2c730b4b..67b8cf05971 100644 --- a/thread-pool/src/test/java/com/iluwatar/threadpool/TaskTest.java +++ b/thread-pool/src/test/java/com/iluwatar/threadpool/TaskTest.java @@ -23,27 +23,25 @@ package com.iluwatar.threadpool; -import org.junit.jupiter.api.Test; +import static java.time.Duration.ofMillis; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTimeout; import java.util.ArrayList; -import java.util.List; import java.util.Objects; 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 java.util.function.IntFunction; import java.util.stream.Collectors; - -import static java.time.Duration.ofMillis; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTimeout; +import java.util.stream.IntStream; +import org.junit.jupiter.api.Test; /** - * Date: 12/30/15 - 18:22 PM - * Test for Tasks using a Thread Pool + * Date: 12/30/15 - 18:22 PM Test for Tasks using a Thread Pool + * * @param Type of Task * @author Jeroen Meulemeester */ @@ -87,14 +85,13 @@ public TaskTest(final IntFunction factory, final int expectedExecutionTime) { @Test public void testIdGeneration() throws Exception { assertTimeout(ofMillis(10000), () -> { - final ExecutorService service = Executors.newFixedThreadPool(THREAD_COUNT); + final var service = Executors.newFixedThreadPool(THREAD_COUNT); - final List> tasks = new ArrayList<>(); - for (int i = 0; i < TASK_COUNT; i++) { - tasks.add(() -> factory.apply(1).getId()); - } + final var tasks = IntStream.range(0, TASK_COUNT) + .>mapToObj(i -> () -> factory.apply(1).getId()) + .collect(Collectors.toCollection(ArrayList::new)); - final List ids = service.invokeAll(tasks) + final var ids = service.invokeAll(tasks) .stream() .map(TaskTest::get) .filter(Objects::nonNull) @@ -102,7 +99,7 @@ public void testIdGeneration() throws Exception { service.shutdownNow(); - final long uniqueIdCount = ids.stream() + final var uniqueIdCount = ids.stream() .distinct() .count(); @@ -117,7 +114,7 @@ public void testIdGeneration() throws Exception { */ @Test public void testTimeMs() { - for (int i = 0; i < 10; i++) { + for (var i = 0; i < 10; i++) { assertEquals(this.expectedExecutionTime * i, this.factory.apply(i).getTimeMs()); } } diff --git a/thread-pool/src/test/java/com/iluwatar/threadpool/WorkerTest.java b/thread-pool/src/test/java/com/iluwatar/threadpool/WorkerTest.java index 13bacef5131..63d2355b217 100644 --- a/thread-pool/src/test/java/com/iluwatar/threadpool/WorkerTest.java +++ b/thread-pool/src/test/java/com/iluwatar/threadpool/WorkerTest.java @@ -23,13 +23,13 @@ package com.iluwatar.threadpool; -import org.junit.jupiter.api.Test; - import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.verifyZeroInteractions; +import org.junit.jupiter.api.Test; + /** * Date: 12/30/15 - 18:21 PM * @@ -42,8 +42,8 @@ public class WorkerTest { */ @Test public void testRun() { - final Task task = mock(Task.class); - final Worker worker = new Worker(task); + final var task = mock(Task.class); + final var worker = new Worker(task); verifyZeroInteractions(task); worker.run(); diff --git a/throttling/src/main/java/com/iluwatar/throttling/App.java b/throttling/src/main/java/com/iluwatar/throttling/App.java index f7b06f6525c..44a2f150ed5 100644 --- a/throttling/src/main/java/com/iluwatar/throttling/App.java +++ b/throttling/src/main/java/com/iluwatar/throttling/App.java @@ -26,6 +26,7 @@ import com.iluwatar.throttling.timer.ThrottleTimerImpl; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; +import java.util.stream.IntStream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -73,14 +74,14 @@ public static void main(String[] args) { private static void makeServiceCalls(Tenant tenant, CallsCount callsCount) { var timer = new ThrottleTimerImpl(10, callsCount); var service = new B2BService(timer, callsCount); - for (int i = 0; i < 20; i++) { + // Sleep is introduced to keep the output in check and easy to view and analyze the results. + IntStream.range(0, 20).forEach(i -> { service.dummyCustomerApi(tenant); - // Sleep is introduced to keep the output in check and easy to view and analyze the results. try { Thread.sleep(1); } catch (InterruptedException e) { LOGGER.error("Thread interrupted: {}", e.getMessage()); } - } + }); } } diff --git a/throttling/src/main/java/com/iluwatar/throttling/CallsCount.java b/throttling/src/main/java/com/iluwatar/throttling/CallsCount.java index a1364ed97f5..8f8036286d1 100644 --- a/throttling/src/main/java/com/iluwatar/throttling/CallsCount.java +++ b/throttling/src/main/java/com/iluwatar/throttling/CallsCount.java @@ -73,8 +73,6 @@ public long getCount(String tenantName) { */ public void reset() { LOGGER.debug("Resetting the map."); - for (Entry e : tenantCallsCount.entrySet()) { - tenantCallsCount.put(e.getKey(), new AtomicLong(0)); - } + tenantCallsCount.replaceAll((k, v) -> new AtomicLong(0)); } } diff --git a/throttling/src/test/java/com/iluwatar/throttling/AppTest.java b/throttling/src/test/java/com/iluwatar/throttling/AppTest.java index 8b2ce1b67f6..daf8c2f2139 100644 --- a/throttling/src/test/java/com/iluwatar/throttling/AppTest.java +++ b/throttling/src/test/java/com/iluwatar/throttling/AppTest.java @@ -32,7 +32,6 @@ public class AppTest { @Test public void test() { - final String[] args = {}; - App.main(args); + App.main(new String[]{}); } } diff --git a/throttling/src/test/java/com/iluwatar/throttling/B2BServiceTest.java b/throttling/src/test/java/com/iluwatar/throttling/B2BServiceTest.java index ba43571a244..6a328c3f0de 100644 --- a/throttling/src/test/java/com/iluwatar/throttling/B2BServiceTest.java +++ b/throttling/src/test/java/com/iluwatar/throttling/B2BServiceTest.java @@ -23,12 +23,12 @@ package com.iluwatar.throttling; +import static org.junit.jupiter.api.Assertions.assertEquals; + import com.iluwatar.throttling.timer.Throttler; -import org.junit.jupiter.api.Disabled; +import java.util.stream.IntStream; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; - /** * B2BServiceTest class to test the B2BService */ @@ -38,15 +38,14 @@ public class B2BServiceTest { @Test public void dummyCustomerApiTest() { - Tenant tenant = new Tenant("testTenant", 2, callsCount); + var tenant = new Tenant("testTenant", 2, callsCount); // In order to assure that throttling limits will not be reset, we use an empty throttling implementation - Throttler timer = () -> { }; - B2BService service = new B2BService(timer, callsCount); + var timer = (Throttler) () -> { + }; + var service = new B2BService(timer, callsCount); - for (int i = 0; i < 5; i++) { - service.dummyCustomerApi(tenant); - } - long counter = callsCount.getCount(tenant.getName()); + IntStream.range(0, 5).mapToObj(i -> tenant).forEach(service::dummyCustomerApi); + var counter = callsCount.getCount(tenant.getName()); assertEquals(2, counter, "Counter limit must be reached"); } } diff --git a/throttling/src/test/java/com/iluwatar/throttling/TenantTest.java b/throttling/src/test/java/com/iluwatar/throttling/TenantTest.java index 85dc59b3b90..32e1b0f4866 100644 --- a/throttling/src/test/java/com/iluwatar/throttling/TenantTest.java +++ b/throttling/src/test/java/com/iluwatar/throttling/TenantTest.java @@ -23,11 +23,10 @@ package com.iluwatar.throttling; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.security.InvalidParameterException; - -import static org.junit.jupiter.api.Assertions.assertThrows; +import org.junit.jupiter.api.Test; /** * TenantTest to test the creation of Tenant with valid parameters. @@ -37,7 +36,7 @@ public class TenantTest { @Test public void constructorTest() { assertThrows(InvalidParameterException.class, () -> { - Tenant tenant = new Tenant("FailTenant", -1, new CallsCount()); + new Tenant("FailTenant", -1, new CallsCount()); }); } } diff --git a/tls/src/main/java/com/iluwatar/tls/App.java b/tls/src/main/java/com/iluwatar/tls/App.java index 35cd89aadf7..9dd611512ef 100644 --- a/tls/src/main/java/com/iluwatar/tls/App.java +++ b/tls/src/main/java/com/iluwatar/tls/App.java @@ -24,10 +24,7 @@ package com.iluwatar.tls; import java.util.Calendar; -import java.util.Date; -import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; -import java.util.concurrent.Future; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -71,20 +68,20 @@ public class App { * @param args command line args */ public static void main(String[] args) { - int counterDateValues = 0; - int counterExceptions = 0; + var counterDateValues = 0; + var counterExceptions = 0; // Create a callable - DateFormatCallable callableDf = new DateFormatCallable("dd/MM/yyyy", "15/12/2015"); + var callableDf = new DateFormatCallable("dd/MM/yyyy", "15/12/2015"); // start 4 threads, each using the same Callable instance - ExecutorService executor = Executors.newCachedThreadPool(); + var executor = Executors.newCachedThreadPool(); - Future futureResult1 = executor.submit(callableDf); - Future futureResult2 = executor.submit(callableDf); - Future futureResult3 = executor.submit(callableDf); - Future futureResult4 = executor.submit(callableDf); + var futureResult1 = executor.submit(callableDf); + var futureResult2 = executor.submit(callableDf); + var futureResult3 = executor.submit(callableDf); + var futureResult4 = executor.submit(callableDf); try { - Result[] result = new Result[4]; + var result = new Result[4]; result[0] = futureResult1.get(); result[1] = futureResult2.get(); result[2] = futureResult3.get(); @@ -92,9 +89,9 @@ public static void main(String[] args) { // Print results of thread executions (converted dates and raised exceptions) // and count them - for (int i = 0; i < result.length; i++) { - counterDateValues = counterDateValues + printAndCountDates(result[i]); - counterExceptions = counterExceptions + printAndCountExceptions(result[i]); + for (var value : result) { + counterDateValues = counterDateValues + printAndCountDates(value); + counterExceptions = counterExceptions + printAndCountExceptions(value); } // a correct run should deliver 20 times 15.12.2015 @@ -115,15 +112,16 @@ public static void main(String[] args) { */ private static int printAndCountDates(Result res) { // a correct run should deliver 5 times 15.12.2015 per each thread - int counter = 0; - for (Date dt : res.getDateList()) { + var counter = 0; + for (var dt : res.getDateList()) { counter++; - Calendar cal = Calendar.getInstance(); + var cal = Calendar.getInstance(); cal.setTime(dt); // Formatted output of the date value: DD.MM.YYYY - LOGGER.info( - cal.get(Calendar.DAY_OF_MONTH) + "." + cal.get(Calendar.MONTH) + "." + +cal - .get(Calendar.YEAR)); + LOGGER.info(cal.get(Calendar.DAY_OF_MONTH) + "." + + cal.get(Calendar.MONTH) + "." + + cal.get(Calendar.YEAR) + ); } return counter; } @@ -136,8 +134,8 @@ private static int printAndCountDates(Result res) { */ private static int printAndCountExceptions(Result res) { // a correct run shouldn't deliver any exception - int counter = 0; - for (String ex : res.getExceptionList()) { + var counter = 0; + for (var ex : res.getExceptionList()) { counter++; LOGGER.info(ex); } diff --git a/tls/src/main/java/com/iluwatar/tls/DateFormatCallable.java b/tls/src/main/java/com/iluwatar/tls/DateFormatCallable.java index 8f0006b9e3a..c4e885896cc 100644 --- a/tls/src/main/java/com/iluwatar/tls/DateFormatCallable.java +++ b/tls/src/main/java/com/iluwatar/tls/DateFormatCallable.java @@ -26,6 +26,7 @@ import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.concurrent.Callable; +import java.util.stream.IntStream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -58,13 +59,10 @@ public class DateFormatCallable implements Callable { * @param inDateValue string date value, e.g. "21/06/2016" */ public DateFormatCallable(String inDateFormat, String inDateValue) { - final String idf = inDateFormat; //TLTL - this.df = new ThreadLocal() { //TLTL - @Override //TLTL - protected DateFormat initialValue() { //TLTL - return new SimpleDateFormat(idf); //TLTL - } //TLTL - }; //TLTL + final var idf = inDateFormat; //TLTL + this.df = ThreadLocal.withInitial(() -> { //TLTL + return new SimpleDateFormat(idf); //TLTL + }); //TLTL // this.df = new SimpleDateFormat(inDateFormat); //NTLNTL this.dateValue = inDateValue; } @@ -72,10 +70,10 @@ protected DateFormat initialValue() { //TLTL @Override public Result call() { LOGGER.info(Thread.currentThread() + " started executing..."); - Result result = new Result(); + var result = new Result(); // Convert date value to date 5 times - for (int i = 1; i <= 5; i++) { + IntStream.rangeClosed(1, 5).forEach(i -> { try { // this is the statement where it is important to have the // instance of SimpleDateFormat locally @@ -86,8 +84,7 @@ public Result call() { // write the Exception to a list and continue work result.getExceptionList().add(e.getClass() + ": " + e.getMessage()); } - - } + }); LOGGER.info(Thread.currentThread() + " finished processing part of the thread"); diff --git a/tls/src/main/java/com/iluwatar/tls/Result.java b/tls/src/main/java/com/iluwatar/tls/Result.java index 2dd249c4d8e..c98a07b913c 100644 --- a/tls/src/main/java/com/iluwatar/tls/Result.java +++ b/tls/src/main/java/com/iluwatar/tls/Result.java @@ -39,11 +39,11 @@ */ public class Result { // A list to collect the date values created in one thread - private List dateList = new ArrayList(); + private List dateList = new ArrayList<>(); // A list to collect Exceptions thrown in one threads (should be none in // this example) - private List exceptionList = new ArrayList(); + private List exceptionList = new ArrayList<>(); /** * Get list of date values collected within a thread execution. diff --git a/tls/src/test/java/com/iluwatar/tls/AppTest.java b/tls/src/test/java/com/iluwatar/tls/AppTest.java index 7f0d6ddadf8..bae673b9735 100644 --- a/tls/src/test/java/com/iluwatar/tls/AppTest.java +++ b/tls/src/test/java/com/iluwatar/tls/AppTest.java @@ -27,14 +27,12 @@ /** * Tests that thread local storage example runs without errors. - * - * @author Thomas Bauer, January 2017 * + * @author Thomas Bauer, January 2017 */ public class AppTest { @Test - public void test() throws Exception { - String[] args = {}; - App.main(args); + public void test() { + App.main(new String[]{}); } } diff --git a/tls/src/test/java/com/iluwatar/tls/DateFormatCallableTest.java b/tls/src/test/java/com/iluwatar/tls/DateFormatCallableTest.java index 2e69e2c7f2e..48e5854a346 100644 --- a/tls/src/test/java/com/iluwatar/tls/DateFormatCallableTest.java +++ b/tls/src/test/java/com/iluwatar/tls/DateFormatCallableTest.java @@ -23,65 +23,62 @@ package com.iluwatar.tls; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; import java.util.ArrayList; import java.util.Calendar; -import java.util.Date; import java.util.List; -import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; -import java.util.concurrent.Future; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.fail; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; /** - * * Test of the Callable - * - * In this test {@link DateFormatCallable} is tested with only one thread (i.e. without concurrency situation) *

- * After a successful run 5 date values should be in the result object. All dates should have - * the same value (15.11.2015). To avoid problems with time zone not the date instances themselves - * are compared by the test. For the test the dates are converted into string format DD.MM.YYY + * In this test {@link DateFormatCallable} is tested with only one thread (i.e. without concurrency + * situation) *

- * Additionally the number of list entries are tested for both the list with the date values - * and the list with the exceptions - * - * @author Thomas Bauer, January 2017 + * After a successful run 5 date values should be in the result object. All dates should have the + * same value (15.11.2015). To avoid problems with time zone not the date instances themselves are + * compared by the test. For the test the dates are converted into string format DD.MM.YYY + *

+ * Additionally the number of list entries are tested for both the list with the date values and the + * list with the exceptions * + * @author Thomas Bauer, January 2017 */ public class DateFormatCallableTest { // Class variables used in setup() have to be static because setup() has to be static /** - * Result object given back by DateFormatCallable - * -- Array with converted date values - * -- Array with thrown exceptions + * Result object given back by DateFormatCallable -- Array with converted date values -- Array + * with thrown exceptions */ - static Result result; + private static Result result; /** - * The date values created by the run of of DateFormatRunnalbe. List will be filled in the setup() method + * The date values created by the run of of DateFormatRunnalbe. List will be filled in the setup() + * method */ - static List createdDateValues = new ArrayList(); + private static List createdDateValues = new ArrayList<>(); /** * Expected number of date values in the date value list created by the run of DateFormatRunnalbe */ - int expectedCounterDateValues = 5; + private int expectedCounterDateValues = 5; /** - * Expected number of exceptions in the exception list created by the run of DateFormatRunnalbe. + * Expected number of exceptions in the exception list created by the run of DateFormatRunnalbe. */ - int expectedCounterExceptions = 0; + private int expectedCounterExceptions = 0; /** - * Expected content of the list containing the date values created by the run of DateFormatRunnalbe + * Expected content of the list containing the date values created by the run of + * DateFormatRunnalbe */ - List expectedDateValues = List.of("15.11.2015", "15.11.2015", "15.11.2015", "15.11.2015", "15.11.2015"); + private List expectedDateValues = + List.of("15.11.2015", "15.11.2015", "15.11.2015", "15.11.2015", "15.11.2015"); /** * Run Callable and prepare results for usage in the test methods @@ -89,10 +86,10 @@ public class DateFormatCallableTest { @BeforeAll public static void setup() { // Create a callable - DateFormatCallable callableDf = new DateFormatCallable("dd/MM/yyyy", "15/12/2015"); + var callableDf = new DateFormatCallable("dd/MM/yyyy", "15/12/2015"); // start thread using the Callable instance - ExecutorService executor = Executors.newCachedThreadPool(); - Future futureResult = executor.submit(callableDf); + var executor = Executors.newCachedThreadPool(); + var futureResult = executor.submit(callableDf); try { result = futureResult.get(); createdDateValues = convertDatesToString(result); @@ -107,18 +104,22 @@ private static List convertDatesToString(Result res) { if (res == null || res.getDateList() == null || res.getDateList().size() == 0) { return null; } - List returnList = new ArrayList(); + var returnList = new ArrayList(); - for (Date dt : res.getDateList()) { - Calendar cal = Calendar.getInstance(); + for (var dt : res.getDateList()) { + var cal = Calendar.getInstance(); cal.setTime(dt); - returnList.add(cal.get(Calendar.DAY_OF_MONTH) + "." + cal.get(Calendar.MONTH) + "." + cal.get(Calendar.YEAR)); + returnList.add(cal.get(Calendar.DAY_OF_MONTH) + "." + + cal.get(Calendar.MONTH) + "." + + cal.get(Calendar.YEAR) + ); } return returnList; } /** - * Test date values after the run of DateFormatRunnalbe. A correct run should deliver 5 times 15.12.2015 + * Test date values after the run of DateFormatRunnalbe. A correct run should deliver 5 times + * 15.12.2015 */ @Test public void testDateValues() { @@ -126,7 +127,8 @@ public void testDateValues() { } /** - * Test number of dates in the list after the run of DateFormatRunnalbe. A correct run should deliver 5 date values + * Test number of dates in the list after the run of DateFormatRunnalbe. A correct run should + * deliver 5 date values */ @Test public void testCounterDateValues() { @@ -134,8 +136,8 @@ public void testCounterDateValues() { } /** - * Test number of Exceptions in the list after the run of DateFormatRunnalbe. A correct run should deliver - * no exceptions + * Test number of Exceptions in the list after the run of DateFormatRunnalbe. A correct run should + * deliver no exceptions */ @Test public void testCounterExceptions() { diff --git a/tls/src/test/java/com/iluwatar/tls/DateFormatCallableTestIncorrectDateFormat.java b/tls/src/test/java/com/iluwatar/tls/DateFormatCallableTestIncorrectDateFormat.java index df2ab2a9341..8b02faf0b68 100644 --- a/tls/src/test/java/com/iluwatar/tls/DateFormatCallableTestIncorrectDateFormat.java +++ b/tls/src/test/java/com/iluwatar/tls/DateFormatCallableTestIncorrectDateFormat.java @@ -23,63 +23,55 @@ package com.iluwatar.tls; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; -import java.util.ArrayList; import java.util.List; -import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; -import java.util.concurrent.Future; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.fail; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; /** - * * Test of the Callable - * - * In this test {@link DateFormatCallable} is tested with only one thread (i.e. without concurrency situation) *

- * An incorrect formatted date is passed to the Callable - * After a successful run 0 date values and 5 exceptions should be in the result object. - * - * @author Thomas Bauer, January 2017 + * In this test {@link DateFormatCallable} is tested with only one thread (i.e. without concurrency + * situation) + *

+ * An incorrect formatted date is passed to the Callable After a successful run 0 date values and 5 + * exceptions should be in the result object. * + * @author Thomas Bauer, January 2017 */ public class DateFormatCallableTestIncorrectDateFormat { // Class variables used in setup() have to be static because setup() has to be static /** - * Result object given back by DateFormatCallable - * -- Array with converted date values - * -- Array with thrown exceptions + * Result object given back by DateFormatCallable -- Array with converted date values -- Array + * with thrown exceptions */ - static Result result; - - /** - * The date values created by the run of DateFormatRunnalbe. List will be filled in the setup() method - */ - static List createdExceptions = new ArrayList(); + private static Result result; /** * Expected number of date values in the date value list created by the run of DateFormatRunnalbe */ - int expectedCounterDateValues = 0; + private int expectedCounterDateValues = 0; /** - * Expected number of exceptions in the exception list created by the run of DateFormatRunnalbe. + * Expected number of exceptions in the exception list created by the run of DateFormatRunnalbe. */ - int expectedCounterExceptions = 5; + private int expectedCounterExceptions = 5; /** - * Expected content of the list containing the exceptions created by the run of DateFormatRunnalbe + * Expected content of the list containing the exceptions created by the run of + * DateFormatRunnalbe */ - List expectedExceptions = List.of("class java.text.ParseException: Unparseable date: \"15.12.2015\"", + private List expectedExceptions = List.of( + "class java.text.ParseException: Unparseable date: \"15.12.2015\"", "class java.text.ParseException: Unparseable date: \"15.12.2015\"", "class java.text.ParseException: Unparseable date: \"15.12.2015\"", "class java.text.ParseException: Unparseable date: \"15.12.2015\"", - "class java.text.ParseException: Unparseable date: \"15.12.2015\""); + "class java.text.ParseException: Unparseable date: \"15.12.2015\"" + ); /** * Run Callable and prepare results for usage in the test methods @@ -87,10 +79,10 @@ public class DateFormatCallableTestIncorrectDateFormat { @BeforeAll public static void setup() { // Create a callable. Pass a string date value not matching the format string - DateFormatCallable callableDf = new DateFormatCallable("dd/MM/yyyy", "15.12.2015"); + var callableDf = new DateFormatCallable("dd/MM/yyyy", "15.12.2015"); // start thread using the Callable instance - ExecutorService executor = Executors.newCachedThreadPool(); - Future futureResult = executor.submit(callableDf); + var executor = Executors.newCachedThreadPool(); + var futureResult = executor.submit(callableDf); try { result = futureResult.get(); } catch (Exception e) { @@ -109,7 +101,8 @@ public void testExceptions() { } /** - * Test number of dates in the list after the run of DateFormatRunnalbe. A correct run should deliver no date values + * Test number of dates in the list after the run of DateFormatRunnalbe. A correct run should + * deliver no date values */ @Test public void testCounterDateValues() { @@ -117,7 +110,7 @@ public void testCounterDateValues() { } /** - * Test number of Exceptions in the list after the run of DateFormatRunnalbe. A correct run should + * Test number of Exceptions in the list after the run of DateFormatRunnalbe. A correct run should * deliver 5 exceptions */ @Test diff --git a/tls/src/test/java/com/iluwatar/tls/DateFormatCallableTestMultiThread.java b/tls/src/test/java/com/iluwatar/tls/DateFormatCallableTestMultiThread.java index 1001e1bdf59..c0e8e184473 100644 --- a/tls/src/test/java/com/iluwatar/tls/DateFormatCallableTestMultiThread.java +++ b/tls/src/test/java/com/iluwatar/tls/DateFormatCallableTestMultiThread.java @@ -23,69 +23,66 @@ package com.iluwatar.tls; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; import java.util.ArrayList; import java.util.Calendar; -import java.util.Date; import java.util.List; -import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; -import java.util.concurrent.Future; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.fail; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; /** - * * Test of the Callable - * + *

* In this test {@link DateFormatCallable} is used by 4 threads in parallel *

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

- * Additionally the number of list entries are tested for both the list with the date values - * and the list with the exceptions - * - * @author Thomas Bauer, January 2017 + * Additionally the number of list entries are tested for both the list with the date values and the + * list with the exceptions * + * @author Thomas Bauer, January 2017 */ public class DateFormatCallableTestMultiThread { // Class variables used in setup() have to be static because setup() has to be static /** - * Result object given back by DateFormatCallable, one for each thread - * -- Array with converted date values - * -- Array with thrown exceptions + * Result object given back by DateFormatCallable, one for each thread -- Array with converted + * date values -- Array with thrown exceptions */ - static Result[] result = new Result[4]; + private static Result[] result = new Result[4]; /** - * The date values created by the run of of DateFormatRunnalbe. List will be filled in the setup() method + * The date values created by the run of of DateFormatRunnalbe. List will be filled in the setup() + * method */ @SuppressWarnings("serial") - static class StringArrayList extends ArrayList { + private static class StringArrayList extends ArrayList { /* nothing needed here */ } - static List[] createdDateValues = new StringArrayList[4]; + + private static List[] createdDateValues = new StringArrayList[4]; /** * Expected number of date values in the date value list created by each thread */ - int expectedCounterDateValues = 5; + private int expectedCounterDateValues = 5; /** - * Expected number of exceptions in the exception list created by each thread + * Expected number of exceptions in the exception list created by each thread */ - int expectedCounterExceptions = 0; + private int expectedCounterExceptions = 0; /** - * Expected content of the list containing the date values created by each thread + * Expected content of the list containing the date values created by each thread */ - List expectedDateValues = List.of("15.11.2015", "15.11.2015", "15.11.2015", "15.11.2015", "15.11.2015"); + private List expectedDateValues = + List.of("15.11.2015", "15.11.2015", "15.11.2015", "15.11.2015", "15.11.2015"); /** * Run Callable and prepare results for usage in the test methods @@ -93,19 +90,19 @@ static class StringArrayList extends ArrayList { @BeforeAll public static void setup() { // Create a callable - DateFormatCallable callableDf = new DateFormatCallable("dd/MM/yyyy", "15/12/2015"); + var callableDf = new DateFormatCallable("dd/MM/yyyy", "15/12/2015"); // start thread using the Callable instance - ExecutorService executor = Executors.newCachedThreadPool(); - Future futureResult1 = executor.submit(callableDf); - Future futureResult2 = executor.submit(callableDf); - Future futureResult3 = executor.submit(callableDf); - Future futureResult4 = executor.submit(callableDf); + var executor = Executors.newCachedThreadPool(); + var futureResult1 = executor.submit(callableDf); + var futureResult2 = executor.submit(callableDf); + var futureResult3 = executor.submit(callableDf); + var futureResult4 = executor.submit(callableDf); try { result[0] = futureResult1.get(); result[1] = futureResult2.get(); result[2] = futureResult3.get(); result[3] = futureResult4.get(); - for (int i = 0; i < result.length; i++) { + for (var i = 0; i < result.length; i++) { createdDateValues[i] = convertDatesToString(result[i]); } } catch (Exception e) { @@ -119,46 +116,49 @@ private static List convertDatesToString(Result res) { if (res == null || res.getDateList() == null || res.getDateList().size() == 0) { return null; } - List returnList = new StringArrayList(); + var returnList = new StringArrayList(); - for (Date dt : res.getDateList()) { - Calendar cal = Calendar.getInstance(); + for (var dt : res.getDateList()) { + var cal = Calendar.getInstance(); cal.setTime(dt); - returnList.add(cal.get(Calendar.DAY_OF_MONTH) + "." + cal.get(Calendar.MONTH) + "." + cal.get(Calendar.YEAR)); + returnList.add(cal.get(Calendar.DAY_OF_MONTH) + "." + + cal.get(Calendar.MONTH) + "." + + cal.get(Calendar.YEAR) + ); } return returnList; } /** - * Test date values after the run of DateFormatRunnalbe. A correct run should deliver 5 times 15.12.2015 - * by each thread + * Test date values after the run of DateFormatRunnalbe. A correct run should deliver 5 times + * 15.12.2015 by each thread */ @Test public void testDateValues() { - for (int i = 0; i < createdDateValues.length; i++) { - assertEquals(expectedDateValues, createdDateValues[i]); + for (var createdDateValue : createdDateValues) { + assertEquals(expectedDateValues, createdDateValue); } } /** - * Test number of dates in the list after the run of DateFormatRunnalbe. A correct run should + * Test number of dates in the list after the run of DateFormatRunnalbe. A correct run should * deliver 5 date values by each thread */ @Test public void testCounterDateValues() { - for (int i = 0; i < result.length; i++) { - assertEquals(expectedCounterDateValues, result[i].getDateList().size()); + for (var value : result) { + assertEquals(expectedCounterDateValues, value.getDateList().size()); } } /** - * Test number of Exceptions in the list after the run of DateFormatRunnalbe. A correct run should + * Test number of Exceptions in the list after the run of DateFormatRunnalbe. A correct run should * deliver no exceptions */ @Test public void testCounterExceptions() { - for (int i = 0; i < result.length; i++) { - assertEquals(expectedCounterExceptions, result[i].getExceptionList().size()); + for (var value : result) { + assertEquals(expectedCounterExceptions, value.getExceptionList().size()); } } } diff --git a/tolerant-reader/src/main/java/com/iluwatar/tolerantreader/RainbowFishSerializer.java b/tolerant-reader/src/main/java/com/iluwatar/tolerantreader/RainbowFishSerializer.java index 33c464190e1..f6a9e6a0ec8 100644 --- a/tolerant-reader/src/main/java/com/iluwatar/tolerantreader/RainbowFishSerializer.java +++ b/tolerant-reader/src/main/java/com/iluwatar/tolerantreader/RainbowFishSerializer.java @@ -82,15 +82,18 @@ public static void writeV2(RainbowFishV2 rainbowFish, String filename) throws IO * Read V1 RainbowFish from file. */ public static RainbowFish readV1(String filename) throws IOException, ClassNotFoundException { - Map map = null; + Map map; try (var fileIn = new FileInputStream(filename); var objIn = new ObjectInputStream(fileIn)) { map = (Map) objIn.readObject(); } - return new RainbowFish(map.get("name"), Integer.parseInt(map.get("age")), Integer - .parseInt(map.get("lengthMeters")), - Integer.parseInt(map.get("weightTons"))); + return new RainbowFish( + map.get("name"), + Integer.parseInt(map.get("age")), + Integer.parseInt(map.get("lengthMeters")), + Integer.parseInt(map.get("weightTons")) + ); } } diff --git a/tolerant-reader/src/test/java/com/iluwatar/tolerantreader/AppTest.java b/tolerant-reader/src/test/java/com/iluwatar/tolerantreader/AppTest.java index 73833f76062..d28e118d268 100644 --- a/tolerant-reader/src/test/java/com/iluwatar/tolerantreader/AppTest.java +++ b/tolerant-reader/src/test/java/com/iluwatar/tolerantreader/AppTest.java @@ -23,32 +23,28 @@ package com.iluwatar.tolerantreader; +import java.io.File; +import java.io.IOException; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.io.File; -import java.io.IOException; - /** - * * Application test - * */ public class AppTest { @Test public void test() throws ClassNotFoundException, IOException { - String[] args = {}; - App.main(args); + App.main(new String[]{}); } @BeforeEach @AfterEach public void cleanup() { - File file1 = new File("fish1.out"); + var file1 = new File("fish1.out"); file1.delete(); - File file2 = new File("fish2.out"); + var file2 = new File("fish2.out"); file2.delete(); } } diff --git a/tolerant-reader/src/test/java/com/iluwatar/tolerantreader/RainbowFishSerializerTest.java b/tolerant-reader/src/test/java/com/iluwatar/tolerantreader/RainbowFishSerializerTest.java index 989059e4463..72e559fb547 100644 --- a/tolerant-reader/src/test/java/com/iluwatar/tolerantreader/RainbowFishSerializerTest.java +++ b/tolerant-reader/src/test/java/com/iluwatar/tolerantreader/RainbowFishSerializerTest.java @@ -23,16 +23,15 @@ package com.iluwatar.tolerantreader; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotSame; + +import java.io.File; import org.junit.Rule; import org.junit.jupiter.api.Test; import org.junit.jupiter.migrationsupport.rules.EnableRuleMigrationSupport; import org.junit.rules.TemporaryFolder; -import java.io.File; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotSame; - /** * Date: 12/30/15 - 18:39 PM * @@ -62,10 +61,10 @@ public class RainbowFishSerializerTest { */ @Test public void testWriteV1ReadV1() throws Exception { - final File outputFile = this.testFolder.newFile(); + final var outputFile = this.testFolder.newFile(); RainbowFishSerializer.writeV1(V1, outputFile.getPath()); - final RainbowFish fish = RainbowFishSerializer.readV1(outputFile.getPath()); + final var fish = RainbowFishSerializer.readV1(outputFile.getPath()); assertNotSame(V1, fish); assertEquals(V1.getName(), fish.getName()); assertEquals(V1.getAge(), fish.getAge()); @@ -79,10 +78,10 @@ public void testWriteV1ReadV1() throws Exception { */ @Test public void testWriteV2ReadV1() throws Exception { - final File outputFile = this.testFolder.newFile(); + final var outputFile = this.testFolder.newFile(); RainbowFishSerializer.writeV2(V2, outputFile.getPath()); - final RainbowFish fish = RainbowFishSerializer.readV1(outputFile.getPath()); + final var fish = RainbowFishSerializer.readV1(outputFile.getPath()); assertNotSame(V2, fish); assertEquals(V2.getName(), fish.getName()); assertEquals(V2.getAge(), fish.getAge()); diff --git a/tolerant-reader/src/test/java/com/iluwatar/tolerantreader/RainbowFishTest.java b/tolerant-reader/src/test/java/com/iluwatar/tolerantreader/RainbowFishTest.java index 7427644dedf..a8155bcb9e6 100644 --- a/tolerant-reader/src/test/java/com/iluwatar/tolerantreader/RainbowFishTest.java +++ b/tolerant-reader/src/test/java/com/iluwatar/tolerantreader/RainbowFishTest.java @@ -23,10 +23,10 @@ package com.iluwatar.tolerantreader; -import org.junit.Test; - import static org.junit.Assert.assertEquals; +import org.junit.Test; + /** * Date: 12/30/15 - 18:34 PM * @@ -39,7 +39,7 @@ public class RainbowFishTest { */ @Test public void testValues() { - final RainbowFish fish = new RainbowFish("name", 1, 2, 3); + final var fish = new RainbowFish("name", 1, 2, 3); assertEquals("name", fish.getName()); assertEquals(1, fish.getAge()); assertEquals(2, fish.getLengthMeters()); diff --git a/tolerant-reader/src/test/java/com/iluwatar/tolerantreader/RainbowFishV2Test.java b/tolerant-reader/src/test/java/com/iluwatar/tolerantreader/RainbowFishV2Test.java index 4d77b6f5f2a..6def17cd137 100644 --- a/tolerant-reader/src/test/java/com/iluwatar/tolerantreader/RainbowFishV2Test.java +++ b/tolerant-reader/src/test/java/com/iluwatar/tolerantreader/RainbowFishV2Test.java @@ -23,12 +23,12 @@ package com.iluwatar.tolerantreader; -import org.junit.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.Test; + /** * Date: 12/30/15 - 18:35 PM * @@ -41,7 +41,7 @@ public class RainbowFishV2Test { */ @Test public void testValues() { - final RainbowFishV2 fish = new RainbowFishV2("name", 1, 2, 3, false, true, false); + final var fish = new RainbowFishV2("name", 1, 2, 3, false, true, false); assertEquals("name", fish.getName()); assertEquals(1, fish.getAge()); assertEquals(2, fish.getLengthMeters()); diff --git a/trampoline/src/main/java/com/iluwatar/trampoline/Trampoline.java b/trampoline/src/main/java/com/iluwatar/trampoline/Trampoline.java index 862300ea37e..7b5a564cf27 100644 --- a/trampoline/src/main/java/com/iluwatar/trampoline/Trampoline.java +++ b/trampoline/src/main/java/com/iluwatar/trampoline/Trampoline.java @@ -99,13 +99,11 @@ public T get() { } T trampoline(final Trampoline trampoline) { - return Stream.iterate(trampoline, Trampoline::jump) .filter(Trampoline::complete) .findFirst() - .get() - .result(); - + .map(Trampoline::result) + .orElseThrow(); } }; } diff --git a/trampoline/src/main/java/com/iluwatar/trampoline/TrampolineApp.java b/trampoline/src/main/java/com/iluwatar/trampoline/TrampolineApp.java index 6abb4d0ff63..31504d82fcb 100644 --- a/trampoline/src/main/java/com/iluwatar/trampoline/TrampolineApp.java +++ b/trampoline/src/main/java/com/iluwatar/trampoline/TrampolineApp.java @@ -40,7 +40,7 @@ public class TrampolineApp { */ public static void main(String[] args) { log.info("start pattern"); - Integer result = loop(10, 1).result(); + var result = loop(10, 1).result(); log.info("result {}", result); } diff --git a/trampoline/src/test/java/com/iluwatar/trampoline/TrampolineAppTest.java b/trampoline/src/test/java/com/iluwatar/trampoline/TrampolineAppTest.java index 27a1fd59e7c..c5d6571cdd5 100644 --- a/trampoline/src/test/java/com/iluwatar/trampoline/TrampolineAppTest.java +++ b/trampoline/src/test/java/com/iluwatar/trampoline/TrampolineAppTest.java @@ -23,22 +23,20 @@ package com.iluwatar.trampoline; -import org.junit.Test; - -import java.io.IOException; +import static org.junit.Assert.assertEquals; -import static org.junit.Assert.*; +import org.junit.Test; /** * Test for trampoline pattern. - * */ + */ public class TrampolineAppTest { @Test public void testTrampolineWithFactorialFunction() { - int result = TrampolineApp.loop(10, 1).result(); + long result = TrampolineApp.loop(10, 1).result(); assertEquals("Be equal", 3628800, result); } diff --git a/twin/src/test/java/com/iluwatar/twin/AppTest.java b/twin/src/test/java/com/iluwatar/twin/AppTest.java index 864c86c1613..50b787eebab 100644 --- a/twin/src/test/java/com/iluwatar/twin/AppTest.java +++ b/twin/src/test/java/com/iluwatar/twin/AppTest.java @@ -26,15 +26,12 @@ import org.junit.jupiter.api.Test; /** - * * Application test - * */ public class AppTest { @Test public void test() throws Exception { - String[] args = {}; - App.main(args); + App.main(new String[]{}); } } diff --git a/twin/src/test/java/com/iluwatar/twin/BallItemTest.java b/twin/src/test/java/com/iluwatar/twin/BallItemTest.java index 70781c0e783..568c1d7b0bf 100644 --- a/twin/src/test/java/com/iluwatar/twin/BallItemTest.java +++ b/twin/src/test/java/com/iluwatar/twin/BallItemTest.java @@ -34,11 +34,10 @@ import ch.qos.logback.core.AppenderBase; import java.util.LinkedList; import java.util.List; - +import java.util.stream.IntStream; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.mockito.InOrder; import org.slf4j.LoggerFactory; /** @@ -62,27 +61,26 @@ public void tearDown() { @Test public void testClick() { - final BallThread ballThread = mock(BallThread.class); - final BallItem ballItem = new BallItem(); + final var ballThread = mock(BallThread.class); + final var ballItem = new BallItem(); ballItem.setTwin(ballThread); - final InOrder inOrder = inOrder(ballThread); + final var inOrder = inOrder(ballThread); - for (int i = 0; i < 10; i++) { + IntStream.range(0, 10).forEach(i -> { ballItem.click(); inOrder.verify(ballThread).suspendMe(); - ballItem.click(); inOrder.verify(ballThread).resumeMe(); - } + }); inOrder.verifyNoMoreInteractions(); } @Test public void testDoDraw() { - final BallItem ballItem = new BallItem(); - final BallThread ballThread = mock(BallThread.class); + final var ballItem = new BallItem(); + final var ballThread = mock(BallThread.class); ballItem.setTwin(ballThread); ballItem.draw(); @@ -95,8 +93,8 @@ public void testDoDraw() { @Test public void testMove() { - final BallItem ballItem = new BallItem(); - final BallThread ballThread = mock(BallThread.class); + final var ballItem = new BallItem(); + final var ballThread = mock(BallThread.class); ballItem.setTwin(ballThread); ballItem.move(); diff --git a/twin/src/test/java/com/iluwatar/twin/BallThreadTest.java b/twin/src/test/java/com/iluwatar/twin/BallThreadTest.java index 773b0546259..568e2ccd6b4 100644 --- a/twin/src/test/java/com/iluwatar/twin/BallThreadTest.java +++ b/twin/src/test/java/com/iluwatar/twin/BallThreadTest.java @@ -23,15 +23,19 @@ package com.iluwatar.twin; -import org.junit.jupiter.api.Test; - import static java.lang.Thread.UncaughtExceptionHandler; import static java.lang.Thread.sleep; import static java.time.Duration.ofMillis; import static org.junit.jupiter.api.Assertions.assertTimeout; import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.*; +import static org.mockito.Mockito.atLeastOnce; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.verifyZeroInteractions; + +import org.junit.jupiter.api.Test; /** * Date: 12/30/15 - 18:55 PM @@ -44,11 +48,11 @@ public class BallThreadTest { * Verify if the {@link BallThread} can be resumed */ @Test - public void testSuspend() throws Exception { + public void testSuspend() { assertTimeout(ofMillis(5000), () -> { - final BallThread ballThread = new BallThread(); + final var ballThread = new BallThread(); - final BallItem ballItem = mock(BallItem.class); + final var ballItem = mock(BallItem.class); ballThread.setTwin(ballItem); ballThread.start(); @@ -72,9 +76,9 @@ public void testSuspend() throws Exception { @Test public void testResume() { assertTimeout(ofMillis(5000), () -> { - final BallThread ballThread = new BallThread(); + final var ballThread = new BallThread(); - final BallItem ballItem = mock(BallItem.class); + final var ballItem = mock(BallItem.class); ballThread.setTwin(ballItem); ballThread.suspendMe(); @@ -102,8 +106,8 @@ public void testResume() { @Test public void testInterrupt() { assertTimeout(ofMillis(5000), () -> { - final BallThread ballThread = new BallThread(); - final UncaughtExceptionHandler exceptionHandler = mock(UncaughtExceptionHandler.class); + final var ballThread = new BallThread(); + final var exceptionHandler = mock(UncaughtExceptionHandler.class); ballThread.setUncaughtExceptionHandler(exceptionHandler); ballThread.setTwin(mock(BallItem.class)); ballThread.start(); diff --git a/typeobjectpattern/src/main/java/com/iluwatar/typeobject/CandyGame.java b/typeobjectpattern/src/main/java/com/iluwatar/typeobject/CandyGame.java index 6b3b138d800..04e281a993c 100644 --- a/typeobjectpattern/src/main/java/com/iluwatar/typeobject/CandyGame.java +++ b/typeobjectpattern/src/main/java/com/iluwatar/typeobject/CandyGame.java @@ -25,6 +25,7 @@ import com.iluwatar.typeobject.Candy.Type; import java.util.ArrayList; +import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -55,21 +56,17 @@ public class CandyGame { } static String numOfSpaces(int num) { - String result = ""; - for (var i = 0; i < num; i++) { - result += " "; - } - return result; + return " ".repeat(Math.max(0, num)); } void printGameStatus() { LOGGER.info(""); - for (var i = 0; i < cells.length; i++) { + for (Cell[] cell : cells) { for (var j = 0; j < cells.length; j++) { - var candyName = cells[i][j].candy.name; + var candyName = cell[j].candy.name; if (candyName.length() < 20) { var totalSpaces = 20 - candyName.length(); - LOGGER.info(numOfSpaces(totalSpaces / 2) + cells[i][j].candy.name + LOGGER.info(numOfSpaces(totalSpaces / 2) + cell[j].candy.name + numOfSpaces(totalSpaces - totalSpaces / 2) + "|"); } else { LOGGER.info(candyName + "|"); @@ -80,8 +77,8 @@ void printGameStatus() { LOGGER.info(""); } - ArrayList adjacentCells(int y, int x) { - ArrayList adjacent = new ArrayList(); + List adjacentCells(int y, int x) { + var adjacent = new ArrayList(); if (y == 0) { adjacent.add(this.cells[1][x]); } @@ -115,8 +112,8 @@ boolean continueRound() { for (var j = 0; j < this.cells.length; j++) { if (!this.cells[i][j].candy.getType().equals(Type.rewardFruit)) { var adj = adjacentCells(i, j); - for (var a = 0; a < adj.size(); a++) { - if (this.cells[i][j].candy.name.equals(adj.get(a).candy.name)) { + for (Cell cell : adj) { + if (this.cells[i][j].candy.name.equals(cell.candy.name)) { return true; } } @@ -157,11 +154,11 @@ void round(int timeSoFar, int totalTime) { } } } - for (var i = 0; i < this.cells.length; i++) { + for (Cell[] cell : this.cells) { var j = 0; var points = 0; while (j < cells.length - 1) { - points = this.cells[i][j].interact(this.cells[i][j + 1], this.pool, this.cells); + points = cell[j].interact(cell[j + 1], this.pool, this.cells); if (points != 0) { handleChange(points); } else { diff --git a/typeobjectpattern/src/main/java/com/iluwatar/typeobject/CellPool.java b/typeobjectpattern/src/main/java/com/iluwatar/typeobject/CellPool.java index 3655e9e5ad2..553458a6d0d 100644 --- a/typeobjectpattern/src/main/java/com/iluwatar/typeobject/CellPool.java +++ b/typeobjectpattern/src/main/java/com/iluwatar/typeobject/CellPool.java @@ -27,6 +27,7 @@ import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; +import java.util.List; import java.util.Random; import org.json.simple.parser.ParseException; @@ -38,12 +39,12 @@ public class CellPool { private static final Random RANDOM = new Random(); - ArrayList pool; + List pool; int pointer; Candy[] randomCode; CellPool(int num) { - this.pool = new ArrayList(num); + this.pool = new ArrayList<>(num); try { this.randomCode = assignRandomCandytypes(); } catch (Exception e) { diff --git a/typeobjectpattern/src/main/java/com/iluwatar/typeobject/JsonParser.java b/typeobjectpattern/src/main/java/com/iluwatar/typeobject/JsonParser.java index fcab6ac2964..01e709c8f24 100644 --- a/typeobjectpattern/src/main/java/com/iluwatar/typeobject/JsonParser.java +++ b/typeobjectpattern/src/main/java/com/iluwatar/typeobject/JsonParser.java @@ -25,11 +25,11 @@ import com.iluwatar.typeobject.Candy.Type; import java.io.File; -import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; -import java.util.Enumeration; import java.util.Hashtable; +import java.util.List; +import java.util.stream.Collectors; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; @@ -43,24 +43,24 @@ public class JsonParser { Hashtable candies; JsonParser() { - this.candies = new Hashtable(); + this.candies = new Hashtable<>(); } - void parse() throws FileNotFoundException, IOException, ParseException { + void parse() throws IOException, ParseException { var parser = new JSONParser(); - var jo = (JSONObject) parser.parse(new FileReader(new File("").getAbsolutePath() - + "\\src\\main\\java\\com\\iluwatar\\typeobject\\candy.json")); + var workingDirectory = new File("").getAbsolutePath(); + var filePath = List.of("src", "main", "java", "com", "iluwatar", "typeobject", "candy.json"); + var absolutePath = workingDirectory + File.separator + String.join(File.separator, filePath); + var jo = (JSONObject) parser.parse(new FileReader(absolutePath)); var a = (JSONArray) jo.get("candies"); for (var o : a) { var candy = (JSONObject) o; var name = (String) candy.get("name"); var parentName = (String) candy.get("parent"); var t = (String) candy.get("type"); - Type type = null; + var type = Type.crushableCandy; if (t.equals("rewardFruit")) { type = Type.rewardFruit; - } else { - type = Type.crushableCandy; } var points = Integer.parseInt((String) candy.get("points")); var c = new Candy(name, parentName, type, points); @@ -70,7 +70,7 @@ void parse() throws FileNotFoundException, IOException, ParseException { } void setParentAndPoints() { - for (Enumeration e = this.candies.keys(); e.hasMoreElements(); ) { + for (var e = this.candies.keys(); e.hasMoreElements(); ) { var c = this.candies.get(e.nextElement()); if (c.parentName == null) { c.parent = null; diff --git a/typeobjectpattern/src/test/java/com/iluwatar/typeobject/CandyGameTest.java b/typeobjectpattern/src/test/java/com/iluwatar/typeobject/CandyGameTest.java index 2b4d815e695..8175d1dd032 100644 --- a/typeobjectpattern/src/test/java/com/iluwatar/typeobject/CandyGameTest.java +++ b/typeobjectpattern/src/test/java/com/iluwatar/typeobject/CandyGameTest.java @@ -23,10 +23,10 @@ package com.iluwatar.typeobject; -import static org.junit.jupiter.api.Assertions.*; -import org.junit.jupiter.api.Test; -import java.util.ArrayList; +import static org.junit.jupiter.api.Assertions.assertTrue; + import com.iluwatar.typeobject.Candy.Type; +import org.junit.jupiter.api.Test; /** * The CandyGameTest class tests the methods in the {@link CandyGame} class. @@ -36,7 +36,7 @@ class CandyGameTest { @Test void adjacentCellsTest() { - var cg = new CandyGame(3,new CellPool(9)); + var cg = new CandyGame(3, new CellPool(9)); var arr1 = cg.adjacentCells(0, 0); var arr2 = cg.adjacentCells(1, 2); var arr3 = cg.adjacentCells(1, 1); @@ -49,19 +49,19 @@ void continueRoundTest() { var c1 = new Candy("green jelly", "jelly", Type.crushableCandy, 5); var c2 = new Candy("purple jelly", "jelly", Type.crushableCandy, 5); var c3 = new Candy("green apple", "apple", Type.rewardFruit, 10); - matrix[0][0] = new Cell(c1,0,0);; - matrix[0][1] = new Cell(c2,1,0); - matrix[1][0] = new Cell(c3,0,1); - matrix[1][1] = new Cell(c2,1,1); + matrix[0][0] = new Cell(c1, 0, 0); + matrix[0][1] = new Cell(c2, 1, 0); + matrix[1][0] = new Cell(c3, 0, 1); + matrix[1][1] = new Cell(c2, 1, 1); var p = new CellPool(4); - var cg = new CandyGame(2,p); + var cg = new CandyGame(2, p); cg.cells = matrix; var fruitInLastRow = cg.continueRound(); matrix[1][0].crush(p, matrix); - matrix[0][0] = new Cell(c3,0,0); - var matchingCandy = cg.continueRound(); - matrix[0][1].crush(p,matrix); - matrix[0][1] = new Cell(c3,1,0); + matrix[0][0] = new Cell(c3, 0, 0); + var matchingCandy = cg.continueRound(); + matrix[0][1].crush(p, matrix); + matrix[0][1] = new Cell(c3, 1, 0); var noneLeft = cg.continueRound(); assertTrue(fruitInLastRow && matchingCandy && !noneLeft); } diff --git a/typeobjectpattern/src/test/java/com/iluwatar/typeobject/CellPoolTest.java b/typeobjectpattern/src/test/java/com/iluwatar/typeobject/CellPoolTest.java index 9c3feb0f537..777dae2dddb 100644 --- a/typeobjectpattern/src/test/java/com/iluwatar/typeobject/CellPoolTest.java +++ b/typeobjectpattern/src/test/java/com/iluwatar/typeobject/CellPoolTest.java @@ -23,9 +23,10 @@ package com.iluwatar.typeobject; -import static org.junit.jupiter.api.Assertions.*; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.Hashtable; +import org.junit.jupiter.api.Test; /** * The CellPoolTest class tests the methods in the {@link CellPool} class. @@ -39,9 +40,7 @@ void assignRandomCandyTypesTest() { var ht = new Hashtable(); var parentTypes = 0; for (var i = 0; i < cp.randomCode.length; i++) { - if (ht.get(cp.randomCode[i].name) == null) { - ht.put(cp.randomCode[i].name, true); - } + ht.putIfAbsent(cp.randomCode[i].name, true); if (cp.randomCode[i].name.equals("fruit") || cp.randomCode[i].name.equals("candy")) { parentTypes++; } diff --git a/typeobjectpattern/src/test/java/com/iluwatar/typeobject/CellTest.java b/typeobjectpattern/src/test/java/com/iluwatar/typeobject/CellTest.java index ad183c5675a..18bca62bb50 100644 --- a/typeobjectpattern/src/test/java/com/iluwatar/typeobject/CellTest.java +++ b/typeobjectpattern/src/test/java/com/iluwatar/typeobject/CellTest.java @@ -23,14 +23,15 @@ package com.iluwatar.typeobject; -import static org.junit.jupiter.api.Assertions.*; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + import com.iluwatar.typeobject.Candy.Type; +import org.junit.jupiter.api.Test; /** * The CellTest class tests the methods in the {@link Cell} class. */ - class CellTest { @Test @@ -38,10 +39,10 @@ void interactTest() { var c1 = new Candy("green jelly", "jelly", Type.crushableCandy, 5); var c2 = new Candy("green apple", "apple", Type.rewardFruit, 10); var matrix = new Cell[4][4]; - matrix[0][0] = new Cell(c1,0,0); - matrix[0][1] = new Cell(c1,1,0); - matrix[0][2] = new Cell(c2,2,0); - matrix[0][3] = new Cell(c1,3,0); + matrix[0][0] = new Cell(c1, 0, 0); + matrix[0][1] = new Cell(c1, 1, 0); + matrix[0][2] = new Cell(c2, 2, 0); + matrix[0][3] = new Cell(c1, 3, 0); var cp = new CellPool(5); var points1 = matrix[0][0].interact(matrix[0][1], cp, matrix); var points2 = matrix[0][2].interact(matrix[0][3], cp, matrix); @@ -53,9 +54,9 @@ void crushTest() { var c1 = new Candy("green jelly", "jelly", Type.crushableCandy, 5); var c2 = new Candy("purple candy", "candy", Type.crushableCandy, 5); var matrix = new Cell[4][4]; - matrix[0][0] = new Cell(c1,0,0); - matrix[1][0] = new Cell(c2,0,1); + matrix[0][0] = new Cell(c1, 0, 0); + matrix[1][0] = new Cell(c2, 0, 1); matrix[1][0].crush(new CellPool(5), matrix); - assertTrue(matrix[1][0].candy.name.equals("green jelly")); + assertEquals("green jelly", matrix[1][0].candy.name); } } diff --git a/unit-of-work/src/test/java/com/iluwatar/unitofwork/AppTest.java b/unit-of-work/src/test/java/com/iluwatar/unitofwork/AppTest.java index a6e9b4b15ab..ecbe5fc5342 100644 --- a/unit-of-work/src/test/java/com/iluwatar/unitofwork/AppTest.java +++ b/unit-of-work/src/test/java/com/iluwatar/unitofwork/AppTest.java @@ -25,15 +25,12 @@ import org.junit.Test; -import java.io.IOException; - /** * AppTest */ public class AppTest { @Test public void test() { - String[] args = {}; - App.main(args); + App.main(new String[]{}); } } diff --git a/unit-of-work/src/test/java/com/iluwatar/unitofwork/StudentRepositoryTest.java b/unit-of-work/src/test/java/com/iluwatar/unitofwork/StudentRepositoryTest.java index eea352f7d0c..cda2f6fca7c 100644 --- a/unit-of-work/src/test/java/com/iluwatar/unitofwork/StudentRepositoryTest.java +++ b/unit-of-work/src/test/java/com/iluwatar/unitofwork/StudentRepositoryTest.java @@ -23,20 +23,22 @@ package com.iluwatar.unitofwork; +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.verifyZeroInteractions; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.*; - /** * tests {@link StudentRepository} */ @@ -51,7 +53,7 @@ public class StudentRepositoryTest { private StudentRepository studentRepository; @Before - public void setUp() throws Exception { + public void setUp() { context = new HashMap<>(); studentRepository = new StudentRepository(context, studentDatabase); } @@ -85,9 +87,9 @@ public void shouldSaveModifiedStudentWithoutWritingToDb() { @Test public void shouldSaveAllLocalChangesToDb() { - context.put(IUnitOfWork.INSERT, Collections.singletonList(student1)); - context.put(IUnitOfWork.MODIFY, Collections.singletonList(student1)); - context.put(IUnitOfWork.DELETE, Collections.singletonList(student1)); + context.put(IUnitOfWork.INSERT, List.of(student1)); + context.put(IUnitOfWork.MODIFY, List.of(student1)); + context.put(IUnitOfWork.DELETE, List.of(student1)); studentRepository.commit(); @@ -116,8 +118,8 @@ public void shouldNotWriteToDbIfNothingToCommit() { @Test public void shouldNotInsertToDbIfNoRegisteredStudentsToBeCommitted() { - context.put(IUnitOfWork.MODIFY, Collections.singletonList(student1)); - context.put(IUnitOfWork.DELETE, Collections.singletonList(student1)); + context.put(IUnitOfWork.MODIFY, List.of(student1)); + context.put(IUnitOfWork.DELETE, List.of(student1)); studentRepository.commit(); @@ -126,8 +128,8 @@ public void shouldNotInsertToDbIfNoRegisteredStudentsToBeCommitted() { @Test public void shouldNotModifyToDbIfNotRegisteredStudentsToBeCommitted() { - context.put(IUnitOfWork.INSERT, Collections.singletonList(student1)); - context.put(IUnitOfWork.DELETE, Collections.singletonList(student1)); + context.put(IUnitOfWork.INSERT, List.of(student1)); + context.put(IUnitOfWork.DELETE, List.of(student1)); studentRepository.commit(); @@ -136,8 +138,8 @@ public void shouldNotModifyToDbIfNotRegisteredStudentsToBeCommitted() { @Test public void shouldNotDeleteFromDbIfNotRegisteredStudentsToBeCommitted() { - context.put(IUnitOfWork.INSERT, Collections.singletonList(student1)); - context.put(IUnitOfWork.MODIFY, Collections.singletonList(student1)); + context.put(IUnitOfWork.INSERT, List.of(student1)); + context.put(IUnitOfWork.MODIFY, List.of(student1)); studentRepository.commit(); diff --git a/value-object/src/test/java/com/iluwatar/value/object/AppTest.java b/value-object/src/test/java/com/iluwatar/value/object/AppTest.java index 62821180829..c0e680ec4c8 100644 --- a/value-object/src/test/java/com/iluwatar/value/object/AppTest.java +++ b/value-object/src/test/java/com/iluwatar/value/object/AppTest.java @@ -32,7 +32,6 @@ public class AppTest { @Test public void test() { - String[] args = {}; - App.main(args); + App.main(new String[]{}); } } diff --git a/value-object/src/test/java/com/iluwatar/value/object/HeroStatTest.java b/value-object/src/test/java/com/iluwatar/value/object/HeroStatTest.java index f662c03e54b..122205a57df 100644 --- a/value-object/src/test/java/com/iluwatar/value/object/HeroStatTest.java +++ b/value-object/src/test/java/com/iluwatar/value/object/HeroStatTest.java @@ -23,13 +23,13 @@ package com.iluwatar.value.object; -import com.google.common.testing.EqualsTester; -import org.junit.jupiter.api.Test; - import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; import static org.junit.Assert.assertThat; +import com.google.common.testing.EqualsTester; +import org.junit.jupiter.api.Test; + /** * Unit test for HeroStat. */ @@ -37,12 +37,10 @@ public class HeroStatTest { /** * Tester for equals() and hashCode() methods of a class. Using guava's EqualsTester. - * - * @see - * http://static.javadoc.io/com.google.guava/guava-testlib/19.0/com/google/common/testing/EqualsTester.html - * - * * + * @see + * http://static.javadoc.io/com.google.guava/guava-testlib/19.0/com/google/common/testing/EqualsTester.html + * */ @Test public void testEquals() { diff --git a/visitor/src/main/java/com/iluwatar/visitor/App.java b/visitor/src/main/java/com/iluwatar/visitor/App.java index 7f0abb0f0f3..fc4caa1f1e7 100644 --- a/visitor/src/main/java/com/iluwatar/visitor/App.java +++ b/visitor/src/main/java/com/iluwatar/visitor/App.java @@ -28,22 +28,22 @@ * can be added without altering the node interface.

* *

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

- * + * traversed by visitors. {@link SoldierVisitor} applies its operation on {@link Soldier}s, {@link + * SergeantVisitor} on {@link Sergeant}s and so on.

*/ public class App { /** * Program entry point. - * + * * @param args command line args */ public static void main(String[] args) { - var commander = - new Commander(new Sergeant(new Soldier(), new Soldier(), new Soldier()), new Sergeant( - new Soldier(), new Soldier(), new Soldier())); + var commander = new Commander( + new Sergeant(new Soldier(), new Soldier(), new Soldier()), + new Sergeant(new Soldier(), new Soldier(), new Soldier()) + ); commander.accept(new SoldierVisitor()); commander.accept(new SergeantVisitor()); commander.accept(new CommanderVisitor()); diff --git a/visitor/src/main/java/com/iluwatar/visitor/Unit.java b/visitor/src/main/java/com/iluwatar/visitor/Unit.java index 318e84262f7..c890884b30f 100644 --- a/visitor/src/main/java/com/iluwatar/visitor/Unit.java +++ b/visitor/src/main/java/com/iluwatar/visitor/Unit.java @@ -23,6 +23,8 @@ package com.iluwatar.visitor; +import java.util.Arrays; + /** * Interface for the nodes in hierarchy. */ @@ -38,8 +40,6 @@ public Unit(Unit... children) { * Accept visitor. */ public void accept(UnitVisitor visitor) { - for (var child : children) { - child.accept(visitor); - } + Arrays.stream(children).forEach(child -> child.accept(visitor)); } } diff --git a/visitor/src/test/java/com/iluwatar/visitor/AppTest.java b/visitor/src/test/java/com/iluwatar/visitor/AppTest.java index 45804a9c6f4..c16f3119521 100644 --- a/visitor/src/test/java/com/iluwatar/visitor/AppTest.java +++ b/visitor/src/test/java/com/iluwatar/visitor/AppTest.java @@ -32,7 +32,6 @@ public class AppTest { @Test public void test() { - String[] args = {}; - App.main(args); + App.main(new String[]{}); } } diff --git a/visitor/src/test/java/com/iluwatar/visitor/UnitTest.java b/visitor/src/test/java/com/iluwatar/visitor/UnitTest.java index 7385ea5a7bd..0356782d715 100644 --- a/visitor/src/test/java/com/iluwatar/visitor/UnitTest.java +++ b/visitor/src/test/java/com/iluwatar/visitor/UnitTest.java @@ -30,12 +30,11 @@ import java.util.Arrays; import java.util.function.Function; - import org.junit.jupiter.api.Test; /** - * Date: 12/30/15 - 18:59 PM. - * Test related to Units + * Date: 12/30/15 - 18:59 PM. Test related to Units + * * @param Type of Unit * @author Jeroen Meulemeester */ @@ -65,9 +64,7 @@ public void testAccept() { unit.accept(visitor); verifyVisit(unit, visitor); - for (final var child : children) { - verify(child).accept(eq(visitor)); - } + Arrays.stream(children).forEach(child -> verify(child).accept(eq(visitor))); verifyNoMoreInteractions(children); verifyNoMoreInteractions(visitor); diff --git a/visitor/src/test/java/com/iluwatar/visitor/VisitorTest.java b/visitor/src/test/java/com/iluwatar/visitor/VisitorTest.java index 3c458f6f4c8..146ee22f8e8 100644 --- a/visitor/src/test/java/com/iluwatar/visitor/VisitorTest.java +++ b/visitor/src/test/java/com/iluwatar/visitor/VisitorTest.java @@ -31,15 +31,14 @@ import java.util.LinkedList; import java.util.List; import java.util.Optional; - import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.slf4j.LoggerFactory; /** - * Date: 12/30/15 - 18:59 PM. - * Test case for Visitor Pattern + * Date: 12/30/15 - 18:59 PM. Test case for Visitor Pattern + * * @param Type of UnitVisitor * @author Jeroen Meulemeester */ @@ -84,11 +83,12 @@ public void tearDown() { * @param sergeantResponse The optional expected response when being visited by a sergeant * @param soldierResponse The optional expected response when being visited by a soldier */ - public VisitorTest(final V visitor, - final Optional commanderResponse, - final Optional sergeantResponse, - final Optional soldierResponse) { - + public VisitorTest( + final V visitor, + final Optional commanderResponse, + final Optional sergeantResponse, + final Optional soldierResponse + ) { this.visitor = visitor; this.commanderResponse = commanderResponse; this.sergeantResponse = sergeantResponse;