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