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
This commit is contained in:
Anurag Agarwal 2019-11-14 11:12:05 +05:30 committed by Ilkka Seppälä
parent 160b737dcc
commit 50467c9e76
45 changed files with 379 additions and 422 deletions

View File

@ -26,15 +26,12 @@ package com.iluwatar.templatemethod;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
/** /**
*
* Application test * Application test
*
*/ */
public class AppTest { public class AppTest {
@Test @Test
public void test() { public void test() {
String[] args = {}; App.main(new String[]{});
App.main(args);
} }
} }

View File

@ -23,12 +23,12 @@
package com.iluwatar.templatemethod; package com.iluwatar.templatemethod;
import org.junit.jupiter.api.Test;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.verifyNoMoreInteractions;
import org.junit.jupiter.api.Test;
/** /**
* Date: 12/29/15 - 18:15 PM * Date: 12/29/15 - 18:15 PM
* *
@ -41,8 +41,8 @@ public class HalflingThiefTest {
*/ */
@Test @Test
public void testSteal() { public void testSteal() {
final StealingMethod method = mock(StealingMethod.class); final var method = mock(StealingMethod.class);
final HalflingThief thief = new HalflingThief(method); final var thief = new HalflingThief(method);
thief.steal(); thief.steal();
verify(method).steal(); verify(method).steal();
@ -55,13 +55,13 @@ public class HalflingThiefTest {
*/ */
@Test @Test
public void testChangeMethod() { public void testChangeMethod() {
final StealingMethod initialMethod = mock(StealingMethod.class); final var initialMethod = mock(StealingMethod.class);
final HalflingThief thief = new HalflingThief(initialMethod); final var thief = new HalflingThief(initialMethod);
thief.steal(); thief.steal();
verify(initialMethod).steal(); verify(initialMethod).steal();
final StealingMethod newMethod = mock(StealingMethod.class); final var newMethod = mock(StealingMethod.class);
thief.changeMethod(newMethod); thief.changeMethod(newMethod);
thief.steal(); thief.steal();

View File

@ -23,6 +23,9 @@
package com.iluwatar.templatemethod; 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.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase; import ch.qos.logback.core.AppenderBase;
@ -33,11 +36,9 @@ import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.slf4j.LoggerFactory; 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 * Date: 12/30/15 - 18:12 PM
*
* @param <M> Type of StealingMethod * @param <M> Type of StealingMethod
* @author Jeroen Meulemeester * @author Jeroen Meulemeester
*/ */

View File

@ -56,7 +56,7 @@ public class App {
LOGGER.info("Program started"); LOGGER.info("Program started");
// Create a list of tasks to be executed // Create a list of tasks to be executed
List<Task> tasks = List.of( var tasks = List.of(
new PotatoPeelingTask(3), new PotatoPeelingTask(3),
new PotatoPeelingTask(6), new PotatoPeelingTask(6),
new CoffeeMakingTask(2), new CoffeeMakingTask(2),
@ -82,10 +82,7 @@ public class App {
// Allocate new worker for each task // Allocate new worker for each task
// The worker is executed when a thread becomes // The worker is executed when a thread becomes
// available in the thread pool // available in the thread pool
for (int i = 0; i < tasks.size(); i++) { tasks.stream().map(Worker::new).forEach(executor::execute);
var worker = new Worker(tasks.get(i));
executor.execute(worker);
}
// All tasks were executed, now shutdown // All tasks were executed, now shutdown
executor.shutdown(); executor.shutdown();
while (!executor.isTerminated()) { while (!executor.isTerminated()) {

View File

@ -27,15 +27,13 @@ import org.junit.jupiter.api.Test;
/** /**
* Application test * Application test
*
* @author ilkka
* *
* @author ilkka
*/ */
public class AppTest { public class AppTest {
@Test @Test
public void test() { public void test() {
String[] args = {}; App.main(new String[]{});
App.main(args);
} }
} }

View File

@ -23,27 +23,25 @@
package com.iluwatar.threadpool; package com.iluwatar.threadpool;
import org.junit.jupiter.api.Test;
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 java.time.Duration.ofMillis;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTimeout; import static org.junit.jupiter.api.Assertions.assertTimeout;
import java.util.ArrayList;
import java.util.Objects;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.function.IntFunction;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.junit.jupiter.api.Test;
/** /**
* Date: 12/30/15 - 18:22 PM * Date: 12/30/15 - 18:22 PM Test for Tasks using a Thread Pool
* Test for Tasks using a Thread Pool *
* @param <T> Type of Task * @param <T> Type of Task
* @author Jeroen Meulemeester * @author Jeroen Meulemeester
*/ */
@ -87,14 +85,13 @@ public abstract class TaskTest<T extends Task> {
@Test @Test
public void testIdGeneration() throws Exception { public void testIdGeneration() throws Exception {
assertTimeout(ofMillis(10000), () -> { assertTimeout(ofMillis(10000), () -> {
final ExecutorService service = Executors.newFixedThreadPool(THREAD_COUNT); final var service = Executors.newFixedThreadPool(THREAD_COUNT);
final List<Callable<Integer>> tasks = new ArrayList<>(); final var tasks = IntStream.range(0, TASK_COUNT)
for (int i = 0; i < TASK_COUNT; i++) { .<Callable<Integer>>mapToObj(i -> () -> factory.apply(1).getId())
tasks.add(() -> factory.apply(1).getId()); .collect(Collectors.toCollection(ArrayList::new));
}
final List<Integer> ids = service.invokeAll(tasks) final var ids = service.invokeAll(tasks)
.stream() .stream()
.map(TaskTest::get) .map(TaskTest::get)
.filter(Objects::nonNull) .filter(Objects::nonNull)
@ -102,7 +99,7 @@ public abstract class TaskTest<T extends Task> {
service.shutdownNow(); service.shutdownNow();
final long uniqueIdCount = ids.stream() final var uniqueIdCount = ids.stream()
.distinct() .distinct()
.count(); .count();
@ -117,7 +114,7 @@ public abstract class TaskTest<T extends Task> {
*/ */
@Test @Test
public void testTimeMs() { 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()); assertEquals(this.expectedExecutionTime * i, this.factory.apply(i).getTimeMs());
} }
} }

View File

@ -23,13 +23,13 @@
package com.iluwatar.threadpool; package com.iluwatar.threadpool;
import org.junit.jupiter.api.Test;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.Mockito.verifyZeroInteractions;
import org.junit.jupiter.api.Test;
/** /**
* Date: 12/30/15 - 18:21 PM * Date: 12/30/15 - 18:21 PM
* *
@ -42,8 +42,8 @@ public class WorkerTest {
*/ */
@Test @Test
public void testRun() { public void testRun() {
final Task task = mock(Task.class); final var task = mock(Task.class);
final Worker worker = new Worker(task); final var worker = new Worker(task);
verifyZeroInteractions(task); verifyZeroInteractions(task);
worker.run(); worker.run();

View File

@ -26,6 +26,7 @@ package com.iluwatar.throttling;
import com.iluwatar.throttling.timer.ThrottleTimerImpl; import com.iluwatar.throttling.timer.ThrottleTimerImpl;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -73,14 +74,14 @@ public class App {
private static void makeServiceCalls(Tenant tenant, CallsCount callsCount) { private static void makeServiceCalls(Tenant tenant, CallsCount callsCount) {
var timer = new ThrottleTimerImpl(10, callsCount); var timer = new ThrottleTimerImpl(10, callsCount);
var service = new B2BService(timer, 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); service.dummyCustomerApi(tenant);
// Sleep is introduced to keep the output in check and easy to view and analyze the results.
try { try {
Thread.sleep(1); Thread.sleep(1);
} catch (InterruptedException e) { } catch (InterruptedException e) {
LOGGER.error("Thread interrupted: {}", e.getMessage()); LOGGER.error("Thread interrupted: {}", e.getMessage());
} }
} });
} }
} }

View File

@ -73,8 +73,6 @@ public final class CallsCount {
*/ */
public void reset() { public void reset() {
LOGGER.debug("Resetting the map."); LOGGER.debug("Resetting the map.");
for (Entry<String, AtomicLong> e : tenantCallsCount.entrySet()) { tenantCallsCount.replaceAll((k, v) -> new AtomicLong(0));
tenantCallsCount.put(e.getKey(), new AtomicLong(0));
}
} }
} }

View File

@ -32,7 +32,6 @@ public class AppTest {
@Test @Test
public void test() { public void test() {
final String[] args = {}; App.main(new String[]{});
App.main(args);
} }
} }

View File

@ -23,12 +23,12 @@
package com.iluwatar.throttling; package com.iluwatar.throttling;
import com.iluwatar.throttling.timer.Throttler;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import com.iluwatar.throttling.timer.Throttler;
import java.util.stream.IntStream;
import org.junit.jupiter.api.Test;
/** /**
* B2BServiceTest class to test the B2BService * B2BServiceTest class to test the B2BService
*/ */
@ -38,15 +38,14 @@ public class B2BServiceTest {
@Test @Test
public void dummyCustomerApiTest() { 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 // In order to assure that throttling limits will not be reset, we use an empty throttling implementation
Throttler timer = () -> { }; var timer = (Throttler) () -> {
B2BService service = new B2BService(timer, callsCount); };
var service = new B2BService(timer, callsCount);
for (int i = 0; i < 5; i++) { IntStream.range(0, 5).mapToObj(i -> tenant).forEach(service::dummyCustomerApi);
service.dummyCustomerApi(tenant); var counter = callsCount.getCount(tenant.getName());
}
long counter = callsCount.getCount(tenant.getName());
assertEquals(2, counter, "Counter limit must be reached"); assertEquals(2, counter, "Counter limit must be reached");
} }
} }

View File

@ -23,11 +23,10 @@
package com.iluwatar.throttling; package com.iluwatar.throttling;
import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertThrows;
import java.security.InvalidParameterException; import java.security.InvalidParameterException;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertThrows;
/** /**
* TenantTest to test the creation of Tenant with valid parameters. * TenantTest to test the creation of Tenant with valid parameters.
@ -37,7 +36,7 @@ public class TenantTest {
@Test @Test
public void constructorTest() { public void constructorTest() {
assertThrows(InvalidParameterException.class, () -> { assertThrows(InvalidParameterException.class, () -> {
Tenant tenant = new Tenant("FailTenant", -1, new CallsCount()); new Tenant("FailTenant", -1, new CallsCount());
}); });
} }
} }

View File

@ -24,10 +24,7 @@
package com.iluwatar.tls; package com.iluwatar.tls;
import java.util.Calendar; import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -71,20 +68,20 @@ public class App {
* @param args command line args * @param args command line args
*/ */
public static void main(String[] args) { public static void main(String[] args) {
int counterDateValues = 0; var counterDateValues = 0;
int counterExceptions = 0; var counterExceptions = 0;
// Create a callable // 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 // start 4 threads, each using the same Callable instance
ExecutorService executor = Executors.newCachedThreadPool(); var executor = Executors.newCachedThreadPool();
Future<Result> futureResult1 = executor.submit(callableDf); var futureResult1 = executor.submit(callableDf);
Future<Result> futureResult2 = executor.submit(callableDf); var futureResult2 = executor.submit(callableDf);
Future<Result> futureResult3 = executor.submit(callableDf); var futureResult3 = executor.submit(callableDf);
Future<Result> futureResult4 = executor.submit(callableDf); var futureResult4 = executor.submit(callableDf);
try { try {
Result[] result = new Result[4]; var result = new Result[4];
result[0] = futureResult1.get(); result[0] = futureResult1.get();
result[1] = futureResult2.get(); result[1] = futureResult2.get();
result[2] = futureResult3.get(); result[2] = futureResult3.get();
@ -92,9 +89,9 @@ public class App {
// Print results of thread executions (converted dates and raised exceptions) // Print results of thread executions (converted dates and raised exceptions)
// and count them // and count them
for (int i = 0; i < result.length; i++) { for (var value : result) {
counterDateValues = counterDateValues + printAndCountDates(result[i]); counterDateValues = counterDateValues + printAndCountDates(value);
counterExceptions = counterExceptions + printAndCountExceptions(result[i]); counterExceptions = counterExceptions + printAndCountExceptions(value);
} }
// a correct run should deliver 20 times 15.12.2015 // a correct run should deliver 20 times 15.12.2015
@ -115,15 +112,16 @@ public class App {
*/ */
private static int printAndCountDates(Result res) { private static int printAndCountDates(Result res) {
// a correct run should deliver 5 times 15.12.2015 per each thread // a correct run should deliver 5 times 15.12.2015 per each thread
int counter = 0; var counter = 0;
for (Date dt : res.getDateList()) { for (var dt : res.getDateList()) {
counter++; counter++;
Calendar cal = Calendar.getInstance(); var cal = Calendar.getInstance();
cal.setTime(dt); cal.setTime(dt);
// Formatted output of the date value: DD.MM.YYYY // Formatted output of the date value: DD.MM.YYYY
LOGGER.info( LOGGER.info(cal.get(Calendar.DAY_OF_MONTH) + "."
cal.get(Calendar.DAY_OF_MONTH) + "." + cal.get(Calendar.MONTH) + "." + +cal + cal.get(Calendar.MONTH) + "."
.get(Calendar.YEAR)); + cal.get(Calendar.YEAR)
);
} }
return counter; return counter;
} }
@ -136,8 +134,8 @@ public class App {
*/ */
private static int printAndCountExceptions(Result res) { private static int printAndCountExceptions(Result res) {
// a correct run shouldn't deliver any exception // a correct run shouldn't deliver any exception
int counter = 0; var counter = 0;
for (String ex : res.getExceptionList()) { for (var ex : res.getExceptionList()) {
counter++; counter++;
LOGGER.info(ex); LOGGER.info(ex);
} }

View File

@ -26,6 +26,7 @@ package com.iluwatar.tls;
import java.text.DateFormat; import java.text.DateFormat;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.concurrent.Callable; import java.util.concurrent.Callable;
import java.util.stream.IntStream;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -58,13 +59,10 @@ public class DateFormatCallable implements Callable<Result> {
* @param inDateValue string date value, e.g. "21/06/2016" * @param inDateValue string date value, e.g. "21/06/2016"
*/ */
public DateFormatCallable(String inDateFormat, String inDateValue) { public DateFormatCallable(String inDateFormat, String inDateValue) {
final String idf = inDateFormat; //TLTL final var idf = inDateFormat; //TLTL
this.df = new ThreadLocal<DateFormat>() { //TLTL this.df = ThreadLocal.withInitial(() -> { //TLTL
@Override //TLTL return new SimpleDateFormat(idf); //TLTL
protected DateFormat initialValue() { //TLTL }); //TLTL
return new SimpleDateFormat(idf); //TLTL
} //TLTL
}; //TLTL
// this.df = new SimpleDateFormat(inDateFormat); //NTLNTL // this.df = new SimpleDateFormat(inDateFormat); //NTLNTL
this.dateValue = inDateValue; this.dateValue = inDateValue;
} }
@ -72,10 +70,10 @@ public class DateFormatCallable implements Callable<Result> {
@Override @Override
public Result call() { public Result call() {
LOGGER.info(Thread.currentThread() + " started executing..."); LOGGER.info(Thread.currentThread() + " started executing...");
Result result = new Result(); var result = new Result();
// Convert date value to date 5 times // Convert date value to date 5 times
for (int i = 1; i <= 5; i++) { IntStream.rangeClosed(1, 5).forEach(i -> {
try { try {
// this is the statement where it is important to have the // this is the statement where it is important to have the
// instance of SimpleDateFormat locally // instance of SimpleDateFormat locally
@ -86,8 +84,7 @@ public class DateFormatCallable implements Callable<Result> {
// write the Exception to a list and continue work // write the Exception to a list and continue work
result.getExceptionList().add(e.getClass() + ": " + e.getMessage()); result.getExceptionList().add(e.getClass() + ": " + e.getMessage());
} }
});
}
LOGGER.info(Thread.currentThread() + " finished processing part of the thread"); LOGGER.info(Thread.currentThread() + " finished processing part of the thread");

View File

@ -39,11 +39,11 @@ import java.util.List;
*/ */
public class Result { public class Result {
// A list to collect the date values created in one thread // A list to collect the date values created in one thread
private List<Date> dateList = new ArrayList<Date>(); private List<Date> dateList = new ArrayList<>();
// A list to collect Exceptions thrown in one threads (should be none in // A list to collect Exceptions thrown in one threads (should be none in
// this example) // this example)
private List<String> exceptionList = new ArrayList<String>(); private List<String> exceptionList = new ArrayList<>();
/** /**
* Get list of date values collected within a thread execution. * Get list of date values collected within a thread execution.

View File

@ -27,14 +27,12 @@ import org.junit.jupiter.api.Test;
/** /**
* Tests that thread local storage example runs without errors. * Tests that thread local storage example runs without errors.
*
* @author Thomas Bauer, January 2017
* *
* @author Thomas Bauer, January 2017
*/ */
public class AppTest { public class AppTest {
@Test @Test
public void test() throws Exception { public void test() {
String[] args = {}; App.main(new String[]{});
App.main(args);
} }
} }

View File

@ -23,65 +23,62 @@
package com.iluwatar.tls; package com.iluwatar.tls;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
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.assertEquals;
import static org.junit.jupiter.api.Assertions.fail; import static org.junit.jupiter.api.Assertions.fail;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.concurrent.Executors;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
/** /**
*
* Test of the Callable * Test of the Callable
*
* In this test {@link DateFormatCallable} is tested with only one thread (i.e. without concurrency situation)
* <p> * <p>
* After a successful run 5 date values should be in the result object. All dates should have * In this test {@link DateFormatCallable} is tested with only one thread (i.e. without concurrency
* the same value (15.11.2015). To avoid problems with time zone not the date instances themselves * situation)
* are compared by the test. For the test the dates are converted into string format DD.MM.YYY
* <p> * <p>
* Additionally the number of list entries are tested for both the list with the date values * After a successful run 5 date values should be in the result object. All dates should have the
* and the list with the exceptions * 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
* @author Thomas Bauer, January 2017 * <p>
* 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 { public class DateFormatCallableTest {
// Class variables used in setup() have to be static because setup() has to be static // Class variables used in setup() have to be static because setup() has to be static
/** /**
* Result object given back by DateFormatCallable * Result object given back by DateFormatCallable -- Array with converted date values -- Array
* -- Array with converted date values * with thrown exceptions
* -- 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<String> createdDateValues = new ArrayList<String>(); private static List<String> createdDateValues = new ArrayList<>();
/** /**
* Expected number of date values in the date value list created by the run of DateFormatRunnalbe * 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<String> expectedDateValues = List.of("15.11.2015", "15.11.2015", "15.11.2015", "15.11.2015", "15.11.2015"); private List<String> 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 * Run Callable and prepare results for usage in the test methods
@ -89,10 +86,10 @@ public class DateFormatCallableTest {
@BeforeAll @BeforeAll
public static void setup() { public static void setup() {
// Create a callable // 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 // start thread using the Callable instance
ExecutorService executor = Executors.newCachedThreadPool(); var executor = Executors.newCachedThreadPool();
Future<Result> futureResult = executor.submit(callableDf); var futureResult = executor.submit(callableDf);
try { try {
result = futureResult.get(); result = futureResult.get();
createdDateValues = convertDatesToString(result); createdDateValues = convertDatesToString(result);
@ -107,18 +104,22 @@ public class DateFormatCallableTest {
if (res == null || res.getDateList() == null || res.getDateList().size() == 0) { if (res == null || res.getDateList() == null || res.getDateList().size() == 0) {
return null; return null;
} }
List<String> returnList = new ArrayList<String>(); var returnList = new ArrayList<String>();
for (Date dt : res.getDateList()) { for (var dt : res.getDateList()) {
Calendar cal = Calendar.getInstance(); var cal = Calendar.getInstance();
cal.setTime(dt); 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; 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 @Test
public void testDateValues() { public void testDateValues() {
@ -126,7 +127,8 @@ public class DateFormatCallableTest {
} }
/** /**
* 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 @Test
public void testCounterDateValues() { public void testCounterDateValues() {
@ -134,8 +136,8 @@ public class DateFormatCallableTest {
} }
/** /**
* Test number of Exceptions in the list after the run of DateFormatRunnalbe. A correct run should deliver * Test number of Exceptions in the list after the run of DateFormatRunnalbe. A correct run should
* no exceptions * deliver no exceptions
*/ */
@Test @Test
public void testCounterExceptions() { public void testCounterExceptions() {

View File

@ -23,63 +23,55 @@
package com.iluwatar.tls; package com.iluwatar.tls;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
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.assertEquals;
import static org.junit.jupiter.api.Assertions.fail; import static org.junit.jupiter.api.Assertions.fail;
import java.util.List;
import java.util.concurrent.Executors;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
/** /**
*
* Test of the Callable * Test of the Callable
*
* In this test {@link DateFormatCallable} is tested with only one thread (i.e. without concurrency situation)
* <p> * <p>
* An incorrect formatted date is passed to the Callable * In this test {@link DateFormatCallable} is tested with only one thread (i.e. without concurrency
* After a successful run 0 date values and 5 exceptions should be in the result object. * situation)
* * <p>
* @author Thomas Bauer, January 2017 * 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 { public class DateFormatCallableTestIncorrectDateFormat {
// Class variables used in setup() have to be static because setup() has to be static // Class variables used in setup() have to be static because setup() has to be static
/** /**
* Result object given back by DateFormatCallable * Result object given back by DateFormatCallable -- Array with converted date values -- Array
* -- Array with converted date values * with thrown exceptions
* -- Array with thrown exceptions
*/ */
static Result result; private static Result result;
/**
* The date values created by the run of DateFormatRunnalbe. List will be filled in the setup() method
*/
static List<String> createdExceptions = new ArrayList<String>();
/** /**
* Expected number of date values in the date value list created by the run of DateFormatRunnalbe * 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<String> expectedExceptions = List.of("class java.text.ParseException: Unparseable date: \"15.12.2015\"", private List<String> 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\"",
"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 * Run Callable and prepare results for usage in the test methods
@ -87,10 +79,10 @@ public class DateFormatCallableTestIncorrectDateFormat {
@BeforeAll @BeforeAll
public static void setup() { public static void setup() {
// Create a callable. Pass a string date value not matching the format string // 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 // start thread using the Callable instance
ExecutorService executor = Executors.newCachedThreadPool(); var executor = Executors.newCachedThreadPool();
Future<Result> futureResult = executor.submit(callableDf); var futureResult = executor.submit(callableDf);
try { try {
result = futureResult.get(); result = futureResult.get();
} catch (Exception e) { } catch (Exception e) {
@ -109,7 +101,8 @@ public class DateFormatCallableTestIncorrectDateFormat {
} }
/** /**
* 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 @Test
public void testCounterDateValues() { public void testCounterDateValues() {
@ -117,7 +110,7 @@ public class DateFormatCallableTestIncorrectDateFormat {
} }
/** /**
* 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 * deliver 5 exceptions
*/ */
@Test @Test

View File

@ -23,69 +23,66 @@
package com.iluwatar.tls; package com.iluwatar.tls;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
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.assertEquals;
import static org.junit.jupiter.api.Assertions.fail; import static org.junit.jupiter.api.Assertions.fail;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.concurrent.Executors;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
/** /**
*
* Test of the Callable * Test of the Callable
* * <p>
* In this test {@link DateFormatCallable} is used by 4 threads in parallel * In this test {@link DateFormatCallable} is used by 4 threads in parallel
* <p> * <p>
* 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 * 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
* <p> * <p>
* Additionally the number of list entries are tested for both the list with the date values * Additionally the number of list entries are tested for both the list with the date values and the
* and the list with the exceptions * list with the exceptions
*
* @author Thomas Bauer, January 2017
* *
* @author Thomas Bauer, January 2017
*/ */
public class DateFormatCallableTestMultiThread { public class DateFormatCallableTestMultiThread {
// Class variables used in setup() have to be static because setup() has to be static // 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 * Result object given back by DateFormatCallable, one for each thread -- Array with converted
* -- Array with converted date values * date values -- Array with thrown exceptions
* -- 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") @SuppressWarnings("serial")
static class StringArrayList extends ArrayList<String> { private static class StringArrayList extends ArrayList<String> {
/* nothing needed here */ /* nothing needed here */
} }
static List<String>[] createdDateValues = new StringArrayList[4];
private static List<String>[] createdDateValues = new StringArrayList[4];
/** /**
* Expected number of date values in the date value list created by each thread * 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<String> expectedDateValues = List.of("15.11.2015", "15.11.2015", "15.11.2015", "15.11.2015", "15.11.2015"); private List<String> 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 * Run Callable and prepare results for usage in the test methods
@ -93,19 +90,19 @@ public class DateFormatCallableTestMultiThread {
@BeforeAll @BeforeAll
public static void setup() { public static void setup() {
// Create a callable // 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 // start thread using the Callable instance
ExecutorService executor = Executors.newCachedThreadPool(); var executor = Executors.newCachedThreadPool();
Future<Result> futureResult1 = executor.submit(callableDf); var futureResult1 = executor.submit(callableDf);
Future<Result> futureResult2 = executor.submit(callableDf); var futureResult2 = executor.submit(callableDf);
Future<Result> futureResult3 = executor.submit(callableDf); var futureResult3 = executor.submit(callableDf);
Future<Result> futureResult4 = executor.submit(callableDf); var futureResult4 = executor.submit(callableDf);
try { try {
result[0] = futureResult1.get(); result[0] = futureResult1.get();
result[1] = futureResult2.get(); result[1] = futureResult2.get();
result[2] = futureResult3.get(); result[2] = futureResult3.get();
result[3] = futureResult4.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]); createdDateValues[i] = convertDatesToString(result[i]);
} }
} catch (Exception e) { } catch (Exception e) {
@ -119,46 +116,49 @@ public class DateFormatCallableTestMultiThread {
if (res == null || res.getDateList() == null || res.getDateList().size() == 0) { if (res == null || res.getDateList() == null || res.getDateList().size() == 0) {
return null; return null;
} }
List<String> returnList = new StringArrayList(); var returnList = new StringArrayList();
for (Date dt : res.getDateList()) { for (var dt : res.getDateList()) {
Calendar cal = Calendar.getInstance(); var cal = Calendar.getInstance();
cal.setTime(dt); 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; 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
* by each thread * 15.12.2015 by each thread
*/ */
@Test @Test
public void testDateValues() { public void testDateValues() {
for (int i = 0; i < createdDateValues.length; i++) { for (var createdDateValue : createdDateValues) {
assertEquals(expectedDateValues, createdDateValues[i]); 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 * deliver 5 date values by each thread
*/ */
@Test @Test
public void testCounterDateValues() { public void testCounterDateValues() {
for (int i = 0; i < result.length; i++) { for (var value : result) {
assertEquals(expectedCounterDateValues, result[i].getDateList().size()); 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 * deliver no exceptions
*/ */
@Test @Test
public void testCounterExceptions() { public void testCounterExceptions() {
for (int i = 0; i < result.length; i++) { for (var value : result) {
assertEquals(expectedCounterExceptions, result[i].getExceptionList().size()); assertEquals(expectedCounterExceptions, value.getExceptionList().size());
} }
} }
} }

View File

@ -82,15 +82,18 @@ public final class RainbowFishSerializer {
* Read V1 RainbowFish from file. * Read V1 RainbowFish from file.
*/ */
public static RainbowFish readV1(String filename) throws IOException, ClassNotFoundException { public static RainbowFish readV1(String filename) throws IOException, ClassNotFoundException {
Map<String, String> map = null; Map<String, String> map;
try (var fileIn = new FileInputStream(filename); try (var fileIn = new FileInputStream(filename);
var objIn = new ObjectInputStream(fileIn)) { var objIn = new ObjectInputStream(fileIn)) {
map = (Map<String, String>) objIn.readObject(); map = (Map<String, String>) objIn.readObject();
} }
return new RainbowFish(map.get("name"), Integer.parseInt(map.get("age")), Integer return new RainbowFish(
.parseInt(map.get("lengthMeters")), map.get("name"),
Integer.parseInt(map.get("weightTons"))); Integer.parseInt(map.get("age")),
Integer.parseInt(map.get("lengthMeters")),
Integer.parseInt(map.get("weightTons"))
);
} }
} }

View File

@ -23,32 +23,28 @@
package com.iluwatar.tolerantreader; package com.iluwatar.tolerantreader;
import java.io.File;
import java.io.IOException;
import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import java.io.File;
import java.io.IOException;
/** /**
*
* Application test * Application test
*
*/ */
public class AppTest { public class AppTest {
@Test @Test
public void test() throws ClassNotFoundException, IOException { public void test() throws ClassNotFoundException, IOException {
String[] args = {}; App.main(new String[]{});
App.main(args);
} }
@BeforeEach @BeforeEach
@AfterEach @AfterEach
public void cleanup() { public void cleanup() {
File file1 = new File("fish1.out"); var file1 = new File("fish1.out");
file1.delete(); file1.delete();
File file2 = new File("fish2.out"); var file2 = new File("fish2.out");
file2.delete(); file2.delete();
} }
} }

View File

@ -23,16 +23,15 @@
package com.iluwatar.tolerantreader; 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.Rule;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.migrationsupport.rules.EnableRuleMigrationSupport; import org.junit.jupiter.migrationsupport.rules.EnableRuleMigrationSupport;
import org.junit.rules.TemporaryFolder; 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 * Date: 12/30/15 - 18:39 PM
* *
@ -62,10 +61,10 @@ public class RainbowFishSerializerTest {
*/ */
@Test @Test
public void testWriteV1ReadV1() throws Exception { public void testWriteV1ReadV1() throws Exception {
final File outputFile = this.testFolder.newFile(); final var outputFile = this.testFolder.newFile();
RainbowFishSerializer.writeV1(V1, outputFile.getPath()); RainbowFishSerializer.writeV1(V1, outputFile.getPath());
final RainbowFish fish = RainbowFishSerializer.readV1(outputFile.getPath()); final var fish = RainbowFishSerializer.readV1(outputFile.getPath());
assertNotSame(V1, fish); assertNotSame(V1, fish);
assertEquals(V1.getName(), fish.getName()); assertEquals(V1.getName(), fish.getName());
assertEquals(V1.getAge(), fish.getAge()); assertEquals(V1.getAge(), fish.getAge());
@ -79,10 +78,10 @@ public class RainbowFishSerializerTest {
*/ */
@Test @Test
public void testWriteV2ReadV1() throws Exception { public void testWriteV2ReadV1() throws Exception {
final File outputFile = this.testFolder.newFile(); final var outputFile = this.testFolder.newFile();
RainbowFishSerializer.writeV2(V2, outputFile.getPath()); RainbowFishSerializer.writeV2(V2, outputFile.getPath());
final RainbowFish fish = RainbowFishSerializer.readV1(outputFile.getPath()); final var fish = RainbowFishSerializer.readV1(outputFile.getPath());
assertNotSame(V2, fish); assertNotSame(V2, fish);
assertEquals(V2.getName(), fish.getName()); assertEquals(V2.getName(), fish.getName());
assertEquals(V2.getAge(), fish.getAge()); assertEquals(V2.getAge(), fish.getAge());

View File

@ -23,10 +23,10 @@
package com.iluwatar.tolerantreader; package com.iluwatar.tolerantreader;
import org.junit.Test;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import org.junit.Test;
/** /**
* Date: 12/30/15 - 18:34 PM * Date: 12/30/15 - 18:34 PM
* *
@ -39,7 +39,7 @@ public class RainbowFishTest {
*/ */
@Test @Test
public void testValues() { 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("name", fish.getName());
assertEquals(1, fish.getAge()); assertEquals(1, fish.getAge());
assertEquals(2, fish.getLengthMeters()); assertEquals(2, fish.getLengthMeters());

View File

@ -23,12 +23,12 @@
package com.iluwatar.tolerantreader; package com.iluwatar.tolerantreader;
import org.junit.Test;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.Test;
/** /**
* Date: 12/30/15 - 18:35 PM * Date: 12/30/15 - 18:35 PM
* *
@ -41,7 +41,7 @@ public class RainbowFishV2Test {
*/ */
@Test @Test
public void testValues() { 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("name", fish.getName());
assertEquals(1, fish.getAge()); assertEquals(1, fish.getAge());
assertEquals(2, fish.getLengthMeters()); assertEquals(2, fish.getLengthMeters());

View File

@ -99,13 +99,11 @@ public interface Trampoline<T> {
} }
T trampoline(final Trampoline<T> trampoline) { T trampoline(final Trampoline<T> trampoline) {
return Stream.iterate(trampoline, Trampoline::jump) return Stream.iterate(trampoline, Trampoline::jump)
.filter(Trampoline::complete) .filter(Trampoline::complete)
.findFirst() .findFirst()
.get() .map(Trampoline::result)
.result(); .orElseThrow();
} }
}; };
} }

View File

@ -40,7 +40,7 @@ public class TrampolineApp {
*/ */
public static void main(String[] args) { public static void main(String[] args) {
log.info("start pattern"); log.info("start pattern");
Integer result = loop(10, 1).result(); var result = loop(10, 1).result();
log.info("result {}", result); log.info("result {}", result);
} }

View File

@ -23,22 +23,20 @@
package com.iluwatar.trampoline; package com.iluwatar.trampoline;
import static org.junit.Assert.assertEquals;
import org.junit.Test; import org.junit.Test;
import java.io.IOException;
import static org.junit.Assert.*;
/** /**
* Test for trampoline pattern. * Test for trampoline pattern.
* */ */
public class TrampolineAppTest { public class TrampolineAppTest {
@Test @Test
public void testTrampolineWithFactorialFunction() { public void testTrampolineWithFactorialFunction() {
int result = TrampolineApp.loop(10, 1).result(); long result = TrampolineApp.loop(10, 1).result();
assertEquals("Be equal", 3628800, result); assertEquals("Be equal", 3628800, result);
} }

View File

@ -26,15 +26,12 @@ package com.iluwatar.twin;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
/** /**
*
* Application test * Application test
*
*/ */
public class AppTest { public class AppTest {
@Test @Test
public void test() throws Exception { public void test() throws Exception {
String[] args = {}; App.main(new String[]{});
App.main(args);
} }
} }

View File

@ -34,11 +34,10 @@ import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase; import ch.qos.logback.core.AppenderBase;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.stream.IntStream;
import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.mockito.InOrder;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
/** /**
@ -62,27 +61,26 @@ public class BallItemTest {
@Test @Test
public void testClick() { public void testClick() {
final BallThread ballThread = mock(BallThread.class); final var ballThread = mock(BallThread.class);
final BallItem ballItem = new BallItem(); final var ballItem = new BallItem();
ballItem.setTwin(ballThread); 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(); ballItem.click();
inOrder.verify(ballThread).suspendMe(); inOrder.verify(ballThread).suspendMe();
ballItem.click(); ballItem.click();
inOrder.verify(ballThread).resumeMe(); inOrder.verify(ballThread).resumeMe();
} });
inOrder.verifyNoMoreInteractions(); inOrder.verifyNoMoreInteractions();
} }
@Test @Test
public void testDoDraw() { public void testDoDraw() {
final BallItem ballItem = new BallItem(); final var ballItem = new BallItem();
final BallThread ballThread = mock(BallThread.class); final var ballThread = mock(BallThread.class);
ballItem.setTwin(ballThread); ballItem.setTwin(ballThread);
ballItem.draw(); ballItem.draw();
@ -95,8 +93,8 @@ public class BallItemTest {
@Test @Test
public void testMove() { public void testMove() {
final BallItem ballItem = new BallItem(); final var ballItem = new BallItem();
final BallThread ballThread = mock(BallThread.class); final var ballThread = mock(BallThread.class);
ballItem.setTwin(ballThread); ballItem.setTwin(ballThread);
ballItem.move(); ballItem.move();

View File

@ -23,15 +23,19 @@
package com.iluwatar.twin; package com.iluwatar.twin;
import org.junit.jupiter.api.Test;
import static java.lang.Thread.UncaughtExceptionHandler; import static java.lang.Thread.UncaughtExceptionHandler;
import static java.lang.Thread.sleep; import static java.lang.Thread.sleep;
import static java.time.Duration.ofMillis; import static java.time.Duration.ofMillis;
import static org.junit.jupiter.api.Assertions.assertTimeout; import static org.junit.jupiter.api.Assertions.assertTimeout;
import static org.mockito.Matchers.any; import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq; 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 * Date: 12/30/15 - 18:55 PM
@ -44,11 +48,11 @@ public class BallThreadTest {
* Verify if the {@link BallThread} can be resumed * Verify if the {@link BallThread} can be resumed
*/ */
@Test @Test
public void testSuspend() throws Exception { public void testSuspend() {
assertTimeout(ofMillis(5000), () -> { 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.setTwin(ballItem);
ballThread.start(); ballThread.start();
@ -72,9 +76,9 @@ public class BallThreadTest {
@Test @Test
public void testResume() { public void testResume() {
assertTimeout(ofMillis(5000), () -> { 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.setTwin(ballItem);
ballThread.suspendMe(); ballThread.suspendMe();
@ -102,8 +106,8 @@ public class BallThreadTest {
@Test @Test
public void testInterrupt() { public void testInterrupt() {
assertTimeout(ofMillis(5000), () -> { assertTimeout(ofMillis(5000), () -> {
final BallThread ballThread = new BallThread(); final var ballThread = new BallThread();
final UncaughtExceptionHandler exceptionHandler = mock(UncaughtExceptionHandler.class); final var exceptionHandler = mock(UncaughtExceptionHandler.class);
ballThread.setUncaughtExceptionHandler(exceptionHandler); ballThread.setUncaughtExceptionHandler(exceptionHandler);
ballThread.setTwin(mock(BallItem.class)); ballThread.setTwin(mock(BallItem.class));
ballThread.start(); ballThread.start();

View File

@ -25,6 +25,7 @@ package com.iluwatar.typeobject;
import com.iluwatar.typeobject.Candy.Type; import com.iluwatar.typeobject.Candy.Type;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -55,21 +56,17 @@ public class CandyGame {
} }
static String numOfSpaces(int num) { static String numOfSpaces(int num) {
String result = ""; return " ".repeat(Math.max(0, num));
for (var i = 0; i < num; i++) {
result += " ";
}
return result;
} }
void printGameStatus() { void printGameStatus() {
LOGGER.info(""); LOGGER.info("");
for (var i = 0; i < cells.length; i++) { for (Cell[] cell : cells) {
for (var j = 0; j < cells.length; j++) { 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) { if (candyName.length() < 20) {
var totalSpaces = 20 - candyName.length(); 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) + "|"); + numOfSpaces(totalSpaces - totalSpaces / 2) + "|");
} else { } else {
LOGGER.info(candyName + "|"); LOGGER.info(candyName + "|");
@ -80,8 +77,8 @@ public class CandyGame {
LOGGER.info(""); LOGGER.info("");
} }
ArrayList<Cell> adjacentCells(int y, int x) { List<Cell> adjacentCells(int y, int x) {
ArrayList<Cell> adjacent = new ArrayList<Cell>(); var adjacent = new ArrayList<Cell>();
if (y == 0) { if (y == 0) {
adjacent.add(this.cells[1][x]); adjacent.add(this.cells[1][x]);
} }
@ -115,8 +112,8 @@ public class CandyGame {
for (var j = 0; j < this.cells.length; j++) { for (var j = 0; j < this.cells.length; j++) {
if (!this.cells[i][j].candy.getType().equals(Type.rewardFruit)) { if (!this.cells[i][j].candy.getType().equals(Type.rewardFruit)) {
var adj = adjacentCells(i, j); var adj = adjacentCells(i, j);
for (var a = 0; a < adj.size(); a++) { for (Cell cell : adj) {
if (this.cells[i][j].candy.name.equals(adj.get(a).candy.name)) { if (this.cells[i][j].candy.name.equals(cell.candy.name)) {
return true; return true;
} }
} }
@ -157,11 +154,11 @@ public class CandyGame {
} }
} }
} }
for (var i = 0; i < this.cells.length; i++) { for (Cell[] cell : this.cells) {
var j = 0; var j = 0;
var points = 0; var points = 0;
while (j < cells.length - 1) { 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) { if (points != 0) {
handleChange(points); handleChange(points);
} else { } else {

View File

@ -27,6 +27,7 @@ import com.iluwatar.typeobject.Candy.Type;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List;
import java.util.Random; import java.util.Random;
import org.json.simple.parser.ParseException; import org.json.simple.parser.ParseException;
@ -38,12 +39,12 @@ import org.json.simple.parser.ParseException;
public class CellPool { public class CellPool {
private static final Random RANDOM = new Random(); private static final Random RANDOM = new Random();
ArrayList<Cell> pool; List<Cell> pool;
int pointer; int pointer;
Candy[] randomCode; Candy[] randomCode;
CellPool(int num) { CellPool(int num) {
this.pool = new ArrayList<Cell>(num); this.pool = new ArrayList<>(num);
try { try {
this.randomCode = assignRandomCandytypes(); this.randomCode = assignRandomCandytypes();
} catch (Exception e) { } catch (Exception e) {

View File

@ -25,11 +25,11 @@ package com.iluwatar.typeobject;
import com.iluwatar.typeobject.Candy.Type; import com.iluwatar.typeobject.Candy.Type;
import java.io.File; import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader; import java.io.FileReader;
import java.io.IOException; import java.io.IOException;
import java.util.Enumeration;
import java.util.Hashtable; import java.util.Hashtable;
import java.util.List;
import java.util.stream.Collectors;
import org.json.simple.JSONArray; import org.json.simple.JSONArray;
import org.json.simple.JSONObject; import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser; import org.json.simple.parser.JSONParser;
@ -43,24 +43,24 @@ public class JsonParser {
Hashtable<String, Candy> candies; Hashtable<String, Candy> candies;
JsonParser() { JsonParser() {
this.candies = new Hashtable<String, Candy>(); this.candies = new Hashtable<>();
} }
void parse() throws FileNotFoundException, IOException, ParseException { void parse() throws IOException, ParseException {
var parser = new JSONParser(); var parser = new JSONParser();
var jo = (JSONObject) parser.parse(new FileReader(new File("").getAbsolutePath() var workingDirectory = new File("").getAbsolutePath();
+ "\\src\\main\\java\\com\\iluwatar\\typeobject\\candy.json")); 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"); var a = (JSONArray) jo.get("candies");
for (var o : a) { for (var o : a) {
var candy = (JSONObject) o; var candy = (JSONObject) o;
var name = (String) candy.get("name"); var name = (String) candy.get("name");
var parentName = (String) candy.get("parent"); var parentName = (String) candy.get("parent");
var t = (String) candy.get("type"); var t = (String) candy.get("type");
Type type = null; var type = Type.crushableCandy;
if (t.equals("rewardFruit")) { if (t.equals("rewardFruit")) {
type = Type.rewardFruit; type = Type.rewardFruit;
} else {
type = Type.crushableCandy;
} }
var points = Integer.parseInt((String) candy.get("points")); var points = Integer.parseInt((String) candy.get("points"));
var c = new Candy(name, parentName, type, points); var c = new Candy(name, parentName, type, points);
@ -70,7 +70,7 @@ public class JsonParser {
} }
void setParentAndPoints() { void setParentAndPoints() {
for (Enumeration<String> e = this.candies.keys(); e.hasMoreElements(); ) { for (var e = this.candies.keys(); e.hasMoreElements(); ) {
var c = this.candies.get(e.nextElement()); var c = this.candies.get(e.nextElement());
if (c.parentName == null) { if (c.parentName == null) {
c.parent = null; c.parent = null;

View File

@ -23,10 +23,10 @@
package com.iluwatar.typeobject; package com.iluwatar.typeobject;
import static org.junit.jupiter.api.Assertions.*; import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import com.iluwatar.typeobject.Candy.Type; import com.iluwatar.typeobject.Candy.Type;
import org.junit.jupiter.api.Test;
/** /**
* The CandyGameTest class tests the methods in the {@link CandyGame} class. * The CandyGameTest class tests the methods in the {@link CandyGame} class.
@ -36,7 +36,7 @@ class CandyGameTest {
@Test @Test
void adjacentCellsTest() { 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 arr1 = cg.adjacentCells(0, 0);
var arr2 = cg.adjacentCells(1, 2); var arr2 = cg.adjacentCells(1, 2);
var arr3 = cg.adjacentCells(1, 1); var arr3 = cg.adjacentCells(1, 1);
@ -49,19 +49,19 @@ class CandyGameTest {
var c1 = new Candy("green jelly", "jelly", Type.crushableCandy, 5); var c1 = new Candy("green jelly", "jelly", Type.crushableCandy, 5);
var c2 = new Candy("purple 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); var c3 = new Candy("green apple", "apple", Type.rewardFruit, 10);
matrix[0][0] = new Cell(c1,0,0);; matrix[0][0] = new Cell(c1, 0, 0);
matrix[0][1] = new Cell(c2,1,0); matrix[0][1] = new Cell(c2, 1, 0);
matrix[1][0] = new Cell(c3,0,1); matrix[1][0] = new Cell(c3, 0, 1);
matrix[1][1] = new Cell(c2,1,1); matrix[1][1] = new Cell(c2, 1, 1);
var p = new CellPool(4); var p = new CellPool(4);
var cg = new CandyGame(2,p); var cg = new CandyGame(2, p);
cg.cells = matrix; cg.cells = matrix;
var fruitInLastRow = cg.continueRound(); var fruitInLastRow = cg.continueRound();
matrix[1][0].crush(p, matrix); matrix[1][0].crush(p, matrix);
matrix[0][0] = new Cell(c3,0,0); matrix[0][0] = new Cell(c3, 0, 0);
var matchingCandy = cg.continueRound(); var matchingCandy = cg.continueRound();
matrix[0][1].crush(p,matrix); matrix[0][1].crush(p, matrix);
matrix[0][1] = new Cell(c3,1,0); matrix[0][1] = new Cell(c3, 1, 0);
var noneLeft = cg.continueRound(); var noneLeft = cg.continueRound();
assertTrue(fruitInLastRow && matchingCandy && !noneLeft); assertTrue(fruitInLastRow && matchingCandy && !noneLeft);
} }

View File

@ -23,9 +23,10 @@
package com.iluwatar.typeobject; package com.iluwatar.typeobject;
import static org.junit.jupiter.api.Assertions.*; import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
import java.util.Hashtable; import java.util.Hashtable;
import org.junit.jupiter.api.Test;
/** /**
* The CellPoolTest class tests the methods in the {@link CellPool} class. * The CellPoolTest class tests the methods in the {@link CellPool} class.
@ -39,9 +40,7 @@ class CellPoolTest {
var ht = new Hashtable<String, Boolean>(); var ht = new Hashtable<String, Boolean>();
var parentTypes = 0; var parentTypes = 0;
for (var i = 0; i < cp.randomCode.length; i++) { for (var i = 0; i < cp.randomCode.length; i++) {
if (ht.get(cp.randomCode[i].name) == null) { ht.putIfAbsent(cp.randomCode[i].name, true);
ht.put(cp.randomCode[i].name, true);
}
if (cp.randomCode[i].name.equals("fruit") || cp.randomCode[i].name.equals("candy")) { if (cp.randomCode[i].name.equals("fruit") || cp.randomCode[i].name.equals("candy")) {
parentTypes++; parentTypes++;
} }

View File

@ -23,14 +23,15 @@
package com.iluwatar.typeobject; package com.iluwatar.typeobject;
import static org.junit.jupiter.api.Assertions.*; import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertTrue;
import com.iluwatar.typeobject.Candy.Type; import com.iluwatar.typeobject.Candy.Type;
import org.junit.jupiter.api.Test;
/** /**
* The CellTest class tests the methods in the {@link Cell} class. * The CellTest class tests the methods in the {@link Cell} class.
*/ */
class CellTest { class CellTest {
@Test @Test
@ -38,10 +39,10 @@ class CellTest {
var c1 = new Candy("green jelly", "jelly", Type.crushableCandy, 5); var c1 = new Candy("green jelly", "jelly", Type.crushableCandy, 5);
var c2 = new Candy("green apple", "apple", Type.rewardFruit, 10); var c2 = new Candy("green apple", "apple", Type.rewardFruit, 10);
var matrix = new Cell[4][4]; var matrix = new Cell[4][4];
matrix[0][0] = new Cell(c1,0,0); matrix[0][0] = new Cell(c1, 0, 0);
matrix[0][1] = new Cell(c1,1,0); matrix[0][1] = new Cell(c1, 1, 0);
matrix[0][2] = new Cell(c2,2,0); matrix[0][2] = new Cell(c2, 2, 0);
matrix[0][3] = new Cell(c1,3,0); matrix[0][3] = new Cell(c1, 3, 0);
var cp = new CellPool(5); var cp = new CellPool(5);
var points1 = matrix[0][0].interact(matrix[0][1], cp, matrix); var points1 = matrix[0][0].interact(matrix[0][1], cp, matrix);
var points2 = matrix[0][2].interact(matrix[0][3], cp, matrix); var points2 = matrix[0][2].interact(matrix[0][3], cp, matrix);
@ -53,9 +54,9 @@ class CellTest {
var c1 = new Candy("green jelly", "jelly", Type.crushableCandy, 5); var c1 = new Candy("green jelly", "jelly", Type.crushableCandy, 5);
var c2 = new Candy("purple candy", "candy", Type.crushableCandy, 5); var c2 = new Candy("purple candy", "candy", Type.crushableCandy, 5);
var matrix = new Cell[4][4]; var matrix = new Cell[4][4];
matrix[0][0] = new Cell(c1,0,0); matrix[0][0] = new Cell(c1, 0, 0);
matrix[1][0] = new Cell(c2,0,1); matrix[1][0] = new Cell(c2, 0, 1);
matrix[1][0].crush(new CellPool(5), matrix); 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);
} }
} }

View File

@ -25,15 +25,12 @@ package com.iluwatar.unitofwork;
import org.junit.Test; import org.junit.Test;
import java.io.IOException;
/** /**
* AppTest * AppTest
*/ */
public class AppTest { public class AppTest {
@Test @Test
public void test() { public void test() {
String[] args = {}; App.main(new String[]{});
App.main(args);
} }
} }

View File

@ -23,20 +23,22 @@
package com.iluwatar.unitofwork; 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.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner; 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} * tests {@link StudentRepository}
*/ */
@ -51,7 +53,7 @@ public class StudentRepositoryTest {
private StudentRepository studentRepository; private StudentRepository studentRepository;
@Before @Before
public void setUp() throws Exception { public void setUp() {
context = new HashMap<>(); context = new HashMap<>();
studentRepository = new StudentRepository(context, studentDatabase); studentRepository = new StudentRepository(context, studentDatabase);
} }
@ -85,9 +87,9 @@ public class StudentRepositoryTest {
@Test @Test
public void shouldSaveAllLocalChangesToDb() { public void shouldSaveAllLocalChangesToDb() {
context.put(IUnitOfWork.INSERT, Collections.singletonList(student1)); context.put(IUnitOfWork.INSERT, List.of(student1));
context.put(IUnitOfWork.MODIFY, Collections.singletonList(student1)); context.put(IUnitOfWork.MODIFY, List.of(student1));
context.put(IUnitOfWork.DELETE, Collections.singletonList(student1)); context.put(IUnitOfWork.DELETE, List.of(student1));
studentRepository.commit(); studentRepository.commit();
@ -116,8 +118,8 @@ public class StudentRepositoryTest {
@Test @Test
public void shouldNotInsertToDbIfNoRegisteredStudentsToBeCommitted() { public void shouldNotInsertToDbIfNoRegisteredStudentsToBeCommitted() {
context.put(IUnitOfWork.MODIFY, Collections.singletonList(student1)); context.put(IUnitOfWork.MODIFY, List.of(student1));
context.put(IUnitOfWork.DELETE, Collections.singletonList(student1)); context.put(IUnitOfWork.DELETE, List.of(student1));
studentRepository.commit(); studentRepository.commit();
@ -126,8 +128,8 @@ public class StudentRepositoryTest {
@Test @Test
public void shouldNotModifyToDbIfNotRegisteredStudentsToBeCommitted() { public void shouldNotModifyToDbIfNotRegisteredStudentsToBeCommitted() {
context.put(IUnitOfWork.INSERT, Collections.singletonList(student1)); context.put(IUnitOfWork.INSERT, List.of(student1));
context.put(IUnitOfWork.DELETE, Collections.singletonList(student1)); context.put(IUnitOfWork.DELETE, List.of(student1));
studentRepository.commit(); studentRepository.commit();
@ -136,8 +138,8 @@ public class StudentRepositoryTest {
@Test @Test
public void shouldNotDeleteFromDbIfNotRegisteredStudentsToBeCommitted() { public void shouldNotDeleteFromDbIfNotRegisteredStudentsToBeCommitted() {
context.put(IUnitOfWork.INSERT, Collections.singletonList(student1)); context.put(IUnitOfWork.INSERT, List.of(student1));
context.put(IUnitOfWork.MODIFY, Collections.singletonList(student1)); context.put(IUnitOfWork.MODIFY, List.of(student1));
studentRepository.commit(); studentRepository.commit();

View File

@ -32,7 +32,6 @@ public class AppTest {
@Test @Test
public void test() { public void test() {
String[] args = {}; App.main(new String[]{});
App.main(args);
} }
} }

View File

@ -23,13 +23,13 @@
package com.iluwatar.value.object; 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.is;
import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.CoreMatchers.not;
import static org.junit.Assert.assertThat; import static org.junit.Assert.assertThat;
import com.google.common.testing.EqualsTester;
import org.junit.jupiter.api.Test;
/** /**
* Unit test for HeroStat. * Unit test for HeroStat.
*/ */
@ -37,12 +37,10 @@ public class HeroStatTest {
/** /**
* Tester for equals() and hashCode() methods of a class. Using guava's EqualsTester. * Tester for equals() and hashCode() methods of a class. Using guava's EqualsTester.
* *
* @see <a href="http://static.javadoc.io/com.google.guava/guava-testlib/19.0/com/google/common/testing/EqualsTester.html"> * @see <a href="http://static.javadoc.io/com.google.guava/guava-testlib/19.0/com/google/common/testing/EqualsTester.html">
* http://static.javadoc.io/com.google.guava/guava-testlib/19.0/com/google/common/testing/EqualsTester.html * http://static.javadoc.io/com.google.guava/guava-testlib/19.0/com/google/common/testing/EqualsTester.html
* </a> * </a>
*
*
*/ */
@Test @Test
public void testEquals() { public void testEquals() {

View File

@ -28,22 +28,22 @@ package com.iluwatar.visitor;
* can be added without altering the node interface.</p> * can be added without altering the node interface.</p>
* *
* <p>In this example there is a unit hierarchy beginning from {@link Commander}. This hierarchy is * <p>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, * traversed by visitors. {@link SoldierVisitor} applies its operation on {@link Soldier}s, {@link
* {@link SergeantVisitor} on {@link Sergeant}s and so on.</p> * SergeantVisitor} on {@link Sergeant}s and so on.</p>
*
*/ */
public class App { public class App {
/** /**
* Program entry point. * Program entry point.
* *
* @param args command line args * @param args command line args
*/ */
public static void main(String[] args) { public static void main(String[] args) {
var commander = var commander = new Commander(
new Commander(new Sergeant(new Soldier(), new Soldier(), new Soldier()), new Sergeant( new Sergeant(new Soldier(), new Soldier(), new Soldier()),
new Soldier(), new Soldier(), new Soldier())); new Sergeant(new Soldier(), new Soldier(), new Soldier())
);
commander.accept(new SoldierVisitor()); commander.accept(new SoldierVisitor());
commander.accept(new SergeantVisitor()); commander.accept(new SergeantVisitor());
commander.accept(new CommanderVisitor()); commander.accept(new CommanderVisitor());

View File

@ -23,6 +23,8 @@
package com.iluwatar.visitor; package com.iluwatar.visitor;
import java.util.Arrays;
/** /**
* Interface for the nodes in hierarchy. * Interface for the nodes in hierarchy.
*/ */
@ -38,8 +40,6 @@ public abstract class Unit {
* Accept visitor. * Accept visitor.
*/ */
public void accept(UnitVisitor visitor) { public void accept(UnitVisitor visitor) {
for (var child : children) { Arrays.stream(children).forEach(child -> child.accept(visitor));
child.accept(visitor);
}
} }
} }

View File

@ -32,7 +32,6 @@ public class AppTest {
@Test @Test
public void test() { public void test() {
String[] args = {}; App.main(new String[]{});
App.main(args);
} }
} }

View File

@ -30,12 +30,11 @@ import static org.mockito.Mockito.verifyNoMoreInteractions;
import java.util.Arrays; import java.util.Arrays;
import java.util.function.Function; import java.util.function.Function;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
/** /**
* Date: 12/30/15 - 18:59 PM. * Date: 12/30/15 - 18:59 PM. Test related to Units
* Test related to Units *
* @param <U> Type of Unit * @param <U> Type of Unit
* @author Jeroen Meulemeester * @author Jeroen Meulemeester
*/ */
@ -65,9 +64,7 @@ public abstract class UnitTest<U extends Unit> {
unit.accept(visitor); unit.accept(visitor);
verifyVisit(unit, visitor); verifyVisit(unit, visitor);
for (final var child : children) { Arrays.stream(children).forEach(child -> verify(child).accept(eq(visitor)));
verify(child).accept(eq(visitor));
}
verifyNoMoreInteractions(children); verifyNoMoreInteractions(children);
verifyNoMoreInteractions(visitor); verifyNoMoreInteractions(visitor);

View File

@ -31,15 +31,14 @@ import ch.qos.logback.core.AppenderBase;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
/** /**
* Date: 12/30/15 - 18:59 PM. * Date: 12/30/15 - 18:59 PM. Test case for Visitor Pattern
* Test case for Visitor Pattern *
* @param <V> Type of UnitVisitor * @param <V> Type of UnitVisitor
* @author Jeroen Meulemeester * @author Jeroen Meulemeester
*/ */
@ -84,11 +83,12 @@ public abstract class VisitorTest<V extends UnitVisitor> {
* @param sergeantResponse The optional expected response when being visited by a sergeant * @param sergeantResponse The optional expected response when being visited by a sergeant
* @param soldierResponse The optional expected response when being visited by a soldier * @param soldierResponse The optional expected response when being visited by a soldier
*/ */
public VisitorTest(final V visitor, public VisitorTest(
final Optional<String> commanderResponse, final V visitor,
final Optional<String> sergeantResponse, final Optional<String> commanderResponse,
final Optional<String> soldierResponse) { final Optional<String> sergeantResponse,
final Optional<String> soldierResponse
) {
this.visitor = visitor; this.visitor = visitor;
this.commanderResponse = commanderResponse; this.commanderResponse = commanderResponse;
this.sergeantResponse = sergeantResponse; this.sergeantResponse = sergeantResponse;