Java 11 migrate remaining e (#1112)
* Moves eip-aggregator to Java 11 * Moves eip-message-channel to Java 11 * Moves eip-publish-subscribe to Java 11 * Moves eip-splitter to Java 11 * Moves eip-wire-tap to Java 11 * Moves event-aggregator to Java 11 * Moves event-asynchronous to Java 11 * Moves event-driven-architecture to Java 11 * Moves event-queue to Java 11 * Moves event-sourcing to Java 11 * Moves execute-around to Java 11 * Moves extension-objects to Java 11
This commit is contained in:
parent
b09b100614
commit
fb2c026822
@ -27,7 +27,6 @@ import org.apache.camel.CamelContext;
|
||||
import org.apache.camel.builder.RouteBuilder;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.context.ConfigurableApplicationContext;
|
||||
|
||||
/**
|
||||
* Sometimes in enterprise systems there is a need to group incoming data in order to process it as
|
||||
@ -49,19 +48,17 @@ public class App {
|
||||
*/
|
||||
public static void main(String[] args) throws Exception {
|
||||
// Run Spring Boot application and obtain ApplicationContext
|
||||
ConfigurableApplicationContext context = SpringApplication.run(App.class, args);
|
||||
var context = SpringApplication.run(App.class, args);
|
||||
|
||||
// Get CamelContext from ApplicationContext
|
||||
CamelContext camelContext = (CamelContext) context.getBean("camelContext");
|
||||
var camelContext = (CamelContext) context.getBean("camelContext");
|
||||
|
||||
// Add a new routes that will handle endpoints form SplitterRoute class.
|
||||
camelContext.addRoutes(new RouteBuilder() {
|
||||
|
||||
@Override
|
||||
public void configure() throws Exception {
|
||||
public void configure() {
|
||||
from("{{endpoint}}").log("ENDPOINT: ${body}");
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
// Add producer that will send test message to an entry point in WireTapRoute
|
||||
|
@ -48,8 +48,6 @@ public class AggregatorRoute extends RouteBuilder {
|
||||
|
||||
/**
|
||||
* Configures the route.
|
||||
*
|
||||
* @throws Exception in case of exception during configuration
|
||||
*/
|
||||
@Override
|
||||
public void configure() {
|
||||
|
@ -40,8 +40,8 @@ public class MessageAggregationStrategy implements AggregationStrategy {
|
||||
return newExchange;
|
||||
}
|
||||
|
||||
String in1 = (String) oldExchange.getIn().getBody();
|
||||
String in2 = (String) newExchange.getIn().getBody();
|
||||
var in1 = (String) oldExchange.getIn().getBody();
|
||||
var in2 = (String) newExchange.getIn().getBody();
|
||||
|
||||
oldExchange.getIn().setBody(in1 + ";" + in2);
|
||||
|
||||
|
@ -32,7 +32,6 @@ public class AppTest {
|
||||
|
||||
@Test
|
||||
public void testMain() throws Exception {
|
||||
String[] args = {};
|
||||
App.main(args);
|
||||
App.main(new String[]{});
|
||||
}
|
||||
}
|
||||
|
@ -23,6 +23,8 @@
|
||||
|
||||
package com.iluwatar.eip.aggregator.routes;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import org.apache.camel.EndpointInject;
|
||||
import org.apache.camel.ProducerTemplate;
|
||||
import org.apache.camel.component.mock.MockEndpoint;
|
||||
@ -35,13 +37,11 @@ import org.springframework.test.annotation.DirtiesContext;
|
||||
import org.springframework.test.context.ActiveProfiles;
|
||||
import org.springframework.test.context.junit.jupiter.SpringExtension;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
/**
|
||||
* Test class for <i>AggregatorRoute</i>.
|
||||
* <p>
|
||||
* In order for it to work we have to mock endpoints we want to read/write to. To mock those we need to substitute
|
||||
* original endpoint names to mocks.
|
||||
* In order for it to work we have to mock endpoints we want to read/write to. To mock those we need
|
||||
* to substitute original endpoint names to mocks.
|
||||
* </p>
|
||||
*/
|
||||
@ExtendWith(SpringExtension.class)
|
||||
@ -59,6 +59,7 @@ public class AggregatorRouteTest {
|
||||
|
||||
/**
|
||||
* Test if endpoint receives three separate messages.
|
||||
*
|
||||
* @throws Exception in case of en exception during the test
|
||||
*/
|
||||
@Test
|
||||
@ -76,10 +77,10 @@ public class AggregatorRouteTest {
|
||||
endpoint.expectedMessageCount(2);
|
||||
endpoint.assertIsSatisfied();
|
||||
|
||||
String body = (String) endpoint.getReceivedExchanges().get(0).getIn().getBody();
|
||||
var body = (String) endpoint.getReceivedExchanges().get(0).getIn().getBody();
|
||||
assertEquals(3, body.split(";").length);
|
||||
|
||||
String body2 = (String) endpoint.getReceivedExchanges().get(1).getIn().getBody();
|
||||
var body2 = (String) endpoint.getReceivedExchanges().get(1).getIn().getBody();
|
||||
assertEquals(2, body2.split(";").length);
|
||||
}
|
||||
}
|
||||
|
@ -23,13 +23,12 @@
|
||||
|
||||
package com.iluwatar.eip.aggregator.routes;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import org.apache.camel.CamelContext;
|
||||
import org.apache.camel.Exchange;
|
||||
import org.apache.camel.impl.DefaultExchange;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
/**
|
||||
* Tests MessageAggregationStrategy
|
||||
*/
|
||||
@ -37,27 +36,27 @@ public class MessageAggregationStrategyTest {
|
||||
|
||||
@Test
|
||||
public void testAggregate() {
|
||||
MessageAggregationStrategy mas = new MessageAggregationStrategy();
|
||||
Exchange oldExchange = new DefaultExchange((CamelContext) null);
|
||||
var mas = new MessageAggregationStrategy();
|
||||
var oldExchange = new DefaultExchange((CamelContext) null);
|
||||
oldExchange.getIn().setBody("TEST1");
|
||||
|
||||
Exchange newExchange = new DefaultExchange((CamelContext) null);
|
||||
var newExchange = new DefaultExchange((CamelContext) null);
|
||||
newExchange.getIn().setBody("TEST2");
|
||||
|
||||
Exchange output = mas.aggregate(oldExchange, newExchange);
|
||||
String outputBody = (String) output.getIn().getBody();
|
||||
var output = mas.aggregate(oldExchange, newExchange);
|
||||
var outputBody = (String) output.getIn().getBody();
|
||||
assertEquals("TEST1;TEST2", outputBody);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAggregateOldNull() {
|
||||
MessageAggregationStrategy mas = new MessageAggregationStrategy();
|
||||
var mas = new MessageAggregationStrategy();
|
||||
|
||||
Exchange newExchange = new DefaultExchange((CamelContext) null);
|
||||
var newExchange = new DefaultExchange((CamelContext) null);
|
||||
newExchange.getIn().setBody("TEST2");
|
||||
|
||||
Exchange output = mas.aggregate(null, newExchange);
|
||||
String outputBody = (String) output.getIn().getBody();
|
||||
var output = mas.aggregate(null, newExchange);
|
||||
var outputBody = (String) output.getIn().getBody();
|
||||
|
||||
assertEquals(newExchange, output);
|
||||
assertEquals("TEST2", outputBody);
|
||||
|
@ -23,7 +23,6 @@
|
||||
|
||||
package com.iluwatar.eip.message.channel;
|
||||
|
||||
import org.apache.camel.CamelContext;
|
||||
import org.apache.camel.builder.RouteBuilder;
|
||||
import org.apache.camel.impl.DefaultCamelContext;
|
||||
import org.slf4j.Logger;
|
||||
@ -57,7 +56,7 @@ public class App {
|
||||
* Program entry point.
|
||||
*/
|
||||
public static void main(String[] args) throws Exception {
|
||||
CamelContext context = new DefaultCamelContext();
|
||||
var context = new DefaultCamelContext();
|
||||
|
||||
context.addRoutes(new RouteBuilder() {
|
||||
|
||||
|
@ -26,15 +26,12 @@ package com.iluwatar.eip.message.channel;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
*
|
||||
* Application test
|
||||
*
|
||||
*/
|
||||
public class AppTest {
|
||||
|
||||
@Test
|
||||
public void test() throws Exception {
|
||||
String[] args = {};
|
||||
App.main(args);
|
||||
App.main(new String[]{});
|
||||
}
|
||||
}
|
||||
|
@ -23,8 +23,6 @@
|
||||
|
||||
package com.iluwatar.eip.publish.subscribe;
|
||||
|
||||
import org.apache.camel.CamelContext;
|
||||
import org.apache.camel.ProducerTemplate;
|
||||
import org.apache.camel.builder.RouteBuilder;
|
||||
import org.apache.camel.impl.DefaultCamelContext;
|
||||
import org.slf4j.Logger;
|
||||
@ -55,14 +53,14 @@ public class App {
|
||||
* Program entry point.
|
||||
*/
|
||||
public static void main(String[] args) throws Exception {
|
||||
CamelContext context = new DefaultCamelContext();
|
||||
var context = new DefaultCamelContext();
|
||||
context.addRoutes(new RouteBuilder() {
|
||||
@Override
|
||||
public void configure() throws Exception {
|
||||
from("direct:origin").multicast().to("mock:foo", "mock:bar", "stream:out");
|
||||
}
|
||||
});
|
||||
ProducerTemplate template = context.createProducerTemplate();
|
||||
var template = context.createProducerTemplate();
|
||||
context.start();
|
||||
context.getRoutes().forEach(r -> LOGGER.info(r.toString()));
|
||||
template.sendBody("direct:origin", "Hello from origin");
|
||||
|
@ -26,15 +26,12 @@ package com.iluwatar.eip.publish.subscribe;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
*
|
||||
* Application test
|
||||
*
|
||||
*/
|
||||
public class AppTest {
|
||||
|
||||
@Test
|
||||
public void test() throws Exception {
|
||||
String[] args = {};
|
||||
App.main(args);
|
||||
App.main(new String[]{});
|
||||
}
|
||||
}
|
||||
|
@ -27,7 +27,6 @@ import org.apache.camel.CamelContext;
|
||||
import org.apache.camel.builder.RouteBuilder;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.context.ConfigurableApplicationContext;
|
||||
|
||||
/**
|
||||
* It is very common in integration systems that incoming messages consists of many items bundled
|
||||
@ -53,10 +52,10 @@ public class App {
|
||||
*/
|
||||
public static void main(String[] args) throws Exception {
|
||||
// Run Spring Boot application and obtain ApplicationContext
|
||||
ConfigurableApplicationContext context = SpringApplication.run(App.class, args);
|
||||
var context = SpringApplication.run(App.class, args);
|
||||
|
||||
// Get CamelContext from ApplicationContext
|
||||
CamelContext camelContext = (CamelContext) context.getBean("camelContext");
|
||||
var camelContext = (CamelContext) context.getBean("camelContext");
|
||||
|
||||
// Add a new routes that will handle endpoints form SplitterRoute class.
|
||||
camelContext.addRoutes(new RouteBuilder() {
|
||||
|
@ -32,7 +32,6 @@ public class AppTest {
|
||||
|
||||
@Test
|
||||
public void testMain() throws Exception {
|
||||
String[] args = {};
|
||||
App.main(args);
|
||||
App.main(new String[]{});
|
||||
}
|
||||
}
|
||||
|
@ -38,8 +38,8 @@ import org.springframework.test.context.junit.jupiter.SpringExtension;
|
||||
/**
|
||||
* Test class for <i>SplitterRoute</i>.
|
||||
* <p>
|
||||
* In order for it to work we have to mock endpoints we want to read/write to. To mock those we need to substitute
|
||||
* original endpoint names to mocks.
|
||||
* In order for it to work we have to mock endpoints we want to read/write to. To mock those we need
|
||||
* to substitute original endpoint names to mocks.
|
||||
* </p>
|
||||
*/
|
||||
@ExtendWith(SpringExtension.class)
|
||||
@ -57,6 +57,7 @@ public class SplitterRouteTest {
|
||||
|
||||
/**
|
||||
* Test if endpoint receives three separate messages.
|
||||
*
|
||||
* @throws Exception in case of en exception during the test
|
||||
*/
|
||||
@Test
|
||||
@ -64,7 +65,7 @@ public class SplitterRouteTest {
|
||||
public void testSplitter() throws Exception {
|
||||
|
||||
// Three items in one entry message
|
||||
entry.sendBody(new String[] {"TEST1", "TEST2", "TEST3"});
|
||||
entry.sendBody(new String[]{"TEST1", "TEST2", "TEST3"});
|
||||
|
||||
// Endpoint should have three different messages in the end order of the messages is not important
|
||||
endpoint.expectedMessageCount(3);
|
||||
|
@ -27,7 +27,6 @@ import org.apache.camel.CamelContext;
|
||||
import org.apache.camel.builder.RouteBuilder;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.context.ConfigurableApplicationContext;
|
||||
|
||||
/**
|
||||
* In most integration cases there is a need to monitor the messages flowing through the system. It
|
||||
@ -52,10 +51,10 @@ public class App {
|
||||
*/
|
||||
public static void main(String[] args) throws Exception {
|
||||
// Run Spring Boot application and obtain ApplicationContext
|
||||
ConfigurableApplicationContext context = SpringApplication.run(App.class, args);
|
||||
var context = SpringApplication.run(App.class, args);
|
||||
|
||||
// Get CamelContext from ApplicationContext
|
||||
CamelContext camelContext = (CamelContext) context.getBean("camelContext");
|
||||
var camelContext = (CamelContext) context.getBean("camelContext");
|
||||
|
||||
// Add a new routes that will handle endpoints form WireTapRoute class.
|
||||
camelContext.addRoutes(new RouteBuilder() {
|
||||
|
@ -32,7 +32,6 @@ public class AppTest {
|
||||
|
||||
@Test
|
||||
public void testMain() throws Exception {
|
||||
String[] args = {};
|
||||
App.main(args);
|
||||
App.main(new String[]{});
|
||||
}
|
||||
}
|
||||
|
@ -23,8 +23,9 @@
|
||||
|
||||
package com.iluwatar.eip.wiretap.routes;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import org.apache.camel.EndpointInject;
|
||||
import org.apache.camel.Message;
|
||||
import org.apache.camel.ProducerTemplate;
|
||||
import org.apache.camel.component.mock.MockEndpoint;
|
||||
import org.junit.jupiter.api.Test;
|
||||
@ -36,13 +37,11 @@ import org.springframework.test.annotation.DirtiesContext;
|
||||
import org.springframework.test.context.ActiveProfiles;
|
||||
import org.springframework.test.context.junit.jupiter.SpringExtension;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
/**
|
||||
* Test class for <i>WireTapRoute</i>.
|
||||
* <p>
|
||||
* In order for it to work we have to mock endpoints we want to read/write to. To mock those we need to substitute
|
||||
* original endpoint names to mocks.
|
||||
* In order for it to work we have to mock endpoints we want to read/write to. To mock those we need
|
||||
* to substitute original endpoint names to mocks.
|
||||
* </p>
|
||||
*/
|
||||
@ExtendWith(SpringExtension.class)
|
||||
@ -63,6 +62,7 @@ public class WireTapRouteTest {
|
||||
|
||||
/**
|
||||
* Test if both endpoints receive exactly one message containing the same, unchanged body.
|
||||
*
|
||||
* @throws Exception in case of en exception during the test
|
||||
*/
|
||||
@Test
|
||||
@ -76,8 +76,8 @@ public class WireTapRouteTest {
|
||||
endpoint.assertIsSatisfied();
|
||||
wireTapEndpoint.assertIsSatisfied();
|
||||
|
||||
Message endpointIn = endpoint.getExchanges().get(0).getIn();
|
||||
Message wireTapEndpointIn = wireTapEndpoint.getExchanges().get(0).getIn();
|
||||
var endpointIn = endpoint.getExchanges().get(0).getIn();
|
||||
var wireTapEndpointIn = wireTapEndpoint.getExchanges().get(0).getIn();
|
||||
|
||||
assertEquals("TEST", endpointIn.getBody());
|
||||
assertEquals("TEST", wireTapEndpointIn.getBody());
|
||||
|
@ -23,8 +23,9 @@
|
||||
|
||||
package com.iluwatar.event.aggregator;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
/**
|
||||
* A system with lots of objects can lead to complexities when a client wants to subscribe to
|
||||
@ -47,19 +48,18 @@ public class App {
|
||||
*/
|
||||
public static void main(String[] args) {
|
||||
|
||||
KingJoffrey kingJoffrey = new KingJoffrey();
|
||||
KingsHand kingsHand = new KingsHand(kingJoffrey);
|
||||
var kingJoffrey = new KingJoffrey();
|
||||
var kingsHand = new KingsHand(kingJoffrey);
|
||||
|
||||
List<EventEmitter> emitters = new ArrayList<>();
|
||||
emitters.add(kingsHand);
|
||||
emitters.add(new LordBaelish(kingsHand));
|
||||
emitters.add(new LordVarys(kingsHand));
|
||||
emitters.add(new Scout(kingsHand));
|
||||
var emitters = List.of(
|
||||
kingsHand,
|
||||
new LordBaelish(kingsHand),
|
||||
new LordVarys(kingsHand),
|
||||
new Scout(kingsHand)
|
||||
);
|
||||
|
||||
for (Weekday day : Weekday.values()) {
|
||||
for (EventEmitter emitter : emitters) {
|
||||
emitter.timePasses(day);
|
||||
}
|
||||
}
|
||||
Arrays.stream(Weekday.values())
|
||||
.<Consumer<? super EventEmitter>>map(day -> emitter -> emitter.timePasses(day))
|
||||
.forEachOrdered(emitters::forEach);
|
||||
}
|
||||
}
|
||||
|
@ -47,9 +47,7 @@ public abstract class EventEmitter {
|
||||
}
|
||||
|
||||
protected void notifyObservers(Event e) {
|
||||
for (EventObserver obs : observers) {
|
||||
obs.onEvent(e);
|
||||
}
|
||||
observers.forEach(obs -> obs.onEvent(e));
|
||||
}
|
||||
|
||||
public abstract void timePasses(Weekday day);
|
||||
|
@ -37,7 +37,7 @@ public class LordBaelish extends EventEmitter {
|
||||
|
||||
@Override
|
||||
public void timePasses(Weekday day) {
|
||||
if (day.equals(Weekday.FRIDAY)) {
|
||||
if (day == Weekday.FRIDAY) {
|
||||
notifyObservers(Event.STARK_SIGHTED);
|
||||
}
|
||||
}
|
||||
|
@ -37,7 +37,7 @@ public class LordVarys extends EventEmitter {
|
||||
|
||||
@Override
|
||||
public void timePasses(Weekday day) {
|
||||
if (day.equals(Weekday.SATURDAY)) {
|
||||
if (day == Weekday.SATURDAY) {
|
||||
notifyObservers(Event.TRAITOR_DETECTED);
|
||||
}
|
||||
}
|
||||
|
@ -37,7 +37,7 @@ public class Scout extends EventEmitter {
|
||||
|
||||
@Override
|
||||
public void timePasses(Weekday day) {
|
||||
if (day.equals(Weekday.TUESDAY)) {
|
||||
if (day == Weekday.TUESDAY) {
|
||||
notifyObservers(Event.WARSHIPS_APPROACHING);
|
||||
}
|
||||
}
|
||||
|
@ -28,8 +28,13 @@ package com.iluwatar.event.aggregator;
|
||||
*/
|
||||
public enum Weekday {
|
||||
|
||||
MONDAY("Monday"), TUESDAY("Tuesday"), WEDNESDAY("Wednesday"), THURSDAY("Thursday"), FRIDAY(
|
||||
"Friday"), SATURDAY("Saturday"), SUNDAY("Sunday");
|
||||
MONDAY("Monday"),
|
||||
TUESDAY("Tuesday"),
|
||||
WEDNESDAY("Wednesday"),
|
||||
THURSDAY("Thursday"),
|
||||
FRIDAY("Friday"),
|
||||
SATURDAY("Saturday"),
|
||||
SUNDAY("Sunday");
|
||||
|
||||
private String description;
|
||||
|
||||
|
@ -26,15 +26,12 @@ package com.iluwatar.event.aggregator;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
*
|
||||
* Application test
|
||||
*
|
||||
*/
|
||||
public class AppTest {
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
String[] args = {};
|
||||
App.main(args);
|
||||
App.main(new String[]{});
|
||||
}
|
||||
}
|
||||
|
@ -23,8 +23,6 @@
|
||||
|
||||
package com.iluwatar.event.aggregator;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.mockito.Matchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.times;
|
||||
@ -35,10 +33,11 @@ import static org.mockito.Mockito.verifyZeroInteractions;
|
||||
import java.util.Objects;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Supplier;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* Date: 12/12/15 - 10:58 PM
|
||||
* Tests for Event Emitter
|
||||
* Date: 12/12/15 - 10:58 PM Tests for Event Emitter
|
||||
*
|
||||
* @param <E> Type of Event Emitter
|
||||
* @author Jeroen Meulemeester
|
||||
*/
|
||||
@ -99,13 +98,13 @@ public abstract class EventEmitterTest<E extends EventEmitter> {
|
||||
private void testAllDays(final Weekday specialDay, final Event event, final E emitter,
|
||||
final EventObserver... observers) {
|
||||
|
||||
for (final Weekday weekday : Weekday.values()) {
|
||||
for (final var weekday : Weekday.values()) {
|
||||
// Pass each week of the day, day by day to the event emitter
|
||||
emitter.timePasses(weekday);
|
||||
|
||||
if (weekday == specialDay) {
|
||||
// On a special day, every observer should have received the event
|
||||
for (final EventObserver observer : observers) {
|
||||
for (final var observer : observers) {
|
||||
verify(observer, times(1)).onEvent(eq(event));
|
||||
}
|
||||
} else {
|
||||
@ -126,10 +125,10 @@ public abstract class EventEmitterTest<E extends EventEmitter> {
|
||||
* @param event The expected event emitted by the test object
|
||||
*/
|
||||
private void testAllDaysWithoutDefaultObserver(final Weekday specialDay, final Event event) {
|
||||
final EventObserver observer1 = mock(EventObserver.class);
|
||||
final EventObserver observer2 = mock(EventObserver.class);
|
||||
final var observer1 = mock(EventObserver.class);
|
||||
final var observer2 = mock(EventObserver.class);
|
||||
|
||||
final E emitter = this.factoryWithoutDefaultObserver.get();
|
||||
final var emitter = this.factoryWithoutDefaultObserver.get();
|
||||
emitter.registerObserver(observer1);
|
||||
emitter.registerObserver(observer2);
|
||||
|
||||
@ -143,11 +142,11 @@ public abstract class EventEmitterTest<E extends EventEmitter> {
|
||||
* @param event The expected event emitted by the test object
|
||||
*/
|
||||
private void testAllDaysWithDefaultObserver(final Weekday specialDay, final Event event) {
|
||||
final EventObserver defaultObserver = mock(EventObserver.class);
|
||||
final EventObserver observer1 = mock(EventObserver.class);
|
||||
final EventObserver observer2 = mock(EventObserver.class);
|
||||
final var defaultObserver = mock(EventObserver.class);
|
||||
final var observer1 = mock(EventObserver.class);
|
||||
final var observer2 = mock(EventObserver.class);
|
||||
|
||||
final E emitter = this.factoryWithDefaultObserver.apply(defaultObserver);
|
||||
final var emitter = this.factoryWithDefaultObserver.apply(defaultObserver);
|
||||
emitter.registerObserver(observer1);
|
||||
emitter.registerObserver(observer2);
|
||||
|
||||
|
@ -23,11 +23,12 @@
|
||||
|
||||
package com.iluwatar.event.aggregator;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
|
||||
import java.util.Arrays;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* Date: 12/12/15 - 2:52 PM
|
||||
*
|
||||
@ -40,11 +41,10 @@ public class EventTest {
|
||||
*/
|
||||
@Test
|
||||
public void testToString() {
|
||||
for (final Event event : Event.values()) {
|
||||
final String toString = event.toString();
|
||||
Arrays.stream(Event.values()).map(Event::toString).forEach(toString -> {
|
||||
assertNotNull(toString);
|
||||
assertFalse(toString.trim().isEmpty());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
}
|
@ -23,19 +23,19 @@
|
||||
|
||||
package com.iluwatar.event.aggregator;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
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.stream.IntStream;
|
||||
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;
|
||||
|
||||
/**
|
||||
* Date: 12/12/15 - 3:04 PM
|
||||
*
|
||||
@ -60,17 +60,16 @@ public class KingJoffreyTest {
|
||||
*/
|
||||
@Test
|
||||
public void testOnEvent() {
|
||||
final KingJoffrey kingJoffrey = new KingJoffrey();
|
||||
final var kingJoffrey = new KingJoffrey();
|
||||
|
||||
for (int i = 0; i < Event.values().length; ++i) {
|
||||
IntStream.range(0, Event.values().length).forEach(i -> {
|
||||
assertEquals(i, appender.getLogSize());
|
||||
Event event = Event.values()[i];
|
||||
var event = Event.values()[i];
|
||||
kingJoffrey.onEvent(event);
|
||||
|
||||
final String expectedMessage = "Received event from the King's Hand: " + event.toString();
|
||||
final var expectedMessage = "Received event from the King's Hand: " + event.toString();
|
||||
assertEquals(expectedMessage, appender.getLastMessage());
|
||||
assertEquals(i + 1, appender.getLogSize());
|
||||
}
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
|
@ -23,14 +23,15 @@
|
||||
|
||||
package com.iluwatar.event.aggregator;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.mockito.Matchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyZeroInteractions;
|
||||
import static org.mockito.Mockito.verifyNoMoreInteractions;
|
||||
import static org.mockito.Mockito.verifyZeroInteractions;
|
||||
|
||||
import java.util.Arrays;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* Date: 12/12/15 - 10:57 AM
|
||||
@ -47,24 +48,24 @@ public class KingsHandTest extends EventEmitterTest<KingsHand> {
|
||||
}
|
||||
|
||||
/**
|
||||
* The {@link KingsHand} is both an {@link EventEmitter} as an {@link EventObserver} so verify if every
|
||||
* event received is passed up to it's superior, in most cases {@link KingJoffrey} but now just a
|
||||
* mocked observer.
|
||||
* The {@link KingsHand} is both an {@link EventEmitter} as an {@link EventObserver} so verify if
|
||||
* every event received is passed up to it's superior, in most cases {@link KingJoffrey} but now
|
||||
* just a mocked observer.
|
||||
*/
|
||||
@Test
|
||||
public void testPassThrough() throws Exception {
|
||||
final EventObserver observer = mock(EventObserver.class);
|
||||
final KingsHand kingsHand = new KingsHand(observer);
|
||||
final var observer = mock(EventObserver.class);
|
||||
final var kingsHand = new KingsHand(observer);
|
||||
|
||||
// The kings hand should not pass any events before he received one
|
||||
verifyZeroInteractions(observer);
|
||||
|
||||
// Verify if each event is passed on to the observer, nothing less, nothing more.
|
||||
for (final Event event : Event.values()) {
|
||||
Arrays.stream(Event.values()).forEach(event -> {
|
||||
kingsHand.onEvent(event);
|
||||
verify(observer, times(1)).onEvent(eq(event));
|
||||
verifyNoMoreInteractions(observer);
|
||||
}
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
|
@ -23,11 +23,12 @@
|
||||
|
||||
package com.iluwatar.event.aggregator;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
|
||||
import java.util.Arrays;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* Date: 12/12/15 - 2:12 PM
|
||||
*
|
||||
@ -37,11 +38,11 @@ public class WeekdayTest {
|
||||
|
||||
@Test
|
||||
public void testToString() {
|
||||
for (final Weekday weekday : Weekday.values()) {
|
||||
Arrays.stream(Weekday.values()).forEach(weekday -> {
|
||||
final String toString = weekday.toString();
|
||||
assertNotNull(toString);
|
||||
assertEquals(weekday.name(), toString.toUpperCase());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
}
|
@ -24,7 +24,6 @@
|
||||
package com.iluwatar.event.asynchronous;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.Properties;
|
||||
import java.util.Scanner;
|
||||
import org.slf4j.Logger;
|
||||
@ -70,8 +69,7 @@ public class App {
|
||||
* @param args command line args
|
||||
*/
|
||||
public static void main(String[] args) {
|
||||
App app = new App();
|
||||
|
||||
var app = new App();
|
||||
app.setUp();
|
||||
app.run();
|
||||
}
|
||||
@ -82,9 +80,9 @@ public class App {
|
||||
* operations.
|
||||
*/
|
||||
public void setUp() {
|
||||
Properties prop = new Properties();
|
||||
var prop = new Properties();
|
||||
|
||||
InputStream inputStream = App.class.getClassLoader().getResourceAsStream(PROP_FILE_NAME);
|
||||
var inputStream = App.class.getClassLoader().getResourceAsStream(PROP_FILE_NAME);
|
||||
|
||||
if (inputStream != null) {
|
||||
try {
|
||||
@ -92,7 +90,7 @@ public class App {
|
||||
} catch (IOException e) {
|
||||
LOGGER.error("{} was not found. Defaulting to non-interactive mode.", PROP_FILE_NAME, e);
|
||||
}
|
||||
String property = prop.getProperty("INTERACTIVE_MODE");
|
||||
var property = prop.getProperty("INTERACTIVE_MODE");
|
||||
if (property.equalsIgnoreCase("YES")) {
|
||||
interactiveMode = true;
|
||||
}
|
||||
@ -114,17 +112,17 @@ public class App {
|
||||
* Run program in non-interactive mode.
|
||||
*/
|
||||
public void quickRun() {
|
||||
EventManager eventManager = new EventManager();
|
||||
var eventManager = new EventManager();
|
||||
|
||||
try {
|
||||
// Create an Asynchronous event.
|
||||
int asyncEventId = eventManager.createAsync(60);
|
||||
var asyncEventId = eventManager.createAsync(60);
|
||||
LOGGER.info("Async Event [{}] has been created.", asyncEventId);
|
||||
eventManager.start(asyncEventId);
|
||||
LOGGER.info("Async Event [{}] has been started.", asyncEventId);
|
||||
|
||||
// Create a Synchronous event.
|
||||
int syncEventId = eventManager.create(60);
|
||||
var syncEventId = eventManager.create(60);
|
||||
LOGGER.info("Sync Event [{}] has been created.", syncEventId);
|
||||
eventManager.start(syncEventId);
|
||||
LOGGER.info("Sync Event [{}] has been started.", syncEventId);
|
||||
@ -147,10 +145,10 @@ public class App {
|
||||
* Run program in interactive mode.
|
||||
*/
|
||||
public void runInteractiveMode() {
|
||||
EventManager eventManager = new EventManager();
|
||||
var eventManager = new EventManager();
|
||||
|
||||
Scanner s = new Scanner(System.in);
|
||||
int option = -1;
|
||||
var s = new Scanner(System.in);
|
||||
var option = -1;
|
||||
while (option != 4) {
|
||||
LOGGER.info("Hello. Would you like to boil some eggs?");
|
||||
LOGGER.info("(1) BOIL AN EGG \n(2) STOP BOILING THIS EGG \n(3) HOW ARE MY EGGS? \n(4) EXIT");
|
||||
@ -174,7 +172,7 @@ public class App {
|
||||
private void processOption3(EventManager eventManager, Scanner s) {
|
||||
s.nextLine();
|
||||
LOGGER.info("Just one egg (O) OR all of them (A) ?: ");
|
||||
String eggChoice = s.nextLine();
|
||||
var eggChoice = s.nextLine();
|
||||
|
||||
if (eggChoice.equalsIgnoreCase("O")) {
|
||||
LOGGER.info("Which egg?: ");
|
||||
@ -191,7 +189,7 @@ public class App {
|
||||
|
||||
private void processOption2(EventManager eventManager, Scanner s) {
|
||||
LOGGER.info("Which egg?: ");
|
||||
int eventId = s.nextInt();
|
||||
var eventId = s.nextInt();
|
||||
try {
|
||||
eventManager.cancel(eventId);
|
||||
LOGGER.info("Egg [{}] is removed from boiler.", eventId);
|
||||
@ -203,12 +201,12 @@ public class App {
|
||||
private void processOption1(EventManager eventManager, Scanner s) {
|
||||
s.nextLine();
|
||||
LOGGER.info("Boil multiple eggs at once (A) or boil them one-by-one (S)?: ");
|
||||
String eventType = s.nextLine();
|
||||
var eventType = s.nextLine();
|
||||
LOGGER.info("How long should this egg be boiled for (in seconds)?: ");
|
||||
int eventTime = s.nextInt();
|
||||
var eventTime = s.nextInt();
|
||||
if (eventType.equalsIgnoreCase("A")) {
|
||||
try {
|
||||
int eventId = eventManager.createAsync(eventTime);
|
||||
var eventId = eventManager.createAsync(eventTime);
|
||||
eventManager.start(eventId);
|
||||
LOGGER.info("Egg [{}] is being boiled.", eventId);
|
||||
} catch (MaxNumOfEventsAllowedException | LongRunningEventException
|
||||
@ -217,7 +215,7 @@ public class App {
|
||||
}
|
||||
} else if (eventType.equalsIgnoreCase("S")) {
|
||||
try {
|
||||
int eventId = eventManager.create(eventTime);
|
||||
var eventId = eventManager.create(eventTime);
|
||||
eventManager.start(eventId);
|
||||
LOGGER.info("Egg [{}] is being boiled.", eventId);
|
||||
} catch (MaxNumOfEventsAllowedException | InvalidOperationException
|
||||
|
@ -82,8 +82,8 @@ public class Event implements IEvent, Runnable {
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
long currentTime = System.currentTimeMillis();
|
||||
long endTime = currentTime + (eventTime * 1000);
|
||||
var currentTime = System.currentTimeMillis();
|
||||
var endTime = currentTime + (eventTime * 1000);
|
||||
while (System.currentTimeMillis() < endTime) {
|
||||
try {
|
||||
Thread.sleep(1000); // Sleep for 1 second.
|
||||
|
@ -23,7 +23,6 @@
|
||||
|
||||
package com.iluwatar.event.asynchronous;
|
||||
|
||||
import java.util.Iterator;
|
||||
import java.util.Map;
|
||||
import java.util.Random;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
@ -75,7 +74,7 @@ public class EventManager implements ThreadCompleteListener {
|
||||
+ " running. Please wait until it finishes and try again.");
|
||||
}
|
||||
|
||||
int eventId = createEvent(eventTime, true);
|
||||
var eventId = createEvent(eventTime, true);
|
||||
currentlyRunningSyncEvent = eventId;
|
||||
|
||||
return eventId;
|
||||
@ -106,9 +105,9 @@ public class EventManager implements ThreadCompleteListener {
|
||||
"Maximum event time allowed is " + MAX_EVENT_TIME + " seconds. Please try again.");
|
||||
}
|
||||
|
||||
int newEventId = generateId();
|
||||
var newEventId = generateId();
|
||||
|
||||
Event newEvent = new Event(newEventId, eventTime, isSynchronous);
|
||||
var newEvent = new Event(newEventId, eventTime, isSynchronous);
|
||||
newEvent.addListener(this);
|
||||
eventPool.put(newEventId, newEvent);
|
||||
|
||||
@ -167,11 +166,7 @@ public class EventManager implements ThreadCompleteListener {
|
||||
*/
|
||||
@SuppressWarnings("rawtypes")
|
||||
public void statusOfAllEvents() {
|
||||
Iterator it = eventPool.entrySet().iterator();
|
||||
while (it.hasNext()) {
|
||||
Map.Entry pair = (Map.Entry) it.next();
|
||||
((Event) pair.getValue()).status();
|
||||
}
|
||||
eventPool.entrySet().forEach(entry -> ((Event) ((Map.Entry) entry).getValue()).status());
|
||||
}
|
||||
|
||||
/**
|
||||
@ -179,11 +174,7 @@ public class EventManager implements ThreadCompleteListener {
|
||||
*/
|
||||
@SuppressWarnings("rawtypes")
|
||||
public void shutdown() {
|
||||
Iterator it = eventPool.entrySet().iterator();
|
||||
while (it.hasNext()) {
|
||||
Map.Entry pair = (Map.Entry) it.next();
|
||||
((Event) pair.getValue()).stop();
|
||||
}
|
||||
eventPool.entrySet().forEach(entry -> ((Event) ((Map.Entry) entry).getValue()).stop());
|
||||
}
|
||||
|
||||
/**
|
||||
@ -194,7 +185,7 @@ public class EventManager implements ThreadCompleteListener {
|
||||
private int generateId() {
|
||||
// nextInt is normally exclusive of the top value,
|
||||
// so add 1 to make it inclusive
|
||||
int randomNum = rand.nextInt((MAX_ID - MIN_ID) + 1) + MIN_ID;
|
||||
var randomNum = rand.nextInt((MAX_ID - MIN_ID) + 1) + MIN_ID;
|
||||
while (eventPool.containsKey(randomNum)) {
|
||||
randomNum = rand.nextInt((MAX_ID - MIN_ID) + 1) + MIN_ID;
|
||||
}
|
||||
|
@ -25,15 +25,12 @@ package com.iluwatar.event.asynchronous;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* Tests that EventAsynchronous example runs without errors.
|
||||
*/
|
||||
public class AppTest {
|
||||
@Test
|
||||
public void test() throws IOException {
|
||||
String[] args = {};
|
||||
App.main(args);
|
||||
public void test() {
|
||||
App.main(new String[]{});
|
||||
}
|
||||
}
|
||||
|
@ -23,28 +23,26 @@
|
||||
|
||||
package com.iluwatar.event.asynchronous;
|
||||
|
||||
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.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
*
|
||||
* Application test
|
||||
*
|
||||
*/
|
||||
public class EventAsynchronousTest {
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(EventAsynchronousTest.class);
|
||||
|
||||
@Test
|
||||
public void testAsynchronousEvent() {
|
||||
EventManager eventManager = new EventManager();
|
||||
var eventManager = new EventManager();
|
||||
try {
|
||||
int aEventId = eventManager.createAsync(60);
|
||||
var aEventId = eventManager.createAsync(60);
|
||||
eventManager.start(aEventId);
|
||||
assertEquals(1, eventManager.getEventPool().size());
|
||||
assertTrue(eventManager.getEventPool().size() < EventManager.MAX_RUNNING_EVENTS);
|
||||
@ -58,9 +56,9 @@ public class EventAsynchronousTest {
|
||||
|
||||
@Test
|
||||
public void testSynchronousEvent() {
|
||||
EventManager eventManager = new EventManager();
|
||||
var eventManager = new EventManager();
|
||||
try {
|
||||
int sEventId = eventManager.create(60);
|
||||
var sEventId = eventManager.create(60);
|
||||
eventManager.start(sEventId);
|
||||
assertEquals(1, eventManager.getEventPool().size());
|
||||
assertTrue(eventManager.getEventPool().size() < EventManager.MAX_RUNNING_EVENTS);
|
||||
@ -76,9 +74,9 @@ public class EventAsynchronousTest {
|
||||
@Test
|
||||
public void testUnsuccessfulSynchronousEvent() {
|
||||
assertThrows(InvalidOperationException.class, () -> {
|
||||
EventManager eventManager = new EventManager();
|
||||
var eventManager = new EventManager();
|
||||
try {
|
||||
int sEventId = eventManager.create(60);
|
||||
var sEventId = eventManager.create(60);
|
||||
eventManager.start(sEventId);
|
||||
sEventId = eventManager.create(60);
|
||||
eventManager.start(sEventId);
|
||||
@ -90,20 +88,18 @@ public class EventAsynchronousTest {
|
||||
|
||||
@Test
|
||||
public void testFullSynchronousEvent() {
|
||||
EventManager eventManager = new EventManager();
|
||||
var eventManager = new EventManager();
|
||||
try {
|
||||
int eventTime = 1;
|
||||
var eventTime = 1;
|
||||
|
||||
int sEventId = eventManager.create(eventTime);
|
||||
var sEventId = eventManager.create(eventTime);
|
||||
assertEquals(1, eventManager.getEventPool().size());
|
||||
eventManager.start(sEventId);
|
||||
|
||||
long currentTime = System.currentTimeMillis();
|
||||
long endTime = currentTime + (eventTime + 2 * 1000); // +2 to give a bit of buffer time for event to
|
||||
// complete
|
||||
// properly.
|
||||
while (System.currentTimeMillis() < endTime) {
|
||||
}
|
||||
var currentTime = System.currentTimeMillis();
|
||||
// +2 to give a bit of buffer time for event to complete properly.
|
||||
var endTime = currentTime + (eventTime + 2 * 1000);
|
||||
while (System.currentTimeMillis() < endTime) ;
|
||||
|
||||
assertTrue(eventManager.getEventPool().isEmpty());
|
||||
|
||||
@ -115,24 +111,23 @@ public class EventAsynchronousTest {
|
||||
|
||||
@Test
|
||||
public void testFullAsynchronousEvent() {
|
||||
EventManager eventManager = new EventManager();
|
||||
var eventManager = new EventManager();
|
||||
try {
|
||||
int eventTime = 1;
|
||||
var eventTime = 1;
|
||||
|
||||
int aEventId1 = eventManager.createAsync(eventTime);
|
||||
int aEventId2 = eventManager.createAsync(eventTime);
|
||||
int aEventId3 = eventManager.createAsync(eventTime);
|
||||
var aEventId1 = eventManager.createAsync(eventTime);
|
||||
var aEventId2 = eventManager.createAsync(eventTime);
|
||||
var aEventId3 = eventManager.createAsync(eventTime);
|
||||
assertEquals(3, eventManager.getEventPool().size());
|
||||
|
||||
eventManager.start(aEventId1);
|
||||
eventManager.start(aEventId2);
|
||||
eventManager.start(aEventId3);
|
||||
|
||||
long currentTime = System.currentTimeMillis();
|
||||
long endTime = currentTime + (eventTime + 2 * 1000); // +2 to give a bit of buffer time for event to complete
|
||||
// properly.
|
||||
while (System.currentTimeMillis() < endTime) {
|
||||
}
|
||||
var currentTime = System.currentTimeMillis();
|
||||
// +2 to give a bit of buffer time for event to complete properly.
|
||||
var endTime = currentTime + (eventTime + 2 * 1000);
|
||||
while (System.currentTimeMillis() < endTime) ;
|
||||
|
||||
assertTrue(eventManager.getEventPool().isEmpty());
|
||||
|
||||
|
@ -52,11 +52,11 @@ public class App {
|
||||
*/
|
||||
public static void main(String[] args) {
|
||||
|
||||
EventDispatcher dispatcher = new EventDispatcher();
|
||||
var dispatcher = new EventDispatcher();
|
||||
dispatcher.registerHandler(UserCreatedEvent.class, new UserCreatedEventHandler());
|
||||
dispatcher.registerHandler(UserUpdatedEvent.class, new UserUpdatedEventHandler());
|
||||
|
||||
User user = new User("iluwatar");
|
||||
var user = new User("iluwatar");
|
||||
dispatcher.dispatch(new UserCreatedEvent(user));
|
||||
dispatcher.dispatch(new UserUpdatedEvent(user));
|
||||
}
|
||||
|
@ -44,8 +44,10 @@ public class EventDispatcher {
|
||||
* @param eventType The {@link Event} to be registered
|
||||
* @param handler The {@link Handler} that will be handling the {@link Event}
|
||||
*/
|
||||
public <E extends Event> void registerHandler(Class<E> eventType,
|
||||
Handler<E> handler) {
|
||||
public <E extends Event> void registerHandler(
|
||||
Class<E> eventType,
|
||||
Handler<E> handler
|
||||
) {
|
||||
handlers.put(eventType, handler);
|
||||
}
|
||||
|
||||
@ -56,7 +58,7 @@ public class EventDispatcher {
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public <E extends Event> void dispatch(E event) {
|
||||
Handler<E> handler = (Handler<E>) handlers.get(event.getClass());
|
||||
var handler = (Handler<E>) handlers.get(event.getClass());
|
||||
if (handler != null) {
|
||||
handler.onEvent(event);
|
||||
}
|
||||
|
@ -25,15 +25,12 @@ package com.iluwatar.eda;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* Tests that Event Driven Architecture example runs without errors.
|
||||
*/
|
||||
public class AppTest {
|
||||
@Test
|
||||
public void test() throws IOException {
|
||||
String[] args = {};
|
||||
App.main(args);
|
||||
public void test() {
|
||||
App.main(new String[]{});
|
||||
}
|
||||
}
|
||||
|
@ -23,11 +23,11 @@
|
||||
|
||||
package com.iluwatar.eda.event;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import com.iluwatar.eda.model.User;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
/**
|
||||
* {@link UserCreatedEventTest} tests and verifies {@link AbstractEvent} behaviour.
|
||||
*/
|
||||
@ -39,8 +39,8 @@ public class UserCreatedEventTest {
|
||||
*/
|
||||
@Test
|
||||
public void testGetEventType() {
|
||||
User user = new User("iluwatar");
|
||||
UserCreatedEvent userCreatedEvent = new UserCreatedEvent(user);
|
||||
var user = new User("iluwatar");
|
||||
var userCreatedEvent = new UserCreatedEvent(user);
|
||||
assertEquals(UserCreatedEvent.class, userCreatedEvent.getType());
|
||||
}
|
||||
}
|
||||
|
@ -23,6 +23,9 @@
|
||||
|
||||
package com.iluwatar.eda.framework;
|
||||
|
||||
import static org.mockito.Mockito.spy;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
import com.iluwatar.eda.event.UserCreatedEvent;
|
||||
import com.iluwatar.eda.event.UserUpdatedEvent;
|
||||
import com.iluwatar.eda.handler.UserCreatedEventHandler;
|
||||
@ -30,9 +33,6 @@ import com.iluwatar.eda.handler.UserUpdatedEventHandler;
|
||||
import com.iluwatar.eda.model.User;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.mockito.Mockito.spy;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
/**
|
||||
* Event Dispatcher unit tests to assert and verify correct event dispatcher behaviour
|
||||
*/
|
||||
@ -45,16 +45,16 @@ public class EventDispatcherTest {
|
||||
@Test
|
||||
public void testEventDriverPattern() {
|
||||
|
||||
EventDispatcher dispatcher = spy(new EventDispatcher());
|
||||
UserCreatedEventHandler userCreatedEventHandler = spy(new UserCreatedEventHandler());
|
||||
UserUpdatedEventHandler userUpdatedEventHandler = spy(new UserUpdatedEventHandler());
|
||||
var dispatcher = spy(new EventDispatcher());
|
||||
var userCreatedEventHandler = spy(new UserCreatedEventHandler());
|
||||
var userUpdatedEventHandler = spy(new UserUpdatedEventHandler());
|
||||
dispatcher.registerHandler(UserCreatedEvent.class, userCreatedEventHandler);
|
||||
dispatcher.registerHandler(UserUpdatedEvent.class, userUpdatedEventHandler);
|
||||
|
||||
User user = new User("iluwatar");
|
||||
var user = new User("iluwatar");
|
||||
|
||||
UserCreatedEvent userCreatedEvent = new UserCreatedEvent(user);
|
||||
UserUpdatedEvent userUpdatedEvent = new UserUpdatedEvent(user);
|
||||
var userCreatedEvent = new UserCreatedEvent(user);
|
||||
var userUpdatedEvent = new UserUpdatedEvent(user);
|
||||
|
||||
//fire a userCreatedEvent and verify that userCreatedEventHandler has been invoked.
|
||||
dispatcher.dispatch(userCreatedEvent);
|
||||
|
@ -53,12 +53,12 @@ public class App {
|
||||
*/
|
||||
public static void main(String[] args) throws UnsupportedAudioFileException, IOException,
|
||||
InterruptedException {
|
||||
Audio audio = Audio.getInstance();
|
||||
var audio = Audio.getInstance();
|
||||
audio.playSound(audio.getAudioStream("./etc/Bass-Drum-1.wav"), -10.0f);
|
||||
audio.playSound(audio.getAudioStream("./etc/Closed-Hi-Hat-1.wav"), -8.0f);
|
||||
|
||||
LOGGER.info("Press Enter key to stop the program...");
|
||||
try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
|
||||
try (var br = new BufferedReader(new InputStreamReader(System.in))) {
|
||||
br.read();
|
||||
}
|
||||
audio.stopService();
|
||||
|
@ -27,7 +27,6 @@ import java.io.File;
|
||||
import java.io.IOException;
|
||||
import javax.sound.sampled.AudioInputStream;
|
||||
import javax.sound.sampled.AudioSystem;
|
||||
import javax.sound.sampled.Clip;
|
||||
import javax.sound.sampled.LineUnavailableException;
|
||||
import javax.sound.sampled.UnsupportedAudioFileException;
|
||||
import org.slf4j.Logger;
|
||||
@ -116,10 +115,11 @@ public class Audio {
|
||||
public void playSound(AudioInputStream stream, float volume) {
|
||||
init();
|
||||
// Walk the pending requests.
|
||||
for (int i = headIndex; i != tailIndex; i = (i + 1) % MAX_PENDING) {
|
||||
if (getPendingAudio()[i].getStream() == stream) {
|
||||
for (var i = headIndex; i != tailIndex; i = (i + 1) % MAX_PENDING) {
|
||||
var playMessage = getPendingAudio()[i];
|
||||
if (playMessage.getStream() == stream) {
|
||||
// Use the larger of the two volumes.
|
||||
getPendingAudio()[i].setVolume(Math.max(volume, getPendingAudio()[i].getVolume()));
|
||||
playMessage.setVolume(Math.max(volume, playMessage.getVolume()));
|
||||
|
||||
// Don't need to enqueue.
|
||||
return;
|
||||
@ -137,11 +137,10 @@ public class Audio {
|
||||
if (headIndex == tailIndex) {
|
||||
return;
|
||||
}
|
||||
Clip clip = null;
|
||||
try {
|
||||
AudioInputStream audioStream = getPendingAudio()[headIndex].getStream();
|
||||
var audioStream = getPendingAudio()[headIndex].getStream();
|
||||
headIndex++;
|
||||
clip = AudioSystem.getClip();
|
||||
var clip = AudioSystem.getClip();
|
||||
clip.open(audioStream);
|
||||
clip.start();
|
||||
} catch (LineUnavailableException e) {
|
||||
|
@ -69,7 +69,7 @@ public class App {
|
||||
*/
|
||||
public static void main(String[] args) {
|
||||
|
||||
DomainEventProcessor eventProcessor = new DomainEventProcessor();
|
||||
var eventProcessor = new DomainEventProcessor();
|
||||
|
||||
|
||||
LOGGER.info("Running the system first time............");
|
||||
|
@ -104,7 +104,7 @@ public class Account {
|
||||
* @return the account
|
||||
*/
|
||||
public Account copy() {
|
||||
Account account = new Account(accountNo, owner);
|
||||
var account = new Account(accountNo, owner);
|
||||
account.setMoney(money);
|
||||
return account;
|
||||
}
|
||||
@ -135,7 +135,7 @@ public class Account {
|
||||
}
|
||||
|
||||
private void handleWithdrawal(BigDecimal money, boolean realTime) {
|
||||
if (this.money.compareTo(money) == -1) {
|
||||
if (this.money.compareTo(money) < 0) {
|
||||
throw new RuntimeException("Insufficient Account Balance");
|
||||
}
|
||||
|
||||
|
@ -72,7 +72,7 @@ public class AccountCreateEvent extends DomainEvent {
|
||||
|
||||
@Override
|
||||
public void process() {
|
||||
Account account = AccountAggregate.getAccount(accountNo);
|
||||
var account = AccountAggregate.getAccount(accountNo);
|
||||
if (account != null) {
|
||||
throw new RuntimeException("Account already exists");
|
||||
}
|
||||
|
@ -23,9 +23,9 @@
|
||||
|
||||
package com.iluwatar.event.sourcing.event;
|
||||
|
||||
import com.iluwatar.event.sourcing.domain.Account;
|
||||
import com.iluwatar.event.sourcing.state.AccountAggregate;
|
||||
import java.math.BigDecimal;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* This is the class that implements money deposit event. Holds the necessary info for a money
|
||||
@ -73,10 +73,8 @@ public class MoneyDepositEvent extends DomainEvent {
|
||||
|
||||
@Override
|
||||
public void process() {
|
||||
Account account = AccountAggregate.getAccount(accountNo);
|
||||
if (account == null) {
|
||||
throw new RuntimeException("Account not found");
|
||||
}
|
||||
var account = Optional.ofNullable(AccountAggregate.getAccount(accountNo))
|
||||
.orElseThrow(() -> new RuntimeException("Account not found"));
|
||||
account.handleEvent(this);
|
||||
}
|
||||
}
|
||||
|
@ -23,9 +23,9 @@
|
||||
|
||||
package com.iluwatar.event.sourcing.event;
|
||||
|
||||
import com.iluwatar.event.sourcing.domain.Account;
|
||||
import com.iluwatar.event.sourcing.state.AccountAggregate;
|
||||
import java.math.BigDecimal;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* This is the class that implements money transfer event. Holds the necessary info for a money
|
||||
@ -86,15 +86,10 @@ public class MoneyTransferEvent extends DomainEvent {
|
||||
|
||||
@Override
|
||||
public void process() {
|
||||
Account accountFrom = AccountAggregate.getAccount(accountNoFrom);
|
||||
if (accountFrom == null) {
|
||||
throw new RuntimeException("Account not found " + accountNoFrom);
|
||||
}
|
||||
Account accountTo = AccountAggregate.getAccount(accountNoTo);
|
||||
if (accountTo == null) {
|
||||
throw new RuntimeException("Account not found " + accountNoTo);
|
||||
}
|
||||
|
||||
var accountFrom = Optional.ofNullable(AccountAggregate.getAccount(accountNoFrom))
|
||||
.orElseThrow(() -> new RuntimeException("Account not found " + accountNoFrom));
|
||||
var accountTo = Optional.ofNullable(AccountAggregate.getAccount(accountNoTo))
|
||||
.orElseThrow(() -> new RuntimeException("Account not found " + accountNoTo));
|
||||
accountFrom.handleTransferFromEvent(this);
|
||||
accountTo.handleTransferToEvent(this);
|
||||
}
|
||||
|
@ -57,13 +57,8 @@ public class DomainEventProcessor {
|
||||
*/
|
||||
public void recover() {
|
||||
DomainEvent domainEvent;
|
||||
while (true) {
|
||||
domainEvent = processorJournal.readNext();
|
||||
if (domainEvent == null) {
|
||||
break;
|
||||
} else {
|
||||
domainEvent.process();
|
||||
}
|
||||
while ((domainEvent = processorJournal.readNext()) != null) {
|
||||
domainEvent.process();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -38,7 +38,7 @@ import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.OutputStreamWriter;
|
||||
import java.io.Writer;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@ -60,8 +60,8 @@ public class JsonFileJournal {
|
||||
public JsonFileJournal() {
|
||||
file = new File("Journal.json");
|
||||
if (file.exists()) {
|
||||
try (BufferedReader input = new BufferedReader(
|
||||
new InputStreamReader(new FileInputStream(file), "UTF-8"))) {
|
||||
try (var input = new BufferedReader(
|
||||
new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8))) {
|
||||
String line;
|
||||
while ((line = input.readLine()) != null) {
|
||||
events.add(line);
|
||||
@ -81,7 +81,7 @@ public class JsonFileJournal {
|
||||
* @param domainEvent the domain event
|
||||
*/
|
||||
public void write(DomainEvent domainEvent) {
|
||||
Gson gson = new Gson();
|
||||
var gson = new Gson();
|
||||
JsonElement jsonElement;
|
||||
if (domainEvent instanceof AccountCreateEvent) {
|
||||
jsonElement = gson.toJsonTree(domainEvent, AccountCreateEvent.class);
|
||||
@ -93,9 +93,9 @@ public class JsonFileJournal {
|
||||
throw new RuntimeException("Journal Event not recegnized");
|
||||
}
|
||||
|
||||
try (Writer output = new BufferedWriter(
|
||||
new OutputStreamWriter(new FileOutputStream(file, true), "UTF-8"))) {
|
||||
String eventString = jsonElement.toString();
|
||||
try (var output = new BufferedWriter(
|
||||
new OutputStreamWriter(new FileOutputStream(file, true), StandardCharsets.UTF_8))) {
|
||||
var eventString = jsonElement.toString();
|
||||
output.write(eventString + "\r\n");
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
@ -120,13 +120,13 @@ public class JsonFileJournal {
|
||||
if (index >= events.size()) {
|
||||
return null;
|
||||
}
|
||||
String event = events.get(index);
|
||||
var event = events.get(index);
|
||||
index++;
|
||||
|
||||
JsonParser parser = new JsonParser();
|
||||
JsonElement jsonElement = parser.parse(event);
|
||||
String eventClassName = jsonElement.getAsJsonObject().get("eventClassName").getAsString();
|
||||
Gson gson = new Gson();
|
||||
var parser = new JsonParser();
|
||||
var jsonElement = parser.parse(event);
|
||||
var eventClassName = jsonElement.getAsJsonObject().get("eventClassName").getAsString();
|
||||
var gson = new Gson();
|
||||
DomainEvent domainEvent;
|
||||
if (eventClassName.equals("AccountCreateEvent")) {
|
||||
domainEvent = gson.fromJson(jsonElement, AccountCreateEvent.class);
|
||||
|
@ -26,6 +26,7 @@ package com.iluwatar.event.sourcing.state;
|
||||
import com.iluwatar.event.sourcing.domain.Account;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* This is the static accounts map holder class. This class holds the state of the accounts.
|
||||
@ -55,11 +56,10 @@ public class AccountAggregate {
|
||||
* @return the copy of the account or null if not found
|
||||
*/
|
||||
public static Account getAccount(int accountNo) {
|
||||
Account account = accounts.get(accountNo);
|
||||
if (account == null) {
|
||||
return null;
|
||||
}
|
||||
return account.copy();
|
||||
return Optional.of(accountNo)
|
||||
.map(accounts::get)
|
||||
.map(Account::copy)
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -21,25 +21,23 @@
|
||||
* THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import com.iluwatar.event.sourcing.domain.Account;
|
||||
import static com.iluwatar.event.sourcing.app.App.ACCOUNT_OF_DAENERYS;
|
||||
import static com.iluwatar.event.sourcing.app.App.ACCOUNT_OF_JON;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import com.iluwatar.event.sourcing.event.AccountCreateEvent;
|
||||
import com.iluwatar.event.sourcing.event.MoneyDepositEvent;
|
||||
import com.iluwatar.event.sourcing.event.MoneyTransferEvent;
|
||||
import com.iluwatar.event.sourcing.processor.DomainEventProcessor;
|
||||
import com.iluwatar.event.sourcing.state.AccountAggregate;
|
||||
import java.math.BigDecimal;
|
||||
import java.util.Date;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.Date;
|
||||
|
||||
import static com.iluwatar.event.sourcing.app.App.ACCOUNT_OF_DAENERYS;
|
||||
import static com.iluwatar.event.sourcing.app.App.ACCOUNT_OF_JON;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
/**
|
||||
* Intergartion Test for Event Sourcing state recovery
|
||||
*
|
||||
* <p>
|
||||
* Created by Serdar Hamzaogullari on 19.08.2017.
|
||||
*/
|
||||
public class IntegrationTest {
|
||||
@ -71,25 +69,25 @@ public class IntegrationTest {
|
||||
1, new Date().getTime(), ACCOUNT_OF_JON, "Jon Snow"));
|
||||
|
||||
eventProcessor.process(new MoneyDepositEvent(
|
||||
2, new Date().getTime(), ACCOUNT_OF_DAENERYS, new BigDecimal("100000")));
|
||||
2, new Date().getTime(), ACCOUNT_OF_DAENERYS, new BigDecimal("100000")));
|
||||
|
||||
eventProcessor.process(new MoneyDepositEvent(
|
||||
3, new Date().getTime(), ACCOUNT_OF_JON, new BigDecimal("100")));
|
||||
3, new Date().getTime(), ACCOUNT_OF_JON, new BigDecimal("100")));
|
||||
|
||||
eventProcessor.process(new MoneyTransferEvent(
|
||||
4, new Date().getTime(), new BigDecimal("10000"), ACCOUNT_OF_DAENERYS,
|
||||
ACCOUNT_OF_JON));
|
||||
|
||||
Account accountOfDaenerysBeforeShotDown = AccountAggregate.getAccount(ACCOUNT_OF_DAENERYS);
|
||||
Account accountOfJonBeforeShotDown = AccountAggregate.getAccount(ACCOUNT_OF_JON);
|
||||
var accountOfDaenerysBeforeShotDown = AccountAggregate.getAccount(ACCOUNT_OF_DAENERYS);
|
||||
var accountOfJonBeforeShotDown = AccountAggregate.getAccount(ACCOUNT_OF_JON);
|
||||
|
||||
AccountAggregate.resetState();
|
||||
|
||||
eventProcessor = new DomainEventProcessor();
|
||||
eventProcessor.recover();
|
||||
|
||||
Account accountOfDaenerysAfterShotDown = AccountAggregate.getAccount(ACCOUNT_OF_DAENERYS);
|
||||
Account accountOfJonAfterShotDown = AccountAggregate.getAccount(ACCOUNT_OF_JON);
|
||||
var accountOfDaenerysAfterShotDown = AccountAggregate.getAccount(ACCOUNT_OF_DAENERYS);
|
||||
var accountOfJonAfterShotDown = AccountAggregate.getAccount(ACCOUNT_OF_JON);
|
||||
|
||||
assertEquals(accountOfDaenerysBeforeShotDown.getMoney(),
|
||||
accountOfDaenerysAfterShotDown.getMoney());
|
||||
|
@ -36,7 +36,7 @@ public class SimpleFileWriter {
|
||||
* Constructor.
|
||||
*/
|
||||
public SimpleFileWriter(String filename, FileWriterAction action) throws IOException {
|
||||
try (FileWriter writer = new FileWriter(filename)) {
|
||||
try (var writer = new FileWriter(filename)) {
|
||||
action.writeFile(writer);
|
||||
}
|
||||
}
|
||||
|
@ -23,30 +23,26 @@
|
||||
|
||||
package com.iluwatar.execute.around;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
*
|
||||
* Tests execute-around example.
|
||||
*
|
||||
*/
|
||||
public class AppTest {
|
||||
|
||||
@Test
|
||||
public void test() throws IOException {
|
||||
String[] args = {};
|
||||
App.main(args);
|
||||
App.main(new String[]{});
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
@AfterEach
|
||||
public void cleanup() {
|
||||
File file = new File("testfile.txt");
|
||||
var file = new File("testfile.txt");
|
||||
file.delete();
|
||||
}
|
||||
}
|
||||
|
@ -23,20 +23,19 @@
|
||||
|
||||
package com.iluwatar.execute.around;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import org.junit.Rule;
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.migrationsupport.rules.EnableRuleMigrationSupport;
|
||||
import org.junit.rules.TemporaryFolder;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* Date: 12/12/15 - 3:21 PM
|
||||
*
|
||||
@ -50,13 +49,13 @@ public class SimpleFileWriterTest {
|
||||
|
||||
@Test
|
||||
public void testWriterNotNull() throws Exception {
|
||||
final File temporaryFile = this.testFolder.newFile();
|
||||
final var temporaryFile = this.testFolder.newFile();
|
||||
new SimpleFileWriter(temporaryFile.getPath(), Assertions::assertNotNull);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCreatesNonExistentFile() throws Exception {
|
||||
final File nonExistingFile = new File(this.testFolder.getRoot(), "non-existing-file");
|
||||
final var nonExistingFile = new File(this.testFolder.getRoot(), "non-existing-file");
|
||||
assertFalse(nonExistingFile.exists());
|
||||
|
||||
new SimpleFileWriter(nonExistingFile.getPath(), Assertions::assertNotNull);
|
||||
@ -65,9 +64,9 @@ public class SimpleFileWriterTest {
|
||||
|
||||
@Test
|
||||
public void testContentsAreWrittenToFile() throws Exception {
|
||||
final String testMessage = "Test message";
|
||||
final var testMessage = "Test message";
|
||||
|
||||
final File temporaryFile = this.testFolder.newFile();
|
||||
final var temporaryFile = this.testFolder.newFile();
|
||||
assertTrue(temporaryFile.exists());
|
||||
|
||||
new SimpleFileWriter(temporaryFile.getPath(), writer -> writer.write(testMessage));
|
||||
@ -76,9 +75,9 @@ public class SimpleFileWriterTest {
|
||||
|
||||
@Test
|
||||
public void testRipplesIoExceptionOccurredWhileWriting() {
|
||||
String message = "Some error";
|
||||
var message = "Some error";
|
||||
assertThrows(IOException.class, () -> {
|
||||
final File temporaryFile = this.testFolder.newFile();
|
||||
final var temporaryFile = this.testFolder.newFile();
|
||||
new SimpleFileWriter(temporaryFile.getPath(), writer -> {
|
||||
throw new IOException(message);
|
||||
});
|
||||
|
@ -24,7 +24,8 @@
|
||||
import abstractextensions.CommanderExtension;
|
||||
import abstractextensions.SergeantExtension;
|
||||
import abstractextensions.SoldierExtension;
|
||||
import org.slf4j.Logger;
|
||||
import java.util.Optional;
|
||||
import java.util.function.Function;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import units.CommanderUnit;
|
||||
import units.SergeantUnit;
|
||||
@ -45,9 +46,9 @@ public class App {
|
||||
public static void main(String[] args) {
|
||||
|
||||
//Create 3 different units
|
||||
Unit soldierUnit = new SoldierUnit("SoldierUnit1");
|
||||
Unit sergeantUnit = new SergeantUnit("SergeantUnit1");
|
||||
Unit commanderUnit = new CommanderUnit("CommanderUnit1");
|
||||
var soldierUnit = new SoldierUnit("SoldierUnit1");
|
||||
var sergeantUnit = new SergeantUnit("SergeantUnit1");
|
||||
var commanderUnit = new CommanderUnit("CommanderUnit1");
|
||||
|
||||
//check for each unit to have an extension
|
||||
checkExtensionsForUnit(soldierUnit);
|
||||
@ -57,32 +58,24 @@ public class App {
|
||||
}
|
||||
|
||||
private static void checkExtensionsForUnit(Unit unit) {
|
||||
final Logger logger = LoggerFactory.getLogger(App.class);
|
||||
final var logger = LoggerFactory.getLogger(App.class);
|
||||
|
||||
SoldierExtension soldierExtension =
|
||||
(SoldierExtension) unit.getUnitExtension("SoldierExtension");
|
||||
SergeantExtension sergeantExtension =
|
||||
(SergeantExtension) unit.getUnitExtension("SergeantExtension");
|
||||
CommanderExtension commanderExtension =
|
||||
(CommanderExtension) unit.getUnitExtension("CommanderExtension");
|
||||
var name = unit.getName();
|
||||
Function<String, Runnable> func = (e) -> () -> logger.info(name + " without " + e);
|
||||
|
||||
//if unit have extension call the method
|
||||
if (soldierExtension != null) {
|
||||
soldierExtension.soldierReady();
|
||||
} else {
|
||||
logger.info(unit.getName() + " without SoldierExtension");
|
||||
}
|
||||
var extension = "SoldierExtension";
|
||||
Optional.ofNullable(unit.getUnitExtension(extension))
|
||||
.map(e -> (SoldierExtension) e)
|
||||
.ifPresentOrElse(SoldierExtension::soldierReady, func.apply(extension));
|
||||
|
||||
if (sergeantExtension != null) {
|
||||
sergeantExtension.sergeantReady();
|
||||
} else {
|
||||
logger.info(unit.getName() + " without SergeantExtension");
|
||||
}
|
||||
extension = "SergeantExtension";
|
||||
Optional.ofNullable(unit.getUnitExtension(extension))
|
||||
.map(e -> (SergeantExtension) e)
|
||||
.ifPresentOrElse(SergeantExtension::sergeantReady, func.apply(extension));
|
||||
|
||||
if (commanderExtension != null) {
|
||||
commanderExtension.commanderReady();
|
||||
} else {
|
||||
logger.info(unit.getName() + " without CommanderExtension");
|
||||
}
|
||||
extension = "CommanderExtension";
|
||||
Optional.ofNullable(unit.getUnitExtension(extension))
|
||||
.map(e -> (CommanderExtension) e)
|
||||
.ifPresentOrElse(CommanderExtension::commanderReady, func.apply(extension));
|
||||
}
|
||||
}
|
||||
|
@ -25,6 +25,7 @@ package units;
|
||||
|
||||
import abstractextensions.UnitExtension;
|
||||
import concreteextensions.Commander;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Class defining CommanderUnit.
|
||||
@ -39,10 +40,7 @@ public class CommanderUnit extends Unit {
|
||||
public UnitExtension getUnitExtension(String extensionName) {
|
||||
|
||||
if (extensionName.equals("CommanderExtension")) {
|
||||
if (unitExtension == null) {
|
||||
unitExtension = new Commander(this);
|
||||
}
|
||||
return unitExtension;
|
||||
return Optional.ofNullable(unitExtension).orElseGet(() -> new Commander(this));
|
||||
}
|
||||
|
||||
return super.getUnitExtension(extensionName);
|
||||
|
@ -25,6 +25,7 @@ package units;
|
||||
|
||||
import abstractextensions.UnitExtension;
|
||||
import concreteextensions.Sergeant;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Class defining SergeantUnit.
|
||||
@ -39,10 +40,7 @@ public class SergeantUnit extends Unit {
|
||||
public UnitExtension getUnitExtension(String extensionName) {
|
||||
|
||||
if (extensionName.equals("SergeantExtension")) {
|
||||
if (unitExtension == null) {
|
||||
unitExtension = new Sergeant(this);
|
||||
}
|
||||
return unitExtension;
|
||||
return Optional.ofNullable(unitExtension).orElseGet(() -> new Sergeant(this));
|
||||
}
|
||||
|
||||
return super.getUnitExtension(extensionName);
|
||||
|
@ -25,6 +25,7 @@ package units;
|
||||
|
||||
import abstractextensions.UnitExtension;
|
||||
import concreteextensions.Soldier;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Class defining SoldierUnit.
|
||||
@ -39,12 +40,9 @@ public class SoldierUnit extends Unit {
|
||||
public UnitExtension getUnitExtension(String extensionName) {
|
||||
|
||||
if (extensionName.equals("SoldierExtension")) {
|
||||
if (unitExtension == null) {
|
||||
unitExtension = new Soldier(this);
|
||||
}
|
||||
|
||||
return unitExtension;
|
||||
return Optional.ofNullable(unitExtension).orElseGet(() -> new Soldier(this));
|
||||
}
|
||||
|
||||
return super.getUnitExtension(extensionName);
|
||||
}
|
||||
}
|
||||
|
@ -28,10 +28,8 @@ import org.junit.jupiter.api.Test;
|
||||
*/
|
||||
public class AppTest {
|
||||
@Test
|
||||
public void main() throws Exception {
|
||||
|
||||
String[] args = {};
|
||||
App.main(args);
|
||||
public void main() {
|
||||
App.main(new String[]{});
|
||||
}
|
||||
|
||||
}
|
@ -32,8 +32,7 @@ import units.CommanderUnit;
|
||||
public class CommanderTest {
|
||||
@Test
|
||||
public void commanderReady() {
|
||||
final Commander commander = new Commander(new CommanderUnit("CommanderUnitTest"));
|
||||
|
||||
final var commander = new Commander(new CommanderUnit("CommanderUnitTest"));
|
||||
commander.commanderReady();
|
||||
}
|
||||
|
||||
|
@ -31,9 +31,8 @@ import units.SergeantUnit;
|
||||
*/
|
||||
public class SergeantTest {
|
||||
@Test
|
||||
public void sergeantReady() throws Exception {
|
||||
final Sergeant sergeant = new Sergeant(new SergeantUnit("SergeantUnitTest"));
|
||||
|
||||
public void sergeantReady() {
|
||||
final var sergeant = new Sergeant(new SergeantUnit("SergeantUnitTest"));
|
||||
sergeant.sergeantReady();
|
||||
}
|
||||
|
||||
|
@ -31,9 +31,8 @@ import units.SoldierUnit;
|
||||
*/
|
||||
public class SoldierTest {
|
||||
@Test
|
||||
public void soldierReady() throws Exception {
|
||||
final Soldier soldier = new Soldier(new SoldierUnit("SoldierUnitTest"));
|
||||
|
||||
public void soldierReady() {
|
||||
final var soldier = new Soldier(new SoldierUnit("SoldierUnitTest"));
|
||||
soldier.soldierReady();
|
||||
}
|
||||
|
||||
|
@ -23,20 +23,18 @@
|
||||
|
||||
package units;
|
||||
|
||||
import abstractextensions.CommanderExtension;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* Created by Srdjan on 03-May-17.
|
||||
*/
|
||||
public class CommanderUnitTest {
|
||||
@Test
|
||||
public void getUnitExtension() {
|
||||
|
||||
final Unit unit = new CommanderUnit("CommanderUnitName");
|
||||
final var unit = new CommanderUnit("CommanderUnitName");
|
||||
|
||||
assertNull(unit.getUnitExtension("SoldierExtension"));
|
||||
assertNull(unit.getUnitExtension("SergeantExtension"));
|
||||
|
@ -23,20 +23,18 @@
|
||||
|
||||
package units;
|
||||
|
||||
import abstractextensions.SergeantExtension;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* Created by Srdjan on 03-May-17.
|
||||
*/
|
||||
public class SergeantUnitTest {
|
||||
@Test
|
||||
public void getUnitExtension() {
|
||||
|
||||
final Unit unit = new SergeantUnit("SergeantUnitName");
|
||||
final var unit = new SergeantUnit("SergeantUnitName");
|
||||
|
||||
assertNull(unit.getUnitExtension("SoldierExtension"));
|
||||
assertNotNull(unit.getUnitExtension("SergeantExtension"));
|
||||
|
@ -23,26 +23,22 @@
|
||||
|
||||
package units;
|
||||
|
||||
import abstractextensions.SoldierExtension;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* Created by Srdjan on 03-May-17.
|
||||
*/
|
||||
public class SoldierUnitTest {
|
||||
@Test
|
||||
public void getUnitExtension() {
|
||||
|
||||
final Unit unit = new SoldierUnit("SoldierUnitName");
|
||||
final var unit = new SoldierUnit("SoldierUnitName");
|
||||
|
||||
assertNotNull(unit.getUnitExtension("SoldierExtension"));
|
||||
assertNull(unit.getUnitExtension("SergeantExtension"));
|
||||
assertNull(unit.getUnitExtension("CommanderExtension"));
|
||||
|
||||
|
||||
}
|
||||
|
||||
}
|
@ -23,11 +23,11 @@
|
||||
|
||||
package units;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* Created by Srdjan on 03-May-17.
|
||||
*/
|
||||
@ -35,11 +35,11 @@ public class UnitTest {
|
||||
|
||||
@Test
|
||||
public void testConstGetSet() throws Exception {
|
||||
final String name = "testName";
|
||||
final Unit unit = new Unit(name);
|
||||
final var name = "testName";
|
||||
final var unit = new Unit(name);
|
||||
assertEquals(name, unit.getName());
|
||||
|
||||
final String newName = "newName";
|
||||
final var newName = "newName";
|
||||
unit.setName(newName);
|
||||
assertEquals(newName, unit.getName());
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user