Fixed most reported issues by SonarCloud.

This commit is contained in:
Toxic Dreamz 2020-08-15 21:47:39 +04:00
parent e7e3ace01f
commit 31471acb69
190 changed files with 1426 additions and 661 deletions

View File

@ -25,14 +25,23 @@ package com.iluwatar.abstractdocument;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/**
* Simple App 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}
* throws an exception.
*/
@Test
public void shouldExecuteAppWithoutException() {
App.main(null);
void shouldExecuteAppWithoutException() {
assertDoesNotThrow(() -> App.main(null));
}
}

View File

@ -25,12 +25,23 @@ package com.iluwatar.abstractfactory;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/**
* Tests that Abstract Factory 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}
* throws an exception.
*/
@Test
public void test() {
App.main(new String[]{});
void shouldExecuteApplicationWithoutException() {
assertDoesNotThrow(() -> App.main(new String[]{}));
}
}

View File

@ -25,13 +25,23 @@ package com.iluwatar.acyclicvisitor;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/**
* Tests that the Acyclic Visitor 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}
* throws an exception.
*/
@Test
public void test() {
App.main(new String[]{});
void shouldExecuteApplicationWithoutException() {
assertDoesNotThrow(() -> App.main(new String[]{}));
}
}

View File

@ -25,12 +25,23 @@ package com.iluwatar.adapter;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/**
* Tests that Adapter 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}
* throws an exception.
*/
@Test
public void test() {
App.main(new String[]{});
void shouldExecuteApplicationWithoutException() {
assertDoesNotThrow(() -> App.main(new String[]{}));
}
}

View File

