diff --git a/commander/src/main/java/com/iluwatar/commander/Commander.java b/commander/src/main/java/com/iluwatar/commander/Commander.java
index 41779c076..2909f9304 100644
--- a/commander/src/main/java/com/iluwatar/commander/Commander.java
+++ b/commander/src/main/java/com/iluwatar/commander/Commander.java
@@ -36,9 +36,11 @@ import com.iluwatar.commander.queue.QueueDatabase;
import com.iluwatar.commander.queue.QueueTask;
import com.iluwatar.commander.queue.QueueTask.TaskType;
import com.iluwatar.commander.shippingservice.ShippingService;
+import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+
/**
* Commander pattern is used to handle all issues that can come up while making a
* distributed transaction. The idea is to have a commander, which coordinates the execution of all
@@ -159,8 +161,8 @@ public class Commander {
private void sendPaymentRequest(Order order) {
if (System.currentTimeMillis() - order.createdTime >= this.paymentTime) {
- if (order.paid.equals(PaymentStatus.Trying)) {
- order.paid = PaymentStatus.NotDone;
+ if (order.paid.equals(PaymentStatus.TRYING)) {
+ order.paid = PaymentStatus.NOT_DONE;
sendPaymentFailureMessage(order);
LOG.error("Order " + order.id + ": Payment time for order over, failed and returning..");
} //if succeeded or failed, would have been dequeued, no attempt to make payment
@@ -172,15 +174,15 @@ public class Commander {
if (!l.isEmpty()) {
if (DatabaseUnavailableException.class.isAssignableFrom(l.get(0).getClass())) {
LOG.debug("Order " + order.id + ": Error in connecting to payment service,"
- + " trying again..");
+ + " trying again..");
} else {
LOG.debug("Order " + order.id + ": Error in creating payment request..");
}
throw l.remove(0);
}
- if (order.paid.equals(PaymentStatus.Trying)) {
+ if (order.paid.equals(PaymentStatus.TRYING)) {
var transactionId = paymentService.receiveRequest(order.price);
- order.paid = PaymentStatus.Done;
+ order.paid = PaymentStatus.DONE;
LOG.info("Order " + order.id + ": Payment successful, transaction Id: " + transactionId);
if (!finalSiteMsgShown) {
LOG.info("Payment made successfully, thank you for shopping with us!!");
@@ -193,26 +195,26 @@ public class Commander {
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.");
+ + "may have been incorrect. "
+ + "Meanwhile, your order has been converted to COD and will be shipped.");
finalSiteMsgShown = true;
}
LOG.error("Order " + order.id + ": Payment details incorrect, failed..");
- o.paid = PaymentStatus.NotDone;
+ o.paid = PaymentStatus.NOT_DONE;
sendPaymentFailureMessage(o);
} else {
- if (o.messageSent.equals(MessageSent.NoneSent)) {
+ 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.");
+ + "asap. Don't worry, your order has been placed and will be shipped.");
finalSiteMsgShown = true;
}
LOG.warn("Order " + order.id + ": Payment error, going to queue..");
sendPaymentPossibleErrorMsg(o);
}
- if (o.paid.equals(PaymentStatus.Trying) && System
- .currentTimeMillis() - o.createdTime < paymentTime) {
- var qt = new QueueTask(o, TaskType.Payment, -1);
+ if (o.paid.equals(PaymentStatus.TRYING) && System
+ .currentTimeMillis() - o.createdTime < paymentTime) {
+ var qt = new QueueTask(o, TaskType.PAYMENT, -1);
updateQueue(qt);
}
}
@@ -234,12 +236,12 @@ public class Commander {
// additional check not needed
LOG.trace("Order " + qt.order.id + ": Queue time for order over, failed..");
return;
- } else if (qt.taskType.equals(TaskType.Payment) && !qt.order.paid.equals(PaymentStatus.Trying)
- || qt.taskType.equals(TaskType.Messaging) && (qt.messageType == 1
- && !qt.order.messageSent.equals(MessageSent.NoneSent)
- || qt.order.messageSent.equals(MessageSent.PaymentFail)
- || qt.order.messageSent.equals(MessageSent.PaymentSuccessful))
- || qt.taskType.equals(TaskType.EmployeeDb) && qt.order.addedToEmployeeHandle) {
+ } else if (qt.taskType.equals(TaskType.PAYMENT) && !qt.order.paid.equals(PaymentStatus.TRYING)
+ || qt.taskType.equals(TaskType.MESSAGING) && (qt.messageType == 1
+ && !qt.order.messageSent.equals(MessageSent.NONE_SENT)
+ || qt.order.messageSent.equals(MessageSent.PAYMENT_FAIL)
+ || qt.order.messageSent.equals(MessageSent.PAYMENT_SUCCESSFUL))
+ || qt.taskType.equals(TaskType.EMPLOYEE_DB) && qt.order.addedToEmployeeHandle) {
LOG.trace("Order " + qt.order.id + ": Not queueing task since task already done..");
return;
}
@@ -256,8 +258,8 @@ public class Commander {
tryDoingTasksInQueue();
};
Retry.HandleErrorIssue handleError = (qt1, err) -> {
- if (qt1.taskType.equals(TaskType.Payment)) {
- qt1.order.paid = PaymentStatus.NotDone;
+ if (qt1.taskType.equals(TaskType.PAYMENT)) {
+ qt1.order.paid = PaymentStatus.NOT_DONE;
sendPaymentFailureMessage(qt1.order);
LOG.error("Order " + qt1.order.id + ": Unable to enqueue payment task,"
+ " payment failed..");
@@ -331,35 +333,9 @@ public class Commander {
}
var list = messagingService.exceptionsList;
Thread t = new Thread(() -> {
- Retry.Operation op = (l) -> {
- if (!l.isEmpty()) {
- if (DatabaseUnavailableException.class.isAssignableFrom(l.get(0).getClass())) {
- LOG.debug("Order " + order.id + ": Error in connecting to messaging service "
- + "(Payment Success msg), trying again..");
- } else {
- LOG.debug("Order " + order.id + ": Error in creating Payment Success"
- + " messaging request..");
- }
- throw l.remove(0);
- }
- if (!order.messageSent.equals(MessageSent.PaymentFail)
- && !order.messageSent.equals(MessageSent.PaymentSuccessful)) {
- var requestId = messagingService.receiveRequest(2);
- order.messageSent = MessageSent.PaymentSuccessful;
- LOG.info("Order " + order.id + ": Payment Success message sent,"
- + " request Id: " + requestId);
- }
- };
+ Retry.Operation op = handleSuccessMessageRetryOperation(order);
Retry.HandleErrorIssue handleError = (o, err) -> {
- if ((o.messageSent.equals(MessageSent.NoneSent) || o.messageSent
- .equals(MessageSent.PaymentTrying))
- && System.currentTimeMillis() - o.createdTime < messageTime) {
- var qt = new QueueTask(order, TaskType.Messaging, 2);
- updateQueue(qt);
- LOG.info("Order " + order.id + ": Error in sending Payment Success message, trying to"
- + " queue task and add to employee handle..");
- employeeHandleIssue(order);
- }
+ handleSuccessMessageErrorIssue(order, o);
};
var r = new Retry<>(op, handleError, numOfRetries, retryDuration,
e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass()));
@@ -372,6 +348,40 @@ public class Commander {
t.start();
}
+ private void handleSuccessMessageErrorIssue(Order order, Order o) {
+ if ((o.messageSent.equals(MessageSent.NONE_SENT) || o.messageSent
+ .equals(MessageSent.PAYMENT_TRYING))
+ && System.currentTimeMillis() - o.createdTime < messageTime) {
+ var qt = new QueueTask(order, TaskType.MESSAGING, 2);
+ updateQueue(qt);
+ LOG.info("Order " + order.id + ": Error in sending Payment Success message, trying to"
+ + " queue task and add to employee handle..");
+ employeeHandleIssue(order);
+ }
+ }
+
+ private Retry.Operation handleSuccessMessageRetryOperation(Order order) {
+ return (l) -> {
+ if (!l.isEmpty()) {
+ if (DatabaseUnavailableException.class.isAssignableFrom(l.get(0).getClass())) {
+ LOG.debug("Order " + order.id + ": Error in connecting to messaging service "
+ + "(Payment Success msg), trying again..");
+ } else {
+ LOG.debug("Order " + order.id + ": Error in creating Payment Success"
+ + " messaging request..");
+ }
+ throw l.remove(0);
+ }
+ if (!order.messageSent.equals(MessageSent.PAYMENT_FAIL)
+ && !order.messageSent.equals(MessageSent.PAYMENT_SUCCESSFUL)) {
+ var requestId = messagingService.receiveRequest(2);
+ order.messageSent = MessageSent.PAYMENT_SUCCESSFUL;
+ LOG.info("Order " + order.id + ": Payment Success message sent,"
+ + " request Id: " + requestId);
+ }
+ };
+ }
+
private void sendPaymentFailureMessage(Order order) {
if (System.currentTimeMillis() - order.createdTime >= this.messageTime) {
LOG.trace("Order " + order.id + ": Message time for order over, returning..");
@@ -380,34 +390,10 @@ public class Commander {
var list = messagingService.exceptionsList;
var t = new Thread(() -> {
Retry.Operation op = (l) -> {
- if (!l.isEmpty()) {
- if (DatabaseUnavailableException.class.isAssignableFrom(l.get(0).getClass())) {
- LOG.debug("Order " + order.id + ": Error in connecting to messaging service "
- + "(Payment Failure msg), trying again..");
- } else {
- LOG.debug("Order " + order.id + ": Error in creating Payment Failure"
- + " message request..");
- }
- throw l.remove(0);
- }
- if (!order.messageSent.equals(MessageSent.PaymentFail)
- && !order.messageSent.equals(MessageSent.PaymentSuccessful)) {
- var requestId = messagingService.receiveRequest(0);
- order.messageSent = MessageSent.PaymentFail;
- LOG.info("Order " + order.id + ": Payment Failure message sent successfully,"
- + " request Id: " + requestId);
- }
+ handlePaymentFailureRetryOperation(order, l);
};
Retry.HandleErrorIssue handleError = (o, err) -> {
- if ((o.messageSent.equals(MessageSent.NoneSent) || o.messageSent
- .equals(MessageSent.PaymentTrying))
- && System.currentTimeMillis() - o.createdTime < messageTime) {
- var qt = new QueueTask(order, TaskType.Messaging, 0);
- updateQueue(qt);
- LOG.warn("Order " + order.id + ": Error in sending Payment Failure message, "
- + "trying to queue task and add to employee handle..");
- employeeHandleIssue(o);
- }
+ handlePaymentErrorIssue(order, o);
};
var r = new Retry<>(op, handleError, numOfRetries, retryDuration,
e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass()));
@@ -420,6 +406,38 @@ public class Commander {
t.start();
}
+ private void handlePaymentErrorIssue(Order order, Order o) {
+ if ((o.messageSent.equals(MessageSent.NONE_SENT) || o.messageSent
+ .equals(MessageSent.PAYMENT_TRYING))
+ && System.currentTimeMillis() - o.createdTime < messageTime) {
+ var qt = new QueueTask(order, TaskType.MESSAGING, 0);
+ updateQueue(qt);
+ LOG.warn("Order " + order.id + ": Error in sending Payment Failure message, "
+ + "trying to queue task and add to employee handle..");
+ employeeHandleIssue(o);
+ }
+ }
+
+ private void handlePaymentFailureRetryOperation(Order order, List l) throws Exception {
+ if (!l.isEmpty()) {
+ if (DatabaseUnavailableException.class.isAssignableFrom(l.get(0).getClass())) {
+ LOG.debug("Order " + order.id + ": Error in connecting to messaging service "
+ + "(Payment Failure msg), trying again..");
+ } else {
+ LOG.debug("Order " + order.id + ": Error in creating Payment Failure"
+ + " message request..");
+ }
+ throw l.remove(0);
+ }
+ if (!order.messageSent.equals(MessageSent.PAYMENT_FAIL)
+ && !order.messageSent.equals(MessageSent.PAYMENT_SUCCESSFUL)) {
+ var requestId = messagingService.receiveRequest(0);
+ order.messageSent = MessageSent.PAYMENT_FAIL;
+ LOG.info("Order " + order.id + ": Payment Failure message sent successfully,"
+ + " request Id: " + requestId);
+ }
+ }
+
private void sendPaymentPossibleErrorMsg(Order order) {
if (System.currentTimeMillis() - order.createdTime >= this.messageTime) {
LOG.trace("Message time for order over, returning..");
@@ -428,34 +446,10 @@ public class Commander {
var list = messagingService.exceptionsList;
var t = new Thread(() -> {
Retry.Operation op = (l) -> {
- if (!l.isEmpty()) {
- if (DatabaseUnavailableException.class.isAssignableFrom(l.get(0).getClass())) {
- LOG.debug("Order " + order.id + ": Error in connecting to messaging service "
- + "(Payment Error msg), trying again..");
- } else {
- LOG.debug("Order " + order.id + ": Error in creating Payment Error"
- + " messaging request..");
- }
- throw l.remove(0);
- }
- if (order.paid.equals(PaymentStatus.Trying) && order.messageSent
- .equals(MessageSent.NoneSent)) {
- var requestId = messagingService.receiveRequest(1);
- order.messageSent = MessageSent.PaymentTrying;
- LOG.info("Order " + order.id + ": Payment Error message sent successfully,"
- + " request Id: " + requestId);
- }
+ handlePaymentPossibleErrorMsgRetryOperation(order, l);
};
Retry.HandleErrorIssue handleError = (o, err) -> {
- if (o.messageSent.equals(MessageSent.NoneSent) && order.paid
- .equals(PaymentStatus.Trying)
- && System.currentTimeMillis() - o.createdTime < messageTime) {
- var qt = new QueueTask(order, TaskType.Messaging, 1);
- updateQueue(qt);
- LOG.warn("Order " + order.id + ": Error in sending Payment Error message, "
- + "trying to queue task and add to employee handle..");
- employeeHandleIssue(o);
- }
+ handlePaymentPossibleErrorMsgErrorIssue(order, o);
};
var r = new Retry<>(op, handleError, numOfRetries, retryDuration,
e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass()));
@@ -468,6 +462,39 @@ public class Commander {
t.start();
}
+ private void handlePaymentPossibleErrorMsgErrorIssue(Order order, Order o) {
+ if (o.messageSent.equals(MessageSent.NONE_SENT) && order.paid
+ .equals(PaymentStatus.TRYING)
+ && System.currentTimeMillis() - o.createdTime < messageTime) {
+ var qt = new QueueTask(order, TaskType.MESSAGING, 1);
+ updateQueue(qt);
+ LOG.warn("Order " + order.id + ": Error in sending Payment Error message, "
+ + "trying to queue task and add to employee handle..");
+ employeeHandleIssue(o);
+ }
+ }
+
+ private void handlePaymentPossibleErrorMsgRetryOperation(Order order, List l)
+ throws Exception {
+ if (!l.isEmpty()) {
+ if (DatabaseUnavailableException.class.isAssignableFrom(l.get(0).getClass())) {
+ LOG.debug("Order " + order.id + ": Error in connecting to messaging service "
+ + "(Payment Error msg), trying again..");
+ } else {
+ LOG.debug("Order " + order.id + ": Error in creating Payment Error"
+ + " messaging request..");
+ }
+ throw l.remove(0);
+ }
+ if (order.paid.equals(PaymentStatus.TRYING) && order.messageSent
+ .equals(MessageSent.NONE_SENT)) {
+ var requestId = messagingService.receiveRequest(1);
+ order.messageSent = MessageSent.PAYMENT_TRYING;
+ LOG.info("Order " + order.id + ": Payment Error message sent successfully,"
+ + " request Id: " + requestId);
+ }
+ }
+
private void employeeHandleIssue(Order order) {
if (System.currentTimeMillis() - order.createdTime >= this.employeeTime) {
LOG.trace("Order " + order.id + ": Employee handle time for order over, returning..");
@@ -490,7 +517,7 @@ public class Commander {
Retry.HandleErrorIssue handleError = (o, err) -> {
if (!o.addedToEmployeeHandle && System
.currentTimeMillis() - order.createdTime < employeeTime) {
- var qt = new QueueTask(order, TaskType.EmployeeDb, -1);
+ var qt = new QueueTask(order, TaskType.EMPLOYEE_DB, -1);
updateQueue(qt);
LOG.warn("Order " + order.id + ": Error in adding to employee db,"
+ " trying to queue task..");
@@ -520,21 +547,21 @@ public class Commander {
LOG.trace("Order " + qt.order.id + ": This queue task of type " + qt.getType()
+ " does not need to be done anymore (timeout), dequeue..");
} else {
- if (qt.taskType.equals(TaskType.Payment)) {
- if (!qt.order.paid.equals(PaymentStatus.Trying)) {
+ if (qt.taskType.equals(TaskType.PAYMENT)) {
+ if (!qt.order.paid.equals(PaymentStatus.TRYING)) {
tryDequeue();
LOG.trace("Order " + qt.order.id + ": This payment task already done, dequeueing..");
} else {
sendPaymentRequest(qt.order);
LOG.debug("Order " + qt.order.id + ": Trying to connect to payment service..");
}
- } else if (qt.taskType.equals(TaskType.Messaging)) {
- if (qt.order.messageSent.equals(MessageSent.PaymentFail)
- || qt.order.messageSent.equals(MessageSent.PaymentSuccessful)) {
+ } 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 " + qt.order.id + ": This messaging task already done, dequeue..");
- } else if (qt.messageType == 1 && (!qt.order.messageSent.equals(MessageSent.NoneSent)
- || !qt.order.paid.equals(PaymentStatus.Trying))) {
+ } else if (qt.messageType == 1 && (!qt.order.messageSent.equals(MessageSent.NONE_SENT)
+ || !qt.order.paid.equals(PaymentStatus.TRYING))) {
tryDequeue();
LOG.trace("Order " + qt.order.id + ": This messaging task does not need to be done,"
+ " dequeue..");
@@ -548,7 +575,7 @@ public class Commander {
sendSuccessMessage(qt.order);
LOG.debug("Order " + qt.order.id + ": Trying to connect to messaging service..");
}
- } else if (qt.taskType.equals(TaskType.EmployeeDb)) {
+ } else if (qt.taskType.equals(TaskType.EMPLOYEE_DB)) {
if (qt.order.addedToEmployeeHandle) {
tryDequeue();
LOG.trace("Order " + qt.order.id + ": This employee handle task already done,"
diff --git a/commander/src/main/java/com/iluwatar/commander/Order.java b/commander/src/main/java/com/iluwatar/commander/Order.java
index 87a9f794a..f736aa47c 100644
--- a/commander/src/main/java/com/iluwatar/commander/Order.java
+++ b/commander/src/main/java/com/iluwatar/commander/Order.java
@@ -33,11 +33,11 @@ import java.util.Random;
public class Order { //can store all transactions ids also
enum PaymentStatus {
- NotDone, Trying, Done
+ NOT_DONE, TRYING, DONE
}
enum MessageSent {
- NoneSent, PaymentFail, PaymentTrying, PaymentSuccessful
+ NONE_SENT, PAYMENT_FAIL, PAYMENT_TRYING, PAYMENT_SUCCESSFUL
}
final User user;
@@ -65,8 +65,8 @@ public class Order { //can store all transactions ids also
}
this.id = id;
USED_IDS.put(this.id, true);
- this.paid = PaymentStatus.Trying;
- this.messageSent = MessageSent.NoneSent;
+ this.paid = PaymentStatus.TRYING;
+ this.messageSent = MessageSent.NONE_SENT;
this.addedToEmployeeHandle = false;
}
diff --git a/commander/src/main/java/com/iluwatar/commander/employeehandle/EmployeeDatabase.java b/commander/src/main/java/com/iluwatar/commander/employeehandle/EmployeeDatabase.java
index 496bb545a..69ebc1fd9 100644
--- a/commander/src/main/java/com/iluwatar/commander/employeehandle/EmployeeDatabase.java
+++ b/commander/src/main/java/com/iluwatar/commander/employeehandle/EmployeeDatabase.java
@@ -33,7 +33,7 @@ import java.util.Hashtable;
*/
public class EmployeeDatabase extends Database {
- private Hashtable data;
+ private final Hashtable data;
public EmployeeDatabase() {
this.data = new Hashtable<>();
diff --git a/commander/src/main/java/com/iluwatar/commander/messagingservice/MessagingDatabase.java b/commander/src/main/java/com/iluwatar/commander/messagingservice/MessagingDatabase.java
index fbba52cac..22ad733cb 100644
--- a/commander/src/main/java/com/iluwatar/commander/messagingservice/MessagingDatabase.java
+++ b/commander/src/main/java/com/iluwatar/commander/messagingservice/MessagingDatabase.java
@@ -33,7 +33,7 @@ import java.util.Hashtable;
*/
public class MessagingDatabase extends Database {
- private Hashtable data;
+ private final Hashtable data;
public MessagingDatabase() {
this.data = new Hashtable<>();
diff --git a/commander/src/main/java/com/iluwatar/commander/messagingservice/MessagingService.java b/commander/src/main/java/com/iluwatar/commander/messagingservice/MessagingService.java
index 3fb385757..e353a4c7c 100644
--- a/commander/src/main/java/com/iluwatar/commander/messagingservice/MessagingService.java
+++ b/commander/src/main/java/com/iluwatar/commander/messagingservice/MessagingService.java
@@ -38,7 +38,7 @@ public class MessagingService extends Service {
private static final Logger LOGGER = LoggerFactory.getLogger(MessagingService.class);
enum MessageToSend {
- PaymentFail, PaymentTrying, PaymentSuccessful
+ PAYMENT_FAIL, PAYMENT_TRYING, PAYMENT_SUCCESSFUL
}
class MessageRequest {
@@ -63,11 +63,11 @@ public class MessagingService extends Service {
var id = generateId();
MessageToSend msg;
if (messageToSend == 0) {
- msg = MessageToSend.PaymentFail;
+ msg = MessageToSend.PAYMENT_FAIL;
} else if (messageToSend == 1) {
- msg = MessageToSend.PaymentTrying;
+ msg = MessageToSend.PAYMENT_TRYING;
} else { //messageToSend == 2
- msg = MessageToSend.PaymentSuccessful;
+ msg = MessageToSend.PAYMENT_SUCCESSFUL;
}
var req = new MessageRequest(id, msg);
return updateDb(req);
@@ -84,10 +84,10 @@ public class MessagingService extends Service {
}
String sendMessage(MessageToSend m) {
- if (m.equals(MessageToSend.PaymentSuccessful)) {
+ if (m.equals(MessageToSend.PAYMENT_SUCCESSFUL)) {
return "Msg: Your order has been placed and paid for successfully!"
+ " Thank you for shopping with us!";
- } else if (m.equals(MessageToSend.PaymentTrying)) {
+ } else if (m.equals(MessageToSend.PAYMENT_TRYING)) {
return "Msg: There was an error in your payment process,"
+ " we are working on it and will return back to you shortly."
+ " Meanwhile, your order has been placed and will be shipped.";
diff --git a/commander/src/main/java/com/iluwatar/commander/paymentservice/PaymentDatabase.java b/commander/src/main/java/com/iluwatar/commander/paymentservice/PaymentDatabase.java
index 644979883..bf9e846bb 100644
--- a/commander/src/main/java/com/iluwatar/commander/paymentservice/PaymentDatabase.java
+++ b/commander/src/main/java/com/iluwatar/commander/paymentservice/PaymentDatabase.java
@@ -34,7 +34,7 @@ import java.util.Hashtable;
public class PaymentDatabase extends Database {
- private Hashtable data;
+ private final Hashtable data;
public PaymentDatabase() {
this.data = new Hashtable<>();
diff --git a/commander/src/main/java/com/iluwatar/commander/queue/QueueDatabase.java b/commander/src/main/java/com/iluwatar/commander/queue/QueueDatabase.java
index 91a7966f7..003a7da46 100644
--- a/commander/src/main/java/com/iluwatar/commander/queue/QueueDatabase.java
+++ b/commander/src/main/java/com/iluwatar/commander/queue/QueueDatabase.java
@@ -35,7 +35,7 @@ import java.util.List;
public class QueueDatabase extends Database {
- private Queue data;
+ private final Queue data;
public List exceptionsList;
public QueueDatabase(Exception... exc) {
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 a27dd62b8..341eb628c 100644
--- a/commander/src/main/java/com/iluwatar/commander/queue/QueueTask.java
+++ b/commander/src/main/java/com/iluwatar/commander/queue/QueueTask.java
@@ -36,7 +36,7 @@ public class QueueTask {
*/
public enum TaskType {
- Messaging, Payment, EmployeeDb
+ MESSAGING, PAYMENT, EMPLOYEE_DB
}
public Order order;
@@ -68,7 +68,7 @@ public class QueueTask {
* @return String representing type of task
*/
public String getType() {
- if (!this.taskType.equals(TaskType.Messaging)) {
+ if (!this.taskType.equals(TaskType.MESSAGING)) {
return this.taskType.toString();
} else {
if (this.messageType == 0) {
diff --git a/commander/src/main/java/com/iluwatar/commander/shippingservice/ShippingDatabase.java b/commander/src/main/java/com/iluwatar/commander/shippingservice/ShippingDatabase.java
index 305122db2..abaf27c9d 100644
--- a/commander/src/main/java/com/iluwatar/commander/shippingservice/ShippingDatabase.java
+++ b/commander/src/main/java/com/iluwatar/commander/shippingservice/ShippingDatabase.java
@@ -34,7 +34,7 @@ import java.util.Hashtable;
public class ShippingDatabase extends Database {
- private Hashtable data;
+ private final Hashtable data;
public ShippingDatabase() {
this.data = new Hashtable<>();
diff --git a/composite/README.md b/composite/README.md
index 25b553b76..dad6fb5a5 100644
--- a/composite/README.md
+++ b/composite/README.md
@@ -34,7 +34,7 @@ Taking our sentence example from above. Here we have the base class and differen
```java
public abstract class LetterComposite {
- private List children = new ArrayList<>();
+ private final List children = new ArrayList<>();
public void add(LetterComposite letter) {
children.add(letter);
@@ -59,7 +59,7 @@ public abstract class LetterComposite {
public class Letter extends LetterComposite {
- private char character;
+ private final char character;
public Letter(char c) {
this.character = c;
diff --git a/composite/pom.xml b/composite/pom.xml
index c16b95c13..6f7147482 100644
--- a/composite/pom.xml
+++ b/composite/pom.xml
@@ -29,7 +29,7 @@
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
composite
diff --git a/composite/src/main/java/com/iluwatar/composite/Letter.java b/composite/src/main/java/com/iluwatar/composite/Letter.java
index ab2d496ea..00b1a9639 100644
--- a/composite/src/main/java/com/iluwatar/composite/Letter.java
+++ b/composite/src/main/java/com/iluwatar/composite/Letter.java
@@ -28,7 +28,7 @@ package com.iluwatar.composite;
*/
public class Letter extends LetterComposite {
- private char character;
+ private final char character;
public Letter(char c) {
this.character = c;
diff --git a/composite/src/main/java/com/iluwatar/composite/LetterComposite.java b/composite/src/main/java/com/iluwatar/composite/LetterComposite.java
index 25808c468..0daf88222 100644
--- a/composite/src/main/java/com/iluwatar/composite/LetterComposite.java
+++ b/composite/src/main/java/com/iluwatar/composite/LetterComposite.java
@@ -1,58 +1,58 @@
-/*
- * The MIT License
- * Copyright © 2014-2019 Ilkka Seppälä
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-
-package com.iluwatar.composite;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Composite interface.
- */
-public abstract class LetterComposite {
-
- private List children = new ArrayList<>();
-
- public void add(LetterComposite letter) {
- children.add(letter);
- }
-
- public int count() {
- return children.size();
- }
-
- protected void printThisBefore() {
- }
-
- protected void printThisAfter() {
- }
-
- /**
- * Print.
- */
- public void print() {
- printThisBefore();
- children.forEach(LetterComposite::print);
- printThisAfter();
- }
-}
+/*
+ * The MIT License
+ * Copyright © 2014-2019 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+package com.iluwatar.composite;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Composite interface.
+ */
+public abstract class LetterComposite {
+
+ private final List children = new ArrayList<>();
+
+ public void add(LetterComposite letter) {
+ children.add(letter);
+ }
+
+ public int count() {
+ return children.size();
+ }
+
+ protected void printThisBefore() {
+ }
+
+ protected void printThisAfter() {
+ }
+
+ /**
+ * Print.
+ */
+ public void print() {
+ printThisBefore();
+ children.forEach(LetterComposite::print);
+ printThisAfter();
+ }
+}
diff --git a/composite/src/main/java/com/iluwatar/composite/module-info.java b/composite/src/main/java/com/iluwatar/composite/module-info.java
deleted file mode 100644
index d75a7b8f8..000000000
--- a/composite/src/main/java/com/iluwatar/composite/module-info.java
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * The MIT License
- * Copyright © 2014-2019 Ilkka Seppälä
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-
-module com.iluwatar.composite {
- requires org.slf4j;
-}
\ No newline at end of file
diff --git a/composite/src/test/java/com/iluwatar/composite/AppTest.java b/composite/src/test/java/com/iluwatar/composite/AppTest.java
index 5eb8c35c7..c82056a51 100644
--- a/composite/src/test/java/com/iluwatar/composite/AppTest.java
+++ b/composite/src/test/java/com/iluwatar/composite/AppTest.java
@@ -23,15 +23,23 @@
package com.iluwatar.composite;
+import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
/**
* Application test
*/
-public class AppTest {
+class AppTest {
+
+ /**
+ * Issue: Add at least one assertion to this test case.
+ *
+ * Solution: Inserted assertion to check whether the execution of the main method in {@link App#main(String[])}
+ * throws an exception.
+ */
@Test
- public void test() {
- App.main(new String[]{});
+ void shouldExecuteApplicationWithoutException() {
+ Assertions.assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
diff --git a/converter/pom.xml b/converter/pom.xml
index 56eb2ccdb..1bed5e973 100644
--- a/converter/pom.xml
+++ b/converter/pom.xml
@@ -20,7 +20,7 @@
java-design-patterns
com.iluwatar
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
converter
4.0.0
diff --git a/converter/src/main/java/com/iluwatar/converter/User.java b/converter/src/main/java/com/iluwatar/converter/User.java
index 637d77a25..2c1ba9ff0 100644
--- a/converter/src/main/java/com/iluwatar/converter/User.java
+++ b/converter/src/main/java/com/iluwatar/converter/User.java
@@ -29,10 +29,10 @@ import java.util.Objects;
* User class.
*/
public class User {
- private String firstName;
- private String lastName;
- private boolean isActive;
- private String userId;
+ private final String firstName;
+ private final String lastName;
+ private final boolean isActive;
+ private final String userId;
/**
* Constructor.
diff --git a/converter/src/main/java/com/iluwatar/converter/UserDto.java b/converter/src/main/java/com/iluwatar/converter/UserDto.java
index e75aaab8c..67a886087 100644
--- a/converter/src/main/java/com/iluwatar/converter/UserDto.java
+++ b/converter/src/main/java/com/iluwatar/converter/UserDto.java
@@ -30,10 +30,10 @@ import java.util.Objects;
*/
public class UserDto {
- private String firstName;
- private String lastName;
- private boolean isActive;
- private String email;
+ private final String firstName;
+ private final String lastName;
+ private final boolean isActive;
+ private final String email;
/**
* Constructor.
diff --git a/converter/src/main/java/com/iluwatar/converter/module-info.java b/converter/src/main/java/com/iluwatar/converter/module-info.java
deleted file mode 100644
index d83a43c6b..000000000
--- a/converter/src/main/java/com/iluwatar/converter/module-info.java
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * The MIT License
- * Copyright © 2014-2019 Ilkka Seppälä
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-
-module com.iluwatar.converter {
- requires org.slf4j;
-}
\ No newline at end of file
diff --git a/converter/src/test/java/com/iluwatar/converter/AppTest.java b/converter/src/test/java/com/iluwatar/converter/AppTest.java
index ed53c6863..7a99fe6ae 100644
--- a/converter/src/test/java/com/iluwatar/converter/AppTest.java
+++ b/converter/src/test/java/com/iluwatar/converter/AppTest.java
@@ -25,14 +25,24 @@ package com.iluwatar.converter;
import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+
/**
* App running test
*/
-public class AppTest {
+class AppTest {
+
+ /**
+ * Issue: Add at least one assertion to this test case.
+ *
+ * Solution: Inserted assertion to check whether the execution of the main method in {@link App#main(String[])}
+ * throws an exception.
+ */
@Test
- public void testMain() {
- App.main(new String[]{});
+ void shouldExecuteApplicationWithoutException() {
+
+ assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
diff --git a/converter/src/test/java/com/iluwatar/converter/ConverterTest.java b/converter/src/test/java/com/iluwatar/converter/ConverterTest.java
index d9e4e418b..46aca82a7 100644
--- a/converter/src/test/java/com/iluwatar/converter/ConverterTest.java
+++ b/converter/src/test/java/com/iluwatar/converter/ConverterTest.java
@@ -34,7 +34,7 @@ import org.junit.jupiter.api.Test;
*/
public class ConverterTest {
- private UserConverter userConverter = new UserConverter();
+ private final UserConverter userConverter = new UserConverter();
/**
* Tests whether a converter created of opposite functions holds equality as a bijection.
diff --git a/cqrs/pom.xml b/cqrs/pom.xml
index b3a0303e6..1838ed599 100644
--- a/cqrs/pom.xml
+++ b/cqrs/pom.xml
@@ -30,7 +30,7 @@
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
cqrs
diff --git a/cqrs/src/main/java/com/iluwatar/cqrs/commandes/CommandServiceImpl.java b/cqrs/src/main/java/com/iluwatar/cqrs/commandes/CommandServiceImpl.java
index ba08811e7..e402adad8 100644
--- a/cqrs/src/main/java/com/iluwatar/cqrs/commandes/CommandServiceImpl.java
+++ b/cqrs/src/main/java/com/iluwatar/cqrs/commandes/CommandServiceImpl.java
@@ -34,7 +34,7 @@ import org.hibernate.SessionFactory;
*/
public class CommandServiceImpl implements ICommandService {
- private SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
+ private final SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
private Author getAuthorByUsername(String username) {
Author author;
diff --git a/cqrs/src/main/java/com/iluwatar/cqrs/queries/QueryServiceImpl.java b/cqrs/src/main/java/com/iluwatar/cqrs/queries/QueryServiceImpl.java
index 9b008402e..d30c0f386 100644
--- a/cqrs/src/main/java/com/iluwatar/cqrs/queries/QueryServiceImpl.java
+++ b/cqrs/src/main/java/com/iluwatar/cqrs/queries/QueryServiceImpl.java
@@ -38,7 +38,7 @@ import org.hibernate.transform.Transformers;
*/
public class QueryServiceImpl implements IQueryService {
- private SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
+ private final SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
@Override
public Author getAuthorByUsername(String username) {
diff --git a/dao/README.md b/dao/README.md
index 4b65679c4..11e5f9ca3 100644
--- a/dao/README.md
+++ b/dao/README.md
@@ -112,7 +112,7 @@ public interface CustomerDao {
public class InMemoryCustomerDao implements CustomerDao {
- private Map idToCustomer = new HashMap<>();
+ private final Map idToCustomer = new HashMap<>();
@Override
public Stream getAll() {
diff --git a/dao/pom.xml b/dao/pom.xml
index 7e8bd5625..32e9ef1ff 100644
--- a/dao/pom.xml
+++ b/dao/pom.xml
@@ -30,7 +30,7 @@
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
dao
diff --git a/dao/src/main/java/com/iluwatar/dao/App.java b/dao/src/main/java/com/iluwatar/dao/App.java
index de9c7b7c1..6d578bc79 100644
--- a/dao/src/main/java/com/iluwatar/dao/App.java
+++ b/dao/src/main/java/com/iluwatar/dao/App.java
@@ -44,7 +44,7 @@ import org.slf4j.LoggerFactory;
*/
public class App {
private static final String DB_URL = "jdbc:h2:~/dao";
- private static Logger log = LoggerFactory.getLogger(App.class);
+ private static final Logger log = LoggerFactory.getLogger(App.class);
private static final String ALL_CUSTOMERS = "customerDao.getAllCustomers(): ";
/**
diff --git a/dao/src/main/java/com/iluwatar/dao/InMemoryCustomerDao.java b/dao/src/main/java/com/iluwatar/dao/InMemoryCustomerDao.java
index 6dbfa367a..0a3bd40e3 100644
--- a/dao/src/main/java/com/iluwatar/dao/InMemoryCustomerDao.java
+++ b/dao/src/main/java/com/iluwatar/dao/InMemoryCustomerDao.java
@@ -36,7 +36,7 @@ import java.util.stream.Stream;
*/
public class InMemoryCustomerDao implements CustomerDao {
- private Map idToCustomer = new HashMap<>();
+ private final Map idToCustomer = new HashMap<>();
/**
* An eagerly evaluated stream of customers stored in memory.
diff --git a/dao/src/main/java/com/iluwatar/dao/module-info.java b/dao/src/main/java/com/iluwatar/dao/module-info.java
deleted file mode 100644
index 08e4f662e..000000000
--- a/dao/src/main/java/com/iluwatar/dao/module-info.java
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- * The MIT License
- * Copyright © 2014-2019 Ilkka Seppälä
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-
-module com.iluwatar.dao {
- requires org.slf4j;
- requires java.sql;
- requires h2;
- requires java.naming;
-}
\ No newline at end of file
diff --git a/dao/src/test/java/com/iluwatar/dao/AppTest.java b/dao/src/test/java/com/iluwatar/dao/AppTest.java
index edfcf7cd0..e6d41fc8a 100644
--- a/dao/src/test/java/com/iluwatar/dao/AppTest.java
+++ b/dao/src/test/java/com/iluwatar/dao/AppTest.java
@@ -25,12 +25,22 @@ package com.iluwatar.dao;
import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+
/**
* Tests that DAO example runs without errors.
*/
-public class AppTest {
+class AppTest {
+
+ /**
+ * Issue: Add at least one assertion to this test case.
+ *
+ * Solution: Inserted assertion to check whether the execution of the main method in {@link App#main(String[])}
+ * throws an exception.
+ */
+
@Test
- public void test() throws Exception {
- App.main(new String[]{});
+ void shouldExecuteDaoWithoutException() {
+ assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
diff --git a/dao/src/test/java/com/iluwatar/dao/DbCustomerDaoTest.java b/dao/src/test/java/com/iluwatar/dao/DbCustomerDaoTest.java
index b7a0b9769..8155cda79 100644
--- a/dao/src/test/java/com/iluwatar/dao/DbCustomerDaoTest.java
+++ b/dao/src/test/java/com/iluwatar/dao/DbCustomerDaoTest.java
@@ -50,7 +50,7 @@ public class DbCustomerDaoTest {
private static final String DB_URL = "jdbc:h2:~/dao";
private DbCustomerDao dao;
- private Customer existingCustomer = new Customer(1, "Freddy", "Krueger");
+ private final Customer existingCustomer = new Customer(1, "Freddy", "Krueger");
/**
* Creates customers schema.
diff --git a/data-bus/pom.xml b/data-bus/pom.xml
index e67135ae0..4db738307 100644
--- a/data-bus/pom.xml
+++ b/data-bus/pom.xml
@@ -33,7 +33,7 @@
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
data-bus
diff --git a/data-bus/src/main/java/com/iluwatar/databus/members/MessageCollectorMember.java b/data-bus/src/main/java/com/iluwatar/databus/members/MessageCollectorMember.java
index 5a8218225..d77d56b9f 100644
--- a/data-bus/src/main/java/com/iluwatar/databus/members/MessageCollectorMember.java
+++ b/data-bus/src/main/java/com/iluwatar/databus/members/MessageCollectorMember.java
@@ -41,7 +41,7 @@ public class MessageCollectorMember implements Member {
private final String name;
- private List messages = new ArrayList<>();
+ private final List messages = new ArrayList<>();
public MessageCollectorMember(String name) {
this.name = name;
diff --git a/data-locality/pom.xml b/data-locality/pom.xml
index 660daa9b7..88fd96c64 100644
--- a/data-locality/pom.xml
+++ b/data-locality/pom.xml
@@ -30,7 +30,7 @@
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
data-locality
diff --git a/data-locality/src/main/java/com/iluwatar/data/locality/game/component/AiComponent.java b/data-locality/src/main/java/com/iluwatar/data/locality/game/component/AiComponent.java
index 5b1be9e35..40acb2f71 100644
--- a/data-locality/src/main/java/com/iluwatar/data/locality/game/component/AiComponent.java
+++ b/data-locality/src/main/java/com/iluwatar/data/locality/game/component/AiComponent.java
@@ -43,6 +43,6 @@ public class AiComponent implements Component {
@Override
public void render() {
-
+ // Do Nothing.
}
}
diff --git a/data-locality/src/main/java/com/iluwatar/data/locality/game/component/manager/AiComponentManager.java b/data-locality/src/main/java/com/iluwatar/data/locality/game/component/manager/AiComponentManager.java
index 616ebf801..c85bd1e68 100644
--- a/data-locality/src/main/java/com/iluwatar/data/locality/game/component/manager/AiComponentManager.java
+++ b/data-locality/src/main/java/com/iluwatar/data/locality/game/component/manager/AiComponentManager.java
@@ -40,7 +40,7 @@ public class AiComponentManager {
private final int numEntities;
- private static final Component[] AI_COMPONENTS = new AiComponent[MAX_ENTITIES];
+ private final Component[] aiComponents = new AiComponent[MAX_ENTITIES];
public AiComponentManager(int numEntities) {
this.numEntities = numEntities;
@@ -51,7 +51,7 @@ public class AiComponentManager {
*/
public void start() {
LOGGER.info("Start AI Game Component");
- IntStream.range(0, numEntities).forEach(i -> AI_COMPONENTS[i] = new AiComponent());
+ IntStream.range(0, numEntities).forEach(i -> aiComponents[i] = new AiComponent());
}
/**
@@ -60,7 +60,7 @@ public class AiComponentManager {
public void update() {
LOGGER.info("Update AI Game Component");
IntStream.range(0, numEntities)
- .filter(i -> AI_COMPONENTS.length > i && AI_COMPONENTS[i] != null)
- .forEach(i -> AI_COMPONENTS[i].update());
+ .filter(i -> aiComponents.length > i && aiComponents[i] != null)
+ .forEach(i -> aiComponents[i].update());
}
}
diff --git a/data-locality/src/main/java/com/iluwatar/data/locality/game/component/manager/PhysicsComponentManager.java b/data-locality/src/main/java/com/iluwatar/data/locality/game/component/manager/PhysicsComponentManager.java
index 61ba4ebdd..155793c88 100644
--- a/data-locality/src/main/java/com/iluwatar/data/locality/game/component/manager/PhysicsComponentManager.java
+++ b/data-locality/src/main/java/com/iluwatar/data/locality/game/component/manager/PhysicsComponentManager.java
@@ -40,7 +40,7 @@ public class PhysicsComponentManager {
private final int numEntities;
- private static final Component[] PHYSICS_COMPONENTS = new PhysicsComponent[MAX_ENTITIES];
+ private final Component[] physicsComponents = new PhysicsComponent[MAX_ENTITIES];
public PhysicsComponentManager(int numEntities) {
this.numEntities = numEntities;
@@ -51,7 +51,7 @@ public class PhysicsComponentManager {
*/
public void start() {
LOGGER.info("Start Physics Game Component ");
- IntStream.range(0, numEntities).forEach(i -> PHYSICS_COMPONENTS[i] = new PhysicsComponent());
+ IntStream.range(0, numEntities).forEach(i -> physicsComponents[i] = new PhysicsComponent());
}
@@ -62,7 +62,7 @@ public class PhysicsComponentManager {
LOGGER.info("Update Physics Game Component ");
// Process physics.
IntStream.range(0, numEntities)
- .filter(i -> PHYSICS_COMPONENTS.length > i && PHYSICS_COMPONENTS[i] != null)
- .forEach(i -> PHYSICS_COMPONENTS[i].update());
+ .filter(i -> physicsComponents.length > i && physicsComponents[i] != null)
+ .forEach(i -> physicsComponents[i].update());
}
}
diff --git a/data-locality/src/main/java/com/iluwatar/data/locality/game/component/manager/RenderComponentManager.java b/data-locality/src/main/java/com/iluwatar/data/locality/game/component/manager/RenderComponentManager.java
index f8c4b3522..be1d3c2e9 100644
--- a/data-locality/src/main/java/com/iluwatar/data/locality/game/component/manager/RenderComponentManager.java
+++ b/data-locality/src/main/java/com/iluwatar/data/locality/game/component/manager/RenderComponentManager.java
@@ -40,7 +40,7 @@ public class RenderComponentManager {
private final int numEntities;
- private static final Component[] RENDER_COMPONENTS = new RenderComponent[MAX_ENTITIES];
+ private final Component[] renderComponents = new RenderComponent[MAX_ENTITIES];
public RenderComponentManager(int numEntities) {
this.numEntities = numEntities;
@@ -51,7 +51,7 @@ public class RenderComponentManager {
*/
public void start() {
LOGGER.info("Start Render Game Component ");
- IntStream.range(0, numEntities).forEach(i -> RENDER_COMPONENTS[i] = new RenderComponent());
+ IntStream.range(0, numEntities).forEach(i -> renderComponents[i] = new RenderComponent());
}
@@ -62,7 +62,7 @@ public class RenderComponentManager {
LOGGER.info("Update Render Game Component ");
// Process Render.
IntStream.range(0, numEntities)
- .filter(i -> RENDER_COMPONENTS.length > i && RENDER_COMPONENTS[i] != null)
- .forEach(i -> RENDER_COMPONENTS[i].render());
+ .filter(i -> renderComponents.length > i && renderComponents[i] != null)
+ .forEach(i -> renderComponents[i].render());
}
}
diff --git a/data-locality/src/test/java/com/iluwatar/data/locality/ApplicationTest.java b/data-locality/src/test/java/com/iluwatar/data/locality/ApplicationTest.java
index 3371be4c1..b7d1f8961 100644
--- a/data-locality/src/test/java/com/iluwatar/data/locality/ApplicationTest.java
+++ b/data-locality/src/test/java/com/iluwatar/data/locality/ApplicationTest.java
@@ -26,16 +26,22 @@ package com.iluwatar.data.locality;
import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+
/**
* Test Game Application
*/
class ApplicationTest {
/**
- * Test run
+ * Issue: Add at least one assertion to this test case.
+ *
+ * Solution: Inserted assertion to check whether the execution of the main method in {@link Application#main(String[])}
+ * throws an exception.
*/
+
@Test
- void main() {
- Application.main(new String[] {});
+ void shouldExecuteGameApplicationWithoutException() {
+ assertDoesNotThrow(() -> Application.main(new String[] {}));
}
}
\ No newline at end of file
diff --git a/data-mapper/pom.xml b/data-mapper/pom.xml
index 64f03a186..cf17de69b 100644
--- a/data-mapper/pom.xml
+++ b/data-mapper/pom.xml
@@ -28,7 +28,7 @@
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
data-mapper
diff --git a/data-mapper/src/main/java/com/iluwatar/datamapper/App.java b/data-mapper/src/main/java/com/iluwatar/datamapper/App.java
index 9bfc32952..09c027401 100644
--- a/data-mapper/src/main/java/com/iluwatar/datamapper/App.java
+++ b/data-mapper/src/main/java/com/iluwatar/datamapper/App.java
@@ -1,83 +1,83 @@
-/*
- * The MIT License
- * Copyright © 2014-2019 Ilkka Seppälä
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-
-package com.iluwatar.datamapper;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * The Data Mapper (DM) is a layer of software that separates the in-memory objects from the
- * database. Its responsibility is to transfer data between the two and also to isolate them from
- * each other. With Data Mapper the in-memory objects needn't know even that there's a database
- * present; they need no SQL interface code, and certainly no knowledge of the database schema. (The
- * database schema is always ignorant of the objects that use it.) Since it's a form of Mapper ,
- * Data Mapper itself is even unknown to the domain layer.
- *
- * The below example demonstrates basic CRUD operations: Create, Read, Update, and Delete.
- */
-public final class App {
-
- private static Logger log = LoggerFactory.getLogger(App.class);
- private static final String STUDENT_STRING = "App.main(), student : ";
-
-
- /**
- * Program entry point.
- *
- * @param args command line args.
- */
- public static void main(final String... args) {
-
- /* Create new data mapper for type 'first' */
- final var mapper = new StudentDataMapperImpl();
-
- /* Create new student */
- var student = new Student(1, "Adam", 'A');
-
- /* Add student in respectibe store */
- mapper.insert(student);
-
- log.debug(STUDENT_STRING + student + ", is inserted");
-
- /* Find this student */
- final var studentToBeFound = mapper.find(student.getStudentId());
-
- log.debug(STUDENT_STRING + studentToBeFound + ", is searched");
-
- /* Update existing student object */
- student = new Student(student.getStudentId(), "AdamUpdated", 'A');
-
- /* Update student in respectibe db */
- mapper.update(student);
-
- log.debug(STUDENT_STRING + student + ", is updated");
- log.debug(STUDENT_STRING + student + ", is going to be deleted");
-
- /* Delete student in db */
- mapper.delete(student);
- }
-
- private App() {
- }
-}
+/*
+ * The MIT License
+ * Copyright © 2014-2019 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+package com.iluwatar.datamapper;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * The Data Mapper (DM) is a layer of software that separates the in-memory objects from the
+ * database. Its responsibility is to transfer data between the two and also to isolate them from
+ * each other. With Data Mapper the in-memory objects needn't know even that there's a database
+ * present; they need no SQL interface code, and certainly no knowledge of the database schema. (The
+ * database schema is always ignorant of the objects that use it.) Since it's a form of Mapper ,
+ * Data Mapper itself is even unknown to the domain layer.
+ *
+ *
The below example demonstrates basic CRUD operations: Create, Read, Update, and Delete.
+ */
+public final class App {
+
+ private static final Logger log = LoggerFactory.getLogger(App.class);
+ private static final String STUDENT_STRING = "App.main(), student : ";
+
+
+ /**
+ * Program entry point.
+ *
+ * @param args command line args.
+ */
+ public static void main(final String... args) {
+
+ /* Create new data mapper for type 'first' */
+ final var mapper = new StudentDataMapperImpl();
+
+ /* Create new student */
+ var student = new Student(1, "Adam", 'A');
+
+ /* Add student in respectibe store */
+ mapper.insert(student);
+
+ log.debug(STUDENT_STRING + student + ", is inserted");
+
+ /* Find this student */
+ final var studentToBeFound = mapper.find(student.getStudentId());
+
+ log.debug(STUDENT_STRING + studentToBeFound + ", is searched");
+
+ /* Update existing student object */
+ student = new Student(student.getStudentId(), "AdamUpdated", 'A');
+
+ /* Update student in respectibe db */
+ mapper.update(student);
+
+ log.debug(STUDENT_STRING + student + ", is updated");
+ log.debug(STUDENT_STRING + student + ", is going to be deleted");
+
+ /* Delete student in db */
+ mapper.delete(student);
+ }
+
+ private App() {
+ }
+}
diff --git a/data-mapper/src/main/java/com/iluwatar/datamapper/StudentDataMapperImpl.java b/data-mapper/src/main/java/com/iluwatar/datamapper/StudentDataMapperImpl.java
index 85ad4aa8d..7abe04e3f 100644
--- a/data-mapper/src/main/java/com/iluwatar/datamapper/StudentDataMapperImpl.java
+++ b/data-mapper/src/main/java/com/iluwatar/datamapper/StudentDataMapperImpl.java
@@ -33,7 +33,7 @@ import java.util.Optional;
public final class StudentDataMapperImpl implements StudentDataMapper {
/* Note: Normally this would be in the form of an actual database */
- private List students = new ArrayList<>();
+ private final List students = new ArrayList<>();
@Override
public Optional find(int studentId) {
diff --git a/data-mapper/src/main/java/com/iluwatar/datamapper/module-info.java b/data-mapper/src/main/java/com/iluwatar/datamapper/module-info.java
deleted file mode 100644
index 7abd78826..000000000
--- a/data-mapper/src/main/java/com/iluwatar/datamapper/module-info.java
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * The MIT License
- * Copyright © 2014-2019 Ilkka Seppälä
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-
-module com.iluwatar.datamapper {
- requires org.slf4j;
-}
\ No newline at end of file
diff --git a/data-mapper/src/test/java/com/iluwatar/datamapper/AppTest.java b/data-mapper/src/test/java/com/iluwatar/datamapper/AppTest.java
index ec1d71be4..ab74edd6c 100644
--- a/data-mapper/src/test/java/com/iluwatar/datamapper/AppTest.java
+++ b/data-mapper/src/test/java/com/iluwatar/datamapper/AppTest.java
@@ -24,14 +24,25 @@
package com.iluwatar.datamapper;
import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.function.Executable;
+
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/**
* Tests that Data-Mapper example runs without errors.
*/
-public final class AppTest {
+final class AppTest {
+
+ /**
+ * Issue: Add at least one assertion to this test case.
+ *
+ * Solution: Inserted assertion to check whether the execution of the main method in {@link App#main(String[])}
+ * throws an exception.
+ */
@Test
- public void test() {
- App.main();
+ void shouldExecuteApplicationWithoutException() {
+
+ assertDoesNotThrow((Executable) App::main);
}
}
diff --git a/data-transfer-object/README.md b/data-transfer-object/README.md
index e9286ce03..fd0ff1137 100644
--- a/data-transfer-object/README.md
+++ b/data-transfer-object/README.md
@@ -64,7 +64,7 @@ Customer resource class acts as the server for customer information.
```java
public class CustomerResource {
- private List customers;
+ private final List customers;
public CustomerResource(List customers) {
this.customers = customers;
diff --git a/data-transfer-object/pom.xml b/data-transfer-object/pom.xml
index 459b1ab1e..2529b3756 100644
--- a/data-transfer-object/pom.xml
+++ b/data-transfer-object/pom.xml
@@ -28,7 +28,7 @@
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
data-transfer-object
diff --git a/data-transfer-object/src/main/java/com/iluwatar/datatransfer/CustomerResource.java b/data-transfer-object/src/main/java/com/iluwatar/datatransfer/CustomerResource.java
index 7e4b8340d..d0a153f6f 100644
--- a/data-transfer-object/src/main/java/com/iluwatar/datatransfer/CustomerResource.java
+++ b/data-transfer-object/src/main/java/com/iluwatar/datatransfer/CustomerResource.java
@@ -30,7 +30,7 @@ import java.util.List;
* has all customer details.
*/
public class CustomerResource {
- private List customers;
+ private final List customers;
/**
* Initialise resource with existing customers.
diff --git a/data-transfer-object/src/main/java/com/iluwatar/datatransfer/module-info.java b/data-transfer-object/src/main/java/com/iluwatar/datatransfer/module-info.java
deleted file mode 100644
index 25685d4d0..000000000
--- a/data-transfer-object/src/main/java/com/iluwatar/datatransfer/module-info.java
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * The MIT License
- * Copyright © 2014-2019 Ilkka Seppälä
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-
-module com.iluwatar.datatransfer {
- requires org.slf4j;
-}
\ No newline at end of file
diff --git a/data-transfer-object/src/test/java/com/iluwatar/datatransfer/AppTest.java b/data-transfer-object/src/test/java/com/iluwatar/datatransfer/AppTest.java
index 3a58d0c54..68a8b9444 100644
--- a/data-transfer-object/src/test/java/com/iluwatar/datatransfer/AppTest.java
+++ b/data-transfer-object/src/test/java/com/iluwatar/datatransfer/AppTest.java
@@ -25,9 +25,19 @@ package com.iluwatar.datatransfer;
import org.junit.jupiter.api.Test;
-public class AppTest {
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+
+class AppTest {
+
+ /**
+ * Issue: Add at least one assertion to this test case.
+ *
+ * Solution: Inserted assertion to check whether the execution of the main method in {@link App#main(String[])}
+ * throws an exception.
+ */
+
@Test
- public void test() throws Exception {
- App.main(new String[]{});
+ void shouldExecuteApplicationWithoutException() {
+ assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
diff --git a/decorator/README.md b/decorator/README.md
index a9dd5d745..26dbd1803 100644
--- a/decorator/README.md
+++ b/decorator/README.md
@@ -70,7 +70,7 @@ public class ClubbedTroll implements Troll {
private static final Logger LOGGER = LoggerFactory.getLogger(ClubbedTroll.class);
- private Troll decorated;
+ private final Troll decorated;
public ClubbedTroll(Troll decorated) {
this.decorated = decorated;
diff --git a/decorator/pom.xml b/decorator/pom.xml
index c7e1a4d8d..b075704c8 100644
--- a/decorator/pom.xml
+++ b/decorator/pom.xml
@@ -29,7 +29,7 @@
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
decorator
diff --git a/decorator/src/main/java/com/iluwatar/decorator/ClubbedTroll.java b/decorator/src/main/java/com/iluwatar/decorator/ClubbedTroll.java
index 70fd15489..74a1434e1 100644
--- a/decorator/src/main/java/com/iluwatar/decorator/ClubbedTroll.java
+++ b/decorator/src/main/java/com/iluwatar/decorator/ClubbedTroll.java
@@ -33,7 +33,7 @@ public class ClubbedTroll implements Troll {
private static final Logger LOGGER = LoggerFactory.getLogger(ClubbedTroll.class);
- private Troll decorated;
+ private final Troll decorated;
public ClubbedTroll(Troll decorated) {
this.decorated = decorated;
diff --git a/decorator/src/main/java/com/iluwatar/decorator/module-info.java b/decorator/src/main/java/com/iluwatar/decorator/module-info.java
deleted file mode 100644
index 50d17f022..000000000
--- a/decorator/src/main/java/com/iluwatar/decorator/module-info.java
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * The MIT License
- * Copyright © 2014-2019 Ilkka Seppälä
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-
-module com.iluwatar.decorator {
- requires org.slf4j;
-}
\ No newline at end of file
diff --git a/decorator/src/test/java/com/iluwatar/decorator/AppTest.java b/decorator/src/test/java/com/iluwatar/decorator/AppTest.java
index e8d4c8505..792d61233 100644
--- a/decorator/src/test/java/com/iluwatar/decorator/AppTest.java
+++ b/decorator/src/test/java/com/iluwatar/decorator/AppTest.java
@@ -25,13 +25,22 @@ package com.iluwatar.decorator;
import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+
/**
* Application test
*/
-public class AppTest {
+class AppTest {
+
+ /**
+ * Issue: Add at least one assertion to this test case.
+ *
+ * Solution: Inserted assertion to check whether the execution of the main method in {@link App#main(String[])}
+ * throws an exception.
+ */
@Test
- public void test() {
- App.main(new String[]{});
+ void shouldExecuteApplicationWithoutException() {
+ assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
diff --git a/decorator/src/test/java/com/iluwatar/decorator/SimpleTrollTest.java b/decorator/src/test/java/com/iluwatar/decorator/SimpleTrollTest.java
index c9f62407c..a398135e6 100644
--- a/decorator/src/test/java/com/iluwatar/decorator/SimpleTrollTest.java
+++ b/decorator/src/test/java/com/iluwatar/decorator/SimpleTrollTest.java
@@ -68,7 +68,7 @@ public class SimpleTrollTest {
private class InMemoryAppender extends AppenderBase {
- private List log = new LinkedList<>();
+ private final List log = new LinkedList<>();
public InMemoryAppender(Class clazz) {
((Logger) LoggerFactory.getLogger(clazz)).addAppender(this);
diff --git a/delegation/pom.xml b/delegation/pom.xml
index 63cd91842..d7ad81362 100644
--- a/delegation/pom.xml
+++ b/delegation/pom.xml
@@ -29,7 +29,7 @@
java-design-patterns
com.iluwatar
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
4.0.0
diff --git a/delegation/src/main/java/com/iluwatar/delegation/module-info.java b/delegation/src/main/java/com/iluwatar/delegation/module-info.java
deleted file mode 100644
index 156477cde..000000000
--- a/delegation/src/main/java/com/iluwatar/delegation/module-info.java
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * The MIT License
- * Copyright © 2014-2019 Ilkka Seppälä
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-
-module com.iluwatar.delegation {
- requires org.slf4j;
-}
\ No newline at end of file
diff --git a/delegation/src/test/java/com/iluwatar/delegation/simple/AppTest.java b/delegation/src/test/java/com/iluwatar/delegation/simple/AppTest.java
index 2865c76c1..8e20c9032 100644
--- a/delegation/src/test/java/com/iluwatar/delegation/simple/AppTest.java
+++ b/delegation/src/test/java/com/iluwatar/delegation/simple/AppTest.java
@@ -25,14 +25,23 @@ package com.iluwatar.delegation.simple;
import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+
/**
* Application Test Entry
*/
-public class AppTest {
+class AppTest {
+
+ /**
+ * Issue: Add at least one assertion to this test case.
+ *
+ * Solution: Inserted assertion to check whether the execution of the main method in {@link App#main(String[])}
+ * throws an exception.
+ */
@Test
- public void test() {
- App.main(new String[]{});
+ void shouldExecuteApplicationWithoutException() {
+ assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
diff --git a/delegation/src/test/java/com/iluwatar/delegation/simple/DelegateTest.java b/delegation/src/test/java/com/iluwatar/delegation/simple/DelegateTest.java
index 2da1e0571..8aefc4b56 100644
--- a/delegation/src/test/java/com/iluwatar/delegation/simple/DelegateTest.java
+++ b/delegation/src/test/java/com/iluwatar/delegation/simple/DelegateTest.java
@@ -86,7 +86,7 @@ public class DelegateTest {
*/
private class InMemoryAppender extends AppenderBase {
- private List log = new LinkedList<>();
+ private final List log = new LinkedList<>();
public InMemoryAppender() {
((Logger) LoggerFactory.getLogger("root")).addAppender(this);
diff --git a/dependency-injection/README.md b/dependency-injection/README.md
index abf647b50..b47c1d2f9 100644
--- a/dependency-injection/README.md
+++ b/dependency-injection/README.md
@@ -62,7 +62,7 @@ public interface Wizard {
public class AdvancedWizard implements Wizard {
- private Tobacco tobacco;
+ private final Tobacco tobacco;
public AdvancedWizard(Tobacco tobacco) {
this.tobacco = tobacco;
diff --git a/dependency-injection/pom.xml b/dependency-injection/pom.xml
index 9baffe382..f3aaba520 100644
--- a/dependency-injection/pom.xml
+++ b/dependency-injection/pom.xml
@@ -29,7 +29,7 @@
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
dependency-injection
diff --git a/dependency-injection/src/main/java/com/iluwatar/dependency/injection/AdvancedWizard.java b/dependency-injection/src/main/java/com/iluwatar/dependency/injection/AdvancedWizard.java
index e0c952186..f0ff2da94 100644
--- a/dependency-injection/src/main/java/com/iluwatar/dependency/injection/AdvancedWizard.java
+++ b/dependency-injection/src/main/java/com/iluwatar/dependency/injection/AdvancedWizard.java
@@ -29,7 +29,7 @@ package com.iluwatar.dependency.injection;
*/
public class AdvancedWizard implements Wizard {
- private Tobacco tobacco;
+ private final Tobacco tobacco;
public AdvancedWizard(Tobacco tobacco) {
this.tobacco = tobacco;
diff --git a/dependency-injection/src/main/java/com/iluwatar/dependency/injection/GuiceWizard.java b/dependency-injection/src/main/java/com/iluwatar/dependency/injection/GuiceWizard.java
index 319a635eb..d769ffd46 100644
--- a/dependency-injection/src/main/java/com/iluwatar/dependency/injection/GuiceWizard.java
+++ b/dependency-injection/src/main/java/com/iluwatar/dependency/injection/GuiceWizard.java
@@ -31,7 +31,7 @@ import javax.inject.Inject;
*/
public class GuiceWizard implements Wizard {
- private Tobacco tobacco;
+ private final Tobacco tobacco;
@Inject
public GuiceWizard(Tobacco tobacco) {
diff --git a/dependency-injection/src/main/java/com/iluwatar/dependency/injection/SimpleWizard.java b/dependency-injection/src/main/java/com/iluwatar/dependency/injection/SimpleWizard.java
index 40bca0ffb..0136ff69f 100644
--- a/dependency-injection/src/main/java/com/iluwatar/dependency/injection/SimpleWizard.java
+++ b/dependency-injection/src/main/java/com/iluwatar/dependency/injection/SimpleWizard.java
@@ -29,7 +29,7 @@ package com.iluwatar.dependency.injection;
*/
public class SimpleWizard implements Wizard {
- private OldTobyTobacco tobacco = new OldTobyTobacco();
+ private final OldTobyTobacco tobacco = new OldTobyTobacco();
public void smoke() {
tobacco.smoke(this);
diff --git a/dependency-injection/src/test/java/com/iluwatar/dependency/injection/AppTest.java b/dependency-injection/src/test/java/com/iluwatar/dependency/injection/AppTest.java
index 51115496d..52508814a 100644
--- a/dependency-injection/src/test/java/com/iluwatar/dependency/injection/AppTest.java
+++ b/dependency-injection/src/test/java/com/iluwatar/dependency/injection/AppTest.java
@@ -25,13 +25,22 @@ package com.iluwatar.dependency.injection;
import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+
/**
* Application test
*/
-public class AppTest {
+class AppTest {
+
+ /**
+ * Issue: Add at least one assertion to this test case.
+ *
+ * Solution: Inserted assertion to check whether the execution of the main method in {@link App#main(String[])}
+ * throws an exception.
+ */
@Test
- public void test() {
- App.main(new String[]{});
+ void shouldExecuteApplicationWithoutException() {
+ assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
diff --git a/dependency-injection/src/test/java/com/iluwatar/dependency/injection/utils/InMemoryAppender.java b/dependency-injection/src/test/java/com/iluwatar/dependency/injection/utils/InMemoryAppender.java
index 9d0ad1b3b..d91099af9 100644
--- a/dependency-injection/src/test/java/com/iluwatar/dependency/injection/utils/InMemoryAppender.java
+++ b/dependency-injection/src/test/java/com/iluwatar/dependency/injection/utils/InMemoryAppender.java
@@ -37,7 +37,7 @@ import java.util.List;
*/
public class InMemoryAppender extends AppenderBase {
- private List log = new LinkedList<>();
+ private final List log = new LinkedList<>();
public InMemoryAppender(Class clazz) {
((Logger) LoggerFactory.getLogger(clazz)).addAppender(this);
diff --git a/dirty-flag/pom.xml b/dirty-flag/pom.xml
index c014cd41e..b796ab37a 100644
--- a/dirty-flag/pom.xml
+++ b/dirty-flag/pom.xml
@@ -29,11 +29,10 @@
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
- com.iluwatar
dirty-flag
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
dirty-flag
http://maven.apache.org
@@ -45,6 +44,12 @@
junit-jupiter-engine
test
+
+ org.mockito
+ mockito-junit-jupiter
+ 3.5.0
+ test
+
diff --git a/dirty-flag/src/main/java/com/iluwatar/dirtyflag/World.java b/dirty-flag/src/main/java/com/iluwatar/dirtyflag/World.java
index db60924c1..1d4fbfa75 100644
--- a/dirty-flag/src/main/java/com/iluwatar/dirtyflag/World.java
+++ b/dirty-flag/src/main/java/com/iluwatar/dirtyflag/World.java
@@ -34,7 +34,7 @@ import java.util.List;
public class World {
private List countries;
- private DataFetcher df;
+ private final DataFetcher df;
public World() {
this.countries = new ArrayList();
diff --git a/dirty-flag/src/main/java/com/iluwatar/dirtyflag/module-info.java b/dirty-flag/src/main/java/com/iluwatar/dirtyflag/module-info.java
deleted file mode 100644
index bf47d2cd7..000000000
--- a/dirty-flag/src/main/java/com/iluwatar/dirtyflag/module-info.java
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * The MIT License
- * Copyright © 2014-2019 Ilkka Seppälä
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-
-module com.iluwatar.dirtyflag {
- requires org.slf4j;
-}
\ No newline at end of file
diff --git a/dirty-flag/src/test/java/org/dirty/flag/AppTest.java b/dirty-flag/src/test/java/org/dirty/flag/AppTest.java
index 1b604898b..82c7fea9b 100644
--- a/dirty-flag/src/test/java/org/dirty/flag/AppTest.java
+++ b/dirty-flag/src/test/java/org/dirty/flag/AppTest.java
@@ -26,12 +26,22 @@ package org.dirty.flag;
import com.iluwatar.dirtyflag.App;
import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+
/**
* Tests that Dirty-Flag example runs without errors.
*/
-public class AppTest {
+class AppTest {
+
+ /**
+ * Issue: Add at least one assertion to this test case.
+ *
+ * Solution: Inserted assertion to check whether the execution of the main method in {@link App#main(String[])}
+ * throws an exception.
+ */
+
@Test
- public void test() {
- App.main(new String[]{});
+ void shouldExecuteApplicationWithoutException() {
+ assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
diff --git a/dirty-flag/src/test/java/org/dirty/flag/DirtyFlagTest.java b/dirty-flag/src/test/java/org/dirty/flag/DirtyFlagTest.java
index 6a3274a45..9af9664d6 100644
--- a/dirty-flag/src/test/java/org/dirty/flag/DirtyFlagTest.java
+++ b/dirty-flag/src/test/java/org/dirty/flag/DirtyFlagTest.java
@@ -23,29 +23,27 @@
package org.dirty.flag;
-import static org.junit.jupiter.api.Assertions.assertFalse;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
import com.iluwatar.dirtyflag.DataFetcher;
+import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
/**
* Application test
*/
-public class DirtyFlagTest {
+class DirtyFlagTest {
@Test
- public void testIsDirty() {
+ void testIsDirty() {
var df = new DataFetcher();
var countries = df.fetch();
- assertFalse(countries.isEmpty());
+ Assertions.assertFalse(countries.isEmpty());
}
@Test
- public void testIsNotDirty() {
+ void testIsNotDirty() {
var df = new DataFetcher();
df.fetch();
var countries = df.fetch();
- assertTrue(countries.isEmpty());
+ Assertions.assertTrue(countries.isEmpty());
}
}
diff --git a/double-buffer/pom.xml b/double-buffer/pom.xml
index 084cbc8c9..cc4032074 100644
--- a/double-buffer/pom.xml
+++ b/double-buffer/pom.xml
@@ -29,7 +29,7 @@
java-design-patterns
com.iluwatar
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
4.0.0
@@ -44,6 +44,11 @@
org.apache.commons
commons-lang3
+
+ org.junit.jupiter
+ junit-jupiter-engine
+ test
+
diff --git a/double-buffer/src/main/java/com/iluwatar/doublebuffer/FrameBuffer.java b/double-buffer/src/main/java/com/iluwatar/doublebuffer/FrameBuffer.java
index 5f683cf1e..4b974a2e8 100644
--- a/double-buffer/src/main/java/com/iluwatar/doublebuffer/FrameBuffer.java
+++ b/double-buffer/src/main/java/com/iluwatar/doublebuffer/FrameBuffer.java
@@ -33,7 +33,7 @@ public class FrameBuffer implements Buffer {
public static final int WIDTH = 10;
public static final int HEIGHT = 8;
- private Pixel[] pixels = new Pixel[WIDTH * HEIGHT];
+ private final Pixel[] pixels = new Pixel[WIDTH * HEIGHT];
public FrameBuffer() {
clearAll();
diff --git a/double-buffer/src/main/java/com/iluwatar/doublebuffer/Pixel.java b/double-buffer/src/main/java/com/iluwatar/doublebuffer/Pixel.java
index 501797743..54f130b1d 100644
--- a/double-buffer/src/main/java/com/iluwatar/doublebuffer/Pixel.java
+++ b/double-buffer/src/main/java/com/iluwatar/doublebuffer/Pixel.java
@@ -31,7 +31,7 @@ public enum Pixel {
WHITE(0),
BLACK(1);
- private int color;
+ private final int color;
Pixel(int color) {
this.color = color;
diff --git a/double-buffer/src/main/java/com/iluwatar/doublebuffer/Scene.java b/double-buffer/src/main/java/com/iluwatar/doublebuffer/Scene.java
index 2c1503918..8ee72ded4 100644
--- a/double-buffer/src/main/java/com/iluwatar/doublebuffer/Scene.java
+++ b/double-buffer/src/main/java/com/iluwatar/doublebuffer/Scene.java
@@ -35,7 +35,7 @@ public class Scene {
private static final Logger LOGGER = LoggerFactory.getLogger(Scene.class);
- private Buffer[] frameBuffers;
+ private final Buffer[] frameBuffers;
private int current;
diff --git a/double-buffer/src/test/java/com/iluwatar/doublebuffer/AppTest.java b/double-buffer/src/test/java/com/iluwatar/doublebuffer/AppTest.java
index eb89a4044..6612d2b00 100644
--- a/double-buffer/src/test/java/com/iluwatar/doublebuffer/AppTest.java
+++ b/double-buffer/src/test/java/com/iluwatar/doublebuffer/AppTest.java
@@ -25,14 +25,23 @@ package com.iluwatar.doublebuffer;
import org.junit.Test;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+
/**
* App unit test.
*/
public class AppTest {
+ /**
+ * Issue: Add at least one assertion to this test case.
+ *
+ * Solution: Inserted assertion to check whether the execution of the main method in {@link App#main(String[])}
+ * throws an exception.
+ */
+
@Test
- public void testMain() {
- App.main(new String[]{});
+ public void shouldExecuteApplicationWithoutException() {
+ assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
diff --git a/double-checked-locking/pom.xml b/double-checked-locking/pom.xml
index a77546386..04aba2260 100644
--- a/double-checked-locking/pom.xml
+++ b/double-checked-locking/pom.xml
@@ -27,7 +27,7 @@
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
double-checked-locking
diff --git a/double-checked-locking/src/main/java/com/iluwatar/doublechecked/locking/module-info.java b/double-checked-locking/src/main/java/com/iluwatar/doublechecked/locking/module-info.java
deleted file mode 100644
index 4f4216ea7..000000000
--- a/double-checked-locking/src/main/java/com/iluwatar/doublechecked/locking/module-info.java
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * The MIT License
- * Copyright © 2014-2019 Ilkka Seppälä
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-
-module com.iluwatar.doublecheckedlocking {
- requires org.slf4j;
-}
\ No newline at end of file
diff --git a/double-checked-locking/src/test/java/com/iluwatar/doublechecked/locking/AppTest.java b/double-checked-locking/src/test/java/com/iluwatar/doublechecked/locking/AppTest.java
index 6eac88fcd..e24e51094 100644
--- a/double-checked-locking/src/test/java/com/iluwatar/doublechecked/locking/AppTest.java
+++ b/double-checked-locking/src/test/java/com/iluwatar/doublechecked/locking/AppTest.java
@@ -25,13 +25,23 @@ package com.iluwatar.doublechecked.locking;
import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+
/**
* Application test
*/
-public class AppTest {
+class AppTest {
+
+ /**
+ * Issue: Add at least one assertion to this test case.
+ *
+ * Solution: Inserted assertion to check whether the execution of the main method in {@link App#main(String[])}
+ * throws an exception.
+ */
+
@Test
- public void test() {
- App.main(new String[]{});
+ void shouldExecuteApplicationWithoutException() {
+ assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
diff --git a/double-checked-locking/src/test/java/com/iluwatar/doublechecked/locking/InventoryTest.java b/double-checked-locking/src/test/java/com/iluwatar/doublechecked/locking/InventoryTest.java
index e8ea7c6f8..fe0cbf5e9 100644
--- a/double-checked-locking/src/test/java/com/iluwatar/doublechecked/locking/InventoryTest.java
+++ b/double-checked-locking/src/test/java/com/iluwatar/doublechecked/locking/InventoryTest.java
@@ -109,7 +109,7 @@ public class InventoryTest {
private class InMemoryAppender extends AppenderBase {
- private List log = new LinkedList<>();
+ private final List log = new LinkedList<>();
public InMemoryAppender(Class clazz) {
((Logger) LoggerFactory.getLogger(clazz)).addAppender(this);
diff --git a/double-dispatch/pom.xml b/double-dispatch/pom.xml
index 9582797a2..275b505a5 100644
--- a/double-dispatch/pom.xml
+++ b/double-dispatch/pom.xml
@@ -29,7 +29,7 @@
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
double-dispatch
diff --git a/double-dispatch/src/main/java/com/iluwatar/doubledispatch/Rectangle.java b/double-dispatch/src/main/java/com/iluwatar/doubledispatch/Rectangle.java
index bd832287c..ea18ca3dc 100644
--- a/double-dispatch/src/main/java/com/iluwatar/doubledispatch/Rectangle.java
+++ b/double-dispatch/src/main/java/com/iluwatar/doubledispatch/Rectangle.java
@@ -28,10 +28,10 @@ package com.iluwatar.doubledispatch;
*/
public class Rectangle {
- private int left;
- private int top;
- private int right;
- private int bottom;
+ private final int left;
+ private final int top;
+ private final int right;
+ private final int bottom;
/**
* Constructor.
diff --git a/double-dispatch/src/main/java/com/iluwatar/doubledispatch/module-info.java b/double-dispatch/src/main/java/com/iluwatar/doubledispatch/module-info.java
deleted file mode 100644
index b1bc2e824..000000000
--- a/double-dispatch/src/main/java/com/iluwatar/doubledispatch/module-info.java
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * The MIT License
- * Copyright © 2014-2019 Ilkka Seppälä
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-
-module com.iluwatar.doubledispatch {
- requires org.slf4j;
-}
\ No newline at end of file
diff --git a/double-dispatch/src/test/java/com/iluwatar/doubledispatch/AppTest.java b/double-dispatch/src/test/java/com/iluwatar/doubledispatch/AppTest.java
index 67ca00c56..e5df7a2be 100644
--- a/double-dispatch/src/test/java/com/iluwatar/doubledispatch/AppTest.java
+++ b/double-dispatch/src/test/java/com/iluwatar/doubledispatch/AppTest.java
@@ -25,13 +25,23 @@ package com.iluwatar.doubledispatch;
import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+
/**
* Application test
*/
-public class AppTest {
+class AppTest {
+
+ /**
+ * Issue: Add at least one assertion to this test case.
+ *
+ * Solution: Inserted assertion to check whether the execution of the main method in {@link App#main(String[])}
+ * throws an exception.
+ */
+
@Test
- public void test() {
- App.main(new String[]{});
+ void shouldExecuteApplicationWithoutException() {
+ assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
diff --git a/eip-aggregator/pom.xml b/eip-aggregator/pom.xml
index 578d1bbf2..efee153a3 100644
--- a/eip-aggregator/pom.xml
+++ b/eip-aggregator/pom.xml
@@ -31,7 +31,7 @@
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
diff --git a/eip-aggregator/src/test/java/com/iluwatar/eip/aggregator/AppTest.java b/eip-aggregator/src/test/java/com/iluwatar/eip/aggregator/AppTest.java
index ed604e8c2..3da3b3e66 100644
--- a/eip-aggregator/src/test/java/com/iluwatar/eip/aggregator/AppTest.java
+++ b/eip-aggregator/src/test/java/com/iluwatar/eip/aggregator/AppTest.java
@@ -25,13 +25,22 @@ package com.iluwatar.eip.aggregator;
import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+
/**
* Test for App class
*/
-public class AppTest {
+class AppTest {
+
+ /**
+ * Issue: Add at least one assertion to this test case.
+ *
+ * Solution: Inserted assertion to check whether the execution of the main method in {@link App#main(String[])}
+ * throws an exception.
+ */
@Test
- public void testMain() throws Exception {
- App.main(new String[]{});
+ void shouldExecuteApplicationWithoutException() {
+ assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
diff --git a/eip-message-channel/pom.xml b/eip-message-channel/pom.xml
index bea72b1f9..12fe153e3 100644
--- a/eip-message-channel/pom.xml
+++ b/eip-message-channel/pom.xml
@@ -30,7 +30,7 @@
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
eip-message-channel
diff --git a/eip-message-channel/src/main/java/com/iluwatar/eip/message/channel/module-info.java b/eip-message-channel/src/main/java/com/iluwatar/eip/message/channel/module-info.java
deleted file mode 100644
index b904ee1c8..000000000
--- a/eip-message-channel/src/main/java/com/iluwatar/eip/message/channel/module-info.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * The MIT License
- * Copyright © 2014-2019 Ilkka Seppälä
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-
-module com.iluwatar.eipmessagechannel {
- requires org.slf4j;
- requires camel.core;
-}
\ No newline at end of file
diff --git a/eip-message-channel/src/test/java/com/iluwatar/eip/message/channel/AppTest.java b/eip-message-channel/src/test/java/com/iluwatar/eip/message/channel/AppTest.java
index 9f11c0209..14cdc5c65 100644
--- a/eip-message-channel/src/test/java/com/iluwatar/eip/message/channel/AppTest.java
+++ b/eip-message-channel/src/test/java/com/iluwatar/eip/message/channel/AppTest.java
@@ -25,13 +25,22 @@ package com.iluwatar.eip.message.channel;
import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+
/**
* Application test
*/
-public class AppTest {
+class AppTest {
+
+ /**
+ * Issue: Add at least one assertion to this test case.
+ *
+ * Solution: Inserted assertion to check whether the execution of the main method in {@link App#main(String[])}
+ * throws an exception.
+ */
@Test
- public void test() throws Exception {
- App.main(new String[]{});
+ void shouldExecuteApplicationWithoutException() {
+ assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
diff --git a/eip-publish-subscribe/pom.xml b/eip-publish-subscribe/pom.xml
index e7b5462b6..f354b1ee3 100644
--- a/eip-publish-subscribe/pom.xml
+++ b/eip-publish-subscribe/pom.xml
@@ -28,7 +28,7 @@
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
eip-publish-subscribe
diff --git a/eip-publish-subscribe/src/main/java/com/iluwatar/eip/publish/subscribe/module-info.java b/eip-publish-subscribe/src/main/java/com/iluwatar/eip/publish/subscribe/module-info.java
deleted file mode 100644
index 50eab8360..000000000
--- a/eip-publish-subscribe/src/main/java/com/iluwatar/eip/publish/subscribe/module-info.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * The MIT License
- * Copyright © 2014-2019 Ilkka Seppälä
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-
-module com.iluwatar.eippublishsubscribe {
- requires org.slf4j;
- requires camel.core;
-}
\ No newline at end of file
diff --git a/eip-publish-subscribe/src/test/java/com/iluwatar/eip/publish/subscribe/AppTest.java b/eip-publish-subscribe/src/test/java/com/iluwatar/eip/publish/subscribe/AppTest.java
index 107e954ed..f910d0abe 100644
--- a/eip-publish-subscribe/src/test/java/com/iluwatar/eip/publish/subscribe/AppTest.java
+++ b/eip-publish-subscribe/src/test/java/com/iluwatar/eip/publish/subscribe/AppTest.java
@@ -25,13 +25,22 @@ package com.iluwatar.eip.publish.subscribe;
import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+
/**
* Application test
*/
-public class AppTest {
+class AppTest {
+
+ /**
+ * Issue: Add at least one assertion to this test case.
+ *
+ * Solution: Inserted assertion to check whether the execution of the main method in {@link App#main(String[])}
+ * throws an exception.
+ */
@Test
- public void test() throws Exception {
- App.main(new String[]{});
+ void shouldExecuteApplicationWithoutException() {
+ assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
diff --git a/eip-splitter/pom.xml b/eip-splitter/pom.xml
index 9c06f3f8d..5b4758a9e 100644
--- a/eip-splitter/pom.xml
+++ b/eip-splitter/pom.xml
@@ -31,7 +31,7 @@
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
diff --git a/eip-splitter/src/test/java/com/iluwatar/eip/splitter/AppTest.java b/eip-splitter/src/test/java/com/iluwatar/eip/splitter/AppTest.java
index 1a7dfcb0a..d5936282e 100644
--- a/eip-splitter/src/test/java/com/iluwatar/eip/splitter/AppTest.java
+++ b/eip-splitter/src/test/java/com/iluwatar/eip/splitter/AppTest.java
@@ -25,13 +25,22 @@ package com.iluwatar.eip.splitter;
import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+
/**
* Test for App class
*/
-public class AppTest {
+class AppTest {
+
+ /**
+ * Issue: Add at least one assertion to this test case.
+ *
+ * Solution: Inserted assertion to check whether the execution of the main method in {@link App#main(String[])}
+ * throws an exception.
+ */
@Test
- public void testMain() throws Exception {
- App.main(new String[]{});
+ void shouldExecuteApplicationWithoutException() {
+ assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
diff --git a/eip-wire-tap/pom.xml b/eip-wire-tap/pom.xml
index 06cbc33db..332861547 100644
--- a/eip-wire-tap/pom.xml
+++ b/eip-wire-tap/pom.xml
@@ -31,7 +31,7 @@
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
diff --git a/eip-wire-tap/src/test/java/com/iluwatar/eip/wiretap/AppTest.java b/eip-wire-tap/src/test/java/com/iluwatar/eip/wiretap/AppTest.java
index 31154043c..8be8bcbe7 100644
--- a/eip-wire-tap/src/test/java/com/iluwatar/eip/wiretap/AppTest.java
+++ b/eip-wire-tap/src/test/java/com/iluwatar/eip/wiretap/AppTest.java
@@ -25,13 +25,22 @@ package com.iluwatar.eip.wiretap;
import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+
/**
* Test for App class
*/
-public class AppTest {
+class AppTest {
+
+ /**
+ * Issue: Add at least one assertion to this test case.
+ *
+ * Solution: Inserted assertion to check whether the execution of the main method in {@link App#main(String[])}
+ * throws an exception.
+ */
@Test
- public void testMain() throws Exception {
- App.main(new String[]{});
+ void shouldExecuteApplicationWithoutException() {
+ assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
diff --git a/event-aggregator/pom.xml b/event-aggregator/pom.xml
index 5553de2e3..813521c48 100644
--- a/event-aggregator/pom.xml
+++ b/event-aggregator/pom.xml
@@ -28,7 +28,7 @@
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
event-aggregator
diff --git a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/Event.java b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/Event.java
index 7a125c042..91bb020ee 100644
--- a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/Event.java
+++ b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/Event.java
@@ -31,7 +31,7 @@ public enum Event {
STARK_SIGHTED("Stark sighted"), WARSHIPS_APPROACHING("Warships approaching"), TRAITOR_DETECTED(
"Traitor detected");
- private String description;
+ private final String description;
Event(String description) {
this.description = description;
diff --git a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/EventEmitter.java b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/EventEmitter.java
index 9985cee60..7d3f32a68 100644
--- a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/EventEmitter.java
+++ b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/EventEmitter.java
@@ -31,7 +31,7 @@ import java.util.List;
*/
public abstract class EventEmitter {
- private List observers;
+ private final List observers;
public EventEmitter() {
observers = new LinkedList<>();
diff --git a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/Weekday.java b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/Weekday.java
index 9ec61339c..1e0ce9491 100644
--- a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/Weekday.java
+++ b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/Weekday.java
@@ -36,7 +36,7 @@ public enum Weekday {
SATURDAY("Saturday"),
SUNDAY("Sunday");
- private String description;
+ private final String description;
Weekday(String description) {
this.description = description;
diff --git a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/module-info.java b/event-aggregator/src/main/java/com/iluwatar/event/aggregator/module-info.java
deleted file mode 100644
index 93ebd3173..000000000
--- a/event-aggregator/src/main/java/com/iluwatar/event/aggregator/module-info.java
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * The MIT License
- * Copyright © 2014-2019 Ilkka Seppälä
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-
-module com.iluwatar.eventaggregator {
- requires org.slf4j;
-}
\ No newline at end of file
diff --git a/event-aggregator/src/test/java/com/iluwatar/event/aggregator/AppTest.java b/event-aggregator/src/test/java/com/iluwatar/event/aggregator/AppTest.java
index a65424023..e56bc9d7f 100644
--- a/event-aggregator/src/test/java/com/iluwatar/event/aggregator/AppTest.java
+++ b/event-aggregator/src/test/java/com/iluwatar/event/aggregator/AppTest.java
@@ -25,13 +25,22 @@ package com.iluwatar.event.aggregator;
import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+
/**
* Application test
*/
-public class AppTest {
+class AppTest {
+
+ /**
+ * Issue: Add at least one assertion to this test case.
+ *
+ * Solution: Inserted assertion to check whether the execution of the main method in {@link App#main(String[])}
+ * throws an exception.
+ */
@Test
- public void test() {
- App.main(new String[]{});
+ void shouldExecuteApplicationWithoutException() {
+ assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
diff --git a/event-aggregator/src/test/java/com/iluwatar/event/aggregator/KingJoffreyTest.java b/event-aggregator/src/test/java/com/iluwatar/event/aggregator/KingJoffreyTest.java
index a8bb6cbaa..f8aa5cb37 100644
--- a/event-aggregator/src/test/java/com/iluwatar/event/aggregator/KingJoffreyTest.java
+++ b/event-aggregator/src/test/java/com/iluwatar/event/aggregator/KingJoffreyTest.java
@@ -74,7 +74,7 @@ public class KingJoffreyTest {
}
private class InMemoryAppender extends AppenderBase {
- private List log = new LinkedList<>();
+ private final List log = new LinkedList<>();
public InMemoryAppender(Class> clazz) {
((Logger) LoggerFactory.getLogger(clazz)).addAppender(this);
diff --git a/event-asynchronous/pom.xml b/event-asynchronous/pom.xml
index 001b3b9a8..06921a100 100644
--- a/event-asynchronous/pom.xml
+++ b/event-asynchronous/pom.xml
@@ -29,7 +29,7 @@
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
event-asynchronous
diff --git a/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/Event.java b/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/Event.java
index 6925a2ffd..68c4c9781 100644
--- a/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/Event.java
+++ b/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/Event.java
@@ -33,9 +33,9 @@ public class Event implements IEvent, Runnable {
private static final Logger LOGGER = LoggerFactory.getLogger(Event.class);
- private int eventId;
- private int eventTime;
- private boolean isSynchronous;
+ private final int eventId;
+ private final int eventTime;
+ private final boolean isSynchronous;
private Thread thread;
private boolean isComplete = false;
private ThreadCompleteListener eventListener;
diff --git a/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/EventManager.java b/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/EventManager.java
index 14d28860b..55671fd82 100644
--- a/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/EventManager.java
+++ b/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/EventManager.java
@@ -43,8 +43,8 @@ public class EventManager implements ThreadCompleteListener {
public static final int MAX_ID = MAX_RUNNING_EVENTS;
public static final int MAX_EVENT_TIME = 1800; // in seconds / 30 minutes.
private int currentlyRunningSyncEvent = -1;
- private Random rand;
- private Map eventPool;
+ private final Random rand;
+ private final Map eventPool;
private static final String DOES_NOT_EXIST = " does not exist.";
diff --git a/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/module-info.java b/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/module-info.java
deleted file mode 100644
index aa9b6c29d..000000000
--- a/event-asynchronous/src/main/java/com/iluwatar/event/asynchronous/module-info.java
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * The MIT License
- * Copyright © 2014-2019 Ilkka Seppälä
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-
-module com.iluwatar.eventasynchronous {
- requires org.slf4j;
-}
\ No newline at end of file
diff --git a/event-asynchronous/src/test/java/com/iluwatar/event/asynchronous/AppTest.java b/event-asynchronous/src/test/java/com/iluwatar/event/asynchronous/AppTest.java
index 76554d6b1..638e77f87 100644
--- a/event-asynchronous/src/test/java/com/iluwatar/event/asynchronous/AppTest.java
+++ b/event-asynchronous/src/test/java/com/iluwatar/event/asynchronous/AppTest.java
@@ -25,12 +25,22 @@ package com.iluwatar.event.asynchronous;
import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+
/**
* Tests that EventAsynchronous example runs without errors.
*/
-public class AppTest {
+class AppTest {
+
+ /**
+ * Issue: Add at least one assertion to this test case.
+ *
+ * Solution: Inserted assertion to check whether the execution of the main method in {@link App#main(String[])}
+ * throws an exception.
+ */
+
@Test
- public void test() {
- App.main(new String[]{});
+ void shouldExecuteApplicationWithoutException() {
+ assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
diff --git a/event-driven-architecture/pom.xml b/event-driven-architecture/pom.xml
index 17d2795c4..c40a8821b 100644
--- a/event-driven-architecture/pom.xml
+++ b/event-driven-architecture/pom.xml
@@ -31,7 +31,7 @@
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
event-driven-architecture
diff --git a/event-driven-architecture/src/main/java/com/iluwatar/eda/event/UserCreatedEvent.java b/event-driven-architecture/src/main/java/com/iluwatar/eda/event/UserCreatedEvent.java
index c18426c95..dd5e65a9a 100644
--- a/event-driven-architecture/src/main/java/com/iluwatar/eda/event/UserCreatedEvent.java
+++ b/event-driven-architecture/src/main/java/com/iluwatar/eda/event/UserCreatedEvent.java
@@ -32,7 +32,7 @@ import com.iluwatar.eda.model.User;
*/
public class UserCreatedEvent extends AbstractEvent {
- private User user;
+ private final User user;
public UserCreatedEvent(User user) {
this.user = user;
diff --git a/event-driven-architecture/src/main/java/com/iluwatar/eda/event/UserUpdatedEvent.java b/event-driven-architecture/src/main/java/com/iluwatar/eda/event/UserUpdatedEvent.java
index 59583053c..05370c6a6 100644
--- a/event-driven-architecture/src/main/java/com/iluwatar/eda/event/UserUpdatedEvent.java
+++ b/event-driven-architecture/src/main/java/com/iluwatar/eda/event/UserUpdatedEvent.java
@@ -32,7 +32,7 @@ import com.iluwatar.eda.model.User;
*/
public class UserUpdatedEvent extends AbstractEvent {
- private User user;
+ private final User user;
public UserUpdatedEvent(User user) {
this.user = user;
diff --git a/event-driven-architecture/src/main/java/com/iluwatar/eda/framework/EventDispatcher.java b/event-driven-architecture/src/main/java/com/iluwatar/eda/framework/EventDispatcher.java
index dd72c1e93..74a7ee145 100644
--- a/event-driven-architecture/src/main/java/com/iluwatar/eda/framework/EventDispatcher.java
+++ b/event-driven-architecture/src/main/java/com/iluwatar/eda/framework/EventDispatcher.java
@@ -32,7 +32,7 @@ import java.util.Map;
*/
public class EventDispatcher {
- private Map, Handler extends Event>> handlers;
+ private final Map, Handler extends Event>> handlers;
public EventDispatcher() {
handlers = new HashMap<>();
diff --git a/event-driven-architecture/src/main/java/com/iluwatar/eda/model/User.java b/event-driven-architecture/src/main/java/com/iluwatar/eda/model/User.java
index 1492c175c..0c9f12501 100644
--- a/event-driven-architecture/src/main/java/com/iluwatar/eda/model/User.java
+++ b/event-driven-architecture/src/main/java/com/iluwatar/eda/model/User.java
@@ -32,7 +32,7 @@ import com.iluwatar.eda.event.UserUpdatedEvent;
*/
public class User {
- private String username;
+ private final String username;
public User(String username) {
this.username = username;
diff --git a/event-driven-architecture/src/test/java/com/iluwatar/eda/AppTest.java b/event-driven-architecture/src/test/java/com/iluwatar/eda/AppTest.java
index 0f1720363..eb944a22c 100644
--- a/event-driven-architecture/src/test/java/com/iluwatar/eda/AppTest.java
+++ b/event-driven-architecture/src/test/java/com/iluwatar/eda/AppTest.java
@@ -25,12 +25,22 @@ package com.iluwatar.eda;
import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+
/**
* Tests that Event Driven Architecture example runs without errors.
*/
-public class AppTest {
+class AppTest {
+
+ /**
+ * Issue: Add at least one assertion to this test case.
+ *
+ * Solution: Inserted assertion to check whether the execution of the main method in {@link App#main(String[])}
+ * throws an exception.
+ */
+
@Test
- public void test() {
- App.main(new String[]{});
+ void shouldExecuteApplicationWithoutException() {
+ assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
diff --git a/event-queue/pom.xml b/event-queue/pom.xml
index fd8ce9902..232b9abaa 100644
--- a/event-queue/pom.xml
+++ b/event-queue/pom.xml
@@ -30,7 +30,7 @@
java-design-patterns
com.iluwatar
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
event-queue
diff --git a/event-queue/src/main/java/com/iluwatar/event/queue/Audio.java b/event-queue/src/main/java/com/iluwatar/event/queue/Audio.java
index 4286a5ed0..a0ff5d987 100644
--- a/event-queue/src/main/java/com/iluwatar/event/queue/Audio.java
+++ b/event-queue/src/main/java/com/iluwatar/event/queue/Audio.java
@@ -49,7 +49,7 @@ public class Audio {
private volatile Thread updateThread = null;
- private PlayMessage[] pendingAudio = new PlayMessage[MAX_PENDING];
+ private final PlayMessage[] pendingAudio = new PlayMessage[MAX_PENDING];
// Visible only for testing purposes
Audio() {
diff --git a/event-sourcing/pom.xml b/event-sourcing/pom.xml
index 0d1592abb..44af5fc5e 100644
--- a/event-sourcing/pom.xml
+++ b/event-sourcing/pom.xml
@@ -30,7 +30,7 @@
java-design-patterns
com.iluwatar
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
event-sourcing
diff --git a/execute-around/pom.xml b/execute-around/pom.xml
index 1752f04f5..2d0640fe0 100644
--- a/execute-around/pom.xml
+++ b/execute-around/pom.xml
@@ -29,7 +29,7 @@
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
execute-around
diff --git a/execute-around/src/main/java/com/iluwatar/execute/around/module-info.java b/execute-around/src/main/java/com/iluwatar/execute/around/module-info.java
deleted file mode 100644
index a3e179094..000000000
--- a/execute-around/src/main/java/com/iluwatar/execute/around/module-info.java
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * The MIT License
- * Copyright © 2014-2019 Ilkka Seppälä
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-
-module com.iluwatar.executearound {
- requires org.slf4j;
-}
\ No newline at end of file
diff --git a/execute-around/src/test/java/com/iluwatar/execute/around/AppTest.java b/execute-around/src/test/java/com/iluwatar/execute/around/AppTest.java
index 5512ba8d2..6516ede4a 100644
--- a/execute-around/src/test/java/com/iluwatar/execute/around/AppTest.java
+++ b/execute-around/src/test/java/com/iluwatar/execute/around/AppTest.java
@@ -29,19 +29,21 @@ import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+
/**
* Tests execute-around example.
*/
-public class AppTest {
+class AppTest {
@Test
- public void test() throws IOException {
- App.main(new String[]{});
+ void shouldExecuteApplicationWithoutException() {
+ assertDoesNotThrow(() -> App.main(new String[]{}));
}
@BeforeEach
@AfterEach
- public void cleanup() {
+ void cleanup() {
var file = new File("testfile.txt");
file.delete();
}
diff --git a/extension-objects/pom.xml b/extension-objects/pom.xml
index 0194357ed..7247a9676 100644
--- a/extension-objects/pom.xml
+++ b/extension-objects/pom.xml
@@ -29,7 +29,7 @@
java-design-patterns
com.iluwatar
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
4.0.0
diff --git a/extension-objects/src/main/java/concreteextensions/Commander.java b/extension-objects/src/main/java/concreteextensions/Commander.java
index 5a0552b20..ffd46dd25 100644
--- a/extension-objects/src/main/java/concreteextensions/Commander.java
+++ b/extension-objects/src/main/java/concreteextensions/Commander.java
@@ -35,7 +35,7 @@ public class Commander implements CommanderExtension {
private static final Logger LOGGER = LoggerFactory.getLogger(Commander.class);
- private CommanderUnit unit;
+ private final CommanderUnit unit;
public Commander(CommanderUnit commanderUnit) {
this.unit = commanderUnit;
@@ -45,4 +45,8 @@ public class Commander implements CommanderExtension {
public void commanderReady() {
LOGGER.info("[Commander] " + unit.getName() + " is ready!");
}
+
+ public CommanderUnit getUnit() {
+ return unit;
+ }
}
diff --git a/extension-objects/src/main/java/concreteextensions/Sergeant.java b/extension-objects/src/main/java/concreteextensions/Sergeant.java
index a45b82f11..aea2ddaca 100644
--- a/extension-objects/src/main/java/concreteextensions/Sergeant.java
+++ b/extension-objects/src/main/java/concreteextensions/Sergeant.java
@@ -35,7 +35,7 @@ public class Sergeant implements SergeantExtension {
private static final Logger LOGGER = LoggerFactory.getLogger(Sergeant.class);
- private SergeantUnit unit;
+ private final SergeantUnit unit;
public Sergeant(SergeantUnit sergeantUnit) {
this.unit = sergeantUnit;
@@ -43,6 +43,10 @@ public class Sergeant implements SergeantExtension {
@Override
public void sergeantReady() {
- LOGGER.info("[Sergeant] " + unit.getName() + " is ready! ");
+ LOGGER.info("[Sergeant] " + unit.getName() + " is ready!");
+ }
+
+ public SergeantUnit getUnit() {
+ return unit;
}
}
diff --git a/extension-objects/src/main/java/concreteextensions/Soldier.java b/extension-objects/src/main/java/concreteextensions/Soldier.java
index b47ba595d..3ceaa7880 100644
--- a/extension-objects/src/main/java/concreteextensions/Soldier.java
+++ b/extension-objects/src/main/java/concreteextensions/Soldier.java
@@ -34,7 +34,7 @@ import units.SoldierUnit;
public class Soldier implements SoldierExtension {
private static final Logger LOGGER = LoggerFactory.getLogger(Soldier.class);
- private SoldierUnit unit;
+ private final SoldierUnit unit;
public Soldier(SoldierUnit soldierUnit) {
this.unit = soldierUnit;
@@ -42,6 +42,10 @@ public class Soldier implements SoldierExtension {
@Override
public void soldierReady() {
- LOGGER.info("[Solider] " + unit.getName() + " is ready!");
+ LOGGER.info("[Soldier] " + unit.getName() + " is ready!");
+ }
+
+ public SoldierUnit getUnit() {
+ return unit;
}
}
diff --git a/extension-objects/src/test/java/AppTest.java b/extension-objects/src/test/java/AppTest.java
index 2af33e506..321bf758f 100644
--- a/extension-objects/src/test/java/AppTest.java
+++ b/extension-objects/src/test/java/AppTest.java
@@ -23,13 +23,16 @@
import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+
/**
* Created by Srdjan on 03-May-17.
*/
-public class AppTest {
+class AppTest {
+
@Test
- public void main() {
- App.main(new String[]{});
+ void shouldExecuteApplicationWithoutException() {
+ assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
\ No newline at end of file
diff --git a/extension-objects/src/test/java/concreteextensions/CommanderTest.java b/extension-objects/src/test/java/concreteextensions/CommanderTest.java
index 60ff614e4..0c9d00baf 100644
--- a/extension-objects/src/test/java/concreteextensions/CommanderTest.java
+++ b/extension-objects/src/test/java/concreteextensions/CommanderTest.java
@@ -23,17 +23,43 @@
package concreteextensions;
+import ch.qos.logback.classic.Level;
+import ch.qos.logback.classic.Logger;
+import ch.qos.logback.classic.spi.ILoggingEvent;
+import ch.qos.logback.core.read.ListAppender;
import org.junit.jupiter.api.Test;
+import org.slf4j.LoggerFactory;
import units.CommanderUnit;
+import java.util.List;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
/**
* Created by Srdjan on 03-May-17.
+ *
+ * Modified by ToxicDreamz on 15-Aug-20
*/
-public class CommanderTest {
+class CommanderTest {
+
@Test
- public void commanderReady() {
+ void shouldExecuteCommanderReady() {
+
+ Logger commanderLogger = (Logger) LoggerFactory.getLogger(Commander.class);
+
+ ListAppender listAppender = new ListAppender<>();
+ listAppender.start();
+
+ commanderLogger.addAppender(listAppender);
+
final var commander = new Commander(new CommanderUnit("CommanderUnitTest"));
commander.commanderReady();
+
+ List logsList = listAppender.list;
+ assertEquals("[Commander] " + commander.getUnit().getName() + " is ready!", logsList.get(0)
+ .getMessage());
+ assertEquals(Level.INFO, logsList.get(0)
+ .getLevel());
}
}
\ No newline at end of file
diff --git a/extension-objects/src/test/java/concreteextensions/SergeantTest.java b/extension-objects/src/test/java/concreteextensions/SergeantTest.java
index a5a60d914..3970a5c80 100644
--- a/extension-objects/src/test/java/concreteextensions/SergeantTest.java
+++ b/extension-objects/src/test/java/concreteextensions/SergeantTest.java
@@ -23,17 +23,41 @@
package concreteextensions;
+import ch.qos.logback.classic.Level;
+import ch.qos.logback.classic.Logger;
+import ch.qos.logback.classic.spi.ILoggingEvent;
+import ch.qos.logback.core.read.ListAppender;
import org.junit.jupiter.api.Test;
+import org.slf4j.LoggerFactory;
import units.SergeantUnit;
+import java.util.List;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
/**
* Created by Srdjan on 03-May-17.
*/
-public class SergeantTest {
+class SergeantTest {
+
@Test
- public void sergeantReady() {
+ void sergeantReady() {
+
+ Logger sergeantLogger = (Logger) LoggerFactory.getLogger(Sergeant.class);
+
+ ListAppender listAppender = new ListAppender<>();
+ listAppender.start();
+
+ sergeantLogger.addAppender(listAppender);
+
final var sergeant = new Sergeant(new SergeantUnit("SergeantUnitTest"));
sergeant.sergeantReady();
+
+ List logsList = listAppender.list;
+ assertEquals("[Sergeant] " + sergeant.getUnit().getName() + " is ready!", logsList.get(0)
+ .getMessage());
+ assertEquals(Level.INFO, logsList.get(0)
+ .getLevel());
}
}
\ No newline at end of file
diff --git a/extension-objects/src/test/java/concreteextensions/SoldierTest.java b/extension-objects/src/test/java/concreteextensions/SoldierTest.java
index 89c8c2d91..98224e848 100644
--- a/extension-objects/src/test/java/concreteextensions/SoldierTest.java
+++ b/extension-objects/src/test/java/concreteextensions/SoldierTest.java
@@ -23,17 +23,41 @@
package concreteextensions;
+import ch.qos.logback.classic.Level;
+import ch.qos.logback.classic.Logger;
+import ch.qos.logback.classic.spi.ILoggingEvent;
+import ch.qos.logback.core.read.ListAppender;
import org.junit.jupiter.api.Test;
+import org.slf4j.LoggerFactory;
import units.SoldierUnit;
+import java.util.List;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
/**
* Created by Srdjan on 03-May-17.
*/
-public class SoldierTest {
+class SoldierTest {
+
@Test
- public void soldierReady() {
+ void soldierReady() {
+
+ Logger soldierLogger = (Logger) LoggerFactory.getLogger(Soldier.class);
+
+ ListAppender listAppender = new ListAppender<>();
+ listAppender.start();
+
+ soldierLogger.addAppender(listAppender);
+
final var soldier = new Soldier(new SoldierUnit("SoldierUnitTest"));
soldier.soldierReady();
+
+ List logsList = listAppender.list;
+ assertEquals("[Soldier] " + soldier.getUnit().getName() + " is ready!", logsList.get(0)
+ .getMessage());
+ assertEquals(Level.INFO, logsList.get(0)
+ .getLevel());
}
}
\ No newline at end of file
diff --git a/facade/README.md b/facade/README.md
index 018c493a7..ce9d892b6 100644
--- a/facade/README.md
+++ b/facade/README.md
@@ -83,7 +83,7 @@ public abstract class DwarvenMineWorker {
public abstract String name();
- static enum Action {
+ enum Action {
GO_TO_SLEEP, WAKE_UP, GO_HOME, GO_TO_MINE, WORK
}
}
diff --git a/facade/pom.xml b/facade/pom.xml
index a7fdb88f0..cf73e6a43 100644
--- a/facade/pom.xml
+++ b/facade/pom.xml
@@ -29,7 +29,7 @@
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
facade
diff --git a/facade/src/main/java/com/iluwatar/facade/module-info.java b/facade/src/main/java/com/iluwatar/facade/module-info.java
deleted file mode 100644
index 966758790..000000000
--- a/facade/src/main/java/com/iluwatar/facade/module-info.java
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * The MIT License
- * Copyright © 2014-2019 Ilkka Seppälä
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-
-module com.iluwatar.facade {
- requires org.slf4j;
-}
\ No newline at end of file
diff --git a/facade/src/test/java/com/iluwatar/facade/AppTest.java b/facade/src/test/java/com/iluwatar/facade/AppTest.java
index b6287b02b..7e2d389dc 100644
--- a/facade/src/test/java/com/iluwatar/facade/AppTest.java
+++ b/facade/src/test/java/com/iluwatar/facade/AppTest.java
@@ -25,13 +25,15 @@ package com.iluwatar.facade;
import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+
/**
* Application test
*/
-public class AppTest {
+class AppTest {
@Test
- public void test() {
- App.main(new String[]{});
+ void shouldExecuteApplicationWithoutException() {
+ assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
diff --git a/facade/src/test/java/com/iluwatar/facade/DwarvenGoldmineFacadeTest.java b/facade/src/test/java/com/iluwatar/facade/DwarvenGoldmineFacadeTest.java
index 3b67f3754..10d6e1ecd 100644
--- a/facade/src/test/java/com/iluwatar/facade/DwarvenGoldmineFacadeTest.java
+++ b/facade/src/test/java/com/iluwatar/facade/DwarvenGoldmineFacadeTest.java
@@ -110,7 +110,7 @@ public class DwarvenGoldmineFacadeTest {
private class InMemoryAppender extends AppenderBase {
- private List log = new LinkedList<>();
+ private final List log = new LinkedList<>();
public InMemoryAppender() {
((Logger) LoggerFactory.getLogger("root")).addAppender(this);
diff --git a/factory-kit/pom.xml b/factory-kit/pom.xml
index 87f27b341..987bbdb24 100644
--- a/factory-kit/pom.xml
+++ b/factory-kit/pom.xml
@@ -30,7 +30,7 @@
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
factory-kit
diff --git a/factory-kit/src/main/java/com/iluwatar/factorykit/module-info.java b/factory-kit/src/main/java/com/iluwatar/factorykit/module-info.java
deleted file mode 100644
index 9440571c4..000000000
--- a/factory-kit/src/main/java/com/iluwatar/factorykit/module-info.java
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * The MIT License
- * Copyright © 2014-2019 Ilkka Seppälä
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-
-module com.iluwatar.factorykit {
- requires org.slf4j;
-}
\ No newline at end of file
diff --git a/factory-kit/src/test/java/com/iluwatar/factorykit/app/AppTest.java b/factory-kit/src/test/java/com/iluwatar/factorykit/app/AppTest.java
index f1d3c65a2..99477aaf0 100644
--- a/factory-kit/src/test/java/com/iluwatar/factorykit/app/AppTest.java
+++ b/factory-kit/src/test/java/com/iluwatar/factorykit/app/AppTest.java
@@ -26,14 +26,16 @@ package com.iluwatar.factorykit.app;
import com.iluwatar.factorykit.App;
import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+
/**
* Application Test Entrypoint
*/
-public class AppTest {
+class AppTest {
@Test
- public void test() {
- App.main(new String[]{});
+ void shouldExecuteApplicationWithoutException() {
+ assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
diff --git a/factory-method/pom.xml b/factory-method/pom.xml
index 5f0358d4d..c49fae691 100644
--- a/factory-method/pom.xml
+++ b/factory-method/pom.xml
@@ -29,7 +29,7 @@
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
factory-method
diff --git a/factory-method/src/main/java/com/iluwatar/factory/method/ElfBlacksmith.java b/factory-method/src/main/java/com/iluwatar/factory/method/ElfBlacksmith.java
index b6f29e43a..99ebcef65 100644
--- a/factory-method/src/main/java/com/iluwatar/factory/method/ElfBlacksmith.java
+++ b/factory-method/src/main/java/com/iluwatar/factory/method/ElfBlacksmith.java
@@ -32,7 +32,7 @@ import java.util.Map;
*/
public class ElfBlacksmith implements Blacksmith {
- private static Map ELFARSENAL;
+ private static final Map ELFARSENAL;
static {
ELFARSENAL = new HashMap<>(WeaponType.values().length);
diff --git a/factory-method/src/main/java/com/iluwatar/factory/method/ElfWeapon.java b/factory-method/src/main/java/com/iluwatar/factory/method/ElfWeapon.java
index 66a6ea7e7..208dfa277 100644
--- a/factory-method/src/main/java/com/iluwatar/factory/method/ElfWeapon.java
+++ b/factory-method/src/main/java/com/iluwatar/factory/method/ElfWeapon.java
@@ -28,7 +28,7 @@ package com.iluwatar.factory.method;
*/
public class ElfWeapon implements Weapon {
- private WeaponType weaponType;
+ private final WeaponType weaponType;
public ElfWeapon(WeaponType weaponType) {
this.weaponType = weaponType;
diff --git a/factory-method/src/main/java/com/iluwatar/factory/method/OrcBlacksmith.java b/factory-method/src/main/java/com/iluwatar/factory/method/OrcBlacksmith.java
index b04830085..ea99200de 100644
--- a/factory-method/src/main/java/com/iluwatar/factory/method/OrcBlacksmith.java
+++ b/factory-method/src/main/java/com/iluwatar/factory/method/OrcBlacksmith.java
@@ -32,7 +32,7 @@ import java.util.Map;
*/
public class OrcBlacksmith implements Blacksmith {
- private static Map ORCARSENAL;
+ private static final Map ORCARSENAL;
static {
ORCARSENAL = new HashMap<>(WeaponType.values().length);
diff --git a/factory-method/src/main/java/com/iluwatar/factory/method/OrcWeapon.java b/factory-method/src/main/java/com/iluwatar/factory/method/OrcWeapon.java
index b35adf798..af1ee5bcf 100644
--- a/factory-method/src/main/java/com/iluwatar/factory/method/OrcWeapon.java
+++ b/factory-method/src/main/java/com/iluwatar/factory/method/OrcWeapon.java
@@ -28,7 +28,7 @@ package com.iluwatar.factory.method;
*/
public class OrcWeapon implements Weapon {
- private WeaponType weaponType;
+ private final WeaponType weaponType;
public OrcWeapon(WeaponType weaponType) {
this.weaponType = weaponType;
diff --git a/factory-method/src/main/java/com/iluwatar/factory/method/WeaponType.java b/factory-method/src/main/java/com/iluwatar/factory/method/WeaponType.java
index 73ab10dd6..6c7c86712 100644
--- a/factory-method/src/main/java/com/iluwatar/factory/method/WeaponType.java
+++ b/factory-method/src/main/java/com/iluwatar/factory/method/WeaponType.java
@@ -30,7 +30,7 @@ public enum WeaponType {
SHORT_SWORD("short sword"), SPEAR("spear"), AXE("axe"), UNDEFINED("");
- private String title;
+ private final String title;
WeaponType(String title) {
this.title = title;
diff --git a/factory-method/src/main/java/com/iluwatar/factory/method/module-info.java b/factory-method/src/main/java/com/iluwatar/factory/method/module-info.java
deleted file mode 100644
index 4ea385c8b..000000000
--- a/factory-method/src/main/java/com/iluwatar/factory/method/module-info.java
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * The MIT License
- * Copyright © 2014-2019 Ilkka Seppälä
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-
-module com.iluwatar.factorymethod {
- requires org.slf4j;
-}
\ No newline at end of file
diff --git a/factory-method/src/test/java/com/iluwatar/factory/method/AppTest.java b/factory-method/src/test/java/com/iluwatar/factory/method/AppTest.java
index c23295d9a..8756ba0aa 100644
--- a/factory-method/src/test/java/com/iluwatar/factory/method/AppTest.java
+++ b/factory-method/src/test/java/com/iluwatar/factory/method/AppTest.java
@@ -25,12 +25,15 @@ package com.iluwatar.factory.method;
import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+
/**
* Tests that Factory Method example runs without errors.
*/
-public class AppTest {
+class AppTest {
+
@Test
- public void test() {
- App.main(new String[]{});
+ void shouldExecuteWithoutException() {
+ assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
diff --git a/feature-toggle/pom.xml b/feature-toggle/pom.xml
index 13f646b80..1818d882d 100644
--- a/feature-toggle/pom.xml
+++ b/feature-toggle/pom.xml
@@ -29,7 +29,7 @@
java-design-patterns
com.iluwatar
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
4.0.0
diff --git a/feature-toggle/src/main/java/com/iluwatar/featuretoggle/module-info.java b/feature-toggle/src/main/java/com/iluwatar/featuretoggle/module-info.java
deleted file mode 100644
index 55c2d7714..000000000
--- a/feature-toggle/src/main/java/com/iluwatar/featuretoggle/module-info.java
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * The MIT License
- * Copyright © 2014-2019 Ilkka Seppälä
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-
-module com.iluwatar.featuretoggle {
- requires org.slf4j;
-}
\ No newline at end of file
diff --git a/feature-toggle/src/main/java/com/iluwatar/featuretoggle/pattern/propertiesversion/PropertiesFeatureToggleVersion.java b/feature-toggle/src/main/java/com/iluwatar/featuretoggle/pattern/propertiesversion/PropertiesFeatureToggleVersion.java
index 6e2281b9a..ed6e69518 100644
--- a/feature-toggle/src/main/java/com/iluwatar/featuretoggle/pattern/propertiesversion/PropertiesFeatureToggleVersion.java
+++ b/feature-toggle/src/main/java/com/iluwatar/featuretoggle/pattern/propertiesversion/PropertiesFeatureToggleVersion.java
@@ -42,7 +42,7 @@ import java.util.Properties;
*/
public class PropertiesFeatureToggleVersion implements Service {
- private boolean isEnhanced;
+ private final boolean isEnhanced;
/**
* Creates an instance of {@link PropertiesFeatureToggleVersion} using the passed {@link
diff --git a/feature-toggle/src/main/java/com/iluwatar/featuretoggle/user/User.java b/feature-toggle/src/main/java/com/iluwatar/featuretoggle/user/User.java
index 5c660ca59..7924f86e8 100644
--- a/feature-toggle/src/main/java/com/iluwatar/featuretoggle/user/User.java
+++ b/feature-toggle/src/main/java/com/iluwatar/featuretoggle/user/User.java
@@ -29,7 +29,7 @@ package com.iluwatar.featuretoggle.user;
*/
public class User {
- private String name;
+ private final String name;
/**
* Default Constructor setting the username.
diff --git a/feature-toggle/src/main/java/com/iluwatar/featuretoggle/user/UserGroup.java b/feature-toggle/src/main/java/com/iluwatar/featuretoggle/user/UserGroup.java
index 524ea6ef8..7b644afd7 100644
--- a/feature-toggle/src/main/java/com/iluwatar/featuretoggle/user/UserGroup.java
+++ b/feature-toggle/src/main/java/com/iluwatar/featuretoggle/user/UserGroup.java
@@ -35,8 +35,8 @@ import java.util.List;
*/
public class UserGroup {
- private static List freeGroup = new ArrayList<>();
- private static List paidGroup = new ArrayList<>();
+ private static final List freeGroup = new ArrayList<>();
+ private static final List paidGroup = new ArrayList<>();
/**
diff --git a/filterer/README.md b/filterer/README.md
new file mode 100644
index 000000000..89dc87e84
--- /dev/null
+++ b/filterer/README.md
@@ -0,0 +1,239 @@
+---
+layout: pattern
+title: Filterer
+folder: filterer
+permalink: /patterns/filterer/
+description: Design pattern that helps container-like objects to return filtered version of themselves.# short meta description that shows in Google search results
+categories:
+ - Functional
+tags:
+ - Extensibility
+---
+
+## Name / classification
+
+Filterer
+
+## Intent
+
+The intent of this design pattern is to introduce a functional interface that will add a
+functionality for container-like objects to easily return filtered versions of themselves.
+
+## Explanation
+
+Real world example
+
+> We are designing a threat (malware) detection software which can analyze target systems for
+> threats that are present in it. In the design we have to take into consideration that new
+> Threat types can be added later. Additionally, there is a requirement that the threat detection
+> system can filter the detected threats based on different criteria (the target system acts as
+> container-like object for threats).
+
+In plain words
+
+> Filterer pattern is a design pattern that helps container-like objects return filtered versions
+> of themselves.
+
+**Programmatic Example**
+
+To model the threat detection example presented above we introduce `Threat` and `ThreatAwareSystem`
+interfaces.
+
+```java
+public interface Threat {
+ String name();
+ int id();
+ ThreatType type();
+}
+
+public interface ThreatAwareSystem {
+ String systemId();
+ List extends Threat> threats();
+ Filterer extends ThreatAwareSystem, ? extends Threat> filtered();
+
+}
+```
+
+Notice the `filtered` method that returns instance of `Filterer` interface which is defined as:
+
+```java
+@FunctionalInterface
+public interface Filterer {
+ G by(Predicate super E> predicate);
+}
+```
+
+It is used to fulfill the requirement for system to be able to filter itself based on threat
+properties. The container-like object (`ThreatAwareSystem` in our case) needs to have a method that
+returns an instance of `Filterer`. This helper interface gives ability to covariantly specify a
+lower bound of contravariant `Predicate` in the subinterfaces of interfaces representing the
+container-like objects.
+
+In our example we will be able to pass a predicate that takes `? extends Threat` object and
+return `? extends ThreatAwareSystem` from `Filtered::by` method. A simple implementation
+of `ThreatAwareSystem`:
+
+```java
+public class SimpleThreatAwareSystem implements ThreatAwareSystem {
+
+ private final String systemId;
+ private final ImmutableList issues;
+
+ public SimpleThreatAwareSystem(final String systemId, final List issues) {
+ this.systemId = systemId;
+ this.issues = ImmutableList.copyOf(issues);
+ }
+
+ @Override
+ public String systemId() {
+ return systemId;
+ }
+
+ @Override
+ public List extends Threat> threats() {
+ return new ArrayList<>(issues);
+ }
+
+ @Override
+ public Filterer extends ThreatAwareSystem, ? extends Threat> filtered() {
+ return this::filteredGroup;
+ }
+
+ private ThreatAwareSystem filteredGroup(Predicate super Threat> predicate) {
+ return new SimpleThreatAwareSystem(this.systemId, filteredItems(predicate));
+ }
+
+ private List filteredItems(Predicate super Threat> predicate) {
+ return this.issues.stream()
+ .filter(predicate)
+ .collect(Collectors.toList());
+ }
+}
+```
+
+The `filtered` method is overridden to filter the threats list by given predicate.
+
+Now if we introduce a new subtype of `Threat` interface that adds probability with which given
+threat can appear:
+
+```java
+public interface ProbableThreat extends Threat {
+ double probability();
+}
+```
+
+We can also introduce a new interface that represents a system that is aware of threats with their
+probabilities:
+
+````java
+public interface ProbabilisticThreatAwareSystem extends ThreatAwareSystem {
+ @Override
+ List extends ProbableThreat> threats();
+
+ @Override
+ Filterer extends ProbabilisticThreatAwareSystem, ? extends ProbableThreat> filtered();
+}
+````
+
+Notice how we override the `filtered` method in `ProbabilisticThreatAwareSystem` and specify
+different return covariant type by specifying different generic types. Our interfaces are clean and
+not cluttered by default implementations. We we will be able to filter
+`ProbabilisticThreatAwareSystem` by `ProbableThreat` properties:
+
+```java
+public class SimpleProbabilisticThreatAwareSystem implements ProbabilisticThreatAwareSystem {
+
+ private final String systemId;
+ private final ImmutableList threats;
+
+ public SimpleProbabilisticThreatAwareSystem(final String systemId, final List threats) {
+ this.systemId = systemId;
+ this.threats = ImmutableList.copyOf(threats);
+ }
+
+ @Override
+ public String systemId() {
+ return systemId;
+ }
+
+ @Override
+ public List extends ProbableThreat> threats() {
+ return threats;
+ }
+
+ @Override
+ public Filterer extends ProbabilisticThreatAwareSystem, ? extends ProbableThreat> filtered() {
+ return this::filteredGroup;
+ }
+
+ private ProbabilisticThreatAwareSystem filteredGroup(final Predicate super ProbableThreat> predicate) {
+ return new SimpleProbabilisticThreatAwareSystem(this.systemId, filteredItems(predicate));
+ }
+
+ private List filteredItems(final Predicate super ProbableThreat> predicate) {
+ return this.threats.stream()
+ .filter(predicate)
+ .collect(Collectors.toList());
+ }
+}
+```
+
+Now if we want filter `ThreatAwareSystem` by threat type we can do:
+
+```java
+Threat rootkit = new SimpleThreat(ThreatType.ROOTKIT, 1, "Simple-Rootkit");
+Threat trojan = new SimpleThreat(ThreatType.TROJAN, 2, "Simple-Trojan");
+List threats = List.of(rootkit, trojan);
+
+ThreatAwareSystem threatAwareSystem = new SimpleThreatAwareSystem("System-1", threats);
+
+ThreatAwareSystem rootkitThreatAwareSystem = threatAwareSystem.filtered()
+ .by(threat -> threat.type() == ThreatType.ROOTKIT);
+```
+
+Or if we want to filter `ProbabilisticThreatAwareSystem`:
+
+```java
+ProbableThreat malwareTroyan = new SimpleProbableThreat("Troyan-ArcBomb", 1, ThreatType.TROJAN, 0.99);
+ProbableThreat rootkit = new SimpleProbableThreat("Rootkit-System", 2, ThreatType.ROOTKIT, 0.8);
+List probableThreats = List.of(malwareTroyan, rootkit);
+
+ProbabilisticThreatAwareSystem simpleProbabilisticThreatAwareSystem =new SimpleProbabilisticThreatAwareSystem("System-1", probableThreats);
+
+ProbabilisticThreatAwareSystem filtered = simpleProbabilisticThreatAwareSystem.filtered()
+ .by(probableThreat -> Double.compare(probableThreat.probability(), 0.99) == 0);
+```
+
+## Class diagram
+
+
+
+## Applicability
+
+Pattern can be used when working with container-like objects that use subtyping, instead of
+parametrizing (generics) for extensible class structure. It enables you to easily extend filtering
+ability of container-like objects as business requirements change.
+
+## Tutorials
+
+* [Article about Filterer pattern posted on it's author's blog](https://blog.tlinkowski.pl/2018/filterer-pattern/)
+* [Application of Filterer pattern in domain of text analysis](https://www.javacodegeeks.com/2019/02/filterer-pattern-10-steps.html)
+
+## Known uses
+
+One of the uses is present on the blog presented in
+[this](https://www.javacodegeeks.com/2019/02/filterer-pattern-10-steps.html) link. It presents how
+to use `Filterer` pattern to create text issue analyzer with support for test cases used for unit
+testing.
+
+## Consequences
+
+Pros:
+ * You can easily introduce new subtypes for container-like objects and subtypes for objects that are contained within them and still be able to filter easily be new properties of those new subtypes.
+
+Cons:
+ * Covariant return types mixed with generics can be sometimes tricky
+
+## Credits
+
+* Author of the pattern : [Tomasz Linkowski](https://tlinkowski.pl/)
diff --git a/filterer/etc/filterer.png b/filterer/etc/filterer.png
new file mode 100644
index 000000000..6a6eb059b
Binary files /dev/null and b/filterer/etc/filterer.png differ
diff --git a/filterer/etc/filterer.urm.puml b/filterer/etc/filterer.urm.puml
new file mode 100644
index 000000000..c0bb0b54d
--- /dev/null
+++ b/filterer/etc/filterer.urm.puml
@@ -0,0 +1,96 @@
+@startuml
+package com.iluwatar.filterer.domain {
+ interface Filterer {
+ + by(Predicate super E>) : G {abstract}
+ }
+}
+package com.iluwatar.filterer {
+ class App {
+ - LOGGER : Logger {static}
+ + App()
+ - filteringSimpleProbableThreats() {static}
+ - filteringSimpleThreats() {static}
+ + main(args : String[]) {static}
+ }
+}
+package com.iluwatar.filterer.threat {
+ interface ProbabilisticThreatAwareSystem {
+ + filtered() : Filterer extends ProbabilisticThreatAwareSystem, ? extends ProbableThreat> {abstract}
+ + threats() : List extends ProbableThreat> {abstract}
+ }
+ interface ProbableThreat {
+ + probability() : double {abstract}
+ }
+ class SimpleProbabilisticThreatAwareSystem {
+ - systemId : String
+ - threats : ImmutableList
+ + SimpleProbabilisticThreatAwareSystem(systemId : String, threats : List)
+ + equals(o : Object) : boolean
+ + filtered() : Filterer extends ProbabilisticThreatAwareSystem, ? extends ProbableThreat>
+ - filteredGroup(predicate : Predicate super ProbableThreat>) : ProbabilisticThreatAwareSystem
+ - filteredItems(predicate : Predicate super ProbableThreat>) : List
+ + hashCode() : int
+ + systemId() : String
+ + threats() : List extends ProbableThreat>
+ + toString() : String
+ }
+ class SimpleProbableThreat {
+ - probability : double
+ + SimpleProbableThreat(name : String, id : int, threatType : ThreatType, probability : double)
+ + equals(o : Object) : boolean
+ + hashCode() : int
+ + probability() : double
+ + toString() : String
+ }
+ class SimpleThreat {
+ - id : int
+ - name : String
+ - threatType : ThreatType
+ + SimpleThreat(threatType : ThreatType, id : int, name : String)
+ + id() : int
+ + name() : String
+ + toString() : String
+ + type() : ThreatType
+ }
+ class SimpleThreatAwareSystem {
+ - issues : ImmutableList
+ - systemId : String
+ + SimpleThreatAwareSystem(systemId : String, issues : List)
+ + equals(o : Object) : boolean
+ + filtered() : Filterer extends ThreatAwareSystem, ? extends Threat>
+ - filteredGroup(predicate : Predicate super Threat>) : ThreatAwareSystem
+ - filteredItems(predicate : Predicate super Threat>) : List
+ + hashCode() : int
+ + systemId() : String
+ + threats() : List extends Threat>
+ + toString() : String
+ }
+ interface Threat {
+ + id() : int {abstract}
+ + name() : String {abstract}
+ + type() : ThreatType {abstract}
+ }
+ interface ThreatAwareSystem {
+ + filtered() : Filterer extends ThreatAwareSystem, ? extends Threat> {abstract}
+ + systemId() : String {abstract}
+ + threats() : List extends Threat> {abstract}
+ }
+ enum ThreatType {
+ + ROOTKIT {static}
+ + TROJAN {static}
+ + WORM {static}
+ + valueOf(name : String) : ThreatType {static}
+ + values() : ThreatType[] {static}
+ }
+}
+SimpleThreatAwareSystem --> "-issues" Threat
+SimpleThreat --> "-threatType" ThreatType
+SimpleProbabilisticThreatAwareSystem --> "-threats" ProbableThreat
+ProbabilisticThreatAwareSystem --|> ThreatAwareSystem
+ProbableThreat --|> Threat
+SimpleProbabilisticThreatAwareSystem ..|> ProbabilisticThreatAwareSystem
+SimpleProbableThreat ..|> ProbableThreat
+SimpleProbableThreat --|> SimpleThreat
+SimpleThreat ..|> Threat
+SimpleThreatAwareSystem ..|> ThreatAwareSystem
+@enduml
\ No newline at end of file
diff --git a/filterer/pom.xml b/filterer/pom.xml
new file mode 100644
index 000000000..46042c1b0
--- /dev/null
+++ b/filterer/pom.xml
@@ -0,0 +1,73 @@
+
+
+
+
+ java-design-patterns
+ com.iluwatar
+ 1.24.0-SNAPSHOT
+
+ 4.0.0
+
+ filterer
+
+
+
+ com.google.guava
+ guava
+
+
+ org.junit.jupiter
+ junit-jupiter-api
+ test
+
+
+ org.junit.jupiter
+ junit-jupiter-engine
+ test
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-assembly-plugin
+
+
+
+
+
+ com.iluwatar.filterer.App
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/filterer/src/main/java/com/iluwatar/filterer/App.java b/filterer/src/main/java/com/iluwatar/filterer/App.java
new file mode 100644
index 000000000..43de5a646
--- /dev/null
+++ b/filterer/src/main/java/com/iluwatar/filterer/App.java
@@ -0,0 +1,108 @@
+/*
+ * The MIT License
+ * Copyright © 2014-2019 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+package com.iluwatar.filterer;
+
+import com.iluwatar.filterer.threat.ProbableThreat;
+import com.iluwatar.filterer.threat.SimpleProbabilisticThreatAwareSystem;
+import com.iluwatar.filterer.threat.SimpleProbableThreat;
+import com.iluwatar.filterer.threat.SimpleThreat;
+import com.iluwatar.filterer.threat.SimpleThreatAwareSystem;
+import com.iluwatar.filterer.threat.Threat;
+import com.iluwatar.filterer.threat.ThreatAwareSystem;
+import com.iluwatar.filterer.threat.ThreatType;
+
+import java.util.List;
+import java.util.function.Predicate;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * This demo class represent how {@link com.iluwatar.filterer.domain.Filterer} pattern is used to
+ * filter container-like objects to return filtered versions of themselves. The container like
+ * objects are systems that are aware of threats that they can be vulnerable to. We would like
+ * to have a way to create copy of different system objects but with filtered threats.
+ * The thing is to keep it simple if we add new subtype of {@link Threat}
+ * (for example {@link ProbableThreat}) - we still need to be able to filter by it's properties.
+ */
+public class App {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(App.class);
+
+ public static void main(String[] args) {
+ filteringSimpleThreats();
+ filteringSimpleProbableThreats();
+ }
+
+ /**
+ * Demonstrates how to filter {@link com.iluwatar.filterer.threat.ProbabilisticThreatAwareSystem}
+ * based on probability property. The @{@link com.iluwatar.filterer.domain.Filterer#by(Predicate)}
+ * method is able to use {@link com.iluwatar.filterer.threat.ProbableThreat}
+ * as predicate argument.
+ */
+ private static void filteringSimpleProbableThreats() {
+ LOGGER.info(" ### Filtering ProbabilisticThreatAwareSystem by probability ###");
+
+ var trojanArcBomb = new SimpleProbableThreat("Trojan-ArcBomb", 1, ThreatType.TROJAN, 0.99);
+ var rootkit = new SimpleProbableThreat("Rootkit-Kernel", 2, ThreatType.ROOTKIT, 0.8);
+
+ List probableThreats = List.of(trojanArcBomb, rootkit);
+
+ var probabilisticThreatAwareSystem =
+ new SimpleProbabilisticThreatAwareSystem("Sys-1", probableThreats);
+
+ LOGGER.info("Filtering ProbabilisticThreatAwareSystem. Initial : "
+ + probabilisticThreatAwareSystem);
+
+ //Filtering using filterer
+ var filteredThreatAwareSystem = probabilisticThreatAwareSystem.filtered()
+ .by(probableThreat -> Double.compare(probableThreat.probability(), 0.99) == 0);
+
+ LOGGER.info("Filtered by probability = 0.99 : " + filteredThreatAwareSystem);
+ }
+
+ /**
+ * Demonstrates how to filter {@link ThreatAwareSystem} based on startingOffset property
+ * of {@link SimpleThreat}. The @{@link com.iluwatar.filterer.domain.Filterer#by(Predicate)}
+ * method is able to use {@link Threat} as predicate argument.
+ */
+ private static void filteringSimpleThreats() {
+ LOGGER.info("### Filtering ThreatAwareSystem by ThreatType ###");
+
+ var rootkit = new SimpleThreat(ThreatType.ROOTKIT, 1, "Simple-Rootkit");
+ var trojan = new SimpleThreat(ThreatType.TROJAN, 2, "Simple-Trojan");
+ List threats = List.of(rootkit, trojan);
+
+ var threatAwareSystem = new SimpleThreatAwareSystem("Sys-1", threats);
+
+ LOGGER.info("Filtering ThreatAwareSystem. Initial : " + threatAwareSystem);
+
+ //Filtering using Filterer
+ var rootkitThreatAwareSystem = threatAwareSystem.filtered()
+ .by(threat -> threat.type() == ThreatType.ROOTKIT);
+
+ LOGGER.info("Filtered by threatType = ROOTKIT : " + rootkitThreatAwareSystem);
+ }
+
+}
diff --git a/filterer/src/main/java/com/iluwatar/filterer/domain/Filterer.java b/filterer/src/main/java/com/iluwatar/filterer/domain/Filterer.java
new file mode 100644
index 000000000..17970c115
--- /dev/null
+++ b/filterer/src/main/java/com/iluwatar/filterer/domain/Filterer.java
@@ -0,0 +1,36 @@
+/*
+ * The MIT License
+ * Copyright © 2014-2019 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+package com.iluwatar.filterer.domain;
+
+import java.util.function.Predicate;
+
+/**
+ * Filterer helper interface.
+ * @param type of the container-like object.
+ * @param type of the elements contained within this container-like object.
+ */
+@FunctionalInterface
+public interface Filterer {
+ G by(Predicate super E> predicate);
+}
\ No newline at end of file
diff --git a/filterer/src/main/java/com/iluwatar/filterer/threat/ProbabilisticThreatAwareSystem.java b/filterer/src/main/java/com/iluwatar/filterer/threat/ProbabilisticThreatAwareSystem.java
new file mode 100644
index 000000000..3a2959828
--- /dev/null
+++ b/filterer/src/main/java/com/iluwatar/filterer/threat/ProbabilisticThreatAwareSystem.java
@@ -0,0 +1,49 @@
+/*
+ * The MIT License
+ * Copyright © 2014-2019 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+package com.iluwatar.filterer.threat;
+
+import com.iluwatar.filterer.domain.Filterer;
+
+import java.util.List;
+
+/**
+ * Represents system that is aware of it's threats with given probability of their occurrence.
+ */
+public interface ProbabilisticThreatAwareSystem extends ThreatAwareSystem {
+
+ /**
+ * {@inheritDoc}
+ * @return
+ */
+ @Override
+ List extends ProbableThreat> threats();
+
+ /**
+ * {@inheritDoc}
+ * @return
+ */
+ @Override
+ Filterer extends ProbabilisticThreatAwareSystem, ? extends ProbableThreat> filtered();
+}
+
diff --git a/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/module-info.java b/filterer/src/main/java/com/iluwatar/filterer/threat/ProbableThreat.java
similarity index 78%
rename from acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/module-info.java
rename to filterer/src/main/java/com/iluwatar/filterer/threat/ProbableThreat.java
index 78de5a786..11e61dbf6 100644
--- a/acyclic-visitor/src/main/java/com/iluwatar/acyclicvisitor/module-info.java
+++ b/filterer/src/main/java/com/iluwatar/filterer/threat/ProbableThreat.java
@@ -21,6 +21,15 @@
* THE SOFTWARE.
*/
-module com.iluwatar.acyclicvisitor {
- requires org.slf4j;
+package com.iluwatar.filterer.threat;
+
+/**
+ * Represents threat that might be a threat with given probability.
+ */
+public interface ProbableThreat extends Threat {
+ /**
+ * Returns probability of occurrence of given threat.
+ * @return probability of occurrence of given threat.
+ */
+ double probability();
}
\ No newline at end of file
diff --git a/filterer/src/main/java/com/iluwatar/filterer/threat/SimpleProbabilisticThreatAwareSystem.java b/filterer/src/main/java/com/iluwatar/filterer/threat/SimpleProbabilisticThreatAwareSystem.java
new file mode 100644
index 000000000..3991d975e
--- /dev/null
+++ b/filterer/src/main/java/com/iluwatar/filterer/threat/SimpleProbabilisticThreatAwareSystem.java
@@ -0,0 +1,113 @@
+/*
+ * The MIT License
+ * Copyright © 2014-2019 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+package com.iluwatar.filterer.threat;
+
+import com.google.common.collect.ImmutableList;
+import com.iluwatar.filterer.domain.Filterer;
+
+import java.util.List;
+import java.util.Objects;
+import java.util.function.Predicate;
+import java.util.stream.Collectors;
+
+/**
+ * {@inheritDoc}
+ */
+public class SimpleProbabilisticThreatAwareSystem implements ProbabilisticThreatAwareSystem {
+
+ private final String systemId;
+ private final ImmutableList threats;
+
+ public SimpleProbabilisticThreatAwareSystem(
+ final String systemId,
+ final List threats
+ ) {
+ this.systemId = systemId;
+ this.threats = ImmutableList.copyOf(threats);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public String systemId() {
+ return systemId;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public List extends ProbableThreat> threats() {
+ return threats;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public Filterer extends ProbabilisticThreatAwareSystem, ? extends ProbableThreat> filtered() {
+ return this::filteredGroup;
+ }
+
+ private ProbabilisticThreatAwareSystem filteredGroup(
+ final Predicate super ProbableThreat> predicate
+ ) {
+ return new SimpleProbabilisticThreatAwareSystem(this.systemId, filteredItems(predicate));
+ }
+
+ private List filteredItems(
+ final Predicate super ProbableThreat> predicate
+ ) {
+ return this.threats.stream()
+ .filter(predicate)
+ .collect(Collectors.toList());
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+ var that = (SimpleProbabilisticThreatAwareSystem) o;
+ return systemId.equals(that.systemId)
+ && threats.equals(that.threats);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(systemId, threats);
+ }
+
+ @Override
+ public String toString() {
+ return "SimpleProbabilisticThreatAwareSystem{"
+ + "systemId='" + systemId + '\''
+ + ", threats=" + threats
+ + '}';
+ }
+}
diff --git a/filterer/src/main/java/com/iluwatar/filterer/threat/SimpleProbableThreat.java b/filterer/src/main/java/com/iluwatar/filterer/threat/SimpleProbableThreat.java
new file mode 100644
index 000000000..54da07873
--- /dev/null
+++ b/filterer/src/main/java/com/iluwatar/filterer/threat/SimpleProbableThreat.java
@@ -0,0 +1,79 @@
+/*
+ * The MIT License
+ * Copyright © 2014-2019 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+package com.iluwatar.filterer.threat;
+
+import java.util.Objects;
+
+/**
+ * {@inheritDoc}
+ */
+public class SimpleProbableThreat extends SimpleThreat implements ProbableThreat {
+
+ private final double probability;
+
+ public SimpleProbableThreat(final String name,
+ final int id,
+ final ThreatType threatType,
+ final double probability
+ ) {
+ super(threatType, id, name);
+ this.probability = probability;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public double probability() {
+ return probability;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+ if (!super.equals(o)) {
+ return false;
+ }
+ var that = (SimpleProbableThreat) o;
+ return Double.compare(that.probability, probability) == 0;
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(super.hashCode(), probability);
+ }
+
+ @Override
+ public String toString() {
+ return "SimpleProbableThreat{"
+ + "probability=" + probability
+ + "} "
+ + super.toString();
+ }
+}
diff --git a/filterer/src/main/java/com/iluwatar/filterer/threat/SimpleThreat.java b/filterer/src/main/java/com/iluwatar/filterer/threat/SimpleThreat.java
new file mode 100644
index 000000000..08a8b0e17
--- /dev/null
+++ b/filterer/src/main/java/com/iluwatar/filterer/threat/SimpleThreat.java
@@ -0,0 +1,101 @@
+/*
+ * The MIT License
+ * Copyright © 2014-2019 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+package com.iluwatar.filterer.threat;
+
+import java.util.Objects;
+
+/**
+ * Represents a simple threat.
+ */
+public class SimpleThreat implements Threat {
+
+ private final ThreatType threatType;
+ private final int id;
+ private final String name;
+
+ /**
+ * Constructor.
+ *
+ * @param threatType {@link ThreatType}.
+ * @param id threat id.
+ * @param name threat name.
+ */
+ public SimpleThreat(final ThreatType threatType, final int id, String name) {
+ this.threatType = threatType;
+ this.id = id;
+ this.name = name;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public String name() {
+ return name;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public int id() {
+ return id;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public ThreatType type() {
+ return threatType;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+ var that = (SimpleThreat) o;
+ return id == that.id
+ && threatType == that.threatType
+ && Objects.equals(name, that.name);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(threatType, id, name);
+ }
+
+ @Override
+ public String toString() {
+ return "SimpleThreat{"
+ + "threatType=" + threatType
+ + ", id=" + id
+ + ", name='" + name + '\''
+ + '}';
+ }
+}
diff --git a/filterer/src/main/java/com/iluwatar/filterer/threat/SimpleThreatAwareSystem.java b/filterer/src/main/java/com/iluwatar/filterer/threat/SimpleThreatAwareSystem.java
new file mode 100644
index 000000000..f1dec40ae
--- /dev/null
+++ b/filterer/src/main/java/com/iluwatar/filterer/threat/SimpleThreatAwareSystem.java
@@ -0,0 +1,107 @@
+/*
+ * The MIT License
+ * Copyright © 2014-2019 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+package com.iluwatar.filterer.threat;
+
+import com.google.common.collect.ImmutableList;
+import com.iluwatar.filterer.domain.Filterer;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Objects;
+import java.util.function.Predicate;
+import java.util.stream.Collectors;
+
+/**
+ * {@inheritDoc}
+ */
+public class SimpleThreatAwareSystem implements ThreatAwareSystem {
+
+ private final String systemId;
+ private final ImmutableList issues;
+
+ public SimpleThreatAwareSystem(final String systemId, final List issues) {
+ this.systemId = systemId;
+ this.issues = ImmutableList.copyOf(issues);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public String systemId() {
+ return systemId;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public List extends Threat> threats() {
+ return new ArrayList<>(issues);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public Filterer extends ThreatAwareSystem, ? extends Threat> filtered() {
+ return this::filteredGroup;
+ }
+
+ private ThreatAwareSystem filteredGroup(Predicate super Threat> predicate) {
+ return new SimpleThreatAwareSystem(this.systemId, filteredItems(predicate));
+ }
+
+ private List filteredItems(Predicate super Threat> predicate) {
+ return this.issues.stream()
+ .filter(predicate)
+ .collect(Collectors.toList());
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+ var that = (SimpleThreatAwareSystem) o;
+ return systemId.equals(that.systemId)
+ && issues.equals(that.issues);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(systemId, issues);
+ }
+
+ @Override
+ public String toString() {
+ return "SimpleThreatAwareSystem{"
+ + "systemId='" + systemId
+ + '\'' + ", issues=" + issues
+ + '}';
+ }
+}
diff --git a/filterer/src/main/java/com/iluwatar/filterer/threat/Threat.java b/filterer/src/main/java/com/iluwatar/filterer/threat/Threat.java
new file mode 100644
index 000000000..515b59332
--- /dev/null
+++ b/filterer/src/main/java/com/iluwatar/filterer/threat/Threat.java
@@ -0,0 +1,49 @@
+/*
+ * The MIT License
+ * Copyright © 2014-2019 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+package com.iluwatar.filterer.threat;
+
+/**
+ * Represents a threat that can be detected in given system.
+ */
+public interface Threat {
+ /**
+ * Returns name of the threat.
+ *
+ * @return value representing name of the threat.
+ */
+ String name();
+
+ /**
+ * Returns unique id of the threat.
+ *
+ * @return value representing threat id.
+ */
+ int id();
+
+ /**
+ * Returns threat type.
+ * @return {@link ThreatType}
+ */
+ ThreatType type();
+}
diff --git a/filterer/src/main/java/com/iluwatar/filterer/threat/ThreatAwareSystem.java b/filterer/src/main/java/com/iluwatar/filterer/threat/ThreatAwareSystem.java
new file mode 100644
index 000000000..b889d537d
--- /dev/null
+++ b/filterer/src/main/java/com/iluwatar/filterer/threat/ThreatAwareSystem.java
@@ -0,0 +1,55 @@
+/*
+ * The MIT License
+ * Copyright © 2014-2019 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+package com.iluwatar.filterer.threat;
+
+import com.iluwatar.filterer.domain.Filterer;
+
+import java.util.List;
+
+/**
+ * Represents system that is aware of threats that are present in it.
+ */
+public interface ThreatAwareSystem {
+
+ /**
+ * Returns the system id.
+ *
+ * @return system id.
+ */
+ String systemId();
+
+ /**
+ * Returns list of threats for this system.
+ * @return list of threats for this system.
+ */
+ List extends Threat> threats();
+
+ /**
+ * Returns the instance of {@link Filterer} helper interface that allows to covariantly
+ * specify lower bound for predicate that we want to filter by.
+ * @return an instance of {@link Filterer} helper interface.
+ */
+ Filterer extends ThreatAwareSystem, ? extends Threat> filtered();
+
+}
diff --git a/business-delegate/src/main/java/com/iluwatar/business/delegate/module-info.java b/filterer/src/main/java/com/iluwatar/filterer/threat/ThreatType.java
similarity index 92%
rename from business-delegate/src/main/java/com/iluwatar/business/delegate/module-info.java
rename to filterer/src/main/java/com/iluwatar/filterer/threat/ThreatType.java
index 8f331c848..5f9a152a8 100644
--- a/business-delegate/src/main/java/com/iluwatar/business/delegate/module-info.java
+++ b/filterer/src/main/java/com/iluwatar/filterer/threat/ThreatType.java
@@ -21,6 +21,6 @@
* THE SOFTWARE.
*/
-module com.iluwatar.business.delegate {
- requires org.slf4j;
-}
\ No newline at end of file
+package com.iluwatar.filterer.threat;
+
+public enum ThreatType { TROJAN, WORM, ROOTKIT }
diff --git a/abstract-document/src/main/java/com/iluwatar/abstractdocument/module-info.java b/filterer/src/test/java/com/iluwatar/filterer/AppTest.java
similarity index 88%
rename from abstract-document/src/main/java/com/iluwatar/abstractdocument/module-info.java
rename to filterer/src/test/java/com/iluwatar/filterer/AppTest.java
index 9121f0049..551ebcc18 100644
--- a/abstract-document/src/main/java/com/iluwatar/abstractdocument/module-info.java
+++ b/filterer/src/test/java/com/iluwatar/filterer/AppTest.java
@@ -21,6 +21,13 @@
* THE SOFTWARE.
*/
-module com.iluwatar.abstractdocument {
- requires org.slf4j;
+package com.iluwatar.filterer;
+
+import org.junit.jupiter.api.Test;
+
+class AppTest {
+ @Test
+ void shouldLaunchApp() {
+ App.main(new String[]{});
+ }
}
\ No newline at end of file
diff --git a/filterer/src/test/java/com/iluwatar/filterer/threat/SimpleProbabilisticThreatAwareSystemTest.java b/filterer/src/test/java/com/iluwatar/filterer/threat/SimpleProbabilisticThreatAwareSystemTest.java
new file mode 100644
index 000000000..2f14ca057
--- /dev/null
+++ b/filterer/src/test/java/com/iluwatar/filterer/threat/SimpleProbabilisticThreatAwareSystemTest.java
@@ -0,0 +1,51 @@
+/*
+ * The MIT License
+ * Copyright © 2014-2019 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+package com.iluwatar.filterer.threat;
+
+import org.junit.jupiter.api.Test;
+
+import java.util.List;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+class SimpleProbabilisticThreatAwareSystemTest {
+ @Test
+ void shouldFilterByProbability() {
+ //given
+ var trojan = new SimpleProbableThreat("Troyan-ArcBomb", 1, ThreatType.TROJAN, 0.99);
+ var rootkit = new SimpleProbableThreat("Rootkit-System", 2, ThreatType.ROOTKIT, 0.8);
+ List probableThreats = List.of(trojan, rootkit);
+
+ var simpleProbabilisticThreatAwareSystem =
+ new SimpleProbabilisticThreatAwareSystem("System-1", probableThreats);
+
+ //when
+ var filtered = simpleProbabilisticThreatAwareSystem.filtered()
+ .by(probableThreat -> Double.compare(probableThreat.probability(), 0.99) == 0);
+
+ //then
+ assertEquals(filtered.threats().size(), 1);
+ assertEquals(filtered.threats().get(0), trojan);
+ }
+}
\ No newline at end of file
diff --git a/filterer/src/test/java/com/iluwatar/filterer/threat/SimpleThreatAwareSystemTest.java b/filterer/src/test/java/com/iluwatar/filterer/threat/SimpleThreatAwareSystemTest.java
new file mode 100644
index 000000000..ea918c9ec
--- /dev/null
+++ b/filterer/src/test/java/com/iluwatar/filterer/threat/SimpleThreatAwareSystemTest.java
@@ -0,0 +1,50 @@
+/*
+ * The MIT License
+ * Copyright © 2014-2019 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+package com.iluwatar.filterer.threat;
+
+import org.junit.jupiter.api.Test;
+
+import java.util.List;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+class SimpleThreatAwareSystemTest {
+ @Test
+ void shouldFilterByThreatType() {
+ //given
+ var rootkit = new SimpleThreat(ThreatType.ROOTKIT, 1, "Simple-Rootkit");
+ var trojan = new SimpleThreat(ThreatType.TROJAN, 2, "Simple-Trojan");
+ List threats = List.of(rootkit, trojan);
+
+ var threatAwareSystem = new SimpleThreatAwareSystem("System-1", threats);
+
+ //when
+ var rootkitThreatAwareSystem = threatAwareSystem.filtered()
+ .by(threat -> threat.type() == ThreatType.ROOTKIT);
+
+ //then
+ assertEquals(rootkitThreatAwareSystem.threats().size(), 1);
+ assertEquals(rootkitThreatAwareSystem.threats().get(0), rootkit);
+ }
+}
\ No newline at end of file
diff --git a/fluentinterface/pom.xml b/fluentinterface/pom.xml
index 9eb063c13..138dbfa12 100644
--- a/fluentinterface/pom.xml
+++ b/fluentinterface/pom.xml
@@ -29,7 +29,7 @@
java-design-patterns
com.iluwatar
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
4.0.0
diff --git a/fluentinterface/src/main/java/com/iluwatar/fluentinterface/app/App.java b/fluentinterface/src/main/java/com/iluwatar/fluentinterface/app/App.java
index 547c657e4..09513163c 100644
--- a/fluentinterface/src/main/java/com/iluwatar/fluentinterface/app/App.java
+++ b/fluentinterface/src/main/java/com/iluwatar/fluentinterface/app/App.java
@@ -94,7 +94,7 @@ public class App {
.filter(positives())
.first(4)
.last(2)
- .map(number -> "String[" + valueOf(number) + "]")
+ .map(number -> "String[" + number + "]")
.asList();
prettyPrint("The lazy list contains the last two of the first four positive numbers "
+ "mapped to Strings: ", lastTwoOfFirstFourStringMapped);
diff --git a/fluentinterface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/lazy/LazyFluentIterable.java b/fluentinterface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/lazy/LazyFluentIterable.java
index f001c532f..966f35287 100644
--- a/fluentinterface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/lazy/LazyFluentIterable.java
+++ b/fluentinterface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/lazy/LazyFluentIterable.java
@@ -198,7 +198,7 @@ public class LazyFluentIterable implements FluentIterable {
@Override
public Iterator iterator() {
return new DecoratingIterator(null) {
- Iterator oldTypeIterator = iterable.iterator();
+ final Iterator oldTypeIterator = iterable.iterator();
@Override
public T computeNext() {
diff --git a/fluentinterface/src/test/java/com/iluwatar/fluentinterface/app/AppTest.java b/fluentinterface/src/test/java/com/iluwatar/fluentinterface/app/AppTest.java
index 6f25d8416..1b6671917 100644
--- a/fluentinterface/src/test/java/com/iluwatar/fluentinterface/app/AppTest.java
+++ b/fluentinterface/src/test/java/com/iluwatar/fluentinterface/app/AppTest.java
@@ -25,13 +25,15 @@ package com.iluwatar.fluentinterface.app;
import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+
/**
* Application Test Entry
*/
-public class AppTest {
+class AppTest {
@Test
- public void test() {
- App.main(new String[]{});
+ void shouldExecuteWithoutException() {
+ assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
diff --git a/flux/pom.xml b/flux/pom.xml
index 8effd0fc9..14f4f5557 100644
--- a/flux/pom.xml
+++ b/flux/pom.xml
@@ -29,7 +29,7 @@
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
flux
diff --git a/flux/src/main/java/com/iluwatar/flux/action/Action.java b/flux/src/main/java/com/iluwatar/flux/action/Action.java
index 6a5f608c2..c8e2e012b 100644
--- a/flux/src/main/java/com/iluwatar/flux/action/Action.java
+++ b/flux/src/main/java/com/iluwatar/flux/action/Action.java
@@ -28,7 +28,7 @@ package com.iluwatar.flux.action;
*/
public abstract class Action {
- private ActionType type;
+ private final ActionType type;
public Action(ActionType type) {
this.type = type;
diff --git a/flux/src/main/java/com/iluwatar/flux/action/ActionType.java b/flux/src/main/java/com/iluwatar/flux/action/ActionType.java
index 6399d2806..e84954efd 100644
--- a/flux/src/main/java/com/iluwatar/flux/action/ActionType.java
+++ b/flux/src/main/java/com/iluwatar/flux/action/ActionType.java
@@ -28,6 +28,6 @@ package com.iluwatar.flux.action;
*/
public enum ActionType {
- MENU_ITEM_SELECTED, CONTENT_CHANGED;
+ MENU_ITEM_SELECTED, CONTENT_CHANGED
}
diff --git a/flux/src/main/java/com/iluwatar/flux/action/Content.java b/flux/src/main/java/com/iluwatar/flux/action/Content.java
index 59a63ec18..6fb2e3e0e 100644
--- a/flux/src/main/java/com/iluwatar/flux/action/Content.java
+++ b/flux/src/main/java/com/iluwatar/flux/action/Content.java
@@ -31,7 +31,7 @@ public enum Content {
PRODUCTS("Products - This page lists the company's products."), COMPANY(
"Company - This page displays information about the company.");
- private String title;
+ private final String title;
Content(String title) {
this.title = title;
diff --git a/flux/src/main/java/com/iluwatar/flux/action/ContentAction.java b/flux/src/main/java/com/iluwatar/flux/action/ContentAction.java
index 3b29b6b4e..c70561a65 100644
--- a/flux/src/main/java/com/iluwatar/flux/action/ContentAction.java
+++ b/flux/src/main/java/com/iluwatar/flux/action/ContentAction.java
@@ -28,7 +28,7 @@ package com.iluwatar.flux.action;
*/
public class ContentAction extends Action {
- private Content content;
+ private final Content content;
public ContentAction(Content content) {
super(ActionType.CONTENT_CHANGED);
diff --git a/flux/src/main/java/com/iluwatar/flux/action/MenuAction.java b/flux/src/main/java/com/iluwatar/flux/action/MenuAction.java
index 5ddeefde4..f833a6187 100644
--- a/flux/src/main/java/com/iluwatar/flux/action/MenuAction.java
+++ b/flux/src/main/java/com/iluwatar/flux/action/MenuAction.java
@@ -29,7 +29,7 @@ package com.iluwatar.flux.action;
*/
public class MenuAction extends Action {
- private MenuItem menuItem;
+ private final MenuItem menuItem;
public MenuAction(MenuItem menuItem) {
super(ActionType.MENU_ITEM_SELECTED);
diff --git a/flux/src/main/java/com/iluwatar/flux/action/MenuItem.java b/flux/src/main/java/com/iluwatar/flux/action/MenuItem.java
index f251e1dd7..90fac3e2e 100644
--- a/flux/src/main/java/com/iluwatar/flux/action/MenuItem.java
+++ b/flux/src/main/java/com/iluwatar/flux/action/MenuItem.java
@@ -30,7 +30,7 @@ public enum MenuItem {
HOME("Home"), PRODUCTS("Products"), COMPANY("Company");
- private String title;
+ private final String title;
MenuItem(String title) {
this.title = title;
diff --git a/flux/src/main/java/com/iluwatar/flux/dispatcher/Dispatcher.java b/flux/src/main/java/com/iluwatar/flux/dispatcher/Dispatcher.java
index cf09ecf68..c43d87680 100644
--- a/flux/src/main/java/com/iluwatar/flux/dispatcher/Dispatcher.java
+++ b/flux/src/main/java/com/iluwatar/flux/dispatcher/Dispatcher.java
@@ -39,7 +39,7 @@ public final class Dispatcher {
private static Dispatcher instance = new Dispatcher();
- private List stores = new LinkedList<>();
+ private final List stores = new LinkedList<>();
private Dispatcher() {
}
@@ -57,15 +57,10 @@ public final class Dispatcher {
*/
public void menuItemSelected(MenuItem menuItem) {
dispatchAction(new MenuAction(menuItem));
- switch (menuItem) {
- case HOME:
- case PRODUCTS:
- default:
- dispatchAction(new ContentAction(Content.PRODUCTS));
- break;
- case COMPANY:
- dispatchAction(new ContentAction(Content.COMPANY));
- break;
+ if (menuItem == MenuItem.COMPANY) {
+ dispatchAction(new ContentAction(Content.COMPANY));
+ } else {
+ dispatchAction(new ContentAction(Content.PRODUCTS));
}
}
diff --git a/flux/src/main/java/com/iluwatar/flux/store/Store.java b/flux/src/main/java/com/iluwatar/flux/store/Store.java
index cfbdf4af5..34188fff2 100644
--- a/flux/src/main/java/com/iluwatar/flux/store/Store.java
+++ b/flux/src/main/java/com/iluwatar/flux/store/Store.java
@@ -33,7 +33,7 @@ import java.util.List;
*/
public abstract class Store {
- private List views = new LinkedList<>();
+ private final List views = new LinkedList<>();
public abstract void onAction(Action action);
diff --git a/flux/src/test/java/com/iluwatar/flux/app/AppTest.java b/flux/src/test/java/com/iluwatar/flux/app/AppTest.java
index 8916ad4de..649708d8f 100644
--- a/flux/src/test/java/com/iluwatar/flux/app/AppTest.java
+++ b/flux/src/test/java/com/iluwatar/flux/app/AppTest.java
@@ -25,13 +25,15 @@ package com.iluwatar.flux.app;
import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+
/**
* Application test
*/
-public class AppTest {
+class AppTest {
@Test
- public void test() {
- App.main(new String[]{});
+ void shouldExecuteWithoutException() {
+ assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
diff --git a/flyweight/pom.xml b/flyweight/pom.xml
index f3a8082b5..b9ffd42ae 100644
--- a/flyweight/pom.xml
+++ b/flyweight/pom.xml
@@ -29,7 +29,7 @@
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
flyweight
diff --git a/flyweight/src/main/java/com/iluwatar/flyweight/AlchemistShop.java b/flyweight/src/main/java/com/iluwatar/flyweight/AlchemistShop.java
index 4fa7312e5..e7af8ee00 100644
--- a/flyweight/src/main/java/com/iluwatar/flyweight/AlchemistShop.java
+++ b/flyweight/src/main/java/com/iluwatar/flyweight/AlchemistShop.java
@@ -34,8 +34,8 @@ public class AlchemistShop {
private static final Logger LOGGER = LoggerFactory.getLogger(AlchemistShop.class);
- private List topShelf;
- private List bottomShelf;
+ private final List topShelf;
+ private final List bottomShelf;
/**
* Constructor.
diff --git a/flyweight/src/test/java/com/iluwatar/flyweight/AppTest.java b/flyweight/src/test/java/com/iluwatar/flyweight/AppTest.java
index 3d81a6db2..5f957c794 100644
--- a/flyweight/src/test/java/com/iluwatar/flyweight/AppTest.java
+++ b/flyweight/src/test/java/com/iluwatar/flyweight/AppTest.java
@@ -25,13 +25,15 @@ package com.iluwatar.flyweight;
import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+
/**
* Application test
*/
-public class AppTest {
+class AppTest {
@Test
- public void test() {
- App.main(new String[]{});
+ void shouldExecuteApplicationWithoutException() {
+ assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
diff --git a/front-controller/pom.xml b/front-controller/pom.xml
index 34dabc182..a90029a82 100644
--- a/front-controller/pom.xml
+++ b/front-controller/pom.xml
@@ -30,7 +30,7 @@
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
front-controller
diff --git a/front-controller/src/test/java/com/iluwatar/front/controller/AppTest.java b/front-controller/src/test/java/com/iluwatar/front/controller/AppTest.java
index 2ea58c6a6..cf33bfb48 100644
--- a/front-controller/src/test/java/com/iluwatar/front/controller/AppTest.java
+++ b/front-controller/src/test/java/com/iluwatar/front/controller/AppTest.java
@@ -25,13 +25,15 @@ package com.iluwatar.front.controller;
import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+
/**
* Application test
*/
-public class AppTest {
+class AppTest {
@Test
- public void test() {
- App.main(new String[]{});
+ void shouldExecuteApplicationWithoutException() {
+ assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
diff --git a/front-controller/src/test/java/com/iluwatar/front/controller/utils/InMemoryAppender.java b/front-controller/src/test/java/com/iluwatar/front/controller/utils/InMemoryAppender.java
index 57cfb2454..8cbf7c631 100644
--- a/front-controller/src/test/java/com/iluwatar/front/controller/utils/InMemoryAppender.java
+++ b/front-controller/src/test/java/com/iluwatar/front/controller/utils/InMemoryAppender.java
@@ -36,7 +36,7 @@ import java.util.List;
*/
public class InMemoryAppender extends AppenderBase {
- private List log = new LinkedList<>();
+ private final List log = new LinkedList<>();
public InMemoryAppender() {
((Logger) LoggerFactory.getLogger("root")).addAppender(this);
diff --git a/game-loop/pom.xml b/game-loop/pom.xml
index 2c2908271..6935c1fd1 100644
--- a/game-loop/pom.xml
+++ b/game-loop/pom.xml
@@ -29,7 +29,7 @@
java-design-patterns
com.iluwatar
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
4.0.0
@@ -39,6 +39,12 @@
junit
junit
+
+
+ org.junit.jupiter
+ junit-jupiter-engine
+ test
+
diff --git a/game-loop/src/test/java/com/iluwatar/gameloop/AppTest.java b/game-loop/src/test/java/com/iluwatar/gameloop/AppTest.java
index 447e4f411..0c027028d 100644
--- a/game-loop/src/test/java/com/iluwatar/gameloop/AppTest.java
+++ b/game-loop/src/test/java/com/iluwatar/gameloop/AppTest.java
@@ -25,14 +25,16 @@ package com.iluwatar.gameloop;
import org.junit.Test;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+
/**
* App unit test class.
*/
public class AppTest {
@Test
- public void testMain() {
- new App().main(new String[]{});
+ public void shouldExecuteApplicationWithoutException() {
+ assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
diff --git a/guarded-suspension/pom.xml b/guarded-suspension/pom.xml
index 791c696c1..f1bd31c66 100644
--- a/guarded-suspension/pom.xml
+++ b/guarded-suspension/pom.xml
@@ -30,7 +30,7 @@
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
jar
guarded-suspension
diff --git a/half-sync-half-async/pom.xml b/half-sync-half-async/pom.xml
index fdb37edb0..635b76172 100644
--- a/half-sync-half-async/pom.xml
+++ b/half-sync-half-async/pom.xml
@@ -29,7 +29,7 @@
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
half-sync-half-async
diff --git a/half-sync-half-async/src/main/java/com/iluwatar/halfsynchalfasync/App.java b/half-sync-half-async/src/main/java/com/iluwatar/halfsynchalfasync/App.java
index 7df2264ab..d013924cb 100644
--- a/half-sync-half-async/src/main/java/com/iluwatar/halfsynchalfasync/App.java
+++ b/half-sync-half-async/src/main/java/com/iluwatar/halfsynchalfasync/App.java
@@ -95,7 +95,7 @@ public class App {
* ArithmeticSumTask.
*/
static class ArithmeticSumTask implements AsyncTask {
- private long numberOfElements;
+ private final long numberOfElements;
public ArithmeticSumTask(long numberOfElements) {
this.numberOfElements = numberOfElements;
diff --git a/half-sync-half-async/src/main/java/com/iluwatar/halfsynchalfasync/AsynchronousService.java b/half-sync-half-async/src/main/java/com/iluwatar/halfsynchalfasync/AsynchronousService.java
index 3a3bb474c..32f5e9d4a 100644
--- a/half-sync-half-async/src/main/java/com/iluwatar/halfsynchalfasync/AsynchronousService.java
+++ b/half-sync-half-async/src/main/java/com/iluwatar/halfsynchalfasync/AsynchronousService.java
@@ -48,7 +48,7 @@ public class AsynchronousService {
* tasks should be performed in the background which does not affect the performance of main
* thread.
*/
- private ExecutorService service;
+ private final ExecutorService service;
/**
* Creates an asynchronous service using {@code workQueue} as communication channel between
diff --git a/half-sync-half-async/src/test/java/com/iluwatar/halfsynchalfasync/AppTest.java b/half-sync-half-async/src/test/java/com/iluwatar/halfsynchalfasync/AppTest.java
index b3cf4839b..395599927 100644
--- a/half-sync-half-async/src/test/java/com/iluwatar/halfsynchalfasync/AppTest.java
+++ b/half-sync-half-async/src/test/java/com/iluwatar/halfsynchalfasync/AppTest.java
@@ -25,13 +25,15 @@ package com.iluwatar.halfsynchalfasync;
import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+
/**
* Application test
*/
-public class AppTest {
+class AppTest {
@Test
- public void test() {
- App.main(null);
+ void shouldExecuteApplicationWithoutException() {
+ assertDoesNotThrow(() -> App.main(null));
}
}
diff --git a/hexagonal/pom.xml b/hexagonal/pom.xml
index 4873d0ddb..f51825d5f 100644
--- a/hexagonal/pom.xml
+++ b/hexagonal/pom.xml
@@ -30,7 +30,7 @@
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
hexagonal
diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/banking/InMemoryBank.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/banking/InMemoryBank.java
index 1a0fdb6b0..746b93508 100644
--- a/hexagonal/src/main/java/com/iluwatar/hexagonal/banking/InMemoryBank.java
+++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/banking/InMemoryBank.java
@@ -32,7 +32,7 @@ import java.util.Map;
*/
public class InMemoryBank implements WireTransfers {
- private static Map accounts = new HashMap<>();
+ private static final Map accounts = new HashMap<>();
static {
accounts
diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/database/InMemoryTicketRepository.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/database/InMemoryTicketRepository.java
index 973747acc..5c0461843 100644
--- a/hexagonal/src/main/java/com/iluwatar/hexagonal/database/InMemoryTicketRepository.java
+++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/database/InMemoryTicketRepository.java
@@ -34,7 +34,7 @@ import java.util.Optional;
*/
public class InMemoryTicketRepository implements LotteryTicketRepository {
- private static Map tickets = new HashMap<>();
+ private static final Map tickets = new HashMap<>();
@Override
public Optional findById(LotteryTicketId id) {
diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/database/MongoTicketRepository.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/database/MongoTicketRepository.java
index 96ab74ba3..6d6c33239 100644
--- a/hexagonal/src/main/java/com/iluwatar/hexagonal/database/MongoTicketRepository.java
+++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/database/MongoTicketRepository.java
@@ -46,6 +46,7 @@ public class MongoTicketRepository implements LotteryTicketRepository {
private static final String DEFAULT_DB = "lotteryDB";
private static final String DEFAULT_TICKETS_COLLECTION = "lotteryTickets";
private static final String DEFAULT_COUNTERS_COLLECTION = "counters";
+ private static final String TICKET_ID = "ticketId";
private MongoClient mongoClient;
private MongoDatabase database;
@@ -93,7 +94,7 @@ public class MongoTicketRepository implements LotteryTicketRepository {
}
private void initCounters() {
- var doc = new Document("_id", "ticketId").append("seq", 1);
+ var doc = new Document("_id", TICKET_ID).append("seq", 1);
countersCollection.insertOne(doc);
}
@@ -103,7 +104,7 @@ public class MongoTicketRepository implements LotteryTicketRepository {
* @return next ticket id
*/
public int getNextId() {
- var find = new Document("_id", "ticketId");
+ var find = new Document("_id", TICKET_ID);
var increase = new Document("seq", 1);
var update = new Document("$inc", increase);
var result = countersCollection.findOneAndUpdate(find, update);
@@ -131,7 +132,7 @@ public class MongoTicketRepository implements LotteryTicketRepository {
@Override
public Optional findById(LotteryTicketId id) {
return ticketsCollection
- .find(new Document("ticketId", id.getId()))
+ .find(new Document(TICKET_ID, id.getId()))
.limit(1)
.into(new ArrayList<>())
.stream()
@@ -142,7 +143,7 @@ public class MongoTicketRepository implements LotteryTicketRepository {
@Override
public Optional save(LotteryTicket ticket) {
var ticketId = getNextId();
- var doc = new Document("ticketId", ticketId);
+ var doc = new Document(TICKET_ID, ticketId);
doc.put("email", ticket.getPlayerDetails().getEmail());
doc.put("bank", ticket.getPlayerDetails().getBankAccount());
doc.put("phone", ticket.getPlayerDetails().getPhoneNumber());
@@ -173,7 +174,7 @@ public class MongoTicketRepository implements LotteryTicketRepository {
.map(Integer::parseInt)
.collect(Collectors.toSet());
var lotteryNumbers = LotteryNumbers.create(numbers);
- var ticketId = new LotteryTicketId(doc.getInteger("ticketId"));
+ var ticketId = new LotteryTicketId(doc.getInteger(TICKET_ID));
return new LotteryTicket(ticketId, playerDetails, lotteryNumbers);
}
}
diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryNumbers.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryNumbers.java
index 8988bba88..acdd2b8c5 100644
--- a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryNumbers.java
+++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryNumbers.java
@@ -116,7 +116,7 @@ public class LotteryNumbers {
*/
private static class RandomNumberGenerator {
- private PrimitiveIterator.OfInt randomIterator;
+ private final PrimitiveIterator.OfInt randomIterator;
/**
* Initialize a new random number generator that generates random numbers in the range [min,
diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicketId.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicketId.java
index dfa324449..114e78c9c 100644
--- a/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicketId.java
+++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicketId.java
@@ -30,7 +30,7 @@ import java.util.concurrent.atomic.AtomicInteger;
*/
public class LotteryTicketId {
- private static AtomicInteger numAllocated = new AtomicInteger(0);
+ private static final AtomicInteger numAllocated = new AtomicInteger(0);
private final int id;
public LotteryTicketId() {
diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/eventlog/MongoEventLog.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/eventlog/MongoEventLog.java
index ba46f2d97..62fcf32b4 100644
--- a/hexagonal/src/main/java/com/iluwatar/hexagonal/eventlog/MongoEventLog.java
+++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/eventlog/MongoEventLog.java
@@ -36,12 +36,15 @@ public class MongoEventLog implements LotteryEventLog {
private static final String DEFAULT_DB = "lotteryDB";
private static final String DEFAULT_EVENTS_COLLECTION = "events";
+ private static final String EMAIL = "email";
+ private static final String PHONE = "phone";
+ public static final String MESSAGE = "message";
private MongoClient mongoClient;
private MongoDatabase database;
private MongoCollection eventsCollection;
- private StdOutEventLog stdOutEventLog = new StdOutEventLog();
+ private final StdOutEventLog stdOutEventLog = new StdOutEventLog();
/**
* Constructor.
@@ -107,41 +110,41 @@ public class MongoEventLog implements LotteryEventLog {
@Override
public void ticketSubmitted(PlayerDetails details) {
- var document = new Document("email", details.getEmail());
- document.put("phone", details.getPhoneNumber());
+ var document = new Document(EMAIL, details.getEmail());
+ document.put(PHONE, details.getPhoneNumber());
document.put("bank", details.getBankAccount());
document
- .put("message", "Lottery ticket was submitted and bank account was charged for 3 credits.");
+ .put(MESSAGE, "Lottery ticket was submitted and bank account was charged for 3 credits.");
eventsCollection.insertOne(document);
stdOutEventLog.ticketSubmitted(details);
}
@Override
public void ticketSubmitError(PlayerDetails details) {
- var document = new Document("email", details.getEmail());
- document.put("phone", details.getPhoneNumber());
+ var document = new Document(EMAIL, details.getEmail());
+ document.put(PHONE, details.getPhoneNumber());
document.put("bank", details.getBankAccount());
- document.put("message", "Lottery ticket could not be submitted because lack of funds.");
+ document.put(MESSAGE, "Lottery ticket could not be submitted because lack of funds.");
eventsCollection.insertOne(document);
stdOutEventLog.ticketSubmitError(details);
}
@Override
public void ticketDidNotWin(PlayerDetails details) {
- var document = new Document("email", details.getEmail());
- document.put("phone", details.getPhoneNumber());
+ var document = new Document(EMAIL, details.getEmail());
+ document.put(PHONE, details.getPhoneNumber());
document.put("bank", details.getBankAccount());
- document.put("message", "Lottery ticket was checked and unfortunately did not win this time.");
+ document.put(MESSAGE, "Lottery ticket was checked and unfortunately did not win this time.");
eventsCollection.insertOne(document);
stdOutEventLog.ticketDidNotWin(details);
}
@Override
public void ticketWon(PlayerDetails details, int prizeAmount) {
- var document = new Document("email", details.getEmail());
- document.put("phone", details.getPhoneNumber());
+ var document = new Document(EMAIL, details.getEmail());
+ document.put(PHONE, details.getPhoneNumber());
document.put("bank", details.getBankAccount());
- document.put("message", String
+ document.put(MESSAGE, String
.format("Lottery ticket won! The bank account was deposited with %d credits.",
prizeAmount));
eventsCollection.insertOne(document);
@@ -150,10 +153,10 @@ public class MongoEventLog implements LotteryEventLog {
@Override
public void prizeError(PlayerDetails details, int prizeAmount) {
- var document = new Document("email", details.getEmail());
- document.put("phone", details.getPhoneNumber());
+ var document = new Document(EMAIL, details.getEmail());
+ document.put(PHONE, details.getPhoneNumber());
document.put("bank", details.getBankAccount());
- document.put("message", String
+ document.put(MESSAGE, String
.format("Lottery ticket won! Unfortunately the bank credit transfer of %d failed.",
prizeAmount));
eventsCollection.insertOne(document);
diff --git a/hexagonal/src/test/java/com/iluwatar/hexagonal/AppTest.java b/hexagonal/src/test/java/com/iluwatar/hexagonal/AppTest.java
index 05d51a283..d2ad89c9b 100644
--- a/hexagonal/src/test/java/com/iluwatar/hexagonal/AppTest.java
+++ b/hexagonal/src/test/java/com/iluwatar/hexagonal/AppTest.java
@@ -25,13 +25,16 @@ package com.iluwatar.hexagonal;
import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+
/**
* Unit test for simple App.
*/
class AppTest {
@Test
- void testApp() {
- App.main(new String[]{});
+ void shouldExecuteApplicationWithoutException() {
+ assertDoesNotThrow(() -> App.main(new String[]{}));
+
}
}
diff --git a/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTest.java b/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTest.java
index 6d3ba8bc5..541b2b98b 100644
--- a/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTest.java
+++ b/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTest.java
@@ -43,7 +43,7 @@ import org.junit.jupiter.api.Test;
*/
class LotteryTest {
- private Injector injector;
+ private final Injector injector;
@Inject
private LotteryAdministration administration;
@Inject
diff --git a/intercepting-filter/pom.xml b/intercepting-filter/pom.xml
index ea8597374..d8ee9985f 100644
--- a/intercepting-filter/pom.xml
+++ b/intercepting-filter/pom.xml
@@ -29,7 +29,7 @@
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
intercepting-filter
diff --git a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Client.java b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Client.java
index 656008c10..52aa890c1 100644
--- a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Client.java
+++ b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Client.java
@@ -51,11 +51,11 @@ public class Client extends JFrame { // NOSONAR
private static final long serialVersionUID = 1L;
private transient FilterManager filterManager;
- private JLabel jl;
- private JTextField[] jtFields;
- private JTextArea[] jtAreas;
- private JButton clearButton;
- private JButton processButton;
+ private final JLabel jl;
+ private final JTextField[] jtFields;
+ private final JTextArea[] jtAreas;
+ private final JButton clearButton;
+ private final JButton processButton;
/**
* Constructor.
diff --git a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/FilterManager.java b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/FilterManager.java
index e8f3b941f..91e438882 100644
--- a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/FilterManager.java
+++ b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/FilterManager.java
@@ -30,7 +30,7 @@ package com.iluwatar.intercepting.filter;
*/
public class FilterManager {
- private FilterChain filterChain;
+ private final FilterChain filterChain;
public FilterManager() {
filterChain = new FilterChain();
diff --git a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Target.java b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Target.java
index 08ed715b1..db552356d 100644
--- a/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Target.java
+++ b/intercepting-filter/src/main/java/com/iluwatar/intercepting/filter/Target.java
@@ -46,9 +46,9 @@ public class Target extends JFrame { //NOSONAR
private static final long serialVersionUID = 1L;
- private JTable jt;
- private DefaultTableModel dtm;
- private JButton del;
+ private final JTable jt;
+ private final DefaultTableModel dtm;
+ private final JButton del;
/**
* Constructor.
diff --git a/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/AppTest.java b/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/AppTest.java
index 8fbe9f1d2..d8f22a478 100644
--- a/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/AppTest.java
+++ b/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/AppTest.java
@@ -25,13 +25,15 @@ package com.iluwatar.intercepting.filter;
import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+
/**
* Application test.
*/
-public class AppTest {
+class AppTest {
@Test
- public void test() {
- App.main(new String[]{});
+ void shouldExecuteApplicationWithoutException() {
+ assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
diff --git a/interpreter/pom.xml b/interpreter/pom.xml
index 118cfcdf6..d32c80839 100644
--- a/interpreter/pom.xml
+++ b/interpreter/pom.xml
@@ -29,7 +29,7 @@
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
interpreter
diff --git a/interpreter/src/main/java/com/iluwatar/interpreter/MinusExpression.java b/interpreter/src/main/java/com/iluwatar/interpreter/MinusExpression.java
index 24ef7914e..46b5c96cb 100644
--- a/interpreter/src/main/java/com/iluwatar/interpreter/MinusExpression.java
+++ b/interpreter/src/main/java/com/iluwatar/interpreter/MinusExpression.java
@@ -28,8 +28,8 @@ package com.iluwatar.interpreter;
*/
public class MinusExpression extends Expression {
- private Expression leftExpression;
- private Expression rightExpression;
+ private final Expression leftExpression;
+ private final Expression rightExpression;
public MinusExpression(Expression leftExpression, Expression rightExpression) {
this.leftExpression = leftExpression;
diff --git a/interpreter/src/main/java/com/iluwatar/interpreter/MultiplyExpression.java b/interpreter/src/main/java/com/iluwatar/interpreter/MultiplyExpression.java
index 606937e0b..926d6c119 100644
--- a/interpreter/src/main/java/com/iluwatar/interpreter/MultiplyExpression.java
+++ b/interpreter/src/main/java/com/iluwatar/interpreter/MultiplyExpression.java
@@ -28,8 +28,8 @@ package com.iluwatar.interpreter;
*/
public class MultiplyExpression extends Expression {
- private Expression leftExpression;
- private Expression rightExpression;
+ private final Expression leftExpression;
+ private final Expression rightExpression;
public MultiplyExpression(Expression leftExpression, Expression rightExpression) {
this.leftExpression = leftExpression;
diff --git a/interpreter/src/main/java/com/iluwatar/interpreter/NumberExpression.java b/interpreter/src/main/java/com/iluwatar/interpreter/NumberExpression.java
index 6b957f6aa..908eec8d1 100644
--- a/interpreter/src/main/java/com/iluwatar/interpreter/NumberExpression.java
+++ b/interpreter/src/main/java/com/iluwatar/interpreter/NumberExpression.java
@@ -28,7 +28,7 @@ package com.iluwatar.interpreter;
*/
public class NumberExpression extends Expression {
- private int number;
+ private final int number;
public NumberExpression(int number) {
this.number = number;
diff --git a/interpreter/src/main/java/com/iluwatar/interpreter/PlusExpression.java b/interpreter/src/main/java/com/iluwatar/interpreter/PlusExpression.java
index 1ce080259..38a8bb4af 100644
--- a/interpreter/src/main/java/com/iluwatar/interpreter/PlusExpression.java
+++ b/interpreter/src/main/java/com/iluwatar/interpreter/PlusExpression.java
@@ -28,8 +28,8 @@ package com.iluwatar.interpreter;
*/
public class PlusExpression extends Expression {
- private Expression leftExpression;
- private Expression rightExpression;
+ private final Expression leftExpression;
+ private final Expression rightExpression;
public PlusExpression(Expression leftExpression, Expression rightExpression) {
this.leftExpression = leftExpression;
diff --git a/interpreter/src/test/java/com/iluwatar/interpreter/AppTest.java b/interpreter/src/test/java/com/iluwatar/interpreter/AppTest.java
index 505dc559c..f4fb45637 100644
--- a/interpreter/src/test/java/com/iluwatar/interpreter/AppTest.java
+++ b/interpreter/src/test/java/com/iluwatar/interpreter/AppTest.java
@@ -25,13 +25,15 @@ package com.iluwatar.interpreter;
import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+
/**
* Application test
*/
-public class AppTest {
+class AppTest {
@Test
- public void test() {
- App.main(new String[]{});
+ void shouldExecuteApplicationWithoutException() {
+ assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
diff --git a/iterator/README.md b/iterator/README.md
index 7f06a64b9..a98010c5a 100644
--- a/iterator/README.md
+++ b/iterator/README.md
@@ -36,7 +36,7 @@ The main class in our example is the treasure chest that contains items.
```java
public class TreasureChest {
- private List- items;
+ private final List
- items;
public TreasureChest() {
items = List.of(
@@ -64,7 +64,7 @@ public class TreasureChest {
public class Item {
private ItemType type;
- private String name;
+ private final String name;
public Item(ItemType type, String name) {
this.setType(type);
diff --git a/iterator/pom.xml b/iterator/pom.xml
index 514cedbea..bca091f11 100644
--- a/iterator/pom.xml
+++ b/iterator/pom.xml
@@ -29,7 +29,7 @@
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
iterator
diff --git a/iterator/src/main/java/com/iluwatar/iterator/bst/BstIterator.java b/iterator/src/main/java/com/iluwatar/iterator/bst/BstIterator.java
index b3e0dc3d6..9f584cddc 100644
--- a/iterator/src/main/java/com/iluwatar/iterator/bst/BstIterator.java
+++ b/iterator/src/main/java/com/iluwatar/iterator/bst/BstIterator.java
@@ -36,7 +36,7 @@ import java.util.NoSuchElementException;
*/
public class BstIterator> implements Iterator> {
- private ArrayDeque> pathStack;
+ private final ArrayDeque> pathStack;
public BstIterator(TreeNode root) {
pathStack = new ArrayDeque<>();
diff --git a/iterator/src/main/java/com/iluwatar/iterator/bst/TreeNode.java b/iterator/src/main/java/com/iluwatar/iterator/bst/TreeNode.java
index 87f16e96c..b0ec5f486 100644
--- a/iterator/src/main/java/com/iluwatar/iterator/bst/TreeNode.java
+++ b/iterator/src/main/java/com/iluwatar/iterator/bst/TreeNode.java
@@ -31,7 +31,7 @@ package com.iluwatar.iterator.bst;
*/
public class TreeNode> {
- private T val;
+ private final T val;
private TreeNode left;
private TreeNode right;
diff --git a/iterator/src/main/java/com/iluwatar/iterator/list/Item.java b/iterator/src/main/java/com/iluwatar/iterator/list/Item.java
index 82e66eb30..00d5625a8 100644
--- a/iterator/src/main/java/com/iluwatar/iterator/list/Item.java
+++ b/iterator/src/main/java/com/iluwatar/iterator/list/Item.java
@@ -29,7 +29,7 @@ package com.iluwatar.iterator.list;
public class Item {
private ItemType type;
- private String name;
+ private final String name;
public Item(ItemType type, String name) {
this.setType(type);
diff --git a/iterator/src/main/java/com/iluwatar/iterator/list/TreasureChest.java b/iterator/src/main/java/com/iluwatar/iterator/list/TreasureChest.java
index f390c760f..8eb4a8e18 100644
--- a/iterator/src/main/java/com/iluwatar/iterator/list/TreasureChest.java
+++ b/iterator/src/main/java/com/iluwatar/iterator/list/TreasureChest.java
@@ -32,7 +32,7 @@ import java.util.List;
*/
public class TreasureChest {
- private List- items;
+ private final List
- items;
/**
* Constructor.
diff --git a/iterator/src/main/java/com/iluwatar/iterator/list/TreasureChestItemIterator.java b/iterator/src/main/java/com/iluwatar/iterator/list/TreasureChestItemIterator.java
index 90461c420..a309b4ece 100644
--- a/iterator/src/main/java/com/iluwatar/iterator/list/TreasureChestItemIterator.java
+++ b/iterator/src/main/java/com/iluwatar/iterator/list/TreasureChestItemIterator.java
@@ -30,9 +30,9 @@ import com.iluwatar.iterator.Iterator;
*/
public class TreasureChestItemIterator implements Iterator
- {
- private TreasureChest chest;
+ private final TreasureChest chest;
private int idx;
- private ItemType type;
+ private final ItemType type;
/**
* Constructor.
diff --git a/iterator/src/test/java/com/iluwatar/iterator/AppTest.java b/iterator/src/test/java/com/iluwatar/iterator/AppTest.java
index ccb33307c..2e0d28b67 100644
--- a/iterator/src/test/java/com/iluwatar/iterator/AppTest.java
+++ b/iterator/src/test/java/com/iluwatar/iterator/AppTest.java
@@ -25,13 +25,15 @@ package com.iluwatar.iterator;
import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+
/**
* Application Test
*/
class AppTest {
@Test
- void testApp() {
- App.main(new String[]{});
+ void shouldExecuteApplicationWithoutException() {
+ assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
\ No newline at end of file
diff --git a/layers/README.md b/layers/README.md
index c3c56ad00..1e309f92b 100644
--- a/layers/README.md
+++ b/layers/README.md
@@ -79,7 +79,7 @@ public class CakeViewImpl implements View {
private static final Logger LOGGER = LoggerFactory.getLogger(CakeViewImpl.class);
- private CakeBakingService cakeBakingService;
+ private final CakeBakingService cakeBakingService;
public CakeViewImpl(CakeBakingService cakeBakingService) {
this.cakeBakingService = cakeBakingService;
diff --git a/layers/pom.xml b/layers/pom.xml
index 2ebace18b..9c299d2ba 100644
--- a/layers/pom.xml
+++ b/layers/pom.xml
@@ -30,7 +30,7 @@
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
com.iluwatar.layers
layers
diff --git a/layers/src/main/java/com/iluwatar/layers/app/App.java b/layers/src/main/java/com/iluwatar/layers/app/App.java
index afeb5ba50..8574b8d02 100644
--- a/layers/src/main/java/com/iluwatar/layers/app/App.java
+++ b/layers/src/main/java/com/iluwatar/layers/app/App.java
@@ -80,7 +80,8 @@ import java.util.List;
*/
public class App {
- private static CakeBakingService cakeBakingService = new CakeBakingServiceImpl();
+ private static final CakeBakingService cakeBakingService = new CakeBakingServiceImpl();
+ public static final String STRAWBERRY = "strawberry";
/**
* Application entry point.
@@ -103,10 +104,10 @@ public class App {
private static void initializeData(CakeBakingService cakeBakingService) {
cakeBakingService.saveNewLayer(new CakeLayerInfo("chocolate", 1200));
cakeBakingService.saveNewLayer(new CakeLayerInfo("banana", 900));
- cakeBakingService.saveNewLayer(new CakeLayerInfo("strawberry", 950));
+ cakeBakingService.saveNewLayer(new CakeLayerInfo(STRAWBERRY, 950));
cakeBakingService.saveNewLayer(new CakeLayerInfo("lemon", 950));
cakeBakingService.saveNewLayer(new CakeLayerInfo("vanilla", 950));
- cakeBakingService.saveNewLayer(new CakeLayerInfo("strawberry", 950));
+ cakeBakingService.saveNewLayer(new CakeLayerInfo(STRAWBERRY, 950));
cakeBakingService.saveNewTopping(new CakeToppingInfo("candies", 350));
cakeBakingService.saveNewTopping(new CakeToppingInfo("cherry", 350));
@@ -114,7 +115,7 @@ public class App {
var cake1 = new CakeInfo(new CakeToppingInfo("candies", 0), List.of(
new CakeLayerInfo("chocolate", 0),
new CakeLayerInfo("banana", 0),
- new CakeLayerInfo("strawberry", 0)));
+ new CakeLayerInfo(STRAWBERRY, 0)));
try {
cakeBakingService.bakeNewCake(cake1);
} catch (CakeBakingException e) {
@@ -123,7 +124,7 @@ public class App {
var cake2 = new CakeInfo(new CakeToppingInfo("cherry", 0), List.of(
new CakeLayerInfo("vanilla", 0),
new CakeLayerInfo("lemon", 0),
- new CakeLayerInfo("strawberry", 0)));
+ new CakeLayerInfo(STRAWBERRY, 0)));
try {
cakeBakingService.bakeNewCake(cake2);
} catch (CakeBakingException e) {
diff --git a/layers/src/main/java/com/iluwatar/layers/service/CakeBakingServiceImpl.java b/layers/src/main/java/com/iluwatar/layers/service/CakeBakingServiceImpl.java
index 226b5bcea..14fee4dfa 100644
--- a/layers/src/main/java/com/iluwatar/layers/service/CakeBakingServiceImpl.java
+++ b/layers/src/main/java/com/iluwatar/layers/service/CakeBakingServiceImpl.java
@@ -52,7 +52,7 @@ import org.springframework.transaction.annotation.Transactional;
@Transactional
public class CakeBakingServiceImpl implements CakeBakingService {
- private AbstractApplicationContext context;
+ private final AbstractApplicationContext context;
public CakeBakingServiceImpl() {
this.context = new ClassPathXmlApplicationContext("applicationContext.xml");
diff --git a/layers/src/main/java/com/iluwatar/layers/view/CakeViewImpl.java b/layers/src/main/java/com/iluwatar/layers/view/CakeViewImpl.java
index 5fcaac776..a5246e7db 100644
--- a/layers/src/main/java/com/iluwatar/layers/view/CakeViewImpl.java
+++ b/layers/src/main/java/com/iluwatar/layers/view/CakeViewImpl.java
@@ -34,7 +34,7 @@ public class CakeViewImpl implements View {
private static final Logger LOGGER = LoggerFactory.getLogger(CakeViewImpl.class);
- private CakeBakingService cakeBakingService;
+ private final CakeBakingService cakeBakingService;
public CakeViewImpl(CakeBakingService cakeBakingService) {
this.cakeBakingService = cakeBakingService;
diff --git a/layers/src/test/java/com/iluwatar/layers/app/AppTest.java b/layers/src/test/java/com/iluwatar/layers/app/AppTest.java
index 10d224a8e..105487683 100644
--- a/layers/src/test/java/com/iluwatar/layers/app/AppTest.java
+++ b/layers/src/test/java/com/iluwatar/layers/app/AppTest.java
@@ -23,19 +23,19 @@
package com.iluwatar.layers.app;
-import com.iluwatar.layers.app.App;
import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+
/**
*
* Application test
*
*/
-public class AppTest {
+class AppTest {
@Test
- public void test() {
- String[] args = {};
- App.main(args);
+ void shouldExecuteApplicationWithoutException() {
+ assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
diff --git a/layers/src/test/java/com/iluwatar/layers/view/CakeViewImplTest.java b/layers/src/test/java/com/iluwatar/layers/view/CakeViewImplTest.java
index b707731d2..3c13966de 100644
--- a/layers/src/test/java/com/iluwatar/layers/view/CakeViewImplTest.java
+++ b/layers/src/test/java/com/iluwatar/layers/view/CakeViewImplTest.java
@@ -90,7 +90,7 @@ public class CakeViewImplTest {
private class InMemoryAppender extends AppenderBase {
- private List log = new LinkedList<>();
+ private final List log = new LinkedList<>();
public InMemoryAppender(Class clazz) {
((Logger) LoggerFactory.getLogger(clazz)).addAppender(this);
diff --git a/lazy-loading/pom.xml b/lazy-loading/pom.xml
index a6a5d3a45..49421edc2 100644
--- a/lazy-loading/pom.xml
+++ b/lazy-loading/pom.xml
@@ -29,7 +29,7 @@
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
lazy-loading
diff --git a/lazy-loading/src/main/java/com/iluwatar/lazy/loading/Java8Holder.java b/lazy-loading/src/main/java/com/iluwatar/lazy/loading/Java8Holder.java
index 2854a7822..395dfb81c 100644
--- a/lazy-loading/src/main/java/com/iluwatar/lazy/loading/Java8Holder.java
+++ b/lazy-loading/src/main/java/com/iluwatar/lazy/loading/Java8Holder.java
@@ -55,7 +55,7 @@ public class Java8Holder {
}
}
- if (!HeavyFactory.class.isInstance(heavy)) {
+ if (!(heavy instanceof HeavyFactory)) {
heavy = new HeavyFactory();
}
diff --git a/lazy-loading/src/test/java/com/iluwatar/lazy/loading/AppTest.java b/lazy-loading/src/test/java/com/iluwatar/lazy/loading/AppTest.java
index eeccd10ce..74c324b24 100644
--- a/lazy-loading/src/test/java/com/iluwatar/lazy/loading/AppTest.java
+++ b/lazy-loading/src/test/java/com/iluwatar/lazy/loading/AppTest.java
@@ -25,16 +25,17 @@ package com.iluwatar.lazy.loading;
import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+
/**
*
* Application test
*
*/
-public class AppTest {
+class AppTest {
@Test
- public void test() {
- String[] args = {};
- App.main(args);
+ void shouldExecuteApplicationWithoutException() {
+ assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
diff --git a/leader-election/pom.xml b/leader-election/pom.xml
index 8fc833f18..78ad13e4d 100644
--- a/leader-election/pom.xml
+++ b/leader-election/pom.xml
@@ -30,7 +30,7 @@
java-design-patterns
com.iluwatar
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
leader-election
diff --git a/leader-election/src/main/java/com/iluwatar/leaderelection/AbstractInstance.java b/leader-election/src/main/java/com/iluwatar/leaderelection/AbstractInstance.java
index f30610597..94db89ef7 100644
--- a/leader-election/src/main/java/com/iluwatar/leaderelection/AbstractInstance.java
+++ b/leader-election/src/main/java/com/iluwatar/leaderelection/AbstractInstance.java
@@ -36,6 +36,7 @@ public abstract class AbstractInstance implements Instance, Runnable {
private static final Logger LOGGER = LoggerFactory.getLogger(AbstractInstance.class);
protected static final int HEARTBEAT_INTERVAL = 5000;
+ private static final String INSTANCE = "Instance ";
protected MessageManager messageManager;
protected Queue messageQueue;
@@ -106,27 +107,27 @@ public abstract class AbstractInstance implements Instance, Runnable {
private void processMessage(Message message) {
switch (message.getType()) {
case ELECTION:
- LOGGER.info("Instance " + localId + " - Election Message handling...");
+ LOGGER.info(INSTANCE + localId + " - Election Message handling...");
handleElectionMessage(message);
break;
case LEADER:
- LOGGER.info("Instance " + localId + " - Leader Message handling...");
+ LOGGER.info(INSTANCE + localId + " - Leader Message handling...");
handleLeaderMessage(message);
break;
case HEARTBEAT:
- LOGGER.info("Instance " + localId + " - Heartbeat Message handling...");
+ LOGGER.info(INSTANCE + localId + " - Heartbeat Message handling...");
handleHeartbeatMessage(message);
break;
case ELECTION_INVOKE:
- LOGGER.info("Instance " + localId + " - Election Invoke Message handling...");
+ LOGGER.info(INSTANCE + localId + " - Election Invoke Message handling...");
handleElectionInvokeMessage();
break;
case LEADER_INVOKE:
- LOGGER.info("Instance " + localId + " - Leader Invoke Message handling...");
+ LOGGER.info(INSTANCE + localId + " - Leader Invoke Message handling...");
handleLeaderInvokeMessage();
break;
case HEARTBEAT_INVOKE:
- LOGGER.info("Instance " + localId + " - Heartbeat Invoke Message handling...");
+ LOGGER.info(INSTANCE + localId + " - Heartbeat Invoke Message handling...");
handleHeartbeatInvokeMessage();
break;
default:
diff --git a/leader-election/src/main/java/com/iluwatar/leaderelection/bully/BullyInstance.java b/leader-election/src/main/java/com/iluwatar/leaderelection/bully/BullyInstance.java
index 92cb18ab4..3181791d4 100644
--- a/leader-election/src/main/java/com/iluwatar/leaderelection/bully/BullyInstance.java
+++ b/leader-election/src/main/java/com/iluwatar/leaderelection/bully/BullyInstance.java
@@ -41,6 +41,7 @@ import org.slf4j.LoggerFactory;
public class BullyInstance extends AbstractInstance {
private static final Logger LOGGER = LoggerFactory.getLogger(BullyInstance.class);
+ private static final String INSTANCE = "Instance ";
/**
* Constructor of BullyInstance.
@@ -59,20 +60,20 @@ public class BullyInstance extends AbstractInstance {
try {
boolean isLeaderAlive = messageManager.sendHeartbeatMessage(leaderId);
if (isLeaderAlive) {
- LOGGER.info("Instance " + localId + "- Leader is alive.");
+ LOGGER.info(INSTANCE + localId + "- Leader is alive.");
Thread.sleep(HEARTBEAT_INTERVAL);
messageManager.sendHeartbeatInvokeMessage(localId);
} else {
- LOGGER.info("Instance " + localId + "- Leader is not alive. Start election.");
+ LOGGER.info(INSTANCE + localId + "- Leader is not alive. Start election.");
boolean electionResult =
messageManager.sendElectionMessage(localId, String.valueOf(localId));
if (electionResult) {
- LOGGER.info("Instance " + localId + "- Succeed in election. Start leader notification.");
+ LOGGER.info(INSTANCE + localId + "- Succeed in election. Start leader notification.");
messageManager.sendLeaderMessage(localId, localId);
}
}
} catch (InterruptedException e) {
- LOGGER.info("Instance " + localId + "- Interrupted.");
+ LOGGER.info(INSTANCE + localId + "- Interrupted.");
}
}
@@ -84,10 +85,10 @@ public class BullyInstance extends AbstractInstance {
@Override
protected void handleElectionInvokeMessage() {
if (!isLeader()) {
- LOGGER.info("Instance " + localId + "- Start election.");
+ LOGGER.info(INSTANCE + localId + "- Start election.");
boolean electionResult = messageManager.sendElectionMessage(localId, String.valueOf(localId));
if (electionResult) {
- LOGGER.info("Instance " + localId + "- Succeed in election. Start leader notification.");
+ LOGGER.info(INSTANCE + localId + "- Succeed in election. Start leader notification.");
leaderId = localId;
messageManager.sendLeaderMessage(localId, localId);
messageManager.sendHeartbeatInvokeMessage(localId);
@@ -101,25 +102,25 @@ public class BullyInstance extends AbstractInstance {
@Override
protected void handleLeaderMessage(Message message) {
leaderId = Integer.valueOf(message.getContent());
- LOGGER.info("Instance " + localId + " - Leader update done.");
+ LOGGER.info(INSTANCE + localId + " - Leader update done.");
}
private boolean isLeader() {
return localId == leaderId;
}
- /**
- * Not used in Bully instance.
- */
@Override
protected void handleLeaderInvokeMessage() {
+ // Not used in Bully Instance
}
@Override
protected void handleHeartbeatMessage(Message message) {
+ // Not used in Bully Instance
}
@Override
protected void handleElectionMessage(Message message) {
+ // Not used in Bully Instance
}
}
diff --git a/leader-election/src/main/java/com/iluwatar/leaderelection/ring/RingInstance.java b/leader-election/src/main/java/com/iluwatar/leaderelection/ring/RingInstance.java
index d4a3075d8..2d2d0ae1a 100644
--- a/leader-election/src/main/java/com/iluwatar/leaderelection/ring/RingInstance.java
+++ b/leader-election/src/main/java/com/iluwatar/leaderelection/ring/RingInstance.java
@@ -46,6 +46,7 @@ import org.slf4j.LoggerFactory;
public class RingInstance extends AbstractInstance {
private static final Logger LOGGER = LoggerFactory.getLogger(RingInstance.class);
+ private static final String INSTANCE = "Instance ";
/**
* Constructor of RingInstance.
@@ -64,15 +65,15 @@ public class RingInstance extends AbstractInstance {
try {
var isLeaderAlive = messageManager.sendHeartbeatMessage(this.leaderId);
if (isLeaderAlive) {
- LOGGER.info("Instance " + localId + "- Leader is alive. Start next heartbeat in 5 second.");
+ LOGGER.info(INSTANCE + localId + "- Leader is alive. Start next heartbeat in 5 second.");
Thread.sleep(HEARTBEAT_INTERVAL);
messageManager.sendHeartbeatInvokeMessage(this.localId);
} else {
- LOGGER.info("Instance " + localId + "- Leader is not alive. Start election.");
+ LOGGER.info(INSTANCE + localId + "- Leader is not alive. Start election.");
messageManager.sendElectionMessage(this.localId, String.valueOf(this.localId));
}
} catch (InterruptedException e) {
- LOGGER.info("Instance " + localId + "- Interrupted.");
+ LOGGER.info(INSTANCE + localId + "- Interrupted.");
}
}
@@ -85,14 +86,14 @@ public class RingInstance extends AbstractInstance {
@Override
protected void handleElectionMessage(Message message) {
var content = message.getContent();
- LOGGER.info("Instance " + localId + " - Election Message: " + content);
+ LOGGER.info(INSTANCE + localId + " - Election Message: " + content);
var candidateList = Arrays.stream(content.trim().split(","))
.map(Integer::valueOf)
.sorted()
.collect(Collectors.toList());
if (candidateList.contains(localId)) {
var newLeaderId = candidateList.get(0);
- LOGGER.info("Instance " + localId + " - New leader should be " + newLeaderId + ".");
+ LOGGER.info(INSTANCE + localId + " - New leader should be " + newLeaderId + ".");
messageManager.sendLeaderMessage(localId, newLeaderId);
} else {
content += "," + localId;
@@ -108,11 +109,11 @@ public class RingInstance extends AbstractInstance {
protected void handleLeaderMessage(Message message) {
var newLeaderId = Integer.valueOf(message.getContent());
if (this.leaderId != newLeaderId) {
- LOGGER.info("Instance " + localId + " - Update leaderID");
+ LOGGER.info(INSTANCE + localId + " - Update leaderID");
this.leaderId = newLeaderId;
messageManager.sendLeaderMessage(localId, newLeaderId);
} else {
- LOGGER.info("Instance " + localId + " - Leader update done. Start heartbeat.");
+ LOGGER.info(INSTANCE + localId + " - Leader update done. Start heartbeat.");
messageManager.sendHeartbeatInvokeMessage(localId);
}
}
@@ -122,14 +123,17 @@ public class RingInstance extends AbstractInstance {
*/
@Override
protected void handleLeaderInvokeMessage() {
+ // Not used in Ring instance.
}
@Override
protected void handleHeartbeatMessage(Message message) {
+ // Not used in Ring instance.
}
@Override
protected void handleElectionInvokeMessage() {
+ // Not used in Ring instance.
}
}
diff --git a/leader-election/src/test/java/com/iluwatar/leaderelection/bully/BullyAppTest.java b/leader-election/src/test/java/com/iluwatar/leaderelection/bully/BullyAppTest.java
index 3ef36f758..19497a32c 100644
--- a/leader-election/src/test/java/com/iluwatar/leaderelection/bully/BullyAppTest.java
+++ b/leader-election/src/test/java/com/iluwatar/leaderelection/bully/BullyAppTest.java
@@ -25,15 +25,16 @@ package com.iluwatar.leaderelection.bully;
import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+
/**
* BullyApp unit test.
*/
-public class BullyAppTest {
+class BullyAppTest {
@Test
- public void test() {
- String[] args = {};
- BullyApp.main(args);
+ void shouldExecuteApplicationWithoutException() {
+ assertDoesNotThrow(() -> BullyApp.main(new String[]{}));
}
}
diff --git a/leader-election/src/test/java/com/iluwatar/leaderelection/ring/RingAppTest.java b/leader-election/src/test/java/com/iluwatar/leaderelection/ring/RingAppTest.java
index ec3851d9b..ce5c59aa7 100644
--- a/leader-election/src/test/java/com/iluwatar/leaderelection/ring/RingAppTest.java
+++ b/leader-election/src/test/java/com/iluwatar/leaderelection/ring/RingAppTest.java
@@ -25,15 +25,16 @@ package com.iluwatar.leaderelection.ring;
import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+
/**
* RingApp unit test.
*/
-public class RingAppTest {
+class RingAppTest {
@Test
- public void test() {
- String[] args = {};
- RingApp.main(args);
+ void shouldExecuteApplicationWithoutException() {
+ assertDoesNotThrow(() -> RingApp.main(new String[]{}));
}
}
diff --git a/leader-followers/pom.xml b/leader-followers/pom.xml
index 4efdbf3ac..42e552ac8 100644
--- a/leader-followers/pom.xml
+++ b/leader-followers/pom.xml
@@ -28,7 +28,7 @@
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
leader-followers
@@ -37,6 +37,11 @@
junit
test
+
+ org.junit.jupiter
+ junit-jupiter-engine
+ test
+
org.mockito
mockito-core
diff --git a/leader-followers/src/main/java/com.iluwatar.leaderfollowers/App.java b/leader-followers/src/main/java/com/iluwatar/leaderfollowers/App.java
similarity index 100%
rename from leader-followers/src/main/java/com.iluwatar.leaderfollowers/App.java
rename to leader-followers/src/main/java/com/iluwatar/leaderfollowers/App.java
diff --git a/leader-followers/src/main/java/com.iluwatar.leaderfollowers/Task.java b/leader-followers/src/main/java/com/iluwatar/leaderfollowers/Task.java
similarity index 100%
rename from leader-followers/src/main/java/com.iluwatar.leaderfollowers/Task.java
rename to leader-followers/src/main/java/com/iluwatar/leaderfollowers/Task.java
diff --git a/leader-followers/src/main/java/com.iluwatar.leaderfollowers/TaskHandler.java b/leader-followers/src/main/java/com/iluwatar/leaderfollowers/TaskHandler.java
similarity index 100%
rename from leader-followers/src/main/java/com.iluwatar.leaderfollowers/TaskHandler.java
rename to leader-followers/src/main/java/com/iluwatar/leaderfollowers/TaskHandler.java
diff --git a/leader-followers/src/main/java/com.iluwatar.leaderfollowers/TaskSet.java b/leader-followers/src/main/java/com/iluwatar/leaderfollowers/TaskSet.java
similarity index 95%
rename from leader-followers/src/main/java/com.iluwatar.leaderfollowers/TaskSet.java
rename to leader-followers/src/main/java/com/iluwatar/leaderfollowers/TaskSet.java
index 3138427a3..3461bc8c0 100644
--- a/leader-followers/src/main/java/com.iluwatar.leaderfollowers/TaskSet.java
+++ b/leader-followers/src/main/java/com/iluwatar/leaderfollowers/TaskSet.java
@@ -31,7 +31,7 @@ import java.util.concurrent.BlockingQueue;
*/
public class TaskSet {
- private BlockingQueue queue = new ArrayBlockingQueue<>(100);
+ private final BlockingQueue queue = new ArrayBlockingQueue<>(100);
public void addTask(Task task) throws InterruptedException {
queue.put(task);
diff --git a/leader-followers/src/main/java/com.iluwatar.leaderfollowers/WorkCenter.java b/leader-followers/src/main/java/com/iluwatar/leaderfollowers/WorkCenter.java
similarity index 97%
rename from leader-followers/src/main/java/com.iluwatar.leaderfollowers/WorkCenter.java
rename to leader-followers/src/main/java/com/iluwatar/leaderfollowers/WorkCenter.java
index 7c63d95d2..935462037 100644
--- a/leader-followers/src/main/java/com.iluwatar.leaderfollowers/WorkCenter.java
+++ b/leader-followers/src/main/java/com/iluwatar/leaderfollowers/WorkCenter.java
@@ -34,7 +34,7 @@ import java.util.concurrent.CopyOnWriteArrayList;
public class WorkCenter {
private Worker leader;
- private List workers = new CopyOnWriteArrayList<>();
+ private final List workers = new CopyOnWriteArrayList<>();
/**
* Create workers and set leader.
diff --git a/leader-followers/src/main/java/com.iluwatar.leaderfollowers/Worker.java b/leader-followers/src/main/java/com/iluwatar/leaderfollowers/Worker.java
similarity index 100%
rename from leader-followers/src/main/java/com.iluwatar.leaderfollowers/Worker.java
rename to leader-followers/src/main/java/com/iluwatar/leaderfollowers/Worker.java
diff --git a/leader-followers/src/test/java/com.iluwatar.leaderfollowers/AppTest.java b/leader-followers/src/test/java/com/AppTest.java
similarity index 83%
rename from leader-followers/src/test/java/com.iluwatar.leaderfollowers/AppTest.java
rename to leader-followers/src/test/java/com/AppTest.java
index 00fbfe4d2..3d0588fef 100644
--- a/leader-followers/src/test/java/com.iluwatar.leaderfollowers/AppTest.java
+++ b/leader-followers/src/test/java/com/AppTest.java
@@ -21,10 +21,13 @@
* THE SOFTWARE.
*/
-package com.iluwatar.leaderfollowers;
+package com;
+import com.iluwatar.leaderfollowers.App;
import org.junit.Test;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+
/**
*
* Application test
@@ -33,9 +36,8 @@ import org.junit.Test;
public class AppTest {
@Test
- public void test() throws InterruptedException {
- String[] args = {};
- App.main(args);
+ public void shouldExecuteApplicationWithoutException() {
+ assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
diff --git a/leader-followers/src/test/java/com.iluwatar.leaderfollowers/TaskHandlerTest.java b/leader-followers/src/test/java/com/TaskHandlerTest.java
similarity index 93%
rename from leader-followers/src/test/java/com.iluwatar.leaderfollowers/TaskHandlerTest.java
rename to leader-followers/src/test/java/com/TaskHandlerTest.java
index 9fb39c922..7dc44c04f 100644
--- a/leader-followers/src/test/java/com.iluwatar.leaderfollowers/TaskHandlerTest.java
+++ b/leader-followers/src/test/java/com/TaskHandlerTest.java
@@ -21,8 +21,10 @@
* THE SOFTWARE.
*/
-package com.iluwatar.leaderfollowers;
+package com;
+import com.iluwatar.leaderfollowers.Task;
+import com.iluwatar.leaderfollowers.TaskHandler;
import org.junit.Assert;
import org.junit.Test;
diff --git a/leader-followers/src/test/java/com.iluwatar.leaderfollowers/TaskSetTest.java b/leader-followers/src/test/java/com/TaskSetTest.java
similarity index 94%
rename from leader-followers/src/test/java/com.iluwatar.leaderfollowers/TaskSetTest.java
rename to leader-followers/src/test/java/com/TaskSetTest.java
index 53cb31deb..e3691d220 100644
--- a/leader-followers/src/test/java/com.iluwatar.leaderfollowers/TaskSetTest.java
+++ b/leader-followers/src/test/java/com/TaskSetTest.java
@@ -21,8 +21,10 @@
* THE SOFTWARE.
*/
-package com.iluwatar.leaderfollowers;
+package com;
+import com.iluwatar.leaderfollowers.Task;
+import com.iluwatar.leaderfollowers.TaskSet;
import org.junit.Assert;
import org.junit.Test;
diff --git a/leader-followers/src/test/java/com.iluwatar.leaderfollowers/WorkCenterTest.java b/leader-followers/src/test/java/com/WorkCenterTest.java
similarity index 93%
rename from leader-followers/src/test/java/com.iluwatar.leaderfollowers/WorkCenterTest.java
rename to leader-followers/src/test/java/com/WorkCenterTest.java
index 045d8c3dc..41e9ff43f 100644
--- a/leader-followers/src/test/java/com.iluwatar.leaderfollowers/WorkCenterTest.java
+++ b/leader-followers/src/test/java/com/WorkCenterTest.java
@@ -21,8 +21,11 @@
* THE SOFTWARE.
*/
-package com.iluwatar.leaderfollowers;
+package com;
+import com.iluwatar.leaderfollowers.TaskHandler;
+import com.iluwatar.leaderfollowers.TaskSet;
+import com.iluwatar.leaderfollowers.WorkCenter;
import org.junit.Assert;
import org.junit.Test;
diff --git a/marker/pom.xml b/marker/pom.xml
index 5212832d8..64b7243f3 100644
--- a/marker/pom.xml
+++ b/marker/pom.xml
@@ -29,7 +29,7 @@
java-design-patterns
com.iluwatar
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
4.0.0
diff --git a/marker/src/main/java/App.java b/marker/src/main/java/App.java
index 384c999dc..0908503e5 100644
--- a/marker/src/main/java/App.java
+++ b/marker/src/main/java/App.java
@@ -46,17 +46,18 @@ public class App {
* @param args command line args
*/
public static void main(String[] args) {
+ final var logger = LoggerFactory.getLogger(App.class);
+ var guard = new Guard();
+ var thief = new Thief();
- final Logger logger = LoggerFactory.getLogger(App.class);
- Guard guard = new Guard();
- Thief thief = new Thief();
-
+ //noinspection ConstantConditions
if (guard instanceof Permission) {
guard.enter();
} else {
logger.info("You have no permission to enter, please leave this area");
}
+ //noinspection ConstantConditions
if (thief instanceof Permission) {
thief.steal();
} else {
diff --git a/marker/src/main/java/Guard.java b/marker/src/main/java/Guard.java
index 9a57e15fd..9e7b731b6 100644
--- a/marker/src/main/java/Guard.java
+++ b/marker/src/main/java/Guard.java
@@ -28,11 +28,9 @@ import org.slf4j.LoggerFactory;
* Class defining Guard.
*/
public class Guard implements Permission {
-
private static final Logger LOGGER = LoggerFactory.getLogger(Guard.class);
- protected static void enter() {
-
+ protected void enter() {
LOGGER.info("You can enter");
}
}
diff --git a/marker/src/main/java/Thief.java b/marker/src/main/java/Thief.java
index 341eae377..0e4cf92e3 100644
--- a/marker/src/main/java/Thief.java
+++ b/marker/src/main/java/Thief.java
@@ -28,14 +28,13 @@ import org.slf4j.LoggerFactory;
* Class defining Thief.
*/
public class Thief {
-
private static final Logger LOGGER = LoggerFactory.getLogger(Thief.class);
- protected static void steal() {
+ protected void steal() {
LOGGER.info("Steal valuable items");
}
- protected static void doNothing() {
+ protected void doNothing() {
LOGGER.info("Pretend nothing happened and just leave");
}
}
diff --git a/marker/src/test/java/AppTest.java b/marker/src/test/java/AppTest.java
index 5d63db0ad..17a13c167 100644
--- a/marker/src/test/java/AppTest.java
+++ b/marker/src/test/java/AppTest.java
@@ -23,14 +23,15 @@
import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+
/**
* Application test
*/
-public class AppTest {
+class AppTest {
@Test
- public void test() {
- String[] args = {};
- App.main(args);
+ void shouldExecuteApplicationWithoutException() {
+ assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
diff --git a/marker/src/test/java/GuardTest.java b/marker/src/test/java/GuardTest.java
index 615d4e129..ae92c27dc 100644
--- a/marker/src/test/java/GuardTest.java
+++ b/marker/src/test/java/GuardTest.java
@@ -33,7 +33,7 @@ public class GuardTest {
@Test
public void testGuard() {
- Guard guard = new Guard();
+ var guard = new Guard();
assertThat(guard, instanceOf(Permission.class));
}
}
\ No newline at end of file
diff --git a/marker/src/test/java/ThiefTest.java b/marker/src/test/java/ThiefTest.java
index 2732fc78a..dc081acf8 100644
--- a/marker/src/test/java/ThiefTest.java
+++ b/marker/src/test/java/ThiefTest.java
@@ -21,9 +21,11 @@
* THE SOFTWARE.
*/
-import org.junit.jupiter.api.Test;
+import static org.hamcrest.CoreMatchers.instanceOf;
+import static org.hamcrest.CoreMatchers.not;
+import static org.hamcrest.MatcherAssert.assertThat;
-import static org.junit.jupiter.api.Assertions.assertFalse;
+import org.junit.jupiter.api.Test;
/**
* Thief test
@@ -31,7 +33,7 @@ import static org.junit.jupiter.api.Assertions.assertFalse;
public class ThiefTest {
@Test
public void testThief() {
- Thief thief = new Thief();
- assertFalse(thief instanceof Permission);
+ var thief = new Thief();
+ assertThat(thief, not(instanceOf(Permission.class)));
}
}
\ No newline at end of file
diff --git a/master-worker-pattern/pom.xml b/master-worker-pattern/pom.xml
index 9924d6a5a..c6bc2facf 100644
--- a/master-worker-pattern/pom.xml
+++ b/master-worker-pattern/pom.xml
@@ -22,38 +22,39 @@
THE SOFTWARE.
-->
-
- 4.0.0
-
- com.iluwatar
- java-design-patterns
- 1.23.0-SNAPSHOT
-
- master-worker-pattern
-
-
- org.junit.jupiter
- junit-jupiter-engine
- test
-
+
+ 4.0.0
+
+ com.iluwatar
+ java-design-patterns
+ 1.24.0-SNAPSHOT
+
+ master-worker-pattern
+
+
+ org.junit.jupiter
+ junit-jupiter-engine
+ test
+
-
-
-
- org.apache.maven.plugins
- maven-assembly-plugin
-
-
-
-
-
- com.iluwatar.masterworker.App
-
-
-
-
-
-
-
-
+
+
+
+ org.apache.maven.plugins
+ maven-assembly-plugin
+
+
+
+
+
+ com.iluwatar.masterworker.App
+
+
+
+
+
+
+
+
diff --git a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/App.java b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/App.java
index 547636066..592ba8c59 100644
--- a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/App.java
+++ b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/App.java
@@ -34,27 +34,25 @@ import org.slf4j.LoggerFactory;
/**
* The Master-Worker pattern is used when the problem at hand can be solved by
- * dividing into
- * multiple parts which need to go through the same computation and may need to be aggregated to get
- * final result. Parallel processing is performed using a system consisting of a master and some
- * number of workers, where a master divides the work among the workers, gets the result back from
- * them and assimilates all the results to give final result. The only communication is between the
- * master and the worker - none of the workers communicate among one another and the user only
- * communicates with the master to get required job done.
+ * dividing into multiple parts which need to go through the same computation and may need to be
+ * aggregated to get final result. Parallel processing is performed using a system consisting of a
+ * master and some number of workers, where a master divides the work among the workers, gets the
+ * result back from them and assimilates all the results to give final result. The only
+ * communication is between the master and the worker - none of the workers communicate among one
+ * another and the user only communicates with the master to get required job done.
* In our example, we have generic abstract classes {@link MasterWorker}, {@link Master} and
- * {@link Worker} which
- * have to be extended by the classes which will perform the specific job at hand (in this case
- * finding transpose of matrix, done by {@link ArrayTransposeMasterWorker}, {@link
- * ArrayTransposeMaster} and {@link ArrayTransposeWorker}). The Master class divides the work into
- * parts to be given to the workers, collects the results from the workers and aggregates it when
- * all workers have responded before returning the solution. The Worker class extends the Thread
- * class to enable parallel processing, and does the work once the data has been received from the
- * Master. The MasterWorker contains a reference to the Master class, gets the input from the App
- * and passes it on to the Master. These 3 classes define the system which computes the result. We
- * also have 2 abstract classes {@link Input} and {@link Result}, which contain the input data and
- * result data respectively. The Input class also has an abstract method divideData which defines
- * how the data is to be divided into segments. These classes are extended by {@link ArrayInput} and
- * {@link ArrayResult}.
+ * {@link Worker} which have to be extended by the classes which will perform the specific job at
+ * hand (in this case finding transpose of matrix, done by {@link ArrayTransposeMasterWorker},
+ * {@link ArrayTransposeMaster} and {@link ArrayTransposeWorker}). The Master class divides the work
+ * into parts to be given to the workers, collects the results from the workers and aggregates it
+ * when all workers have responded before returning the solution. The Worker class extends the
+ * Thread class to enable parallel processing, and does the work once the data has been received
+ * from the Master. The MasterWorker contains a reference to the Master class, gets the input from
+ * the App and passes it on to the Master. These 3 classes define the system which computes the
+ * result. We also have 2 abstract classes {@link Input} and {@link Result}, which contain the input
+ * data and result data respectively. The Input class also has an abstract method divideData which
+ * defines how the data is to be divided into segments. These classes are extended by {@link
+ * ArrayInput} and {@link ArrayResult}.
*/
public class App {
@@ -68,12 +66,12 @@ public class App {
*/
public static void main(String[] args) {
- ArrayTransposeMasterWorker mw = new ArrayTransposeMasterWorker();
- int rows = 10;
- int columns = 20;
- int[][] inputMatrix = ArrayUtilityMethods.createRandomIntMatrix(rows, columns);
- ArrayInput input = new ArrayInput(inputMatrix);
- ArrayResult result = (ArrayResult) mw.getResult(input);
+ var mw = new ArrayTransposeMasterWorker();
+ var rows = 10;
+ var columns = 20;
+ var inputMatrix = ArrayUtilityMethods.createRandomIntMatrix(rows, columns);
+ var input = new ArrayInput(inputMatrix);
+ var result = (ArrayResult) mw.getResult(input);
if (result != null) {
ArrayUtilityMethods.printMatrix(inputMatrix);
ArrayUtilityMethods.printMatrix(result.data);
diff --git a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/ArrayInput.java b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/ArrayInput.java
index cd03a0a21..c8e68f958 100644
--- a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/ArrayInput.java
+++ b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/ArrayInput.java
@@ -25,6 +25,7 @@ package com.iluwatar.masterworker;
import java.util.ArrayList;
import java.util.Arrays;
+import java.util.List;
/**
* Class ArrayInput extends abstract class {@link Input} and contains data of type int[][].
@@ -37,12 +38,12 @@ public class ArrayInput extends Input {
}
static int[] makeDivisions(int[][] data, int num) {
- int initialDivision = data.length / num; //equally dividing
- int[] divisions = new int[num];
+ var initialDivision = data.length / num; //equally dividing
+ var divisions = new int[num];
Arrays.fill(divisions, initialDivision);
if (initialDivision * num != data.length) {
- int extra = data.length - initialDivision * num;
- int l = 0;
+ var extra = data.length - initialDivision * num;
+ var l = 0;
//equally dividing extra among all parts
while (extra > 0) {
divisions[l] = divisions[l] + 1;
@@ -58,22 +59,20 @@ public class ArrayInput extends Input {
}
@Override
- public ArrayList divideData(int num) {
+ public List > divideData(int num) {
if (this.data == null) {
return null;
} else {
- int[] divisions = makeDivisions(this.data, num);
- ArrayList result = new ArrayList (num);
- int rowsDone = 0; //number of rows divided so far
- for (int i = 0; i < num; i++) {
- int rows = divisions[i];
+ var divisions = makeDivisions(this.data, num);
+ var result = new ArrayList >(num);
+ var rowsDone = 0; //number of rows divided so far
+ for (var i = 0; i < num; i++) {
+ var rows = divisions[i];
if (rows != 0) {
- int[][] divided = new int[rows][this.data[0].length];
- for (int j = 0; j < rows; j++) {
- divided[j] = this.data[rowsDone + j];
- }
+ var divided = new int[rows][this.data[0].length];
+ System.arraycopy(this.data, rowsDone, divided, 0, rows);
rowsDone += rows;
- ArrayInput dividedInput = new ArrayInput(divided);
+ var dividedInput = new ArrayInput(divided);
result.add(dividedInput);
} else {
break; //rest of divisions will also be 0
diff --git a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/ArrayUtilityMethods.java b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/ArrayUtilityMethods.java
index 525bed003..5e695e5da 100644
--- a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/ArrayUtilityMethods.java
+++ b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/ArrayUtilityMethods.java
@@ -47,8 +47,8 @@ public class ArrayUtilityMethods {
if (a1.length != a2.length) {
return false;
} else {
- boolean answer = false;
- for (int i = 0; i < a1.length; i++) {
+ var answer = false;
+ for (var i = 0; i < a1.length; i++) {
if (a1[i] == a2[i]) {
answer = true;
} else {
@@ -69,8 +69,8 @@ public class ArrayUtilityMethods {
if (m1.length != m2.length) {
return false;
} else {
- boolean answer = false;
- for (int i = 0; i < m1.length; i++) {
+ var answer = false;
+ for (var i = 0; i < m1.length; i++) {
if (arraysSame(m1[i], m2[i])) {
answer = true;
} else {
@@ -88,9 +88,9 @@ public class ArrayUtilityMethods {
* @return it (int[][]).
*/
public static int[][] createRandomIntMatrix(int rows, int columns) {
- int[][] matrix = new int[rows][columns];
- for (int i = 0; i < rows; i++) {
- for (int j = 0; j < columns; j++) {
+ var matrix = new int[rows][columns];
+ for (var i = 0; i < rows; i++) {
+ for (var j = 0; j < columns; j++) {
//filling cells in matrix
matrix[i][j] = RANDOM.nextInt(10);
}
@@ -104,9 +104,9 @@ public class ArrayUtilityMethods {
public static void printMatrix(int[][] matrix) {
//prints out int[][]
- for (int i = 0; i < matrix.length; i++) {
- for (int j = 0; j < matrix[0].length; j++) {
- LOGGER.info(matrix[i][j] + " ");
+ for (var ints : matrix) {
+ for (var j = 0; j < matrix[0].length; j++) {
+ LOGGER.info(ints[j] + " ");
}
LOGGER.info("");
}
diff --git a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/Input.java b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/Input.java
index 6a957ae80..8d832f6c7 100644
--- a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/Input.java
+++ b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/Input.java
@@ -23,7 +23,7 @@
package com.iluwatar.masterworker;
-import java.util.ArrayList;
+import java.util.List;
/**
* The abstract Input class, having 1 public field which contains input data, and abstract method
@@ -40,5 +40,5 @@ public abstract class Input {
this.data = data;
}
- public abstract ArrayList divideData(int num);
+ public abstract List > divideData(int num);
}
diff --git a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/MasterWorker.java b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/MasterWorker.java
index 2b16cbf76..817fd65d3 100644
--- a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/MasterWorker.java
+++ b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/MasterWorker.java
@@ -40,7 +40,7 @@ public abstract class MasterWorker {
abstract Master setMaster(int numOfWorkers);
- public Result getResult(Input input) {
+ public Result> getResult(Input> input) {
this.master.doWork(input);
return this.master.getFinalResult();
}
diff --git a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/systemmaster/ArrayTransposeMaster.java b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/systemmaster/ArrayTransposeMaster.java
index ffa64572c..9bfbf200e 100644
--- a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/systemmaster/ArrayTransposeMaster.java
+++ b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/systemmaster/ArrayTransposeMaster.java
@@ -27,7 +27,8 @@ import com.iluwatar.masterworker.ArrayResult;
import com.iluwatar.masterworker.system.systemworkers.ArrayTransposeWorker;
import com.iluwatar.masterworker.system.systemworkers.Worker;
import java.util.ArrayList;
-import java.util.Enumeration;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
/**
* Class ArrayTransposeMaster extends abstract class {@link Master} and contains definition of
@@ -41,35 +42,33 @@ public class ArrayTransposeMaster extends Master {
@Override
ArrayList setWorkers(int num) {
- ArrayList ws = new ArrayList(num);
- for (int i = 0; i < num; i++) {
- ws.add(new ArrayTransposeWorker(this, i + 1));
- //i+1 will be id
- }
- return ws;
+ //i+1 will be id
+ return IntStream.range(0, num)
+ .mapToObj(i -> new ArrayTransposeWorker(this, i + 1))
+ .collect(Collectors.toCollection(() -> new ArrayList<>(num)));
}
@Override
ArrayResult aggregateData() {
// number of rows in final result is number of rows in any of obtained results from workers
- int rows = ((ArrayResult) this.getAllResultData()
- .get(this.getAllResultData().keys().nextElement())).data.length;
- int columns =
- 0; //number of columns is sum of number of columns in all results obtained from workers
- for (Enumeration e = this.getAllResultData().keys(); e.hasMoreElements(); ) {
- columns += ((ArrayResult) this.getAllResultData().get(e.nextElement())).data[0].length;
+ var allResultData = this.getAllResultData();
+ var rows = ((ArrayResult) allResultData.elements().nextElement()).data.length;
+ var elements = allResultData.elements();
+ var columns = 0; // columns = sum of number of columns in all results obtained from workers
+ while (elements.hasMoreElements()) {
+ columns += ((ArrayResult) elements.nextElement()).data[0].length;
}
- int[][] resultData = new int[rows][columns];
- int columnsDone = 0; //columns aggregated so far
- for (int i = 0; i < this.getExpectedNumResults(); i++) {
+ var resultData = new int[rows][columns];
+ var columnsDone = 0; //columns aggregated so far
+ var workers = this.getWorkers();
+ for (var i = 0; i < this.getExpectedNumResults(); i++) {
//result obtained from ith worker
- int[][] work =
- ((ArrayResult) this.getAllResultData().get(this.getWorkers().get(i).getWorkerId())).data;
- for (int m = 0; m < work.length; m++) {
+ var worker = workers.get(i);
+ var workerId = worker.getWorkerId();
+ var work = ((ArrayResult) allResultData.get(workerId)).data;
+ for (var m = 0; m < work.length; m++) {
//m = row number, n = columns number
- for (int n = 0; n < work[0].length; n++) {
- resultData[m][columnsDone + n] = work[m][n];
- }
+ System.arraycopy(work[m], 0, resultData[m], columnsDone, work[0].length);
}
columnsDone += work[0].length;
}
diff --git a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/systemmaster/Master.java b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/systemmaster/Master.java
index 2466df256..06ea3a8fe 100644
--- a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/systemmaster/Master.java
+++ b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/systemmaster/Master.java
@@ -26,8 +26,8 @@ package com.iluwatar.masterworker.system.systemmaster;
import com.iluwatar.masterworker.Input;
import com.iluwatar.masterworker.Result;
import com.iluwatar.masterworker.system.systemworkers.Worker;
-import java.util.ArrayList;
import java.util.Hashtable;
+import java.util.List;
/**
* The abstract Master class which contains private fields numOfWorkers (number of workers), workers
@@ -38,24 +38,24 @@ import java.util.Hashtable;
public abstract class Master {
private final int numOfWorkers;
- private final ArrayList workers;
+ private final List workers;
+ private final Hashtable> allResultData;
private int expectedNumResults;
- private Hashtable allResultData;
- private Result finalResult;
+ private Result> finalResult;
Master(int numOfWorkers) {
this.numOfWorkers = numOfWorkers;
this.workers = setWorkers(numOfWorkers);
this.expectedNumResults = 0;
- this.allResultData = new Hashtable(numOfWorkers);
+ this.allResultData = new Hashtable<>(numOfWorkers);
this.finalResult = null;
}
- public Result getFinalResult() {
+ public Result> getFinalResult() {
return this.finalResult;
}
- Hashtable getAllResultData() {
+ Hashtable> getAllResultData() {
return this.allResultData;
}
@@ -63,34 +63,41 @@ public abstract class Master {
return this.expectedNumResults;
}
- ArrayList getWorkers() {
+ List getWorkers() {
return this.workers;
}
- abstract ArrayList setWorkers(int num);
+ abstract List setWorkers(int num);
- public void doWork(Input input) {
+ public void doWork(Input> input) {
divideWork(input);
}
- private void divideWork(Input input) {
- ArrayList dividedInput = input.divideData(numOfWorkers);
+ private void divideWork(Input> input) {
+ var dividedInput = input.divideData(numOfWorkers);
if (dividedInput != null) {
this.expectedNumResults = dividedInput.size();
- for (int i = 0; i < this.expectedNumResults; i++) {
+ for (var i = 0; i < this.expectedNumResults; i++) {
//ith division given to ith worker in this.workers
this.workers.get(i).setReceivedData(this, dividedInput.get(i));
- this.workers.get(i).run();
+ this.workers.get(i).start();
+ }
+ for (var i = 0; i < this.expectedNumResults; i++) {
+ try {
+ this.workers.get(i).join();
+ } catch (InterruptedException e) {
+ System.err.println("Error while executing thread");
+ }
}
}
}
- public void receiveData(Result data, Worker w) {
+ public void receiveData(Result> data, Worker w) {
//check if can receive..if yes:
collectResult(data, w.getWorkerId());
}
- private void collectResult(Result data, int workerId) {
+ private void collectResult(Result> data, int workerId) {
this.allResultData.put(workerId, data);
if (this.allResultData.size() == this.expectedNumResults) {
//all data received
@@ -98,5 +105,5 @@ public abstract class Master {
}
}
- abstract Result aggregateData();
+ abstract Result> aggregateData();
}
diff --git a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/systemworkers/ArrayTransposeWorker.java b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/systemworkers/ArrayTransposeWorker.java
index 37d8ba005..3f2da0a0a 100644
--- a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/systemworkers/ArrayTransposeWorker.java
+++ b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/systemworkers/ArrayTransposeWorker.java
@@ -41,12 +41,12 @@ public class ArrayTransposeWorker extends Worker {
@Override
ArrayResult executeOperation() {
//number of rows in result matrix is equal to number of columns in input matrix and vice versa
- ArrayInput arrayInput = (ArrayInput) this.getReceivedData();
- final int rows = arrayInput.data[0].length;
- final int cols = arrayInput.data.length;
- int[][] resultData = new int[rows][cols];
- for (int i = 0; i < cols; i++) {
- for (int j = 0; j < rows; j++) {
+ var arrayInput = (ArrayInput) this.getReceivedData();
+ final var rows = arrayInput.data[0].length;
+ final var cols = arrayInput.data.length;
+ var resultData = new int[rows][cols];
+ for (var i = 0; i < cols; i++) {
+ for (var j = 0; j < rows; j++) {
//flipping element positions along diagonal
resultData[j][i] = arrayInput.data[i][j];
}
diff --git a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/systemworkers/Worker.java b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/systemworkers/Worker.java
index bfe226ee0..526299645 100644
--- a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/systemworkers/Worker.java
+++ b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/systemworkers/Worker.java
@@ -35,7 +35,7 @@ import com.iluwatar.masterworker.system.systemmaster.Master;
public abstract class Worker extends Thread {
private final Master master;
private final int workerId;
- private Input receivedData;
+ private Input> receivedData;
Worker(Master master, int id) {
this.master = master;
@@ -47,23 +47,23 @@ public abstract class Worker extends Thread {
return this.workerId;
}
- Input getReceivedData() {
+ Input> getReceivedData() {
return this.receivedData;
}
- public void setReceivedData(Master m, Input i) {
+ public void setReceivedData(Master m, Input> i) {
//check if ready to receive..if yes:
this.receivedData = i;
}
- abstract Result executeOperation();
+ abstract Result> executeOperation();
- private void sendToMaster(Result data) {
+ private void sendToMaster(Result> data) {
this.master.receiveData(data, this);
}
public void run() { //from Thread class
- Result work = executeOperation();
+ var work = executeOperation();
sendToMaster(work);
}
}
diff --git a/master-worker-pattern/src/test/java/com/iluwatar/masterworker/ArrayInputTest.java b/master-worker-pattern/src/test/java/com/iluwatar/masterworker/ArrayInputTest.java
index b5820e2af..1d3c7f0bc 100644
--- a/master-worker-pattern/src/test/java/com/iluwatar/masterworker/ArrayInputTest.java
+++ b/master-worker-pattern/src/test/java/com/iluwatar/masterworker/ArrayInputTest.java
@@ -23,38 +23,39 @@
package com.iluwatar.masterworker;
-import static org.junit.jupiter.api.Assertions.*;
-import java.util.ArrayList;
+import static com.iluwatar.masterworker.ArrayUtilityMethods.matricesSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
import java.util.Random;
import org.junit.jupiter.api.Test;
/**
-* Testing divideData method in {@link ArrayInput} class.
-*/
+ * Testing divideData method in {@link ArrayInput} class.
+ */
class ArrayInputTest {
@Test
void divideDataTest() {
- int rows = 10;
- int columns = 10;
- int[][] inputMatrix = new int[rows][columns];
- Random rand = new Random();
- for (int i = 0; i < rows; i++) {
- for (int j = 0; j < columns; j++) {
+ var rows = 10;
+ var columns = 10;
+ var inputMatrix = new int[rows][columns];
+ var rand = new Random();
+ for (var i = 0; i < rows; i++) {
+ for (var j = 0; j < columns; j++) {
inputMatrix[i][j] = rand.nextInt(10);
}
}
- ArrayInput i = new ArrayInput(inputMatrix);
- ArrayList table = i.divideData(4);
- int[][] division1 = new int[][] {inputMatrix[0], inputMatrix[1], inputMatrix[2]};
- int[][] division2 = new int[][] {inputMatrix[3], inputMatrix[4], inputMatrix[5]};
- int[][] division3 = new int[][] {inputMatrix[6], inputMatrix[7]};
- int[][] division4 = new int[][] {inputMatrix[8], inputMatrix[9]};
- assertTrue(ArrayUtilityMethods.matricesSame((int[][]) table.get(0).data, division1)
- && ArrayUtilityMethods.matricesSame((int[][]) table.get(1).data, division2)
- && ArrayUtilityMethods.matricesSame((int[][]) table.get(2).data, division3)
- && ArrayUtilityMethods.matricesSame((int[][]) table.get(3).data, division4));
+ var i = new ArrayInput(inputMatrix);
+ var table = i.divideData(4);
+ var division1 = new int[][]{inputMatrix[0], inputMatrix[1], inputMatrix[2]};
+ var division2 = new int[][]{inputMatrix[3], inputMatrix[4], inputMatrix[5]};
+ var division3 = new int[][]{inputMatrix[6], inputMatrix[7]};
+ var division4 = new int[][]{inputMatrix[8], inputMatrix[9]};
+ assertTrue(matricesSame(table.get(0).data, division1)
+ && matricesSame(table.get(1).data, division2)
+ && matricesSame(table.get(2).data, division3)
+ && matricesSame(table.get(3).data, division4));
}
}
diff --git a/master-worker-pattern/src/test/java/com/iluwatar/masterworker/ArrayUtilityMethodsTest.java b/master-worker-pattern/src/test/java/com/iluwatar/masterworker/ArrayUtilityMethodsTest.java
index aae784b52..d25276572 100644
--- a/master-worker-pattern/src/test/java/com/iluwatar/masterworker/ArrayUtilityMethodsTest.java
+++ b/master-worker-pattern/src/test/java/com/iluwatar/masterworker/ArrayUtilityMethodsTest.java
@@ -23,27 +23,27 @@
package com.iluwatar.masterworker;
-import static org.junit.jupiter.api.Assertions.*;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
/**
-* Testing utility methods in {@link ArrayUtilityMethods} class.
-*/
+ * Testing utility methods in {@link ArrayUtilityMethods} class.
+ */
class ArrayUtilityMethodsTest {
@Test
void arraysSameTest() {
- int[] arr1 = new int[] {1,4,2,6};
- int[] arr2 = new int[] {1,4,2,6};
+ var arr1 = new int[]{1, 4, 2, 6};
+ var arr2 = new int[]{1, 4, 2, 6};
assertTrue(ArrayUtilityMethods.arraysSame(arr1, arr2));
}
@Test
void matricesSameTest() {
- int[][] matrix1 = new int[][] {{1,4,2,6},{5,8,6,7}};
- int[][] matrix2 = new int[][] {{1,4,2,6},{5,8,6,7}};
+ var matrix1 = new int[][]{{1, 4, 2, 6}, {5, 8, 6, 7}};
+ var matrix2 = new int[][]{{1, 4, 2, 6}, {5, 8, 6, 7}};
assertTrue(ArrayUtilityMethods.matricesSame(matrix1, matrix2));
}
diff --git a/master-worker-pattern/src/test/java/com/iluwatar/masterworker/system/ArrayTransposeMasterWorkerTest.java b/master-worker-pattern/src/test/java/com/iluwatar/masterworker/system/ArrayTransposeMasterWorkerTest.java
index b80d7881f..79838ed35 100644
--- a/master-worker-pattern/src/test/java/com/iluwatar/masterworker/system/ArrayTransposeMasterWorkerTest.java
+++ b/master-worker-pattern/src/test/java/com/iluwatar/masterworker/system/ArrayTransposeMasterWorkerTest.java
@@ -23,25 +23,38 @@
package com.iluwatar.masterworker.system;
-import static org.junit.jupiter.api.Assertions.*;
-import org.junit.jupiter.api.Test;
-import com.iluwatar.masterworker.ArrayUtilityMethods;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
import com.iluwatar.masterworker.ArrayInput;
import com.iluwatar.masterworker.ArrayResult;
+import com.iluwatar.masterworker.ArrayUtilityMethods;
+import org.junit.jupiter.api.Test;
/**
-* Testing getResult method in {@link ArrayTransposeMasterWorker} class.
-*/
+ * Testing getResult method in {@link ArrayTransposeMasterWorker} class.
+ */
class ArrayTransposeMasterWorkerTest {
@Test
void getResultTest() {
- ArrayTransposeMasterWorker atmw = new ArrayTransposeMasterWorker();
- int[][] matrix = new int[][] {{1,2,3,4,5}, {1,2,3,4,5}, {1,2,3,4,5}, {1,2,3,4,5}, {1,2,3,4,5}};
- int[][] matrixTranspose = new int[][] {{1,1,1,1,1}, {2,2,2,2,2}, {3,3,3,3,3}, {4,4,4,4,4}, {5,5,5,5,5}};
- ArrayInput i = new ArrayInput(matrix);
- ArrayResult r = (ArrayResult) atmw.getResult(i);
+ var atmw = new ArrayTransposeMasterWorker();
+ var matrix = new int[][]{
+ {1, 2, 3, 4, 5},
+ {1, 2, 3, 4, 5},
+ {1, 2, 3, 4, 5},
+ {1, 2, 3, 4, 5},
+ {1, 2, 3, 4, 5}
+ };
+ var matrixTranspose = new int[][]{
+ {1, 1, 1, 1, 1},
+ {2, 2, 2, 2, 2},
+ {3, 3, 3, 3, 3},
+ {4, 4, 4, 4, 4},
+ {5, 5, 5, 5, 5}
+ };
+ var i = new ArrayInput(matrix);
+ var r = (ArrayResult) atmw.getResult(i);
assertTrue(ArrayUtilityMethods.matricesSame(r.data, matrixTranspose));
- }
+ }
}
diff --git a/master-worker-pattern/src/test/java/com/iluwatar/masterworker/system/systemworkers/ArrayTransposeWorkerTest.java b/master-worker-pattern/src/test/java/com/iluwatar/masterworker/system/systemworkers/ArrayTransposeWorkerTest.java
index 3e5f581b9..c4b210643 100644
--- a/master-worker-pattern/src/test/java/com/iluwatar/masterworker/system/systemworkers/ArrayTransposeWorkerTest.java
+++ b/master-worker-pattern/src/test/java/com/iluwatar/masterworker/system/systemworkers/ArrayTransposeWorkerTest.java
@@ -23,29 +23,29 @@
package com.iluwatar.masterworker.system.systemworkers;
-import static org.junit.jupiter.api.Assertions.*;
-import org.junit.jupiter.api.Test;
-import com.iluwatar.masterworker.ArrayUtilityMethods;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
import com.iluwatar.masterworker.ArrayInput;
-import com.iluwatar.masterworker.ArrayResult;
+import com.iluwatar.masterworker.ArrayUtilityMethods;
import com.iluwatar.masterworker.system.systemmaster.ArrayTransposeMaster;
+import org.junit.jupiter.api.Test;
/**
-* Testing executeOperation method in {@link ArrayTransposeWorker} class.
-*/
+ * Testing executeOperation method in {@link ArrayTransposeWorker} class.
+ */
class ArrayTransposeWorkerTest {
@Test
void executeOperationTest() {
- ArrayTransposeMaster atm = new ArrayTransposeMaster(1);
- ArrayTransposeWorker atw = new ArrayTransposeWorker(atm, 1);
- int[][] matrix = new int[][] {{2,4}, {3,5}};
- int[][] matrixTranspose = new int[][] {{2,3}, {4,5}};
- ArrayInput i = new ArrayInput(matrix);
+ var atm = new ArrayTransposeMaster(1);
+ var atw = new ArrayTransposeWorker(atm, 1);
+ var matrix = new int[][]{{2, 4}, {3, 5}};
+ var matrixTranspose = new int[][]{{2, 3}, {4, 5}};
+ var i = new ArrayInput(matrix);
atw.setReceivedData(atm, i);
- ArrayResult r = atw.executeOperation();
+ var r = atw.executeOperation();
assertTrue(ArrayUtilityMethods.matricesSame(r.data, matrixTranspose));
}
-
+
}
diff --git a/mediator/pom.xml b/mediator/pom.xml
index 23d28726b..ae802a349 100644
--- a/mediator/pom.xml
+++ b/mediator/pom.xml
@@ -29,7 +29,7 @@
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
mediator
diff --git a/mediator/src/main/java/com/iluwatar/mediator/Action.java b/mediator/src/main/java/com/iluwatar/mediator/Action.java
index 66e1f42c4..60ce3949a 100644
--- a/mediator/src/main/java/com/iluwatar/mediator/Action.java
+++ b/mediator/src/main/java/com/iluwatar/mediator/Action.java
@@ -1,52 +1,51 @@
-/*
- * The MIT License
- * Copyright © 2014-2019 Ilkka Seppälä
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-
-package com.iluwatar.mediator;
-
-/**
- * Action enumeration.
- */
-public enum Action {
-
- HUNT("hunted a rabbit", "arrives for dinner"),
- TALE("tells a tale", "comes to listen"),
- GOLD("found gold", "takes his share of the gold"),
- ENEMY("spotted enemies", "runs for cover"),
- NONE("", "");
-
- private String title;
- private String description;
-
- Action(String title, String description) {
- this.title = title;
- this.description = description;
- }
-
- public String getDescription() {
- return description;
- }
-
- public String toString() {
- return title;
- }
-}
+/*
+ * The MIT License
+ * Copyright © 2014-2019 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+package com.iluwatar.mediator;
+
+/**
+ * Action enumeration.
+ */
+public enum Action {
+ HUNT("hunted a rabbit", "arrives for dinner"),
+ TALE("tells a tale", "comes to listen"),
+ GOLD("found gold", "takes his share of the gold"),
+ ENEMY("spotted enemies", "runs for cover"),
+ NONE("", "");
+
+ private final String title;
+ private final String description;
+
+ Action(String title, String description) {
+ this.title = title;
+ this.description = description;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public String toString() {
+ return title;
+ }
+}
diff --git a/mediator/src/main/java/com/iluwatar/mediator/App.java b/mediator/src/main/java/com/iluwatar/mediator/App.java
index 9dbedb4ab..0e9021c0d 100644
--- a/mediator/src/main/java/com/iluwatar/mediator/App.java
+++ b/mediator/src/main/java/com/iluwatar/mediator/App.java
@@ -55,10 +55,10 @@ public class App {
// create party and members
Party party = new PartyImpl();
- Hobbit hobbit = new Hobbit();
- Wizard wizard = new Wizard();
- Rogue rogue = new Rogue();
- Hunter hunter = new Hunter();
+ var hobbit = new Hobbit();
+ var wizard = new Wizard();
+ var rogue = new Rogue();
+ var hunter = new Hunter();
// add party members
party.addMember(hobbit);
diff --git a/mediator/src/main/java/com/iluwatar/mediator/PartyImpl.java b/mediator/src/main/java/com/iluwatar/mediator/PartyImpl.java
index 6384a2187..f842a0f39 100644
--- a/mediator/src/main/java/com/iluwatar/mediator/PartyImpl.java
+++ b/mediator/src/main/java/com/iluwatar/mediator/PartyImpl.java
@@ -39,7 +39,7 @@ public class PartyImpl implements Party {
@Override
public void act(PartyMember actor, Action action) {
- for (PartyMember member : members) {
+ for (var member : members) {
if (!member.equals(actor)) {
member.partyAction(action);
}
diff --git a/mediator/src/test/java/com/iluwatar/mediator/AppTest.java b/mediator/src/test/java/com/iluwatar/mediator/AppTest.java
index 3a55d51d8..558ec4907 100644
--- a/mediator/src/test/java/com/iluwatar/mediator/AppTest.java
+++ b/mediator/src/test/java/com/iluwatar/mediator/AppTest.java
@@ -25,16 +25,15 @@ package com.iluwatar.mediator;
import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+
/**
- *
* Application test
- *
*/
-public class AppTest {
+class AppTest {
@Test
- public void test() {
- String[] args = {};
- App.main(args);
+ void shouldExecuteApplicationWithoutException() {
+ assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
diff --git a/mediator/src/test/java/com/iluwatar/mediator/PartyImplTest.java b/mediator/src/test/java/com/iluwatar/mediator/PartyImplTest.java
index 5d2446545..d25562f84 100644
--- a/mediator/src/test/java/com/iluwatar/mediator/PartyImplTest.java
+++ b/mediator/src/test/java/com/iluwatar/mediator/PartyImplTest.java
@@ -43,10 +43,10 @@ public class PartyImplTest {
*/
@Test
public void testPartyAction() {
- final PartyMember partyMember1 = mock(PartyMember.class);
- final PartyMember partyMember2 = mock(PartyMember.class);
+ final var partyMember1 = mock(PartyMember.class);
+ final var partyMember2 = mock(PartyMember.class);
- final PartyImpl party = new PartyImpl();
+ final var party = new PartyImpl();
party.addMember(partyMember1);
party.addMember(partyMember2);
@@ -58,7 +58,6 @@ public class PartyImplTest {
verify(partyMember2).partyAction(Action.GOLD);
verifyNoMoreInteractions(partyMember1, partyMember2);
-
}
}
diff --git a/mediator/src/test/java/com/iluwatar/mediator/PartyMemberTest.java b/mediator/src/test/java/com/iluwatar/mediator/PartyMemberTest.java
index 951f8e166..a0e722cfd 100644
--- a/mediator/src/test/java/com/iluwatar/mediator/PartyMemberTest.java
+++ b/mediator/src/test/java/com/iluwatar/mediator/PartyMemberTest.java
@@ -23,24 +23,24 @@
package com.iluwatar.mediator;
-import ch.qos.logback.classic.Logger;
-import ch.qos.logback.classic.spi.ILoggingEvent;
-import ch.qos.logback.core.AppenderBase;
-import org.junit.jupiter.api.AfterEach;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.params.ParameterizedTest;
-import org.junit.jupiter.params.provider.MethodSource;
-import org.slf4j.LoggerFactory;
-
-import java.util.Collection;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.function.Supplier;
-
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
+import ch.qos.logback.classic.Logger;
+import ch.qos.logback.classic.spi.ILoggingEvent;
+import ch.qos.logback.core.AppenderBase;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.function.Supplier;
+import java.util.stream.Stream;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.LoggerFactory;
+
/**
* Date: 12/19/15 - 10:13 PM
*
@@ -48,12 +48,12 @@ import static org.mockito.Mockito.verify;
*/
public class PartyMemberTest {
- static Collection[]> dataProvider() {
- return List.of(
- new Supplier[]{Hobbit::new},
- new Supplier[]{Hunter::new},
- new Supplier[]{Rogue::new},
- new Supplier[]{Wizard::new}
+ static Stream dataProvider() {
+ return Stream.of(
+ Arguments.of((Supplier) Hobbit::new),
+ Arguments.of((Supplier) Hunter::new),
+ Arguments.of((Supplier) Rogue::new),
+ Arguments.of((Supplier) Wizard::new)
);
}
@@ -75,9 +75,9 @@ public class PartyMemberTest {
@ParameterizedTest
@MethodSource("dataProvider")
public void testPartyAction(Supplier memberSupplier) {
- final PartyMember member = memberSupplier.get();
+ final var member = memberSupplier.get();
- for (final Action action : Action.values()) {
+ for (final var action : Action.values()) {
member.partyAction(action);
assertEquals(member.toString() + " " + action.getDescription(), appender.getLastMessage());
}
@@ -91,16 +91,16 @@ public class PartyMemberTest {
@ParameterizedTest
@MethodSource("dataProvider")
public void testAct(Supplier memberSupplier) {
- final PartyMember member = memberSupplier.get();
+ final var member = memberSupplier.get();
member.act(Action.GOLD);
assertEquals(0, appender.getLogSize());
- final Party party = mock(Party.class);
+ final var party = mock(Party.class);
member.joinedParty(party);
assertEquals(member.toString() + " joins the party", appender.getLastMessage());
- for (final Action action : Action.values()) {
+ for (final var action : Action.values()) {
member.act(action);
assertEquals(member.toString() + " " + action.toString(), appender.getLastMessage());
verify(party).act(member, action);
@@ -114,16 +114,16 @@ public class PartyMemberTest {
*/
@ParameterizedTest
@MethodSource("dataProvider")
- public void testToString(Supplier memberSupplier) throws Exception {
- final PartyMember member = memberSupplier.get();
- final Class extends PartyMember> memberClass = member.getClass();
+ public void testToString(Supplier memberSupplier) {
+ final var member = memberSupplier.get();
+ final var memberClass = member.getClass();
assertEquals(memberClass.getSimpleName(), member.toString());
}
- private class InMemoryAppender extends AppenderBase {
- private List log = new LinkedList<>();
+ private static class InMemoryAppender extends AppenderBase {
+ private final List log = new LinkedList<>();
- public InMemoryAppender(Class clazz) {
+ public InMemoryAppender(Class> clazz) {
((Logger) LoggerFactory.getLogger(clazz)).addAppender(this);
start();
}
diff --git a/memento/README.md b/memento/README.md
index 8011dfc49..8bbebd36a 100644
--- a/memento/README.md
+++ b/memento/README.md
@@ -34,11 +34,14 @@ Let's first define the types of stars we are capable to handle.
```java
public enum StarType {
+ SUN("sun"),
+ RED_GIANT("red giant"),
+ WHITE_DWARF("white dwarf"),
+ SUPERNOVA("supernova"),
+ DEAD("dead star"),
+ UNDEFINED("");
- SUN("sun"), RED_GIANT("red giant"), WHITE_DWARF("white dwarf"), SUPERNOVA("supernova"), DEAD(
- "dead star"), UNDEFINED("");
-
- private String title;
+ private final String title;
StarType(String title) {
this.title = title;
@@ -95,8 +98,7 @@ public class Star {
}
StarMemento getMemento() {
-
- StarMementoInternal state = new StarMementoInternal();
+ var state = new StarMementoInternal();
state.setAgeYears(ageYears);
state.setMassTons(massTons);
state.setType(type);
@@ -104,8 +106,7 @@ public class Star {
}
void setMemento(StarMemento memento) {
-
- StarMementoInternal state = (StarMementoInternal) memento;
+ var state = (StarMementoInternal) memento;
this.type = state.getType();
this.ageYears = state.getAgeYears();
this.massTons = state.getMassTons();
@@ -152,8 +153,8 @@ public class Star {
And finally here's how we use the mementos to store and restore star states.
```java
- Stack states = new Stack<>();
- Star star = new Star(StarType.SUN, 10000000, 500000);
+ var states = new Stack<>();
+ var star = new Star(StarType.SUN, 10000000, 500000);
LOGGER.info(star.toString());
states.add(star.getMemento());
star.timePasses();
diff --git a/memento/pom.xml b/memento/pom.xml
index 70121cea3..596883819 100644
--- a/memento/pom.xml
+++ b/memento/pom.xml
@@ -29,7 +29,7 @@
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
memento
diff --git a/memento/src/main/java/com/iluwatar/memento/App.java b/memento/src/main/java/com/iluwatar/memento/App.java
index af57d8d4a..77cc0f214 100644
--- a/memento/src/main/java/com/iluwatar/memento/App.java
+++ b/memento/src/main/java/com/iluwatar/memento/App.java
@@ -52,9 +52,9 @@ public class App {
* Program entry point.
*/
public static void main(String[] args) {
- Stack states = new Stack<>();
+ var states = new Stack();
- Star star = new Star(StarType.SUN, 10000000, 500000);
+ var star = new Star(StarType.SUN, 10000000, 500000);
LOGGER.info(star.toString());
states.add(star.getMemento());
star.timePasses();
diff --git a/memento/src/main/java/com/iluwatar/memento/Star.java b/memento/src/main/java/com/iluwatar/memento/Star.java
index ebeea28f2..af1c98b04 100644
--- a/memento/src/main/java/com/iluwatar/memento/Star.java
+++ b/memento/src/main/java/com/iluwatar/memento/Star.java
@@ -70,22 +70,18 @@ public class Star {
}
StarMemento getMemento() {
-
- StarMementoInternal state = new StarMementoInternal();
+ var state = new StarMementoInternal();
state.setAgeYears(ageYears);
state.setMassTons(massTons);
state.setType(type);
return state;
-
}
void setMemento(StarMemento memento) {
-
- StarMementoInternal state = (StarMementoInternal) memento;
+ var state = (StarMementoInternal) memento;
this.type = state.getType();
this.ageYears = state.getAgeYears();
this.massTons = state.getMassTons();
-
}
@Override
diff --git a/memento/src/main/java/com/iluwatar/memento/StarType.java b/memento/src/main/java/com/iluwatar/memento/StarType.java
index 507cd506b..aa92bf6e6 100644
--- a/memento/src/main/java/com/iluwatar/memento/StarType.java
+++ b/memento/src/main/java/com/iluwatar/memento/StarType.java
@@ -27,11 +27,14 @@ package com.iluwatar.memento;
* StarType enumeration.
*/
public enum StarType {
+ SUN("sun"),
+ RED_GIANT("red giant"),
+ WHITE_DWARF("white dwarf"),
+ SUPERNOVA("supernova"),
+ DEAD("dead star"),
+ UNDEFINED("");
- SUN("sun"), RED_GIANT("red giant"), WHITE_DWARF("white dwarf"), SUPERNOVA("supernova"), DEAD(
- "dead star"), UNDEFINED("");
-
- private String title;
+ private final String title;
StarType(String title) {
this.title = title;
diff --git a/memento/src/test/java/com/iluwatar/memento/AppTest.java b/memento/src/test/java/com/iluwatar/memento/AppTest.java
index 074de2c41..2d8a518e2 100644
--- a/memento/src/test/java/com/iluwatar/memento/AppTest.java
+++ b/memento/src/test/java/com/iluwatar/memento/AppTest.java
@@ -25,16 +25,15 @@ package com.iluwatar.memento;
import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+
/**
- *
* Application test
- *
*/
-public class AppTest {
+class AppTest {
@Test
- public void test() {
- String[] args = {};
- App.main(args);
+ void shouldExecuteWithoutException() {
+ assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
diff --git a/memento/src/test/java/com/iluwatar/memento/StarTest.java b/memento/src/test/java/com/iluwatar/memento/StarTest.java
index 40adb99e1..aab59e9c3 100644
--- a/memento/src/test/java/com/iluwatar/memento/StarTest.java
+++ b/memento/src/test/java/com/iluwatar/memento/StarTest.java
@@ -23,10 +23,10 @@
package com.iluwatar.memento;
-import org.junit.jupiter.api.Test;
-
import static org.junit.jupiter.api.Assertions.assertEquals;
+import org.junit.jupiter.api.Test;
+
/**
* Date: 12/20/15 - 10:08 AM
*
@@ -39,7 +39,7 @@ public class StarTest {
*/
@Test
public void testTimePasses() {
- final Star star = new Star(StarType.SUN, 1, 2);
+ final var star = new Star(StarType.SUN, 1, 2);
assertEquals("sun age: 1 years mass: 2 tons", star.toString());
star.timePasses();
@@ -66,16 +66,16 @@ public class StarTest {
*/
@Test
public void testSetMemento() {
- final Star star = new Star(StarType.SUN, 1, 2);
- final StarMemento firstMemento = star.getMemento();
+ final var star = new Star(StarType.SUN, 1, 2);
+ final var firstMemento = star.getMemento();
assertEquals("sun age: 1 years mass: 2 tons", star.toString());
star.timePasses();
- final StarMemento secondMemento = star.getMemento();
+ final var secondMemento = star.getMemento();
assertEquals("red giant age: 2 years mass: 16 tons", star.toString());
star.timePasses();
- final StarMemento thirdMemento = star.getMemento();
+ final var thirdMemento = star.getMemento();
assertEquals("white dwarf age: 4 years mass: 128 tons", star.toString());
star.timePasses();
diff --git a/model-view-controller/pom.xml b/model-view-controller/pom.xml
index a8ef230e8..98c9dddfe 100644
--- a/model-view-controller/pom.xml
+++ b/model-view-controller/pom.xml
@@ -29,7 +29,7 @@
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
model-view-controller
diff --git a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/App.java b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/App.java
index 4607f009d..cabc4d96f 100644
--- a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/App.java
+++ b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/App.java
@@ -47,9 +47,9 @@ public class App {
*/
public static void main(String[] args) {
// create model, view and controller
- GiantModel giant = new GiantModel(Health.HEALTHY, Fatigue.ALERT, Nourishment.SATURATED);
- GiantView view = new GiantView();
- GiantController controller = new GiantController(giant, view);
+ var giant = new GiantModel(Health.HEALTHY, Fatigue.ALERT, Nourishment.SATURATED);
+ var view = new GiantView();
+ var controller = new GiantController(giant, view);
// initial display
controller.updateView();
// controller receives some interactions that affect the giant
diff --git a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Fatigue.java b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Fatigue.java
index b1663df1f..64bae6e51 100644
--- a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Fatigue.java
+++ b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Fatigue.java
@@ -27,10 +27,11 @@ package com.iluwatar.model.view.controller;
* Fatigue enumeration.
*/
public enum Fatigue {
+ ALERT("alert"),
+ TIRED("tired"),
+ SLEEPING("sleeping");
- ALERT("alert"), TIRED("tired"), SLEEPING("sleeping");
-
- private String title;
+ private final String title;
Fatigue(String title) {
this.title = title;
diff --git a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantController.java b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantController.java
index e66608117..f96113574 100644
--- a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantController.java
+++ b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantController.java
@@ -28,14 +28,15 @@ package com.iluwatar.model.view.controller;
*/
public class GiantController {
- private GiantModel giant;
- private GiantView view;
+ private final GiantModel giant;
+ private final GiantView view;
public GiantController(GiantModel giant, GiantView view) {
this.giant = giant;
this.view = view;
}
+ @SuppressWarnings("UnusedReturnValue")
public Health getHealth() {
return giant.getHealth();
}
@@ -44,6 +45,7 @@ public class GiantController {
this.giant.setHealth(health);
}
+ @SuppressWarnings("UnusedReturnValue")
public Fatigue getFatigue() {
return giant.getFatigue();
}
@@ -52,6 +54,7 @@ public class GiantController {
this.giant.setFatigue(fatigue);
}
+ @SuppressWarnings("UnusedReturnValue")
public Nourishment getNourishment() {
return giant.getNourishment();
}
diff --git a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Health.java b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Health.java
index 30b3b2b90..f15585cdd 100644
--- a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Health.java
+++ b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Health.java
@@ -27,10 +27,11 @@ package com.iluwatar.model.view.controller;
* Health enumeration.
*/
public enum Health {
+ HEALTHY("healthy"),
+ WOUNDED("wounded"),
+ DEAD("dead");
- HEALTHY("healthy"), WOUNDED("wounded"), DEAD("dead");
-
- private String title;
+ private final String title;
Health(String title) {
this.title = title;
diff --git a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Nourishment.java b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Nourishment.java
index 3ced564cc..ba00c38c5 100644
--- a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Nourishment.java
+++ b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Nourishment.java
@@ -27,10 +27,11 @@ package com.iluwatar.model.view.controller;
* Nourishment enumeration.
*/
public enum Nourishment {
+ SATURATED("saturated"),
+ HUNGRY("hungry"),
+ STARVING("starving");
- SATURATED("saturated"), HUNGRY("hungry"), STARVING("starving");
-
- private String title;
+ private final String title;
Nourishment(String title) {
this.title = title;
diff --git a/model-view-controller/src/test/java/com/iluwatar/model/view/controller/AppTest.java b/model-view-controller/src/test/java/com/iluwatar/model/view/controller/AppTest.java
index e6d2d9a0b..a0fdbf3ba 100644
--- a/model-view-controller/src/test/java/com/iluwatar/model/view/controller/AppTest.java
+++ b/model-view-controller/src/test/java/com/iluwatar/model/view/controller/AppTest.java
@@ -25,16 +25,15 @@ package com.iluwatar.model.view.controller;
import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+
/**
- *
* Application test
- *
*/
-public class AppTest {
+class AppTest {
@Test
- public void test() {
- String[] args = {};
- App.main(args);
+ void shouldExecuteApplicationWithoutException() {
+ assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
diff --git a/model-view-controller/src/test/java/com/iluwatar/model/view/controller/GiantControllerTest.java b/model-view-controller/src/test/java/com/iluwatar/model/view/controller/GiantControllerTest.java
index a2f42a80d..d106d0944 100644
--- a/model-view-controller/src/test/java/com/iluwatar/model/view/controller/GiantControllerTest.java
+++ b/model-view-controller/src/test/java/com/iluwatar/model/view/controller/GiantControllerTest.java
@@ -23,13 +23,13 @@
package com.iluwatar.model.view.controller;
-import org.junit.jupiter.api.Test;
-
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.verifyZeroInteractions;
+import org.junit.jupiter.api.Test;
+
/**
* Date: 12/20/15 - 2:19 PM
*
@@ -42,19 +42,20 @@ public class GiantControllerTest {
*/
@Test
public void testSetHealth() {
- final GiantModel model = mock(GiantModel.class);
- final GiantView view = mock(GiantView.class);
- final GiantController controller = new GiantController(model, view);
+ final var model = mock(GiantModel.class);
+ final var view = mock(GiantView.class);
+ final var controller = new GiantController(model, view);
verifyZeroInteractions(model, view);
- for (final Health health : Health.values()) {
+ for (final var health : Health.values()) {
controller.setHealth(health);
verify(model).setHealth(health);
verifyZeroInteractions(view);
}
controller.getHealth();
+ //noinspection ResultOfMethodCallIgnored
verify(model).getHealth();
verifyNoMoreInteractions(model, view);
@@ -65,19 +66,20 @@ public class GiantControllerTest {
*/
@Test
public void testSetFatigue() {
- final GiantModel model = mock(GiantModel.class);
- final GiantView view = mock(GiantView.class);
- final GiantController controller = new GiantController(model, view);
+ final var model = mock(GiantModel.class);
+ final var view = mock(GiantView.class);
+ final var controller = new GiantController(model, view);
verifyZeroInteractions(model, view);
- for (final Fatigue fatigue : Fatigue.values()) {
+ for (final var fatigue : Fatigue.values()) {
controller.setFatigue(fatigue);
verify(model).setFatigue(fatigue);
verifyZeroInteractions(view);
}
controller.getFatigue();
+ //noinspection ResultOfMethodCallIgnored
verify(model).getFatigue();
verifyNoMoreInteractions(model, view);
@@ -88,19 +90,20 @@ public class GiantControllerTest {
*/
@Test
public void testSetNourishment() {
- final GiantModel model = mock(GiantModel.class);
- final GiantView view = mock(GiantView.class);
- final GiantController controller = new GiantController(model, view);
+ final var model = mock(GiantModel.class);
+ final var view = mock(GiantView.class);
+ final var controller = new GiantController(model, view);
verifyZeroInteractions(model, view);
- for (final Nourishment nourishment : Nourishment.values()) {
+ for (final var nourishment : Nourishment.values()) {
controller.setNourishment(nourishment);
verify(model).setNourishment(nourishment);
verifyZeroInteractions(view);
}
controller.getNourishment();
+ //noinspection ResultOfMethodCallIgnored
verify(model).getNourishment();
verifyNoMoreInteractions(model, view);
@@ -108,9 +111,9 @@ public class GiantControllerTest {
@Test
public void testUpdateView() {
- final GiantModel model = mock(GiantModel.class);
- final GiantView view = mock(GiantView.class);
- final GiantController controller = new GiantController(model, view);
+ final var model = mock(GiantModel.class);
+ final var view = mock(GiantView.class);
+ final var controller = new GiantController(model, view);
verifyZeroInteractions(model, view);
diff --git a/model-view-controller/src/test/java/com/iluwatar/model/view/controller/GiantModelTest.java b/model-view-controller/src/test/java/com/iluwatar/model/view/controller/GiantModelTest.java
index a566010cd..677ab436e 100644
--- a/model-view-controller/src/test/java/com/iluwatar/model/view/controller/GiantModelTest.java
+++ b/model-view-controller/src/test/java/com/iluwatar/model/view/controller/GiantModelTest.java
@@ -23,10 +23,10 @@
package com.iluwatar.model.view.controller;
-import org.junit.jupiter.api.Test;
-
import static org.junit.jupiter.api.Assertions.assertEquals;
+import org.junit.jupiter.api.Test;
+
/**
* Date: 12/20/15 - 2:10 PM
*
@@ -39,12 +39,13 @@ public class GiantModelTest {
*/
@Test
public void testSetHealth() {
- final GiantModel model = new GiantModel(Health.HEALTHY, Fatigue.ALERT, Nourishment.SATURATED);
+ final var model = new GiantModel(Health.HEALTHY, Fatigue.ALERT, Nourishment.SATURATED);
assertEquals(Health.HEALTHY, model.getHealth());
- for (final Health health : Health.values()) {
+ var messageFormat = "The giant looks %s, alert and saturated.";
+ for (final var health : Health.values()) {
model.setHealth(health);
assertEquals(health, model.getHealth());
- assertEquals("The giant looks " + health.toString() + ", alert and saturated.", model.toString());
+ assertEquals(String.format(messageFormat, health), model.toString());
}
}
@@ -53,12 +54,13 @@ public class GiantModelTest {
*/
@Test
public void testSetFatigue() {
- final GiantModel model = new GiantModel(Health.HEALTHY, Fatigue.ALERT, Nourishment.SATURATED);
+ final var model = new GiantModel(Health.HEALTHY, Fatigue.ALERT, Nourishment.SATURATED);
assertEquals(Fatigue.ALERT, model.getFatigue());
- for (final Fatigue fatigue : Fatigue.values()) {
+ var messageFormat = "The giant looks healthy, %s and saturated.";
+ for (final var fatigue : Fatigue.values()) {
model.setFatigue(fatigue);
assertEquals(fatigue, model.getFatigue());
- assertEquals("The giant looks healthy, " + fatigue.toString() + " and saturated.", model.toString());
+ assertEquals(String.format(messageFormat, fatigue), model.toString());
}
}
@@ -67,12 +69,13 @@ public class GiantModelTest {
*/
@Test
public void testSetNourishment() {
- final GiantModel model = new GiantModel(Health.HEALTHY, Fatigue.ALERT, Nourishment.SATURATED);
+ final var model = new GiantModel(Health.HEALTHY, Fatigue.ALERT, Nourishment.SATURATED);
assertEquals(Nourishment.SATURATED, model.getNourishment());
- for (final Nourishment nourishment : Nourishment.values()) {
+ var messageFormat = "The giant looks healthy, alert and %s.";
+ for (final var nourishment : Nourishment.values()) {
model.setNourishment(nourishment);
assertEquals(nourishment, model.getNourishment());
- assertEquals("The giant looks healthy, alert and " + nourishment.toString() + ".", model.toString());
+ assertEquals(String.format(messageFormat, nourishment), model.toString());
}
}
diff --git a/model-view-controller/src/test/java/com/iluwatar/model/view/controller/GiantViewTest.java b/model-view-controller/src/test/java/com/iluwatar/model/view/controller/GiantViewTest.java
index a3e33f9dd..c6314c1dd 100644
--- a/model-view-controller/src/test/java/com/iluwatar/model/view/controller/GiantViewTest.java
+++ b/model-view-controller/src/test/java/com/iluwatar/model/view/controller/GiantViewTest.java
@@ -31,7 +31,6 @@ import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;
import java.util.LinkedList;
import java.util.List;
-
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -62,9 +61,9 @@ public class GiantViewTest {
*/
@Test
public void testDisplayGiant() {
- final GiantView view = new GiantView();
+ final var view = new GiantView();
- final GiantModel model = mock(GiantModel.class);
+ final var model = mock(GiantModel.class);
view.displayGiant(model);
assertEquals(model.toString(), appender.getLastMessage());
@@ -74,10 +73,10 @@ public class GiantViewTest {
/**
* Logging Appender Implementation
*/
- public class InMemoryAppender extends AppenderBase {
- private List log = new LinkedList<>();
+ public static class InMemoryAppender extends AppenderBase {
+ private final List log = new LinkedList<>();
- public InMemoryAppender(Class clazz) {
+ public InMemoryAppender(Class> clazz) {
((Logger) LoggerFactory.getLogger(clazz)).addAppender(this);
start();
}
diff --git a/model-view-presenter/pom.xml b/model-view-presenter/pom.xml
index 97b47f82c..ee309f292 100644
--- a/model-view-presenter/pom.xml
+++ b/model-view-presenter/pom.xml
@@ -29,7 +29,7 @@
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
model-view-presenter
model-view-presenter
diff --git a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/App.java b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/App.java
index 43984e847..ac3b83927 100644
--- a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/App.java
+++ b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/App.java
@@ -44,9 +44,9 @@ public class App {
* @param args command line args
*/
public static void main(String[] args) {
- FileLoader loader = new FileLoader();
- FileSelectorJFrame frame = new FileSelectorJFrame();
- FileSelectorPresenter presenter = new FileSelectorPresenter(frame);
+ var loader = new FileLoader();
+ var frame = new FileSelectorJFrame();
+ var presenter = new FileSelectorPresenter(frame);
presenter.setLoader(loader);
presenter.start();
}
diff --git a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileLoader.java b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileLoader.java
index 9c01b2044..7dd5dd215 100644
--- a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileLoader.java
+++ b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileLoader.java
@@ -27,6 +27,7 @@ import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.Serializable;
+import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -59,18 +60,11 @@ public class FileLoader implements Serializable {
* Loads the data of the file specified.
*/
public String loadData() {
- String dataFileName = this.fileName;
- try (BufferedReader br = new BufferedReader(new FileReader(new File(dataFileName)))) {
- StringBuilder sb = new StringBuilder();
- String line;
-
- while ((line = br.readLine()) != null) {
- sb.append(line).append('\n');
- }
-
+ var dataFileName = this.fileName;
+ try (var br = new BufferedReader(new FileReader(new File(dataFileName)))) {
+ var result = br.lines().collect(Collectors.joining("\n"));
this.loaded = true;
-
- return sb.toString();
+ return result;
} catch (Exception e) {
LOGGER.error("File {} does not exist", dataFileName);
}
diff --git a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorJFrame.java b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorJFrame.java
index 77523ccaa..f59bcdf6f 100644
--- a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorJFrame.java
+++ b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorJFrame.java
@@ -23,9 +23,13 @@
package com.iluwatar.model.view.presenter;
+import static javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
+import static javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
+
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
+
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
@@ -48,37 +52,22 @@ public class FileSelectorJFrame extends JFrame implements FileSelectorView, Acti
/**
* The "OK" button for loading the file.
*/
- private JButton ok;
+ private final JButton ok;
/**
* The cancel button.
*/
- private JButton cancel;
-
- /**
- * The information label.
- */
- private JLabel info;
-
- /**
- * The contents label.
- */
- private JLabel contents;
+ private final JButton cancel;
/**
* The text field for giving the name of the file that we want to open.
*/
- private JTextField input;
+ private final JTextField input;
/**
* A text area that will keep the contents of the file opened.
*/
- private JTextArea area;
-
- /**
- * The panel that will hold our widgets.
- */
- private JPanel panel;
+ private final JTextArea area;
/**
* The Presenter component that the frame will interact with.
@@ -95,14 +84,14 @@ public class FileSelectorJFrame extends JFrame implements FileSelectorView, Acti
*/
public FileSelectorJFrame() {
super("File Loader");
- this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
+ this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setLayout(null);
this.setBounds(100, 100, 500, 200);
/*
* Add the panel.
*/
- this.panel = new JPanel();
+ var panel = new JPanel();
panel.setLayout(null);
this.add(panel);
panel.setBounds(0, 0, 500, 200);
@@ -111,32 +100,32 @@ public class FileSelectorJFrame extends JFrame implements FileSelectorView, Acti
/*
* Add the info label.
*/
- this.info = new JLabel("File Name :");
- this.panel.add(info);
+ var info = new JLabel("File Name :");
+ panel.add(info);
info.setBounds(30, 10, 100, 30);
/*
* Add the contents label.
*/
- this.contents = new JLabel("File contents :");
- this.panel.add(contents);
- this.contents.setBounds(30, 100, 120, 30);
+ var contents = new JLabel("File contents :");
+ panel.add(contents);
+ contents.setBounds(30, 100, 120, 30);
/*
* Add the text field.
*/
this.input = new JTextField(100);
- this.panel.add(input);
+ panel.add(input);
this.input.setBounds(150, 15, 200, 20);
/*
* Add the text area.
*/
this.area = new JTextArea(100, 100);
- JScrollPane pane = new JScrollPane(area);
- pane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
- pane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
- this.panel.add(pane);
+ var pane = new JScrollPane(area);
+ pane.setHorizontalScrollBarPolicy(HORIZONTAL_SCROLLBAR_AS_NEEDED);
+ pane.setVerticalScrollBarPolicy(VERTICAL_SCROLLBAR_AS_NEEDED);
+ panel.add(pane);
this.area.setEditable(false);
pane.setBounds(150, 100, 250, 80);
@@ -144,7 +133,7 @@ public class FileSelectorJFrame extends JFrame implements FileSelectorView, Acti
* Add the OK button.
*/
this.ok = new JButton("OK");
- this.panel.add(ok);
+ panel.add(ok);
this.ok.setBounds(250, 50, 100, 25);
this.ok.addActionListener(this);
@@ -152,7 +141,7 @@ public class FileSelectorJFrame extends JFrame implements FileSelectorView, Acti
* Add the cancel button.
*/
this.cancel = new JButton("Cancel");
- this.panel.add(this.cancel);
+ panel.add(this.cancel);
this.cancel.setBounds(380, 50, 100, 25);
this.cancel.addActionListener(this);
diff --git a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorPresenter.java b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorPresenter.java
index 35e1c0076..5cd6580d9 100644
--- a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorPresenter.java
+++ b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorPresenter.java
@@ -41,7 +41,7 @@ public class FileSelectorPresenter implements Serializable {
/**
* The View component that the presenter interacts with.
*/
- private FileSelectorView view;
+ private final FileSelectorView view;
/**
* The Model component that the presenter interacts with.
@@ -91,7 +91,7 @@ public class FileSelectorPresenter implements Serializable {
}
if (loader.fileExists()) {
- String data = loader.loadData();
+ var data = loader.loadData();
view.displayData(data);
} else {
view.showMessage("The file specified does not exist.");
diff --git a/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/AppTest.java b/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/AppTest.java
index 00e35ae1b..6529cd18d 100644
--- a/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/AppTest.java
+++ b/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/AppTest.java
@@ -25,17 +25,16 @@ package com.iluwatar.model.view.presenter;
import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+
/**
- *
* Application test
- *
*/
-public class AppTest {
+class AppTest {
@Test
- public void test() {
- String[] args = {};
- App.main(args);
+ void shouldExecuteApplicationWithoutException() {
+ assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
diff --git a/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/FileLoaderTest.java b/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/FileLoaderTest.java
index a63ca5ae8..3787cd20b 100644
--- a/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/FileLoaderTest.java
+++ b/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/FileLoaderTest.java
@@ -23,10 +23,10 @@
package com.iluwatar.model.view.presenter;
-import org.junit.jupiter.api.Test;
-
import static org.junit.jupiter.api.Assertions.assertNull;
+import org.junit.jupiter.api.Test;
+
/**
* Date: 12/21/15 - 12:12 PM
*
@@ -35,8 +35,8 @@ import static org.junit.jupiter.api.Assertions.assertNull;
public class FileLoaderTest {
@Test
- public void testLoadData() throws Exception {
- final FileLoader fileLoader = new FileLoader();
+ public void testLoadData() {
+ final var fileLoader = new FileLoader();
fileLoader.setFileName("non-existing-file");
assertNull(fileLoader.loadData());
}
diff --git a/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/FileSelectorPresenterTest.java b/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/FileSelectorPresenterTest.java
index fdc19398d..238d3a135 100644
--- a/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/FileSelectorPresenterTest.java
+++ b/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/FileSelectorPresenterTest.java
@@ -23,14 +23,14 @@
package com.iluwatar.model.view.presenter;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
/**
* This test case is responsible for testing our application by taking advantage of the
* Model-View-Controller architectural pattern.
@@ -79,7 +79,7 @@ public class FileSelectorPresenterTest {
*/
@Test
public void updateFileNameToLoader() {
- String expectedFile = "Stamatis";
+ var expectedFile = "Stamatis";
stub.setFileName(expectedFile);
presenter.start();
diff --git a/module/pom.xml b/module/pom.xml
index 25ad707eb..2dc3fe340 100644
--- a/module/pom.xml
+++ b/module/pom.xml
@@ -23,38 +23,39 @@
THE SOFTWARE.
-->
-
- 4.0.0
-
- com.iluwatar
- java-design-patterns
- 1.23.0-SNAPSHOT
-
- module
-
-
- org.junit.jupiter
- junit-jupiter-engine
- test
-
-
-
-
-
- org.apache.maven.plugins
- maven-assembly-plugin
-
-
-
-
-
- com.iluwatar.module.App
-
-
-
-
-
-
-
-
+
+ 4.0.0
+
+ com.iluwatar
+ java-design-patterns
+ 1.24.0-SNAPSHOT
+
+ module
+
+
+ org.junit.jupiter
+ junit-jupiter-engine
+ test
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-assembly-plugin
+
+
+
+
+
+ com.iluwatar.module.App
+
+
+
+
+
+
+
+
diff --git a/module/src/main/java/com/iluwatar/module/App.java b/module/src/main/java/com/iluwatar/module/App.java
index d50693440..0f89d8f89 100644
--- a/module/src/main/java/com/iluwatar/module/App.java
+++ b/module/src/main/java/com/iluwatar/module/App.java
@@ -67,10 +67,8 @@ public class App {
/**
* Following method is main executor.
- *
- * @param args for providing default program arguments
*/
- public static void execute(final String... args) {
+ public static void execute() {
/* Send logs on file system */
fileLoggerModule.printString(MESSAGE);
@@ -90,7 +88,7 @@ public class App {
*/
public static void main(final String... args) throws FileNotFoundException {
prepare();
- execute(args);
+ execute();
unprepare();
}
}
diff --git a/module/src/test/java/com/iluwatar/module/AppTest.java b/module/src/test/java/com/iluwatar/module/AppTest.java
index 88fa4c68c..4bf72fcb0 100644
--- a/module/src/test/java/com/iluwatar/module/AppTest.java
+++ b/module/src/test/java/com/iluwatar/module/AppTest.java
@@ -23,18 +23,19 @@
package com.iluwatar.module;
-import org.junit.jupiter.api.Test;
-
import java.io.FileNotFoundException;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.function.Executable;
+
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/**
* Tests that Module example runs without errors.
*/
-public final class AppTest {
+final class AppTest {
@Test
- public void test() throws FileNotFoundException {
- final String[] args = {};
- App.main(args);
+ void shouldExecuteWithoutException() {
+ assertDoesNotThrow((Executable) App::main);
}
}
diff --git a/module/src/test/java/com/iluwatar/module/FileLoggerModuleTest.java b/module/src/test/java/com/iluwatar/module/FileLoggerModuleTest.java
index 646bba642..9899d4c5c 100644
--- a/module/src/test/java/com/iluwatar/module/FileLoggerModuleTest.java
+++ b/module/src/test/java/com/iluwatar/module/FileLoggerModuleTest.java
@@ -23,17 +23,16 @@
package com.iluwatar.module;
-import org.junit.jupiter.api.Test;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertNull;
+import org.junit.jupiter.api.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
* The Module pattern can be considered a Creational pattern and a Structural pattern. It manages
@@ -58,13 +57,13 @@ public final class FileLoggerModuleTest {
/**
* This test verify that 'MESSAGE' is perfectly printed in output file
- *
+ *
* @throws IOException if program is not able to find log files (output.txt and error.txt)
*/
@Test
public void testFileMessage() throws IOException {
- /* Get singletong instance of File Logger Module */
+ /* Get singleton instance of File Logger Module */
final var fileLoggerModule = FileLoggerModule.getSingleton();
/* Prepare the essential sub modules, to perform the sequence of jobs */
@@ -82,13 +81,13 @@ public final class FileLoggerModuleTest {
/**
* This test verify that nothing is printed in output file
- *
+ *
* @throws IOException if program is not able to find log files (output.txt and error.txt)
*/
@Test
public void testNoFileMessage() throws IOException {
- /* Get singletong instance of File Logger Module */
+ /* Get singleton instance of File Logger Module */
final var fileLoggerModule = FileLoggerModule.getSingleton();
/* Prepare the essential sub modules, to perform the sequence of jobs */
@@ -103,14 +102,14 @@ public final class FileLoggerModuleTest {
/**
* This test verify that 'ERROR' is perfectly printed in error file
- *
+ *
* @throws FileNotFoundException if program is not able to find log files (output.txt and
- * error.txt)
+ * error.txt)
*/
@Test
public void testFileErrorMessage() throws FileNotFoundException {
- /* Get singletong instance of File Logger Module */
+ /* Get singleton instance of File Logger Module */
final var fileLoggerModule = FileLoggerModule.getSingleton();
/* Prepare the essential sub modules, to perform the sequence of jobs */
@@ -122,20 +121,20 @@ public final class FileLoggerModuleTest {
/* Test if 'Message' is printed in file */
assertEquals(ERROR, readFirstLine(ERROR_FILE));
- /* Unprepare to cleanup the modules */
+ /* Un-prepare to cleanup the modules */
fileLoggerModule.unprepare();
}
/**
* This test verify that nothing is printed in error file
- *
+ *
* @throws FileNotFoundException if program is not able to find log files (output.txt and
- * error.txt)
+ * error.txt)
*/
@Test
public void testNoFileErrorMessage() throws FileNotFoundException {
- /* Get singletong instance of File Logger Module */
+ /* Get singleton instance of File Logger Module */
final var fileLoggerModule = FileLoggerModule.getSingleton();
/* Prepare the essential sub modules, to perform the sequence of jobs */
@@ -150,11 +149,11 @@ public final class FileLoggerModuleTest {
/**
* Utility method to read first line of a file
- *
+ *
* @param file as file name to be read
* @return a string value as first line in file
*/
- private static final String readFirstLine(final String file) {
+ private static String readFirstLine(final String file) {
String firstLine = null;
try (var bufferedReader = new BufferedReader(new FileReader(file))) {
diff --git a/monad/pom.xml b/monad/pom.xml
index f553c3079..2c21a28b3 100644
--- a/monad/pom.xml
+++ b/monad/pom.xml
@@ -29,7 +29,7 @@
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
monad
diff --git a/monad/src/main/java/com/iluwatar/monad/App.java b/monad/src/main/java/com/iluwatar/monad/App.java
index ccb42edd0..bb3315064 100644
--- a/monad/src/main/java/com/iluwatar/monad/App.java
+++ b/monad/src/main/java/com/iluwatar/monad/App.java
@@ -41,9 +41,8 @@ import org.slf4j.LoggerFactory;
* instance of a plain object with {@link Validator#of(Object)} and validates it {@link
* Validator#validate(Function, Predicate, String)} against given predicates.
*
- * As a validation result {@link Validator#get()} it either returns valid object {@link
- * Validator#t} or throws a list of exceptions {@link Validator#exceptions} collected during
- * validation.
+ *
As a validation result {@link Validator#get()} either returns valid object
+ * or throws {@link IllegalStateException} with list of exceptions collected during validation.
*/
public class App {
@@ -55,10 +54,10 @@ public class App {
* @param args command line args
*/
public static void main(String[] args) {
- User user = new User("user", 24, Sex.FEMALE, "foobar.com");
+ var user = new User("user", 24, Sex.FEMALE, "foobar.com");
LOGGER.info(Validator.of(user).validate(User::getName, Objects::nonNull, "name is null")
.validate(User::getName, name -> !name.isEmpty(), "name is empty")
- .validate(User::getEmail, email -> !email.contains("@"), "email doesn't containt '@'")
+ .validate(User::getEmail, email -> !email.contains("@"), "email doesn't contains '@'")
.validate(User::getAge, age -> age > 20 && age < 30, "age isn't between...").get()
.toString());
}
diff --git a/monad/src/main/java/com/iluwatar/monad/User.java b/monad/src/main/java/com/iluwatar/monad/User.java
index 77766d1aa..8644c4c0a 100644
--- a/monad/src/main/java/com/iluwatar/monad/User.java
+++ b/monad/src/main/java/com/iluwatar/monad/User.java
@@ -1,66 +1,66 @@
-/*
- * The MIT License
- * Copyright © 2014-2019 Ilkka Seppälä
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-
-package com.iluwatar.monad;
-
-/**
- * User Definition.
- */
-public class User {
-
- private String name;
- private int age;
- private Sex sex;
- private String email;
-
- /**
- * Constructor.
- *
- * @param name - name
- * @param age - age
- * @param sex - sex
- * @param email - email address
- */
- public User(String name, int age, Sex sex, String email) {
- this.name = name;
- this.age = age;
- this.sex = sex;
- this.email = email;
- }
-
- public String getName() {
- return name;
- }
-
- public int getAge() {
- return age;
- }
-
- public Sex getSex() {
- return sex;
- }
-
- public String getEmail() {
- return email;
- }
-}
+/*
+ * The MIT License
+ * Copyright © 2014-2019 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+package com.iluwatar.monad;
+
+/**
+ * User Definition.
+ */
+public class User {
+
+ private final String name;
+ private final int age;
+ private final Sex sex;
+ private final String email;
+
+ /**
+ * Constructor.
+ *
+ * @param name - name
+ * @param age - age
+ * @param sex - sex
+ * @param email - email address
+ */
+ public User(String name, int age, Sex sex, String email) {
+ this.name = name;
+ this.age = age;
+ this.sex = sex;
+ this.email = email;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public int getAge() {
+ return age;
+ }
+
+ public Sex getSex() {
+ return sex;
+ }
+
+ public String getEmail() {
+ return email;
+ }
+}
diff --git a/monad/src/main/java/com/iluwatar/monad/Validator.java b/monad/src/main/java/com/iluwatar/monad/Validator.java
index 2d1f1bdab..47acc8a42 100644
--- a/monad/src/main/java/com/iluwatar/monad/Validator.java
+++ b/monad/src/main/java/com/iluwatar/monad/Validator.java
@@ -85,18 +85,21 @@ public class Validator {
}
/**
- * Extension for the {@link Validator#validate(Function, Predicate, String)} method, dedicated for
- * objects, that need to be projected before requested validation.
+ * Extension for the {@link Validator#validate(Predicate, String)} method, dedicated for objects,
+ * that need to be projected before requested validation.
*
* @param projection function that gets an objects, and returns projection representing element to
* be validated.
- * @param validation see {@link Validator#validate(Function, Predicate, String)}
- * @param message see {@link Validator#validate(Function, Predicate, String)}
- * @param see {@link Validator#validate(Function, Predicate, String)}
+ * @param validation see {@link Validator#validate(Predicate, String)}
+ * @param message see {@link Validator#validate(Predicate, String)}
+ * @param see {@link Validator#validate(Predicate, String)}
* @return this
*/
- public Validator validate(Function projection, Predicate validation,
- String message) {
+ public Validator validate(
+ Function projection,
+ Predicate validation,
+ String message
+ ) {
return validate(projection.andThen(validation::test)::apply, message);
}
@@ -110,7 +113,7 @@ public class Validator {
if (exceptions.isEmpty()) {
return obj;
}
- IllegalStateException e = new IllegalStateException();
+ var e = new IllegalStateException();
exceptions.forEach(e::addSuppressed);
throw e;
}
diff --git a/monad/src/test/java/com/iluwatar/monad/AppTest.java b/monad/src/test/java/com/iluwatar/monad/AppTest.java
index f4d89a7cd..d56270173 100644
--- a/monad/src/test/java/com/iluwatar/monad/AppTest.java
+++ b/monad/src/test/java/com/iluwatar/monad/AppTest.java
@@ -32,8 +32,7 @@ public class AppTest {
@Test
public void testMain() {
- String[] args = {};
- App.main(args);
+ App.main(new String[]{});
}
}
diff --git a/monad/src/test/java/com/iluwatar/monad/MonadTest.java b/monad/src/test/java/com/iluwatar/monad/MonadTest.java
index d1bdd7487..afd5b50f8 100644
--- a/monad/src/test/java/com/iluwatar/monad/MonadTest.java
+++ b/monad/src/test/java/com/iluwatar/monad/MonadTest.java
@@ -23,13 +23,12 @@
package com.iluwatar.monad;
-import org.junit.jupiter.api.Test;
-
-import java.util.Objects;
-
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
+import java.util.Objects;
+import org.junit.jupiter.api.Test;
+
/**
* Test for Monad Pattern
*/
@@ -37,27 +36,33 @@ public class MonadTest {
@Test
public void testForInvalidName() {
- User tom = new User(null, 21, Sex.MALE, "tom@foo.bar");
- assertThrows(IllegalStateException.class, () -> {
- Validator.of(tom).validate(User::getName, Objects::nonNull, "name cannot be null").get();
- });
+ var tom = new User(null, 21, Sex.MALE, "tom@foo.bar");
+ assertThrows(
+ IllegalStateException.class,
+ () -> Validator.of(tom)
+ .validate(User::getName, Objects::nonNull, "name cannot be null")
+ .get()
+ );
}
@Test
public void testForInvalidAge() {
- User john = new User("John", 17, Sex.MALE, "john@qwe.bar");
- assertThrows(IllegalStateException.class, () -> {
- Validator.of(john).validate(User::getName, Objects::nonNull, "name cannot be null")
- .validate(User::getAge, age -> age > 21, "user is underaged")
- .get();
- });
+ var john = new User("John", 17, Sex.MALE, "john@qwe.bar");
+ assertThrows(
+ IllegalStateException.class,
+ () -> Validator.of(john)
+ .validate(User::getName, Objects::nonNull, "name cannot be null")
+ .validate(User::getAge, age -> age > 21, "user is underage")
+ .get()
+ );
}
@Test
public void testForValid() {
- User sarah = new User("Sarah", 42, Sex.FEMALE, "sarah@det.org");
- User validated = Validator.of(sarah).validate(User::getName, Objects::nonNull, "name cannot be null")
- .validate(User::getAge, age -> age > 21, "user is underaged")
+ var sarah = new User("Sarah", 42, Sex.FEMALE, "sarah@det.org");
+ var validated = Validator.of(sarah)
+ .validate(User::getName, Objects::nonNull, "name cannot be null")
+ .validate(User::getAge, age -> age > 21, "user is underage")
.validate(User::getSex, sex -> sex == Sex.FEMALE, "user is not female")
.validate(User::getEmail, email -> email.contains("@"), "email does not contain @ sign")
.get();
diff --git a/monostate/pom.xml b/monostate/pom.xml
index 0e51fc700..02e271931 100644
--- a/monostate/pom.xml
+++ b/monostate/pom.xml
@@ -29,7 +29,7 @@
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
monostate
diff --git a/monostate/src/main/java/com/iluwatar/monostate/App.java b/monostate/src/main/java/com/iluwatar/monostate/App.java
index 64cb38461..9f5b2c173 100644
--- a/monostate/src/main/java/com/iluwatar/monostate/App.java
+++ b/monostate/src/main/java/com/iluwatar/monostate/App.java
@@ -30,7 +30,7 @@ package com.iluwatar.monostate;
*
* In the following example, The {@link LoadBalancer} class represents the app's logic. It
* contains a series of Servers, which can handle requests of type {@link Request}. Two instances of
- * LoadBalacer are created. When a request is made to a server via the first LoadBalancer the state
+ * LoadBalancer are created. When a request is made to a server via the first LoadBalancer the state
* change in the first load balancer affects the second. So if the first LoadBalancer selects the
* Server 1, the second LoadBalancer on a new request will select the Second server. If a third
* LoadBalancer is created and a new request is made to it, then it will select the third server as
@@ -43,8 +43,8 @@ public class App {
* @param args command line args
*/
public static void main(String[] args) {
- LoadBalancer loadBalancer1 = new LoadBalancer();
- LoadBalancer loadBalancer2 = new LoadBalancer();
+ var loadBalancer1 = new LoadBalancer();
+ var loadBalancer2 = new LoadBalancer();
loadBalancer1.serverRequest(new Request("Hello"));
loadBalancer2.serverRequest(new Request("Hello World"));
}
diff --git a/monostate/src/main/java/com/iluwatar/monostate/LoadBalancer.java b/monostate/src/main/java/com/iluwatar/monostate/LoadBalancer.java
index 8546ae177..7a784f514 100644
--- a/monostate/src/main/java/com/iluwatar/monostate/LoadBalancer.java
+++ b/monostate/src/main/java/com/iluwatar/monostate/LoadBalancer.java
@@ -38,8 +38,8 @@ public class LoadBalancer {
private static int lastServedId;
static {
- int id = 0;
- for (int port : new int[]{8080, 8081, 8082, 8083, 8084}) {
+ var id = 0;
+ for (var port : new int[]{8080, 8081, 8082, 8083, 8084}) {
SERVERS.add(new Server("localhost", port, ++id));
}
}
@@ -69,7 +69,7 @@ public class LoadBalancer {
if (lastServedId >= SERVERS.size()) {
lastServedId = 0;
}
- Server server = SERVERS.get(lastServedId++);
+ var server = SERVERS.get(lastServedId++);
server.serve(request);
}
diff --git a/monostate/src/test/java/com/iluwatar/monostate/AppTest.java b/monostate/src/test/java/com/iluwatar/monostate/AppTest.java
index c914f136e..d17a56bb9 100644
--- a/monostate/src/test/java/com/iluwatar/monostate/AppTest.java
+++ b/monostate/src/test/java/com/iluwatar/monostate/AppTest.java
@@ -32,8 +32,7 @@ public class AppTest {
@Test
public void testMain() {
- String[] args = {};
- App.main(args);
+ App.main(new String[]{});
}
}
diff --git a/monostate/src/test/java/com/iluwatar/monostate/LoadBalancerTest.java b/monostate/src/test/java/com/iluwatar/monostate/LoadBalancerTest.java
index 736bf6ea6..d62c029e2 100644
--- a/monostate/src/test/java/com/iluwatar/monostate/LoadBalancerTest.java
+++ b/monostate/src/test/java/com/iluwatar/monostate/LoadBalancerTest.java
@@ -44,8 +44,8 @@ public class LoadBalancerTest {
@Test
public void testSameStateAmongstAllInstances() {
- final LoadBalancer firstBalancer = new LoadBalancer();
- final LoadBalancer secondBalancer = new LoadBalancer();
+ final var firstBalancer = new LoadBalancer();
+ final var secondBalancer = new LoadBalancer();
firstBalancer.addServer(new Server("localhost", 8085, 6));
// Both should have the same number of servers.
assertEquals(firstBalancer.getNoOfServers(), secondBalancer.getNoOfServers());
@@ -55,18 +55,18 @@ public class LoadBalancerTest {
@Test
public void testServe() {
- final Server server = mock(Server.class);
+ final var server = mock(Server.class);
when(server.getHost()).thenReturn("testhost");
when(server.getPort()).thenReturn(1234);
doNothing().when(server).serve(any(Request.class));
- final LoadBalancer loadBalancer = new LoadBalancer();
+ final var loadBalancer = new LoadBalancer();
loadBalancer.addServer(server);
verifyZeroInteractions(server);
- final Request request = new Request("test");
- for (int i = 0; i < loadBalancer.getNoOfServers() * 2; i++) {
+ final var request = new Request("test");
+ for (var i = 0; i < loadBalancer.getNoOfServers() * 2; i++) {
loadBalancer.serverRequest(request);
}
diff --git a/multiton/README.md b/multiton/README.md
index ec1429a8f..85ce3acf2 100644
--- a/multiton/README.md
+++ b/multiton/README.md
@@ -35,14 +35,14 @@ Nazgul is the multiton class.
```java
public enum NazgulName {
- KHAMUL, MURAZOR, DWAR, JI_INDUR, AKHORAHIL, HOARMURATH, ADUNAPHEL, REN, UVATHA;
+ KHAMUL, MURAZOR, DWAR, JI_INDUR, AKHORAHIL, HOARMURATH, ADUNAPHEL, REN, UVATHA
}
public final class Nazgul {
- private static Map nazguls;
+ private static final Map nazguls;
- private NazgulName name;
+ private final NazgulName name;
static {
nazguls = new ConcurrentHashMap<>();
diff --git a/multiton/pom.xml b/multiton/pom.xml
index ef1e9c892..d1e4d50d5 100644
--- a/multiton/pom.xml
+++ b/multiton/pom.xml
@@ -29,7 +29,7 @@
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
multiton
diff --git a/multiton/src/main/java/com/iluwatar/multiton/Nazgul.java b/multiton/src/main/java/com/iluwatar/multiton/Nazgul.java
index f55f85aca..e08107eeb 100644
--- a/multiton/src/main/java/com/iluwatar/multiton/Nazgul.java
+++ b/multiton/src/main/java/com/iluwatar/multiton/Nazgul.java
@@ -31,9 +31,9 @@ import java.util.concurrent.ConcurrentHashMap;
*/
public final class Nazgul {
- private static Map nazguls;
+ private static final Map nazguls;
- private NazgulName name;
+ private final NazgulName name;
static {
nazguls = new ConcurrentHashMap<>();
diff --git a/multiton/src/main/java/com/iluwatar/multiton/NazgulEnum.java b/multiton/src/main/java/com/iluwatar/multiton/NazgulEnum.java
index 5b5c48d66..bb1454b9f 100644
--- a/multiton/src/main/java/com/iluwatar/multiton/NazgulEnum.java
+++ b/multiton/src/main/java/com/iluwatar/multiton/NazgulEnum.java
@@ -27,7 +27,13 @@ package com.iluwatar.multiton;
* enum based multiton implementation.
*/
public enum NazgulEnum {
-
- KHAMUL, MURAZOR, DWAR, JI_INDUR, AKHORAHIL, HOARMURATH, ADUNAPHEL, REN, UVATHA;
-
+ KHAMUL,
+ MURAZOR,
+ DWAR,
+ JI_INDUR,
+ AKHORAHIL,
+ HOARMURATH,
+ ADUNAPHEL,
+ REN,
+ UVATHA
}
diff --git a/multiton/src/main/java/com/iluwatar/multiton/NazgulName.java b/multiton/src/main/java/com/iluwatar/multiton/NazgulName.java
index c7865dceb..cce19c6ff 100644
--- a/multiton/src/main/java/com/iluwatar/multiton/NazgulName.java
+++ b/multiton/src/main/java/com/iluwatar/multiton/NazgulName.java
@@ -27,7 +27,13 @@ package com.iluwatar.multiton;
* Each Nazgul has different {@link NazgulName}.
*/
public enum NazgulName {
-
- KHAMUL, MURAZOR, DWAR, JI_INDUR, AKHORAHIL, HOARMURATH, ADUNAPHEL, REN, UVATHA;
-
+ KHAMUL,
+ MURAZOR,
+ DWAR,
+ JI_INDUR,
+ AKHORAHIL,
+ HOARMURATH,
+ ADUNAPHEL,
+ REN,
+ UVATHA
}
diff --git a/multiton/src/test/java/com/iluwatar/multiton/AppTest.java b/multiton/src/test/java/com/iluwatar/multiton/AppTest.java
index f577b7f07..0496ebdaf 100644
--- a/multiton/src/test/java/com/iluwatar/multiton/AppTest.java
+++ b/multiton/src/test/java/com/iluwatar/multiton/AppTest.java
@@ -26,15 +26,12 @@ package com.iluwatar.multiton;
import org.junit.jupiter.api.Test;
/**
- *
* Application test
- *
*/
public class AppTest {
@Test
public void test() {
- String[] args = {};
- App.main(args);
+ App.main(new String[]{});
}
}
diff --git a/multiton/src/test/java/com/iluwatar/multiton/NazgulEnumTest.java b/multiton/src/test/java/com/iluwatar/multiton/NazgulEnumTest.java
index 6668874f4..4d107a181 100644
--- a/multiton/src/test/java/com/iluwatar/multiton/NazgulEnumTest.java
+++ b/multiton/src/test/java/com/iluwatar/multiton/NazgulEnumTest.java
@@ -39,10 +39,10 @@ class NazgulEnumTest {
*/
@Test
public void testTheSameObjectIsReturnedWithMultipleCalls() {
- for (int i = 0; i < NazgulEnum.values().length; i++) {
- NazgulEnum instance1 = NazgulEnum.values()[i];
- NazgulEnum instance2 = NazgulEnum.values()[i];
- NazgulEnum instance3 = NazgulEnum.values()[i];
+ for (var i = 0; i < NazgulEnum.values().length; i++) {
+ var instance1 = NazgulEnum.values()[i];
+ var instance2 = NazgulEnum.values()[i];
+ var instance3 = NazgulEnum.values()[i];
assertSame(instance1, instance2);
assertSame(instance1, instance3);
assertSame(instance2, instance3);
diff --git a/multiton/src/test/java/com/iluwatar/multiton/NazgulTest.java b/multiton/src/test/java/com/iluwatar/multiton/NazgulTest.java
index 0429f8e29..f900659a8 100644
--- a/multiton/src/test/java/com/iluwatar/multiton/NazgulTest.java
+++ b/multiton/src/test/java/com/iluwatar/multiton/NazgulTest.java
@@ -41,8 +41,8 @@ public class NazgulTest {
*/
@Test
public void testGetInstance() {
- for (final NazgulName name : NazgulName.values()) {
- final Nazgul nazgul = Nazgul.getInstance(name);
+ for (final var name : NazgulName.values()) {
+ final var nazgul = Nazgul.getInstance(name);
assertNotNull(nazgul);
assertSame(nazgul, Nazgul.getInstance(name));
assertEquals(name, nazgul.getName());
diff --git a/mute-idiom/pom.xml b/mute-idiom/pom.xml
index a32f6a3ea..2bf95f070 100644
--- a/mute-idiom/pom.xml
+++ b/mute-idiom/pom.xml
@@ -30,7 +30,7 @@
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
mute-idiom
diff --git a/mute-idiom/src/main/java/com/iluwatar/mute/App.java b/mute-idiom/src/main/java/com/iluwatar/mute/App.java
index d4f140bf0..eca345014 100644
--- a/mute-idiom/src/main/java/com/iluwatar/mute/App.java
+++ b/mute-idiom/src/main/java/com/iluwatar/mute/App.java
@@ -25,7 +25,7 @@ package com.iluwatar.mute;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
-import java.sql.SQLException;
+import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -52,9 +52,8 @@ public class App {
* Program entry point.
*
* @param args command line args.
- * @throws Exception if any exception occurs
*/
- public static void main(String[] args) throws Exception {
+ public static void main(String[] args) {
useOfLoggedMute();
@@ -68,17 +67,17 @@ public class App {
* exception occurs.
*/
private static void useOfMute() {
- ByteArrayOutputStream out = new ByteArrayOutputStream();
+ var out = new ByteArrayOutputStream();
Mute.mute(() -> out.write("Hello".getBytes()));
}
- private static void useOfLoggedMute() throws SQLException {
- Resource resource = null;
+ private static void useOfLoggedMute() {
+ Optional resource = Optional.empty();
try {
- resource = acquireResource();
- utilizeResource(resource);
+ resource = Optional.of(acquireResource());
+ utilizeResource(resource.get());
} finally {
- closeResource(resource);
+ resource.ifPresent(App::closeResource);
}
}
@@ -86,14 +85,14 @@ public class App {
* All we can do while failed close of a resource is to log it.
*/
private static void closeResource(Resource resource) {
- Mute.loggedMute(() -> resource.close());
+ Mute.loggedMute(resource::close);
}
- private static void utilizeResource(Resource resource) throws SQLException {
+ private static void utilizeResource(Resource resource) {
LOGGER.info("Utilizing acquired resource: {}", resource);
}
- private static Resource acquireResource() throws SQLException {
+ private static Resource acquireResource() {
return new Resource() {
@Override
diff --git a/mute-idiom/src/test/java/com/iluwatar/mute/AppTest.java b/mute-idiom/src/test/java/com/iluwatar/mute/AppTest.java
index 5ca525a9d..c5ce35582 100644
--- a/mute-idiom/src/test/java/com/iluwatar/mute/AppTest.java
+++ b/mute-idiom/src/test/java/com/iluwatar/mute/AppTest.java
@@ -25,14 +25,15 @@ package com.iluwatar.mute;
import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+
/**
* Tests that Mute idiom example runs without errors.
- *
*/
-public class AppTest {
+class AppTest {
@Test
- public void test() throws Exception {
- App.main(null);
+ void shouldExecuteApplicationWithoutException() {
+ assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
diff --git a/mute-idiom/src/test/java/com/iluwatar/mute/MuteTest.java b/mute-idiom/src/test/java/com/iluwatar/mute/MuteTest.java
index f2743113b..e92b26f9b 100644
--- a/mute-idiom/src/test/java/com/iluwatar/mute/MuteTest.java
+++ b/mute-idiom/src/test/java/com/iluwatar/mute/MuteTest.java
@@ -23,46 +23,41 @@
package com.iluwatar.mute;
+import java.io.ByteArrayOutputStream;
+import java.io.PrintStream;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.PrintStream;
-
-import static org.junit.jupiter.api.Assertions.assertThrows;
-import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Test for the mute-idiom pattern
*/
-public class MuteTest {
+class MuteTest {
private static final Logger LOGGER = LoggerFactory.getLogger(MuteTest.class);
private static final String MESSAGE = "should not occur";
@Test
- public void muteShouldRunTheCheckedRunnableAndNotThrowAnyExceptionIfCheckedRunnableDoesNotThrowAnyException() {
- Mute.mute(this::methodNotThrowingAnyException);
+ void muteShouldRunTheCheckedRunnableAndNotThrowAnyExceptionIfCheckedRunnableDoesNotThrowAnyException() {
+ assertDoesNotThrow(() -> Mute.mute(this::methodNotThrowingAnyException));
}
@Test
- public void muteShouldRethrowUnexpectedExceptionAsAssertionError() {
- assertThrows(AssertionError.class, () -> {
- Mute.mute(this::methodThrowingException);
- });
+ void muteShouldRethrowUnexpectedExceptionAsAssertionError() {
+ assertThrows(AssertionError.class, () -> Mute.mute(this::methodThrowingException));
}
@Test
- public void loggedMuteShouldRunTheCheckedRunnableAndNotThrowAnyExceptionIfCheckedRunnableDoesNotThrowAnyException() {
- Mute.loggedMute(this::methodNotThrowingAnyException);
+ void loggedMuteShouldRunTheCheckedRunnableAndNotThrowAnyExceptionIfCheckedRunnableDoesNotThrowAnyException() {
+ assertDoesNotThrow(() -> Mute.mute(this::methodNotThrowingAnyException));
}
@Test
- public void loggedMuteShouldLogExceptionTraceBeforeSwallowingIt() {
- ByteArrayOutputStream stream = new ByteArrayOutputStream();
+ void loggedMuteShouldLogExceptionTraceBeforeSwallowingIt() {
+ var stream = new ByteArrayOutputStream();
System.setErr(new PrintStream(stream));
Mute.loggedMute(this::methodThrowingException);
diff --git a/mutex/pom.xml b/mutex/pom.xml
index 9cdff25e4..84455abb1 100644
--- a/mutex/pom.xml
+++ b/mutex/pom.xml
@@ -29,7 +29,7 @@
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
mutex
diff --git a/mutex/src/main/java/com/iluwatar/mutex/App.java b/mutex/src/main/java/com/iluwatar/mutex/App.java
index e4a952ef9..c50acc65a 100644
--- a/mutex/src/main/java/com/iluwatar/mutex/App.java
+++ b/mutex/src/main/java/com/iluwatar/mutex/App.java
@@ -38,10 +38,10 @@ public class App {
* main method.
*/
public static void main(String[] args) {
- Mutex mutex = new Mutex();
- Jar jar = new Jar(1000, mutex);
- Thief peter = new Thief("Peter", jar);
- Thief john = new Thief("John", jar);
+ var mutex = new Mutex();
+ var jar = new Jar(1000, mutex);
+ var peter = new Thief("Peter", jar);
+ var john = new Thief("John", jar);
peter.start();
john.start();
}
diff --git a/mutex/src/main/java/com/iluwatar/mutex/Jar.java b/mutex/src/main/java/com/iluwatar/mutex/Jar.java
index f68b266ad..4a0861e1a 100644
--- a/mutex/src/main/java/com/iluwatar/mutex/Jar.java
+++ b/mutex/src/main/java/com/iluwatar/mutex/Jar.java
@@ -48,7 +48,7 @@ public class Jar {
* Method for a thief to take a bean.
*/
public boolean takeBean() {
- boolean success = false;
+ var success = false;
try {
lock.acquire();
success = beans > 0;
diff --git a/mutex/src/main/java/com/iluwatar/mutex/Thief.java b/mutex/src/main/java/com/iluwatar/mutex/Thief.java
index 29caba540..a9a715970 100644
--- a/mutex/src/main/java/com/iluwatar/mutex/Thief.java
+++ b/mutex/src/main/java/com/iluwatar/mutex/Thief.java
@@ -54,7 +54,7 @@ public class Thief extends Thread {
*/
@Override
public void run() {
- int beans = 0;
+ var beans = 0;
while (jar.takeBean()) {
beans = beans + 1;
diff --git a/mutex/src/test/java/com/iluwatar/mutex/AppTest.java b/mutex/src/test/java/com/iluwatar/mutex/AppTest.java
index 1793bf90b..7866b22a8 100644
--- a/mutex/src/test/java/com/iluwatar/mutex/AppTest.java
+++ b/mutex/src/test/java/com/iluwatar/mutex/AppTest.java
@@ -25,15 +25,15 @@ package com.iluwatar.mutex;
import org.junit.jupiter.api.Test;
-import java.io.IOException;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/**
* Application Test Entrypoint
*/
-public class AppTest {
+class AppTest {
+
@Test
- public void test() throws IOException {
- String[] args = {};
- App.main(args);
+ void shouldExecuteApplicationWithoutException() {
+ assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
diff --git a/mutex/src/test/java/com/iluwatar/mutex/JarTest.java b/mutex/src/test/java/com/iluwatar/mutex/JarTest.java
index e0a316072..786f96e44 100644
--- a/mutex/src/test/java/com/iluwatar/mutex/JarTest.java
+++ b/mutex/src/test/java/com/iluwatar/mutex/JarTest.java
@@ -23,10 +23,11 @@
package com.iluwatar.mutex;
-import org.junit.jupiter.api.Test;
-
import static org.junit.jupiter.api.Assertions.assertFalse;
-import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.util.stream.IntStream;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
/**
* Test case for taking beans from a Jar
@@ -35,12 +36,10 @@ public class JarTest {
@Test
public void testTakeBeans() {
- Mutex mutex = new Mutex();
- Jar jar = new Jar(10, mutex);
- for (int i = 0; i < 10; i++) {
- assertTrue(jar.takeBean());
- }
+ var mutex = new Mutex();
+ var jar = new Jar(10, mutex);
+ IntStream.range(0, 10).mapToObj(i -> jar.takeBean()).forEach(Assertions::assertTrue);
assertFalse(jar.takeBean());
}
-}
\ No newline at end of file
+}
diff --git a/mutex/src/test/java/com/iluwatar/mutex/MutexTest.java b/mutex/src/test/java/com/iluwatar/mutex/MutexTest.java
index 2e3184c51..d6d0cc1d7 100644
--- a/mutex/src/test/java/com/iluwatar/mutex/MutexTest.java
+++ b/mutex/src/test/java/com/iluwatar/mutex/MutexTest.java
@@ -23,12 +23,12 @@
package com.iluwatar.mutex;
-import org.junit.jupiter.api.Test;
-
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.fail;
+import org.junit.jupiter.api.Test;
+
/**
* Test case for acquiring and releasing a Mutex
*/
@@ -36,7 +36,7 @@ public class MutexTest {
@Test
public void acquireReleaseTest() {
- Mutex mutex = new Mutex();
+ var mutex = new Mutex();
assertNull(mutex.getOwner());
try {
mutex.acquire();
diff --git a/naked-objects/dom/pom.xml b/naked-objects/dom/pom.xml
index dffc1650c..1b1eb2266 100644
--- a/naked-objects/dom/pom.xml
+++ b/naked-objects/dom/pom.xml
@@ -30,7 +30,7 @@
com.iluwatar
naked-objects
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
naked-objects-dom
@@ -127,7 +127,7 @@
-
+
diff --git a/naked-objects/dom/src/main/java/domainapp/dom/app/homepage/HomePageViewModel.layout.json b/naked-objects/dom/src/main/java/domainapp/dom/app/homepage/HomePageViewModel.layout.json
index 638473eee..fe39b5b42 100644
--- a/naked-objects/dom/src/main/java/domainapp/dom/app/homepage/HomePageViewModel.layout.json
+++ b/naked-objects/dom/src/main/java/domainapp/dom/app/homepage/HomePageViewModel.layout.json
@@ -1,19 +1,3 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
{
"columns": [
{
diff --git a/naked-objects/dom/src/main/java/domainapp/dom/modules/simple/SimpleObject.java b/naked-objects/dom/src/main/java/domainapp/dom/modules/simple/SimpleObject.java
index 809da6d31..43d96f280 100644
--- a/naked-objects/dom/src/main/java/domainapp/dom/modules/simple/SimpleObject.java
+++ b/naked-objects/dom/src/main/java/domainapp/dom/modules/simple/SimpleObject.java
@@ -50,9 +50,9 @@ import org.apache.isis.applib.util.ObjectContracts;
strategy = javax.jdo.annotations.IdGeneratorStrategy.IDENTITY, column = "id")
@javax.jdo.annotations.Version(strategy = VersionStrategy.VERSION_NUMBER, column = "version")
@javax.jdo.annotations.Queries({
- @javax.jdo.annotations.Query(name = "find", language = "JDOQL", value = "SELECT "
+ @javax.jdo.annotations.Query(name = "find", value = "SELECT "
+ "FROM domainapp.dom.modules.simple.SimpleObject "),
- @javax.jdo.annotations.Query(name = "findByName", language = "JDOQL", value = "SELECT "
+ @javax.jdo.annotations.Query(name = "findByName", value = "SELECT "
+ "FROM domainapp.dom.modules.simple.SimpleObject " + "WHERE name.indexOf(:name) >= 0 ")})
@javax.jdo.annotations.Unique(name = "SimpleObject_name_UNQ", members = {"name"})
@DomainObject
diff --git a/naked-objects/dom/src/main/java/domainapp/dom/modules/simple/SimpleObject.layout.json b/naked-objects/dom/src/main/java/domainapp/dom/modules/simple/SimpleObject.layout.json
index 78b2ac096..998c419f2 100644
--- a/naked-objects/dom/src/main/java/domainapp/dom/modules/simple/SimpleObject.layout.json
+++ b/naked-objects/dom/src/main/java/domainapp/dom/modules/simple/SimpleObject.layout.json
@@ -1,19 +1,3 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
{
"columns": [
{
diff --git a/naked-objects/dom/src/test/java/domainapp/dom/modules/simple/SimpleObjectTest.java b/naked-objects/dom/src/test/java/domainapp/dom/modules/simple/SimpleObjectTest.java
index 03ab30f75..5435325cf 100644
--- a/naked-objects/dom/src/test/java/domainapp/dom/modules/simple/SimpleObjectTest.java
+++ b/naked-objects/dom/src/test/java/domainapp/dom/modules/simple/SimpleObjectTest.java
@@ -37,12 +37,12 @@ public class SimpleObjectTest {
SimpleObject simpleObject;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
simpleObject = new SimpleObject();
}
@Test
- public void testName() throws Exception {
+ public void testName() {
// given
String name = "Foobar";
assertNull(simpleObject.getName());
diff --git a/naked-objects/dom/src/test/java/domainapp/dom/modules/simple/SimpleObjectsTest.java b/naked-objects/dom/src/test/java/domainapp/dom/modules/simple/SimpleObjectsTest.java
index a95ad5aa3..5fbcfde2b 100644
--- a/naked-objects/dom/src/test/java/domainapp/dom/modules/simple/SimpleObjectsTest.java
+++ b/naked-objects/dom/src/test/java/domainapp/dom/modules/simple/SimpleObjectsTest.java
@@ -52,13 +52,13 @@ public class SimpleObjectsTest {
SimpleObjects simpleObjects;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
simpleObjects = new SimpleObjects();
simpleObjects.container = mockContainer;
}
@Test
- public void testCreate() throws Exception {
+ public void testCreate() {
// given
final SimpleObject simpleObject = new SimpleObject();
@@ -85,7 +85,7 @@ public class SimpleObjectsTest {
}
@Test
- public void testListAll() throws Exception {
+ public void testListAll() {
// given
final List all = Lists.newArrayList();
diff --git a/naked-objects/fixture/pom.xml b/naked-objects/fixture/pom.xml
index 3457ac0a4..a918e20de 100644
--- a/naked-objects/fixture/pom.xml
+++ b/naked-objects/fixture/pom.xml
@@ -30,7 +30,7 @@
com.iluwatar
naked-objects
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
naked-objects-fixture
diff --git a/naked-objects/fixture/src/main/java/domainapp/fixture/modules/simple/SimpleObjectCreate.java b/naked-objects/fixture/src/main/java/domainapp/fixture/modules/simple/SimpleObjectCreate.java
index dc19195ac..0df939678 100644
--- a/naked-objects/fixture/src/main/java/domainapp/fixture/modules/simple/SimpleObjectCreate.java
+++ b/naked-objects/fixture/src/main/java/domainapp/fixture/modules/simple/SimpleObjectCreate.java
@@ -67,8 +67,7 @@ public class SimpleObjectCreate extends FixtureScript {
@Override
protected void execute(final ExecutionContext ec) {
-
- String paramName = checkParam("name", ec, String.class);
+ var paramName = checkParam("name", ec, String.class);
this.simpleObject = wrap(simpleObjects).create(paramName);
diff --git a/naked-objects/fixture/src/main/java/domainapp/fixture/scenarios/RecreateSimpleObjects.java b/naked-objects/fixture/src/main/java/domainapp/fixture/scenarios/RecreateSimpleObjects.java
index 847f15d01..5dc9a4785 100644
--- a/naked-objects/fixture/src/main/java/domainapp/fixture/scenarios/RecreateSimpleObjects.java
+++ b/naked-objects/fixture/src/main/java/domainapp/fixture/scenarios/RecreateSimpleObjects.java
@@ -27,7 +27,6 @@ import com.google.common.collect.Lists;
import domainapp.dom.modules.simple.SimpleObject;
import domainapp.fixture.modules.simple.SimpleObjectCreate;
import domainapp.fixture.modules.simple.SimpleObjectsTearDown;
-import java.util.Collections;
import java.util.List;
import org.apache.isis.applib.fixturescripts.FixtureScript;
@@ -37,8 +36,18 @@ import org.apache.isis.applib.fixturescripts.FixtureScript;
*/
public class RecreateSimpleObjects extends FixtureScript {
- public final List names = Collections.unmodifiableList(List.of("Foo", "Bar", "Baz",
- "Frodo", "Froyo", "Fizz", "Bip", "Bop", "Bang", "Boo"));
+ public final List names = List.of(
+ "Foo",
+ "Bar",
+ "Baz",
+ "Frodo",
+ "Froyo",
+ "Fizz",
+ "Bip",
+ "Bop",
+ "Bang",
+ "Boo"
+ );
// region > number (optional input)
private Integer number;
@@ -77,7 +86,7 @@ public class RecreateSimpleObjects extends FixtureScript {
protected void execute(final ExecutionContext ec) {
// defaults
- final int paramNumber = defaultParam("number", ec, 3);
+ final var paramNumber = defaultParam("number", ec, 3);
// validate
if (paramNumber < 0 || paramNumber > names.size()) {
@@ -90,8 +99,8 @@ public class RecreateSimpleObjects extends FixtureScript {
//
ec.executeChild(this, new SimpleObjectsTearDown());
- for (int i = 0; i < paramNumber; i++) {
- final SimpleObjectCreate fs = new SimpleObjectCreate().setName(names.get(i));
+ for (var i = 0; i < paramNumber; i++) {
+ final var fs = new SimpleObjectCreate().setName(names.get(i));
ec.executeChild(this, fs.getName(), fs);
simpleObjects.add(fs.getSimpleObject());
}
diff --git a/naked-objects/integtests/pom.xml b/naked-objects/integtests/pom.xml
index f46541f48..b9482b292 100644
--- a/naked-objects/integtests/pom.xml
+++ b/naked-objects/integtests/pom.xml
@@ -30,7 +30,7 @@
com.iluwatar
naked-objects
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
naked-objects-integtests
diff --git a/naked-objects/integtests/src/test/java/domainapp/integtests/bootstrap/SimpleAppSystemInitializer.java b/naked-objects/integtests/src/test/java/domainapp/integtests/bootstrap/SimpleAppSystemInitializer.java
index f67c26876..ad186d706 100644
--- a/naked-objects/integtests/src/test/java/domainapp/integtests/bootstrap/SimpleAppSystemInitializer.java
+++ b/naked-objects/integtests/src/test/java/domainapp/integtests/bootstrap/SimpleAppSystemInitializer.java
@@ -40,7 +40,7 @@ public final class SimpleAppSystemInitializer {
* Init test system
*/
public static void initIsft() {
- IsisSystemForTest isft = IsisSystemForTest.getElseNull();
+ var isft = IsisSystemForTest.getElseNull();
if (isft == null) {
isft = new SimpleAppSystemBuilder().build().setUpSystem();
IsisSystemForTest.set(isft);
@@ -58,8 +58,7 @@ public final class SimpleAppSystemInitializer {
}
private static IsisConfiguration testConfiguration() {
- final IsisConfigurationForJdoIntegTests testConfiguration =
- new IsisConfigurationForJdoIntegTests();
+ final var testConfiguration = new IsisConfigurationForJdoIntegTests();
testConfiguration.addRegisterEntitiesPackagePrefix("domainapp.dom.modules");
return testConfiguration;
diff --git a/naked-objects/integtests/src/test/java/domainapp/integtests/specglue/CatalogOfFixturesGlue.java b/naked-objects/integtests/src/test/java/domainapp/integtests/specglue/CatalogOfFixturesGlue.java
index 025c6724a..142b0e9fb 100644
--- a/naked-objects/integtests/src/test/java/domainapp/integtests/specglue/CatalogOfFixturesGlue.java
+++ b/naked-objects/integtests/src/test/java/domainapp/integtests/specglue/CatalogOfFixturesGlue.java
@@ -23,10 +23,9 @@
package domainapp.integtests.specglue;
-import org.apache.isis.core.specsupport.specs.CukeGlueAbstract;
-
import cucumber.api.java.Before;
import domainapp.fixture.scenarios.RecreateSimpleObjects;
+import org.apache.isis.core.specsupport.specs.CukeGlueAbstract;
/**
* Test Execution to append a fixture of SimpleObjects
@@ -34,7 +33,7 @@ import domainapp.fixture.scenarios.RecreateSimpleObjects;
public class CatalogOfFixturesGlue extends CukeGlueAbstract {
@Before(value = {"@integration", "@SimpleObjectsFixture"}, order = 20000)
- public void integrationFixtures() throws Throwable {
+ public void integrationFixtures() {
scenarioExecution().install(new RecreateSimpleObjects());
}
}
diff --git a/naked-objects/integtests/src/test/java/domainapp/integtests/specglue/modules/simple/SimpleObjectGlue.java b/naked-objects/integtests/src/test/java/domainapp/integtests/specglue/modules/simple/SimpleObjectGlue.java
index 7b508faf3..51253b667 100644
--- a/naked-objects/integtests/src/test/java/domainapp/integtests/specglue/modules/simple/SimpleObjectGlue.java
+++ b/naked-objects/integtests/src/test/java/domainapp/integtests/specglue/modules/simple/SimpleObjectGlue.java
@@ -28,9 +28,7 @@ import static org.junit.Assert.assertThat;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.When;
-import domainapp.dom.modules.simple.SimpleObject;
import domainapp.dom.modules.simple.SimpleObjects;
-import java.util.List;
import java.util.UUID;
import org.apache.isis.core.specsupport.specs.CukeGlueAbstract;
@@ -40,9 +38,9 @@ import org.apache.isis.core.specsupport.specs.CukeGlueAbstract;
public class SimpleObjectGlue extends CukeGlueAbstract {
@Given("^there are.* (\\d+) simple objects$")
- public void thereAreNumSimpleObjects(int n) throws Throwable {
+ public void thereAreNumSimpleObjects(int n) {
try {
- final List findAll = service(SimpleObjects.class).listAll();
+ final var findAll = service(SimpleObjects.class).listAll();
assertThat(findAll.size(), is(n));
putVar("list", "all", findAll);
@@ -52,7 +50,7 @@ public class SimpleObjectGlue extends CukeGlueAbstract {
}
@When("^I create a new simple object$")
- public void createNewSimpleObject() throws Throwable {
+ public void createNewSimpleObject() {
service(SimpleObjects.class).create(UUID.randomUUID().toString());
}
diff --git a/naked-objects/integtests/src/test/java/domainapp/integtests/tests/modules/simple/SimpleObjectIntegTest.java b/naked-objects/integtests/src/test/java/domainapp/integtests/tests/modules/simple/SimpleObjectIntegTest.java
index 11ff6a47d..819220344 100644
--- a/naked-objects/integtests/src/test/java/domainapp/integtests/tests/modules/simple/SimpleObjectIntegTest.java
+++ b/naked-objects/integtests/src/test/java/domainapp/integtests/tests/modules/simple/SimpleObjectIntegTest.java
@@ -26,8 +26,10 @@ package domainapp.integtests.tests.modules.simple;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
+import domainapp.dom.modules.simple.SimpleObject;
+import domainapp.fixture.scenarios.RecreateSimpleObjects;
+import domainapp.integtests.tests.SimpleAppIntegTest;
import javax.inject.Inject;
-
import org.apache.isis.applib.DomainObjectContainer;
import org.apache.isis.applib.fixturescripts.FixtureScripts;
import org.apache.isis.applib.services.wrapper.DisabledException;
@@ -35,10 +37,6 @@ import org.apache.isis.applib.services.wrapper.InvalidException;
import org.junit.Before;
import org.junit.Test;
-import domainapp.dom.modules.simple.SimpleObject;
-import domainapp.fixture.scenarios.RecreateSimpleObjects;
-import domainapp.integtests.tests.SimpleAppIntegTest;
-
/**
* Test Fixtures with Simple Objects
*/
@@ -56,7 +54,7 @@ public class SimpleObjectIntegTest extends SimpleAppIntegTest {
private static final String NEW_NAME = "new name";
@Before
- public void setUp() throws Exception {
+ public void setUp() {
// given
fs = new RecreateSimpleObjects().setNumber(1);
fixtureScripts.runFixtureScript(fs, null);
@@ -68,15 +66,15 @@ public class SimpleObjectIntegTest extends SimpleAppIntegTest {
}
@Test
- public void testNameAccessible() throws Exception {
- // when
- final String name = simpleObjectWrapped.getName();
+ public void testNameAccessible() {
+ /* when */
+ final var name = simpleObjectWrapped.getName();
// then
assertEquals(fs.names.get(0), name);
}
@Test
- public void testNameCannotBeUpdatedDirectly() throws Exception {
+ public void testNameCannotBeUpdatedDirectly() {
// expect
expectedExceptions.expect(DisabledException.class);
@@ -86,7 +84,7 @@ public class SimpleObjectIntegTest extends SimpleAppIntegTest {
}
@Test
- public void testUpdateName() throws Exception {
+ public void testUpdateName() {
// when
simpleObjectWrapped.updateName(NEW_NAME);
@@ -96,7 +94,7 @@ public class SimpleObjectIntegTest extends SimpleAppIntegTest {
}
@Test
- public void testUpdateNameFailsValidation() throws Exception {
+ public void testUpdateNameFailsValidation() {
// expect
expectedExceptions.expect(InvalidException.class);
@@ -107,13 +105,13 @@ public class SimpleObjectIntegTest extends SimpleAppIntegTest {
}
@Test
- public void testInterpolatesName() throws Exception {
+ public void testInterpolatesName() {
// given
- final String name = simpleObjectWrapped.getName();
+ final var name = simpleObjectWrapped.getName();
// when
- final String title = container.titleOf(simpleObjectWrapped);
+ final var title = container.titleOf(simpleObjectWrapped);
// then
assertEquals("Object: " + name, title);
diff --git a/naked-objects/integtests/src/test/java/domainapp/integtests/tests/modules/simple/SimpleObjectsIntegTest.java b/naked-objects/integtests/src/test/java/domainapp/integtests/tests/modules/simple/SimpleObjectsIntegTest.java
index c762dd88f..2699c5aad 100644
--- a/naked-objects/integtests/src/test/java/domainapp/integtests/tests/modules/simple/SimpleObjectsIntegTest.java
+++ b/naked-objects/integtests/src/test/java/domainapp/integtests/tests/modules/simple/SimpleObjectsIntegTest.java
@@ -25,11 +25,13 @@ package domainapp.integtests.tests.modules.simple;
import static org.junit.Assert.assertEquals;
+import com.google.common.base.Throwables;
+import domainapp.dom.modules.simple.SimpleObjects;
+import domainapp.fixture.modules.simple.SimpleObjectsTearDown;
+import domainapp.fixture.scenarios.RecreateSimpleObjects;
+import domainapp.integtests.tests.SimpleAppIntegTest;
import java.sql.SQLIntegrityConstraintViolationException;
-import java.util.List;
-
import javax.inject.Inject;
-
import org.apache.isis.applib.fixturescripts.FixtureScript;
import org.apache.isis.applib.fixturescripts.FixtureScripts;
import org.hamcrest.Description;
@@ -37,14 +39,6 @@ import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
import org.junit.Test;
-import com.google.common.base.Throwables;
-
-import domainapp.dom.modules.simple.SimpleObject;
-import domainapp.dom.modules.simple.SimpleObjects;
-import domainapp.fixture.modules.simple.SimpleObjectsTearDown;
-import domainapp.fixture.scenarios.RecreateSimpleObjects;
-import domainapp.integtests.tests.SimpleAppIntegTest;
-
/**
* Fixture Pattern Integration Test
*/
@@ -56,25 +50,25 @@ public class SimpleObjectsIntegTest extends SimpleAppIntegTest {
SimpleObjects simpleObjects;
@Test
- public void testListAll() throws Exception {
+ public void testListAll() {
// given
- RecreateSimpleObjects fs = new RecreateSimpleObjects();
+ var fs = new RecreateSimpleObjects();
fixtureScripts.runFixtureScript(fs, null);
nextTransaction();
// when
- final List all = wrap(simpleObjects).listAll();
+ final var all = wrap(simpleObjects).listAll();
// then
assertEquals(fs.getSimpleObjects().size(), all.size());
- SimpleObject simpleObject = wrap(all.get(0));
+ var simpleObject = wrap(all.get(0));
assertEquals(fs.getSimpleObjects().get(0).getName(), simpleObject.getName());
}
-
+
@Test
- public void testListAllWhenNone() throws Exception {
+ public void testListAllWhenNone() {
// given
FixtureScript fs = new SimpleObjectsTearDown();
@@ -82,14 +76,14 @@ public class SimpleObjectsIntegTest extends SimpleAppIntegTest {
nextTransaction();
// when
- final List all = wrap(simpleObjects).listAll();
+ final var all = wrap(simpleObjects).listAll();
// then
assertEquals(0, all.size());
}
-
+
@Test
- public void testCreate() throws Exception {
+ public void testCreate() {
// given
FixtureScript fs = new SimpleObjectsTearDown();
@@ -100,12 +94,12 @@ public class SimpleObjectsIntegTest extends SimpleAppIntegTest {
wrap(simpleObjects).create("Faz");
// then
- final List all = wrap(simpleObjects).listAll();
+ final var all = wrap(simpleObjects).listAll();
assertEquals(1, all.size());
}
-
+
@Test
- public void testCreateWhenAlreadyExists() throws Exception {
+ public void testCreateWhenAlreadyExists() {
// given
FixtureScript fs = new SimpleObjectsTearDown();
@@ -115,24 +109,22 @@ public class SimpleObjectsIntegTest extends SimpleAppIntegTest {
nextTransaction();
// then
- expectedExceptions.expectCause(causalChainContains(SQLIntegrityConstraintViolationException.class));
+ expectedExceptions
+ .expectCause(causalChainContains(SQLIntegrityConstraintViolationException.class));
// when
wrap(simpleObjects).create("Faz");
nextTransaction();
}
-
+
+ @SuppressWarnings("SameParameterValue")
private static Matcher extends Throwable> causalChainContains(final Class> cls) {
- return new TypeSafeMatcher() {
+ return new TypeSafeMatcher<>() {
@Override
+ @SuppressWarnings("UnstableApiUsage")
protected boolean matchesSafely(Throwable item) {
- final List causalChain = Throwables.getCausalChain(item);
- for (Throwable throwable : causalChain) {
- if (cls.isAssignableFrom(throwable.getClass())) {
- return true;
- }
- }
- return false;
+ final var causalChain = Throwables.getCausalChain(item);
+ return causalChain.stream().map(Throwable::getClass).anyMatch(cls::isAssignableFrom);
}
@Override
diff --git a/naked-objects/pom.xml b/naked-objects/pom.xml
index 5b7a2e0c7..e8b9b79c5 100644
--- a/naked-objects/pom.xml
+++ b/naked-objects/pom.xml
@@ -29,7 +29,7 @@
java-design-patterns
com.iluwatar
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
naked-objects
pom
@@ -333,17 +333,17 @@
${project.groupId}
naked-objects-dom
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
${project.groupId}
naked-objects-fixture
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
${project.groupId}
naked-objects-webapp
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
diff --git a/naked-objects/webapp/ide/eclipse/launch/.gitignore b/naked-objects/webapp/ide/eclipse/launch/.gitignore
index 3d9734548..3cefd2567 100644
--- a/naked-objects/webapp/ide/eclipse/launch/.gitignore
+++ b/naked-objects/webapp/ide/eclipse/launch/.gitignore
@@ -2,7 +2,3 @@
/SimpleApp-PROTOTYPE-no-fixtures.launch
/SimpleApp-PROTOTYPE-with-fixtures.launch
/SimpleApp-SERVER-no-fixtures.launch
-/SimpleApp-PROTOTYPE-jrebel.launch
-/SimpleApp-PROTOTYPE-no-fixtures.launch
-/SimpleApp-PROTOTYPE-with-fixtures.launch
-/SimpleApp-SERVER-no-fixtures.launch
diff --git a/naked-objects/webapp/pom.xml b/naked-objects/webapp/pom.xml
index bdf638cba..3a817f9e2 100644
--- a/naked-objects/webapp/pom.xml
+++ b/naked-objects/webapp/pom.xml
@@ -30,7 +30,7 @@
com.iluwatar
naked-objects
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
naked-objects-webapp
@@ -129,7 +129,7 @@
-
+
diff --git a/naked-objects/webapp/src/main/java/domainapp/webapp/SimpleApplication.java b/naked-objects/webapp/src/main/java/domainapp/webapp/SimpleApplication.java
index 8425712dc..780e4027e 100644
--- a/naked-objects/webapp/src/main/java/domainapp/webapp/SimpleApplication.java
+++ b/naked-objects/webapp/src/main/java/domainapp/webapp/SimpleApplication.java
@@ -31,18 +31,15 @@ import com.google.inject.name.Names;
import com.google.inject.util.Modules;
import com.google.inject.util.Providers;
import de.agilecoders.wicket.core.Bootstrap;
-import de.agilecoders.wicket.core.settings.IBootstrapSettings;
import de.agilecoders.wicket.themes.markup.html.bootswatch.BootswatchTheme;
import de.agilecoders.wicket.themes.markup.html.bootswatch.BootswatchThemeProvider;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
-import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.isis.viewer.wicket.viewer.IsisWicketApplication;
import org.apache.isis.viewer.wicket.viewer.integration.wicket.AuthenticatedWebSessionForIsis;
import org.apache.wicket.Session;
-import org.apache.wicket.request.IRequestParameters;
import org.apache.wicket.request.Request;
import org.apache.wicket.request.Response;
import org.apache.wicket.request.http.WebRequest;
@@ -85,7 +82,7 @@ public class SimpleApplication extends IsisWicketApplication {
protected void init() {
super.init();
- IBootstrapSettings settings = Bootstrap.getSettings();
+ var settings = Bootstrap.getSettings();
settings.setThemeProvider(new BootswatchThemeProvider(BootswatchTheme.Flatly));
}
@@ -96,13 +93,10 @@ public class SimpleApplication extends IsisWicketApplication {
}
// else demo mode
- final AuthenticatedWebSessionForIsis s =
- (AuthenticatedWebSessionForIsis) super.newSession(request, response);
- IRequestParameters requestParameters = request.getRequestParameters();
- final org.apache.wicket.util.string.StringValue user =
- requestParameters.getParameterValue("user");
- final org.apache.wicket.util.string.StringValue password =
- requestParameters.getParameterValue("pass");
+ final var s = (AuthenticatedWebSessionForIsis) super.newSession(request, response);
+ var requestParameters = request.getRequestParameters();
+ final var user = requestParameters.getParameterValue("user");
+ final var password = requestParameters.getParameterValue("pass");
s.signIn(user.toString(), password.toString());
return s;
}
@@ -115,7 +109,7 @@ public class SimpleApplication extends IsisWicketApplication {
// else demo mode
try {
- String uname = servletRequest.getParameter("user");
+ var uname = servletRequest.getParameter("user");
if (uname != null) {
servletRequest.getSession().invalidate();
}
@@ -127,7 +121,7 @@ public class SimpleApplication extends IsisWicketApplication {
@Override
protected Module newIsisWicketModule() {
- final Module isisDefaults = super.newIsisWicketModule();
+ final var isisDefaults = super.newIsisWicketModule();
final Module overrides = new AbstractModule() {
@Override
@@ -148,11 +142,11 @@ public class SimpleApplication extends IsisWicketApplication {
return Modules.override(isisDefaults).with(overrides);
}
+ @SuppressWarnings({"UnstableApiUsage", "SameParameterValue"})
private static String readLines(final Class> contextClass, final String resourceName) {
try {
- List readLines =
- Resources.readLines(Resources.getResource(contextClass, resourceName),
- Charset.defaultCharset());
+ var resource = Resources.getResource(contextClass, resourceName);
+ var readLines = Resources.readLines(resource, Charset.defaultCharset());
return Joiner.on("\n").join(readLines);
} catch (IOException e) {
return "This is a simple app";
diff --git a/naked-objects/webapp/src/main/webapp/about/index.html b/naked-objects/webapp/src/main/webapp/about/index.html
index e929c5b6d..4579f3d0b 100644
--- a/naked-objects/webapp/src/main/webapp/about/index.html
+++ b/naked-objects/webapp/src/main/webapp/about/index.html
@@ -110,8 +110,8 @@ th, td {
provides access to a RESTful API conformant with the
- Restful Objects spec. This is part of Apache Isis Core. The
- implementation technology is JBoss RestEasy.
+ Restful Objects spec. This is part of Apache Isis Core.
+ The implementation technology is JBoss RestEasy.
diff --git a/null-object/README.md b/null-object/README.md
index 0fce86f0e..f5d92a7fc 100644
--- a/null-object/README.md
+++ b/null-object/README.md
@@ -101,7 +101,7 @@ public class NodeImpl implements Node {
public final class NullNode implements Node {
- private static NullNode instance = new NullNode();
+ private static final NullNode instance = new NullNode();
private NullNode() {
}
@@ -141,11 +141,16 @@ public final class NullNode implements Node {
Then we can construct and traverse the binary tree without errors as follows.
```java
- Node root =
- new NodeImpl("1", new NodeImpl("11", new NodeImpl("111", NullNode.getInstance(),
- NullNode.getInstance()), NullNode.getInstance()), new NodeImpl("12",
- NullNode.getInstance(), new NodeImpl("122", NullNode.getInstance(),
- NullNode.getInstance())));
+ var root = new NodeImpl("1",
+ new NodeImpl("11",
+ new NodeImpl("111", NullNode.getInstance(), NullNode.getInstance()),
+ NullNode.getInstance()
+ ),
+ new NodeImpl("12",
+ NullNode.getInstance(),
+ new NodeImpl("122", NullNode.getInstance(), NullNode.getInstance())
+ )
+ );
root.walk();
// 1
diff --git a/null-object/pom.xml b/null-object/pom.xml
index 7b88fca79..4317ee36a 100644
--- a/null-object/pom.xml
+++ b/null-object/pom.xml
@@ -29,7 +29,7 @@
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
null-object
diff --git a/null-object/src/main/java/com/iluwatar/nullobject/App.java b/null-object/src/main/java/com/iluwatar/nullobject/App.java
index 2826bafd0..cd35a3042 100644
--- a/null-object/src/main/java/com/iluwatar/nullobject/App.java
+++ b/null-object/src/main/java/com/iluwatar/nullobject/App.java
@@ -37,12 +37,16 @@ public class App {
* @param args command line args
*/
public static void main(String[] args) {
-
- Node root =
- new NodeImpl("1", new NodeImpl("11", new NodeImpl("111", NullNode.getInstance(),
- NullNode.getInstance()), NullNode.getInstance()), new NodeImpl("12",
- NullNode.getInstance(), new NodeImpl("122", NullNode.getInstance(),
- NullNode.getInstance())));
+ var root = new NodeImpl("1",
+ new NodeImpl("11",
+ new NodeImpl("111", NullNode.getInstance(), NullNode.getInstance()),
+ NullNode.getInstance()
+ ),
+ new NodeImpl("12",
+ NullNode.getInstance(),
+ new NodeImpl("122", NullNode.getInstance(), NullNode.getInstance())
+ )
+ );
root.walk();
}
diff --git a/null-object/src/main/java/com/iluwatar/nullobject/NullNode.java b/null-object/src/main/java/com/iluwatar/nullobject/NullNode.java
index 9b28c249b..472a1a2fd 100644
--- a/null-object/src/main/java/com/iluwatar/nullobject/NullNode.java
+++ b/null-object/src/main/java/com/iluwatar/nullobject/NullNode.java
@@ -30,7 +30,7 @@ package com.iluwatar.nullobject;
*/
public final class NullNode implements Node {
- private static NullNode instance = new NullNode();
+ private static final NullNode instance = new NullNode();
private NullNode() {
}
diff --git a/null-object/src/test/java/com/iluwatar/nullobject/AppTest.java b/null-object/src/test/java/com/iluwatar/nullobject/AppTest.java
index 97d6b5eef..27724a724 100644
--- a/null-object/src/test/java/com/iluwatar/nullobject/AppTest.java
+++ b/null-object/src/test/java/com/iluwatar/nullobject/AppTest.java
@@ -25,16 +25,15 @@ package com.iluwatar.nullobject;
import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+
/**
- *
* Application test
- *
*/
-public class AppTest {
+class AppTest {
@Test
- public void test() {
- String[] args = {};
- App.main(args);
+ void shouldExecuteApplicationWithoutException() {
+ assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
diff --git a/null-object/src/test/java/com/iluwatar/nullobject/NullNodeTest.java b/null-object/src/test/java/com/iluwatar/nullobject/NullNodeTest.java
index b4d9f72d0..5862d1e1a 100644
--- a/null-object/src/test/java/com/iluwatar/nullobject/NullNodeTest.java
+++ b/null-object/src/test/java/com/iluwatar/nullobject/NullNodeTest.java
@@ -35,30 +35,29 @@ import static org.junit.jupiter.api.Assertions.assertSame;
*
* @author Jeroen Meulemeester
*/
-public class NullNodeTest {
+class NullNodeTest {
/**
* Verify if {@link NullNode#getInstance()} actually returns the same object instance
*/
@Test
- public void testGetInstance() {
- final NullNode instance = NullNode.getInstance();
+ void testGetInstance() {
+ final var instance = NullNode.getInstance();
assertNotNull(instance);
assertSame(instance, NullNode.getInstance());
}
@Test
- public void testFields() {
- final NullNode node = NullNode.getInstance();
+ void testFields() {
+ final var node = NullNode.getInstance();
assertEquals(0, node.getTreeSize());
assertNull(node.getName());
assertNull(node.getLeft());
assertNull(node.getRight());
}
- @Test
- public void testWalk() {
- NullNode.getInstance().walk();
- }
+ /**
+ * Removed unnecessary test method for {@link NullNode#walk()} as the method doesn't have an implementation.
+ */
}
diff --git a/null-object/src/test/java/com/iluwatar/nullobject/TreeTest.java b/null-object/src/test/java/com/iluwatar/nullobject/TreeTest.java
index 4ff30f524..9a2b485d0 100644
--- a/null-object/src/test/java/com/iluwatar/nullobject/TreeTest.java
+++ b/null-object/src/test/java/com/iluwatar/nullobject/TreeTest.java
@@ -23,22 +23,21 @@
package com.iluwatar.nullobject;
-import ch.qos.logback.classic.Logger;
-import ch.qos.logback.classic.spi.ILoggingEvent;
-import ch.qos.logback.core.AppenderBase;
-import org.junit.jupiter.api.AfterEach;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import org.slf4j.LoggerFactory;
-
-import java.util.LinkedList;
-import java.util.List;
-
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
+import ch.qos.logback.classic.Logger;
+import ch.qos.logback.classic.spi.ILoggingEvent;
+import ch.qos.logback.core.AppenderBase;
+import java.util.LinkedList;
+import java.util.List;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.slf4j.LoggerFactory;
+
/**
* Date: 12/26/15 - 11:44 PM
*
@@ -75,12 +74,12 @@ public class TreeTest {
private static final Node TREE_ROOT;
static {
- final NodeImpl level1B = new NodeImpl("level1_b", NullNode.getInstance(), NullNode.getInstance());
- final NodeImpl level2B = new NodeImpl("level2_b", NullNode.getInstance(), NullNode.getInstance());
- final NodeImpl level3A = new NodeImpl("level3_a", NullNode.getInstance(), NullNode.getInstance());
- final NodeImpl level3B = new NodeImpl("level3_b", NullNode.getInstance(), NullNode.getInstance());
- final NodeImpl level2A = new NodeImpl("level2_a", level3A, level3B);
- final NodeImpl level1A = new NodeImpl("level1_a", level2A, level2B);
+ final var level1B = new NodeImpl("level1_b", NullNode.getInstance(), NullNode.getInstance());
+ final var level2B = new NodeImpl("level2_b", NullNode.getInstance(), NullNode.getInstance());
+ final var level3A = new NodeImpl("level3_a", NullNode.getInstance(), NullNode.getInstance());
+ final var level3B = new NodeImpl("level3_b", NullNode.getInstance(), NullNode.getInstance());
+ final var level2A = new NodeImpl("level2_a", level3A, level3B);
+ final var level1A = new NodeImpl("level1_a", level2A, level2B);
TREE_ROOT = new NodeImpl("root", level1A, level1B);
}
@@ -112,17 +111,17 @@ public class TreeTest {
@Test
public void testGetLeft() {
- final Node level1 = TREE_ROOT.getLeft();
+ final var level1 = TREE_ROOT.getLeft();
assertNotNull(level1);
assertEquals("level1_a", level1.getName());
assertEquals(5, level1.getTreeSize());
- final Node level2 = level1.getLeft();
+ final var level2 = level1.getLeft();
assertNotNull(level2);
assertEquals("level2_a", level2.getName());
assertEquals(3, level2.getTreeSize());
- final Node level3 = level2.getLeft();
+ final var level3 = level2.getLeft();
assertNotNull(level3);
assertEquals("level3_a", level3.getName());
assertEquals(1, level3.getTreeSize());
@@ -132,7 +131,7 @@ public class TreeTest {
@Test
public void testGetRight() {
- final Node level1 = TREE_ROOT.getRight();
+ final var level1 = TREE_ROOT.getRight();
assertNotNull(level1);
assertEquals("level1_b", level1.getName());
assertEquals(1, level1.getTreeSize());
@@ -140,8 +139,8 @@ public class TreeTest {
assertSame(NullNode.getInstance(), level1.getLeft());
}
- private class InMemoryAppender extends AppenderBase {
- private List log = new LinkedList<>();
+ private static class InMemoryAppender extends AppenderBase {
+ private final List log = new LinkedList<>();
public InMemoryAppender() {
((Logger) LoggerFactory.getLogger("root")).addAppender(this);
@@ -154,7 +153,7 @@ public class TreeTest {
}
public boolean logContains(String message) {
- return log.stream().anyMatch(event -> event.getMessage().equals(message));
+ return log.stream().map(ILoggingEvent::getMessage).anyMatch(message::equals);
}
public int getLogSize() {
diff --git a/object-mother/pom.xml b/object-mother/pom.xml
index 5ac3ce410..f9ca156ad 100644
--- a/object-mother/pom.xml
+++ b/object-mother/pom.xml
@@ -30,7 +30,7 @@
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
object-mother
diff --git a/object-mother/src/main/java/com/iluwatar/objectmother/Queen.java b/object-mother/src/main/java/com/iluwatar/objectmother/Queen.java
index 4c704f6b1..308760ba9 100644
--- a/object-mother/src/main/java/com/iluwatar/objectmother/Queen.java
+++ b/object-mother/src/main/java/com/iluwatar/objectmother/Queen.java
@@ -66,9 +66,6 @@ public class Queen implements Royalty {
* @return A value which describes if the flirt was successful or not.
*/
public boolean getFlirted(King king) {
- if (this.isFlirty && king.isHappy && !king.isDrunk) {
- return true;
- }
- return false;
+ return this.isFlirty && king.isHappy && !king.isDrunk;
}
}
diff --git a/object-pool/README.md b/object-pool/README.md
index a8a20638c..34d216a02 100644
--- a/object-pool/README.md
+++ b/object-pool/README.md
@@ -36,7 +36,7 @@ Here's the basic Oliphaunt class. These are very expensive to create.
```java
public class Oliphaunt {
- private static AtomicInteger counter = new AtomicInteger(0);
+ private static final AtomicInteger counter = new AtomicInteger(0);
private final int id;
@@ -65,8 +65,8 @@ Next we present the Object Pool and more specifically Oliphaunt Pool.
```java
public abstract class ObjectPool {
- private Set available = new HashSet<>();
- private Set inUse = new HashSet<>();
+ private final Set available = new HashSet<>();
+ private final Set inUse = new HashSet<>();
protected abstract T create();
diff --git a/object-pool/pom.xml b/object-pool/pom.xml
index 2adad8942..0587c3968 100644
--- a/object-pool/pom.xml
+++ b/object-pool/pom.xml
@@ -29,7 +29,7 @@
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
object-pool
diff --git a/object-pool/src/main/java/com/iluwatar/object/pool/App.java b/object-pool/src/main/java/com/iluwatar/object/pool/App.java
index cbfc7dea5..48957ce24 100644
--- a/object-pool/src/main/java/com/iluwatar/object/pool/App.java
+++ b/object-pool/src/main/java/com/iluwatar/object/pool/App.java
@@ -57,12 +57,14 @@ public class App {
var pool = new OliphauntPool();
LOGGER.info(pool.toString());
var oliphaunt1 = pool.checkOut();
- LOGGER.info("Checked out {}", oliphaunt1);
+ String checkedOut = "Checked out {}";
+
+ LOGGER.info(checkedOut, oliphaunt1);
LOGGER.info(pool.toString());
var oliphaunt2 = pool.checkOut();
- LOGGER.info("Checked out {}", oliphaunt2);
+ LOGGER.info(checkedOut, oliphaunt2);
var oliphaunt3 = pool.checkOut();
- LOGGER.info("Checked out {}", oliphaunt3);
+ LOGGER.info(checkedOut, oliphaunt3);
LOGGER.info(pool.toString());
LOGGER.info("Checking in {}", oliphaunt1);
pool.checkIn(oliphaunt1);
@@ -70,9 +72,9 @@ public class App {
pool.checkIn(oliphaunt2);
LOGGER.info(pool.toString());
var oliphaunt4 = pool.checkOut();
- LOGGER.info("Checked out {}", oliphaunt4);
+ LOGGER.info(checkedOut, oliphaunt4);
var oliphaunt5 = pool.checkOut();
- LOGGER.info("Checked out {}", oliphaunt5);
+ LOGGER.info(checkedOut, oliphaunt5);
LOGGER.info(pool.toString());
}
}
diff --git a/object-pool/src/main/java/com/iluwatar/object/pool/ObjectPool.java b/object-pool/src/main/java/com/iluwatar/object/pool/ObjectPool.java
index b8ce3cc05..43ac5d873 100644
--- a/object-pool/src/main/java/com/iluwatar/object/pool/ObjectPool.java
+++ b/object-pool/src/main/java/com/iluwatar/object/pool/ObjectPool.java
@@ -33,8 +33,8 @@ import java.util.Set;
*/
public abstract class ObjectPool {
- private Set available = new HashSet<>();
- private Set inUse = new HashSet<>();
+ private final Set available = new HashSet<>();
+ private final Set inUse = new HashSet<>();
protected abstract T create();
diff --git a/object-pool/src/main/java/com/iluwatar/object/pool/Oliphaunt.java b/object-pool/src/main/java/com/iluwatar/object/pool/Oliphaunt.java
index 42db07158..09dedbab0 100644
--- a/object-pool/src/main/java/com/iluwatar/object/pool/Oliphaunt.java
+++ b/object-pool/src/main/java/com/iluwatar/object/pool/Oliphaunt.java
@@ -30,7 +30,7 @@ import java.util.concurrent.atomic.AtomicInteger;
*/
public class Oliphaunt {
- private static AtomicInteger counter = new AtomicInteger(0);
+ private static final AtomicInteger counter = new AtomicInteger(0);
private final int id;
diff --git a/object-pool/src/test/java/com/iluwatar/object/pool/AppTest.java b/object-pool/src/test/java/com/iluwatar/object/pool/AppTest.java
index 7113f9304..f36563a8c 100644
--- a/object-pool/src/test/java/com/iluwatar/object/pool/AppTest.java
+++ b/object-pool/src/test/java/com/iluwatar/object/pool/AppTest.java
@@ -30,11 +30,10 @@ import org.junit.jupiter.api.Test;
* Application test
*
*/
-public class AppTest {
+class AppTest {
@Test
- public void test() {
- String[] args = {};
- App.main(args);
+ void shouldExecuteApplicationWithoutException() {
+ App.main(new String[]{});
}
}
diff --git a/observer/README.md b/observer/README.md
index edc72ae24..d0ddf3c00 100644
--- a/observer/README.md
+++ b/observer/README.md
@@ -13,18 +13,18 @@ tags:
Dependents, Publish-Subscribe
## Intent
-Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified
+Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified
and updated automatically.
## Explanation
Real world example
-> In a land far away lives the races of hobbits and orcs. Both of them are mostly outdoors so they closely follow the changes in weather. One could say that they are constantly observing the weather.
+> In a land far away lives the races of hobbits and orcs. Both of them are mostly outdoors so they closely follow the changes in weather. One could say that they are constantly observing the weather.
In plain words
-> Register as an observer to receive state changes in the object.
+> Register as an observer to receive state changes in the object.
Wikipedia says
@@ -46,22 +46,7 @@ public class Orcs implements WeatherObserver {
@Override
public void update(WeatherType currentWeather) {
- switch (currentWeather) {
- case COLD:
- LOGGER.info("The orcs are freezing cold.");
- break;
- case RAINY:
- LOGGER.info("The orcs are dripping wet.");
- break;
- case SUNNY:
- LOGGER.info("The sun hurts the orcs' eyes.");
- break;
- case WINDY:
- LOGGER.info("The orc smell almost vanishes in the wind.");
- break;
- default:
- break;
- }
+ LOGGER.info("The orcs are facing " + currentWeather.getDescription() + " weather now");
}
}
@@ -72,21 +57,7 @@ public class Hobbits implements WeatherObserver {
@Override
public void update(WeatherType currentWeather) {
switch (currentWeather) {
- case COLD:
- LOGGER.info("The hobbits are shivering in the cold weather.");
- break;
- case RAINY:
- LOGGER.info("The hobbits look for cover from the rain.");
- break;
- case SUNNY:
- LOGGER.info("The happy hobbits bade in the warm sun.");
- break;
- case WINDY:
- LOGGER.info("The hobbits hold their hats tightly in the windy weather.");
- break;
- default:
- break;
- }
+ LOGGER.info("The hobbits are facing " + currentWeather.getDescription() + " weather now");
}
}
```
@@ -99,7 +70,7 @@ public class Weather {
private static final Logger LOGGER = LoggerFactory.getLogger(Weather.class);
private WeatherType currentWeather;
- private List observers;
+ private final List observers;
public Weather() {
observers = new ArrayList<>();
@@ -141,20 +112,20 @@ Here's the full example in action.
weather.timePasses();
// The weather changed to rainy.
- // The orcs are dripping wet.
- // The hobbits look for cover from the rain.
+ // The orcs are facing rainy weather now
+ // The hobbits are facing rainy weather now
weather.timePasses();
// The weather changed to windy.
- // The orc smell almost vanishes in the wind.
- // The hobbits hold their hats tightly in the windy weather.
+ // The orcs are facing windy weather now
+ // The hobbits are facing windy weather now
weather.timePasses();
// The weather changed to cold.
- // The orcs are freezing cold.
- // The hobbits are shivering in the cold weather.
+ // The orcs are facing cold weather now
+ // The hobbits are facing cold weather now
weather.timePasses();
// The weather changed to sunny.
- // The sun hurts the orcs' eyes.
- // The happy hobbits bade in the warm sun.
+ // The orcs are facing sunny weather now
+ // The hobbits are facing sunny weather now
```
## Class diagram
diff --git a/observer/etc/observer.urm.puml b/observer/etc/observer.urm.puml
index bea9aab53..497ef5fde 100644
--- a/observer/etc/observer.urm.puml
+++ b/observer/etc/observer.urm.puml
@@ -33,7 +33,9 @@ package com.iluwatar.observer {
+ RAINY {static}
+ SUNNY {static}
+ WINDY {static}
+ + description String
+ toString() : String
+ + getDescription() : String
+ valueOf(name : String) : WeatherType {static}
+ values() : WeatherType[] {static}
}
@@ -71,10 +73,10 @@ package com.iluwatar.observer.generic {
Weather --> "-currentWeather" WeatherType
GWeather --> "-currentWeather" WeatherType
Weather --> "-observers" WeatherObserver
-Hobbits ..|> WeatherObserver
-Orcs ..|> WeatherObserver
-GHobbits ..|> Race
-GOrcs ..|> Race
-GWeather --|> Observable
-Race --|> Observer
-@enduml
\ No newline at end of file
+Hobbits ..|> WeatherObserver
+Orcs ..|> WeatherObserver
+GHobbits ..|> Race
+GOrcs ..|> Race
+GWeather --|> Observable
+Race --|> Observer
+@enduml
diff --git a/observer/etc/observer_with_generics.png b/observer/etc/observer_with_generics.png
new file mode 100644
index 000000000..06ff0d9cc
Binary files /dev/null and b/observer/etc/observer_with_generics.png differ
diff --git a/observer/pom.xml b/observer/pom.xml
index 1e48268d8..c558992ac 100644
--- a/observer/pom.xml
+++ b/observer/pom.xml
@@ -29,7 +29,7 @@
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
observer
diff --git a/observer/src/main/java/com/iluwatar/observer/Hobbits.java b/observer/src/main/java/com/iluwatar/observer/Hobbits.java
index 646ceebfd..5894c93a6 100644
--- a/observer/src/main/java/com/iluwatar/observer/Hobbits.java
+++ b/observer/src/main/java/com/iluwatar/observer/Hobbits.java
@@ -35,21 +35,6 @@ public class Hobbits implements WeatherObserver {
@Override
public void update(WeatherType currentWeather) {
- switch (currentWeather) {
- case COLD:
- LOGGER.info("The hobbits are shivering in the cold weather.");
- break;
- case RAINY:
- LOGGER.info("The hobbits look for cover from the rain.");
- break;
- case SUNNY:
- LOGGER.info("The happy hobbits bade in the warm sun.");
- break;
- case WINDY:
- LOGGER.info("The hobbits hold their hats tightly in the windy weather.");
- break;
- default:
- break;
- }
+ LOGGER.info("The hobbits are facing " + currentWeather.getDescription() + " weather now");
}
}
diff --git a/observer/src/main/java/com/iluwatar/observer/Orcs.java b/observer/src/main/java/com/iluwatar/observer/Orcs.java
index a28ffbc5b..1a955aafd 100644
--- a/observer/src/main/java/com/iluwatar/observer/Orcs.java
+++ b/observer/src/main/java/com/iluwatar/observer/Orcs.java
@@ -35,21 +35,6 @@ public class Orcs implements WeatherObserver {
@Override
public void update(WeatherType currentWeather) {
- switch (currentWeather) {
- case COLD:
- LOGGER.info("The orcs are freezing cold.");
- break;
- case RAINY:
- LOGGER.info("The orcs are dripping wet.");
- break;
- case SUNNY:
- LOGGER.info("The sun hurts the orcs' eyes.");
- break;
- case WINDY:
- LOGGER.info("The orc smell almost vanishes in the wind.");
- break;
- default:
- break;
- }
+ LOGGER.info("The orcs are facing " + currentWeather.getDescription() + " weather now");
}
}
diff --git a/observer/src/main/java/com/iluwatar/observer/Weather.java b/observer/src/main/java/com/iluwatar/observer/Weather.java
index 778858107..a0d80d6bc 100644
--- a/observer/src/main/java/com/iluwatar/observer/Weather.java
+++ b/observer/src/main/java/com/iluwatar/observer/Weather.java
@@ -37,7 +37,7 @@ public class Weather {
private static final Logger LOGGER = LoggerFactory.getLogger(Weather.class);
private WeatherType currentWeather;
- private List observers;
+ private final List observers;
public Weather() {
observers = new ArrayList<>();
diff --git a/observer/src/main/java/com/iluwatar/observer/WeatherType.java b/observer/src/main/java/com/iluwatar/observer/WeatherType.java
index 75ee17d60..e11317c21 100644
--- a/observer/src/main/java/com/iluwatar/observer/WeatherType.java
+++ b/observer/src/main/java/com/iluwatar/observer/WeatherType.java
@@ -28,7 +28,20 @@ package com.iluwatar.observer;
*/
public enum WeatherType {
- SUNNY, RAINY, WINDY, COLD;
+ SUNNY("Sunny"),
+ RAINY("Rainy"),
+ WINDY("Windy"),
+ COLD("Cold");
+
+ private final String description;
+
+ WeatherType(String description) {
+ this.description = description;
+ }
+
+ public String getDescription() {
+ return this.description;
+ }
@Override
public String toString() {
diff --git a/observer/src/main/java/com/iluwatar/observer/generic/GHobbits.java b/observer/src/main/java/com/iluwatar/observer/generic/GHobbits.java
index 7a555d850..90fd4e300 100644
--- a/observer/src/main/java/com/iluwatar/observer/generic/GHobbits.java
+++ b/observer/src/main/java/com/iluwatar/observer/generic/GHobbits.java
@@ -36,21 +36,6 @@ public class GHobbits implements Race {
@Override
public void update(GWeather weather, WeatherType weatherType) {
- switch (weatherType) {
- case COLD:
- LOGGER.info("The hobbits are shivering in the cold weather.");
- break;
- case RAINY:
- LOGGER.info("The hobbits look for cover from the rain.");
- break;
- case SUNNY:
- LOGGER.info("The happy hobbits bade in the warm sun.");
- break;
- case WINDY:
- LOGGER.info("The hobbits hold their hats tightly in the windy weather.");
- break;
- default:
- break;
- }
+ LOGGER.info("The hobbits are facing " + weatherType.getDescription() + " weather now");
}
}
diff --git a/observer/src/main/java/com/iluwatar/observer/generic/GOrcs.java b/observer/src/main/java/com/iluwatar/observer/generic/GOrcs.java
index d9adbf116..bc49c4e30 100644
--- a/observer/src/main/java/com/iluwatar/observer/generic/GOrcs.java
+++ b/observer/src/main/java/com/iluwatar/observer/generic/GOrcs.java
@@ -36,21 +36,6 @@ public class GOrcs implements Race {
@Override
public void update(GWeather weather, WeatherType weatherType) {
- switch (weatherType) {
- case COLD:
- LOGGER.info("The orcs are freezing cold.");
- break;
- case RAINY:
- LOGGER.info("The orcs are dripping wet.");
- break;
- case SUNNY:
- LOGGER.info("The sun hurts the orcs' eyes.");
- break;
- case WINDY:
- LOGGER.info("The orc smell almost vanishes in the wind.");
- break;
- default:
- break;
- }
+ LOGGER.info("The orcs are facing " + weatherType.getDescription() + " weather now");
}
}
diff --git a/observer/src/test/java/com/iluwatar/observer/AppTest.java b/observer/src/test/java/com/iluwatar/observer/AppTest.java
index b557fdf7e..6b1f426d6 100644
--- a/observer/src/test/java/com/iluwatar/observer/AppTest.java
+++ b/observer/src/test/java/com/iluwatar/observer/AppTest.java
@@ -25,16 +25,17 @@ package com.iluwatar.observer;
import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+
/**
*
* Application test
*
*/
-public class AppTest {
+class AppTest {
@Test
- public void test() {
- String[] args = {};
- App.main(args);
+ void shouldExecuteApplicationWithoutException() {
+ assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
diff --git a/observer/src/test/java/com/iluwatar/observer/HobbitsTest.java b/observer/src/test/java/com/iluwatar/observer/HobbitsTest.java
index 66ec45fdb..345b8e331 100644
--- a/observer/src/test/java/com/iluwatar/observer/HobbitsTest.java
+++ b/observer/src/test/java/com/iluwatar/observer/HobbitsTest.java
@@ -36,10 +36,10 @@ public class HobbitsTest extends WeatherObserverTest {
@Override
public Collection dataProvider() {
return List.of(
- new Object[]{WeatherType.SUNNY, "The happy hobbits bade in the warm sun."},
- new Object[]{WeatherType.RAINY, "The hobbits look for cover from the rain."},
- new Object[]{WeatherType.WINDY, "The hobbits hold their hats tightly in the windy weather."},
- new Object[]{WeatherType.COLD, "The hobbits are shivering in the cold weather."});
+ new Object[]{WeatherType.SUNNY, "The hobbits are facing Sunny weather now"},
+ new Object[]{WeatherType.RAINY, "The hobbits are facing Rainy weather now"},
+ new Object[]{WeatherType.WINDY, "The hobbits are facing Windy weather now"},
+ new Object[]{WeatherType.COLD, "The hobbits are facing Cold weather now"});
}
/**
diff --git a/observer/src/test/java/com/iluwatar/observer/OrcsTest.java b/observer/src/test/java/com/iluwatar/observer/OrcsTest.java
index ff615df3c..65beeaf0e 100644
--- a/observer/src/test/java/com/iluwatar/observer/OrcsTest.java
+++ b/observer/src/test/java/com/iluwatar/observer/OrcsTest.java
@@ -36,10 +36,10 @@ public class OrcsTest extends WeatherObserverTest {
@Override
public Collection dataProvider() {
return List.of(
- new Object[]{WeatherType.SUNNY, "The sun hurts the orcs' eyes."},
- new Object[]{WeatherType.RAINY, "The orcs are dripping wet."},
- new Object[]{WeatherType.WINDY, "The orc smell almost vanishes in the wind."},
- new Object[]{WeatherType.COLD, "The orcs are freezing cold."});
+ new Object[]{WeatherType.SUNNY, "The orcs are facing Sunny weather now"},
+ new Object[]{WeatherType.RAINY, "The orcs are facing Rainy weather now"},
+ new Object[]{WeatherType.WINDY, "The orcs are facing Windy weather now"},
+ new Object[]{WeatherType.COLD, "The orcs are facing Cold weather now"});
}
/**
diff --git a/observer/src/test/java/com/iluwatar/observer/generic/GHobbitsTest.java b/observer/src/test/java/com/iluwatar/observer/generic/GHobbitsTest.java
index dd0e6d6bf..756d72239 100644
--- a/observer/src/test/java/com/iluwatar/observer/generic/GHobbitsTest.java
+++ b/observer/src/test/java/com/iluwatar/observer/generic/GHobbitsTest.java
@@ -38,10 +38,10 @@ public class GHobbitsTest extends ObserverTest {
@Override
public Collection dataProvider() {
return List.of(
- new Object[]{WeatherType.SUNNY, "The happy hobbits bade in the warm sun."},
- new Object[]{WeatherType.RAINY, "The hobbits look for cover from the rain."},
- new Object[]{WeatherType.WINDY, "The hobbits hold their hats tightly in the windy weather."},
- new Object[]{WeatherType.COLD, "The hobbits are shivering in the cold weather."}
+ new Object[]{WeatherType.SUNNY, "The hobbits are facing Sunny weather now"},
+ new Object[]{WeatherType.RAINY, "The hobbits are facing Rainy weather now"},
+ new Object[]{WeatherType.WINDY, "The hobbits are facing Windy weather now"},
+ new Object[]{WeatherType.COLD, "The hobbits are facing Cold weather now"}
);
}
diff --git a/observer/src/test/java/com/iluwatar/observer/generic/OrcsTest.java b/observer/src/test/java/com/iluwatar/observer/generic/OrcsTest.java
index 396de4456..523678288 100644
--- a/observer/src/test/java/com/iluwatar/observer/generic/OrcsTest.java
+++ b/observer/src/test/java/com/iluwatar/observer/generic/OrcsTest.java
@@ -38,10 +38,10 @@ public class OrcsTest extends ObserverTest {
@Override
public Collection dataProvider() {
return List.of(
- new Object[]{WeatherType.SUNNY, "The sun hurts the orcs' eyes."},
- new Object[]{WeatherType.RAINY, "The orcs are dripping wet."},
- new Object[]{WeatherType.WINDY, "The orc smell almost vanishes in the wind."},
- new Object[]{WeatherType.COLD, "The orcs are freezing cold."}
+ new Object[]{WeatherType.SUNNY, "The orcs are facing Sunny weather now"},
+ new Object[]{WeatherType.RAINY, "The orcs are facing Rainy weather now"},
+ new Object[]{WeatherType.WINDY, "The orcs are facing Windy weather now"},
+ new Object[]{WeatherType.COLD, "The orcs are facing Cold weather now"}
);
}
diff --git a/observer/src/test/java/com/iluwatar/observer/utils/InMemoryAppender.java b/observer/src/test/java/com/iluwatar/observer/utils/InMemoryAppender.java
index b3d2bf1bc..132216d19 100644
--- a/observer/src/test/java/com/iluwatar/observer/utils/InMemoryAppender.java
+++ b/observer/src/test/java/com/iluwatar/observer/utils/InMemoryAppender.java
@@ -35,7 +35,7 @@ import java.util.List;
* InMemory Log Appender Util.
*/
public class InMemoryAppender extends AppenderBase {
- private List log = new LinkedList<>();
+ private final List log = new LinkedList<>();
public InMemoryAppender(Class clazz) {
((Logger) LoggerFactory.getLogger(clazz)).addAppender(this);
diff --git a/page-object/pom.xml b/page-object/pom.xml
index 4bf31d72e..a91843121 100644
--- a/page-object/pom.xml
+++ b/page-object/pom.xml
@@ -46,7 +46,7 @@
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
page-object
pom
diff --git a/page-object/sample-application/pom.xml b/page-object/sample-application/pom.xml
index 5ded184cc..6748a4063 100644
--- a/page-object/sample-application/pom.xml
+++ b/page-object/sample-application/pom.xml
@@ -29,7 +29,7 @@
page-object
com.iluwatar
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
sample-application
diff --git a/page-object/src/test/java/com/iluwatar/pageobject/AlbumListPageTest.java b/page-object/src/test/java/com/iluwatar/pageobject/AlbumListPageTest.java
index 779458e05..22bc8a5fb 100644
--- a/page-object/src/test/java/com/iluwatar/pageobject/AlbumListPageTest.java
+++ b/page-object/src/test/java/com/iluwatar/pageobject/AlbumListPageTest.java
@@ -36,7 +36,7 @@ import org.junit.jupiter.api.Test;
*/
public class AlbumListPageTest {
- private AlbumListPage albumListPage = new AlbumListPage(new WebClient());
+ private final AlbumListPage albumListPage = new AlbumListPage(new WebClient());
@BeforeEach
public void setUp() {
diff --git a/page-object/src/test/java/com/iluwatar/pageobject/AlbumPageTest.java b/page-object/src/test/java/com/iluwatar/pageobject/AlbumPageTest.java
index 601093343..68c836bd3 100644
--- a/page-object/src/test/java/com/iluwatar/pageobject/AlbumPageTest.java
+++ b/page-object/src/test/java/com/iluwatar/pageobject/AlbumPageTest.java
@@ -36,7 +36,7 @@ import org.junit.jupiter.api.Test;
*/
public class AlbumPageTest {
- private AlbumPage albumPage = new AlbumPage(new WebClient());
+ private final AlbumPage albumPage = new AlbumPage(new WebClient());
@BeforeEach
public void setUp() {
diff --git a/page-object/src/test/java/com/iluwatar/pageobject/LoginPageTest.java b/page-object/src/test/java/com/iluwatar/pageobject/LoginPageTest.java
index 022f736ca..460bdcf96 100644
--- a/page-object/src/test/java/com/iluwatar/pageobject/LoginPageTest.java
+++ b/page-object/src/test/java/com/iluwatar/pageobject/LoginPageTest.java
@@ -36,7 +36,7 @@ import org.junit.jupiter.api.Test;
*/
public class LoginPageTest {
- private LoginPage loginPage = new LoginPage(new WebClient());
+ private final LoginPage loginPage = new LoginPage(new WebClient());
@BeforeEach
public void setUp() {
diff --git a/page-object/test-automation/pom.xml b/page-object/test-automation/pom.xml
index 68025f4b8..5f64807de 100644
--- a/page-object/test-automation/pom.xml
+++ b/page-object/test-automation/pom.xml
@@ -29,7 +29,7 @@
page-object
com.iluwatar
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
test-automation
diff --git a/page-object/test-automation/src/test/java/com/iluwatar/pageobject/AlbumListPageTest.java b/page-object/test-automation/src/test/java/com/iluwatar/pageobject/AlbumListPageTest.java
index d1b450a24..1acdd5ba5 100644
--- a/page-object/test-automation/src/test/java/com/iluwatar/pageobject/AlbumListPageTest.java
+++ b/page-object/test-automation/src/test/java/com/iluwatar/pageobject/AlbumListPageTest.java
@@ -34,7 +34,7 @@ import org.junit.jupiter.api.Test;
*/
public class AlbumListPageTest {
- private AlbumListPage albumListPage = new AlbumListPage(new WebClient());
+ private final AlbumListPage albumListPage = new AlbumListPage(new WebClient());
@BeforeEach
public void setUp() {
diff --git a/page-object/test-automation/src/test/java/com/iluwatar/pageobject/AlbumPageTest.java b/page-object/test-automation/src/test/java/com/iluwatar/pageobject/AlbumPageTest.java
index 8e694a592..ecde999c3 100644
--- a/page-object/test-automation/src/test/java/com/iluwatar/pageobject/AlbumPageTest.java
+++ b/page-object/test-automation/src/test/java/com/iluwatar/pageobject/AlbumPageTest.java
@@ -34,7 +34,7 @@ import org.junit.jupiter.api.Test;
*/
public class AlbumPageTest {
- private AlbumPage albumPage = new AlbumPage(new WebClient());
+ private final AlbumPage albumPage = new AlbumPage(new WebClient());
@BeforeEach
public void setUp() {
diff --git a/page-object/test-automation/src/test/java/com/iluwatar/pageobject/LoginPageTest.java b/page-object/test-automation/src/test/java/com/iluwatar/pageobject/LoginPageTest.java
index 89668882d..429b7fcc5 100644
--- a/page-object/test-automation/src/test/java/com/iluwatar/pageobject/LoginPageTest.java
+++ b/page-object/test-automation/src/test/java/com/iluwatar/pageobject/LoginPageTest.java
@@ -34,7 +34,7 @@ import org.junit.jupiter.api.Test;
*/
public class LoginPageTest {
- private LoginPage loginPage = new LoginPage(new WebClient());
+ private final LoginPage loginPage = new LoginPage(new WebClient());
@BeforeEach
public void setUp() {
diff --git a/partial-response/pom.xml b/partial-response/pom.xml
index 83d81bf82..fbece028e 100644
--- a/partial-response/pom.xml
+++ b/partial-response/pom.xml
@@ -29,24 +29,28 @@
java-design-patterns
com.iluwatar
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
4.0.0
partial-response
-
- junit
- junit
-
org.junit.vintage
junit-vintage-engine
+ 5.4.0
test
org.mockito
- mockito-core
+ mockito-junit-jupiter
+ 3.5.0
+ test
+
+
+ org.junit.jupiter
+ junit-jupiter-engine
+ test
diff --git a/partial-response/src/main/java/com/iluwatar/partialresponse/VideoResource.java b/partial-response/src/main/java/com/iluwatar/partialresponse/VideoResource.java
index a61a3c429..11a4f23ca 100644
--- a/partial-response/src/main/java/com/iluwatar/partialresponse/VideoResource.java
+++ b/partial-response/src/main/java/com/iluwatar/partialresponse/VideoResource.java
@@ -30,8 +30,8 @@ import java.util.Map;
* has all video details.
*/
public class VideoResource {
- private FieldJsonMapper fieldJsonMapper;
- private Map videos;
+ private final FieldJsonMapper fieldJsonMapper;
+ private final Map videos;
/**
* Constructor.
diff --git a/partial-response/src/test/java/com/iluwatar/partialresponse/AppTest.java b/partial-response/src/test/java/com/iluwatar/partialresponse/AppTest.java
index d50084a36..c423355f5 100644
--- a/partial-response/src/test/java/com/iluwatar/partialresponse/AppTest.java
+++ b/partial-response/src/test/java/com/iluwatar/partialresponse/AppTest.java
@@ -23,16 +23,17 @@
package com.iluwatar.partialresponse;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Assertions;
/**
* Application test
*/
-public class AppTest {
+class AppTest {
@Test
- public void main() throws Exception {
- App.main(new String[]{});
+ void shouldExecuteApplicationWithoutException() {
+ Assertions.assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
\ No newline at end of file
diff --git a/partial-response/src/test/java/com/iluwatar/partialresponse/FieldJsonMapperTest.java b/partial-response/src/test/java/com/iluwatar/partialresponse/FieldJsonMapperTest.java
index 57741c1d7..6bf5bf190 100644
--- a/partial-response/src/test/java/com/iluwatar/partialresponse/FieldJsonMapperTest.java
+++ b/partial-response/src/test/java/com/iluwatar/partialresponse/FieldJsonMapperTest.java
@@ -23,24 +23,23 @@
package com.iluwatar.partialresponse;
-import static org.junit.Assert.assertEquals;
-
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
/**
* tests {@link FieldJsonMapper}.
*/
-public class FieldJsonMapperTest {
- private FieldJsonMapper mapper;
+class FieldJsonMapperTest {
+ private static FieldJsonMapper mapper;
- @Before
- public void setUp() {
+ @BeforeAll
+ static void setUp() {
mapper = new FieldJsonMapper();
}
@Test
- public void shouldReturnJsonForSpecifiedFieldsInVideo() throws Exception {
+ void shouldReturnJsonForSpecifiedFieldsInVideo() throws Exception {
var fields = new String[]{"id", "title", "length"};
var video = new Video(
2, "Godzilla Resurgence", 120,
@@ -50,6 +49,6 @@ public class FieldJsonMapperTest {
var jsonFieldResponse = mapper.toJson(video, fields);
var expectedDetails = "{\"id\": 2,\"title\": \"Godzilla Resurgence\",\"length\": 120}";
- assertEquals(expectedDetails, jsonFieldResponse);
+ Assertions.assertEquals(expectedDetails, jsonFieldResponse);
}
}
\ No newline at end of file
diff --git a/partial-response/src/test/java/com/iluwatar/partialresponse/VideoResourceTest.java b/partial-response/src/test/java/com/iluwatar/partialresponse/VideoResourceTest.java
index 252499803..dbd8e78dd 100644
--- a/partial-response/src/test/java/com/iluwatar/partialresponse/VideoResourceTest.java
+++ b/partial-response/src/test/java/com/iluwatar/partialresponse/VideoResourceTest.java
@@ -23,30 +23,29 @@
package com.iluwatar.partialresponse;
-import static org.junit.Assert.assertEquals;
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.eq;
-import static org.mockito.Mockito.when;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.Matchers;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.mockito.junit.jupiter.MockitoExtension;
import java.util.Map;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.Mock;
-import org.mockito.runners.MockitoJUnitRunner;
/**
* tests {@link VideoResource}.
*/
-@RunWith(MockitoJUnitRunner.class)
-public class VideoResourceTest {
+@ExtendWith(MockitoExtension.class)
+class VideoResourceTest {
@Mock
- private FieldJsonMapper fieldJsonMapper;
+ private static FieldJsonMapper fieldJsonMapper;
- private VideoResource resource;
+ private static VideoResource resource;
- @Before
- public void setUp() {
+ @BeforeAll
+ static void setUp() {
var videos = Map.of(
1, new Video(1, "Avatar", 178, "epic science fiction film",
"James Cameron", "English"),
@@ -58,23 +57,23 @@ public class VideoResourceTest {
}
@Test
- public void shouldGiveVideoDetailsById() throws Exception {
+ void shouldGiveVideoDetailsById() throws Exception {
var actualDetails = resource.getDetails(1);
var expectedDetails = "{\"id\": 1,\"title\": \"Avatar\",\"length\": 178,\"description\": "
+ "\"epic science fiction film\",\"director\": \"James Cameron\",\"language\": \"English\",}";
- assertEquals(expectedDetails, actualDetails);
+ Assertions.assertEquals(expectedDetails, actualDetails);
}
@Test
- public void shouldGiveSpecifiedFieldsInformationOfVideo() throws Exception {
+ void shouldGiveSpecifiedFieldsInformationOfVideo() throws Exception {
var fields = new String[]{"id", "title", "length"};
var expectedDetails = "{\"id\": 1,\"title\": \"Avatar\",\"length\": 178}";
- when(fieldJsonMapper.toJson(any(Video.class), eq(fields))).thenReturn(expectedDetails);
+ Mockito.when(fieldJsonMapper.toJson(Matchers.any(Video.class), Matchers.eq(fields))).thenReturn(expectedDetails);
var actualFieldsDetails = resource.getDetails(2, fields);
- assertEquals(expectedDetails, actualFieldsDetails);
+ Assertions.assertEquals(expectedDetails, actualFieldsDetails);
}
}
\ No newline at end of file
diff --git a/pipeline/pom.xml b/pipeline/pom.xml
index 8c511cd8a..fca6180bc 100644
--- a/pipeline/pom.xml
+++ b/pipeline/pom.xml
@@ -29,7 +29,7 @@
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
pipeline
diff --git a/pipeline/src/test/java/com/iluwatar/pipeline/AppTest.java b/pipeline/src/test/java/com/iluwatar/pipeline/AppTest.java
index 8ea6a4c60..1316491ad 100644
--- a/pipeline/src/test/java/com/iluwatar/pipeline/AppTest.java
+++ b/pipeline/src/test/java/com/iluwatar/pipeline/AppTest.java
@@ -25,13 +25,15 @@ package com.iluwatar.pipeline;
import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+
/**
* Application Test
*/
-public class AppTest {
+class AppTest {
@Test
- public void test() {
- App.main(new String[]{});
+ void shouldExecuteApplicationWithoutException() {
+ assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
diff --git a/poison-pill/README.md b/poison-pill/README.md
index 823bb7df8..a6cd2fe80 100644
--- a/poison-pill/README.md
+++ b/poison-pill/README.md
@@ -80,7 +80,7 @@ public interface Message {
public class SimpleMessage implements Message {
- private Map headers = new HashMap<>();
+ private final Map headers = new HashMap<>();
private String body;
@Override
diff --git a/poison-pill/pom.xml b/poison-pill/pom.xml
index 4989581d7..c4780fe1b 100644
--- a/poison-pill/pom.xml
+++ b/poison-pill/pom.xml
@@ -29,7 +29,7 @@
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
poison-pill
diff --git a/poison-pill/src/main/java/com/iluwatar/poison/pill/SimpleMessage.java b/poison-pill/src/main/java/com/iluwatar/poison/pill/SimpleMessage.java
index 8a7af515f..70d116c9f 100644
--- a/poison-pill/src/main/java/com/iluwatar/poison/pill/SimpleMessage.java
+++ b/poison-pill/src/main/java/com/iluwatar/poison/pill/SimpleMessage.java
@@ -32,7 +32,7 @@ import java.util.Map;
*/
public class SimpleMessage implements Message {
- private Map headers = new HashMap<>();
+ private final Map headers = new HashMap<>();
private String body;
@Override
diff --git a/poison-pill/src/test/java/com/iluwatar/poison/pill/AppTest.java b/poison-pill/src/test/java/com/iluwatar/poison/pill/AppTest.java
index c23fe5563..50d7a90c9 100644
--- a/poison-pill/src/test/java/com/iluwatar/poison/pill/AppTest.java
+++ b/poison-pill/src/test/java/com/iluwatar/poison/pill/AppTest.java
@@ -25,13 +25,15 @@ package com.iluwatar.poison.pill;
import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+
/**
* Application test
*/
-public class AppTest {
+class AppTest {
@Test
- public void test() {
- App.main(new String[]{});
+ void shouldExecuteApplicationWithoutException() {
+ assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
diff --git a/poison-pill/src/test/java/com/iluwatar/poison/pill/ConsumerTest.java b/poison-pill/src/test/java/com/iluwatar/poison/pill/ConsumerTest.java
index 100565fbc..8365fca17 100644
--- a/poison-pill/src/test/java/com/iluwatar/poison/pill/ConsumerTest.java
+++ b/poison-pill/src/test/java/com/iluwatar/poison/pill/ConsumerTest.java
@@ -92,7 +92,7 @@ public class ConsumerTest {
}
private class InMemoryAppender extends AppenderBase {
- private List log = new LinkedList<>();
+ private final List log = new LinkedList<>();
public InMemoryAppender(Class clazz) {
((Logger) LoggerFactory.getLogger(clazz)).addAppender(this);
diff --git a/pom.xml b/pom.xml
index f23369107..56b955204 100644
--- a/pom.xml
+++ b/pom.xml
@@ -20,7 +20,7 @@
4.0.0
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
pom
2014-2019
@@ -52,13 +52,14 @@
2.3.1
2.3.2
1.3.2
- 1.19.0
- 1.4.8
+ 1.1.0
+ 2.0.0
+ 3.5.0
https://sonarcloud.io
iluwatar
iluwatar_java-design-patterns
- ${artifactId}
+ ${project.artifactId}
Java Design Patterns
@@ -192,6 +193,8 @@
leader-followers
strangler
arrange-act-assert
+ transaction-script
+ filterer
@@ -335,8 +338,8 @@
com.github.stefanbirkner
- system-rules
- ${system-rules.version}
+ system-lambda
+ ${system-lambda.version}
test
@@ -375,10 +378,7 @@
org.apache.maven.plugins
maven-surefire-plugin
- 3.0.0-M3
-
- -Xmx1024M ${argLine}
-
+ 3.0.0-M5
org.springframework.boot
@@ -474,7 +474,7 @@
true
- ${projectRoot}${file.separator}license-plugin-header-style.xml
+ license-plugin-header-style.xml
SLASHSTAR_CUSTOM_STYLE
@@ -540,14 +540,4 @@
-
-
-
- org.apache.maven.plugins
- maven-jxr-plugin
- 3.0.0
-
-
-
-
-
\ No newline at end of file
+
diff --git a/priority-queue/pom.xml b/priority-queue/pom.xml
index 7f435f489..ff04a5359 100644
--- a/priority-queue/pom.xml
+++ b/priority-queue/pom.xml
@@ -31,7 +31,7 @@
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
diff --git a/private-class-data/README.md b/private-class-data/README.md
index 20e343285..d4788d2dd 100644
--- a/private-class-data/README.md
+++ b/private-class-data/README.md
@@ -9,9 +9,119 @@ tags:
---
## Intent
-Private Class Data design pattern seeks to reduce exposure of
-attributes by limiting their visibility. It reduces the number of class
-attributes by encapsulating them in single Data object.
+Private Class Data design pattern seeks to reduce exposure of attributes by limiting their
+visibility. It reduces the number of class attributes by encapsulating them in single Data object.
+
+## Explanation
+
+Real world example
+
+> Imagine you are cooking a stew for your family for dinner. You want to prevent your family members
+> from consuming the stew by tasting it while you are cooking, otherwise there will be no more stew
+> for dinner later.
+
+In plain words
+
+> Private class data pattern prevents manipulation of data that is meant to be immutable by
+> separating the data from the methods that use it into a class that maintains the data state.
+
+Wikipedia says
+
+> Private class data is a design pattern in computer programming used to encapsulate class
+> attributes and their manipulation.
+
+**Programmatic Example**
+
+Taking our stew example from above. First we have a `Stew` class where its data is not protected by
+private class data, making the stew's ingredient mutable to class methods.
+
+```java
+public class Stew {
+ private static final Logger LOGGER = LoggerFactory.getLogger(Stew.class);
+ private int numPotatoes;
+ private int numCarrots;
+ private int numMeat;
+ private int numPeppers;
+ public Stew(int numPotatoes, int numCarrots, int numMeat, int numPeppers) {
+ this.numPotatoes = numPotatoes;
+ this.numCarrots = numCarrots;
+ this.numMeat = numMeat;
+ this.numPeppers = numPeppers;
+ }
+ public void mix() {
+ LOGGER.info("Mixing the stew we find: {} potatoes, {} carrots, {} meat and {} peppers",
+ numPotatoes, numCarrots, numMeat, numPeppers);
+ }
+ public void taste() {
+ LOGGER.info("Tasting the stew");
+ if (numPotatoes > 0) {
+ numPotatoes--;
+ }
+ if (numCarrots > 0) {
+ numCarrots--;
+ }
+ if (numMeat > 0) {
+ numMeat--;
+ }
+ if (numPeppers > 0) {
+ numPeppers--;
+ }
+ }
+}
+```
+
+Now, we have `ImmutableStew` class, where its data is protected by `StewData` class. Now, the
+methods in are unable to manipulate the data of the `ImmutableStew` class.
+
+```java
+public class StewData {
+ private final int numPotatoes;
+ private final int numCarrots;
+ private final int numMeat;
+ private final int numPeppers;
+ public StewData(int numPotatoes, int numCarrots, int numMeat, int numPeppers) {
+ this.numPotatoes = numPotatoes;
+ this.numCarrots = numCarrots;
+ this.numMeat = numMeat;
+ this.numPeppers = numPeppers;
+ }
+ public int getNumPotatoes() {
+ return numPotatoes;
+ }
+ public int getNumCarrots() {
+ return numCarrots;
+ }
+ public int getNumMeat() {
+ return numMeat;
+ }
+ public int getNumPeppers() {
+ return numPeppers;
+ }
+}
+public class ImmutableStew {
+ private static final Logger LOGGER = LoggerFactory.getLogger(ImmutableStew.class);
+ private final StewData data;
+ public ImmutableStew(int numPotatoes, int numCarrots, int numMeat, int numPeppers) {
+ data = new StewData(numPotatoes, numCarrots, numMeat, numPeppers);
+ }
+ public void mix() {
+ LOGGER
+ .info("Mixing the immutable stew we find: {} potatoes, {} carrots, {} meat and {} peppers",
+ data.getNumPotatoes(), data.getNumCarrots(), data.getNumMeat(), data.getNumPeppers());
+ }
+}
+```
+
+Let's try creating an instance of each class and call their methods:
+
+```java
+var stew = new Stew(1, 2, 3, 4);
+stew.mix(); // Mixing the stew we find: 1 potatoes, 2 carrots, 3 meat and 4 peppers
+stew.taste(); // Tasting the stew
+stew.mix(); // Mixing the stew we find: 0 potatoes, 1 carrots, 2 meat and 3 peppers
+var immutableStew = new ImmutableStew(2, 4, 3, 6);
+immutableStew.mix(); // Mixing the immutable stew we find: 2 potatoes, 4 carrots, 3 meat and 6 peppers
+```
## Class diagram

diff --git a/private-class-data/pom.xml b/private-class-data/pom.xml
index cb81ca3fc..01d0149ea 100644
--- a/private-class-data/pom.xml
+++ b/private-class-data/pom.xml
@@ -29,7 +29,7 @@
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
private-class-data
diff --git a/private-class-data/src/main/java/com/iluwatar/privateclassdata/ImmutableStew.java b/private-class-data/src/main/java/com/iluwatar/privateclassdata/ImmutableStew.java
index 695424695..d312cd34a 100644
--- a/private-class-data/src/main/java/com/iluwatar/privateclassdata/ImmutableStew.java
+++ b/private-class-data/src/main/java/com/iluwatar/privateclassdata/ImmutableStew.java
@@ -1,50 +1,50 @@
-/*
- * The MIT License
- * Copyright © 2014-2019 Ilkka Seppälä
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-
-package com.iluwatar.privateclassdata;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Immutable stew class, protected with Private Class Data pattern.
- */
-public class ImmutableStew {
-
- private static final Logger LOGGER = LoggerFactory.getLogger(ImmutableStew.class);
-
- private StewData data;
-
- public ImmutableStew(int numPotatoes, int numCarrots, int numMeat, int numPeppers) {
- data = new StewData(numPotatoes, numCarrots, numMeat, numPeppers);
- }
-
- /**
- * Mix the stew.
- */
- public void mix() {
- LOGGER
- .info("Mixing the immutable stew we find: {} potatoes, {} carrots, {} meat and {} peppers",
- data.getNumPotatoes(), data.getNumCarrots(), data.getNumMeat(), data.getNumPeppers());
- }
-}
+/*
+ * The MIT License
+ * Copyright © 2014-2019 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+package com.iluwatar.privateclassdata;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Immutable stew class, protected with Private Class Data pattern.
+ */
+public class ImmutableStew {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(ImmutableStew.class);
+
+ private final StewData data;
+
+ public ImmutableStew(int numPotatoes, int numCarrots, int numMeat, int numPeppers) {
+ data = new StewData(numPotatoes, numCarrots, numMeat, numPeppers);
+ }
+
+ /**
+ * Mix the stew.
+ */
+ public void mix() {
+ LOGGER
+ .info("Mixing the immutable stew we find: {} potatoes, {} carrots, {} meat and {} peppers",
+ data.getNumPotatoes(), data.getNumCarrots(), data.getNumMeat(), data.getNumPeppers());
+ }
+}
diff --git a/private-class-data/src/main/java/com/iluwatar/privateclassdata/StewData.java b/private-class-data/src/main/java/com/iluwatar/privateclassdata/StewData.java
index bcdaba3e9..1b0fd269b 100644
--- a/private-class-data/src/main/java/com/iluwatar/privateclassdata/StewData.java
+++ b/private-class-data/src/main/java/com/iluwatar/privateclassdata/StewData.java
@@ -1,61 +1,61 @@
-/*
- * The MIT License
- * Copyright © 2014-2019 Ilkka Seppälä
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-
-package com.iluwatar.privateclassdata;
-
-/**
- * Stew ingredients.
- */
-public class StewData {
-
- private int numPotatoes;
- private int numCarrots;
- private int numMeat;
- private int numPeppers;
-
- /**
- * Constructor.
- */
- public StewData(int numPotatoes, int numCarrots, int numMeat, int numPeppers) {
- this.numPotatoes = numPotatoes;
- this.numCarrots = numCarrots;
- this.numMeat = numMeat;
- this.numPeppers = numPeppers;
- }
-
- public int getNumPotatoes() {
- return numPotatoes;
- }
-
- public int getNumCarrots() {
- return numCarrots;
- }
-
- public int getNumMeat() {
- return numMeat;
- }
-
- public int getNumPeppers() {
- return numPeppers;
- }
-}
+/*
+ * The MIT License
+ * Copyright © 2014-2019 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+package com.iluwatar.privateclassdata;
+
+/**
+ * Stew ingredients.
+ */
+public class StewData {
+
+ private final int numPotatoes;
+ private final int numCarrots;
+ private final int numMeat;
+ private final int numPeppers;
+
+ /**
+ * Constructor.
+ */
+ public StewData(int numPotatoes, int numCarrots, int numMeat, int numPeppers) {
+ this.numPotatoes = numPotatoes;
+ this.numCarrots = numCarrots;
+ this.numMeat = numMeat;
+ this.numPeppers = numPeppers;
+ }
+
+ public int getNumPotatoes() {
+ return numPotatoes;
+ }
+
+ public int getNumCarrots() {
+ return numCarrots;
+ }
+
+ public int getNumMeat() {
+ return numMeat;
+ }
+
+ public int getNumPeppers() {
+ return numPeppers;
+ }
+}
diff --git a/private-class-data/src/test/java/com/iluwatar/privateclassdata/AppTest.java b/private-class-data/src/test/java/com/iluwatar/privateclassdata/AppTest.java
index 166ddbdee..d551614cf 100644
--- a/private-class-data/src/test/java/com/iluwatar/privateclassdata/AppTest.java
+++ b/private-class-data/src/test/java/com/iluwatar/privateclassdata/AppTest.java
@@ -25,13 +25,15 @@ package com.iluwatar.privateclassdata;
import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+
/**
* Application test
*/
-public class AppTest {
+class AppTest {
@Test
- public void test() {
- App.main(new String[]{});
+ void shouldExecuteApplicationWithoutException() {
+ assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
diff --git a/private-class-data/src/test/java/com/iluwatar/privateclassdata/utils/InMemoryAppender.java b/private-class-data/src/test/java/com/iluwatar/privateclassdata/utils/InMemoryAppender.java
index 6fbe638ae..bbcbc8021 100644
--- a/private-class-data/src/test/java/com/iluwatar/privateclassdata/utils/InMemoryAppender.java
+++ b/private-class-data/src/test/java/com/iluwatar/privateclassdata/utils/InMemoryAppender.java
@@ -34,7 +34,7 @@ import org.slf4j.LoggerFactory;
* InMemory Log Appender Util.
*/
public class InMemoryAppender extends AppenderBase {
- private List log = new LinkedList<>();
+ private final List log = new LinkedList<>();
public InMemoryAppender() {
((Logger) LoggerFactory.getLogger("root")).addAppender(this);
diff --git a/producer-consumer/pom.xml b/producer-consumer/pom.xml
index ab1872c51..4884ef728 100644
--- a/producer-consumer/pom.xml
+++ b/producer-consumer/pom.xml
@@ -29,7 +29,7 @@
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
producer-consumer
diff --git a/producer-consumer/src/main/java/com/iluwatar/producer/consumer/Item.java b/producer-consumer/src/main/java/com/iluwatar/producer/consumer/Item.java
index 6991ec4d1..89f692282 100644
--- a/producer-consumer/src/main/java/com/iluwatar/producer/consumer/Item.java
+++ b/producer-consumer/src/main/java/com/iluwatar/producer/consumer/Item.java
@@ -28,9 +28,9 @@ package com.iluwatar.producer.consumer;
*/
public class Item {
- private String producer;
+ private final String producer;
- private int id;
+ private final int id;
public Item(String producer, int id) {
this.id = id;
diff --git a/producer-consumer/src/main/java/com/iluwatar/producer/consumer/ItemQueue.java b/producer-consumer/src/main/java/com/iluwatar/producer/consumer/ItemQueue.java
index 674fb069a..118e3265d 100644
--- a/producer-consumer/src/main/java/com/iluwatar/producer/consumer/ItemQueue.java
+++ b/producer-consumer/src/main/java/com/iluwatar/producer/consumer/ItemQueue.java
@@ -31,7 +31,7 @@ import java.util.concurrent.LinkedBlockingQueue;
*/
public class ItemQueue {
- private BlockingQueue- queue;
+ private final BlockingQueue
- queue;
public ItemQueue() {
diff --git a/producer-consumer/src/test/java/com/iluwatar/producer/consumer/AppTest.java b/producer-consumer/src/test/java/com/iluwatar/producer/consumer/AppTest.java
index bf4b6cc66..0a436bd02 100644
--- a/producer-consumer/src/test/java/com/iluwatar/producer/consumer/AppTest.java
+++ b/producer-consumer/src/test/java/com/iluwatar/producer/consumer/AppTest.java
@@ -25,14 +25,16 @@ package com.iluwatar.producer.consumer;
import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+
/**
* Application test
*/
-public class AppTest {
+class AppTest {
@Test
- public void test() {
- App.main(new String[]{});
+ void shouldExecuteApplicationWithoutException() {
+ assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
diff --git a/promise/README.md b/promise/README.md
index cf3d96c88..993d29a9f 100644
--- a/promise/README.md
+++ b/promise/README.md
@@ -9,18 +9,277 @@ tags:
---
## Also known as
+
CompletableFuture
## Intent
-A Promise represents a proxy for a value not necessarily known when the promise is created. It
-allows you to associate dependent promises to an asynchronous action's eventual success value or
-failure reason. Promises are a way to write async code that still appears as though it is executing
-in a synchronous way.
+
+A Promise represents a proxy for a value not necessarily known when the promise is created. It allows you to associate
+dependent promises to an asynchronous action's eventual success value or failure reason. Promises are a way to write
+async code that still appears as though it is executing in a synchronous way.
+
+## Explanation
+
+The Promise object is used for asynchronous computations. A Promise represents an operation that hasn't completed yet,
+but is expected in the future.
+
+Promises provide a few advantages over callback objects:
+ * Functional composition and error handling
+ * Prevents callback hell and provides callback aggregation
+
+Real world example
+
+> We are developing a software solution that downloads files and calculates the number of lines and character
+frequencies in those files. Promise is an ideal solution to make the code concise and easy to understand.
+
+In plain words
+
+> Promise is a placeholder for an asynchronous operation that is ongoing.
+
+Wikipedia says
+
+> In computer science, future, promise, delay, and deferred refer to constructs used for synchronizing program
+execution in some concurrent programming languages. They describe an object that acts as a proxy for a result that is
+initially unknown, usually because the computation of its value is not yet complete.
+
+**Programmatic Example**
+
+In the example a file is downloaded and its line count is calculated. The calculated line count is then consumed and
+printed on console.
+
+Let's first introduce a support class we need for implementation. Here's `PromiseSupport`.
+
+```java
+class PromiseSupport
implements Future {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(PromiseSupport.class);
+
+ private static final int RUNNING = 1;
+ private static final int FAILED = 2;
+ private static final int COMPLETED = 3;
+
+ private final Object lock;
+
+ private volatile int state = RUNNING;
+ private T value;
+ private Exception exception;
+
+ PromiseSupport() {
+ this.lock = new Object();
+ }
+
+ void fulfill(T value) {
+ this.value = value;
+ this.state = COMPLETED;
+ synchronized (lock) {
+ lock.notifyAll();
+ }
+ }
+
+ void fulfillExceptionally(Exception exception) {
+ this.exception = exception;
+ this.state = FAILED;
+ synchronized (lock) {
+ lock.notifyAll();
+ }
+ }
+
+ @Override
+ public boolean cancel(boolean mayInterruptIfRunning) {
+ return false;
+ }
+
+ @Override
+ public boolean isCancelled() {
+ return false;
+ }
+
+ @Override
+ public boolean isDone() {
+ return state > RUNNING;
+ }
+
+ @Override
+ public T get() throws InterruptedException, ExecutionException {
+ synchronized (lock) {
+ while (state == RUNNING) {
+ lock.wait();
+ }
+ }
+ if (state == COMPLETED) {
+ return value;
+ }
+ throw new ExecutionException(exception);
+ }
+
+ @Override
+ public T get(long timeout, TimeUnit unit) throws ExecutionException {
+ synchronized (lock) {
+ while (state == RUNNING) {
+ try {
+ lock.wait(unit.toMillis(timeout));
+ } catch (InterruptedException e) {
+ LOGGER.warn("Interrupted!", e);
+ Thread.currentThread().interrupt();
+ }
+ }
+ }
+
+ if (state == COMPLETED) {
+ return value;
+ }
+ throw new ExecutionException(exception);
+ }
+}
+```
+
+With `PromiseSupport` in place we can implement the actual `Promise`.
+
+```java
+public class Promise extends PromiseSupport {
+
+ private Runnable fulfillmentAction;
+ private Consumer super Throwable> exceptionHandler;
+
+ public Promise() {
+ }
+
+ @Override
+ public void fulfill(T value) {
+ super.fulfill(value);
+ postFulfillment();
+ }
+
+ @Override
+ public void fulfillExceptionally(Exception exception) {
+ super.fulfillExceptionally(exception);
+ handleException(exception);
+ postFulfillment();
+ }
+
+ private void handleException(Exception exception) {
+ if (exceptionHandler == null) {
+ return;
+ }
+ exceptionHandler.accept(exception);
+ }
+
+ private void postFulfillment() {
+ if (fulfillmentAction == null) {
+ return;
+ }
+ fulfillmentAction.run();
+ }
+
+ public Promise fulfillInAsync(final Callable task, Executor executor) {
+ executor.execute(() -> {
+ try {
+ fulfill(task.call());
+ } catch (Exception ex) {
+ fulfillExceptionally(ex);
+ }
+ });
+ return this;
+ }
+
+ public Promise thenAccept(Consumer super T> action) {
+ var dest = new Promise();
+ fulfillmentAction = new ConsumeAction(this, dest, action);
+ return dest;
+ }
+
+ public Promise onError(Consumer super Throwable> exceptionHandler) {
+ this.exceptionHandler = exceptionHandler;
+ return this;
+ }
+
+ public Promise thenApply(Function super T, V> func) {
+ Promise dest = new Promise<>();
+ fulfillmentAction = new TransformAction(this, dest, func);
+ return dest;
+ }
+
+ private class ConsumeAction implements Runnable {
+
+ private final Promise src;
+ private final Promise dest;
+ private final Consumer super T> action;
+
+ private ConsumeAction(Promise src, Promise dest, Consumer super T> action) {
+ this.src = src;
+ this.dest = dest;
+ this.action = action;
+ }
+
+ @Override
+ public void run() {
+ try {
+ action.accept(src.get());
+ dest.fulfill(null);
+ } catch (Throwable throwable) {
+ dest.fulfillExceptionally((Exception) throwable.getCause());
+ }
+ }
+ }
+
+ private class TransformAction implements Runnable {
+
+ private final Promise src;
+ private final Promise dest;
+ private final Function super T, V> func;
+
+ private TransformAction(Promise src, Promise dest, Function super T, V> func) {
+ this.src = src;
+ this.dest = dest;
+ this.func = func;
+ }
+
+ @Override
+ public void run() {
+ try {
+ dest.fulfill(func.apply(src.get()));
+ } catch (Throwable throwable) {
+ dest.fulfillExceptionally((Exception) throwable.getCause());
+ }
+ }
+ }
+}
+```
+
+Now we can show the full example in action. Here's how to download and count the number of lines in a file using
+`Promise`.
+
+```java
+ countLines().thenAccept(
+ count -> {
+ LOGGER.info("Line count is: {}", count);
+ taskCompleted();
+ }
+ );
+
+ private Promise countLines() {
+ return download(DEFAULT_URL).thenApply(Utility::countLines);
+ }
+
+ private Promise download(String urlString) {
+ return new Promise()
+ .fulfillInAsync(
+ () -> Utility.downloadFile(urlString), executor)
+ .onError(
+ throwable -> {
+ throwable.printStackTrace();
+ taskCompleted();
+ }
+ );
+ }
+```
## Class diagram
+

## Applicability
+
Promise pattern is applicable in concurrent programming when some work needs to be done asynchronously
and:
@@ -35,10 +294,17 @@ and:
* [Guava ListenableFuture](https://github.com/google/guava/wiki/ListenableFutureExplained)
## Related Patterns
- * Async Method Invocation
- * Callback
+
+ * [Async Method Invocation](https://java-design-patterns.com/patterns/async-method-invocation/)
+ * [Callback](https://java-design-patterns.com/patterns/callback/)
+
+## Tutorials
+
+* [Guide To CompletableFuture](https://www.baeldung.com/java-completablefuture)
## Credits
* [You are missing the point to Promises](https://gist.github.com/domenic/3889970)
* [Functional style callbacks using CompletableFuture](https://www.infoq.com/articles/Functional-Style-Callbacks-Using-CompletableFuture)
+* [Java 8 in Action: Lambdas, Streams, and functional-style programming](https://www.amazon.com/gp/product/1617291994/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=1617291994&linkId=995af46887bb7b65e6c788a23eaf7146)
+* [Modern Java in Action: Lambdas, streams, functional and reactive programming](https://www.amazon.com/gp/product/1617293563/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=1617293563&linkId=f70fe0d3e1efaff89554a6479c53759c)
diff --git a/promise/pom.xml b/promise/pom.xml
index 4a9d76df1..6ef67edec 100644
--- a/promise/pom.xml
+++ b/promise/pom.xml
@@ -29,7 +29,7 @@
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
promise
diff --git a/promise/src/main/java/com/iluwatar/promise/Promise.java b/promise/src/main/java/com/iluwatar/promise/Promise.java
index 9eecf00eb..e81cccb58 100644
--- a/promise/src/main/java/com/iluwatar/promise/Promise.java
+++ b/promise/src/main/java/com/iluwatar/promise/Promise.java
@@ -47,6 +47,7 @@ public class Promise extends PromiseSupport {
* Creates a promise that will be fulfilled in future.
*/
public Promise() {
+ // Empty constructor
}
/**
diff --git a/promise/src/test/java/com/iluwatar/promise/AppTest.java b/promise/src/test/java/com/iluwatar/promise/AppTest.java
index 63ac06aec..bf2f264c0 100644
--- a/promise/src/test/java/com/iluwatar/promise/AppTest.java
+++ b/promise/src/test/java/com/iluwatar/promise/AppTest.java
@@ -26,13 +26,15 @@ package com.iluwatar.promise;
import java.util.concurrent.ExecutionException;
import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+
/**
* Application test.
*/
-public class AppTest {
+class AppTest {
@Test
- public void testApp() throws InterruptedException, ExecutionException {
- App.main(null);
+ void shouldExecuteApplicationWithoutException() {
+ assertDoesNotThrow(() -> App.main(null));
}
}
diff --git a/promise/src/test/java/com/iluwatar/promise/PromiseTest.java b/promise/src/test/java/com/iluwatar/promise/PromiseTest.java
index a72faf01e..3b6d43be2 100644
--- a/promise/src/test/java/com/iluwatar/promise/PromiseTest.java
+++ b/promise/src/test/java/com/iluwatar/promise/PromiseTest.java
@@ -67,7 +67,7 @@ public class PromiseTest {
@Test
public void promiseIsFulfilledWithAnExceptionIfTaskThrowsAnException()
- throws InterruptedException, TimeoutException {
+ throws InterruptedException {
testWaitingForeverForPromiseToBeFulfilled();
testWaitingSomeTimeForPromiseToBeFulfilled();
}
diff --git a/property/pom.xml b/property/pom.xml
index d271af036..8746a60ac 100644
--- a/property/pom.xml
+++ b/property/pom.xml
@@ -29,7 +29,7 @@
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
property
diff --git a/property/src/main/java/com/iluwatar/property/Character.java b/property/src/main/java/com/iluwatar/property/Character.java
index afe9fe16c..3d3813e5f 100644
--- a/property/src/main/java/com/iluwatar/property/Character.java
+++ b/property/src/main/java/com/iluwatar/property/Character.java
@@ -61,10 +61,12 @@ public class Character implements Prototype {
@Override
public void set(Stats stat, Integer val) {
+ // Does Nothing
}
@Override
public void remove(Stats stat) {
+ // Does Nothing.
}
};
}
diff --git a/property/src/test/java/com/iluwatar/property/AppTest.java b/property/src/test/java/com/iluwatar/property/AppTest.java
index 89c0dcbf6..38c5cb4d5 100644
--- a/property/src/test/java/com/iluwatar/property/AppTest.java
+++ b/property/src/test/java/com/iluwatar/property/AppTest.java
@@ -25,13 +25,15 @@ package com.iluwatar.property;
import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+
/**
* Application test
*/
-public class AppTest {
+class AppTest {
@Test
- public void test() {
- App.main(new String[]{});
+ void shouldExecuteWithoutException() {
+ assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
diff --git a/prototype/pom.xml b/prototype/pom.xml
index e68b11892..220ed4521 100644
--- a/prototype/pom.xml
+++ b/prototype/pom.xml
@@ -29,7 +29,7 @@
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
prototype
diff --git a/prototype/src/main/java/com/iluwatar/prototype/ElfBeast.java b/prototype/src/main/java/com/iluwatar/prototype/ElfBeast.java
index 1401460d6..8e2ed9474 100644
--- a/prototype/src/main/java/com/iluwatar/prototype/ElfBeast.java
+++ b/prototype/src/main/java/com/iluwatar/prototype/ElfBeast.java
@@ -28,7 +28,7 @@ package com.iluwatar.prototype;
*/
public class ElfBeast extends Beast {
- private String helpType;
+ private final String helpType;
public ElfBeast(String helpType) {
this.helpType = helpType;
diff --git a/prototype/src/main/java/com/iluwatar/prototype/ElfMage.java b/prototype/src/main/java/com/iluwatar/prototype/ElfMage.java
index 4a7eea98f..42a54ca97 100644
--- a/prototype/src/main/java/com/iluwatar/prototype/ElfMage.java
+++ b/prototype/src/main/java/com/iluwatar/prototype/ElfMage.java
@@ -28,7 +28,7 @@ package com.iluwatar.prototype;
*/
public class ElfMage extends Mage {
- private String helpType;
+ private final String helpType;
public ElfMage(String helpType) {
this.helpType = helpType;
diff --git a/prototype/src/main/java/com/iluwatar/prototype/ElfWarlord.java b/prototype/src/main/java/com/iluwatar/prototype/ElfWarlord.java
index 101cd5942..fb426a444 100644
--- a/prototype/src/main/java/com/iluwatar/prototype/ElfWarlord.java
+++ b/prototype/src/main/java/com/iluwatar/prototype/ElfWarlord.java
@@ -28,7 +28,7 @@ package com.iluwatar.prototype;
*/
public class ElfWarlord extends Warlord {
- private String helpType;
+ private final String helpType;
public ElfWarlord(String helpType) {
this.helpType = helpType;
diff --git a/prototype/src/main/java/com/iluwatar/prototype/HeroFactoryImpl.java b/prototype/src/main/java/com/iluwatar/prototype/HeroFactoryImpl.java
index eb84b2982..14516f3b4 100644
--- a/prototype/src/main/java/com/iluwatar/prototype/HeroFactoryImpl.java
+++ b/prototype/src/main/java/com/iluwatar/prototype/HeroFactoryImpl.java
@@ -1,65 +1,65 @@
-/*
- * The MIT License
- * Copyright © 2014-2019 Ilkka Seppälä
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-
-package com.iluwatar.prototype;
-
-/**
- * Concrete factory class.
- */
-public class HeroFactoryImpl implements HeroFactory {
-
- private Mage mage;
- private Warlord warlord;
- private Beast beast;
-
- /**
- * Constructor.
- */
- public HeroFactoryImpl(Mage mage, Warlord warlord, Beast beast) {
- this.mage = mage;
- this.warlord = warlord;
- this.beast = beast;
- }
-
- /**
- * Create mage.
- */
- public Mage createMage() {
- return mage.copy();
- }
-
- /**
- * Create warlord.
- */
- public Warlord createWarlord() {
- return warlord.copy();
- }
-
- /**
- * Create beast.
- */
- public Beast createBeast() {
- return beast.copy();
- }
-
-}
+/*
+ * The MIT License
+ * Copyright © 2014-2019 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+package com.iluwatar.prototype;
+
+/**
+ * Concrete factory class.
+ */
+public class HeroFactoryImpl implements HeroFactory {
+
+ private final Mage mage;
+ private final Warlord warlord;
+ private final Beast beast;
+
+ /**
+ * Constructor.
+ */
+ public HeroFactoryImpl(Mage mage, Warlord warlord, Beast beast) {
+ this.mage = mage;
+ this.warlord = warlord;
+ this.beast = beast;
+ }
+
+ /**
+ * Create mage.
+ */
+ public Mage createMage() {
+ return mage.copy();
+ }
+
+ /**
+ * Create warlord.
+ */
+ public Warlord createWarlord() {
+ return warlord.copy();
+ }
+
+ /**
+ * Create beast.
+ */
+ public Beast createBeast() {
+ return beast.copy();
+ }
+
+}
diff --git a/prototype/src/main/java/com/iluwatar/prototype/OrcBeast.java b/prototype/src/main/java/com/iluwatar/prototype/OrcBeast.java
index cf3dc18d8..91339887c 100644
--- a/prototype/src/main/java/com/iluwatar/prototype/OrcBeast.java
+++ b/prototype/src/main/java/com/iluwatar/prototype/OrcBeast.java
@@ -28,7 +28,7 @@ package com.iluwatar.prototype;
*/
public class OrcBeast extends Beast {
- private String weapon;
+ private final String weapon;
public OrcBeast(String weapon) {
this.weapon = weapon;
diff --git a/prototype/src/main/java/com/iluwatar/prototype/OrcMage.java b/prototype/src/main/java/com/iluwatar/prototype/OrcMage.java
index cb8239c3f..439e7f368 100644
--- a/prototype/src/main/java/com/iluwatar/prototype/OrcMage.java
+++ b/prototype/src/main/java/com/iluwatar/prototype/OrcMage.java
@@ -28,7 +28,7 @@ package com.iluwatar.prototype;
*/
public class OrcMage extends Mage {
- private String weapon;
+ private final String weapon;
public OrcMage(String weapon) {
this.weapon = weapon;
diff --git a/prototype/src/main/java/com/iluwatar/prototype/OrcWarlord.java b/prototype/src/main/java/com/iluwatar/prototype/OrcWarlord.java
index 39facc41e..a2ae31b4d 100644
--- a/prototype/src/main/java/com/iluwatar/prototype/OrcWarlord.java
+++ b/prototype/src/main/java/com/iluwatar/prototype/OrcWarlord.java
@@ -28,7 +28,7 @@ package com.iluwatar.prototype;
*/
public class OrcWarlord extends Warlord {
- private String weapon;
+ private final String weapon;
public OrcWarlord(String weapon) {
this.weapon = weapon;
diff --git a/prototype/src/test/java/com/iluwatar/prototype/AppTest.java b/prototype/src/test/java/com/iluwatar/prototype/AppTest.java
index 489b6365c..d82568ddf 100644
--- a/prototype/src/test/java/com/iluwatar/prototype/AppTest.java
+++ b/prototype/src/test/java/com/iluwatar/prototype/AppTest.java
@@ -25,13 +25,15 @@ package com.iluwatar.prototype;
import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+
/**
* Application test
*/
-public class AppTest {
+class AppTest {
@Test
- public void test() {
- App.main(new String[]{});
+ void shouldExecuteApplicationWithoutException() {
+ assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
diff --git a/proxy/README.md b/proxy/README.md
index b89d2a624..ddcc4e784 100644
--- a/proxy/README.md
+++ b/proxy/README.md
@@ -132,12 +132,16 @@ are several common situations in which the Proxy pattern is applicable
* [Controlling Access With Proxy Pattern](http://java-design-patterns.com/blog/controlling-access-with-proxy-pattern/)
-## Real world examples
+## Known uses
* [java.lang.reflect.Proxy](http://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Proxy.html)
* [Apache Commons Proxy](https://commons.apache.org/proper/commons-proxy/)
* Mocking frameworks Mockito, Powermock, EasyMock
+## Related patterns
+
+* [Ambassador](https://java-design-patterns.com/patterns/ambassador/)
+
## Credits
* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59)
diff --git a/proxy/pom.xml b/proxy/pom.xml
index f54c77dcf..0e7707bf8 100644
--- a/proxy/pom.xml
+++ b/proxy/pom.xml
@@ -29,7 +29,7 @@
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
proxy
diff --git a/proxy/src/test/java/com/iluwatar/proxy/AppTest.java b/proxy/src/test/java/com/iluwatar/proxy/AppTest.java
index 2fdd5253e..dde0bbe57 100644
--- a/proxy/src/test/java/com/iluwatar/proxy/AppTest.java
+++ b/proxy/src/test/java/com/iluwatar/proxy/AppTest.java
@@ -25,13 +25,15 @@ package com.iluwatar.proxy;
import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+
/**
* Application test
*/
-public class AppTest {
+class AppTest {
@Test
- public void test() {
- App.main(new String[]{});
+ void shouldExecuteApplicationWithoutException() {
+ assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
diff --git a/proxy/src/test/java/com/iluwatar/proxy/utils/InMemoryAppender.java b/proxy/src/test/java/com/iluwatar/proxy/utils/InMemoryAppender.java
index 2187c3300..173825288 100644
--- a/proxy/src/test/java/com/iluwatar/proxy/utils/InMemoryAppender.java
+++ b/proxy/src/test/java/com/iluwatar/proxy/utils/InMemoryAppender.java
@@ -35,7 +35,7 @@ import org.slf4j.LoggerFactory;
* InMemory Log Appender Util.
*/
public class InMemoryAppender extends AppenderBase {
- private List log = new LinkedList<>();
+ private final List log = new LinkedList<>();
public InMemoryAppender(Class clazz) {
((Logger) LoggerFactory.getLogger(clazz)).addAppender(this);
diff --git a/queue-load-leveling/pom.xml b/queue-load-leveling/pom.xml
index ee6e6c623..817e6e3cc 100644
--- a/queue-load-leveling/pom.xml
+++ b/queue-load-leveling/pom.xml
@@ -29,7 +29,7 @@
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
queue-load-leveling
diff --git a/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/AppTest.java b/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/AppTest.java
index 55c9528e6..2adc15011 100644
--- a/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/AppTest.java
+++ b/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/AppTest.java
@@ -25,12 +25,15 @@ package com.iluwatar.queue.load.leveling;
import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+
/**
* Application Test
*/
-public class AppTest {
+class AppTest {
+
@Test
- public void test() {
- App.main(new String[]{});
+ void shouldExecuteApplicationWithoutException() {
+ assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
\ No newline at end of file
diff --git a/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/TaskGenSrvExeTest.java b/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/TaskGenSrvExeTest.java
index 1e81c5d11..3d12e6abf 100644
--- a/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/TaskGenSrvExeTest.java
+++ b/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/TaskGenSrvExeTest.java
@@ -25,14 +25,17 @@ package com.iluwatar.queue.load.leveling;
import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
/**
* Test case for submitting Message to Blocking Queue by TaskGenerator and retrieve the message by
* ServiceExecutor.
*/
-public class TaskGenSrvExeTest {
+class TaskGenSrvExeTest {
@Test
- public void taskGeneratorTest() {
+ void taskGeneratorTest() {
var msgQueue = new MessageQueue();
// Create a task generator thread with 1 job to submit.
@@ -40,10 +43,14 @@ public class TaskGenSrvExeTest {
var taskGenThr = new Thread(taskRunnable);
taskGenThr.start();
+ assertNotNull(taskGenThr);
+
// Create a service executor thread.
var srvRunnable = new ServiceExecutor(msgQueue);
var srvExeThr = new Thread(srvRunnable);
srvExeThr.start();
+
+ assertNotNull(srvExeThr);
}
}
diff --git a/reactor/pom.xml b/reactor/pom.xml
index b95b0b6e2..c25ed45ae 100644
--- a/reactor/pom.xml
+++ b/reactor/pom.xml
@@ -29,7 +29,7 @@
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
reactor
diff --git a/reactor/src/main/java/com/iluwatar/reactor/app/App.java b/reactor/src/main/java/com/iluwatar/reactor/app/App.java
index 3bd8176a6..f656eacf6 100644
--- a/reactor/src/main/java/com/iluwatar/reactor/app/App.java
+++ b/reactor/src/main/java/com/iluwatar/reactor/app/App.java
@@ -89,8 +89,8 @@ import java.util.List;
public class App {
private NioReactor reactor;
- private List channels = new ArrayList<>();
- private Dispatcher dispatcher;
+ private final List channels = new ArrayList<>();
+ private final Dispatcher dispatcher;
/**
* Creates an instance of App which will use provided dispatcher for dispatching events on
diff --git a/reactor/src/main/java/com/iluwatar/reactor/framework/NioDatagramChannel.java b/reactor/src/main/java/com/iluwatar/reactor/framework/NioDatagramChannel.java
index 13657cdb2..aba99d65c 100644
--- a/reactor/src/main/java/com/iluwatar/reactor/framework/NioDatagramChannel.java
+++ b/reactor/src/main/java/com/iluwatar/reactor/framework/NioDatagramChannel.java
@@ -134,7 +134,7 @@ public class NioDatagramChannel extends AbstractNioChannel {
*/
public static class DatagramPacket {
private SocketAddress sender;
- private ByteBuffer data;
+ private final ByteBuffer data;
private SocketAddress receiver;
/**
diff --git a/reactor/src/main/java/com/iluwatar/reactor/framework/NioReactor.java b/reactor/src/main/java/com/iluwatar/reactor/framework/NioReactor.java
index 1a0b17386..77e39a88d 100644
--- a/reactor/src/main/java/com/iluwatar/reactor/framework/NioReactor.java
+++ b/reactor/src/main/java/com/iluwatar/reactor/framework/NioReactor.java
@@ -228,8 +228,8 @@ public class NioReactor {
* A command that changes the interested operations of the key provided.
*/
class ChangeKeyOpsCommand implements Runnable {
- private SelectionKey key;
- private int interestedOps;
+ private final SelectionKey key;
+ private final int interestedOps;
public ChangeKeyOpsCommand(SelectionKey key, int interestedOps) {
this.key = key;
diff --git a/reactor/src/test/java/com/iluwatar/reactor/app/ReactorTest.java b/reactor/src/test/java/com/iluwatar/reactor/app/ReactorTest.java
index 76ddfbdba..1d7faab7e 100644
--- a/reactor/src/test/java/com/iluwatar/reactor/app/ReactorTest.java
+++ b/reactor/src/test/java/com/iluwatar/reactor/app/ReactorTest.java
@@ -30,6 +30,9 @@ import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+
/**
* This class tests the Distributed Logging service by starting a Reactor and then sending it
* concurrent logging requests using multiple clients.
@@ -50,9 +53,13 @@ public class ReactorTest {
var app = new App(new ThreadPoolDispatcher(2));
app.start();
+ assertNotNull(app);
+
var client = new AppClient();
client.start();
+ assertNotNull(client);
+
// allow clients to send requests. Artificial delay.
try {
Thread.sleep(2000);
@@ -78,9 +85,13 @@ public class ReactorTest {
var app = new App(new SameThreadDispatcher());
app.start();
+ assertNotNull(app);
+
var client = new AppClient();
client.start();
+ assertNotNull(client);
+
// allow clients to send requests. Artificial delay.
try {
Thread.sleep(2000);
diff --git a/reader-writer-lock/pom.xml b/reader-writer-lock/pom.xml
index 92f53df66..37f70b435 100644
--- a/reader-writer-lock/pom.xml
+++ b/reader-writer-lock/pom.xml
@@ -29,7 +29,7 @@
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
reader-writer-lock
diff --git a/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/Reader.java b/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/Reader.java
index 6d705de2f..c54e62e58 100644
--- a/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/Reader.java
+++ b/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/Reader.java
@@ -34,11 +34,11 @@ public class Reader implements Runnable {
private static final Logger LOGGER = LoggerFactory.getLogger(Reader.class);
- private Lock readLock;
+ private final Lock readLock;
- private String name;
+ private final String name;
- private long readingTime;
+ private final long readingTime;
/**
* Create new Reader.
diff --git a/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/ReaderWriterLock.java b/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/ReaderWriterLock.java
index 99c9b056b..932428b4f 100644
--- a/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/ReaderWriterLock.java
+++ b/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/ReaderWriterLock.java
@@ -59,8 +59,8 @@ public class ReaderWriterLock implements ReadWriteLock {
*/
private final Set globalMutex = new HashSet<>();
- private ReadLock readerLock = new ReadLock();
- private WriteLock writerLock = new WriteLock();
+ private final ReadLock readerLock = new ReadLock();
+ private final WriteLock writerLock = new WriteLock();
@Override
public Lock readLock() {
diff --git a/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/Writer.java b/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/Writer.java
index 7a971b28b..fbc8321f2 100644
--- a/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/Writer.java
+++ b/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/Writer.java
@@ -34,11 +34,11 @@ public class Writer implements Runnable {
private static final Logger LOGGER = LoggerFactory.getLogger(Writer.class);
- private Lock writeLock;
+ private final Lock writeLock;
- private String name;
+ private final String name;
- private long writingTime;
+ private final long writingTime;
/**
* Create new Writer who writes for 250ms.
diff --git a/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/AppTest.java b/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/AppTest.java
index a0175e259..63f4c764d 100644
--- a/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/AppTest.java
+++ b/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/AppTest.java
@@ -25,14 +25,16 @@ package com.iluwatar.reader.writer.lock;
import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+
/**
* Application test
*/
-public class AppTest {
+class AppTest {
@Test
- public void test() {
- App.main(new String[]{});
+ void shouldExecuteWithoutException() {
+ assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
diff --git a/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/utils/InMemoryAppender.java b/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/utils/InMemoryAppender.java
index c7e8bc02a..01a63d6c8 100644
--- a/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/utils/InMemoryAppender.java
+++ b/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/utils/InMemoryAppender.java
@@ -34,7 +34,7 @@ import org.slf4j.LoggerFactory;
* InMemory Log Appender Util.
*/
public class InMemoryAppender extends AppenderBase {
- private List log = new LinkedList<>();
+ private final List log = new LinkedList<>();
public InMemoryAppender(Class clazz) {
((Logger) LoggerFactory.getLogger(clazz)).addAppender(this);
diff --git a/repository/README.md b/repository/README.md
index 09a9a2bba..ad603ee2b 100644
--- a/repository/README.md
+++ b/repository/README.md
@@ -157,9 +157,9 @@ public class PersonSpecifications {
public static class AgeBetweenSpec implements Specification {
- private int from;
+ private final int from;
- private int to;
+ private final int to;
public AgeBetweenSpec(int from, int to) {
this.from = from;
diff --git a/repository/pom.xml b/repository/pom.xml
index 0b98cdb41..694629efa 100644
--- a/repository/pom.xml
+++ b/repository/pom.xml
@@ -29,7 +29,7 @@
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
repository
diff --git a/repository/src/main/java/com/iluwatar/repository/PersonSpecifications.java b/repository/src/main/java/com/iluwatar/repository/PersonSpecifications.java
index f91c0a6e1..919b746be 100644
--- a/repository/src/main/java/com/iluwatar/repository/PersonSpecifications.java
+++ b/repository/src/main/java/com/iluwatar/repository/PersonSpecifications.java
@@ -39,9 +39,9 @@ public class PersonSpecifications {
*/
public static class AgeBetweenSpec implements Specification {
- private int from;
+ private final int from;
- private int to;
+ private final int to;
public AgeBetweenSpec(int from, int to) {
this.from = from;
diff --git a/repository/src/test/java/com/iluwatar/repository/AnnotationBasedRepositoryTest.java b/repository/src/test/java/com/iluwatar/repository/AnnotationBasedRepositoryTest.java
index 6b47cbe9a..9e2e1f4e1 100644
--- a/repository/src/test/java/com/iluwatar/repository/AnnotationBasedRepositoryTest.java
+++ b/repository/src/test/java/com/iluwatar/repository/AnnotationBasedRepositoryTest.java
@@ -48,12 +48,12 @@ public class AnnotationBasedRepositoryTest {
@Resource
private PersonRepository repository;
- private Person peter = new Person("Peter", "Sagan", 17);
- private Person nasta = new Person("Nasta", "Kuzminova", 25);
- private Person john = new Person("John", "lawrence", 35);
- private Person terry = new Person("Terry", "Law", 36);
+ private final Person peter = new Person("Peter", "Sagan", 17);
+ private final Person nasta = new Person("Nasta", "Kuzminova", 25);
+ private final Person john = new Person("John", "lawrence", 35);
+ private final Person terry = new Person("Terry", "Law", 36);
- private List persons = List.of(peter, nasta, john, terry);
+ private final List persons = List.of(peter, nasta, john, terry);
/**
* Prepare data for test
diff --git a/repository/src/test/java/com/iluwatar/repository/AppTest.java b/repository/src/test/java/com/iluwatar/repository/AppTest.java
index b12f03d8c..d44af23db 100644
--- a/repository/src/test/java/com/iluwatar/repository/AppTest.java
+++ b/repository/src/test/java/com/iluwatar/repository/AppTest.java
@@ -25,12 +25,15 @@ package com.iluwatar.repository;
import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+
/**
* Tests that Repository example runs without errors.
*/
-public class AppTest {
+class AppTest {
+
@Test
- public void test() {
- App.main(new String[]{});
+ void shouldExecuteWithoutException() {
+ assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
diff --git a/repository/src/test/java/com/iluwatar/repository/RepositoryTest.java b/repository/src/test/java/com/iluwatar/repository/RepositoryTest.java
index ad9587aca..77e2b3e35 100644
--- a/repository/src/test/java/com/iluwatar/repository/RepositoryTest.java
+++ b/repository/src/test/java/com/iluwatar/repository/RepositoryTest.java
@@ -48,12 +48,12 @@ public class RepositoryTest {
@Resource
private PersonRepository repository;
- private Person peter = new Person("Peter", "Sagan", 17);
- private Person nasta = new Person("Nasta", "Kuzminova", 25);
- private Person john = new Person("John", "lawrence", 35);
- private Person terry = new Person("Terry", "Law", 36);
+ private final Person peter = new Person("Peter", "Sagan", 17);
+ private final Person nasta = new Person("Nasta", "Kuzminova", 25);
+ private final Person john = new Person("John", "lawrence", 35);
+ private final Person terry = new Person("Terry", "Law", 36);
- private List persons = List.of(peter, nasta, john, terry);
+ private final List persons = List.of(peter, nasta, john, terry);
/**
* Prepare data for test
diff --git a/resource-acquisition-is-initialization/pom.xml b/resource-acquisition-is-initialization/pom.xml
index ef8e19f48..34428033b 100644
--- a/resource-acquisition-is-initialization/pom.xml
+++ b/resource-acquisition-is-initialization/pom.xml
@@ -29,7 +29,7 @@
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
resource-acquisition-is-initialization
diff --git a/resource-acquisition-is-initialization/src/test/java/com/iluwatar/resource/acquisition/is/initialization/AppTest.java b/resource-acquisition-is-initialization/src/test/java/com/iluwatar/resource/acquisition/is/initialization/AppTest.java
index dedeee7e0..057a85500 100644
--- a/resource-acquisition-is-initialization/src/test/java/com/iluwatar/resource/acquisition/is/initialization/AppTest.java
+++ b/resource-acquisition-is-initialization/src/test/java/com/iluwatar/resource/acquisition/is/initialization/AppTest.java
@@ -25,13 +25,15 @@ package com.iluwatar.resource.acquisition.is.initialization;
import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+
/**
* Application test
*/
-public class AppTest {
+class AppTest {
@Test
- public void test() throws Exception {
- App.main(new String[]{});
+ void shouldExecuteWithoutException() {
+ assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
diff --git a/resource-acquisition-is-initialization/src/test/java/com/iluwatar/resource/acquisition/is/initialization/ClosableTest.java b/resource-acquisition-is-initialization/src/test/java/com/iluwatar/resource/acquisition/is/initialization/ClosableTest.java
index 7bba17553..53caabea7 100644
--- a/resource-acquisition-is-initialization/src/test/java/com/iluwatar/resource/acquisition/is/initialization/ClosableTest.java
+++ b/resource-acquisition-is-initialization/src/test/java/com/iluwatar/resource/acquisition/is/initialization/ClosableTest.java
@@ -68,7 +68,7 @@ public class ClosableTest {
* Logging Appender Implementation
*/
public class InMemoryAppender extends AppenderBase {
- private List log = new LinkedList<>();
+ private final List log = new LinkedList<>();
public InMemoryAppender() {
((Logger) LoggerFactory.getLogger("root")).addAppender(this);
diff --git a/retry/pom.xml b/retry/pom.xml
index e6c2701e0..2f0b15bd2 100644
--- a/retry/pom.xml
+++ b/retry/pom.xml
@@ -28,7 +28,7 @@
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
retry
jar
diff --git a/retry/src/main/java/com/iluwatar/retry/App.java b/retry/src/main/java/com/iluwatar/retry/App.java
index 06f43c29f..7d6e6faec 100644
--- a/retry/src/main/java/com/iluwatar/retry/App.java
+++ b/retry/src/main/java/com/iluwatar/retry/App.java
@@ -59,6 +59,7 @@ import org.slf4j.LoggerFactory;
*/
public final class App {
private static final Logger LOG = LoggerFactory.getLogger(App.class);
+ public static final String NOT_FOUND = "not found";
private static BusinessOperation op;
/**
@@ -81,7 +82,7 @@ public final class App {
}
private static void errorNoRetry() throws Exception {
- op = new FindCustomer("123", new CustomerNotFoundException("not found"));
+ op = new FindCustomer("123", new CustomerNotFoundException(NOT_FOUND));
try {
op.perform();
} catch (CustomerNotFoundException e) {
@@ -91,7 +92,7 @@ public final class App {
private static void errorWithRetry() throws Exception {
final var retry = new Retry<>(
- new FindCustomer("123", new CustomerNotFoundException("not found")),
+ new FindCustomer("123", new CustomerNotFoundException(NOT_FOUND)),
3, //3 attempts
100, //100 ms delay between attempts
e -> CustomerNotFoundException.class.isAssignableFrom(e.getClass())
@@ -106,7 +107,7 @@ public final class App {
private static void errorWithRetryExponentialBackoff() throws Exception {
final var retry = new RetryExponentialBackoff<>(
- new FindCustomer("123", new CustomerNotFoundException("not found")),
+ new FindCustomer("123", new CustomerNotFoundException(NOT_FOUND)),
6, //6 attempts
30000, //30 s max delay between attempts
e -> CustomerNotFoundException.class.isAssignableFrom(e.getClass())
diff --git a/role-object/pom.xml b/role-object/pom.xml
index ccb8219eb..07becfc9b 100644
--- a/role-object/pom.xml
+++ b/role-object/pom.xml
@@ -29,7 +29,7 @@
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
role-object
@@ -39,6 +39,11 @@
junit
test
+
+ org.junit.jupiter
+ junit-jupiter-engine
+ test
+
diff --git a/role-object/src/main/java/com/iluwatar/roleobject/CustomerCore.java b/role-object/src/main/java/com/iluwatar/roleobject/CustomerCore.java
index 966d0e3f0..1c4cf0383 100644
--- a/role-object/src/main/java/com/iluwatar/roleobject/CustomerCore.java
+++ b/role-object/src/main/java/com/iluwatar/roleobject/CustomerCore.java
@@ -36,7 +36,7 @@ import java.util.Optional;
*/
public class CustomerCore extends Customer {
- private Map roles;
+ private final Map roles;
public CustomerCore() {
roles = new HashMap<>();
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 cbc6cc79b..a776178fb 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 @@ public enum Role {
Borrower(BorrowerRole.class), Investor(InvestorRole.class);
- private Class extends CustomerRole> typeCst;
+ private final Class extends CustomerRole> typeCst;
Role(Class extends CustomerRole> typeCst) {
this.typeCst = typeCst;
diff --git a/role-object/src/test/java/com/iluwatar/roleobject/ApplicationRoleObjectTest.java b/role-object/src/test/java/com/iluwatar/roleobject/ApplicationRoleObjectTest.java
index eb8d57f4f..01535f477 100644
--- a/role-object/src/test/java/com/iluwatar/roleobject/ApplicationRoleObjectTest.java
+++ b/role-object/src/test/java/com/iluwatar/roleobject/ApplicationRoleObjectTest.java
@@ -24,10 +24,12 @@ package com.iluwatar.roleobject;
import org.junit.Test;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+
public class ApplicationRoleObjectTest {
@Test
- public void mainTest() {
- ApplicationRoleObject.main(new String[]{});
+ public void shouldExecuteApplicationWithoutException() {
+ assertDoesNotThrow(() -> ApplicationRoleObject.main(new String[]{}));
}
}
\ No newline at end of file
diff --git a/saga/pom.xml b/saga/pom.xml
index 08a5cdc77..a3ae60ed8 100644
--- a/saga/pom.xml
+++ b/saga/pom.xml
@@ -30,7 +30,7 @@
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
saga
@@ -40,6 +40,11 @@
junit
test
+
+ org.junit.jupiter
+ junit-jupiter-engine
+ test
+
diff --git a/saga/src/main/java/com/iluwatar/saga/choreography/Saga.java b/saga/src/main/java/com/iluwatar/saga/choreography/Saga.java
index 818b59a14..506587c76 100644
--- a/saga/src/main/java/com/iluwatar/saga/choreography/Saga.java
+++ b/saga/src/main/java/com/iluwatar/saga/choreography/Saga.java
@@ -33,7 +33,7 @@ import java.util.List;
*/
public class Saga {
- private List chapters;
+ private final List chapters;
private int pos;
private boolean forward;
private boolean finished;
@@ -153,7 +153,7 @@ public class Saga {
* outcoming parameter).
*/
public static class Chapter {
- private String name;
+ private final String name;
private ChapterResult result;
private Object inValue;
diff --git a/saga/src/main/java/com/iluwatar/saga/choreography/ServiceDiscoveryService.java b/saga/src/main/java/com/iluwatar/saga/choreography/ServiceDiscoveryService.java
index a616ff4a5..c6bc7bc80 100644
--- a/saga/src/main/java/com/iluwatar/saga/choreography/ServiceDiscoveryService.java
+++ b/saga/src/main/java/com/iluwatar/saga/choreography/ServiceDiscoveryService.java
@@ -32,7 +32,7 @@ import java.util.Optional;
* The class representing a service discovery pattern.
*/
public class ServiceDiscoveryService {
- private Map services;
+ private final Map services;
/**
* find any service.
diff --git a/saga/src/main/java/com/iluwatar/saga/orchestration/ChapterResult.java b/saga/src/main/java/com/iluwatar/saga/orchestration/ChapterResult.java
index ef34ddb98..b04d22849 100644
--- a/saga/src/main/java/com/iluwatar/saga/orchestration/ChapterResult.java
+++ b/saga/src/main/java/com/iluwatar/saga/orchestration/ChapterResult.java
@@ -29,8 +29,8 @@ package com.iluwatar.saga.orchestration;
* @param incoming value
*/
public class ChapterResult {
- private K value;
- private State state;
+ private final K value;
+ private final State state;
public K getValue() {
return value;
diff --git a/saga/src/main/java/com/iluwatar/saga/orchestration/Saga.java b/saga/src/main/java/com/iluwatar/saga/orchestration/Saga.java
index aff3593f1..1b68d6cf7 100644
--- a/saga/src/main/java/com/iluwatar/saga/orchestration/Saga.java
+++ b/saga/src/main/java/com/iluwatar/saga/orchestration/Saga.java
@@ -32,7 +32,7 @@ import java.util.List;
*/
public class Saga {
- private List chapters;
+ private final List chapters;
private Saga() {
diff --git a/saga/src/main/java/com/iluwatar/saga/orchestration/ServiceDiscoveryService.java b/saga/src/main/java/com/iluwatar/saga/orchestration/ServiceDiscoveryService.java
index dbc6e7eb5..f88efae52 100644
--- a/saga/src/main/java/com/iluwatar/saga/orchestration/ServiceDiscoveryService.java
+++ b/saga/src/main/java/com/iluwatar/saga/orchestration/ServiceDiscoveryService.java
@@ -31,7 +31,7 @@ import java.util.Optional;
* The class representing a service discovery pattern.
*/
public class ServiceDiscoveryService {
- private Map> services;
+ private final Map> services;
public Optional find(String service) {
return Optional.ofNullable(services.getOrDefault(service, null));
diff --git a/saga/src/test/java/com/iluwatar/saga/choreography/SagaApplicationTest.java b/saga/src/test/java/com/iluwatar/saga/choreography/SagaApplicationTest.java
index d7a2a34b2..5d73a9fa3 100644
--- a/saga/src/test/java/com/iluwatar/saga/choreography/SagaApplicationTest.java
+++ b/saga/src/test/java/com/iluwatar/saga/choreography/SagaApplicationTest.java
@@ -25,13 +25,15 @@ package com.iluwatar.saga.choreography;
import com.iluwatar.saga.orchestration.SagaApplication;
import org.junit.Test;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+
/***
* empty test
*/
public class SagaApplicationTest {
@Test
- public void mainTest() {
- SagaApplication.main(new String[]{});
+ public void shouldExecuteWithoutException() {
+ assertDoesNotThrow(() -> SagaApplication.main(new String[]{}));
}
}
\ No newline at end of file
diff --git a/saga/src/test/java/com/iluwatar/saga/orchestration/SagaOrchestratorInternallyTest.java b/saga/src/test/java/com/iluwatar/saga/orchestration/SagaOrchestratorInternallyTest.java
index 423b8e12e..f80a46fdc 100644
--- a/saga/src/test/java/com/iluwatar/saga/orchestration/SagaOrchestratorInternallyTest.java
+++ b/saga/src/test/java/com/iluwatar/saga/orchestration/SagaOrchestratorInternallyTest.java
@@ -34,7 +34,7 @@ import org.junit.Test;
*/
public class SagaOrchestratorInternallyTest {
- private List records = new ArrayList<>();
+ private final List records = new ArrayList<>();
@Test
public void executeTest() {
diff --git a/semaphore/pom.xml b/semaphore/pom.xml
index b6375366b..64fd44db6 100644
--- a/semaphore/pom.xml
+++ b/semaphore/pom.xml
@@ -29,7 +29,7 @@
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
semaphore
diff --git a/semaphore/src/main/java/com/iluwatar/semaphore/Fruit.java b/semaphore/src/main/java/com/iluwatar/semaphore/Fruit.java
index d94764dbe..1f4026b92 100644
--- a/semaphore/src/main/java/com/iluwatar/semaphore/Fruit.java
+++ b/semaphore/src/main/java/com/iluwatar/semaphore/Fruit.java
@@ -35,7 +35,7 @@ public class Fruit {
ORANGE, APPLE, LEMON
}
- private FruitType type;
+ private final FruitType type;
public Fruit(FruitType type) {
this.type = type;
diff --git a/semaphore/src/main/java/com/iluwatar/semaphore/FruitBowl.java b/semaphore/src/main/java/com/iluwatar/semaphore/FruitBowl.java
index 6b43c8100..5c2901efe 100644
--- a/semaphore/src/main/java/com/iluwatar/semaphore/FruitBowl.java
+++ b/semaphore/src/main/java/com/iluwatar/semaphore/FruitBowl.java
@@ -31,7 +31,7 @@ import java.util.List;
*/
public class FruitBowl {
- private List fruit = new ArrayList<>();
+ private final List fruit = new ArrayList<>();
/**
* Returns the amount of fruits left in bowl.
diff --git a/semaphore/src/main/java/com/iluwatar/semaphore/FruitShop.java b/semaphore/src/main/java/com/iluwatar/semaphore/FruitShop.java
index a360f955c..c74145610 100644
--- a/semaphore/src/main/java/com/iluwatar/semaphore/FruitShop.java
+++ b/semaphore/src/main/java/com/iluwatar/semaphore/FruitShop.java
@@ -31,7 +31,7 @@ public class FruitShop {
/**
* The FruitBowl instances stored in the class.
*/
- private FruitBowl[] bowls = {
+ private final FruitBowl[] bowls = {
new FruitBowl(),
new FruitBowl(),
new FruitBowl()
@@ -40,7 +40,7 @@ public class FruitShop {
/**
* Access flags for each of the FruitBowl instances.
*/
- private boolean[] available = {
+ private final boolean[] available = {
true,
true,
true
@@ -49,7 +49,7 @@ public class FruitShop {
/**
* The Semaphore that controls access to the class resources.
*/
- private Semaphore semaphore;
+ private final Semaphore semaphore;
/**
* FruitShop constructor.
diff --git a/semaphore/src/test/java/com/iluwatar/semaphore/AppTest.java b/semaphore/src/test/java/com/iluwatar/semaphore/AppTest.java
index f450c0593..302796238 100644
--- a/semaphore/src/test/java/com/iluwatar/semaphore/AppTest.java
+++ b/semaphore/src/test/java/com/iluwatar/semaphore/AppTest.java
@@ -25,12 +25,15 @@ package com.iluwatar.semaphore;
import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+
/**
* Application Test Entrypoint
*/
-public class AppTest {
+class AppTest {
+
@Test
- public void test() {
- App.main(new String[]{});
+ void shouldExecuteWithoutException() {
+ assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
diff --git a/servant/pom.xml b/servant/pom.xml
index 395060d50..c7b282c09 100644
--- a/servant/pom.xml
+++ b/servant/pom.xml
@@ -29,7 +29,7 @@
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
servant
diff --git a/servant/src/main/java/com/iluwatar/servant/App.java b/servant/src/main/java/com/iluwatar/servant/App.java
index b68cb9aee..9c4591b05 100644
--- a/servant/src/main/java/com/iluwatar/servant/App.java
+++ b/servant/src/main/java/com/iluwatar/servant/App.java
@@ -39,8 +39,8 @@ public class App {
private static final Logger LOGGER = LoggerFactory.getLogger(App.class);
- private static Servant jenkins = new Servant("Jenkins");
- private static Servant travis = new Servant("Travis");
+ private static final Servant jenkins = new Servant("Jenkins");
+ private static final Servant travis = new Servant("Travis");
/**
* Program entry point.
diff --git a/servant/src/test/java/com/iluwatar/servant/AppTest.java b/servant/src/test/java/com/iluwatar/servant/AppTest.java
index ab1e99e55..d05c22eeb 100644
--- a/servant/src/test/java/com/iluwatar/servant/AppTest.java
+++ b/servant/src/test/java/com/iluwatar/servant/AppTest.java
@@ -25,13 +25,15 @@ package com.iluwatar.servant;
import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+
/**
* Application test
*/
-public class AppTest {
+class AppTest {
@Test
- public void test() {
- App.main(new String[]{});
+ void shouldExecuteWithoutException() {
+ assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
diff --git a/serverless/pom.xml b/serverless/pom.xml
index 1fb55ec47..2880764ec 100644
--- a/serverless/pom.xml
+++ b/serverless/pom.xml
@@ -31,7 +31,7 @@
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
diff --git a/serverless/src/main/java/com/iluwatar/serverless/baas/api/AbstractDynamoDbHandler.java b/serverless/src/main/java/com/iluwatar/serverless/baas/api/AbstractDynamoDbHandler.java
index a13893f70..abe7c388d 100644
--- a/serverless/src/main/java/com/iluwatar/serverless/baas/api/AbstractDynamoDbHandler.java
+++ b/serverless/src/main/java/com/iluwatar/serverless/baas/api/AbstractDynamoDbHandler.java
@@ -40,7 +40,7 @@ import java.util.Map;
public abstract class AbstractDynamoDbHandler {
private DynamoDBMapper dynamoDbMapper;
- private ObjectMapper objectMapper;
+ private final ObjectMapper objectMapper;
public AbstractDynamoDbHandler() {
this.initAmazonDynamoDb();
diff --git a/serverless/src/test/java/com/iluwatar/serverless/baas/api/SavePersonApiHandlerTest.java b/serverless/src/test/java/com/iluwatar/serverless/baas/api/SavePersonApiHandlerTest.java
index ef3909adc..a8c729163 100644
--- a/serverless/src/test/java/com/iluwatar/serverless/baas/api/SavePersonApiHandlerTest.java
+++ b/serverless/src/test/java/com/iluwatar/serverless/baas/api/SavePersonApiHandlerTest.java
@@ -52,7 +52,7 @@ public class SavePersonApiHandlerTest {
@Mock
private DynamoDBMapper dynamoDbMapper;
- private ObjectMapper objectMapper = new ObjectMapper();
+ private final ObjectMapper objectMapper = new ObjectMapper();
@Before
public void setUp() {
diff --git a/service-layer/README.md b/service-layer/README.md
index 910eaeaea..5e8e49ea6 100644
--- a/service-layer/README.md
+++ b/service-layer/README.md
@@ -155,9 +155,9 @@ public interface MagicService {
public class MagicServiceImpl implements MagicService {
- private WizardDao wizardDao;
- private SpellbookDao spellbookDao;
- private SpellDao spellDao;
+ private final WizardDao wizardDao;
+ private final SpellbookDao spellbookDao;
+ private final SpellDao spellDao;
public MagicServiceImpl(WizardDao wizardDao, SpellbookDao spellbookDao, SpellDao spellDao) {
this.wizardDao = wizardDao;
diff --git a/service-layer/pom.xml b/service-layer/pom.xml
index 881ec8ba6..071cf0f49 100644
--- a/service-layer/pom.xml
+++ b/service-layer/pom.xml
@@ -29,7 +29,7 @@
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
service-layer
diff --git a/service-layer/src/main/java/com/iluwatar/servicelayer/app/App.java b/service-layer/src/main/java/com/iluwatar/servicelayer/app/App.java
index ea660f01e..e360e5c94 100644
--- a/service-layer/src/main/java/com/iluwatar/servicelayer/app/App.java
+++ b/service-layer/src/main/java/com/iluwatar/servicelayer/app/App.java
@@ -55,6 +55,7 @@ import org.slf4j.LoggerFactory;
public class App {
private static final Logger LOGGER = LoggerFactory.getLogger(App.class);
+ public static final String BOOK_OF_IDORES = "Book of Idores";
/**
* Program entry point.
@@ -135,7 +136,7 @@ public class App {
spellbook4.addSpell(spell11);
spellbook4.addSpell(spell12);
spellbookDao.merge(spellbook4);
- var spellbook5 = new Spellbook("Book of Idores");
+ var spellbook5 = new Spellbook(BOOK_OF_IDORES);
spellbookDao.persist(spellbook5);
spellbook5.addSpell(spell13);
spellbookDao.merge(spellbook5);
@@ -164,7 +165,7 @@ public class App {
wizardDao.merge(wizard2);
var wizard3 = new Wizard("Xuban Munoa");
wizardDao.persist(wizard3);
- wizard3.addSpellbook(spellbookDao.findByName("Book of Idores"));
+ wizard3.addSpellbook(spellbookDao.findByName(BOOK_OF_IDORES));
wizard3.addSpellbook(spellbookDao.findByName("Book of Opaen"));
wizardDao.merge(wizard3);
var wizard4 = new Wizard("Blasius Dehooge");
@@ -188,7 +189,7 @@ public class App {
LOGGER.info("Enumerating all spells");
service.findAllSpells().stream().map(Spell::getName).forEach(LOGGER::info);
LOGGER.info("Find wizards with spellbook 'Book of Idores'");
- var wizardsWithSpellbook = service.findWizardsWithSpellbook("Book of Idores");
+ var wizardsWithSpellbook = service.findWizardsWithSpellbook(BOOK_OF_IDORES);
wizardsWithSpellbook.forEach(w -> LOGGER.info("{} has 'Book of Idores'", w.getName()));
LOGGER.info("Find wizards with spell 'Fireball'");
var wizardsWithSpell = service.findWizardsWithSpell("Fireball");
diff --git a/service-layer/src/main/java/com/iluwatar/servicelayer/magic/MagicServiceImpl.java b/service-layer/src/main/java/com/iluwatar/servicelayer/magic/MagicServiceImpl.java
index 962487bd9..cdcf926d0 100644
--- a/service-layer/src/main/java/com/iluwatar/servicelayer/magic/MagicServiceImpl.java
+++ b/service-layer/src/main/java/com/iluwatar/servicelayer/magic/MagicServiceImpl.java
@@ -37,9 +37,9 @@ import java.util.List;
*/
public class MagicServiceImpl implements MagicService {
- private WizardDao wizardDao;
- private SpellbookDao spellbookDao;
- private SpellDao spellDao;
+ private final WizardDao wizardDao;
+ private final SpellbookDao spellbookDao;
+ private final SpellDao spellDao;
/**
* Constructor.
diff --git a/service-layer/src/test/java/com/iluwatar/servicelayer/app/AppTest.java b/service-layer/src/test/java/com/iluwatar/servicelayer/app/AppTest.java
index 26aa2b168..5cc1ccfff 100644
--- a/service-layer/src/test/java/com/iluwatar/servicelayer/app/AppTest.java
+++ b/service-layer/src/test/java/com/iluwatar/servicelayer/app/AppTest.java
@@ -27,18 +27,20 @@ import com.iluwatar.servicelayer.hibernate.HibernateUtil;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+
/**
* Application test
*/
-public class AppTest {
+class AppTest {
@Test
- public void test() {
- App.main(new String[]{});
+ void shouldExecuteWithoutException() {
+ assertDoesNotThrow(() -> App.main(new String[]{}));
}
@AfterEach
- public void tearDown() {
+ void tearDown() {
HibernateUtil.dropSession();
}
diff --git a/service-locator/pom.xml b/service-locator/pom.xml
index 1d8e9fcd8..2b0037eb8 100644
--- a/service-locator/pom.xml
+++ b/service-locator/pom.xml
@@ -29,7 +29,7 @@
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
service-locator
diff --git a/service-locator/src/main/java/com/iluwatar/servicelocator/App.java b/service-locator/src/main/java/com/iluwatar/servicelocator/App.java
index efc25bd89..85419b603 100644
--- a/service-locator/src/main/java/com/iluwatar/servicelocator/App.java
+++ b/service-locator/src/main/java/com/iluwatar/servicelocator/App.java
@@ -37,19 +37,22 @@ package com.iluwatar.servicelocator;
*/
public class App {
+ public static final String JNDI_SERVICE_A = "jndi/serviceA";
+ public static final String JNDI_SERVICE_B = "jndi/serviceB";
+
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) {
- var service = ServiceLocator.getService("jndi/serviceA");
+ var service = ServiceLocator.getService(JNDI_SERVICE_A);
service.execute();
- service = ServiceLocator.getService("jndi/serviceB");
+ service = ServiceLocator.getService(JNDI_SERVICE_B);
service.execute();
- service = ServiceLocator.getService("jndi/serviceA");
+ service = ServiceLocator.getService(JNDI_SERVICE_A);
service.execute();
- service = ServiceLocator.getService("jndi/serviceA");
+ service = ServiceLocator.getService(JNDI_SERVICE_A);
service.execute();
}
}
diff --git a/service-locator/src/main/java/com/iluwatar/servicelocator/ServiceLocator.java b/service-locator/src/main/java/com/iluwatar/servicelocator/ServiceLocator.java
index 60f0f7c03..4e787d34c 100644
--- a/service-locator/src/main/java/com/iluwatar/servicelocator/ServiceLocator.java
+++ b/service-locator/src/main/java/com/iluwatar/servicelocator/ServiceLocator.java
@@ -31,7 +31,7 @@ package com.iluwatar.servicelocator;
*/
public final class ServiceLocator {
- private static ServiceCache serviceCache = new ServiceCache();
+ private static final ServiceCache serviceCache = new ServiceCache();
private ServiceLocator() {
}
diff --git a/service-locator/src/test/java/com/iluwatar/servicelocator/AppTest.java b/service-locator/src/test/java/com/iluwatar/servicelocator/AppTest.java
index cb4c98c07..75d6f8b05 100644
--- a/service-locator/src/test/java/com/iluwatar/servicelocator/AppTest.java
+++ b/service-locator/src/test/java/com/iluwatar/servicelocator/AppTest.java
@@ -25,13 +25,15 @@ package com.iluwatar.servicelocator;
import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+
/**
* Application test
*/
-public class AppTest {
+class AppTest {
@Test
- public void test() {
- App.main(new String[]{});
+ void shouldExecuteWithoutException() {
+ assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
diff --git a/sharding/pom.xml b/sharding/pom.xml
index a641ce375..5f6c40ee5 100644
--- a/sharding/pom.xml
+++ b/sharding/pom.xml
@@ -29,7 +29,7 @@
java-design-patterns
com.iluwatar
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
4.0.0
@@ -40,6 +40,11 @@
junit
junit
+
+ org.junit.jupiter
+ junit-jupiter-engine
+ test
+
diff --git a/sharding/src/main/java/com/iluwatar/sharding/App.java b/sharding/src/main/java/com/iluwatar/sharding/App.java
index fe3cb7923..109f88cf8 100644
--- a/sharding/src/main/java/com/iluwatar/sharding/App.java
+++ b/sharding/src/main/java/com/iluwatar/sharding/App.java
@@ -36,10 +36,10 @@ public class App {
*/
public static void main(String[] args) {
- var data1 = new Data(1, "data1", Data.DataType.type1);
- var data2 = new Data(2, "data2", Data.DataType.type2);
- var data3 = new Data(3, "data3", Data.DataType.type3);
- var data4 = new Data(4, "data4", Data.DataType.type1);
+ var data1 = new Data(1, "data1", Data.DataType.TYPE_1);
+ var data2 = new Data(2, "data2", Data.DataType.TYPE_2);
+ var data3 = new Data(3, "data3", Data.DataType.TYPE_3);
+ var data4 = new Data(4, "data4", Data.DataType.TYPE_1);
var shard1 = new Shard(1);
var shard2 = new Shard(2);
diff --git a/sharding/src/main/java/com/iluwatar/sharding/Data.java b/sharding/src/main/java/com/iluwatar/sharding/Data.java
index 92e84e93a..abe49f15d 100644
--- a/sharding/src/main/java/com/iluwatar/sharding/Data.java
+++ b/sharding/src/main/java/com/iluwatar/sharding/Data.java
@@ -71,7 +71,7 @@ public class Data {
}
enum DataType {
- type1, type2, type3
+ TYPE_1, TYPE_2, TYPE_3
}
@Override
diff --git a/sharding/src/main/java/com/iluwatar/sharding/LookupShardManager.java b/sharding/src/main/java/com/iluwatar/sharding/LookupShardManager.java
index 4948c2a19..ce239c156 100644
--- a/sharding/src/main/java/com/iluwatar/sharding/LookupShardManager.java
+++ b/sharding/src/main/java/com/iluwatar/sharding/LookupShardManager.java
@@ -39,7 +39,7 @@ public class LookupShardManager extends ShardManager {
private static final Logger LOGGER = LoggerFactory.getLogger(LookupShardManager.class);
- private Map lookupMap = new HashMap<>();
+ private final Map lookupMap = new HashMap<>();
@Override
public int storeData(Data data) {
diff --git a/sharding/src/main/java/com/iluwatar/sharding/RangeShardManager.java b/sharding/src/main/java/com/iluwatar/sharding/RangeShardManager.java
index bdb862571..d06cd51da 100644
--- a/sharding/src/main/java/com/iluwatar/sharding/RangeShardManager.java
+++ b/sharding/src/main/java/com/iluwatar/sharding/RangeShardManager.java
@@ -47,11 +47,11 @@ public class RangeShardManager extends ShardManager {
protected int allocateShard(Data data) {
var type = data.getType();
switch (type) {
- case type1:
+ case TYPE_1:
return 1;
- case type2:
+ case TYPE_2:
return 2;
- case type3:
+ case TYPE_3:
return 3;
default:
return -1;
diff --git a/sharding/src/main/java/com/iluwatar/sharding/Shard.java b/sharding/src/main/java/com/iluwatar/sharding/Shard.java
index eb0814258..56037bc3a 100644
--- a/sharding/src/main/java/com/iluwatar/sharding/Shard.java
+++ b/sharding/src/main/java/com/iluwatar/sharding/Shard.java
@@ -33,7 +33,7 @@ public class Shard {
private final int id;
- private Map dataStore;
+ private final Map dataStore;
public Shard(final int id) {
this.id = id;
diff --git a/sharding/src/test/java/com/iluwatar/sharding/AppTest.java b/sharding/src/test/java/com/iluwatar/sharding/AppTest.java
index 40e6391bf..f23b71d1e 100644
--- a/sharding/src/test/java/com/iluwatar/sharding/AppTest.java
+++ b/sharding/src/test/java/com/iluwatar/sharding/AppTest.java
@@ -25,14 +25,16 @@ package com.iluwatar.sharding;
import org.junit.Test;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+
/**
* Unit tests for App class.
*/
public class AppTest {
@Test
- public void testMain() {
- App.main(new String[]{});
+ public void shouldExecuteWithoutException() {
+ assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
diff --git a/sharding/src/test/java/com/iluwatar/sharding/HashShardManagerTest.java b/sharding/src/test/java/com/iluwatar/sharding/HashShardManagerTest.java
index 6418cf0c4..e19de75d2 100644
--- a/sharding/src/test/java/com/iluwatar/sharding/HashShardManagerTest.java
+++ b/sharding/src/test/java/com/iluwatar/sharding/HashShardManagerTest.java
@@ -56,7 +56,7 @@ public class HashShardManagerTest {
@Test
public void testStoreData() {
- var data = new Data(1, "test", Data.DataType.type1);
+ var data = new Data(1, "test", Data.DataType.TYPE_1);
hashShardManager.storeData(data);
Assert.assertEquals(data, hashShardManager.getShardById(1).getDataById(1));
}
diff --git a/sharding/src/test/java/com/iluwatar/sharding/LookupShardManagerTest.java b/sharding/src/test/java/com/iluwatar/sharding/LookupShardManagerTest.java
index 70650bb50..c6ce5851d 100644
--- a/sharding/src/test/java/com/iluwatar/sharding/LookupShardManagerTest.java
+++ b/sharding/src/test/java/com/iluwatar/sharding/LookupShardManagerTest.java
@@ -52,7 +52,7 @@ public class LookupShardManagerTest {
@Test
public void testStoreData() {
try {
- var data = new Data(1, "test", Data.DataType.type1);
+ var data = new Data(1, "test", Data.DataType.TYPE_1);
lookupShardManager.storeData(data);
var field = LookupShardManager.class.getDeclaredField("lookupMap");
field.setAccessible(true);
diff --git a/sharding/src/test/java/com/iluwatar/sharding/RangeShardManagerTest.java b/sharding/src/test/java/com/iluwatar/sharding/RangeShardManagerTest.java
index 997687dfc..9ea4a2d86 100644
--- a/sharding/src/test/java/com/iluwatar/sharding/RangeShardManagerTest.java
+++ b/sharding/src/test/java/com/iluwatar/sharding/RangeShardManagerTest.java
@@ -50,7 +50,7 @@ public class RangeShardManagerTest {
@Test
public void testStoreData() {
- var data = new Data(1, "test", Data.DataType.type1);
+ var data = new Data(1, "test", Data.DataType.TYPE_1);
rangeShardManager.storeData(data);
Assert.assertEquals(data, rangeShardManager.getShardById(1).getDataById(1));
}
diff --git a/sharding/src/test/java/com/iluwatar/sharding/ShardTest.java b/sharding/src/test/java/com/iluwatar/sharding/ShardTest.java
index a747933af..a12ab3a97 100644
--- a/sharding/src/test/java/com/iluwatar/sharding/ShardTest.java
+++ b/sharding/src/test/java/com/iluwatar/sharding/ShardTest.java
@@ -42,7 +42,7 @@ public class ShardTest {
@Before
public void setup() {
- data = new Data(1, "test", Data.DataType.type1);
+ data = new Data(1, "test", Data.DataType.TYPE_1);
shard = new Shard(1);
}
diff --git a/singleton/README.md b/singleton/README.md
index 83f7fb355..60a103a3b 100644
--- a/singleton/README.md
+++ b/singleton/README.md
@@ -34,7 +34,7 @@ Joshua Bloch, Effective Java 2nd Edition p.18
```java
public enum EnumIvoryTower {
- INSTANCE;
+ INSTANCE
}
```
diff --git a/singleton/pom.xml b/singleton/pom.xml
index b09602d0e..80a34ea86 100644
--- a/singleton/pom.xml
+++ b/singleton/pom.xml
@@ -29,7 +29,7 @@
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
singleton
diff --git a/singleton/src/main/java/com/iluwatar/singleton/InitializingOnDemandHolderIdiom.java b/singleton/src/main/java/com/iluwatar/singleton/InitializingOnDemandHolderIdiom.java
index 205a7bd80..42779ff71 100644
--- a/singleton/src/main/java/com/iluwatar/singleton/InitializingOnDemandHolderIdiom.java
+++ b/singleton/src/main/java/com/iluwatar/singleton/InitializingOnDemandHolderIdiom.java
@@ -45,7 +45,7 @@ public final class InitializingOnDemandHolderIdiom {
}
/**
- * Sigleton instance.
+ * Singleton instance.
*
* @return Singleton instance
*/
diff --git a/singleton/src/test/java/com/iluwatar/singleton/AppTest.java b/singleton/src/test/java/com/iluwatar/singleton/AppTest.java
index b7c55ddea..5d3f247de 100644
--- a/singleton/src/test/java/com/iluwatar/singleton/AppTest.java
+++ b/singleton/src/test/java/com/iluwatar/singleton/AppTest.java
@@ -25,13 +25,15 @@ package com.iluwatar.singleton;
import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+
/**
* Application test.
*/
-public class AppTest {
+class AppTest {
@Test
- public void test() {
- App.main(new String[]{});
+ void shouldExecuteWithoutException() {
+ assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
diff --git a/spatial-partition/pom.xml b/spatial-partition/pom.xml
index 7312427d0..fe749b22b 100644
--- a/spatial-partition/pom.xml
+++ b/spatial-partition/pom.xml
@@ -46,7 +46,7 @@
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
spatial-partition
diff --git a/spatial-partition/src/main/java/com/iluwatar/spatialpartition/App.java b/spatial-partition/src/main/java/com/iluwatar/spatialpartition/App.java
index 8a0e2383c..083d6a019 100644
--- a/spatial-partition/src/main/java/com/iluwatar/spatialpartition/App.java
+++ b/spatial-partition/src/main/java/com/iluwatar/spatialpartition/App.java
@@ -59,6 +59,7 @@ import org.slf4j.LoggerFactory;
public class App {
private static final Logger LOGGER = LoggerFactory.getLogger(App.class);
+ private static final String BUBBLE = "Bubble ";
static void noSpatialPartition(int numOfMovements, Hashtable bubbles) {
//all bubbles have to be checked for collision for all bubbles
@@ -76,7 +77,7 @@ public class App {
numOfMovements--;
}
//bubbles not popped
- bubbles.keySet().stream().map(key -> "Bubble " + key + " not popped").forEach(LOGGER::info);
+ bubbles.keySet().stream().map(key -> BUBBLE + key + " not popped").forEach(LOGGER::info);
}
static void withSpatialPartition(
@@ -99,7 +100,7 @@ public class App {
numOfMovements--;
}
//bubbles not popped
- bubbles.keySet().stream().map(key -> "Bubble " + key + " not popped").forEach(LOGGER::info);
+ bubbles.keySet().stream().map(key -> BUBBLE + key + " not popped").forEach(LOGGER::info);
}
/**
@@ -116,7 +117,7 @@ public class App {
var b = new Bubble(rand.nextInt(300), rand.nextInt(300), i, rand.nextInt(2) + 1);
bubbles1.put(i, b);
bubbles2.put(i, b);
- LOGGER.info("Bubble " + i + " with radius " + b.radius
+ LOGGER.info(BUBBLE + i + " with radius " + b.radius
+ " added at (" + b.coordinateX + "," + b.coordinateY + ")");
}
diff --git a/spatial-partition/src/main/java/com/iluwatar/spatialpartition/SpatialPartitionBubbles.java b/spatial-partition/src/main/java/com/iluwatar/spatialpartition/SpatialPartitionBubbles.java
index b3f60632f..c0eb5ecde 100644
--- a/spatial-partition/src/main/java/com/iluwatar/spatialpartition/SpatialPartitionBubbles.java
+++ b/spatial-partition/src/main/java/com/iluwatar/spatialpartition/SpatialPartitionBubbles.java
@@ -34,8 +34,8 @@ import java.util.Hashtable;
public class SpatialPartitionBubbles extends SpatialPartitionGeneric {
- final Hashtable bubbles;
- final QuadTree quadTree;
+ private final Hashtable bubbles;
+ private final QuadTree quadTree;
SpatialPartitionBubbles(Hashtable bubbles, QuadTree quadTree) {
this.bubbles = bubbles;
diff --git a/specification/README.md b/specification/README.md
index 6e52bd2e7..6cc0c702f 100644
--- a/specification/README.md
+++ b/specification/README.md
@@ -146,7 +146,7 @@ public abstract class AbstractSelector implements Predicate {
```java
public class ConjunctionSelector extends AbstractSelector {
- private List> leafComponents;
+ private final List> leafComponents;
@SafeVarargs
ConjunctionSelector(AbstractSelector... selectors) {
diff --git a/specification/pom.xml b/specification/pom.xml
index 9214e984e..1494ca305 100644
--- a/specification/pom.xml
+++ b/specification/pom.xml
@@ -29,7 +29,7 @@
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
specification
diff --git a/specification/src/main/java/com/iluwatar/specification/creature/AbstractCreature.java b/specification/src/main/java/com/iluwatar/specification/creature/AbstractCreature.java
index 6b359d8ac..214ae4562 100644
--- a/specification/src/main/java/com/iluwatar/specification/creature/AbstractCreature.java
+++ b/specification/src/main/java/com/iluwatar/specification/creature/AbstractCreature.java
@@ -33,11 +33,11 @@ import com.iluwatar.specification.property.Size;
*/
public abstract class AbstractCreature implements Creature {
- private String name;
- private Size size;
- private Movement movement;
- private Color color;
- private Mass mass;
+ private final String name;
+ private final Size size;
+ private final Movement movement;
+ private final Color color;
+ private final Mass mass;
/**
* Constructor.
diff --git a/specification/src/main/java/com/iluwatar/specification/property/Color.java b/specification/src/main/java/com/iluwatar/specification/property/Color.java
index 6e96b5813..b3128054e 100644
--- a/specification/src/main/java/com/iluwatar/specification/property/Color.java
+++ b/specification/src/main/java/com/iluwatar/specification/property/Color.java
@@ -30,7 +30,7 @@ public enum Color {
DARK("dark"), LIGHT("light"), GREEN("green"), RED("red");
- private String title;
+ private final String title;
Color(String title) {
this.title = title;
diff --git a/specification/src/main/java/com/iluwatar/specification/property/Mass.java b/specification/src/main/java/com/iluwatar/specification/property/Mass.java
index b2d6ddc66..e0e90aa06 100644
--- a/specification/src/main/java/com/iluwatar/specification/property/Mass.java
+++ b/specification/src/main/java/com/iluwatar/specification/property/Mass.java
@@ -28,8 +28,8 @@ package com.iluwatar.specification.property;
*/
public class Mass {
- private double value;
- private String title;
+ private final double value;
+ private final String title;
public Mass(double value) {
this.value = value;
diff --git a/specification/src/main/java/com/iluwatar/specification/property/Movement.java b/specification/src/main/java/com/iluwatar/specification/property/Movement.java
index f76b0584f..fcdcfae70 100644
--- a/specification/src/main/java/com/iluwatar/specification/property/Movement.java
+++ b/specification/src/main/java/com/iluwatar/specification/property/Movement.java
@@ -30,7 +30,7 @@ public enum Movement {
WALKING("walking"), SWIMMING("swimming"), FLYING("flying");
- private String title;
+ private final String title;
Movement(String title) {
this.title = title;
diff --git a/specification/src/main/java/com/iluwatar/specification/property/Size.java b/specification/src/main/java/com/iluwatar/specification/property/Size.java
index 27bc48024..c5ad5525c 100644
--- a/specification/src/main/java/com/iluwatar/specification/property/Size.java
+++ b/specification/src/main/java/com/iluwatar/specification/property/Size.java
@@ -30,7 +30,7 @@ public enum Size {
SMALL("small"), NORMAL("normal"), LARGE("large");
- private String title;
+ private final String title;
Size(String title) {
this.title = title;
diff --git a/specification/src/main/java/com/iluwatar/specification/selector/ConjunctionSelector.java b/specification/src/main/java/com/iluwatar/specification/selector/ConjunctionSelector.java
index bd29aa260..661c8bceb 100644
--- a/specification/src/main/java/com/iluwatar/specification/selector/ConjunctionSelector.java
+++ b/specification/src/main/java/com/iluwatar/specification/selector/ConjunctionSelector.java
@@ -30,7 +30,7 @@ import java.util.List;
*/
public class ConjunctionSelector extends AbstractSelector {
- private List> leafComponents;
+ private final List> leafComponents;
@SafeVarargs
ConjunctionSelector(AbstractSelector... selectors) {
diff --git a/specification/src/main/java/com/iluwatar/specification/selector/DisjunctionSelector.java b/specification/src/main/java/com/iluwatar/specification/selector/DisjunctionSelector.java
index 1fb38a43d..32dcf7e73 100644
--- a/specification/src/main/java/com/iluwatar/specification/selector/DisjunctionSelector.java
+++ b/specification/src/main/java/com/iluwatar/specification/selector/DisjunctionSelector.java
@@ -30,7 +30,7 @@ import java.util.List;
*/
public class DisjunctionSelector extends AbstractSelector {
- private List> leafComponents;
+ private final List> leafComponents;
@SafeVarargs
DisjunctionSelector(AbstractSelector... selectors) {
diff --git a/specification/src/main/java/com/iluwatar/specification/selector/NegationSelector.java b/specification/src/main/java/com/iluwatar/specification/selector/NegationSelector.java
index ad3063000..30302baa2 100644
--- a/specification/src/main/java/com/iluwatar/specification/selector/NegationSelector.java
+++ b/specification/src/main/java/com/iluwatar/specification/selector/NegationSelector.java
@@ -30,7 +30,7 @@ package com.iluwatar.specification.selector;
*/
public class NegationSelector extends AbstractSelector {
- private AbstractSelector component;
+ private final AbstractSelector component;
NegationSelector(AbstractSelector selector) {
this.component = selector;
diff --git a/specification/src/test/java/com/iluwatar/specification/app/AppTest.java b/specification/src/test/java/com/iluwatar/specification/app/AppTest.java
index bc6f2226f..4b29e11e8 100644
--- a/specification/src/test/java/com/iluwatar/specification/app/AppTest.java
+++ b/specification/src/test/java/com/iluwatar/specification/app/AppTest.java
@@ -25,13 +25,15 @@ package com.iluwatar.specification.app;
import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+
/**
* Application test
*/
-public class AppTest {
+class AppTest {
@Test
- public void test() {
- App.main(new String[]{});
+ void shouldExecuteWithoutException() {
+ assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
diff --git a/state/README.md b/state/README.md
index 7be4d3351..a8dd2b5fc 100644
--- a/state/README.md
+++ b/state/README.md
@@ -43,7 +43,7 @@ public class PeacefulState implements State {
private static final Logger LOGGER = LoggerFactory.getLogger(PeacefulState.class);
- private Mammoth mammoth;
+ private final Mammoth mammoth;
public PeacefulState(Mammoth mammoth) {
this.mammoth = mammoth;
@@ -64,7 +64,7 @@ public class AngryState implements State {
private static final Logger LOGGER = LoggerFactory.getLogger(AngryState.class);
- private Mammoth mammoth;
+ private final Mammoth mammoth;
public AngryState(Mammoth mammoth) {
this.mammoth = mammoth;
diff --git a/state/pom.xml b/state/pom.xml
index b1ff3f5f3..a434dabe4 100644
--- a/state/pom.xml
+++ b/state/pom.xml
@@ -29,7 +29,7 @@
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
state
diff --git a/state/src/main/java/com/iluwatar/state/AngryState.java b/state/src/main/java/com/iluwatar/state/AngryState.java
index 8dc296c53..e105262b8 100644
--- a/state/src/main/java/com/iluwatar/state/AngryState.java
+++ b/state/src/main/java/com/iluwatar/state/AngryState.java
@@ -1,52 +1,52 @@
-/*
- * The MIT License
- * Copyright © 2014-2019 Ilkka Seppälä
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-
-package com.iluwatar.state;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Angry state.
- */
-public class AngryState implements State {
-
- private static final Logger LOGGER = LoggerFactory.getLogger(AngryState.class);
-
- private Mammoth mammoth;
-
- public AngryState(Mammoth mammoth) {
- this.mammoth = mammoth;
- }
-
- @Override
- public void observe() {
- LOGGER.info("{} is furious!", mammoth);
- }
-
- @Override
- public void onEnterState() {
- LOGGER.info("{} gets angry!", mammoth);
- }
-
-}
+/*
+ * The MIT License
+ * Copyright © 2014-2019 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+package com.iluwatar.state;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Angry state.
+ */
+public class AngryState implements State {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(AngryState.class);
+
+ private final Mammoth mammoth;
+
+ public AngryState(Mammoth mammoth) {
+ this.mammoth = mammoth;
+ }
+
+ @Override
+ public void observe() {
+ LOGGER.info("{} is furious!", mammoth);
+ }
+
+ @Override
+ public void onEnterState() {
+ LOGGER.info("{} gets angry!", mammoth);
+ }
+
+}
diff --git a/state/src/main/java/com/iluwatar/state/PeacefulState.java b/state/src/main/java/com/iluwatar/state/PeacefulState.java
index ed83a0738..adf8be209 100644
--- a/state/src/main/java/com/iluwatar/state/PeacefulState.java
+++ b/state/src/main/java/com/iluwatar/state/PeacefulState.java
@@ -1,52 +1,52 @@
-/*
- * The MIT License
- * Copyright © 2014-2019 Ilkka Seppälä
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-
-package com.iluwatar.state;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Peaceful state.
- */
-public class PeacefulState implements State {
-
- private static final Logger LOGGER = LoggerFactory.getLogger(PeacefulState.class);
-
- private Mammoth mammoth;
-
- public PeacefulState(Mammoth mammoth) {
- this.mammoth = mammoth;
- }
-
- @Override
- public void observe() {
- LOGGER.info("{} is calm and peaceful.", mammoth);
- }
-
- @Override
- public void onEnterState() {
- LOGGER.info("{} calms down.", mammoth);
- }
-
-}
+/*
+ * The MIT License
+ * Copyright © 2014-2019 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+package com.iluwatar.state;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Peaceful state.
+ */
+public class PeacefulState implements State {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(PeacefulState.class);
+
+ private final Mammoth mammoth;
+
+ public PeacefulState(Mammoth mammoth) {
+ this.mammoth = mammoth;
+ }
+
+ @Override
+ public void observe() {
+ LOGGER.info("{} is calm and peaceful.", mammoth);
+ }
+
+ @Override
+ public void onEnterState() {
+ LOGGER.info("{} calms down.", mammoth);
+ }
+
+}
diff --git a/state/src/test/java/com/iluwatar/state/AppTest.java b/state/src/test/java/com/iluwatar/state/AppTest.java
index 9f7b65ff2..90beddb33 100644
--- a/state/src/test/java/com/iluwatar/state/AppTest.java
+++ b/state/src/test/java/com/iluwatar/state/AppTest.java
@@ -25,13 +25,15 @@ package com.iluwatar.state;
import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+
/**
* Application test
*/
-public class AppTest {
+class AppTest {
@Test
- public void test() {
- App.main(new String[]{});
+ void shouldExecuteWithoutException() {
+ assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
diff --git a/state/src/test/java/com/iluwatar/state/MammothTest.java b/state/src/test/java/com/iluwatar/state/MammothTest.java
index 15624c7ab..4cc6e0adb 100644
--- a/state/src/test/java/com/iluwatar/state/MammothTest.java
+++ b/state/src/test/java/com/iluwatar/state/MammothTest.java
@@ -96,7 +96,7 @@ public class MammothTest {
}
private class InMemoryAppender extends AppenderBase {
- private List log = new LinkedList<>();
+ private final List log = new LinkedList<>();
public InMemoryAppender() {
((Logger) LoggerFactory.getLogger("root")).addAppender(this);
diff --git a/step-builder/pom.xml b/step-builder/pom.xml
index 3cea3b158..de5763695 100644
--- a/step-builder/pom.xml
+++ b/step-builder/pom.xml
@@ -30,7 +30,7 @@
java-design-patterns
com.iluwatar
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
step-builder
diff --git a/step-builder/src/main/java/com/iluwatar/stepbuilder/CharacterStepBuilder.java b/step-builder/src/main/java/com/iluwatar/stepbuilder/CharacterStepBuilder.java
index a0c7f84e6..5be38e471 100644
--- a/step-builder/src/main/java/com/iluwatar/stepbuilder/CharacterStepBuilder.java
+++ b/step-builder/src/main/java/com/iluwatar/stepbuilder/CharacterStepBuilder.java
@@ -105,7 +105,7 @@ public final class CharacterStepBuilder {
private String wizardClass;
private String weapon;
private String spell;
- private List abilities = new ArrayList<>();
+ private final List abilities = new ArrayList<>();
@Override
public ClassStep name(String name) {
diff --git a/step-builder/src/test/java/com/iluwatar/stepbuilder/AppTest.java b/step-builder/src/test/java/com/iluwatar/stepbuilder/AppTest.java
index 1f3fc6238..20119b41b 100644
--- a/step-builder/src/test/java/com/iluwatar/stepbuilder/AppTest.java
+++ b/step-builder/src/test/java/com/iluwatar/stepbuilder/AppTest.java
@@ -25,13 +25,15 @@ package com.iluwatar.stepbuilder;
import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+
/**
* Application test
*/
-public class AppTest {
+class AppTest {
@Test
- public void test() {
- App.main(new String[]{});
+ void shouldExecuteWithoutException() {
+ assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
diff --git a/strangler/pom.xml b/strangler/pom.xml
index 4a1fb42ba..7cb2ff263 100644
--- a/strangler/pom.xml
+++ b/strangler/pom.xml
@@ -29,7 +29,7 @@
java-design-patterns
com.iluwatar
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
4.0.0
diff --git a/strangler/src/main/java/com/iluwatar/strangler/NewSource.java b/strangler/src/main/java/com/iluwatar/strangler/NewSource.java
index f53a31bd8..8cc1822fe 100644
--- a/strangler/src/main/java/com/iluwatar/strangler/NewSource.java
+++ b/strangler/src/main/java/com/iluwatar/strangler/NewSource.java
@@ -34,9 +34,10 @@ import org.slf4j.LoggerFactory;
public class NewSource {
private static final Logger LOGGER = LoggerFactory.getLogger(NewSource.class);
private static final String VERSION = "2.0";
+ public static final String SOURCE_MODULE = "Source module {}";
public int accumulateSum(int... nums) {
- LOGGER.info("Source module {}", VERSION);
+ LOGGER.info(SOURCE_MODULE, VERSION);
return Arrays.stream(nums).reduce(0, Integer::sum);
}
@@ -45,12 +46,12 @@ public class NewSource {
* Replace old one in {@link OldSource}
*/
public int accumulateMul(int... nums) {
- LOGGER.info("Source module {}", VERSION);
+ LOGGER.info(SOURCE_MODULE, VERSION);
return Arrays.stream(nums).reduce(1, (a, b) -> a * b);
}
public boolean ifNonZero(int... nums) {
- LOGGER.info("Source module {}", VERSION);
+ LOGGER.info(SOURCE_MODULE, VERSION);
return Arrays.stream(nums).allMatch(num -> num != 0);
}
}
diff --git a/strangler/src/test/java/com/iluwatar/strangler/AppTest.java b/strangler/src/test/java/com/iluwatar/strangler/AppTest.java
index a9e878a94..7e45d63ec 100644
--- a/strangler/src/test/java/com/iluwatar/strangler/AppTest.java
+++ b/strangler/src/test/java/com/iluwatar/strangler/AppTest.java
@@ -25,12 +25,15 @@ package com.iluwatar.strangler;
import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+
/**
* Application test
*/
-public class AppTest {
+class AppTest {
+
@Test
- public void test() {
- App.main(new String[]{});
+ void shouldExecuteWithoutException() {
+ assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
diff --git a/strategy/pom.xml b/strategy/pom.xml
index cd1395c7a..0f3b0e830 100644
--- a/strategy/pom.xml
+++ b/strategy/pom.xml
@@ -29,7 +29,7 @@
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
strategy
diff --git a/strategy/src/test/java/com/iluwatar/strategy/AppTest.java b/strategy/src/test/java/com/iluwatar/strategy/AppTest.java
index f1137c4c5..174334f51 100644
--- a/strategy/src/test/java/com/iluwatar/strategy/AppTest.java
+++ b/strategy/src/test/java/com/iluwatar/strategy/AppTest.java
@@ -25,13 +25,15 @@ package com.iluwatar.strategy;
import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+
/**
* Application test.
*/
-public class AppTest {
+class AppTest {
@Test
- public void test() {
- App.main(new String[]{});
+ void shouldExecuteWithoutException() {
+ assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
diff --git a/strategy/src/test/java/com/iluwatar/strategy/DragonSlayingStrategyTest.java b/strategy/src/test/java/com/iluwatar/strategy/DragonSlayingStrategyTest.java
index cca82cefc..0b5a2d615 100644
--- a/strategy/src/test/java/com/iluwatar/strategy/DragonSlayingStrategyTest.java
+++ b/strategy/src/test/java/com/iluwatar/strategy/DragonSlayingStrategyTest.java
@@ -91,7 +91,7 @@ public class DragonSlayingStrategyTest {
}
private class InMemoryAppender extends AppenderBase {
- private List log = new LinkedList<>();
+ private final List log = new LinkedList<>();
public InMemoryAppender() {
((Logger) LoggerFactory.getLogger("root")).addAppender(this);
diff --git a/subclass-sandbox/pom.xml b/subclass-sandbox/pom.xml
index 264343b00..780547e95 100644
--- a/subclass-sandbox/pom.xml
+++ b/subclass-sandbox/pom.xml
@@ -29,7 +29,7 @@
java-design-patterns
com.iluwatar
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
4.0.0
@@ -42,7 +42,12 @@
com.github.stefanbirkner
- system-rules
+ system-lambda
+
+
+ org.junit.jupiter
+ junit-jupiter-engine
+ test
diff --git a/subclass-sandbox/src/test/java/com/iluwatar/subclasssandbox/AppTest.java b/subclass-sandbox/src/test/java/com/iluwatar/subclasssandbox/AppTest.java
index 83ba5315f..8d4865f6b 100644
--- a/subclass-sandbox/src/test/java/com/iluwatar/subclasssandbox/AppTest.java
+++ b/subclass-sandbox/src/test/java/com/iluwatar/subclasssandbox/AppTest.java
@@ -25,13 +25,15 @@ package com.iluwatar.subclasssandbox;
import org.junit.Test;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+
/**
* App unit tests.
*/
public class AppTest {
@Test
- public void testMain() {
- App.main(new String[]{});
+ public void shouldExecuteWithoutException() {
+ assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
diff --git a/subclass-sandbox/src/test/java/com/iluwatar/subclasssandbox/GroundDiveTest.java b/subclass-sandbox/src/test/java/com/iluwatar/subclasssandbox/GroundDiveTest.java
index 97e2ac67d..3b379946c 100644
--- a/subclass-sandbox/src/test/java/com/iluwatar/subclasssandbox/GroundDiveTest.java
+++ b/subclass-sandbox/src/test/java/com/iluwatar/subclasssandbox/GroundDiveTest.java
@@ -23,55 +23,48 @@
package com.iluwatar.subclasssandbox;
+import com.github.stefanbirkner.systemlambda.Statement;
import org.junit.Assert;
-import org.junit.Rule;
import org.junit.Test;
-import org.junit.contrib.java.lang.system.SystemOutRule;
+
+import static com.github.stefanbirkner.systemlambda.SystemLambda.tapSystemOutNormalized;
/**
* GroundDive unit tests.
*/
public class GroundDiveTest {
- @Rule
- public SystemOutRule log = new SystemOutRule().enableLog();
-
@Test
- public void testMove() {
- log.clearLog();
+ public void testMove() throws Exception {
var groundDive = new GroundDive();
groundDive.move(1.0, 1.0, 1.0);
- var outputLog = getLogContent(log.getLog());
+ var outputLog = getLogContent(() -> groundDive.move(1.0, 1.0, 1.0));
var expectedLog = "Move to ( 1.0, 1.0, 1.0 )";
Assert.assertEquals(outputLog, expectedLog);
}
@Test
- public void testPlaySound() {
- log.clearLog();
+ public void testPlaySound() throws Exception {
var groundDive = new GroundDive();
- groundDive.playSound("SOUND_NAME", 1);
- var outputLog = getLogContent(log.getLog());
+ var outputLog = getLogContent(() -> groundDive.playSound("SOUND_NAME", 1));
var expectedLog = "Play SOUND_NAME with volumn 1";
Assert.assertEquals(outputLog, expectedLog);
}
@Test
- public void testSpawnParticles() {
- log.clearLog();
+ public void testSpawnParticles() throws Exception {
var groundDive = new GroundDive();
- groundDive.spawnParticles("PARTICLE_TYPE", 100);
- final var outputLog = getLogContent(log.getLog());
+ final var outputLog = getLogContent(
+ () -> groundDive.spawnParticles("PARTICLE_TYPE", 100));
final var expectedLog = "Spawn 100 particle with type PARTICLE_TYPE";
Assert.assertEquals(outputLog, expectedLog);
}
@Test
- public void testActivate() {
- log.clearLog();
+ public void testActivate() throws Exception {
var groundDive = new GroundDive();
- groundDive.activate();
- var logs = log.getLog().split("\n");
+ var logs = tapSystemOutNormalized(groundDive::activate)
+ .split("\n");
final var expectedSize = 3;
final var log1 = logs[0].split("-")[1].trim() + " -" + logs[0].split("-")[2].trim();
final var expectedLog1 = "Move to ( 0.0, 0.0, -20.0 )";
@@ -85,6 +78,11 @@ public class GroundDiveTest {
Assert.assertEquals(log3, expectedLog3);
}
+ private String getLogContent(Statement statement) throws Exception {
+ var log = tapSystemOutNormalized(statement);
+ return getLogContent(log);
+ }
+
private String getLogContent(String log) {
return log.split("-")[1].trim();
}
diff --git a/subclass-sandbox/src/test/java/com/iluwatar/subclasssandbox/SkyLaunchTest.java b/subclass-sandbox/src/test/java/com/iluwatar/subclasssandbox/SkyLaunchTest.java
index e192737f6..d285e6c7d 100644
--- a/subclass-sandbox/src/test/java/com/iluwatar/subclasssandbox/SkyLaunchTest.java
+++ b/subclass-sandbox/src/test/java/com/iluwatar/subclasssandbox/SkyLaunchTest.java
@@ -23,55 +23,47 @@
package com.iluwatar.subclasssandbox;
+import com.github.stefanbirkner.systemlambda.Statement;
import org.junit.Assert;
-import org.junit.Rule;
import org.junit.Test;
-import org.junit.contrib.java.lang.system.SystemOutRule;
+
+import static com.github.stefanbirkner.systemlambda.SystemLambda.tapSystemOutNormalized;
/**
* SkyLaunch unit tests.
*/
public class SkyLaunchTest {
- @Rule
- public SystemOutRule log = new SystemOutRule().enableLog();
-
@Test
- public void testMove() {
- log.clearLog();
+ public void testMove() throws Exception {
var skyLaunch = new SkyLaunch();
- skyLaunch.move(1.0, 1.0, 1.0);
- var outputLog = getLogContent(log.getLog());
+ var outputLog = getLogContent(() -> skyLaunch.move(1.0, 1.0, 1.0));
var expectedLog = "Move to ( 1.0, 1.0, 1.0 )";
Assert.assertEquals(outputLog, expectedLog);
}
@Test
- public void testPlaySound() {
- log.clearLog();
+ public void testPlaySound() throws Exception {
var skyLaunch = new SkyLaunch();
- skyLaunch.playSound("SOUND_NAME", 1);
- var outputLog = getLogContent(log.getLog());
+ var outputLog = getLogContent(() -> skyLaunch.playSound("SOUND_NAME", 1));
var expectedLog = "Play SOUND_NAME with volumn 1";
Assert.assertEquals(outputLog, expectedLog);
}
@Test
- public void testSpawnParticles() {
- log.clearLog();
+ public void testSpawnParticles() throws Exception {
var skyLaunch = new SkyLaunch();
- skyLaunch.spawnParticles("PARTICLE_TYPE", 100);
- var outputLog = getLogContent(log.getLog());
+ var outputLog = getLogContent(
+ () -> skyLaunch.spawnParticles("PARTICLE_TYPE", 100));
var expectedLog = "Spawn 100 particle with type PARTICLE_TYPE";
Assert.assertEquals(outputLog, expectedLog);
}
@Test
- public void testActivate() {
- log.clearLog();
+ public void testActivate() throws Exception {
var skyLaunch = new SkyLaunch();
- skyLaunch.activate();
- var logs = log.getLog().split("\n");
+ var logs = tapSystemOutNormalized(skyLaunch::activate)
+ .split("\n");
final var expectedSize = 3;
final var log1 = getLogContent(logs[0]);
final var expectedLog1 = "Move to ( 0.0, 0.0, 20.0 )";
@@ -85,6 +77,11 @@ public class SkyLaunchTest {
Assert.assertEquals(log3, expectedLog3);
}
+ private String getLogContent(Statement statement) throws Exception {
+ var log = tapSystemOutNormalized(statement);
+ return getLogContent(log);
+ }
+
private String getLogContent(String log) {
return log.split("-")[1].trim();
}
diff --git a/template-method/pom.xml b/template-method/pom.xml
index c449ef04f..cbf2ac156 100644
--- a/template-method/pom.xml
+++ b/template-method/pom.xml
@@ -29,7 +29,7 @@
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
template-method
diff --git a/template-method/src/test/java/com/iluwatar/templatemethod/AppTest.java b/template-method/src/test/java/com/iluwatar/templatemethod/AppTest.java
index e70e8a78f..32f09242e 100644
--- a/template-method/src/test/java/com/iluwatar/templatemethod/AppTest.java
+++ b/template-method/src/test/java/com/iluwatar/templatemethod/AppTest.java
@@ -25,13 +25,15 @@ package com.iluwatar.templatemethod;
import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+
/**
* Application test
*/
-public class AppTest {
+class AppTest {
@Test
- public void test() {
- App.main(new String[]{});
+ void shouldExecuteWithoutException() {
+ assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
diff --git a/template-method/src/test/java/com/iluwatar/templatemethod/StealingMethodTest.java b/template-method/src/test/java/com/iluwatar/templatemethod/StealingMethodTest.java
index ba6030da4..95326eeec 100644
--- a/template-method/src/test/java/com/iluwatar/templatemethod/StealingMethodTest.java
+++ b/template-method/src/test/java/com/iluwatar/templatemethod/StealingMethodTest.java
@@ -146,7 +146,7 @@ public abstract class StealingMethodTest {
}
private class InMemoryAppender extends AppenderBase {
- private List log = new LinkedList<>();
+ private final List log = new LinkedList<>();
public InMemoryAppender() {
((Logger) LoggerFactory.getLogger("root")).addAppender(this);
diff --git a/thread-pool/pom.xml b/thread-pool/pom.xml
index 0ea0b1266..3727bd240 100644
--- a/thread-pool/pom.xml
+++ b/thread-pool/pom.xml
@@ -29,7 +29,7 @@
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
thread-pool
diff --git a/thread-pool/src/test/java/com/iluwatar/threadpool/AppTest.java b/thread-pool/src/test/java/com/iluwatar/threadpool/AppTest.java
index ca6dc30e4..4c1cf90d6 100644
--- a/thread-pool/src/test/java/com/iluwatar/threadpool/AppTest.java
+++ b/thread-pool/src/test/java/com/iluwatar/threadpool/AppTest.java
@@ -25,15 +25,17 @@ package com.iluwatar.threadpool;
import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+
/**
* Application test
*
* @author ilkka
*/
-public class AppTest {
+class AppTest {
@Test
- public void test() {
- App.main(new String[]{});
+ void shouldExecuteWithoutException() {
+ assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
diff --git a/throttling/README.md b/throttling/README.md
index 48e1b1c78..257bce54a 100644
--- a/throttling/README.md
+++ b/throttling/README.md
@@ -32,8 +32,8 @@ Tenant class presents the clients of the API. CallsCount tracks the number of AP
```java
public class Tenant {
- private String name;
- private int allowedCallsPerSecond;
+ private final String name;
+ private final int allowedCallsPerSecond;
public Tenant(String name, int allowedCallsPerSecond, CallsCount callsCount) {
if (allowedCallsPerSecond < 0) {
@@ -56,7 +56,7 @@ public class Tenant {
public final class CallsCount {
private static final Logger LOGGER = LoggerFactory.getLogger(CallsCount.class);
- private Map tenantCallsCount = new ConcurrentHashMap<>();
+ private final Map tenantCallsCount = new ConcurrentHashMap<>();
public void addTenant(String tenantName) {
tenantCallsCount.putIfAbsent(tenantName, new AtomicLong(0));
diff --git a/throttling/pom.xml b/throttling/pom.xml
index 6ae062c5e..ba2ca9c47 100644
--- a/throttling/pom.xml
+++ b/throttling/pom.xml
@@ -29,7 +29,7 @@
java-design-patterns
com.iluwatar
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
4.0.0
diff --git a/throttling/src/main/java/com/iluwatar/throttling/CallsCount.java b/throttling/src/main/java/com/iluwatar/throttling/CallsCount.java
index 8f8036286..abfd4d351 100644
--- a/throttling/src/main/java/com/iluwatar/throttling/CallsCount.java
+++ b/throttling/src/main/java/com/iluwatar/throttling/CallsCount.java
@@ -38,7 +38,7 @@ import org.slf4j.LoggerFactory;
public final class CallsCount {
private static final Logger LOGGER = LoggerFactory.getLogger(CallsCount.class);
- private Map tenantCallsCount = new ConcurrentHashMap<>();
+ private final Map tenantCallsCount = new ConcurrentHashMap<>();
/**
* Add a new tenant to the map.
diff --git a/throttling/src/main/java/com/iluwatar/throttling/Tenant.java b/throttling/src/main/java/com/iluwatar/throttling/Tenant.java
index d94344428..5fe2c72db 100644
--- a/throttling/src/main/java/com/iluwatar/throttling/Tenant.java
+++ b/throttling/src/main/java/com/iluwatar/throttling/Tenant.java
@@ -30,8 +30,8 @@ import java.security.InvalidParameterException;
*/
public class Tenant {
- private String name;
- private int allowedCallsPerSecond;
+ private final String name;
+ private final int allowedCallsPerSecond;
/**
* Constructor.
diff --git a/throttling/src/test/java/com/iluwatar/throttling/AppTest.java b/throttling/src/test/java/com/iluwatar/throttling/AppTest.java
index daf8c2f21..dcabb02b3 100644
--- a/throttling/src/test/java/com/iluwatar/throttling/AppTest.java
+++ b/throttling/src/test/java/com/iluwatar/throttling/AppTest.java
@@ -25,13 +25,15 @@ package com.iluwatar.throttling;
import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+
/**
* Application test
*/
-public class AppTest {
+class AppTest {
@Test
- public void test() {
- App.main(new String[]{});
+ void shouldExecuteApplicationWithoutException() {
+ assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
diff --git a/throttling/src/test/java/com/iluwatar/throttling/B2BServiceTest.java b/throttling/src/test/java/com/iluwatar/throttling/B2BServiceTest.java
index 6a328c3f0..786325237 100644
--- a/throttling/src/test/java/com/iluwatar/throttling/B2BServiceTest.java
+++ b/throttling/src/test/java/com/iluwatar/throttling/B2BServiceTest.java
@@ -34,7 +34,7 @@ import org.junit.jupiter.api.Test;
*/
public class B2BServiceTest {
- private CallsCount callsCount = new CallsCount();
+ private final CallsCount callsCount = new CallsCount();
@Test
public void dummyCustomerApiTest() {
diff --git a/tls/pom.xml b/tls/pom.xml
index 7100ae295..54e911e40 100644
--- a/tls/pom.xml
+++ b/tls/pom.xml
@@ -29,7 +29,7 @@
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
tls
diff --git a/tls/src/main/java/com/iluwatar/tls/DateFormatCallable.java b/tls/src/main/java/com/iluwatar/tls/DateFormatCallable.java
index c4e885896..4e5c14e0b 100644
--- a/tls/src/main/java/com/iluwatar/tls/DateFormatCallable.java
+++ b/tls/src/main/java/com/iluwatar/tls/DateFormatCallable.java
@@ -1,93 +1,93 @@
-/*
- * The MIT License
- * Copyright © 2014-2019 Ilkka Seppälä
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-
-package com.iluwatar.tls;
-
-import java.text.DateFormat;
-import java.text.SimpleDateFormat;
-import java.util.concurrent.Callable;
-import java.util.stream.IntStream;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * DateFormatCallable converts string dates to a date format using SimpleDateFormat. The date format
- * and the date value will be passed to the Callable by the constructor. The constructor creates a
- * instance of SimpleDateFormat and stores it in a ThreadLocal class variable. For the complete
- * description of the example see {@link App}.
- *
- * You can comment out the code marked with //TLTL and comment in the code marked //NTLNTL. Then
- * you can see what will happen if you do not use the ThreadLocal. For details see the description
- * of {@link App}
- *
- * @author Thomas Bauer, 2017
- */
-public class DateFormatCallable implements Callable {
-
- private static final Logger LOGGER = LoggerFactory.getLogger(DateFormatCallable.class);
- // class variables (members)
- private ThreadLocal df; //TLTL
- // private DateFormat df; //NTLNTL
-
- private String dateValue; // for dateValue Thread Local not needed
-
-
- /**
- * The date format and the date value are passed to the constructor.
- *
- * @param inDateFormat string date format string, e.g. "dd/MM/yyyy"
- * @param inDateValue string date value, e.g. "21/06/2016"
- */
- public DateFormatCallable(String inDateFormat, String inDateValue) {
- final var idf = inDateFormat; //TLTL
- this.df = ThreadLocal.withInitial(() -> { //TLTL
- return new SimpleDateFormat(idf); //TLTL
- }); //TLTL
- // this.df = new SimpleDateFormat(inDateFormat); //NTLNTL
- this.dateValue = inDateValue;
- }
-
- @Override
- public Result call() {
- LOGGER.info(Thread.currentThread() + " started executing...");
- var result = new Result();
-
- // Convert date value to date 5 times
- IntStream.rangeClosed(1, 5).forEach(i -> {
- try {
- // this is the statement where it is important to have the
- // instance of SimpleDateFormat locally
- // Create the date value and store it in dateList
- result.getDateList().add(this.df.get().parse(this.dateValue)); //TLTL
- // result.getDateList().add(this.df.parse(this.dateValue)); //NTLNTL
- } catch (Exception e) {
- // write the Exception to a list and continue work
- result.getExceptionList().add(e.getClass() + ": " + e.getMessage());
- }
- });
-
- LOGGER.info(Thread.currentThread() + " finished processing part of the thread");
-
- return result;
- }
-}
+/*
+ * The MIT License
+ * Copyright © 2014-2019 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+package com.iluwatar.tls;
+
+import java.text.DateFormat;
+import java.text.SimpleDateFormat;
+import java.util.concurrent.Callable;
+import java.util.stream.IntStream;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * DateFormatCallable converts string dates to a date format using SimpleDateFormat. The date format
+ * and the date value will be passed to the Callable by the constructor. The constructor creates a
+ * instance of SimpleDateFormat and stores it in a ThreadLocal class variable. For the complete
+ * description of the example see {@link App}.
+ *
+ * You can comment out the code marked with //TLTL and comment in the code marked //NTLNTL. Then
+ * you can see what will happen if you do not use the ThreadLocal. For details see the description
+ * of {@link App}
+ *
+ * @author Thomas Bauer, 2017
+ */
+public class DateFormatCallable implements Callable {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(DateFormatCallable.class);
+ // class variables (members)
+ private final ThreadLocal df; //TLTL
+ // private DateFormat df; //NTLNTL
+
+ private final String dateValue; // for dateValue Thread Local not needed
+
+
+ /**
+ * The date format and the date value are passed to the constructor.
+ *
+ * @param inDateFormat string date format string, e.g. "dd/MM/yyyy"
+ * @param inDateValue string date value, e.g. "21/06/2016"
+ */
+ public DateFormatCallable(String inDateFormat, String inDateValue) {
+ final var idf = inDateFormat; //TLTL
+ this.df = ThreadLocal.withInitial(() -> { //TLTL
+ return new SimpleDateFormat(idf); //TLTL
+ }); //TLTL
+ // this.df = new SimpleDateFormat(inDateFormat); //NTLNTL
+ this.dateValue = inDateValue;
+ }
+
+ @Override
+ public Result call() {
+ LOGGER.info(Thread.currentThread() + " started executing...");
+ var result = new Result();
+
+ // Convert date value to date 5 times
+ IntStream.rangeClosed(1, 5).forEach(i -> {
+ try {
+ // this is the statement where it is important to have the
+ // instance of SimpleDateFormat locally
+ // Create the date value and store it in dateList
+ result.getDateList().add(this.df.get().parse(this.dateValue)); //TLTL
+ // result.getDateList().add(this.df.parse(this.dateValue)); //NTLNTL
+ } catch (Exception e) {
+ // write the Exception to a list and continue work
+ result.getExceptionList().add(e.getClass() + ": " + e.getMessage());
+ }
+ });
+
+ LOGGER.info(Thread.currentThread() + " finished processing part of the thread");
+
+ return result;
+ }
+}
diff --git a/tls/src/main/java/com/iluwatar/tls/Result.java b/tls/src/main/java/com/iluwatar/tls/Result.java
index c98a07b91..38dc197cf 100644
--- a/tls/src/main/java/com/iluwatar/tls/Result.java
+++ b/tls/src/main/java/com/iluwatar/tls/Result.java
@@ -1,65 +1,65 @@
-/*
- * The MIT License
- * Copyright © 2014-2019 Ilkka Seppälä
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-
-/*
- * Fiducia IT AG, All rights reserved. Use is subject to license terms.
- */
-
-package com.iluwatar.tls;
-
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.List;
-
-/**
- * Result object that will be returned by the Callable {@link DateFormatCallable} used in {@link
- * App}.
- *
- * @author Thomas Bauer, 2017
- */
-public class Result {
- // A list to collect the date values created in one thread
- private List dateList = new ArrayList<>();
-
- // A list to collect Exceptions thrown in one threads (should be none in
- // this example)
- private List exceptionList = new ArrayList<>();
-
- /**
- * Get list of date values collected within a thread execution.
- *
- * @return List of date values collected within an thread execution
- */
- public List getDateList() {
- return dateList;
- }
-
- /**
- * Get list of exceptions thrown within a thread execution.
- *
- * @return List of exceptions thrown within an thread execution
- */
- public List getExceptionList() {
- return exceptionList;
- }
-}
+/*
+ * The MIT License
+ * Copyright © 2014-2019 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+/*
+ * Fiducia IT AG, All rights reserved. Use is subject to license terms.
+ */
+
+package com.iluwatar.tls;
+
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+
+/**
+ * Result object that will be returned by the Callable {@link DateFormatCallable} used in {@link
+ * App}.
+ *
+ * @author Thomas Bauer, 2017
+ */
+public class Result {
+ // A list to collect the date values created in one thread
+ private final List dateList = new ArrayList<>();
+
+ // A list to collect Exceptions thrown in one threads (should be none in
+ // this example)
+ private final List exceptionList = new ArrayList<>();
+
+ /**
+ * Get list of date values collected within a thread execution.
+ *
+ * @return List of date values collected within an thread execution
+ */
+ public List getDateList() {
+ return dateList;
+ }
+
+ /**
+ * Get list of exceptions thrown within a thread execution.
+ *
+ * @return List of exceptions thrown within an thread execution
+ */
+ public List getExceptionList() {
+ return exceptionList;
+ }
+}
diff --git a/tls/src/test/java/com/iluwatar/tls/AppTest.java b/tls/src/test/java/com/iluwatar/tls/AppTest.java
index bae673b97..ba3774b3e 100644
--- a/tls/src/test/java/com/iluwatar/tls/AppTest.java
+++ b/tls/src/test/java/com/iluwatar/tls/AppTest.java
@@ -25,14 +25,16 @@ package com.iluwatar.tls;
import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+
/**
* Tests that thread local storage example runs without errors.
*
* @author Thomas Bauer, January 2017
*/
-public class AppTest {
+class AppTest {
@Test
- public void test() {
- App.main(new String[]{});
+ void shouldExecuteApplicationWithoutException() {
+ assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
diff --git a/tls/src/test/java/com/iluwatar/tls/DateFormatCallableTest.java b/tls/src/test/java/com/iluwatar/tls/DateFormatCallableTest.java
index 48e5854a3..5338829d0 100644
--- a/tls/src/test/java/com/iluwatar/tls/DateFormatCallableTest.java
+++ b/tls/src/test/java/com/iluwatar/tls/DateFormatCallableTest.java
@@ -66,18 +66,18 @@ public class DateFormatCallableTest {
/**
* Expected number of date values in the date value list created by the run of DateFormatRunnalbe
*/
- private int expectedCounterDateValues = 5;
+ private final int expectedCounterDateValues = 5;
/**
* Expected number of exceptions in the exception list created by the run of DateFormatRunnalbe.
*/
- private int expectedCounterExceptions = 0;
+ private final int expectedCounterExceptions = 0;
/**
* Expected content of the list containing the date values created by the run of
* DateFormatRunnalbe
*/
- private List expectedDateValues =
+ private final List expectedDateValues =
List.of("15.11.2015", "15.11.2015", "15.11.2015", "15.11.2015", "15.11.2015");
/**
diff --git a/tls/src/test/java/com/iluwatar/tls/DateFormatCallableTestIncorrectDateFormat.java b/tls/src/test/java/com/iluwatar/tls/DateFormatCallableTestIncorrectDateFormat.java
index 8b02faf0b..7b3d6b4ad 100644
--- a/tls/src/test/java/com/iluwatar/tls/DateFormatCallableTestIncorrectDateFormat.java
+++ b/tls/src/test/java/com/iluwatar/tls/DateFormatCallableTestIncorrectDateFormat.java
@@ -54,18 +54,18 @@ public class DateFormatCallableTestIncorrectDateFormat {
/**
* Expected number of date values in the date value list created by the run of DateFormatRunnalbe
*/
- private int expectedCounterDateValues = 0;
+ private final int expectedCounterDateValues = 0;
/**
* Expected number of exceptions in the exception list created by the run of DateFormatRunnalbe.
*/
- private int expectedCounterExceptions = 5;
+ private final int expectedCounterExceptions = 5;
/**
* Expected content of the list containing the exceptions created by the run of
* DateFormatRunnalbe
*/
- private List expectedExceptions = List.of(
+ private final List expectedExceptions = List.of(
"class java.text.ParseException: Unparseable date: \"15.12.2015\"",
"class java.text.ParseException: Unparseable date: \"15.12.2015\"",
"class java.text.ParseException: Unparseable date: \"15.12.2015\"",
diff --git a/tls/src/test/java/com/iluwatar/tls/DateFormatCallableTestMultiThread.java b/tls/src/test/java/com/iluwatar/tls/DateFormatCallableTestMultiThread.java
index c0e8e1844..b3328d4c5 100644
--- a/tls/src/test/java/com/iluwatar/tls/DateFormatCallableTestMultiThread.java
+++ b/tls/src/test/java/com/iluwatar/tls/DateFormatCallableTestMultiThread.java
@@ -55,7 +55,7 @@ public class DateFormatCallableTestMultiThread {
* Result object given back by DateFormatCallable, one for each thread -- Array with converted
* date values -- Array with thrown exceptions
*/
- private static Result[] result = new Result[4];
+ private static final Result[] result = new Result[4];
/**
* The date values created by the run of of DateFormatRunnalbe. List will be filled in the setup()
@@ -66,22 +66,22 @@ public class DateFormatCallableTestMultiThread {
/* nothing needed here */
}
- private static List[] createdDateValues = new StringArrayList[4];
+ private static final List[] createdDateValues = new StringArrayList[4];
/**
* Expected number of date values in the date value list created by each thread
*/
- private int expectedCounterDateValues = 5;
+ private final int expectedCounterDateValues = 5;
/**
* Expected number of exceptions in the exception list created by each thread
*/
- private int expectedCounterExceptions = 0;
+ private final int expectedCounterExceptions = 0;
/**
* Expected content of the list containing the date values created by each thread
*/
- private List expectedDateValues =
+ private final List expectedDateValues =
List.of("15.11.2015", "15.11.2015", "15.11.2015", "15.11.2015", "15.11.2015");
/**
diff --git a/tolerant-reader/README.md b/tolerant-reader/README.md
index a62e5f4cd..922de90de 100644
--- a/tolerant-reader/README.md
+++ b/tolerant-reader/README.md
@@ -35,10 +35,10 @@ public class RainbowFish implements Serializable {
private static final long serialVersionUID = 1L;
- private String name;
- private int age;
- private int lengthMeters;
- private int weightTons;
+ private final String name;
+ private final int age;
+ private final int lengthMeters;
+ private final int weightTons;
/**
* Constructor.
diff --git a/tolerant-reader/pom.xml b/tolerant-reader/pom.xml
index 2966cca19..6cc0ac283 100644
--- a/tolerant-reader/pom.xml
+++ b/tolerant-reader/pom.xml
@@ -29,7 +29,7 @@
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
tolerant-reader
diff --git a/tolerant-reader/src/main/java/com/iluwatar/tolerantreader/RainbowFish.java b/tolerant-reader/src/main/java/com/iluwatar/tolerantreader/RainbowFish.java
index 775fc98f7..7529435fe 100644
--- a/tolerant-reader/src/main/java/com/iluwatar/tolerantreader/RainbowFish.java
+++ b/tolerant-reader/src/main/java/com/iluwatar/tolerantreader/RainbowFish.java
@@ -32,10 +32,10 @@ public class RainbowFish implements Serializable {
private static final long serialVersionUID = 1L;
- private String name;
- private int age;
- private int lengthMeters;
- private int weightTons;
+ private final String name;
+ private final int age;
+ private final int lengthMeters;
+ private final int weightTons;
/**
* Constructor.
diff --git a/tolerant-reader/src/main/java/com/iluwatar/tolerantreader/RainbowFishSerializer.java b/tolerant-reader/src/main/java/com/iluwatar/tolerantreader/RainbowFishSerializer.java
index f6a9e6a0e..98ad31fe5 100644
--- a/tolerant-reader/src/main/java/com/iluwatar/tolerantreader/RainbowFishSerializer.java
+++ b/tolerant-reader/src/main/java/com/iluwatar/tolerantreader/RainbowFishSerializer.java
@@ -38,6 +38,9 @@ import java.util.Map;
*/
public final class RainbowFishSerializer {
+ public static final String LENGTH_METERS = "lengthMeters";
+ public static final String WEIGHT_TONS = "weightTons";
+
private RainbowFishSerializer() {
}
@@ -48,8 +51,8 @@ public final class RainbowFishSerializer {
var map = Map.of(
"name", rainbowFish.getName(),
"age", String.format("%d", rainbowFish.getAge()),
- "lengthMeters", String.format("%d", rainbowFish.getLengthMeters()),
- "weightTons", String.format("%d", rainbowFish.getWeightTons())
+ LENGTH_METERS, String.format("%d", rainbowFish.getLengthMeters()),
+ WEIGHT_TONS, String.format("%d", rainbowFish.getWeightTons())
);
try (var fileOut = new FileOutputStream(filename);
@@ -65,8 +68,8 @@ public final class RainbowFishSerializer {
var map = Map.of(
"name", rainbowFish.getName(),
"age", String.format("%d", rainbowFish.getAge()),
- "lengthMeters", String.format("%d", rainbowFish.getLengthMeters()),
- "weightTons", String.format("%d", rainbowFish.getWeightTons()),
+ "lengthMeters", String.format("%d", rainbowFish.getLengthMeters()),
+ WEIGHT_TONS, String.format("%d", rainbowFish.getWeightTons()),
"angry", Boolean.toString(rainbowFish.getAngry()),
"hungry", Boolean.toString(rainbowFish.getHungry()),
"sleeping", Boolean.toString(rainbowFish.getSleeping())
@@ -93,7 +96,7 @@ public final class RainbowFishSerializer {
map.get("name"),
Integer.parseInt(map.get("age")),
Integer.parseInt(map.get("lengthMeters")),
- Integer.parseInt(map.get("weightTons"))
+ Integer.parseInt(map.get(WEIGHT_TONS))
);
}
}
diff --git a/tolerant-reader/src/test/java/com/iluwatar/tolerantreader/AppTest.java b/tolerant-reader/src/test/java/com/iluwatar/tolerantreader/AppTest.java
index d28e118d2..4b9432408 100644
--- a/tolerant-reader/src/test/java/com/iluwatar/tolerantreader/AppTest.java
+++ b/tolerant-reader/src/test/java/com/iluwatar/tolerantreader/AppTest.java
@@ -29,19 +29,21 @@ import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+
/**
* Application test
*/
-public class AppTest {
+class AppTest {
@Test
- public void test() throws ClassNotFoundException, IOException {
- App.main(new String[]{});
+ void shouldExecuteWithoutException() {
+ assertDoesNotThrow(() -> App.main(new String[]{}));
}
@BeforeEach
@AfterEach
- public void cleanup() {
+ void cleanup() {
var file1 = new File("fish1.out");
file1.delete();
var file2 = new File("fish2.out");
diff --git a/trampoline/pom.xml b/trampoline/pom.xml
index 13988ca92..fff117bf8 100644
--- a/trampoline/pom.xml
+++ b/trampoline/pom.xml
@@ -30,7 +30,7 @@
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
trampoline
diff --git a/transaction-script/.gitignore b/transaction-script/.gitignore
new file mode 100644
index 000000000..431845ed0
--- /dev/null
+++ b/transaction-script/.gitignore
@@ -0,0 +1,2 @@
+/target/
+.idea/
diff --git a/transaction-script/README.md b/transaction-script/README.md
new file mode 100644
index 000000000..3ae3cf4c1
--- /dev/null
+++ b/transaction-script/README.md
@@ -0,0 +1,119 @@
+---
+layout: pattern
+title: Transaction Script
+folder: transaction-script
+permalink: /patterns/transaction-script/
+categories: Behavioral
+tags:
+ - Data access
+---
+
+## Intent
+
+Transaction Script organizes business logic by procedures where each procedure handles a single
+request from the presentation.
+
+## Explanation
+
+Real world example
+
+> You need to create a hotel room booking system. Since the requirements are quite simple we intend
+> to use the Transaction Script pattern here.
+
+In plain words
+
+> Transaction Script organizes business logic into transactions that the system needs to carry out.
+
+Programmatic example
+
+The `Hotel` class takes care of booking and cancelling room reservations.
+
+```java
+public class Hotel {
+ private static final Logger LOGGER = LoggerFactory.getLogger(App.class);
+
+ private final HotelDaoImpl hotelDao;
+
+ public Hotel(HotelDaoImpl hotelDao) {
+ this.hotelDao = hotelDao;
+ }
+
+ public void bookRoom(int roomNumber) throws Exception {
+
+ Optional room = hotelDao.getById(roomNumber);
+
+ if (room.isEmpty()) {
+ throw new Exception("Room number: " + roomNumber + " does not exist");
+ } else {
+ if (room.get().isBooked()) {
+ throw new Exception("Room already booked!");
+ } else {
+ Room updateRoomBooking = room.get();
+ updateRoomBooking.setBooked(true);
+ hotelDao.update(updateRoomBooking);
+ }
+ }
+ }
+
+ public void cancelRoomBooking(int roomNumber) throws Exception {
+
+ Optional room = hotelDao.getById(roomNumber);
+
+ if (room.isEmpty()) {
+ throw new Exception("Room number: " + roomNumber + " does not exist");
+ } else {
+ if (room.get().isBooked()) {
+ Room updateRoomBooking = room.get();
+ updateRoomBooking.setBooked(false);
+ int refundAmount = updateRoomBooking.getPrice();
+ hotelDao.update(updateRoomBooking);
+
+ LOGGER.info("Booking cancelled for room number: " + roomNumber);
+ LOGGER.info(refundAmount + " is refunded");
+ } else {
+ throw new Exception("No booking for the room exists");
+ }
+ }
+ }
+}
+```
+
+The `Hotel` class has two methods, one for booking and cancelling a room respectively. Each one of
+them handles a single transaction in the system, making `Hotel` implement the Transaction Script
+pattern.
+
+The `bookRoom` method consolidates all the needed steps like checking if the room is already booked
+or not, if not booked then books the room and updates the database by using the DAO.
+
+The `cancelRoom` method consolidates steps like checking if the room is booked or not,
+if booked then calculates the refund amount and updates the database using the DAO.
+
+## Class diagram
+
+
+
+## Applicability
+
+Use the Transaction Script pattern when the application has only a small amount of logic and that
+logic won't be extended in the future.
+
+## Consequences
+
+* As the business logic gets more complicated,
+it gets progressively harder to keep the transaction script
+in a well-designed state.
+* Code duplication between transaction scripts can occur.
+* Normally not easy to refactor transactions script to other domain logic
+patterns.
+
+## Related patterns
+
+* Domain Model
+* Table Module
+* Service Layer
+
+## Credits
+
+* [Transaction Script Pattern](https://dzone.com/articles/transaction-script-pattern#:~:text=Transaction%20Script%20(TS)%20is%20the,need%20big%20architecture%20behind%20them.)
+* [Transaction Script](https://www.informit.com/articles/article.aspx?p=1398617)
+* [Patterns of Enterprise Application Architecture](https://www.amazon.com/gp/product/0321127420/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=0321127420&linkId=18acc13ba60d66690009505577c45c04)
diff --git a/transaction-script/etc/transaction-script.png b/transaction-script/etc/transaction-script.png
new file mode 100644
index 000000000..6d0cffb6a
Binary files /dev/null and b/transaction-script/etc/transaction-script.png differ
diff --git a/transaction-script/etc/transaction-script.urm.puml b/transaction-script/etc/transaction-script.urm.puml
new file mode 100644
index 000000000..e8d172377
--- /dev/null
+++ b/transaction-script/etc/transaction-script.urm.puml
@@ -0,0 +1,65 @@
+@startuml
+package com.ashishtrivedi16.transaction-script {
+ class App {
+ - H2_DB_URL : String {static}
+ - LOGGER : Logger {static}
+ - addRooms(hotelDaoImpl : HotelDaoImpl) {static}
+ - createDataSource() : DataSource {static}
+ - createSchema(dataSource : DataSource) {static}
+ - deleteSchema(dataSource : DataSource) {static}
+ - getRoomsStatus(hotelDaoImpl : HotelDaoImpl) {static}
+ - generateSampleRooms() : List {static}
+ + main(args : String[]) {static}
+ }
+ class Room {
+ - id: Int
+ - roomType: String
+ - price: Int
+ - booked: Boolean
+ + Customer(id : int, roomType : String, price: Int, booked: Boolean)
+ + getId() : int
+ + getRoomType() : String
+ + getPrice() : Int
+ + isBooked() : Boolean
+ + setId(id : int)
+ + setRoomType(roomType : String)
+ + setPrice(price : Int)
+ + setBooked(booked : boolean)
+ + equals(that : Object) : boolean
+ + hashCode() : int
+ + toString() : String
+ }
+ interface HotelDao {
+ + add(Room) : boolean {abstract}
+ + delete(Room) : boolean {abstract}
+ + getAll() : Stream {abstract}
+ + getById(int) : Optional {abstract}
+ + update(Room) : boolean {abstract}
+ }
+ class RoomSchemaSql {
+ + CREATE_SCHEMA_SQL : String {static}
+ + DELETE_SCHEMA_SQL : String {static}
+ - RoomSchemaSql()
+ }
+ class HotelDaoImpl {
+ - dataSource : DataSource
+ + HotelDaoImpl(dataSource : DataSource)
+ + add(room : Room) : boolean
+ - createRoom(resultSet : ResultSet) : Room
+ + delete(room : Room) : boolean
+ + getAll() : Stream
+ + getById(id : int) : Optional
+ - getConnection() : Connection
+ - mutedClose(connection : Connection, statement : PreparedStatement, resultSet : ResultSet)
+ + update(room : Room) : boolean
+ }
+ class Hotel {
+ - LOGGER : Logger {static}
+ - hotelDao: HotelDaoImpl
+ + Hotel(hotelDao: HotelDaoImpl)
+ + bookRoom(roomNumber: Int)
+ + cancelRoomBooking(roomNumber: Int)
+ }
+}
+HotelDaoImpl ..|> HotelDao
+@enduml
diff --git a/transaction-script/pom.xml b/transaction-script/pom.xml
new file mode 100644
index 000000000..7a6f40219
--- /dev/null
+++ b/transaction-script/pom.xml
@@ -0,0 +1,73 @@
+
+
+
+
+ java-design-patterns
+ com.iluwatar
+ 1.24.0-SNAPSHOT
+
+ 4.0.0
+
+ transaction-script
+
+
+
+ com.h2database
+ h2
+
+
+ org.junit.jupiter
+ junit-jupiter-engine
+ test
+
+
+ org.mockito
+ mockito-core
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-assembly-plugin
+
+
+
+
+
+ com.iluwatar.transactionscript.App
+
+
+
+
+
+
+
+
+
+
diff --git a/transaction-script/src/main/java/com/iluwatar/transactionscript/App.java b/transaction-script/src/main/java/com/iluwatar/transactionscript/App.java
new file mode 100644
index 000000000..59ea5363d
--- /dev/null
+++ b/transaction-script/src/main/java/com/iluwatar/transactionscript/App.java
@@ -0,0 +1,145 @@
+/*
+ * The MIT License
+ * Copyright © 2014-2019 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+package com.iluwatar.transactionscript;
+
+import java.util.List;
+import javax.sql.DataSource;
+import org.h2.jdbcx.JdbcDataSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Transaction Script (TS) is one of the simplest domain logic pattern.
+ * It needs less work to implement than other domain logic patterns and therefore
+ * it’s perfect fit for smaller applications that don't need big architecture behind them.
+ *
+ * In this example we will use the TS pattern to implement booking and cancellation
+ * methods for a Hotel management App. The main method will initialise an instance of
+ * {@link Hotel} and add rooms to it. After that it will book and cancel a couple of rooms
+ * and that will be printed by the logger.
+ *
+ * The thing we have to note here is that all the operations related to booking or cancelling
+ * a room like checking the database if the room exists, checking the booking status or the
+ * room, calculating refund price are all clubbed inside a single transaction script method.
+ */
+public class App {
+
+ private static final String H2_DB_URL = "jdbc:h2:~/test";
+ private static final Logger LOGGER = LoggerFactory.getLogger(App.class);
+
+ /**
+ * Program entry point.
+ * Initialises an instance of Hotel and adds rooms to it.
+ * Carries out booking and cancel booking transactions.
+ * @param args command line arguments
+ * @throws Exception if any error occurs
+ */
+ public static void main(String[] args) throws Exception {
+
+ final var dataSource = createDataSource();
+ deleteSchema(dataSource);
+ createSchema(dataSource);
+ final var dao = new HotelDaoImpl(dataSource);
+
+ // Add rooms
+ addRooms(dao);
+
+ // Print room booking status
+ getRoomStatus(dao);
+
+ var hotel = new Hotel(dao);
+
+ // Book rooms
+ hotel.bookRoom(1);
+ hotel.bookRoom(2);
+ hotel.bookRoom(3);
+ hotel.bookRoom(4);
+ hotel.bookRoom(5);
+ hotel.bookRoom(6);
+
+ // Cancel booking for a few rooms
+ hotel.cancelRoomBooking(1);
+ hotel.cancelRoomBooking(3);
+ hotel.cancelRoomBooking(5);
+
+ getRoomStatus(dao);
+
+ deleteSchema(dataSource);
+
+ }
+
+ private static void getRoomStatus(HotelDaoImpl dao) throws Exception {
+ try (var customerStream = dao.getAll()) {
+ customerStream.forEach((customer) -> LOGGER.info(customer.toString()));
+ }
+ }
+
+ private static void deleteSchema(DataSource dataSource) throws java.sql.SQLException {
+ try (var connection = dataSource.getConnection();
+ var statement = connection.createStatement()) {
+ statement.execute(RoomSchemaSql.DELETE_SCHEMA_SQL);
+ }
+ }
+
+ private static void createSchema(DataSource dataSource) throws Exception {
+ try (var connection = dataSource.getConnection();
+ var statement = connection.createStatement()) {
+ statement.execute(RoomSchemaSql.CREATE_SCHEMA_SQL);
+ } catch (Exception e) {
+ throw new Exception(e.getMessage(), e);
+ }
+ }
+
+ /**
+ * Get database.
+ *
+ * @return h2 datasource
+ */
+ private static DataSource createDataSource() {
+ var dataSource = new JdbcDataSource();
+ dataSource.setUrl(H2_DB_URL);
+ return dataSource;
+ }
+
+ private static void addRooms(HotelDaoImpl hotelDao) throws Exception {
+ for (var room : generateSampleRooms()) {
+ hotelDao.add(room);
+ }
+ }
+
+ /**
+ * Generate rooms.
+ *
+ * @return list of rooms
+ */
+ private static List generateSampleRooms() {
+ final var room1 = new Room(1, "Single", 50, false);
+ final var room2 = new Room(2, "Double", 80, false);
+ final var room3 = new Room(3, "Queen", 120, false);
+ final var room4 = new Room(4, "King", 150, false);
+ final var room5 = new Room(5, "Single", 50, false);
+ final var room6 = new Room(6, "Double", 80, false);
+ return List.of(room1, room2, room3, room4, room5, room6);
+ }
+}
diff --git a/transaction-script/src/main/java/com/iluwatar/transactionscript/Hotel.java b/transaction-script/src/main/java/com/iluwatar/transactionscript/Hotel.java
new file mode 100644
index 000000000..c24ea4f68
--- /dev/null
+++ b/transaction-script/src/main/java/com/iluwatar/transactionscript/Hotel.java
@@ -0,0 +1,87 @@
+/*
+ * The MIT License
+ * Copyright © 2014-2019 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+package com.iluwatar.transactionscript;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class Hotel {
+ private static final Logger LOGGER = LoggerFactory.getLogger(App.class);
+
+ private final HotelDaoImpl hotelDao;
+
+ public Hotel(HotelDaoImpl hotelDao) {
+ this.hotelDao = hotelDao;
+ }
+
+ /**
+ * Book a room.
+ *
+ * @param roomNumber room to book
+ * @throws Exception if any error
+ */
+ public void bookRoom(int roomNumber) throws Exception {
+
+ var room = hotelDao.getById(roomNumber);
+
+ if (room.isEmpty()) {
+ throw new Exception("Room number: " + roomNumber + " does not exist");
+ } else {
+ if (room.get().isBooked()) {
+ throw new Exception("Room already booked!");
+ } else {
+ var updateRoomBooking = room.get();
+ updateRoomBooking.setBooked(true);
+ hotelDao.update(updateRoomBooking);
+ }
+ }
+ }
+
+ /**
+ * Cancel a room booking.
+ *
+ * @param roomNumber room to cancel booking
+ * @throws Exception if any error
+ */
+ public void cancelRoomBooking(int roomNumber) throws Exception {
+
+ var room = hotelDao.getById(roomNumber);
+
+ if (room.isEmpty()) {
+ throw new Exception("Room number: " + roomNumber + " does not exist");
+ } else {
+ if (room.get().isBooked()) {
+ var updateRoomBooking = room.get();
+ updateRoomBooking.setBooked(false);
+ int refundAmount = updateRoomBooking.getPrice();
+ hotelDao.update(updateRoomBooking);
+
+ LOGGER.info("Booking cancelled for room number: " + roomNumber);
+ LOGGER.info(refundAmount + " is refunded");
+ } else {
+ throw new Exception("No booking for the room exists");
+ }
+ }
+ }
+}
diff --git a/transaction-script/src/main/java/com/iluwatar/transactionscript/HotelDao.java b/transaction-script/src/main/java/com/iluwatar/transactionscript/HotelDao.java
new file mode 100644
index 000000000..b06211905
--- /dev/null
+++ b/transaction-script/src/main/java/com/iluwatar/transactionscript/HotelDao.java
@@ -0,0 +1,40 @@
+/*
+ * The MIT License
+ * Copyright © 2014-2019 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+package com.iluwatar.transactionscript;
+
+import java.util.Optional;
+import java.util.stream.Stream;
+
+public interface HotelDao {
+
+ Stream getAll() throws Exception;
+
+ Optional getById(int id) throws Exception;
+
+ Boolean add(Room room) throws Exception;
+
+ Boolean update(Room room) throws Exception;
+
+ Boolean delete(Room room) throws Exception;
+}
diff --git a/transaction-script/src/main/java/com/iluwatar/transactionscript/HotelDaoImpl.java b/transaction-script/src/main/java/com/iluwatar/transactionscript/HotelDaoImpl.java
new file mode 100644
index 000000000..240f96892
--- /dev/null
+++ b/transaction-script/src/main/java/com/iluwatar/transactionscript/HotelDaoImpl.java
@@ -0,0 +1,172 @@
+/*
+ * The MIT License
+ * Copyright © 2014-2019 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+package com.iluwatar.transactionscript;
+
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.util.Optional;
+import java.util.Spliterator;
+import java.util.Spliterators;
+import java.util.function.Consumer;
+import java.util.stream.Stream;
+import java.util.stream.StreamSupport;
+import javax.sql.DataSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class HotelDaoImpl implements HotelDao {
+ private static final Logger LOGGER = LoggerFactory.getLogger(App.class);
+
+ private final DataSource dataSource;
+
+ public HotelDaoImpl(DataSource dataSource) {
+ this.dataSource = dataSource;
+ }
+
+ @Override
+ public Stream getAll() throws Exception {
+ try {
+ var connection = getConnection();
+ var statement = connection.prepareStatement("SELECT * FROM ROOMS");
+ var resultSet = statement.executeQuery(); // NOSONAR
+ return StreamSupport.stream(new Spliterators.AbstractSpliterator(Long.MAX_VALUE,
+ Spliterator.ORDERED) {
+
+ @Override
+ public boolean tryAdvance(Consumer super Room> action) {
+ try {
+ if (!resultSet.next()) {
+ return false;
+ }
+ action.accept(createRoom(resultSet));
+ return true;
+ } catch (Exception e) {
+ throw new RuntimeException(e); // NOSONAR
+ }
+ }
+ }, false).onClose(() -> {
+ try {
+ mutedClose(connection, statement, resultSet);
+ } catch (Exception e) {
+ LOGGER.error(e.getMessage());
+ }
+ });
+ } catch (Exception e) {
+ throw new Exception(e.getMessage(), e);
+ }
+ }
+
+ @Override
+ public Optional getById(int id) throws Exception {
+ ResultSet resultSet = null;
+
+ try (var connection = getConnection();
+ var statement = connection.prepareStatement("SELECT * FROM ROOMS WHERE ID = ?")) {
+
+ statement.setInt(1, id);
+ resultSet = statement.executeQuery();
+ if (resultSet.next()) {
+ return Optional.of(createRoom(resultSet));
+ } else {
+ return Optional.empty();
+ }
+ } catch (Exception e) {
+ throw new Exception(e.getMessage(), e);
+ } finally {
+ if (resultSet != null) {
+ resultSet.close();
+ }
+ }
+ }
+
+ @Override
+ public Boolean add(Room room) throws Exception {
+ if (getById(room.getId()).isPresent()) {
+ return false;
+ }
+
+ try (var connection = getConnection();
+ var statement = connection.prepareStatement("INSERT INTO ROOMS VALUES (?,?,?,?)")) {
+ statement.setInt(1, room.getId());
+ statement.setString(2, room.getRoomType());
+ statement.setInt(3, room.getPrice());
+ statement.setBoolean(4, room.isBooked());
+ statement.execute();
+ return true;
+ } catch (Exception e) {
+ throw new Exception(e.getMessage(), e);
+ }
+ }
+
+ @Override
+ public Boolean update(Room room) throws Exception {
+ try (var connection = getConnection();
+ var statement =
+ connection
+ .prepareStatement("UPDATE ROOMS SET ROOM_TYPE = ?, PRICE = ?, BOOKED = ?"
+ + " WHERE ID = ?")) {
+ statement.setString(1, room.getRoomType());
+ statement.setInt(2, room.getPrice());
+ statement.setBoolean(3, room.isBooked());
+ statement.setInt(4, room.getId());
+ return statement.executeUpdate() > 0;
+ } catch (Exception e) {
+ throw new Exception(e.getMessage(), e);
+ }
+ }
+
+ @Override
+ public Boolean delete(Room room) throws Exception {
+ try (var connection = getConnection();
+ var statement = connection.prepareStatement("DELETE FROM ROOMS WHERE ID = ?")) {
+ statement.setInt(1, room.getId());
+ return statement.executeUpdate() > 0;
+ } catch (Exception e) {
+ throw new Exception(e.getMessage(), e);
+ }
+ }
+
+ private Connection getConnection() throws Exception {
+ return dataSource.getConnection();
+ }
+
+ private void mutedClose(Connection connection, PreparedStatement statement, ResultSet resultSet)
+ throws Exception {
+ try {
+ resultSet.close();
+ statement.close();
+ connection.close();
+ } catch (Exception e) {
+ throw new Exception(e.getMessage(), e);
+ }
+ }
+
+ private Room createRoom(ResultSet resultSet) throws Exception {
+ return new Room(resultSet.getInt("ID"),
+ resultSet.getString("ROOM_TYPE"),
+ resultSet.getInt("PRICE"),
+ resultSet.getBoolean("BOOKED"));
+ }
+}
diff --git a/transaction-script/src/main/java/com/iluwatar/transactionscript/Room.java b/transaction-script/src/main/java/com/iluwatar/transactionscript/Room.java
new file mode 100644
index 000000000..fedf4ed21
--- /dev/null
+++ b/transaction-script/src/main/java/com/iluwatar/transactionscript/Room.java
@@ -0,0 +1,123 @@
+/*
+ * The MIT License
+ * Copyright © 2014-2019 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+package com.iluwatar.transactionscript;
+
+/**
+ * A room POJO that represents the data that will be read from the data source.
+ */
+public class Room {
+
+ private int id;
+ private String roomType;
+ private int price;
+ private boolean booked;
+
+ /**
+ * Create an instance of room.
+ * @param id room id
+ * @param roomType room type
+ * @param price room price
+ * @param booked room booking status
+ */
+ public Room(int id, String roomType, int price, boolean booked) {
+ this.id = id;
+ this.roomType = roomType;
+ this.price = price;
+ this.booked = booked;
+ }
+
+ public int getId() {
+ return id;
+ }
+
+ public void setId(int id) {
+ this.id = id;
+ }
+
+ public String getRoomType() {
+ return roomType;
+ }
+
+ public void setRoomType(String roomType) {
+ this.roomType = roomType;
+ }
+
+ public int getPrice() {
+ return price;
+ }
+
+ public void setPrice(int price) {
+ this.price = price;
+ }
+
+ public boolean isBooked() {
+ return booked;
+ }
+
+ public void setBooked(boolean booked) {
+ this.booked = booked;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+
+ Room room = (Room) o;
+
+ if (id != room.id) {
+ return false;
+ }
+ if (price != room.price) {
+ return false;
+ }
+ if (booked != room.booked) {
+ return false;
+ }
+ return roomType.equals(room.roomType);
+ }
+
+ @Override
+ public int hashCode() {
+ int result = id;
+ result = 31 * result + roomType.hashCode();
+ result = 31 * result + price;
+ result = 31 * result + (booked ? 1 : 0);
+ return result;
+ }
+
+ @Override
+ public String toString() {
+ return "Room{"
+ + "id=" + id
+ + ", roomType=" + roomType
+ + ", price=" + price
+ + ", booked=" + booked
+ + '}';
+ }
+}
diff --git a/transaction-script/src/main/java/com/iluwatar/transactionscript/RoomSchemaSql.java b/transaction-script/src/main/java/com/iluwatar/transactionscript/RoomSchemaSql.java
new file mode 100644
index 000000000..4d919137a
--- /dev/null
+++ b/transaction-script/src/main/java/com/iluwatar/transactionscript/RoomSchemaSql.java
@@ -0,0 +1,38 @@
+/*
+ * The MIT License
+ * Copyright © 2014-2019 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+package com.iluwatar.transactionscript;
+
+/**
+ * Customer Schema SQL Class.
+ */
+public final class RoomSchemaSql {
+
+ public static final String CREATE_SCHEMA_SQL =
+ "CREATE TABLE ROOMS (ID NUMBER, ROOM_TYPE VARCHAR(100), PRICE INT(100), BOOKED VARCHAR(100))";
+ public static final String DELETE_SCHEMA_SQL = "DROP TABLE ROOMS IF EXISTS";
+
+ private RoomSchemaSql() {
+ }
+
+}
diff --git a/transaction-script/src/test/java/com/iluwatar/transactionscript/AppTest.java b/transaction-script/src/test/java/com/iluwatar/transactionscript/AppTest.java
new file mode 100644
index 000000000..eb819cabe
--- /dev/null
+++ b/transaction-script/src/test/java/com/iluwatar/transactionscript/AppTest.java
@@ -0,0 +1,39 @@
+/*
+ * The MIT License
+ * Copyright © 2014-2019 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+package com.iluwatar.transactionscript;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+
+/**
+ * Tests that Transaction script example runs without errors.
+ */
+class AppTest {
+
+ @Test
+ void shouldExecuteWithoutException() {
+ assertDoesNotThrow(() -> App.main(new String[]{}));
+ }
+}
diff --git a/transaction-script/src/test/java/com/iluwatar/transactionscript/HotelDaoImplTest.java b/transaction-script/src/test/java/com/iluwatar/transactionscript/HotelDaoImplTest.java
new file mode 100644
index 000000000..6dbbc8ff4
--- /dev/null
+++ b/transaction-script/src/test/java/com/iluwatar/transactionscript/HotelDaoImplTest.java
@@ -0,0 +1,273 @@
+/*
+ * The MIT License
+ * Copyright © 2014-2019 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+package com.iluwatar.transactionscript;
+
+import org.h2.jdbcx.JdbcDataSource;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Nested;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mockito;
+
+import javax.sql.DataSource;
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.SQLException;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.junit.jupiter.api.Assumptions.assumeTrue;
+import static org.mockito.Mockito.*;
+
+/**
+ * Tests {@link HotelDaoImpl}.
+ */
+public class HotelDaoImplTest {
+
+ private static final String DB_URL = "jdbc:h2:~/test";
+ private HotelDaoImpl dao;
+ private Room existingRoom = new Room(1, "Single", 50, false);
+
+ /**
+ * Creates rooms schema.
+ *
+ * @throws SQLException if there is any error while creating schema.
+ */
+ @BeforeEach
+ public void createSchema() throws SQLException {
+ try (var connection = DriverManager.getConnection(DB_URL);
+ var statement = connection.createStatement()) {
+ statement.execute(RoomSchemaSql.DELETE_SCHEMA_SQL);
+ statement.execute(RoomSchemaSql.CREATE_SCHEMA_SQL);
+ }
+ }
+
+ /**
+ * Represents the scenario where DB connectivity is present.
+ */
+ @Nested
+ public class ConnectionSuccess {
+
+ /**
+ * Setup for connection success scenario.
+ *
+ * @throws Exception if any error occurs.
+ */
+ @BeforeEach
+ public void setUp() throws Exception {
+ var dataSource = new JdbcDataSource();
+ dataSource.setURL(DB_URL);
+ dao = new HotelDaoImpl(dataSource);
+ var result = dao.add(existingRoom);
+ Assertions.assertTrue(result);
+ }
+
+ /**
+ * Represents the scenario when DAO operations are being performed on a non existing room.
+ */
+ @Nested
+ public class NonExistingRoom {
+
+ @Test
+ public void addingShouldResultInSuccess() throws Exception {
+ try (var allRooms = dao.getAll()) {
+ assumeTrue(allRooms.count() == 1);
+ }
+
+ final var nonExistingRoom = new Room(2, "Double", 80, false);
+ var result = dao.add(nonExistingRoom);
+ Assertions.assertTrue(result);
+
+ assertRoomCountIs(2);
+ assertEquals(nonExistingRoom, dao.getById(nonExistingRoom.getId()).get());
+ }
+
+ @Test
+ public void deletionShouldBeFailureAndNotAffectExistingRooms() throws Exception {
+ final var nonExistingRoom = new Room(2, "Double", 80, false);
+ var result = dao.delete(nonExistingRoom);
+
+ Assertions.assertFalse(result);
+ assertRoomCountIs(1);
+ }
+
+ @Test
+ public void updationShouldBeFailureAndNotAffectExistingRooms() throws Exception {
+ final var nonExistingId = getNonExistingRoomId();
+ final var newRoomType = "Double";
+ final var newPrice = 80;
+ final var room = new Room(nonExistingId, newRoomType, newPrice, false);
+ var result = dao.update(room);
+
+ Assertions.assertFalse(result);
+ assertFalse(dao.getById(nonExistingId).isPresent());
+ }
+
+ @Test
+ public void retrieveShouldReturnNoRoom() throws Exception {
+ assertFalse(dao.getById(getNonExistingRoomId()).isPresent());
+ }
+ }
+
+ /**
+ * Represents a scenario where DAO operations are being performed on an already existing
+ * room.
+ */
+ @Nested
+ public class ExistingRoom {
+
+ @Test
+ public void addingShouldResultInFailureAndNotAffectExistingRooms() throws Exception {
+ var existingRoom = new Room(1, "Single", 50, false);
+ var result = dao.add(existingRoom);
+
+ Assertions.assertFalse(result);
+ assertRoomCountIs(1);
+ assertEquals(existingRoom, dao.getById(existingRoom.getId()).get());
+ }
+
+ @Test
+ public void deletionShouldBeSuccessAndRoomShouldBeNonAccessible() throws Exception {
+ var result = dao.delete(existingRoom);
+
+ Assertions.assertTrue(result);
+ assertRoomCountIs(0);
+ assertFalse(dao.getById(existingRoom.getId()).isPresent());
+ }
+
+ @Test
+ public void updationShouldBeSuccessAndAccessingTheSameRoomShouldReturnUpdatedInformation() throws
+ Exception {
+ final var newRoomType = "Double";
+ final var newPrice = 80;
+ final var newBookingStatus = false;
+ final var Room = new Room(existingRoom.getId(), newRoomType, newPrice, newBookingStatus);
+ var result = dao.update(Room);
+
+ Assertions.assertTrue(result);
+
+ final var room = dao.getById(existingRoom.getId()).get();
+ assertEquals(newRoomType, room.getRoomType());
+ assertEquals(newPrice, room.getPrice());
+ assertEquals(newBookingStatus, room.isBooked());
+ }
+ }
+ }
+
+ /**
+ * Represents a scenario where DB connectivity is not present due to network issue, or DB service
+ * unavailable.
+ */
+ @Nested
+ public class ConnectivityIssue {
+
+ private static final String EXCEPTION_CAUSE = "Connection not available";
+
+ /**
+ * setup a connection failure scenario.
+ *
+ * @throws SQLException if any error occurs.
+ */
+ @BeforeEach
+ public void setUp() throws SQLException {
+ dao = new HotelDaoImpl(mockedDatasource());
+ }
+
+ private DataSource mockedDatasource() throws SQLException {
+ var mockedDataSource = mock(DataSource.class);
+ var mockedConnection = mock(Connection.class);
+ var exception = new SQLException(EXCEPTION_CAUSE);
+ doThrow(exception).when(mockedConnection).prepareStatement(Mockito.anyString());
+ doReturn(mockedConnection).when(mockedDataSource).getConnection();
+ return mockedDataSource;
+ }
+
+ @Test
+ public void addingARoomFailsWithExceptionAsFeedbackToClient() {
+ assertThrows(Exception.class, () -> {
+ dao.add(new Room(2, "Double", 80, false));
+ });
+ }
+
+ @Test
+ public void deletingARoomFailsWithExceptionAsFeedbackToTheClient() {
+ assertThrows(Exception.class, () -> {
+ dao.delete(existingRoom);
+ });
+ }
+
+ @Test
+ public void updatingARoomFailsWithFeedbackToTheClient() {
+ final var newRoomType = "Double";
+ final var newPrice = 80;
+ final var newBookingStatus = false;
+ assertThrows(Exception.class, () -> {
+ dao.update(new Room(existingRoom.getId(), newRoomType, newPrice, newBookingStatus));
+ });
+ }
+
+ @Test
+ public void retrievingARoomByIdFailsWithExceptionAsFeedbackToClient() {
+ assertThrows(Exception.class, () -> {
+ dao.getById(existingRoom.getId());
+ });
+ }
+
+ @Test
+ public void retrievingAllRoomsFailsWithExceptionAsFeedbackToClient() {
+ assertThrows(Exception.class, () -> {
+ dao.getAll();
+ });
+ }
+
+ }
+
+ /**
+ * Delete room schema for fresh setup per test.
+ *
+ * @throws SQLException if any error occurs.
+ */
+ @AfterEach
+ public void deleteSchema() throws SQLException {
+ try (var connection = DriverManager.getConnection(DB_URL);
+ var statement = connection.createStatement()) {
+ statement.execute(RoomSchemaSql.DELETE_SCHEMA_SQL);
+ }
+ }
+
+ private void assertRoomCountIs(int count) throws Exception {
+ try (var allRooms = dao.getAll()) {
+ assertEquals(count, allRooms.count());
+ }
+ }
+
+ /**
+ * An arbitrary number which does not correspond to an active Room id.
+ *
+ * @return an int of a room id which doesn't exist
+ */
+ private int getNonExistingRoomId() {
+ return 999;
+ }
+}
diff --git a/transaction-script/src/test/java/com/iluwatar/transactionscript/HotelTest.java b/transaction-script/src/test/java/com/iluwatar/transactionscript/HotelTest.java
new file mode 100644
index 000000000..ab0265244
--- /dev/null
+++ b/transaction-script/src/test/java/com/iluwatar/transactionscript/HotelTest.java
@@ -0,0 +1,151 @@
+/*
+ * The MIT License
+ * Copyright © 2014-2019 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+package com.iluwatar.transactionscript;
+
+import org.h2.jdbcx.JdbcDataSource;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import javax.sql.DataSource;
+import java.util.List;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+/**
+ * Tests {@link Hotel}
+ */
+public class HotelTest {
+
+ private static final String H2_DB_URL = "jdbc:h2:~/test";
+
+ private Hotel hotel;
+ private HotelDaoImpl dao;
+
+ @BeforeEach
+ public void setUp() throws Exception {
+ final var dataSource = createDataSource();
+ deleteSchema(dataSource);
+ createSchema(dataSource);
+ dao = new HotelDaoImpl(dataSource);
+ addRooms(dao);
+ hotel = new Hotel(dao);
+
+ }
+
+ @Test
+ public void bookingRoomShouldChangeBookedStatusToTrue() throws Exception {
+ hotel.bookRoom(1);
+ assertTrue(dao.getById(1).get().isBooked());
+ }
+
+ @Test()
+ public void bookingRoomWithInvalidIdShouldRaiseException() {
+ assertThrows(Exception.class, () -> {
+ hotel.bookRoom(getNonExistingRoomId());
+ });
+ }
+
+ @Test()
+ public void bookingRoomAgainShouldRaiseException() {
+ assertThrows(Exception.class, () -> {
+ hotel.bookRoom(1);
+ hotel.bookRoom(1);
+ });
+ }
+
+ @Test
+ public void NotBookingRoomShouldNotChangeBookedStatus() throws Exception {
+ assertFalse(dao.getById(1).get().isBooked());
+ }
+
+ @Test
+ public void cancelRoomBookingShouldChangeBookedStatus() throws Exception {
+ hotel.bookRoom(1);
+ assertTrue(dao.getById(1).get().isBooked());
+ hotel.cancelRoomBooking(1);
+ assertFalse(dao.getById(1).get().isBooked());
+ }
+
+ @Test
+ public void cancelRoomBookingWithInvalidIdShouldRaiseException() {
+ assertThrows(Exception.class, () -> {
+ hotel.cancelRoomBooking(getNonExistingRoomId());
+ });
+ }
+
+ @Test
+ public void cancelRoomBookingForUnbookedRoomShouldRaiseException() {
+ assertThrows(Exception.class, () -> {
+ hotel.cancelRoomBooking(1);
+ });
+ }
+
+
+ private static void deleteSchema(DataSource dataSource) throws java.sql.SQLException {
+ try (var connection = dataSource.getConnection();
+ var statement = connection.createStatement()) {
+ statement.execute(RoomSchemaSql.DELETE_SCHEMA_SQL);
+ }
+ }
+
+ private static void createSchema(DataSource dataSource) throws Exception {
+ try (var connection = dataSource.getConnection();
+ var statement = connection.createStatement()) {
+ statement.execute(RoomSchemaSql.CREATE_SCHEMA_SQL);
+ } catch (Exception e) {
+ throw new Exception(e.getMessage(), e);
+ }
+ }
+
+ public static DataSource createDataSource() {
+ JdbcDataSource dataSource = new JdbcDataSource();
+ dataSource.setUrl(H2_DB_URL);
+ return dataSource;
+ }
+
+ private static void addRooms(HotelDaoImpl hotelDao) throws Exception {
+ for (var room : generateSampleRooms()) {
+ hotelDao.add(room);
+ }
+ }
+
+ public static List generateSampleRooms() {
+ final var room1 = new Room(1, "Single", 50, false);
+ final var room2 = new Room(2, "Double", 80, false);
+ final var room3 = new Room(3, "Queen", 120, false);
+ final var room4 = new Room(4, "King", 150, false);
+ final var room5 = new Room(5, "Single", 50, false);
+ final var room6 = new Room(6, "Double", 80, false);
+ return List.of(room1, room2, room3, room4, room5, room6);
+ }
+
+ /**
+ * An arbitrary number which does not correspond to an active Room id.
+ *
+ * @return an int of a room id which doesn't exist
+ */
+ private int getNonExistingRoomId() {
+ return 999;
+ }
+}
diff --git a/transaction-script/src/test/java/com/iluwatar/transactionscript/RoomTest.java b/transaction-script/src/test/java/com/iluwatar/transactionscript/RoomTest.java
new file mode 100644
index 000000000..6755c2e5a
--- /dev/null
+++ b/transaction-script/src/test/java/com/iluwatar/transactionscript/RoomTest.java
@@ -0,0 +1,95 @@
+/*
+ * The MIT License
+ * Copyright © 2014-2019 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+package com.iluwatar.transactionscript;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+
+/**
+ * Tests {@link Room}.
+ */
+public class RoomTest {
+
+ private Room room;
+ private static final int ID = 1;
+ private static final String ROOMTYPE = "Single";
+ private static final int PRICE = 50;
+ private static final boolean BOOKED = false;
+
+ @BeforeEach
+ public void setUp() {
+ room = new Room(ID, ROOMTYPE, PRICE, BOOKED);
+ }
+
+ @Test
+ public void getAndSetId() {
+ final var newId = 2;
+ room.setId(newId);
+ assertEquals(newId, room.getId());
+ }
+
+ @Test
+ public void getAndSetRoomType() {
+ final var newRoomType = "Double";
+ room.setRoomType(newRoomType);
+ assertEquals(newRoomType, room.getRoomType());
+ }
+
+ @Test
+ public void getAndSetLastName() {
+ final var newPrice = 60;
+ room.setPrice(newPrice);
+ assertEquals(newPrice, room.getPrice());
+ }
+
+ @Test
+ public void notEqualWithDifferentId() {
+ final var newId = 2;
+ final var otherRoom = new Room(newId, ROOMTYPE, PRICE, BOOKED);
+ assertNotEquals(room, otherRoom);
+ assertNotEquals(room.hashCode(), otherRoom.hashCode());
+ }
+
+ @Test
+ public void equalsWithSameObjectValues() {
+ final var otherRoom = new Room(ID, ROOMTYPE, PRICE, BOOKED);
+ assertEquals(room, otherRoom);
+ assertEquals(room.hashCode(), otherRoom.hashCode());
+ }
+
+ @Test
+ public void equalsWithSameObjects() {
+ assertEquals(room, room);
+ assertEquals(room.hashCode(), room.hashCode());
+ }
+
+ @Test
+ public void testToString() {
+ assertEquals(String.format("Room{id=%s, roomType=%s, price=%s, booked=%s}",
+ room.getId(), room.getRoomType(), room.getPrice(), room.isBooked()), room.toString());
+ }
+}
diff --git a/twin/pom.xml b/twin/pom.xml
index cb60511c9..b879ac593 100644
--- a/twin/pom.xml
+++ b/twin/pom.xml
@@ -29,7 +29,7 @@
com.iluwatar
java-design-patterns
- 1.23.0-SNAPSHOT
+ 1.24.0-SNAPSHOT
twin
diff --git a/twin/src/test/java/com/iluwatar/twin/AppTest.java b/twin/src/test/java/com/iluwatar/twin/AppTest.java
index 50b787eeb..38a3208ad 100644
--- a/twin/src/test/java/com/iluwatar/twin/AppTest.java
+++ b/twin/src/test/java/com/iluwatar/twin/AppTest.java
@@ -25,13 +25,15 @@ package com.iluwatar.twin;
import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+
/**
* Application test
*/
-public class AppTest {
+class AppTest {
@Test
- public void test() throws Exception {
- App.main(new String[]{});
+ void shouldExecuteWithoutException() {
+ assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
diff --git a/twin/src/test/java/com/iluwatar/twin/BallItemTest.java b/twin/src/test/java/com/iluwatar/twin/BallItemTest.java
index 568c1d7b0..18aba2bed 100644
--- a/twin/src/test/java/com/iluwatar/twin/BallItemTest.java
+++ b/twin/src/test/java/com/iluwatar/twin/BallItemTest.java
@@ -108,7 +108,7 @@ public class BallItemTest {
* Logging Appender Implementation
*/
public class InMemoryAppender extends AppenderBase {
- private List log = new LinkedList<>();
+ private final List