From ef42e169b961d4715e8fccaa44073769831d6ecb Mon Sep 17 00:00:00 2001 From: k1w1dev Date: Sat, 4 May 2024 17:20:01 +1200 Subject: [PATCH] fix: Fix sonar issues (#2925) * Remove unused member which was also causing a false positive sonar issue. Fixes sonar issue https://sonarcloud.io/project/issues?open=AY3gHwu5DIZTZkppqVEG&id=iluwatar_java-design-patterns * Fixes sonar issue https://sonarcloud.io/project/issues?open=AXK0OzDA-CiGJS70dLki&id=iluwatar_java-design-patterns related to "Refactor the code of the lambda to not have multiple invocations throwing the same checked exception." Also, updated the code to use Instant and Duration to deal with time instead of int. Added the awaitility library to perform assertions in test which is more reliable than using Thread.sleep directly to wait for events to happen. * checkstyle fix * Add sneaky throws to fix sonar lint issue. This is fine as the newFile method is not being tested but instead the new SimpleFileWriter(...) is. * The first booking needs to happen outside the assertions. Fixed other warnings * Use records to pass around related objects instead of using a large number of individual params, which sonar did not like. * Checkstyle fixes * checkstyle fixes * Remove complexity to keep sonar happy. * Split into different methods to reduce complexity. Could be broken down even further but currently Sonar is happy. * Move files to correct package * Add valid assertions to tests * rename constants to avoid confusion * Sonar warning related to cognitive complexity can be suppressed as the methods are quite generic and not functional enough to be separated out. * Use constants to keep Sonar happy * Use correct constant naming conventions * Use correct constant naming conventions * Use lombok to define noargsconstructor * Use a single method to do the logging * Remove unused constructor and redundant method * Use a reusable method for logging --- .../commander/AppEmployeeDbFailCases.java | 25 +- .../commander/AppMessagingFailCases.java | 39 +-- .../commander/AppPaymentFailCases.java | 31 +- .../iluwatar/commander/AppQueueFailCases.java | 38 +-- .../commander/AppShippingFailCases.java | 37 +-- .../com/iluwatar/commander/Commander.java | 296 ++++++++++-------- .../com/iluwatar/commander/RetryParams.java | 10 + .../com/iluwatar/commander/TimeLimits.java | 16 + .../iluwatar/commander/queue/QueueTask.java | 6 +- .../com/iluwatar/commander/CommanderTest.java | 97 ++++-- .../iluwatar/compositeview/AppServlet.java | 8 +- .../java/com/iluwatar/context/object/App.java | 13 +- .../datatransfer/product/ProductResource.java | 20 +- .../doubledispatch/SpaceStationMir.java | 16 +- .../java/com/iluwatar/embedded/value/App.java | 12 +- .../iluwatar/embedded/value/DataSource.java | 8 +- .../com/iluwatar/embedded/value/AppTest.java | 6 +- event-based-asynchronous/pom.xml | 8 +- .../com/iluwatar/event/asynchronous/App.java | 9 +- .../event/asynchronous/AsyncEvent.java | 18 +- .../event/asynchronous/EventManager.java | 17 +- .../asynchronous/EventAsynchronousTest.java | 157 ++++------ .../execute/around/SimpleFileWriterTest.java | 14 +- .../health/check/CpuHealthIndicator.java | 9 +- .../view/intent/CalculatorViewModel.java | 15 +- .../actions/AdditionCalculatorAction.java | 6 +- .../actions/DivisionCalculatorAction.java | 6 +- .../MultiplicationCalculatorAction.java | 6 +- .../actions/SetVariableCalculatorAction.java | 6 +- .../actions/SubtractionCalculatorAction.java | 6 +- .../view/intent/CalculatorViewModelTest.java | 24 +- .../iluwatar/page/controller}/App.java | 0 .../page/controller}/SignupController.java | 0 .../page/controller}/SignupModel.java | 12 +- .../iluwatar/page/controller}/SignupView.java | 6 +- .../page/controller}/UserController.java | 6 +- .../iluwatar/page/controller}/UserModel.java | 13 +- .../iluwatar/page/controller}/UserView.java | 0 .../roleobject/ApplicationRoleObject.java | 20 +- .../java/com/iluwatar/roleobject/Role.java | 4 +- .../iluwatar/roleobject/CustomerCoreTest.java | 32 +- .../com/iluwatar/roleobject/RoleTest.java | 2 +- .../main/java/com/iluwatar/strategy/App.java | 8 +- .../com/iluwatar/strategy/LambdaStrategy.java | 8 +- .../iluwatar/transactionscript/HotelTest.java | 32 +- .../com/iluwatar/typeobject/CandyGame.java | 3 +- 46 files changed, 571 insertions(+), 554 deletions(-) create mode 100644 commander/src/main/java/com/iluwatar/commander/RetryParams.java create mode 100644 commander/src/main/java/com/iluwatar/commander/TimeLimits.java rename page-controller/src/main/java/{com.iluwatar.page.controller => com/iluwatar/page/controller}/App.java (100%) rename page-controller/src/main/java/{com.iluwatar.page.controller => com/iluwatar/page/controller}/SignupController.java (100%) rename page-controller/src/main/java/{com.iluwatar.page.controller => com/iluwatar/page/controller}/SignupModel.java (94%) rename page-controller/src/main/java/{com.iluwatar.page.controller => com/iluwatar/page/controller}/SignupView.java (97%) rename page-controller/src/main/java/{com.iluwatar.page.controller => com/iluwatar/page/controller}/UserController.java (97%) rename page-controller/src/main/java/{com.iluwatar.page.controller => com/iluwatar/page/controller}/UserModel.java (94%) rename page-controller/src/main/java/{com.iluwatar.page.controller => com/iluwatar/page/controller}/UserView.java (100%) diff --git a/commander/src/main/java/com/iluwatar/commander/AppEmployeeDbFailCases.java b/commander/src/main/java/com/iluwatar/commander/AppEmployeeDbFailCases.java index 8d633a6d3..a4b9d4ab6 100644 --- a/commander/src/main/java/com/iluwatar/commander/AppEmployeeDbFailCases.java +++ b/commander/src/main/java/com/iluwatar/commander/AppEmployeeDbFailCases.java @@ -41,15 +41,11 @@ import com.iluwatar.commander.shippingservice.ShippingService; * available/unavailable. */ public class AppEmployeeDbFailCases { - private final int numOfRetries = 3; - private final long retryDuration = 30000; - private final long queueTime = 240000; //4 mins - private final long queueTaskTime = 60000; //1 min - private final long paymentTime = 120000; //2 mins - private final long messageTime = 150000; //2.5 mins - private final long employeeTime = 240000; //4 mins + private static final RetryParams retryParams = RetryParams.DEFAULT; - void employeeDatabaseUnavailableCase() throws Exception { + private static final TimeLimits timeLimits = TimeLimits.DEFAULT; + + void employeeDatabaseUnavailableCase() { var ps = new PaymentService(new PaymentDatabase(), new DatabaseUnavailableException(), new DatabaseUnavailableException(), new DatabaseUnavailableException(), new DatabaseUnavailableException(), new DatabaseUnavailableException(), @@ -64,22 +60,20 @@ public class AppEmployeeDbFailCases { new QueueDatabase(new DatabaseUnavailableException(), new DatabaseUnavailableException(), new DatabaseUnavailableException(), new DatabaseUnavailableException(), new DatabaseUnavailableException(), new DatabaseUnavailableException()); - var c = new Commander(eh, ps, ss, ms, qdb, numOfRetries, retryDuration, - queueTime, queueTaskTime, paymentTime, messageTime, employeeTime); + var c = new Commander(eh, ps, ss, ms, qdb, retryParams, timeLimits); var user = new User("Jim", "ABCD"); var order = new Order(user, "book", 10f); c.placeOrder(order); } - void employeeDbSuccessCase() throws Exception { + void employeeDbSuccessCase() { var ps = new PaymentService(new PaymentDatabase()); var ss = new ShippingService(new ShippingDatabase(), new ItemUnavailableException()); var ms = new MessagingService(new MessagingDatabase()); var eh = new EmployeeHandle(new EmployeeDatabase(), new DatabaseUnavailableException(), new DatabaseUnavailableException()); var qdb = new QueueDatabase(); - var c = new Commander(eh, ps, ss, ms, qdb, numOfRetries, retryDuration, - queueTime, queueTaskTime, paymentTime, messageTime, employeeTime); + var c = new Commander(eh, ps, ss, ms, qdb, retryParams, timeLimits); var user = new User("Jim", "ABCD"); var order = new Order(user, "book", 10f); c.placeOrder(order); @@ -91,9 +85,8 @@ public class AppEmployeeDbFailCases { * @param args command line args */ - public static void main(String[] args) throws Exception { + public static void main(String[] args) { var aefc = new AppEmployeeDbFailCases(); - //aefc.employeeDatabaseUnavailableCase(); aefc.employeeDbSuccessCase(); } -} +} \ No newline at end of file diff --git a/commander/src/main/java/com/iluwatar/commander/AppMessagingFailCases.java b/commander/src/main/java/com/iluwatar/commander/AppMessagingFailCases.java index 69c4cede9..f7c58e0ae 100644 --- a/commander/src/main/java/com/iluwatar/commander/AppMessagingFailCases.java +++ b/commander/src/main/java/com/iluwatar/commander/AppMessagingFailCases.java @@ -41,15 +41,12 @@ import com.iluwatar.commander.shippingservice.ShippingService; */ public class AppMessagingFailCases { - private final int numOfRetries = 3; - private final long retryDuration = 30000; - private final long queueTime = 240000; //4 mins - private final long queueTaskTime = 60000; //1 min - private final long paymentTime = 120000; //2 mins - private final long messageTime = 150000; //2.5 mins - private final long employeeTime = 240000; //4 mins + private static final RetryParams retryParams = RetryParams.DEFAULT; - void messagingDatabaseUnavailableCasePaymentSuccess() throws Exception { + private static final TimeLimits timeLimits = TimeLimits.DEFAULT; + + + void messagingDatabaseUnavailableCasePaymentSuccess() { //rest is successful var ps = new PaymentService(new PaymentDatabase()); var ss = new ShippingService(new ShippingDatabase()); @@ -59,14 +56,13 @@ public class AppMessagingFailCases { new DatabaseUnavailableException()); var eh = new EmployeeHandle(new EmployeeDatabase()); var qdb = new QueueDatabase(); - var c = new Commander(eh, ps, ss, ms, qdb, numOfRetries, retryDuration, - queueTime, queueTaskTime, paymentTime, messageTime, employeeTime); + var c = new Commander(eh, ps, ss, ms, qdb, retryParams, timeLimits); var user = new User("Jim", "ABCD"); var order = new Order(user, "book", 10f); c.placeOrder(order); } - void messagingDatabaseUnavailableCasePaymentError() throws Exception { + void messagingDatabaseUnavailableCasePaymentError() { //rest is successful var ps = new PaymentService(new PaymentDatabase(), new DatabaseUnavailableException(), new DatabaseUnavailableException(), new DatabaseUnavailableException(), @@ -84,14 +80,13 @@ public class AppMessagingFailCases { new DatabaseUnavailableException()); var eh = new EmployeeHandle(new EmployeeDatabase()); var qdb = new QueueDatabase(); - var c = new Commander(eh, ps, ss, ms, qdb, numOfRetries, retryDuration, - queueTime, queueTaskTime, paymentTime, messageTime, employeeTime); + var c = new Commander(eh, ps, ss, ms, qdb, retryParams, timeLimits); var user = new User("Jim", "ABCD"); var order = new Order(user, "book", 10f); c.placeOrder(order); } - void messagingDatabaseUnavailableCasePaymentFailure() throws Exception { + void messagingDatabaseUnavailableCasePaymentFailure() { //rest is successful var ps = new PaymentService(new PaymentDatabase(), new DatabaseUnavailableException(), new DatabaseUnavailableException(), new DatabaseUnavailableException(), @@ -107,15 +102,13 @@ public class AppMessagingFailCases { new QueueDatabase(new DatabaseUnavailableException(), new DatabaseUnavailableException(), new DatabaseUnavailableException(), new DatabaseUnavailableException(), new DatabaseUnavailableException(), new DatabaseUnavailableException()); - var c = - new Commander(eh, ps, ss, ms, qdb, numOfRetries, retryDuration, queueTime, queueTaskTime, - paymentTime, messageTime, employeeTime); + var c = new Commander(eh, ps, ss, ms, qdb, retryParams, timeLimits); var user = new User("Jim", "ABCD"); var order = new Order(user, "book", 10f); c.placeOrder(order); } - void messagingSuccessCase() throws Exception { + void messagingSuccessCase() { //done here var ps = new PaymentService(new PaymentDatabase(), new DatabaseUnavailableException(), new DatabaseUnavailableException(), new DatabaseUnavailableException(), @@ -126,8 +119,7 @@ public class AppMessagingFailCases { new DatabaseUnavailableException()); var eh = new EmployeeHandle(new EmployeeDatabase()); var qdb = new QueueDatabase(); - var c = new Commander(eh, ps, ss, ms, qdb, numOfRetries, retryDuration, - queueTime, queueTaskTime, paymentTime, messageTime, employeeTime); + var c = new Commander(eh, ps, ss, ms, qdb, retryParams, timeLimits); var user = new User("Jim", "ABCD"); var order = new Order(user, "book", 10f); c.placeOrder(order); @@ -139,11 +131,8 @@ public class AppMessagingFailCases { * @param args command line args */ - public static void main(String[] args) throws Exception { + public static void main(String[] args) { var amfc = new AppMessagingFailCases(); - //amfc.messagingDatabaseUnavailableCasePaymentSuccess(); - //amfc.messagingDatabaseUnavailableCasePaymentError(); - //amfc.messagingDatabaseUnavailableCasePaymentFailure(); amfc.messagingSuccessCase(); } -} +} \ No newline at end of file diff --git a/commander/src/main/java/com/iluwatar/commander/AppPaymentFailCases.java b/commander/src/main/java/com/iluwatar/commander/AppPaymentFailCases.java index be133ccdc..02c7db04b 100644 --- a/commander/src/main/java/com/iluwatar/commander/AppPaymentFailCases.java +++ b/commander/src/main/java/com/iluwatar/commander/AppPaymentFailCases.java @@ -41,29 +41,24 @@ import com.iluwatar.commander.shippingservice.ShippingService; */ public class AppPaymentFailCases { - private final int numOfRetries = 3; - private final long retryDuration = 30000; - private final long queueTime = 240000; //4 mins - private final long queueTaskTime = 60000; //1 min - private final long paymentTime = 120000; //2 mins - private final long messageTime = 150000; //2.5 mins - private final long employeeTime = 240000; //4 mins + private static final RetryParams retryParams = RetryParams.DEFAULT; - void paymentNotPossibleCase() throws Exception { + private static final TimeLimits timeLimits = TimeLimits.DEFAULT; + + void paymentNotPossibleCase() { var ps = new PaymentService(new PaymentDatabase(), new DatabaseUnavailableException(), new PaymentDetailsErrorException()); var ss = new ShippingService(new ShippingDatabase()); var ms = new MessagingService(new MessagingDatabase(), new DatabaseUnavailableException()); var eh = new EmployeeHandle(new EmployeeDatabase()); var qdb = new QueueDatabase(new DatabaseUnavailableException()); - var c = new Commander(eh, ps, ss, ms, qdb, numOfRetries, retryDuration, - queueTime, queueTaskTime, paymentTime, messageTime, employeeTime); + var c = new Commander(eh, ps, ss, ms, qdb, retryParams, timeLimits); var user = new User("Jim", "ABCD"); var order = new Order(user, "book", 10f); c.placeOrder(order); } - void paymentDatabaseUnavailableCase() throws Exception { + void paymentDatabaseUnavailableCase() { //rest is successful var ps = new PaymentService(new PaymentDatabase(), new DatabaseUnavailableException(), new DatabaseUnavailableException(), new DatabaseUnavailableException(), @@ -73,14 +68,13 @@ public class AppPaymentFailCases { var ms = new MessagingService(new MessagingDatabase()); var eh = new EmployeeHandle(new EmployeeDatabase()); var qdb = new QueueDatabase(); - var c = new Commander(eh, ps, ss, ms, qdb, numOfRetries, retryDuration, - queueTime, queueTaskTime, paymentTime, messageTime, employeeTime); + var c = new Commander(eh, ps, ss, ms, qdb, retryParams, timeLimits); var user = new User("Jim", "ABCD"); var order = new Order(user, "book", 10f); c.placeOrder(order); } - void paymentSuccessCase() throws Exception { + void paymentSuccessCase() { //goes to message after 2 retries maybe - rest is successful for now var ps = new PaymentService(new PaymentDatabase(), new DatabaseUnavailableException(), new DatabaseUnavailableException()); @@ -89,8 +83,7 @@ public class AppPaymentFailCases { new MessagingService(new MessagingDatabase(), new DatabaseUnavailableException()); var eh = new EmployeeHandle(new EmployeeDatabase()); var qdb = new QueueDatabase(new DatabaseUnavailableException()); - var c = new Commander(eh, ps, ss, ms, qdb, numOfRetries, retryDuration, - queueTime, queueTaskTime, paymentTime, messageTime, employeeTime); + var c = new Commander(eh, ps, ss, ms, qdb, retryParams, timeLimits); var user = new User("Jim", "ABCD"); var order = new Order(user, "book", 10f); c.placeOrder(order); @@ -102,10 +95,8 @@ public class AppPaymentFailCases { * @param args command line args */ - public static void main(String[] args) throws Exception { + public static void main(String[] args) { var apfc = new AppPaymentFailCases(); - //apfc.paymentNotPossibleCase(); - //apfc.paymentDatabaseUnavailableCase(); apfc.paymentSuccessCase(); } -} +} \ No newline at end of file diff --git a/commander/src/main/java/com/iluwatar/commander/AppQueueFailCases.java b/commander/src/main/java/com/iluwatar/commander/AppQueueFailCases.java index 08f0fc218..b53793d82 100644 --- a/commander/src/main/java/com/iluwatar/commander/AppQueueFailCases.java +++ b/commander/src/main/java/com/iluwatar/commander/AppQueueFailCases.java @@ -41,15 +41,12 @@ import com.iluwatar.commander.shippingservice.ShippingService; */ public class AppQueueFailCases { - private final int numOfRetries = 3; - private final long retryDuration = 30000; - private final long queueTime = 240000; //4 mins - private final long queueTaskTime = 60000; //1 min - private final long paymentTime = 120000; //2 mins - private final long messageTime = 150000; //2.5 mins - private final long employeeTime = 240000; //4 mins + private static final RetryParams retryParams = RetryParams.DEFAULT; - void queuePaymentTaskDatabaseUnavailableCase() throws Exception { + private static final TimeLimits timeLimits = TimeLimits.DEFAULT; + + + void queuePaymentTaskDatabaseUnavailableCase() { var ps = new PaymentService(new PaymentDatabase(), new DatabaseUnavailableException(), new DatabaseUnavailableException(), new DatabaseUnavailableException(), new DatabaseUnavailableException(), new DatabaseUnavailableException(), @@ -61,14 +58,13 @@ public class AppQueueFailCases { new QueueDatabase(new DatabaseUnavailableException(), new DatabaseUnavailableException(), new DatabaseUnavailableException(), new DatabaseUnavailableException(), new DatabaseUnavailableException(), new DatabaseUnavailableException()); - var c = new Commander(eh, ps, ss, ms, qdb, numOfRetries, retryDuration, - queueTime, queueTaskTime, paymentTime, messageTime, employeeTime); + var c = new Commander(eh, ps, ss, ms, qdb, retryParams, timeLimits); var user = new User("Jim", "ABCD"); var order = new Order(user, "book", 10f); c.placeOrder(order); } - void queueMessageTaskDatabaseUnavailableCase() throws Exception { + void queueMessageTaskDatabaseUnavailableCase() { var ps = new PaymentService(new PaymentDatabase()); var ss = new ShippingService(new ShippingDatabase()); var ms = new MessagingService(new MessagingDatabase(), new DatabaseUnavailableException(), @@ -80,14 +76,13 @@ public class AppQueueFailCases { new QueueDatabase(new DatabaseUnavailableException(), new DatabaseUnavailableException(), new DatabaseUnavailableException(), new DatabaseUnavailableException(), new DatabaseUnavailableException(), new DatabaseUnavailableException()); - var c = new Commander(eh, ps, ss, ms, qdb, numOfRetries, retryDuration, - queueTime, queueTaskTime, paymentTime, messageTime, employeeTime); + var c = new Commander(eh, ps, ss, ms, qdb, retryParams, timeLimits); var user = new User("Jim", "ABCD"); var order = new Order(user, "book", 10f); c.placeOrder(order); } - void queueEmployeeDbTaskDatabaseUnavailableCase() throws Exception { + void queueEmployeeDbTaskDatabaseUnavailableCase() { var ps = new PaymentService(new PaymentDatabase()); var ss = new ShippingService(new ShippingDatabase(), new ItemUnavailableException()); var ms = new MessagingService(new MessagingDatabase()); @@ -105,14 +100,13 @@ public class AppQueueFailCases { new DatabaseUnavailableException(), new DatabaseUnavailableException(), new DatabaseUnavailableException(), new DatabaseUnavailableException(), new DatabaseUnavailableException(), new DatabaseUnavailableException()); - var c = new Commander(eh, ps, ss, ms, qdb, numOfRetries, retryDuration, - queueTime, queueTaskTime, paymentTime, messageTime, employeeTime); + var c = new Commander(eh, ps, ss, ms, qdb, retryParams, timeLimits); var user = new User("Jim", "ABCD"); var order = new Order(user, "book", 10f); c.placeOrder(order); } - void queueSuccessCase() throws Exception { + void queueSuccessCase() { var ps = new PaymentService(new PaymentDatabase(), new DatabaseUnavailableException(), new DatabaseUnavailableException(), new DatabaseUnavailableException(), new DatabaseUnavailableException(), new DatabaseUnavailableException(), @@ -124,8 +118,7 @@ public class AppQueueFailCases { var eh = new EmployeeHandle(new EmployeeDatabase()); var qdb = new QueueDatabase(new DatabaseUnavailableException(), new DatabaseUnavailableException()); - var c = new Commander(eh, ps, ss, ms, qdb, numOfRetries, retryDuration, - queueTime, queueTaskTime, paymentTime, messageTime, employeeTime); + var c = new Commander(eh, ps, ss, ms, qdb, retryParams, timeLimits); var user = new User("Jim", "ABCD"); var order = new Order(user, "book", 10f); c.placeOrder(order); @@ -137,11 +130,8 @@ public class AppQueueFailCases { * @param args command line args */ - public static void main(String[] args) throws Exception { + public static void main(String[] args) { var aqfc = new AppQueueFailCases(); - //aqfc.queuePaymentTaskDatabaseUnavailableCase(); - //aqfc.queueMessageTaskDatabaseUnavailableCase(); - //aqfc.queueEmployeeDbTaskDatabaseUnavailableCase(); aqfc.queueSuccessCase(); } -} +} \ No newline at end of file diff --git a/commander/src/main/java/com/iluwatar/commander/AppShippingFailCases.java b/commander/src/main/java/com/iluwatar/commander/AppShippingFailCases.java index fdba598e6..efd924988 100644 --- a/commander/src/main/java/com/iluwatar/commander/AppShippingFailCases.java +++ b/commander/src/main/java/com/iluwatar/commander/AppShippingFailCases.java @@ -43,41 +43,35 @@ import com.iluwatar.commander.shippingservice.ShippingService; */ public class AppShippingFailCases { - private final int numOfRetries = 3; - private final long retryDuration = 30000; - private final long queueTime = 240000; //4 mins - private final long queueTaskTime = 60000; //1 min - private final long paymentTime = 120000; //2 mins - private final long messageTime = 150000; //2.5 mins - private final long employeeTime = 240000; //4 mins + private static final RetryParams retryParams = RetryParams.DEFAULT; - void itemUnavailableCase() throws Exception { + private static final TimeLimits timeLimits = TimeLimits.DEFAULT; + + void itemUnavailableCase() { var ps = new PaymentService(new PaymentDatabase()); var ss = new ShippingService(new ShippingDatabase(), new ItemUnavailableException()); var ms = new MessagingService(new MessagingDatabase()); var eh = new EmployeeHandle(new EmployeeDatabase()); var qdb = new QueueDatabase(); - var c = new Commander(eh, ps, ss, ms, qdb, numOfRetries, retryDuration, - queueTime, queueTaskTime, paymentTime, messageTime, employeeTime); + var c = new Commander(eh, ps, ss, ms, qdb, retryParams, timeLimits); var user = new User("Jim", "ABCD"); var order = new Order(user, "book", 10f); c.placeOrder(order); } - void shippingNotPossibleCase() throws Exception { + void shippingNotPossibleCase() { var ps = new PaymentService(new PaymentDatabase()); var ss = new ShippingService(new ShippingDatabase(), new ShippingNotPossibleException()); var ms = new MessagingService(new MessagingDatabase()); var eh = new EmployeeHandle(new EmployeeDatabase()); var qdb = new QueueDatabase(); - var c = new Commander(eh, ps, ss, ms, qdb, numOfRetries, retryDuration, - queueTime, queueTaskTime, paymentTime, messageTime, employeeTime); + var c = new Commander(eh, ps, ss, ms, qdb, retryParams, timeLimits); var user = new User("Jim", "ABCD"); var order = new Order(user, "book", 10f); c.placeOrder(order); } - void shippingDatabaseUnavailableCase() throws Exception { + void shippingDatabaseUnavailableCase() { //rest is successful var ps = new PaymentService(new PaymentDatabase()); var ss = new ShippingService(new ShippingDatabase(), new DatabaseUnavailableException(), @@ -87,14 +81,13 @@ public class AppShippingFailCases { var ms = new MessagingService(new MessagingDatabase()); var eh = new EmployeeHandle(new EmployeeDatabase()); var qdb = new QueueDatabase(); - var c = new Commander(eh, ps, ss, ms, qdb, numOfRetries, retryDuration, - queueTime, queueTaskTime, paymentTime, messageTime, employeeTime); + var c = new Commander(eh, ps, ss, ms, qdb, retryParams, timeLimits); var user = new User("Jim", "ABCD"); var order = new Order(user, "book", 10f); c.placeOrder(order); } - void shippingSuccessCase() throws Exception { + void shippingSuccessCase() { //goes to payment after 2 retries maybe - rest is successful for now var ps = new PaymentService(new PaymentDatabase(), new DatabaseUnavailableException()); var ss = new ShippingService(new ShippingDatabase(), new DatabaseUnavailableException(), @@ -102,8 +95,7 @@ public class AppShippingFailCases { var ms = new MessagingService(new MessagingDatabase(), new DatabaseUnavailableException()); var eh = new EmployeeHandle(new EmployeeDatabase()); var qdb = new QueueDatabase(); - var c = new Commander(eh, ps, ss, ms, qdb, numOfRetries, retryDuration, - queueTime, queueTaskTime, paymentTime, messageTime, employeeTime); + var c = new Commander(eh, ps, ss, ms, qdb, retryParams, timeLimits); var user = new User("Jim", "ABCD"); var order = new Order(user, "book", 10f); c.placeOrder(order); @@ -115,11 +107,8 @@ public class AppShippingFailCases { * @param args command line args */ - public static void main(String[] args) throws Exception { + public static void main(String[] args) { var asfc = new AppShippingFailCases(); - //asfc.itemUnavailableCase(); - //asfc.shippingNotPossibleCase(); - //asfc.shippingDatabaseUnavailableCase(); asfc.shippingSuccessCase(); } -} +} \ No newline at end of file diff --git a/commander/src/main/java/com/iluwatar/commander/Commander.java b/commander/src/main/java/com/iluwatar/commander/Commander.java index 4a1483c11..42f1cabc4 100644 --- a/commander/src/main/java/com/iluwatar/commander/Commander.java +++ b/commander/src/main/java/com/iluwatar/commander/Commander.java @@ -28,6 +28,7 @@ import com.iluwatar.commander.Order.MessageSent; import com.iluwatar.commander.Order.PaymentStatus; import com.iluwatar.commander.employeehandle.EmployeeHandle; import com.iluwatar.commander.exceptions.DatabaseUnavailableException; +import com.iluwatar.commander.exceptions.IsEmptyException; import com.iluwatar.commander.exceptions.ItemUnavailableException; import com.iluwatar.commander.exceptions.PaymentDetailsErrorException; import com.iluwatar.commander.exceptions.ShippingNotPossibleException; @@ -88,6 +89,7 @@ public class Commander { private final long messageTime; private final long employeeTime; private boolean finalSiteMsgShown; + private static final Logger LOG = LoggerFactory.getLogger(Commander.class); //we could also have another db where it stores all orders @@ -98,32 +100,32 @@ public class Commander { private static final String TRY_CONNECTING_MSG_SVC = ": Trying to connect to messaging service.."; + private static final String DEFAULT_EXCEPTION_MESSAGE = "An exception occurred"; + Commander(EmployeeHandle empDb, PaymentService paymentService, ShippingService shippingService, - MessagingService messagingService, QueueDatabase qdb, int numOfRetries, - long retryDuration, long queueTime, long queueTaskTime, long paymentTime, - long messageTime, long employeeTime) { + MessagingService messagingService, QueueDatabase qdb, RetryParams retryParams, TimeLimits timeLimits) { this.paymentService = paymentService; this.shippingService = shippingService; this.messagingService = messagingService; this.employeeDb = empDb; this.queue = qdb; - this.numOfRetries = numOfRetries; - this.retryDuration = retryDuration; - this.queueTime = queueTime; - this.queueTaskTime = queueTaskTime; - this.paymentTime = paymentTime; - this.messageTime = messageTime; - this.employeeTime = employeeTime; + this.numOfRetries = retryParams.numOfRetries(); + this.retryDuration = retryParams.retryDuration(); + this.queueTime = timeLimits.queueTime(); + this.queueTaskTime = timeLimits.queueTaskTime(); + this.paymentTime = timeLimits.paymentTime(); + this.messageTime = timeLimits.messageTime(); + this.employeeTime = timeLimits.employeeTime(); this.finalSiteMsgShown = false; } - void placeOrder(Order order) throws Exception { + void placeOrder(Order order) { sendShippingRequest(order); } private void sendShippingRequest(Order order) { var list = shippingService.exceptionsList; - Retry.Operation op = (l) -> { + Retry.Operation op = l -> { if (!l.isEmpty()) { if (DatabaseUnavailableException.class.isAssignableFrom(l.get(0).getClass())) { LOG.debug(ORDER_ID + ": Error in connecting to shipping service, " @@ -178,67 +180,86 @@ public class Commander { } var list = paymentService.exceptionsList; var t = new Thread(() -> { - Retry.Operation op = (l) -> { - if (!l.isEmpty()) { - if (DatabaseUnavailableException.class.isAssignableFrom(l.get(0).getClass())) { - LOG.debug(ORDER_ID + ": Error in connecting to payment service," - + " trying again..", order.id); - } else { - LOG.debug(ORDER_ID + ": Error in creating payment request..", order.id); - } - throw l.remove(0); - } - if (order.paid.equals(PaymentStatus.TRYING)) { - var transactionId = paymentService.receiveRequest(order.price); - order.paid = PaymentStatus.DONE; - LOG.info(ORDER_ID + ": Payment successful, transaction Id: {}", - order.id, transactionId); - if (!finalSiteMsgShown) { - LOG.info("Payment made successfully, thank you for shopping with us!!"); - finalSiteMsgShown = true; - } - sendSuccessMessage(order); - } - }; - Retry.HandleErrorIssue handleError = (o, err) -> { - if (PaymentDetailsErrorException.class.isAssignableFrom(err.getClass())) { - if (!finalSiteMsgShown) { - LOG.info("There was an error in payment. Your account/card details " - + "may have been incorrect. " - + "Meanwhile, your order has been converted to COD and will be shipped."); - finalSiteMsgShown = true; - } - LOG.error(ORDER_ID + ": Payment details incorrect, failed..", order.id); - o.paid = PaymentStatus.NOT_DONE; - sendPaymentFailureMessage(o); - } else { - if (o.messageSent.equals(MessageSent.NONE_SENT)) { - if (!finalSiteMsgShown) { - LOG.info("There was an error in payment. We are on it, and will get back to you " - + "asap. Don't worry, your order has been placed and will be shipped."); - finalSiteMsgShown = true; - } - LOG.warn(ORDER_ID + ": Payment error, going to queue..", order.id); - sendPaymentPossibleErrorMsg(o); - } - if (o.paid.equals(PaymentStatus.TRYING) && System - .currentTimeMillis() - o.createdTime < paymentTime) { - var qt = new QueueTask(o, TaskType.PAYMENT, -1); - updateQueue(qt); - } - } - }; + Retry.Operation op = getRetryOperation(order); + + Retry.HandleErrorIssue handleError = getRetryHandleErrorIssue(order); + var r = new Retry<>(op, handleError, numOfRetries, retryDuration, e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass())); try { r.perform(list, order); } catch (Exception e1) { - LOG.error("An exception occurred", e1); + LOG.error(DEFAULT_EXCEPTION_MESSAGE, e1); } }); + t.start(); } + private Retry.HandleErrorIssue getRetryHandleErrorIssue(Order order) { + return (o, err) -> { + if (PaymentDetailsErrorException.class.isAssignableFrom(err.getClass())) { + handlePaymentDetailsError(order.id, o); + } else { + if (o.messageSent.equals(MessageSent.NONE_SENT)) { + handlePaymentError(order.id, o); + } + if (o.paid.equals(PaymentStatus.TRYING) && System + .currentTimeMillis() - o.createdTime < paymentTime) { + var qt = new QueueTask(o, TaskType.PAYMENT, -1); + updateQueue(qt); + } + } + }; + } + + private void handlePaymentError(String orderId, Order o) { + if (!finalSiteMsgShown) { + LOG.info("There was an error in payment. We are on it, and will get back to you " + + "asap. Don't worry, your order has been placed and will be shipped."); + finalSiteMsgShown = true; + } + LOG.warn(ORDER_ID + ": Payment error, going to queue..", orderId); + sendPaymentPossibleErrorMsg(o); + } + + private void handlePaymentDetailsError(String orderId, Order o) { + if (!finalSiteMsgShown) { + LOG.info("There was an error in payment. Your account/card details " + + "may have been incorrect. " + + "Meanwhile, your order has been converted to COD and will be shipped."); + finalSiteMsgShown = true; + } + LOG.error(ORDER_ID + ": Payment details incorrect, failed..", orderId); + o.paid = PaymentStatus.NOT_DONE; + sendPaymentFailureMessage(o); + } + + private Retry.Operation getRetryOperation(Order order) { + return l -> { + if (!l.isEmpty()) { + if (DatabaseUnavailableException.class.isAssignableFrom(l.get(0).getClass())) { + LOG.debug(ORDER_ID + ": Error in connecting to payment service," + + " trying again..", order.id); + } else { + LOG.debug(ORDER_ID + ": Error in creating payment request..", order.id); + } + throw l.remove(0); + } + if (order.paid.equals(PaymentStatus.TRYING)) { + var transactionId = paymentService.receiveRequest(order.price); + order.paid = PaymentStatus.DONE; + LOG.info(ORDER_ID + ": Payment successful, transaction Id: {}", + order.id, transactionId); + if (!finalSiteMsgShown) { + LOG.info("Payment made successfully, thank you for shopping with us!!"); + finalSiteMsgShown = true; + } + sendSuccessMessage(order); + } + }; + } + private void updateQueue(QueueTask qt) { if (System.currentTimeMillis() - qt.order.createdTime >= this.queueTime) { // since payment time is lesser than queuetime it would have already failed.. @@ -256,7 +277,7 @@ public class Commander { } var list = queue.exceptionsList; Thread t = new Thread(() -> { - Retry.Operation op = (list1) -> { + Retry.Operation op = list1 -> { if (!list1.isEmpty()) { LOG.warn(ORDER_ID + ": Error in connecting to queue db, trying again..", qt.order.id); throw list1.remove(0); @@ -282,7 +303,7 @@ public class Commander { try { r.perform(list, qt); } catch (Exception e1) { - LOG.error("An exception occurred", e1); + LOG.error(DEFAULT_EXCEPTION_MESSAGE, e1); } }); t.start(); @@ -291,7 +312,7 @@ public class Commander { private void tryDoingTasksInQueue() { //commander controls operations done to queue var list = queue.exceptionsList; var t2 = new Thread(() -> { - Retry.Operation op = (list1) -> { + Retry.Operation op = list1 -> { if (!list1.isEmpty()) { LOG.warn("Error in accessing queue db to do tasks, trying again.."); throw list1.remove(0); @@ -305,7 +326,7 @@ public class Commander { try { r.perform(list, null); } catch (Exception e1) { - LOG.error("An exception occurred", e1); + LOG.error(DEFAULT_EXCEPTION_MESSAGE, e1); } }); t2.start(); @@ -314,7 +335,7 @@ public class Commander { private void tryDequeue() { var list = queue.exceptionsList; var t3 = new Thread(() -> { - Retry.Operation op = (list1) -> { + Retry.Operation op = list1 -> { if (!list1.isEmpty()) { LOG.warn("Error in accessing queue db to dequeue task, trying again.."); throw list1.remove(0); @@ -329,7 +350,7 @@ public class Commander { try { r.perform(list, null); } catch (Exception e1) { - LOG.error("An exception occurred", e1); + LOG.error(DEFAULT_EXCEPTION_MESSAGE, e1); } }); t3.start(); @@ -343,15 +364,13 @@ public class Commander { var list = messagingService.exceptionsList; Thread t = new Thread(() -> { Retry.Operation op = handleSuccessMessageRetryOperation(order); - Retry.HandleErrorIssue handleError = (o, err) -> { - handleSuccessMessageErrorIssue(order, o); - }; + Retry.HandleErrorIssue handleError = (o, err) -> handleSuccessMessageErrorIssue(order, o); var r = new Retry<>(op, handleError, numOfRetries, retryDuration, e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass())); try { r.perform(list, order); } catch (Exception e1) { - LOG.error("An exception occurred", e1); + LOG.error(DEFAULT_EXCEPTION_MESSAGE, e1); } }); t.start(); @@ -370,7 +389,7 @@ public class Commander { } private Retry.Operation handleSuccessMessageRetryOperation(Order order) { - return (l) -> { + return l -> { if (!l.isEmpty()) { if (DatabaseUnavailableException.class.isAssignableFrom(l.get(0).getClass())) { LOG.debug(ORDER_ID + ERROR_CONNECTING_MSG_SVC @@ -398,18 +417,14 @@ public class Commander { } var list = messagingService.exceptionsList; var t = new Thread(() -> { - Retry.Operation op = (l) -> { - handlePaymentFailureRetryOperation(order, l); - }; - Retry.HandleErrorIssue handleError = (o, err) -> { - handlePaymentErrorIssue(order, o); - }; + Retry.Operation op = l -> handlePaymentFailureRetryOperation(order, l); + Retry.HandleErrorIssue handleError = (o, err) -> handlePaymentErrorIssue(order, o); var r = new Retry<>(op, handleError, numOfRetries, retryDuration, e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass())); try { r.perform(list, order); } catch (Exception e1) { - LOG.error("An exception occurred", e1); + LOG.error(DEFAULT_EXCEPTION_MESSAGE, e1); } }); t.start(); @@ -427,16 +442,14 @@ public class Commander { } } - private void handlePaymentFailureRetryOperation(Order order, List l) throws Exception { + private void handlePaymentFailureRetryOperation(Order order, List l) throws IndexOutOfBoundsException, DatabaseUnavailableException { if (!l.isEmpty()) { if (DatabaseUnavailableException.class.isAssignableFrom(l.get(0).getClass())) { - LOG.debug(ORDER_ID + ERROR_CONNECTING_MSG_SVC - + "(Payment Failure msg), trying again..", order.id); + LOG.debug(ORDER_ID + ERROR_CONNECTING_MSG_SVC + "(Payment Failure msg), trying again..", order.id); } else { - LOG.debug(ORDER_ID + ": Error in creating Payment Failure" - + " message request..", order.id); + LOG.debug(ORDER_ID + ": Error in creating Payment Failure" + " message request..", order.id); } - throw l.remove(0); + throw new IndexOutOfBoundsException(); } if (!order.messageSent.equals(MessageSent.PAYMENT_FAIL) && !order.messageSent.equals(MessageSent.PAYMENT_SUCCESSFUL)) { @@ -454,18 +467,14 @@ public class Commander { } var list = messagingService.exceptionsList; var t = new Thread(() -> { - Retry.Operation op = (l) -> { - handlePaymentPossibleErrorMsgRetryOperation(order, l); - }; - Retry.HandleErrorIssue handleError = (o, err) -> { - handlePaymentPossibleErrorMsgErrorIssue(order, o); - }; + Retry.Operation op = l -> handlePaymentPossibleErrorMsgRetryOperation(order, l); + Retry.HandleErrorIssue handleError = (o, err) -> handlePaymentPossibleErrorMsgErrorIssue(order, o); var r = new Retry<>(op, handleError, numOfRetries, retryDuration, e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass())); try { r.perform(list, order); } catch (Exception e1) { - LOG.error("An exception occurred", e1); + LOG.error(DEFAULT_EXCEPTION_MESSAGE, e1); } }); t.start(); @@ -484,7 +493,7 @@ public class Commander { } private void handlePaymentPossibleErrorMsgRetryOperation(Order order, List l) - throws Exception { + throws IndexOutOfBoundsException, DatabaseUnavailableException { if (!l.isEmpty()) { if (DatabaseUnavailableException.class.isAssignableFrom(l.get(0).getClass())) { LOG.debug(ORDER_ID + ERROR_CONNECTING_MSG_SVC @@ -493,7 +502,7 @@ public class Commander { LOG.debug(ORDER_ID + ": Error in creating Payment Error" + " messaging request..", order.id); } - throw l.remove(0); + throw new IndexOutOfBoundsException(); } if (order.paid.equals(PaymentStatus.TRYING) && order.messageSent .equals(MessageSent.NONE_SENT)) { @@ -511,7 +520,7 @@ public class Commander { } var list = employeeDb.exceptionsList; var t = new Thread(() -> { - Retry.Operation op = (l) -> { + Retry.Operation op = l -> { if (!l.isEmpty()) { LOG.warn(ORDER_ID + ": Error in connecting to employee handle," + " trying again..", order.id); @@ -537,18 +546,18 @@ public class Commander { try { r.perform(list, order); } catch (Exception e1) { - LOG.error("An exception occurred", e1); + LOG.error(DEFAULT_EXCEPTION_MESSAGE, e1); } }); t.start(); } - private void doTasksInQueue() throws Exception { + private void doTasksInQueue() throws IsEmptyException, InterruptedException { if (queueItems != 0) { var qt = queue.peek(); //this should probably be cloned here //this is why we have retry for doTasksInQueue LOG.trace(ORDER_ID + ": Started doing task of type {}", qt.order.id, qt.getType()); - if (qt.getFirstAttemptTime() == -1) { + if (qt.isFirstAttempt()) { qt.setFirstAttemptTime(System.currentTimeMillis()); } if (System.currentTimeMillis() - qt.getFirstAttemptTime() >= queueTaskTime) { @@ -556,43 +565,11 @@ public class Commander { LOG.trace(ORDER_ID + ": This queue task of type {}" + " does not need to be done anymore (timeout), dequeue..", qt.order.id, qt.getType()); } else { - if (qt.taskType.equals(TaskType.PAYMENT)) { - if (!qt.order.paid.equals(PaymentStatus.TRYING)) { - tryDequeue(); - LOG.trace(ORDER_ID + ": This payment task already done, dequeueing..", qt.order.id); - } else { - sendPaymentRequest(qt.order); - LOG.debug(ORDER_ID + ": Trying to connect to payment service..", qt.order.id); - } - } else if (qt.taskType.equals(TaskType.MESSAGING)) { - if (qt.order.messageSent.equals(MessageSent.PAYMENT_FAIL) - || qt.order.messageSent.equals(MessageSent.PAYMENT_SUCCESSFUL)) { - tryDequeue(); - LOG.trace(ORDER_ID + ": This messaging task already done, dequeue..", qt.order.id); - } else if (qt.messageType == 1 && (!qt.order.messageSent.equals(MessageSent.NONE_SENT) - || !qt.order.paid.equals(PaymentStatus.TRYING))) { - tryDequeue(); - LOG.trace(ORDER_ID + ": This messaging task does not need to be done," - + " dequeue..", qt.order.id); - } else if (qt.messageType == 0) { - sendPaymentFailureMessage(qt.order); - LOG.debug(ORDER_ID + TRY_CONNECTING_MSG_SVC, qt.order.id); - } else if (qt.messageType == 1) { - sendPaymentPossibleErrorMsg(qt.order); - LOG.debug(ORDER_ID + TRY_CONNECTING_MSG_SVC, qt.order.id); - } else if (qt.messageType == 2) { - sendSuccessMessage(qt.order); - LOG.debug(ORDER_ID + TRY_CONNECTING_MSG_SVC, qt.order.id); - } - } else if (qt.taskType.equals(TaskType.EMPLOYEE_DB)) { - if (qt.order.addedToEmployeeHandle) { - tryDequeue(); - LOG.trace(ORDER_ID + ": This employee handle task already done," - + " dequeue..", qt.order.id); - } else { - employeeHandleIssue(qt.order); - LOG.debug(ORDER_ID + ": Trying to connect to employee handle..", qt.order.id); - } + switch (qt.taskType) { + case PAYMENT -> doPaymentTask(qt); + case MESSAGING -> doMessagingTask(qt); + case EMPLOYEE_DB -> doEmployeeDbTask(qt); + default -> throw new IllegalArgumentException("Unknown task type"); } } } @@ -604,4 +581,47 @@ public class Commander { } } -} + private void doEmployeeDbTask(QueueTask qt) { + if (qt.order.addedToEmployeeHandle) { + tryDequeue(); + LOG.trace(ORDER_ID + ": This employee handle task already done," + + " dequeue..", qt.order.id); + } else { + employeeHandleIssue(qt.order); + LOG.debug(ORDER_ID + ": Trying to connect to employee handle..", qt.order.id); + } + } + + private void doMessagingTask(QueueTask qt) { + if (qt.order.messageSent.equals(MessageSent.PAYMENT_FAIL) + || qt.order.messageSent.equals(MessageSent.PAYMENT_SUCCESSFUL)) { + tryDequeue(); + LOG.trace(ORDER_ID + ": This messaging task already done, dequeue..", qt.order.id); + } else if (qt.messageType == 1 && (!qt.order.messageSent.equals(MessageSent.NONE_SENT) + || !qt.order.paid.equals(PaymentStatus.TRYING))) { + tryDequeue(); + LOG.trace(ORDER_ID + ": This messaging task does not need to be done," + + " dequeue..", qt.order.id); + } else if (qt.messageType == 0) { + sendPaymentFailureMessage(qt.order); + LOG.debug(ORDER_ID + TRY_CONNECTING_MSG_SVC, qt.order.id); + } else if (qt.messageType == 1) { + sendPaymentPossibleErrorMsg(qt.order); + LOG.debug(ORDER_ID + TRY_CONNECTING_MSG_SVC, qt.order.id); + } else if (qt.messageType == 2) { + sendSuccessMessage(qt.order); + LOG.debug(ORDER_ID + TRY_CONNECTING_MSG_SVC, qt.order.id); + } + } + + private void doPaymentTask(QueueTask qt) { + if (!qt.order.paid.equals(PaymentStatus.TRYING)) { + tryDequeue(); + LOG.trace(ORDER_ID + ": This payment task already done, dequeueing..", qt.order.id); + } else { + sendPaymentRequest(qt.order); + LOG.debug(ORDER_ID + ": Trying to connect to payment service..", qt.order.id); + } + } + +} \ No newline at end of file diff --git a/commander/src/main/java/com/iluwatar/commander/RetryParams.java b/commander/src/main/java/com/iluwatar/commander/RetryParams.java new file mode 100644 index 000000000..d6cf5dfec --- /dev/null +++ b/commander/src/main/java/com/iluwatar/commander/RetryParams.java @@ -0,0 +1,10 @@ +package com.iluwatar.commander; + +/** + * Record to hold the parameters related to retries. + * @param numOfRetries number of retries + * @param retryDuration retry duration + */ +public record RetryParams(int numOfRetries, long retryDuration) { + public static final RetryParams DEFAULT = new RetryParams(3, 30000L); +} \ No newline at end of file diff --git a/commander/src/main/java/com/iluwatar/commander/TimeLimits.java b/commander/src/main/java/com/iluwatar/commander/TimeLimits.java new file mode 100644 index 000000000..6de079edd --- /dev/null +++ b/commander/src/main/java/com/iluwatar/commander/TimeLimits.java @@ -0,0 +1,16 @@ +package com.iluwatar.commander; + +/** + * Record to hold parameters related to time limit + * for various tasks. + * @param queueTime time limit for queue + * @param queueTaskTime time limit for queuing task + * @param paymentTime time limit for payment error message + * @param messageTime time limit for message time order + * @param employeeTime time limit for employee handle time + */ +public record TimeLimits(long queueTime, long queueTaskTime, long paymentTime, + long messageTime, long employeeTime) { + + public static final TimeLimits DEFAULT = new TimeLimits(240000L, 60000L, 120000L, 150000L, 240000L); +} \ No newline at end of file diff --git a/commander/src/main/java/com/iluwatar/commander/queue/QueueTask.java b/commander/src/main/java/com/iluwatar/commander/queue/QueueTask.java index 32d205e79..e0194508d 100644 --- a/commander/src/main/java/com/iluwatar/commander/queue/QueueTask.java +++ b/commander/src/main/java/com/iluwatar/commander/queue/QueueTask.java @@ -72,4 +72,8 @@ public class QueueTask { } } } -} + + public boolean isFirstAttempt() { + return this.firstAttemptTime == -1L; + } +} \ No newline at end of file diff --git a/commander/src/test/java/com/iluwatar/commander/CommanderTest.java b/commander/src/test/java/com/iluwatar/commander/CommanderTest.java index 42405417c..f6c2351fe 100644 --- a/commander/src/test/java/com/iluwatar/commander/CommanderTest.java +++ b/commander/src/test/java/com/iluwatar/commander/CommanderTest.java @@ -46,13 +46,9 @@ import static org.junit.jupiter.api.Assertions.assertFalse; class CommanderTest { - private final int numOfRetries = 1; - private final long retryDuration = 1_000; - private long queueTime = 1_00; - private long queueTaskTime = 1_000; - private long paymentTime = 6_000; - private long messageTime = 5_000; - private long employeeTime = 2_000; + private final RetryParams retryParams = new RetryParams(1, 1_000L); + + private final TimeLimits timeLimits = new TimeLimits(1L, 1000L, 6000L, 5000L, 2000L); private static final List exceptionList = new ArrayList<>(); @@ -96,8 +92,7 @@ class CommanderTest { new DatabaseUnavailableException(), new DatabaseUnavailableException(), new DatabaseUnavailableException(), new DatabaseUnavailableException()); return new Commander(employeeHandle, paymentService, shippingService, - messagingService, qdb, numOfRetries, retryDuration, - queueTime, queueTaskTime, paymentTime, messageTime, employeeTime); + messagingService, qdb, retryParams, timeLimits); } private Commander buildCommanderObjectVanilla() { @@ -118,8 +113,7 @@ class CommanderTest { new DatabaseUnavailableException(), new DatabaseUnavailableException(), new DatabaseUnavailableException(), new DatabaseUnavailableException()); return new Commander(employeeHandle, paymentService, shippingService, - messagingService, qdb, numOfRetries, retryDuration, - queueTime, queueTaskTime, paymentTime, messageTime, employeeTime); + messagingService, qdb, retryParams, timeLimits); } private Commander buildCommanderObjectUnknownException() { @@ -132,8 +126,7 @@ class CommanderTest { var qdb = new QueueDatabase (new DatabaseUnavailableException(), new IllegalStateException()); return new Commander(employeeHandle, paymentService, shippingService, - messagingService, qdb, numOfRetries, retryDuration, - queueTime, queueTaskTime, paymentTime, messageTime, employeeTime); + messagingService, qdb, retryParams, timeLimits); } private Commander buildCommanderObjectNoPaymentException1() { @@ -146,8 +139,7 @@ class CommanderTest { var qdb = new QueueDatabase (new DatabaseUnavailableException(), new IllegalStateException()); return new Commander(employeeHandle, paymentService, shippingService, - messagingService, qdb, numOfRetries, retryDuration, - queueTime, queueTaskTime, paymentTime, messageTime, employeeTime); + messagingService, qdb, retryParams, timeLimits); } private Commander buildCommanderObjectNoPaymentException2() { @@ -160,8 +152,7 @@ class CommanderTest { var qdb = new QueueDatabase (new DatabaseUnavailableException(), new IllegalStateException()); return new Commander(employeeHandle, paymentService, shippingService, - messagingService, qdb, numOfRetries, retryDuration, - queueTime, queueTaskTime, paymentTime, messageTime, employeeTime); + messagingService, qdb, retryParams, timeLimits); } private Commander buildCommanderObjectNoPaymentException3() { @@ -174,8 +165,7 @@ class CommanderTest { var qdb = new QueueDatabase (new DatabaseUnavailableException(), new IllegalStateException()); return new Commander(employeeHandle, paymentService, shippingService, - messagingService, qdb, numOfRetries, retryDuration, - queueTime, queueTaskTime, paymentTime, messageTime, employeeTime); + messagingService, qdb, retryParams, timeLimits); } private Commander buildCommanderObjectWithDB() { @@ -206,8 +196,7 @@ class CommanderTest { return new Commander(employeeHandle, paymentService, shippingService, - messagingService, null, numOfRetries, retryDuration, - queueTime, queueTaskTime, paymentTime, messageTime, employeeTime); + messagingService, null, retryParams, timeLimits); } private Commander buildCommanderObjectWithoutDB() { @@ -238,12 +227,13 @@ class CommanderTest { return new Commander(employeeHandle, paymentService, shippingService, - messagingService, null, numOfRetries, retryDuration, - queueTime, queueTaskTime, paymentTime, messageTime, employeeTime); + messagingService, null, retryParams, timeLimits); } @Test - void testPlaceOrderVanilla() throws Exception { + void testPlaceOrderVanilla() { + long paymentTime = timeLimits.paymentTime(); + long queueTaskTime = timeLimits.queueTaskTime(); for (double d = 0.1; d < 2; d = d + 0.1) { paymentTime *= d; queueTaskTime *= d; @@ -258,6 +248,8 @@ class CommanderTest { @Test void testPlaceOrder() throws Exception { + long paymentTime = timeLimits.paymentTime(); + long queueTaskTime = timeLimits.queueTaskTime(); for (double d = 0.1; d < 2; d = d + 0.1) { paymentTime *= d; queueTaskTime *= d; @@ -272,6 +264,8 @@ class CommanderTest { @Test void testPlaceOrder2() throws Exception { + long paymentTime = timeLimits.paymentTime(); + long queueTaskTime = timeLimits.queueTaskTime(); for (double d = 0.1; d < 2; d = d + 0.1) { paymentTime *= d; queueTaskTime *= d; @@ -286,6 +280,8 @@ class CommanderTest { @Test void testPlaceOrderNoException1() throws Exception { + long paymentTime = timeLimits.paymentTime(); + long queueTaskTime = timeLimits.queueTaskTime(); for (double d = 0.1; d < 2; d = d + 0.1) { paymentTime *= d; queueTaskTime *= d; @@ -300,6 +296,8 @@ class CommanderTest { @Test void testPlaceOrderNoException2() throws Exception { + long paymentTime = timeLimits.paymentTime(); + long queueTaskTime = timeLimits.queueTaskTime(); for (double d = 0.1; d < 2; d = d + 0.1) { paymentTime *= d; queueTaskTime *= d; @@ -314,6 +312,8 @@ class CommanderTest { @Test void testPlaceOrderNoException3() throws Exception { + long paymentTime = timeLimits.paymentTime(); + long queueTaskTime = timeLimits.queueTaskTime(); for (double d = 0.1; d < 2; d = d + 0.1) { paymentTime *= d; queueTaskTime *= d; @@ -328,6 +328,8 @@ class CommanderTest { @Test void testPlaceOrderNoException4() throws Exception { + long paymentTime = timeLimits.paymentTime(); + long queueTaskTime = timeLimits.queueTaskTime(); for (double d = 0.1; d < 2; d = d + 0.1) { paymentTime *= d; queueTaskTime *= d; @@ -344,6 +346,11 @@ class CommanderTest { @Test void testPlaceOrderUnknownException() throws Exception { + long paymentTime = timeLimits.paymentTime(); + long queueTaskTime = timeLimits.queueTaskTime(); + long messageTime = timeLimits.messageTime(); + long employeeTime = timeLimits.employeeTime(); + long queueTime = timeLimits.queueTime(); for (double d = 0.1; d < 2; d = d + 0.1) { paymentTime *= d; queueTaskTime *= d; @@ -361,6 +368,11 @@ class CommanderTest { @Test void testPlaceOrderShortDuration() throws Exception { + long paymentTime = timeLimits.paymentTime(); + long queueTaskTime = timeLimits.queueTaskTime(); + long messageTime = timeLimits.messageTime(); + long employeeTime = timeLimits.employeeTime(); + long queueTime = timeLimits.queueTime(); for (double d = 0.1; d < 2; d = d + 0.1) { paymentTime *= d; queueTaskTime *= d; @@ -378,6 +390,11 @@ class CommanderTest { @Test void testPlaceOrderShortDuration2() throws Exception { + long paymentTime = timeLimits.paymentTime(); + long queueTaskTime = timeLimits.queueTaskTime(); + long messageTime = timeLimits.messageTime(); + long employeeTime = timeLimits.employeeTime(); + long queueTime = timeLimits.queueTime(); for (double d = 0.1; d < 2; d = d + 0.1) { paymentTime *= d; queueTaskTime *= d; @@ -395,6 +412,11 @@ class CommanderTest { @Test void testPlaceOrderNoExceptionShortMsgDuration() throws Exception { + long paymentTime = timeLimits.paymentTime(); + long queueTaskTime = timeLimits.queueTaskTime(); + long messageTime = timeLimits.messageTime(); + long employeeTime = timeLimits.employeeTime(); + long queueTime = timeLimits.queueTime(); for (double d = 0.1; d < 2; d = d + 0.1) { paymentTime *= d; queueTaskTime *= d; @@ -412,6 +434,11 @@ class CommanderTest { @Test void testPlaceOrderNoExceptionShortQueueDuration() throws Exception { + long paymentTime = timeLimits.paymentTime(); + long queueTaskTime = timeLimits.queueTaskTime(); + long messageTime = timeLimits.messageTime(); + long employeeTime = timeLimits.employeeTime(); + long queueTime = timeLimits.queueTime(); for (double d = 0.1; d < 2; d = d + 0.1) { paymentTime *= d; queueTaskTime *= d; @@ -429,6 +456,11 @@ class CommanderTest { @Test void testPlaceOrderWithDatabase() throws Exception { + long paymentTime = timeLimits.paymentTime(); + long queueTaskTime = timeLimits.queueTaskTime(); + long messageTime = timeLimits.messageTime(); + long employeeTime = timeLimits.employeeTime(); + long queueTime = timeLimits.queueTime(); for (double d = 0.1; d < 2; d = d + 0.1) { paymentTime *= d; queueTaskTime *= d; @@ -446,6 +478,11 @@ class CommanderTest { @Test void testPlaceOrderWithDatabaseAndExceptions() throws Exception { + long paymentTime = timeLimits.paymentTime(); + long queueTaskTime = timeLimits.queueTaskTime(); + long messageTime = timeLimits.messageTime(); + long employeeTime = timeLimits.employeeTime(); + long queueTime = timeLimits.queueTime(); for (double d = 0.1; d < 2; d = d + 0.1) { paymentTime *= d; queueTaskTime *= d; @@ -488,6 +525,11 @@ class CommanderTest { @Test void testPlaceOrderWithoutDatabase() throws Exception { + long paymentTime = timeLimits.paymentTime(); + long queueTaskTime = timeLimits.queueTaskTime(); + long messageTime = timeLimits.messageTime(); + long employeeTime = timeLimits.employeeTime(); + long queueTime = timeLimits.queueTime(); for (double d = 0.1; d < 2; d = d + 0.1) { paymentTime *= d; queueTaskTime *= d; @@ -505,6 +547,11 @@ class CommanderTest { @Test void testPlaceOrderWithoutDatabaseAndExceptions() throws Exception { + long paymentTime = timeLimits.paymentTime(); + long queueTaskTime = timeLimits.queueTaskTime(); + long messageTime = timeLimits.messageTime(); + long employeeTime = timeLimits.employeeTime(); + long queueTime = timeLimits.queueTime(); for (double d = 0.1; d < 2; d = d + 0.1) { paymentTime *= d; queueTaskTime *= d; @@ -545,4 +592,4 @@ class CommanderTest { } } -} +} \ No newline at end of file diff --git a/composite-view/src/main/java/com/iluwatar/compositeview/AppServlet.java b/composite-view/src/main/java/com/iluwatar/compositeview/AppServlet.java index d2ec90675..a10d98c52 100644 --- a/composite-view/src/main/java/com/iluwatar/compositeview/AppServlet.java +++ b/composite-view/src/main/java/com/iluwatar/compositeview/AppServlet.java @@ -29,6 +29,7 @@ import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import java.io.PrintWriter; +import lombok.NoArgsConstructor; import lombok.extern.slf4j.Slf4j; /** @@ -36,6 +37,7 @@ import lombok.extern.slf4j.Slf4j; * Runs on Tomcat 10 and handles Http requests */ @Slf4j +@NoArgsConstructor public final class AppServlet extends HttpServlet { private static final String CONTENT_TYPE = "text/html"; private String msgPartOne = "

This Server Doesn't Support"; @@ -50,10 +52,6 @@ public final class AppServlet extends HttpServlet { private String destination = "newsDisplay.jsp"; - public AppServlet() { - - } - @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) { try { @@ -95,4 +93,4 @@ public final class AppServlet extends HttpServlet { LOGGER.error("Exception occurred PUT request processing ", e); } } -} +} \ No newline at end of file diff --git a/context-object/src/main/java/com/iluwatar/context/object/App.java b/context-object/src/main/java/com/iluwatar/context/object/App.java index 4147357d2..133a7cc5d 100644 --- a/context-object/src/main/java/com/iluwatar/context/object/App.java +++ b/context-object/src/main/java/com/iluwatar/context/object/App.java @@ -49,18 +49,23 @@ public class App { var layerA = new LayerA(); layerA.addAccountInfo(SERVICE); - LOGGER.info("Context = {}", layerA.getContext()); + logContext(layerA.getContext()); //Initiate second layer and preserving information retrieved in first layer through passing context object var layerB = new LayerB(layerA); layerB.addSessionInfo(SERVICE); - LOGGER.info("Context = {}", layerB.getContext()); + logContext(layerB.getContext()); //Initiate third layer and preserving information retrieved in first and second layer through passing context object var layerC = new LayerC(layerB); layerC.addSearchInfo(SERVICE); - LOGGER.info("Context = {}", layerC.getContext()); + logContext(layerC.getContext()); } -} + + private static void logContext(ServiceContext context) { + LOGGER.info("Context = {}", context); + + } +} \ No newline at end of file diff --git a/data-transfer-object/src/main/java/com/iluwatar/datatransfer/product/ProductResource.java b/data-transfer-object/src/main/java/com/iluwatar/datatransfer/product/ProductResource.java index dc40f0688..e0345b411 100644 --- a/data-transfer-object/src/main/java/com/iluwatar/datatransfer/product/ProductResource.java +++ b/data-transfer-object/src/main/java/com/iluwatar/datatransfer/product/ProductResource.java @@ -31,14 +31,6 @@ import java.util.List; * has all product details. */ public record ProductResource(List products) { - /** - * Initialise resource with existing products. - * - * @param products initialize resource with existing products. Act as database. - */ - public ProductResource { - } - /** * Get all products. * @@ -80,14 +72,4 @@ public record ProductResource(List products) { .cost(createProductDto.getCost()) .build()); } - - /** - * List of all products in an entity representation. - * - * @return : all the products entity that stored in the products list - */ - @Override - public List products() { - return products; - } -} +} \ No newline at end of file diff --git a/double-dispatch/src/main/java/com/iluwatar/doubledispatch/SpaceStationMir.java b/double-dispatch/src/main/java/com/iluwatar/doubledispatch/SpaceStationMir.java index b92e7e9d4..3f718c8d9 100644 --- a/double-dispatch/src/main/java/com/iluwatar/doubledispatch/SpaceStationMir.java +++ b/double-dispatch/src/main/java/com/iluwatar/doubledispatch/SpaceStationMir.java @@ -54,22 +54,24 @@ public class SpaceStationMir extends GameObject { @Override public void collisionResolve(Meteoroid meteoroid) { - LOGGER.info(AppConstants.HITS + " {} is damaged!", meteoroid.getClass().getSimpleName(), - this.getClass().getSimpleName(), this.getClass().getSimpleName()); + logHits(meteoroid); setDamaged(true); } @Override public void collisionResolve(SpaceStationMir mir) { - LOGGER.info(AppConstants.HITS + " {} is damaged!", mir.getClass().getSimpleName(), - this.getClass().getSimpleName(), this.getClass().getSimpleName()); + logHits(mir); setDamaged(true); } @Override public void collisionResolve(SpaceStationIss iss) { - LOGGER.info(AppConstants.HITS, " {} is damaged!", iss.getClass().getSimpleName(), - this.getClass().getSimpleName(), this.getClass().getSimpleName()); + logHits(iss); setDamaged(true); } -} + + private void logHits(GameObject gameObject) { + LOGGER.info(AppConstants.HITS, " {} is damaged!", gameObject.getClass().getSimpleName(), + this.getClass().getSimpleName(), this.getClass().getSimpleName()); + } +} \ No newline at end of file diff --git a/embedded-value/src/main/java/com/iluwatar/embedded/value/App.java b/embedded-value/src/main/java/com/iluwatar/embedded/value/App.java index 07dbacd09..a55c8d0e0 100644 --- a/embedded-value/src/main/java/com/iluwatar/embedded/value/App.java +++ b/embedded-value/src/main/java/com/iluwatar/embedded/value/App.java @@ -40,6 +40,10 @@ import lombok.extern.slf4j.Slf4j; */ @Slf4j public class App { + + private static final String BANGLORE = "Banglore"; + private static final String KARNATAKA = "Karnataka"; + /** * Program entry point. @@ -53,11 +57,11 @@ public class App { // Orders to insert into database final var order1 = new Order("JBL headphone", "Ram", - new ShippingAddress("Bangalore", "Karnataka", "560040")); + new ShippingAddress(BANGLORE, KARNATAKA, "560040")); final var order2 = new Order("MacBook Pro", "Manjunath", - new ShippingAddress("Bangalore", "Karnataka", "581204")); + new ShippingAddress(BANGLORE, KARNATAKA, "581204")); final var order3 = new Order("Carrie Soto is Back", "Shiva", - new ShippingAddress("Bangalore", "Karnataka", "560004")); + new ShippingAddress(BANGLORE, KARNATAKA, "560004")); // Create table for orders - Orders(id, name, orderedBy, city, state, pincode). // We can see that table is different from the Order object we have. @@ -102,4 +106,4 @@ public class App { LOGGER.error("Error deleting table"); } } -} +} \ No newline at end of file diff --git a/embedded-value/src/main/java/com/iluwatar/embedded/value/DataSource.java b/embedded-value/src/main/java/com/iluwatar/embedded/value/DataSource.java index 6aac60735..111c652fd 100644 --- a/embedded-value/src/main/java/com/iluwatar/embedded/value/DataSource.java +++ b/embedded-value/src/main/java/com/iluwatar/embedded/value/DataSource.java @@ -24,6 +24,8 @@ */ package com.iluwatar.embedded.value; +import static java.sql.PreparedStatement.RETURN_GENERATED_KEYS; + import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; @@ -33,6 +35,8 @@ import java.util.ArrayList; import java.util.stream.Stream; import lombok.extern.slf4j.Slf4j; + + /** * Communicates with H2 database with the help of JDBC API. * Inherits the SQL queries and methods from @link AbstractDataSource class. @@ -68,7 +72,7 @@ public class DataSource implements DataSourceInterface { public boolean createSchema() { try (Statement createschema = conn.createStatement()) { createschema.execute(CREATE_SCHEMA); - insertIntoOrders = conn.prepareStatement(INSERT_ORDER, PreparedStatement.RETURN_GENERATED_KEYS); + insertIntoOrders = conn.prepareStatement(INSERT_ORDER, RETURN_GENERATED_KEYS); getschema = conn.createStatement(); queryOrders = conn.createStatement(); removeorder = conn.prepareStatement(REMOVE_ORDER); @@ -204,4 +208,4 @@ public class DataSource implements DataSourceInterface { } return false; } -} +} \ No newline at end of file diff --git a/embedded-value/src/test/java/com/iluwatar/embedded/value/AppTest.java b/embedded-value/src/test/java/com/iluwatar/embedded/value/AppTest.java index 1e97bfabc..ae2d9c071 100644 --- a/embedded-value/src/test/java/com/iluwatar/embedded/value/AppTest.java +++ b/embedded-value/src/test/java/com/iluwatar/embedded/value/AppTest.java @@ -32,10 +32,10 @@ import org.junit.jupiter.api.Test; * Check whether the execution of the main method in {@link App} * throws an exception. */ -public class AppTest { +class AppTest { @Test - public void doesNotThrowException() { + void doesNotThrowException() { assertDoesNotThrow(() -> App.main(new String[] {})); } -} +} \ No newline at end of file diff --git a/event-based-asynchronous/pom.xml b/event-based-asynchronous/pom.xml index 22471b72b..45475d35d 100644 --- a/event-based-asynchronous/pom.xml +++ b/event-based-asynchronous/pom.xml @@ -39,6 +39,12 @@ junit-jupiter-engine test + + org.awaitility + awaitility + 4.2.0 + test + @@ -59,4 +65,4 @@ - + \ No newline at end of file diff --git a/event-based-asynchronous/src/main/java/com/iluwatar/event/asynchronous/App.java b/event-based-asynchronous/src/main/java/com/iluwatar/event/asynchronous/App.java index 33a61def5..fd94357d0 100644 --- a/event-based-asynchronous/src/main/java/com/iluwatar/event/asynchronous/App.java +++ b/event-based-asynchronous/src/main/java/com/iluwatar/event/asynchronous/App.java @@ -25,6 +25,7 @@ package com.iluwatar.event.asynchronous; import java.io.IOException; +import java.time.Duration; import java.util.Properties; import java.util.Scanner; import lombok.extern.slf4j.Slf4j; @@ -115,13 +116,13 @@ public class App { try { // Create an Asynchronous event. - var asyncEventId = eventManager.createAsync(60); + var asyncEventId = eventManager.createAsync(Duration.ofSeconds(60)); LOGGER.info("Async Event [{}] has been created.", asyncEventId); eventManager.start(asyncEventId); LOGGER.info("Async Event [{}] has been started.", asyncEventId); // Create a Synchronous event. - var syncEventId = eventManager.create(60); + var syncEventId = eventManager.create(Duration.ofSeconds(60)); LOGGER.info("Sync Event [{}] has been created.", syncEventId); eventManager.start(syncEventId); LOGGER.info("Sync Event [{}] has been started.", syncEventId); @@ -207,7 +208,7 @@ public class App { LOGGER.info("Boil multiple eggs at once (A) or boil them one-by-one (S)?: "); var eventType = s.nextLine(); LOGGER.info("How long should this egg be boiled for (in seconds)?: "); - var eventTime = s.nextInt(); + var eventTime = Duration.ofSeconds(s.nextInt()); if (eventType.equalsIgnoreCase("A")) { try { var eventId = eventManager.createAsync(eventTime); @@ -231,4 +232,4 @@ public class App { } } -} +} \ No newline at end of file diff --git a/event-based-asynchronous/src/main/java/com/iluwatar/event/asynchronous/AsyncEvent.java b/event-based-asynchronous/src/main/java/com/iluwatar/event/asynchronous/AsyncEvent.java index 10177c6e2..7537afd44 100644 --- a/event-based-asynchronous/src/main/java/com/iluwatar/event/asynchronous/AsyncEvent.java +++ b/event-based-asynchronous/src/main/java/com/iluwatar/event/asynchronous/AsyncEvent.java @@ -24,6 +24,8 @@ */ package com.iluwatar.event.asynchronous; +import java.time.Duration; +import java.time.Instant; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import lombok.Getter; @@ -38,11 +40,11 @@ import lombok.extern.slf4j.Slf4j; public class AsyncEvent implements Event, Runnable { private final int eventId; - private final int eventTime; + private final Duration eventTime; @Getter private final boolean synchronous; private Thread thread; - private AtomicBoolean isComplete = new AtomicBoolean(false); + private final AtomicBoolean isComplete = new AtomicBoolean(false); private ThreadCompleteListener eventListener; @Override @@ -71,9 +73,9 @@ public class AsyncEvent implements Event, Runnable { @Override public void run() { - var currentTime = System.currentTimeMillis(); - var endTime = currentTime + (eventTime * 1000L); - while (System.currentTimeMillis() < endTime) { + var currentTime = Instant.now(); + var endTime = currentTime.plusSeconds(eventTime.getSeconds()); + while (Instant.now().compareTo(endTime) < 0) { try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { @@ -90,13 +92,9 @@ public class AsyncEvent implements Event, Runnable { this.eventListener = listener; } - public final void removeListener() { - this.eventListener = null; - } - private void completed() { if (eventListener != null) { eventListener.completedEventHandler(eventId); } } -} +} \ No newline at end of file diff --git a/event-based-asynchronous/src/main/java/com/iluwatar/event/asynchronous/EventManager.java b/event-based-asynchronous/src/main/java/com/iluwatar/event/asynchronous/EventManager.java index b6c773db2..44561d6e2 100644 --- a/event-based-asynchronous/src/main/java/com/iluwatar/event/asynchronous/EventManager.java +++ b/event-based-asynchronous/src/main/java/com/iluwatar/event/asynchronous/EventManager.java @@ -25,6 +25,7 @@ package com.iluwatar.event.asynchronous; import java.security.SecureRandom; +import java.time.Duration; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import lombok.Getter; @@ -43,7 +44,7 @@ public class EventManager implements ThreadCompleteListener { // Just don't want to have too many running events. :) public static final int MIN_ID = 1; public static final int MAX_ID = MAX_RUNNING_EVENTS; - public static final int MAX_EVENT_TIME = 1800; // in seconds / 30 minutes. + public static final Duration MAX_EVENT_TIME = Duration.ofSeconds(1800); // 30 minutes. private int currentlyRunningSyncEvent = -1; private final SecureRandom rand; @@ -71,7 +72,7 @@ public class EventManager implements ThreadCompleteListener { * already running. * @throws LongRunningEventException Long-running events are not allowed in the app. */ - public int create(int eventTime) + public int create(Duration eventTime) throws MaxNumOfEventsAllowedException, InvalidOperationException, LongRunningEventException { if (currentlyRunningSyncEvent != -1) { throw new InvalidOperationException("Event [" + currentlyRunningSyncEvent + "] is still" @@ -92,19 +93,23 @@ public class EventManager implements ThreadCompleteListener { * @throws MaxNumOfEventsAllowedException When too many events are running at a time. * @throws LongRunningEventException Long-running events are not allowed in the app. */ - public int createAsync(int eventTime) throws MaxNumOfEventsAllowedException, + public int createAsync(Duration eventTime) throws MaxNumOfEventsAllowedException, LongRunningEventException { return createEvent(eventTime, false); } - private int createEvent(int eventTime, boolean isSynchronous) + private int createEvent(Duration eventTime, boolean isSynchronous) throws MaxNumOfEventsAllowedException, LongRunningEventException { + if (eventTime.isNegative()) { + throw new IllegalArgumentException("eventTime cannot be negative"); + } + if (eventPool.size() == MAX_RUNNING_EVENTS) { throw new MaxNumOfEventsAllowedException("Too many events are running at the moment." + " Please try again later."); } - if (eventTime >= MAX_EVENT_TIME) { + if (eventTime.getSeconds() > MAX_EVENT_TIME.getSeconds()) { throw new LongRunningEventException( "Maximum event time allowed is " + MAX_EVENT_TIME + " seconds. Please try again."); } @@ -215,4 +220,4 @@ public class EventManager implements ThreadCompleteListener { public int numOfCurrentlyRunningSyncEvent() { return currentlyRunningSyncEvent; } -} +} \ No newline at end of file diff --git a/event-based-asynchronous/src/test/java/com/iluwatar/event/asynchronous/EventAsynchronousTest.java b/event-based-asynchronous/src/test/java/com/iluwatar/event/asynchronous/EventAsynchronousTest.java index a6a5eb0c6..5de006341 100644 --- a/event-based-asynchronous/src/test/java/com/iluwatar/event/asynchronous/EventAsynchronousTest.java +++ b/event-based-asynchronous/src/test/java/com/iluwatar/event/asynchronous/EventAsynchronousTest.java @@ -24,142 +24,109 @@ */ package com.iluwatar.event.asynchronous; +import static org.awaitility.Awaitility.await; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import lombok.SneakyThrows; import org.junit.jupiter.api.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import java.time.Duration; /** * Application test */ class EventAsynchronousTest { - private static final Logger LOGGER = LoggerFactory.getLogger(EventAsynchronousTest.class); @Test + @SneakyThrows void testAsynchronousEvent() { var eventManager = new EventManager(); - try { - var aEventId = eventManager.createAsync(60); - eventManager.start(aEventId); - assertEquals(1, eventManager.getEventPool().size()); - assertTrue(eventManager.getEventPool().size() < EventManager.MAX_RUNNING_EVENTS); - assertEquals(-1, eventManager.numOfCurrentlyRunningSyncEvent()); - eventManager.cancel(aEventId); - assertTrue(eventManager.getEventPool().isEmpty()); - } catch (MaxNumOfEventsAllowedException | LongRunningEventException | EventDoesNotExistException e) { - LOGGER.error(e.getMessage()); - } + var aEventId = eventManager.createAsync(Duration.ofSeconds(60)); + + assertDoesNotThrow(() ->eventManager.start(aEventId)); + + assertEquals(1, eventManager.getEventPool().size()); + assertTrue(eventManager.getEventPool().size() < EventManager.MAX_RUNNING_EVENTS); + assertEquals(-1, eventManager.numOfCurrentlyRunningSyncEvent()); + + assertDoesNotThrow(() -> eventManager.cancel(aEventId)); + assertTrue(eventManager.getEventPool().isEmpty()); + } @Test + @SneakyThrows void testSynchronousEvent() { var eventManager = new EventManager(); - try { - var sEventId = eventManager.create(60); - eventManager.start(sEventId); - assertEquals(1, eventManager.getEventPool().size()); - assertTrue(eventManager.getEventPool().size() < EventManager.MAX_RUNNING_EVENTS); - assertNotEquals(-1, eventManager.numOfCurrentlyRunningSyncEvent()); - eventManager.cancel(sEventId); - assertTrue(eventManager.getEventPool().isEmpty()); - } catch (MaxNumOfEventsAllowedException | LongRunningEventException | EventDoesNotExistException - | InvalidOperationException e) { - LOGGER.error(e.getMessage()); - } + var sEventId = eventManager.create(Duration.ofSeconds(60)); + + assertDoesNotThrow(() -> eventManager.start(sEventId)); + assertEquals(1, eventManager.getEventPool().size()); + assertTrue(eventManager.getEventPool().size() < EventManager.MAX_RUNNING_EVENTS); + assertNotEquals(-1, eventManager.numOfCurrentlyRunningSyncEvent()); + + assertDoesNotThrow(() -> eventManager.cancel(sEventId)); + assertTrue(eventManager.getEventPool().isEmpty()); + } @Test + @SneakyThrows + void testFullSynchronousEvent() { + var eventManager = new EventManager(); + + var eventTime = Duration.ofSeconds(1); + + var sEventId = eventManager.create(eventTime); + assertEquals(1, eventManager.getEventPool().size()); + + eventManager.start(sEventId); + + await().until(() -> eventManager.getEventPool().isEmpty()); + + } + + @Test + @SneakyThrows void testUnsuccessfulSynchronousEvent() { assertThrows(InvalidOperationException.class, () -> { var eventManager = new EventManager(); - try { - var sEventId = eventManager.create(60); - eventManager.start(sEventId); - sEventId = eventManager.create(60); - eventManager.start(sEventId); - } catch (MaxNumOfEventsAllowedException | LongRunningEventException | EventDoesNotExistException e) { - LOGGER.error(e.getMessage()); - } + + var sEventId = assertDoesNotThrow(() -> eventManager.create(Duration.ofSeconds(60))); + eventManager.start(sEventId); + sEventId = eventManager.create(Duration.ofSeconds(60)); + eventManager.start(sEventId); + }); } @Test - void testFullSynchronousEvent() { - var eventManager = new EventManager(); - try { - var eventTime = 1; - - var sEventId = eventManager.create(eventTime); - assertEquals(1, eventManager.getEventPool().size()); - eventManager.start(sEventId); - - var currentTime = System.currentTimeMillis(); - // +2 to give a bit of buffer time for event to complete properly. - var endTime = currentTime + (eventTime + 2 * 1000); - - long sleepTime = endTime - System.currentTimeMillis(); - if (sleepTime > 0) { - try { - Thread.sleep(sleepTime); - } catch (InterruptedException e) { - LOGGER.error("Thread interrupted: ", e); - Thread.currentThread().interrupt(); - } - } - - assertTrue(eventManager.getEventPool().isEmpty()); - - } catch (MaxNumOfEventsAllowedException | LongRunningEventException | EventDoesNotExistException - | InvalidOperationException e) { - LOGGER.error(e.getMessage()); - } - } - - @Test + @SneakyThrows void testFullAsynchronousEvent() { var eventManager = new EventManager(); - try { - var eventTime = 1; + var eventTime = Duration.ofSeconds(1); - var aEventId1 = eventManager.createAsync(eventTime); - var aEventId2 = eventManager.createAsync(eventTime); - var aEventId3 = eventManager.createAsync(eventTime); - assertEquals(3, eventManager.getEventPool().size()); + var aEventId1 = assertDoesNotThrow(() -> eventManager.createAsync(eventTime)); + var aEventId2 = assertDoesNotThrow(() -> eventManager.createAsync(eventTime)); + var aEventId3 = assertDoesNotThrow(() -> eventManager.createAsync(eventTime)); + assertEquals(3, eventManager.getEventPool().size()); - eventManager.start(aEventId1); - eventManager.start(aEventId2); - eventManager.start(aEventId3); + eventManager.start(aEventId1); + eventManager.start(aEventId2); + eventManager.start(aEventId3); - var currentTime = System.currentTimeMillis(); - // +2 to give a bit of buffer time for event to complete properly. - var endTime = currentTime + (eventTime + 2 * 1000); + await().until(() -> eventManager.getEventPool().isEmpty()); - long sleepTime = endTime - System.currentTimeMillis(); - if (sleepTime > 0) { - try { - Thread.sleep(sleepTime); - } catch (InterruptedException e) { - LOGGER.error("Thread interrupted: ", e); - Thread.currentThread().interrupt(); - } - } - - assertTrue(eventManager.getEventPool().isEmpty()); - - } catch (MaxNumOfEventsAllowedException | LongRunningEventException | EventDoesNotExistException e) { - LOGGER.error(e.getMessage()); - } } @Test void testLongRunningEventException(){ assertThrows(LongRunningEventException.class, () -> { var eventManager = new EventManager(); - eventManager.createAsync(2000); + eventManager.createAsync(Duration.ofMinutes(31)); }); } @@ -169,7 +136,7 @@ class EventAsynchronousTest { assertThrows(MaxNumOfEventsAllowedException.class, () -> { final var eventManager = new EventManager(); for(int i=0;i<1100;i++){ - eventManager.createAsync(i); + eventManager.createAsync(Duration.ofSeconds(i)); } }); } diff --git a/execute-around/src/test/java/com/iluwatar/execute/around/SimpleFileWriterTest.java b/execute-around/src/test/java/com/iluwatar/execute/around/SimpleFileWriterTest.java index e9ca45f05..df2452716 100644 --- a/execute-around/src/test/java/com/iluwatar/execute/around/SimpleFileWriterTest.java +++ b/execute-around/src/test/java/com/iluwatar/execute/around/SimpleFileWriterTest.java @@ -31,6 +31,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.File; import java.io.IOException; import java.nio.file.Files; +import lombok.SneakyThrows; import org.junit.Rule; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; @@ -74,15 +75,12 @@ class SimpleFileWriterTest { assertTrue(Files.lines(temporaryFile.toPath()).allMatch(testMessage::equals)); } + @Test + @SneakyThrows void testRipplesIoExceptionOccurredWhileWriting() { var message = "Some error"; - assertThrows(IOException.class, () -> { - final var temporaryFile = this.testFolder.newFile(); - new SimpleFileWriter(temporaryFile.getPath(), writer -> { - throw new IOException(message); - }); - }, message); + final var temporaryFile = this.testFolder.newFile(); + assertThrows(IOException.class, () -> new SimpleFileWriter(temporaryFile.getPath(), writer -> {throw new IOException("error");}), message); } - -} +} \ No newline at end of file diff --git a/health-check/src/main/java/com/iluwatar/health/check/CpuHealthIndicator.java b/health-check/src/main/java/com/iluwatar/health/check/CpuHealthIndicator.java index b2f3ab1b3..313614db0 100644 --- a/health-check/src/main/java/com/iluwatar/health/check/CpuHealthIndicator.java +++ b/health-check/src/main/java/com/iluwatar/health/check/CpuHealthIndicator.java @@ -79,13 +79,6 @@ public class CpuHealthIndicator implements HealthIndicator { @Value("${cpu.load.average.threshold:0.75}") private double loadAverageThreshold; - /** - * The warning message to include in the health indicator's response when the load average is high - * but not exceeding the threshold. - */ - @Value("${cpu.warning.message:High load average}") - private String defaultWarningMessage; - private static final String ERROR_MESSAGE = "error"; private static final String HIGH_SYSTEM_CPU_LOAD_MESSAGE = "High system CPU load: {}"; @@ -144,4 +137,4 @@ public class CpuHealthIndicator implements HealthIndicator { return Health.up().withDetails(details).build(); } } -} +} \ No newline at end of file diff --git a/model-view-intent/src/main/java/com/iluwatar/model/view/intent/CalculatorViewModel.java b/model-view-intent/src/main/java/com/iluwatar/model/view/intent/CalculatorViewModel.java index 3865ec30b..fc5d182ad 100644 --- a/model-view-intent/src/main/java/com/iluwatar/model/view/intent/CalculatorViewModel.java +++ b/model-view-intent/src/main/java/com/iluwatar/model/view/intent/CalculatorViewModel.java @@ -50,17 +50,16 @@ public final class CalculatorViewModel { */ void handleAction(final CalculatorAction action) { switch (action.tag()) { - case AdditionCalculatorAction.TAG -> add(); - case SubtractionCalculatorAction.TAG -> subtract(); - case MultiplicationCalculatorAction.TAG -> multiply(); - case DivisionCalculatorAction.TAG -> divide(); - case SetVariableCalculatorAction.TAG -> { + case AdditionCalculatorAction.ADDITION -> add(); + case SubtractionCalculatorAction.SUBTRACTION -> subtract(); + case MultiplicationCalculatorAction.MULTIPLICATION -> multiply(); + case DivisionCalculatorAction.DIVISION -> divide(); + case SetVariableCalculatorAction.SET_VARIABLE -> { SetVariableCalculatorAction setVariableAction = (SetVariableCalculatorAction) action; setVariable(setVariableAction.getVariable()); } - default -> { - } + default -> throw new IllegalArgumentException("Unknown tag"); } } @@ -124,4 +123,4 @@ public final class CalculatorViewModel { model.getOutput() / model.getVariable() ); } -} +} \ No newline at end of file diff --git a/model-view-intent/src/main/java/com/iluwatar/model/view/intent/actions/AdditionCalculatorAction.java b/model-view-intent/src/main/java/com/iluwatar/model/view/intent/actions/AdditionCalculatorAction.java index 2a57ba320..a93308e7f 100644 --- a/model-view-intent/src/main/java/com/iluwatar/model/view/intent/actions/AdditionCalculatorAction.java +++ b/model-view-intent/src/main/java/com/iluwatar/model/view/intent/actions/AdditionCalculatorAction.java @@ -31,13 +31,13 @@ public class AdditionCalculatorAction implements CalculatorAction { /** * Subclass tag. * */ - public static final String TAG = "ADDITION"; + public static final String ADDITION = "ADDITION"; /** * Makes checking subclass type trivial. * */ @Override public String tag() { - return TAG; + return ADDITION; } -} +} \ No newline at end of file diff --git a/model-view-intent/src/main/java/com/iluwatar/model/view/intent/actions/DivisionCalculatorAction.java b/model-view-intent/src/main/java/com/iluwatar/model/view/intent/actions/DivisionCalculatorAction.java index 787de2d02..7622e4f2f 100644 --- a/model-view-intent/src/main/java/com/iluwatar/model/view/intent/actions/DivisionCalculatorAction.java +++ b/model-view-intent/src/main/java/com/iluwatar/model/view/intent/actions/DivisionCalculatorAction.java @@ -31,13 +31,13 @@ public class DivisionCalculatorAction implements CalculatorAction { /** * Subclass tag. * */ - public static final String TAG = "DIVISION"; + public static final String DIVISION = "DIVISION"; /** * Makes checking subclass type trivial. * */ @Override public String tag() { - return TAG; + return DIVISION; } -} +} \ No newline at end of file diff --git a/model-view-intent/src/main/java/com/iluwatar/model/view/intent/actions/MultiplicationCalculatorAction.java b/model-view-intent/src/main/java/com/iluwatar/model/view/intent/actions/MultiplicationCalculatorAction.java index 6287bfdcf..a163bd5d6 100644 --- a/model-view-intent/src/main/java/com/iluwatar/model/view/intent/actions/MultiplicationCalculatorAction.java +++ b/model-view-intent/src/main/java/com/iluwatar/model/view/intent/actions/MultiplicationCalculatorAction.java @@ -31,13 +31,13 @@ public class MultiplicationCalculatorAction implements CalculatorAction { /** * Subclass tag. * */ - public static final String TAG = "MULTIPLICATION"; + public static final String MULTIPLICATION = "MULTIPLICATION"; /** * Makes checking subclass type trivial. * */ @Override public String tag() { - return TAG; + return MULTIPLICATION; } -} +} \ No newline at end of file diff --git a/model-view-intent/src/main/java/com/iluwatar/model/view/intent/actions/SetVariableCalculatorAction.java b/model-view-intent/src/main/java/com/iluwatar/model/view/intent/actions/SetVariableCalculatorAction.java index 0876d2be2..c178d5400 100644 --- a/model-view-intent/src/main/java/com/iluwatar/model/view/intent/actions/SetVariableCalculatorAction.java +++ b/model-view-intent/src/main/java/com/iluwatar/model/view/intent/actions/SetVariableCalculatorAction.java @@ -36,7 +36,7 @@ public final class SetVariableCalculatorAction implements CalculatorAction { /** * Subclass tag. */ - public static final String TAG = "SET_VARIABLE"; + public static final String SET_VARIABLE = "SET_VARIABLE"; /** * Used by {@link com.iluwatar.model.view.intent.CalculatorViewModel}. @@ -49,6 +49,6 @@ public final class SetVariableCalculatorAction implements CalculatorAction { */ @Override public String tag() { - return TAG; + return SET_VARIABLE; } -} +} \ No newline at end of file diff --git a/model-view-intent/src/main/java/com/iluwatar/model/view/intent/actions/SubtractionCalculatorAction.java b/model-view-intent/src/main/java/com/iluwatar/model/view/intent/actions/SubtractionCalculatorAction.java index 2a8b7f420..68c576ed1 100644 --- a/model-view-intent/src/main/java/com/iluwatar/model/view/intent/actions/SubtractionCalculatorAction.java +++ b/model-view-intent/src/main/java/com/iluwatar/model/view/intent/actions/SubtractionCalculatorAction.java @@ -31,13 +31,13 @@ public class SubtractionCalculatorAction implements CalculatorAction { /** * Subclass tag. * */ - public static final String TAG = "SUBTRACTION"; + public static final String SUBTRACTION = "SUBTRACTION"; /** * Makes checking subclass type trivial. * */ @Override public String tag() { - return TAG; + return SUBTRACTION; } -} +} \ No newline at end of file diff --git a/model-view-intent/src/test/java/com/iluwatar/model/view/intent/CalculatorViewModelTest.java b/model-view-intent/src/test/java/com/iluwatar/model/view/intent/CalculatorViewModelTest.java index ae61d104b..453def145 100644 --- a/model-view-intent/src/test/java/com/iluwatar/model/view/intent/CalculatorViewModelTest.java +++ b/model-view-intent/src/test/java/com/iluwatar/model/view/intent/CalculatorViewModelTest.java @@ -29,7 +29,9 @@ import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; -public class CalculatorViewModelTest { +import static org.junit.jupiter.api.Assertions.assertEquals; + +class CalculatorViewModelTest { private CalculatorModel modelAfterExecutingActions(List actions) { CalculatorViewModel viewModel = new CalculatorViewModel(); @@ -42,7 +44,8 @@ public class CalculatorViewModelTest { @Test void testSetup() { CalculatorModel model = modelAfterExecutingActions(new ArrayList<>()); - assert model.getVariable() == 0 && model.getOutput() == 0; + assertEquals(0, model.getVariable()); + assertEquals(0, model.getOutput()); } @Test @@ -51,7 +54,8 @@ public class CalculatorViewModelTest { new SetVariableCalculatorAction(10.0) ); CalculatorModel model = modelAfterExecutingActions(actions); - assert model.getVariable() == 10.0 && model.getOutput() == 0; + assertEquals(10.0, model.getVariable()); + assertEquals(0, model.getOutput()); } @Test @@ -64,7 +68,8 @@ public class CalculatorViewModelTest { new AdditionCalculatorAction() ); CalculatorModel model = modelAfterExecutingActions(actions); - assert model.getVariable() == 7.0 && model.getOutput() == 11.0; + assertEquals(7.0, model.getVariable()); + assertEquals(11.0, model.getOutput()); } @Test @@ -76,7 +81,8 @@ public class CalculatorViewModelTest { new SubtractionCalculatorAction() ); CalculatorModel model = modelAfterExecutingActions(actions); - assert model.getVariable() == 2.0 && model.getOutput() == 2.0; + assertEquals(2.0, model.getVariable()); + assertEquals(2.0, model.getOutput()); } @Test @@ -88,7 +94,8 @@ public class CalculatorViewModelTest { new MultiplicationCalculatorAction() ); CalculatorModel model = modelAfterExecutingActions(actions); - assert model.getVariable() == 2.0 && model.getOutput() == 8.0; + assertEquals(2.0, model.getVariable()); + assertEquals(8.0, model.getOutput()); } @Test @@ -101,6 +108,7 @@ public class CalculatorViewModelTest { new DivisionCalculatorAction() ); CalculatorModel model = modelAfterExecutingActions(actions); - assert model.getVariable() == 2.0 && model.getOutput() == 2.0; + assertEquals(2.0, model.getVariable()); + assertEquals(2.0, model.getOutput()); } -} +} \ No newline at end of file diff --git a/page-controller/src/main/java/com.iluwatar.page.controller/App.java b/page-controller/src/main/java/com/iluwatar/page/controller/App.java similarity index 100% rename from page-controller/src/main/java/com.iluwatar.page.controller/App.java rename to page-controller/src/main/java/com/iluwatar/page/controller/App.java diff --git a/page-controller/src/main/java/com.iluwatar.page.controller/SignupController.java b/page-controller/src/main/java/com/iluwatar/page/controller/SignupController.java similarity index 100% rename from page-controller/src/main/java/com.iluwatar.page.controller/SignupController.java rename to page-controller/src/main/java/com/iluwatar/page/controller/SignupController.java diff --git a/page-controller/src/main/java/com.iluwatar.page.controller/SignupModel.java b/page-controller/src/main/java/com/iluwatar/page/controller/SignupModel.java similarity index 94% rename from page-controller/src/main/java/com.iluwatar.page.controller/SignupModel.java rename to page-controller/src/main/java/com/iluwatar/page/controller/SignupModel.java index 97229c402..ee9c2e1ce 100644 --- a/page-controller/src/main/java/com.iluwatar.page.controller/SignupModel.java +++ b/page-controller/src/main/java/com/iluwatar/page/controller/SignupModel.java @@ -24,21 +24,19 @@ */ package com.iluwatar.page.controller; -import lombok.Getter; -import lombok.Setter; +import lombok.Data; +import lombok.NoArgsConstructor; import org.springframework.stereotype.Component; /** * ignup model. */ @Component -@Getter -@Setter +@Data +@NoArgsConstructor public class SignupModel { private String name; private String email; private String password; - public SignupModel() { - } -} +} \ No newline at end of file diff --git a/page-controller/src/main/java/com.iluwatar.page.controller/SignupView.java b/page-controller/src/main/java/com/iluwatar/page/controller/SignupView.java similarity index 97% rename from page-controller/src/main/java/com.iluwatar.page.controller/SignupView.java rename to page-controller/src/main/java/com/iluwatar/page/controller/SignupView.java index 5d127ea2a..c295fa471 100644 --- a/page-controller/src/main/java/com.iluwatar.page.controller/SignupView.java +++ b/page-controller/src/main/java/com/iluwatar/page/controller/SignupView.java @@ -24,15 +24,15 @@ */ package com.iluwatar.page.controller; +import lombok.NoArgsConstructor; import lombok.extern.slf4j.Slf4j; /** * Signup View. */ @Slf4j +@NoArgsConstructor public class SignupView { - public SignupView() { - } public String display() { LOGGER.info("display signup front page"); @@ -46,4 +46,4 @@ public class SignupView { LOGGER.info("Redirect to user page with " + "name " + form.getName() + " email " + form.getEmail()); return "redirect:/user"; } -} +} \ No newline at end of file diff --git a/page-controller/src/main/java/com.iluwatar.page.controller/UserController.java b/page-controller/src/main/java/com/iluwatar/page/controller/UserController.java similarity index 97% rename from page-controller/src/main/java/com.iluwatar.page.controller/UserController.java rename to page-controller/src/main/java/com/iluwatar/page/controller/UserController.java index e3bcca6f1..0f4743778 100644 --- a/page-controller/src/main/java/com.iluwatar.page.controller/UserController.java +++ b/page-controller/src/main/java/com/iluwatar/page/controller/UserController.java @@ -24,6 +24,7 @@ */ package com.iluwatar.page.controller; +import lombok.NoArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; @@ -34,11 +35,10 @@ import org.springframework.web.bind.annotation.GetMapping; */ @Slf4j @Controller +@NoArgsConstructor public class UserController { private final UserView view = new UserView(); - public UserController() {} - /** * Handle http GET request and access view and model. */ @@ -48,4 +48,4 @@ public class UserController { model.addAttribute("email", form.getEmail()); return view.display(form); } -} +} \ No newline at end of file diff --git a/page-controller/src/main/java/com.iluwatar.page.controller/UserModel.java b/page-controller/src/main/java/com/iluwatar/page/controller/UserModel.java similarity index 94% rename from page-controller/src/main/java/com.iluwatar.page.controller/UserModel.java rename to page-controller/src/main/java/com/iluwatar/page/controller/UserModel.java index 86e9548a2..0f099b2e6 100644 --- a/page-controller/src/main/java/com.iluwatar.page.controller/UserModel.java +++ b/page-controller/src/main/java/com/iluwatar/page/controller/UserModel.java @@ -24,17 +24,16 @@ */ package com.iluwatar.page.controller; -import lombok.Getter; -import lombok.Setter; +import lombok.Data; +import lombok.NoArgsConstructor; /** * User model. */ -@Getter -@Setter +@Data +@NoArgsConstructor public class UserModel { private String name; private String email; - - public UserModel() {} -} + +} \ No newline at end of file diff --git a/page-controller/src/main/java/com.iluwatar.page.controller/UserView.java b/page-controller/src/main/java/com/iluwatar/page/controller/UserView.java similarity index 100% rename from page-controller/src/main/java/com.iluwatar.page.controller/UserView.java rename to page-controller/src/main/java/com/iluwatar/page/controller/UserView.java diff --git a/role-object/src/main/java/com/iluwatar/roleobject/ApplicationRoleObject.java b/role-object/src/main/java/com/iluwatar/roleobject/ApplicationRoleObject.java index 51a106864..59537c767 100644 --- a/role-object/src/main/java/com/iluwatar/roleobject/ApplicationRoleObject.java +++ b/role-object/src/main/java/com/iluwatar/roleobject/ApplicationRoleObject.java @@ -24,8 +24,8 @@ */ package com.iluwatar.roleobject; -import static com.iluwatar.roleobject.Role.Borrower; -import static com.iluwatar.roleobject.Role.Investor; +import static com.iluwatar.roleobject.Role.BORROWER; +import static com.iluwatar.roleobject.Role.INVESTOR; import lombok.extern.slf4j.Slf4j; @@ -65,29 +65,29 @@ public class ApplicationRoleObject { * @param args program arguments */ public static void main(String[] args) { - var customer = Customer.newCustomer(Borrower, Investor); + var customer = Customer.newCustomer(BORROWER, INVESTOR); LOGGER.info(" the new customer created : {}", customer); - var hasBorrowerRole = customer.hasRole(Borrower); + var hasBorrowerRole = customer.hasRole(BORROWER); LOGGER.info(" customer has a borrowed role - {}", hasBorrowerRole); - var hasInvestorRole = customer.hasRole(Investor); + var hasInvestorRole = customer.hasRole(INVESTOR); LOGGER.info(" customer has an investor role - {}", hasInvestorRole); - customer.getRole(Investor, InvestorRole.class) + customer.getRole(INVESTOR, InvestorRole.class) .ifPresent(inv -> { inv.setAmountToInvest(1000); inv.setName("Billy"); }); - customer.getRole(Borrower, BorrowerRole.class) + customer.getRole(BORROWER, BorrowerRole.class) .ifPresent(inv -> inv.setName("Johny")); - customer.getRole(Investor, InvestorRole.class) + customer.getRole(INVESTOR, InvestorRole.class) .map(InvestorRole::invest) .ifPresent(LOGGER::info); - customer.getRole(Borrower, BorrowerRole.class) + customer.getRole(BORROWER, BorrowerRole.class) .map(BorrowerRole::borrow) .ifPresent(LOGGER::info); } -} +} \ No newline at end of file diff --git a/role-object/src/main/java/com/iluwatar/roleobject/Role.java b/role-object/src/main/java/com/iluwatar/roleobject/Role.java index de216b0d7..7a681f02a 100644 --- a/role-object/src/main/java/com/iluwatar/roleobject/Role.java +++ b/role-object/src/main/java/com/iluwatar/roleobject/Role.java @@ -34,7 +34,7 @@ import org.slf4j.LoggerFactory; */ public enum Role { - Borrower(BorrowerRole.class), Investor(InvestorRole.class); + BORROWER(BorrowerRole.class), INVESTOR(InvestorRole.class); private final Class typeCst; @@ -58,4 +58,4 @@ public enum Role { return Optional.empty(); } -} +} \ No newline at end of file diff --git a/role-object/src/test/java/com/iluwatar/roleobject/CustomerCoreTest.java b/role-object/src/test/java/com/iluwatar/roleobject/CustomerCoreTest.java index 544d72a9e..9cb10b8e1 100644 --- a/role-object/src/test/java/com/iluwatar/roleobject/CustomerCoreTest.java +++ b/role-object/src/test/java/com/iluwatar/roleobject/CustomerCoreTest.java @@ -35,55 +35,55 @@ class CustomerCoreTest { @Test void addRole() { var core = new CustomerCore(); - assertTrue(core.addRole(Role.Borrower)); + assertTrue(core.addRole(Role.BORROWER)); } @Test void hasRole() { var core = new CustomerCore(); - core.addRole(Role.Borrower); - assertTrue(core.hasRole(Role.Borrower)); - assertFalse(core.hasRole(Role.Investor)); + core.addRole(Role.BORROWER); + assertTrue(core.hasRole(Role.BORROWER)); + assertFalse(core.hasRole(Role.INVESTOR)); } @Test void remRole() { var core = new CustomerCore(); - core.addRole(Role.Borrower); + core.addRole(Role.BORROWER); - var bRole = core.getRole(Role.Borrower, BorrowerRole.class); + var bRole = core.getRole(Role.BORROWER, BorrowerRole.class); assertTrue(bRole.isPresent()); - assertTrue(core.remRole(Role.Borrower)); + assertTrue(core.remRole(Role.BORROWER)); - var empt = core.getRole(Role.Borrower, BorrowerRole.class); + var empt = core.getRole(Role.BORROWER, BorrowerRole.class); assertFalse(empt.isPresent()); } @Test void getRole() { var core = new CustomerCore(); - core.addRole(Role.Borrower); + core.addRole(Role.BORROWER); - var bRole = core.getRole(Role.Borrower, BorrowerRole.class); + var bRole = core.getRole(Role.BORROWER, BorrowerRole.class); assertTrue(bRole.isPresent()); - var nonRole = core.getRole(Role.Borrower, InvestorRole.class); + var nonRole = core.getRole(Role.BORROWER, InvestorRole.class); assertFalse(nonRole.isPresent()); - var invRole = core.getRole(Role.Investor, InvestorRole.class); + var invRole = core.getRole(Role.INVESTOR, InvestorRole.class); assertFalse(invRole.isPresent()); } @Test void toStringTest() { var core = new CustomerCore(); - core.addRole(Role.Borrower); - assertEquals("Customer{roles=[Borrower]}", core.toString()); + core.addRole(Role.BORROWER); + assertEquals("Customer{roles=[BORROWER]}", core.toString()); core = new CustomerCore(); - core.addRole(Role.Investor); - assertEquals("Customer{roles=[Investor]}", core.toString()); + core.addRole(Role.INVESTOR); + assertEquals("Customer{roles=[INVESTOR]}", core.toString()); core = new CustomerCore(); assertEquals("Customer{roles=[]}", core.toString()); diff --git a/role-object/src/test/java/com/iluwatar/roleobject/RoleTest.java b/role-object/src/test/java/com/iluwatar/roleobject/RoleTest.java index b501b469d..503685180 100644 --- a/role-object/src/test/java/com/iluwatar/roleobject/RoleTest.java +++ b/role-object/src/test/java/com/iluwatar/roleobject/RoleTest.java @@ -33,7 +33,7 @@ class RoleTest { @Test void instanceTest() { - var instance = Role.Borrower.instance(); + var instance = Role.BORROWER.instance(); assertTrue(instance.isPresent()); assertEquals(instance.get().getClass(), BorrowerRole.class); } diff --git a/strategy/src/main/java/com/iluwatar/strategy/App.java b/strategy/src/main/java/com/iluwatar/strategy/App.java index 0378f6eb3..aa603c106 100644 --- a/strategy/src/main/java/com/iluwatar/strategy/App.java +++ b/strategy/src/main/java/com/iluwatar/strategy/App.java @@ -79,13 +79,13 @@ public class App { // Java 8 lambda implementation with enum Strategy pattern LOGGER.info(GREEN_DRAGON_SPOTTED); - dragonSlayer.changeStrategy(LambdaStrategy.Strategy.MeleeStrategy); + dragonSlayer.changeStrategy(LambdaStrategy.Strategy.MELEE_STRATEGY); dragonSlayer.goToBattle(); LOGGER.info(RED_DRAGON_EMERGES); - dragonSlayer.changeStrategy(LambdaStrategy.Strategy.ProjectileStrategy); + dragonSlayer.changeStrategy(LambdaStrategy.Strategy.PROJECTILE_STRATEGY); dragonSlayer.goToBattle(); LOGGER.info(BLACK_DRAGON_LANDS); - dragonSlayer.changeStrategy(LambdaStrategy.Strategy.SpellStrategy); + dragonSlayer.changeStrategy(LambdaStrategy.Strategy.SPELL_STRATEGY); dragonSlayer.goToBattle(); } -} +} \ No newline at end of file diff --git a/strategy/src/main/java/com/iluwatar/strategy/LambdaStrategy.java b/strategy/src/main/java/com/iluwatar/strategy/LambdaStrategy.java index 698e1bb14..e31621db0 100644 --- a/strategy/src/main/java/com/iluwatar/strategy/LambdaStrategy.java +++ b/strategy/src/main/java/com/iluwatar/strategy/LambdaStrategy.java @@ -36,11 +36,11 @@ public class LambdaStrategy { * Enum to demonstrate strategy pattern. */ public enum Strategy implements DragonSlayingStrategy { - MeleeStrategy(() -> LOGGER.info( + MELEE_STRATEGY(() -> LOGGER.info( "With your Excalibur you severe the dragon's head!")), - ProjectileStrategy(() -> LOGGER.info( + PROJECTILE_STRATEGY(() -> LOGGER.info( "You shoot the dragon with the magical crossbow and it falls dead on the ground!")), - SpellStrategy(() -> LOGGER.info( + SPELL_STRATEGY(() -> LOGGER.info( "You cast the spell of disintegration and the dragon vaporizes in a pile of dust!")); private final DragonSlayingStrategy dragonSlayingStrategy; @@ -54,4 +54,4 @@ public class LambdaStrategy { dragonSlayingStrategy.execute(); } } -} +} \ No newline at end of file diff --git a/transaction-script/src/test/java/com/iluwatar/transactionscript/HotelTest.java b/transaction-script/src/test/java/com/iluwatar/transactionscript/HotelTest.java index e8a7f6a0b..4045ac3e3 100644 --- a/transaction-script/src/test/java/com/iluwatar/transactionscript/HotelTest.java +++ b/transaction-script/src/test/java/com/iluwatar/transactionscript/HotelTest.java @@ -30,6 +30,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.List; import javax.sql.DataSource; +import lombok.SneakyThrows; import org.h2.jdbcx.JdbcDataSource; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -58,49 +59,48 @@ class HotelTest { @Test void bookingRoomShouldChangeBookedStatusToTrue() throws Exception { hotel.bookRoom(1); + assertTrue(dao.getById(1).isPresent()); assertTrue(dao.getById(1).get().isBooked()); } - @Test() + @Test void bookingRoomWithInvalidIdShouldRaiseException() { - assertThrows(Exception.class, () -> { - hotel.bookRoom(getNonExistingRoomId()); - }); + assertThrows(Exception.class, () -> hotel.bookRoom(getNonExistingRoomId())); } - @Test() + + @Test + @SneakyThrows void bookingRoomAgainShouldRaiseException() { - assertThrows(Exception.class, () -> { - hotel.bookRoom(1); - hotel.bookRoom(1); - }); + hotel.bookRoom(1); + assertThrows(Exception.class, () -> hotel.bookRoom(1), "Room already booked!"); } @Test void NotBookingRoomShouldNotChangeBookedStatus() throws Exception { + assertTrue(dao.getById(1).isPresent()); assertFalse(dao.getById(1).get().isBooked()); } @Test void cancelRoomBookingShouldChangeBookedStatus() throws Exception { hotel.bookRoom(1); + assertTrue(dao.getById(1).isPresent()); assertTrue(dao.getById(1).get().isBooked()); + hotel.cancelRoomBooking(1); + assertTrue(dao.getById(1).isPresent()); assertFalse(dao.getById(1).get().isBooked()); } @Test void cancelRoomBookingWithInvalidIdShouldRaiseException() { - assertThrows(Exception.class, () -> { - hotel.cancelRoomBooking(getNonExistingRoomId()); - }); + assertThrows(Exception.class, () -> hotel.cancelRoomBooking(getNonExistingRoomId())); } @Test void cancelRoomBookingForUnbookedRoomShouldRaiseException() { - assertThrows(Exception.class, () -> { - hotel.cancelRoomBooking(1); - }); + assertThrows(Exception.class, () -> hotel.cancelRoomBooking(1)); } @@ -150,4 +150,4 @@ class HotelTest { private int getNonExistingRoomId() { return 999; } -} +} \ No newline at end of file diff --git a/typeobjectpattern/src/main/java/com/iluwatar/typeobject/CandyGame.java b/typeobjectpattern/src/main/java/com/iluwatar/typeobject/CandyGame.java index 9e3568e65..85d39c8c7 100644 --- a/typeobjectpattern/src/main/java/com/iluwatar/typeobject/CandyGame.java +++ b/typeobjectpattern/src/main/java/com/iluwatar/typeobject/CandyGame.java @@ -35,6 +35,7 @@ import lombok.extern.slf4j.Slf4j; */ @Slf4j +@SuppressWarnings("java:S3776") //"Cognitive Complexity of methods should not be too high" public class CandyGame { Cell[][] cells; @@ -169,4 +170,4 @@ public class CandyGame { } } -} +} \ No newline at end of file