@ -62,7 +62,7 @@ public class RemoteService implements RemoteServiceInterface {
*
* @param value integer value to be multiplied.
* @return if waitTime is less than {@link RemoteService#THRESHOLD}, it returns value * 10,
* otherwise {@link RemoteServiceInterface#FAILURE}.
* otherwise {@link RemoteServiceStatus#FAILURE}.
*/
@Override
public long doRemoteFunction(int value) {
@ -74,6 +74,6 @@ public class RemoteService implements RemoteServiceInterface {
} catch (InterruptedException e) {
LOGGER.error("Thread sleep state interrupted", e);
}
return waitTime <= THRESHOLD ? value * 10 : FAILURE;
return waitTime <= THRESHOLD ? value * 10 : RemoteServiceStatus.FAILURE.getRemoteServiceStatusValue();
}
}

View File

@ -27,7 +27,6 @@ package com.iluwatar.ambassador;
* Interface shared by ({@link RemoteService}) and ({@link ServiceAmbassador}).
*/
interface RemoteServiceInterface {
int FAILURE = -1;
long doRemoteFunction(int value);
}

View File

@ -0,0 +1,23 @@
package com.iluwatar.ambassador;
/**
* Holds information regarding the status of the Remote Service.
*
* !Attention - This Enum replaces the integer value previously stored in {@link RemoteServiceInterface}
* as SonarCloud was identifying it as an issue. All test cases have been checked after changes, without failures.
*/
public enum RemoteServiceStatus {
FAILURE(-1)
;
private final long remoteServiceStatusValue;
RemoteServiceStatus(long remoteServiceStatusValue) {
this.remoteServiceStatusValue = remoteServiceStatusValue;
}
public long getRemoteServiceStatusValue() {
return remoteServiceStatusValue;
}
}

View File

@ -23,6 +23,7 @@
package com.iluwatar.ambassador;
import static com.iluwatar.ambassador.RemoteServiceStatus.FAILURE;
import static java.lang.Thread.sleep;
import org.slf4j.Logger;
@ -58,14 +59,14 @@ public class ServiceAmbassador implements RemoteServiceInterface {
private long safeCall(int value) {
var retries = 0;
var result = (long) FAILURE;
var result = FAILURE.getRemoteServiceStatusValue();
for (int i = 0; i < RETRIES; i++) {
if (retries >= RETRIES) {
return FAILURE;
return FAILURE.getRemoteServiceStatusValue();
}
if ((result = checkLatency(value)) == FAILURE) {
if ((result = checkLatency(value)) == FAILURE.getRemoteServiceStatusValue()) {
LOGGER.info("Failed to reach remote: (" + (i + 1) + ")");
retries++;
try {

View File

@ -25,13 +25,23 @@ package com.iluwatar.ambassador;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/**
* Application test
*/
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}
* throws an exception.
*/
@Test
void test() {
App.main(new String[]{});
void shouldExecuteApplicationWithoutException() {
assertDoesNotThrow(() -> App.main(new String[]{}));
}
}

View File

@ -37,6 +37,6 @@ class ClientTest {
Client client = new Client();
var result = client.useService(10);
assertTrue(result == 100 || result == RemoteService.FAILURE);
assertTrue(result == 100 || result == RemoteServiceStatus.FAILURE.getRemoteServiceStatusValue());
}
}

View File

@ -37,7 +37,7 @@ class RemoteServiceTest {
void testFailedCall() {
var remoteService = new RemoteService(new StaticRandomProvider(0.21));
var result = remoteService.doRemoteFunction(10);
assertEquals(RemoteServiceInterface.FAILURE, result);
assertEquals(RemoteServiceStatus.FAILURE.getRemoteServiceStatusValue(), result);
}
@Test

View File

@ -35,6 +35,6 @@ class ServiceAmbassadorTest {
@Test
void test() {
long result = new ServiceAmbassador().doRemoteFunction(10);
assertTrue(result == 100 || result == RemoteServiceInterface.FAILURE);
assertTrue(result == 100 || result == RemoteServiceStatus.FAILURE.getRemoteServiceStatusValue());
}
}

View File

@ -25,12 +25,24 @@ package com.iluwatar.async.method.invocation;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/**
* Application test
*/
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}
* throws an exception.
*/
@Test
void test() throws Exception {
App.main(new String[]{});
void shouldExecuteApplicationWithoutException() {
assertDoesNotThrow(() -> App.main(new String[]{}));
}
}

View File

@ -24,15 +24,26 @@
package com.iluwatar.balking;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/**
* Application test
*/
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}
* throws an exception.
*/
@Test
void main() {
App.main();
void shouldExecuteApplicationWithoutException() {
assertDoesNotThrow((Executable) App::main);
}
}

View File

@ -25,12 +25,22 @@ package com.iluwatar.bridge;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/**
* Application test
*/
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}
* throws an exception.
*/
@Test
void test() {
App.main(new String[]{});
void shouldExecuteApplicationWithoutException() {
assertDoesNotThrow(() -> App.main(new String[]{}));
}
}

View File

@ -25,12 +25,23 @@ package com.iluwatar.builder;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/**
* Application test
*/
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}
* throws an exception.
*/
@Test
void test() {
App.main(new String[]{});
void shouldExecuteApplicationWithoutException() {
assertDoesNotThrow(() -> App.main(new String[]{}));
}
}

View File

@ -27,13 +27,23 @@ import org.junit.jupiter.api.Test;
import java.io.IOException;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/**
* Tests that Business Delegate 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}
* throws an exception.
*/
@Test
public void test() throws IOException {
String[] args = {};
App.main(args);
void shouldExecuteApplicationWithoutException() {
assertDoesNotThrow(() -> App.main(new String[]{}));
}
}

View File

@ -58,12 +58,14 @@ public class App {
var vm = new VirtualMachine();
vm.getWizards()[0] = wizard;
interpretInstruction("LITERAL 0", vm);
interpretInstruction("LITERAL 0", vm);
String literal = "LITERAL 0";
interpretInstruction(literal, vm);
interpretInstruction(literal, vm);
interpretInstruction("GET_HEALTH", vm);
interpretInstruction("LITERAL 0", vm);
interpretInstruction(literal, vm);
interpretInstruction("GET_AGILITY", vm);
interpretInstruction("LITERAL 0", vm);
interpretInstruction(literal, vm);
interpretInstruction("GET_WISDOM ", vm);
interpretInstruction("ADD", vm);
interpretInstruction("LITERAL 2", vm);

View File

@ -25,13 +25,22 @@ package com.iluwatar.bytecode;
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}
* throws an exception.
*/
@Test
public void test() {
App.main(new String[]{});
void shouldExecuteApplicationWithoutException() {
assertDoesNotThrow(() -> App.main(new String[]{}));
}
}

View File

@ -27,12 +27,23 @@ import org.junit.jupiter.api.Test;
import java.io.IOException;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/**
* Tests that Caching 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}
* throws an exception.
*/
@Test
public void test() {
App.main(new String[]{});
void shouldExecuteApplicationWithoutException() {
assertDoesNotThrow(() -> App.main(new String[]{}));
}
}

View File

@ -25,12 +25,23 @@ package com.iluwatar.callback;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/**
* Tests that Callback 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}
* throws an exception.
*/
@Test
public void test() {
App.main(new String[]{});
void shouldExecuteApplicationWithoutException() {
assertDoesNotThrow(() -> App.main(new String[]{}));
}
}

View File

@ -25,13 +25,23 @@ package com.iluwatar.chain;
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}
* throws an exception.
*/
@Test
public void test() {
App.main(new String[]{});
void shouldExecuteApplicationWithoutException() {
assertDoesNotThrow(() -> App.main(new String[]{}));
}
}

View File

@ -39,6 +39,12 @@
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@ -25,12 +25,19 @@ package com.iluwatar.combinator;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
public class CombinatorAppTest {
/**
* Issue: Add at least one assertion to this test case.
*
* Solution: Inserted assertion to check whether the execution of the main method in {@link CombinatorApp#main(String[])}
* throws an exception.
*/
@Test
public void main() {
CombinatorApp.main(new String[]{});
public void shouldExecuteApplicationWithoutException() {
assertDoesNotThrow(() -> CombinatorApp.main(new String[]{}));
}
}

View File

@ -25,12 +25,21 @@ package com.iluwatar.command;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/**
* Tests that Command 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[]{}));
}
}

View File

@ -39,6 +39,8 @@ import com.iluwatar.commander.shippingservice.ShippingService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
/**
* <p>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
@ -169,53 +171,10 @@ public class Commander {
var list = paymentService.exceptionsList;
var t = new Thread(() -> {
Retry.Operation op = (l) -> {
if (!l.isEmpty()) {
if (DatabaseUnavailableException.class.isAssignableFrom(l.get(0).getClass())) {
LOG.debug("Order " + order.id + ": Error in connecting to payment service,"
+ " trying again..");
} else {
LOG.debug("Order " + order.id + ": Error in creating payment request..");
}
throw l.remove(0);
}
if (order.paid.equals(PaymentStatus.Trying)) {
var transactionId = paymentService.receiveRequest(order.price);
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!!");
finalSiteMsgShown = true;
}
sendSuccessMessage(order);
}
handlePaymentRetryOperation(order, l);
};
Retry.HandleErrorIssue<Order> handleError = (o, err) -> {
if (PaymentDetailsErrorException.class.isAssignableFrom(err.getClass())) {
if (!finalSiteMsgShown) {
LOG.info("There was an error in payment. Your account/card details "
+ "may have been incorrect. "
+ "Meanwhile, your order has been converted to COD and will be shipped.");
finalSiteMsgShown = true;
}
LOG.error("Order " + order.id + ": Payment details incorrect, failed..");
o.paid = PaymentStatus.NotDone;
sendPaymentFailureMessage(o);
} else {
if (o.messageSent.equals(MessageSent.NoneSent)) {
if (!finalSiteMsgShown) {
LOG.info("There was an error in payment. We are on it, and will get back to you "
+ "asap. Don't worry, your order has been placed and will be shipped.");
finalSiteMsgShown = true;
}
LOG.warn("Order " + 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);
updateQueue(qt);
}
}
handlePaymentErrorIssue(order, o, err);
};
var r = new Retry<>(op, handleError, numOfRetries, retryDuration,
e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass()));
@ -228,18 +187,70 @@ public class Commander {
t.start();
}
private void handlePaymentRetryOperation(Order order, List<Exception> l) throws Exception {
if (!l.isEmpty()) {
if (DatabaseUnavailableException.class.isAssignableFrom(l.get(0).getClass())) {
LOG.debug("Order " + order.id + ": Error in connecting to payment service,"
+ " trying again..");
} else {
LOG.debug("Order " + order.id + ": Error in creating payment request..");
}
throw l.remove(0);
}
if (order.paid.equals(PaymentStatus.TRYING)) {
var transactionId = paymentService.receiveRequest(order.price);
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!!");
finalSiteMsgShown = true;
}
sendSuccessMessage(order);
}
}
private void handlePaymentErrorIssue(Order order, Order o, Exception err) {
if (PaymentDetailsErrorException.class.isAssignableFrom(err.getClass())) {
if (!finalSiteMsgShown) {
LOG.info("There was an error in payment. Your account/card details "
+ "may have been incorrect. "
+ "Meanwhile, your order has been converted to COD and will be shipped.");
finalSiteMsgShown = true;
}
LOG.error("Order " + order.id + ": Payment details incorrect, failed..");
o.paid = PaymentStatus.NOT_DONE;
sendPaymentFailureMessage(o);
} else {
if (o.messageSent.equals(MessageSent.NONE_SENT)) {
if (!finalSiteMsgShown) {
LOG.info("There was an error in payment. We are on it, and will get back to you "
+ "asap. Don't worry, your order has been placed and will be shipped.");
finalSiteMsgShown = true;
}
LOG.warn("Order " + 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);
updateQueue(qt);
}
}
}
private void updateQueue(QueueTask qt) {
if (System.currentTimeMillis() - qt.order.createdTime >= this.queueTime) {
// since payment time is lesser than queuetime it would have already failed..
// 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 +267,8 @@ public class Commander {
tryDoingTasksInQueue();
};
Retry.HandleErrorIssue<QueueTask> 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,7 +342,35 @@ public class Commander {
}
var list = messagingService.exceptionsList;
Thread t = new Thread(() -> {
Retry.Operation op = (l) -> {
Retry.Operation op = handleSuccessMessageRetryOperation(order);
Retry.HandleErrorIssue<Order> handleError = (o, err) -> {
handleSuccessMessageErrorIssue(order, o);
};
var r = new Retry<>(op, handleError, numOfRetries, retryDuration,
e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass()));
try {
r.perform(list, order);
} catch (Exception e1) {
e1.printStackTrace();
}
});
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 "
@ -342,34 +381,14 @@ public class Commander {
}
throw l.remove(0);
}
if (!order.messageSent.equals(MessageSent.PaymentFail)
&& !order.messageSent.equals(MessageSent.PaymentSuccessful)) {
if (!order.messageSent.equals(MessageSent.PAYMENT_FAIL)
&& !order.messageSent.equals(MessageSent.PAYMENT_SUCCESSFUL)) {
var requestId = messagingService.receiveRequest(2);
order.messageSent = MessageSent.PaymentSuccessful;
order.messageSent = MessageSent.PAYMENT_SUCCESSFUL;
LOG.info("Order " + order.id + ": Payment Success message sent,"
+ " request Id: " + requestId);
}
};
Retry.HandleErrorIssue<Order> 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);
}
};
var r = new Retry<>(op, handleError, numOfRetries, retryDuration,
e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass()));
try {
r.perform(list, order);
} catch (Exception e1) {
e1.printStackTrace();
}
});
t.start();
}
private void sendPaymentFailureMessage(Order order) {
@ -380,34 +399,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<Order> 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 +415,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<Exception> 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 +455,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<Order> 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 +471,38 @@ 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<Exception> 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 +525,7 @@ public class Commander {
Retry.HandleErrorIssue<Order> 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 +555,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 +583,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,"

View File

@ -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;
}

View File

@ -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.";

View File

@ -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) {

View File

@ -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[]{}));
}
}

View File

@ -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[]{}));
}
}

View File

@ -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[]{}));
}
}

View File

@ -43,6 +43,6 @@ public class AiComponent implements Component {
@Override
public void render() {
// Do Nothing.
}
}

View File

@ -40,7 +40,7 @@ public class AiComponentManager {
private final int numEntities;
private static final Component[] AI_COMPONENTS = new AiComponent[MAX_ENTITIES];
private final Component[] AI_COMPONENTS = new AiComponent[MAX_ENTITIES];
public AiComponentManager(int numEntities) {
this.numEntities = numEntities;

View File

@ -40,7 +40,7 @@ public class PhysicsComponentManager {
private final int numEntities;
private static final Component[] PHYSICS_COMPONENTS = new PhysicsComponent[MAX_ENTITIES];
private final Component[] PHYSICS_COMPONENTS = new PhysicsComponent[MAX_ENTITIES];
public PhysicsComponentManager(int numEntities) {
this.numEntities = numEntities;

View File

@ -40,7 +40,7 @@ public class RenderComponentManager {
private final int numEntities;
private static final Component[] RENDER_COMPONENTS = new RenderComponent[MAX_ENTITIES];
private final Component[] RENDER_COMPONENTS = new RenderComponent[MAX_ENTITIES];
public RenderComponentManager(int numEntities) {
this.numEntities = numEntities;

View File

@ -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[] {}));
}
}

View File

@ -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);
}
}

View File

@ -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[]{}));
}
}

View File

@ -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[]{}));
}
}

View File

@ -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[]{}));
}
}

View File

@ -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[]{}));
}
}

View File

@ -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[]{}));
}
}

View File

@ -44,6 +44,11 @@
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>

View File

@ -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[]{}));
}
}

View File

@ -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[]{}));
}
}

View File

@ -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[]{}));
}
}

View File

@ -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[]{}));
}
}

View File

@ -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[]{}));
}
}

View File

@ -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[]{}));
}
}

View File

@ -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[]{}));
}
}

View File

@ -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[]{}));
}
}

View File

@ -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[]{}));
}
}

View File

@ -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[]{}));
}
}

View File

@ -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[]{}));
}
}

View File

@ -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();
}

View File

@ -45,4 +45,8 @@ public class Commander implements CommanderExtension {
public void commanderReady() {
LOGGER.info("[Commander] " + unit.getName() + " is ready!");
}
public CommanderUnit getUnit() {
return unit;
}
}

View File

@ -45,4 +45,8 @@ public class Sergeant implements SergeantExtension {
public void sergeantReady() {
LOGGER.info("[Sergeant] " + unit.getName() + " is ready!");
}
public SergeantUnit getUnit() {
return unit;
}
}

View File

@ -44,4 +44,8 @@ public class Soldier implements SoldierExtension {
public void soldierReady() {
LOGGER.info("[Solider] " + unit.getName() + " is ready!");
}
public SoldierUnit getUnit() {
return unit;
}
}

View File

@ -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[]{}));
}
}

View File

@ -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<ILoggingEvent> listAppender = new ListAppender<>();
listAppender.start();
commanderLogger.addAppender(listAppender);
final var commander = new Commander(new CommanderUnit("CommanderUnitTest"));
commander.commanderReady();
List<ILoggingEvent> logsList = listAppender.list;
assertEquals("[Commander] " + commander.getUnit().getName() + " is ready!", logsList.get(0)
.getMessage());
assertEquals(Level.INFO, logsList.get(0)
.getLevel());
}
}

View File

@ -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<ILoggingEvent> listAppender = new ListAppender<>();
listAppender.start();
sergeantLogger.addAppender(listAppender);
final var sergeant = new Sergeant(new SergeantUnit("SergeantUnitTest"));
sergeant.sergeantReady();
List<ILoggingEvent> logsList = listAppender.list;
assertEquals("[Sergeant] " + sergeant.getUnit().getName() + " is ready!", logsList.get(0)
.getMessage());
assertEquals(Level.INFO, logsList.get(0)
.getLevel());
}
}

View File

@ -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<ILoggingEvent> listAppender = new ListAppender<>();
listAppender.start();
soldierLogger.addAppender(listAppender);
final var soldier = new Soldier(new SoldierUnit("SoldierUnitTest"));
soldier.soldierReady();
List<ILoggingEvent> logsList = listAppender.list;
assertEquals("[Soldier] " + soldier.getUnit().getName() + " is ready!", logsList.get(0)
.getMessage());
assertEquals(Level.INFO, logsList.get(0)
.getLevel());
}
}

View File

@ -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[]{}));
}
}

View File

@ -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[]{}));
}
}

View File

@ -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[]{}));
}
}

View File

@ -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[]{}));
}
}

View File

@ -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:
if (menuItem == MenuItem.COMPANY) {
dispatchAction(new ContentAction(Content.COMPANY));
break;
} else {
dispatchAction(new ContentAction(Content.PRODUCTS));
}
}

View File

@ -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[]{}));
}
}

View File

@ -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[]{}));
}
}

View File

@ -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[]{}));
}
}

View File

@ -39,6 +39,12 @@
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>

View File

@ -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[]{}));
}
}

View File

@ -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));
}
}

View File

@ -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<LotteryTicket> 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<LotteryTicketId> 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);
}
}

View File

@ -36,6 +36,9 @@ 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;
@ -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);

View File

@ -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[]{}));
}
}

View File

@ -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[]{}));
}
}

View File

@ -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[]{}));
}
}

View File

@ -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[]{}));
}
}

View File

@ -81,6 +81,7 @@ import java.util.List;
public class App {
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) {

View File

@ -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[]{}));
}
}

View File

@ -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[]{}));
}
}

View File

@ -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<Message> 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:

View File

@ -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
}
}

View File

@ -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.
}
}

View File

@ -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[]{}));
}
}

View File

@ -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[]{}));
}
}

View File

@ -37,6 +37,11 @@
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>

View File

@ -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[]{}));
}
}

View File

@ -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;

View File

@ -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;

View File

@ -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;

View File

@ -23,13 +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() {
App.main(new String[]{});
void shouldExecuteApplicationWithoutException() {
assertDoesNotThrow(() -> App.main(new String[]{}));
}
}

Some files were not shown because too many files have changed in this diff Show More