From 7928ac7cfd6df9ca3fb954451e4286e2db68671c Mon Sep 17 00:00:00 2001 From: Miro Wengner Date: Tue, 8 Oct 2024 11:34:00 +0200 Subject: [PATCH] [69] robo4j-socket-http next chunk --- robo4j-hw-rpi/pom.xml | 17 +- robo4j-socket-http/pom.xml | 10 +- .../http/test/json/JsonCodecsTests.java | 53 ++-- .../test/units/HttpServerConfigTests.java | 152 ++++++----- .../http/test/units/HttpServerUnitTests.java | 73 +++--- .../test/units/RoboDatagramClientTest.java | 14 +- .../test/units/RoboDatagramPingPongTest.java | 167 ++++++------ .../RoboHttpClientWithResponseTests.java | 78 +++--- .../http/test/units/RoboHttpDynamicTests.java | 40 +-- .../http/test/units/RoboHttpPingPongTest.java | 206 +++++++-------- .../test/units/RoboHttpUnitGetTestApp.java | 243 +++++++++--------- .../units/config/ServiceContainerUnit.java | 17 +- .../SocketMessageDecoratedProducerUnit.java | 201 +++++++-------- .../test/units/config/StringProducerUnit.java | 77 +++--- 14 files changed, 673 insertions(+), 675 deletions(-) diff --git a/robo4j-hw-rpi/pom.xml b/robo4j-hw-rpi/pom.xml index 68cc1fce..ba4be8c1 100644 --- a/robo4j-hw-rpi/pom.xml +++ b/robo4j-hw-rpi/pom.xml @@ -36,14 +36,6 @@ com.robo4j robo4j-math - - org.slf4j - slf4j-api - - - org.slf4j - slf4j-simple - com.pi4j @@ -60,8 +52,17 @@ pi4j-plugin-linuxfs ${pi4j.version} + + org.slf4j + slf4j-api + + + org.slf4j + slf4j-simple + test + org.junit.jupiter junit-jupiter-engine diff --git a/robo4j-socket-http/pom.xml b/robo4j-socket-http/pom.xml index 0d11661d..3dfbf558 100644 --- a/robo4j-socket-http/pom.xml +++ b/robo4j-socket-http/pom.xml @@ -35,8 +35,16 @@ com.robo4j robo4j-core - + + org.slf4j + slf4j-api + + + org.slf4j + slf4j-simple + test + org.junit.jupiter junit-jupiter-engine diff --git a/robo4j-socket-http/src/test/java/com/robo4j/socket/http/test/json/JsonCodecsTests.java b/robo4j-socket-http/src/test/java/com/robo4j/socket/http/test/json/JsonCodecsTests.java index 15d791c1..b1c7475a 100644 --- a/robo4j-socket-http/src/test/java/com/robo4j/socket/http/test/json/JsonCodecsTests.java +++ b/robo4j-socket-http/src/test/java/com/robo4j/socket/http/test/json/JsonCodecsTests.java @@ -170,40 +170,20 @@ void nestedObjectToJson() { @Test void nestedJsonToObject() { - TestPerson testPerson2 = new TestPerson(); - testPerson2.setName("name2"); - testPerson2.setValue(5); - - TestPerson testPerson111 = new TestPerson(); - testPerson111.setName("name111"); - testPerson111.setValue(42); - - TestPerson testPerson11 = new TestPerson(); - testPerson11.setName("name11"); - testPerson11.setValue(0); - testPerson11.setChild(testPerson111); - - TestPerson testPerson1 = new TestPerson(); - testPerson1.setName("name1"); - testPerson1.setValue(22); - testPerson1.setChild(testPerson11); - - Map personMap = new LinkedHashMap<>(); - personMap.put("person1", testPerson1); - personMap.put("person2", testPerson2); + Map personMap = getStringTestPersonMap(); long start = System.nanoTime(); NSBWithSimpleCollectionsTypesMessage obj1 = collectionsTypesMessageCodec.decode(testJson); TimeUtils.printTimeDiffNano("decodeFromJson", start); + LOGGER.info("Obj: {}", obj1); + assertEquals(Integer.valueOf(42), obj1.getNumber()); assertEquals("no message", obj1.getMessage()); - assertTrue(!obj1.getActive()); + assertFalse(obj1.getActive()); assertArrayEquals(new String[]{"one", "two"}, obj1.getArray()); assertTrue(obj1.getList().containsAll(Arrays.asList("text1", "text2"))); assertEquals(personMap, obj1.getPersonMap()); - - System.out.println("Obj: " + obj1); } @Test @@ -247,4 +227,29 @@ private static void printJson(String resultJson) { LOGGER.debug("resultJson:{}", resultJson); } + private static Map getStringTestPersonMap() { + TestPerson testPerson2 = new TestPerson(); + testPerson2.setName("name2"); + testPerson2.setValue(5); + + TestPerson testPerson111 = new TestPerson(); + testPerson111.setName("name111"); + testPerson111.setValue(42); + + TestPerson testPerson11 = new TestPerson(); + testPerson11.setName("name11"); + testPerson11.setValue(0); + testPerson11.setChild(testPerson111); + + TestPerson testPerson1 = new TestPerson(); + testPerson1.setName("name1"); + testPerson1.setValue(22); + testPerson1.setChild(testPerson11); + + Map personMap = new LinkedHashMap<>(); + personMap.put("person1", testPerson1); + personMap.put("person2", testPerson2); + return personMap; + } + } diff --git a/robo4j-socket-http/src/test/java/com/robo4j/socket/http/test/units/HttpServerConfigTests.java b/robo4j-socket-http/src/test/java/com/robo4j/socket/http/test/units/HttpServerConfigTests.java index 545f8f44..c520c854 100644 --- a/robo4j-socket-http/src/test/java/com/robo4j/socket/http/test/units/HttpServerConfigTests.java +++ b/robo4j-socket-http/src/test/java/com/robo4j/socket/http/test/units/HttpServerConfigTests.java @@ -22,17 +22,13 @@ import com.robo4j.socket.http.util.JsonUtil; import com.robo4j.util.StringConstants; import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.Arrays; import java.util.Collections; -import java.util.List; -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.*; /** * test for Http Server Unit configuration @@ -41,100 +37,96 @@ * @author Miroslav Wengner (@miragemiko) */ class HttpServerConfigTests { + private static final Logger LOGGER = LoggerFactory.getLogger(HttpServerConfigTests.class); - @Test - void serverConfigurationNullTest() { + @Test + void serverConfigurationNullTest() { + Throwable exception = assertThrows(NullPointerException.class, () -> { + HttpPathMethodDTO serverUnitPathDTO = HttpPathUtils.readServerPathDTO(null); + assertNull(serverUnitPathDTO); + }); - Throwable exception = assertThrows(NullPointerException.class, () -> { - HttpPathMethodDTO serverUnitPathDTO = HttpPathUtils.readServerPathDTO(null); - assertNull(serverUnitPathDTO); - }); + assertNotNull(exception.getMessage()); + } - assertNotNull(exception.getMessage()); - } + @Test + void serverConfigurationEmptyTest() { + Throwable exception = assertThrows(ArrayIndexOutOfBoundsException.class, () -> { + HttpPathUtils.readServerPathDTO(StringConstants.EMPTY); + }); - @Test - void serverConfigurationEmptyTest() { - Throwable exception = assertThrows(ArrayIndexOutOfBoundsException.class, () -> { - HttpPathUtils.readServerPathDTO(StringConstants.EMPTY); - }); + assertEquals("Index 0 out of bounds for length 0", exception.getMessage()); + } - assertEquals("Index 0 out of bounds for length 0", exception.getMessage()); - } + @Test + void serverConfigurationWithoutPropertiesDTOTest() { + var configurationJson = "{\"roboUnit\":\"roboUnit1\",\"method\":\"GET\"}"; + var serverUnitPathDTO = HttpPathUtils.readServerPathDTO(configurationJson); - @Test - void serverConfigurationWithoutPropertiesDTOTest() { + LOGGER.info("serverUnitPathDTO: {}", serverUnitPathDTO); + assertEquals("roboUnit1", serverUnitPathDTO.getRoboUnit()); + assertEquals(HttpMethod.GET, serverUnitPathDTO.getMethod()); + assertTrue(serverUnitPathDTO.getCallbacks().isEmpty()); - String configurationJson = "{\"roboUnit\":\"roboUnit1\",\"method\":\"GET\"}"; - HttpPathMethodDTO serverUnitPathDTO = HttpPathUtils.readServerPathDTO(configurationJson); + } - System.out.println("serverUnitPathDTO: " + serverUnitPathDTO); - assertEquals("roboUnit1", serverUnitPathDTO.getRoboUnit()); - assertEquals(HttpMethod.GET, serverUnitPathDTO.getMethod()); - assertTrue(serverUnitPathDTO.getCallbacks().isEmpty()); + @Test + void serverConfigurationWithPropertiesParsingDTOTest() { + var configurationJson = "{\"roboUnit\":\"roboUnit1\",\"method\":\"GET\",\"callbacks\":[\"filter1\",\"filter2\"]}"; + var serverUnitPathDTO = HttpPathUtils.readServerPathDTO(configurationJson); - } + assertEquals("roboUnit1", serverUnitPathDTO.getRoboUnit()); + assertEquals(HttpMethod.GET, serverUnitPathDTO.getMethod()); + assertArrayEquals(Arrays.asList("filter1", "filter2").toArray(), serverUnitPathDTO.getCallbacks().toArray()); + } - @Test - void serverConfigurationWithPropertiesParsingDTOTest() { + @Test + void serverConfigurationNullPathTest() { + var paths = JsonUtil.readPathConfig(HttpPathMethodDTO.class, null); - String configurationJson = "{\"roboUnit\":\"roboUnit1\",\"method\":\"GET\",\"callbacks\":[\"filter1\",\"filter2\"]}"; - HttpPathMethodDTO serverUnitPathDTO = HttpPathUtils.readServerPathDTO(configurationJson); + assertNotNull(paths); + assertTrue(paths.isEmpty()); - assertEquals("roboUnit1", serverUnitPathDTO.getRoboUnit()); - assertEquals(HttpMethod.GET, serverUnitPathDTO.getMethod()); - assertArrayEquals(Arrays.asList("filter1", "filter2").toArray(), serverUnitPathDTO.getCallbacks().toArray()); + } - System.out.println("serverUnitPathDTO: " + serverUnitPathDTO); + @Test + void serverConfigurationEmptyPathTest() { + var paths = JsonUtil.readPathConfig(HttpPathMethodDTO.class, StringConstants.EMPTY); - } + assertNotNull(paths); + assertTrue(paths.isEmpty()); + } - @Test - void serverConfigurationNullPathTest() { - List paths = JsonUtil.readPathConfig(HttpPathMethodDTO.class, null); - assertNotNull(paths); - assertTrue(paths.isEmpty()); + @Test + void serverConfigurationWithMultiplePathsWithoutPropertiesTest() { + var configurationJson = "[{\"roboUnit\":\"roboUnit1\",\"method\":\"GET\"}," + + "{\"roboUnit\":\"roboUnit2\",\"method\":\"POST\"}]"; - } + var expectedPathList = Arrays.asList(new HttpPathMethodDTO("roboUnit1", HttpMethod.GET), + new HttpPathMethodDTO("roboUnit2", HttpMethod.POST)); - @Test - void serverConfigurationEmptyPathTest() { - List paths = JsonUtil.readPathConfig(HttpPathMethodDTO.class, StringConstants.EMPTY); - assertNotNull(paths); - assertTrue(paths.isEmpty()); + var paths = JsonUtil.readPathConfig(HttpPathMethodDTO.class, configurationJson); - } + assertEquals(expectedPathList.size(), paths.size()); + assertArrayEquals(expectedPathList.toArray(), paths.toArray()); + } - @Test - void serverConfigurationWithMultiplePathsWithoutPropertiesTest() { - String configurationJson = "[{\"roboUnit\":\"roboUnit1\",\"method\":\"GET\"}," - + "{\"roboUnit\":\"roboUnit2\",\"method\":\"POST\"}]"; + @Test + void serverConfigurationWithMultiplePathsWithPropertiesTest() { + var configurationJson = "[{\"roboUnit\":\"roboUnit1\",\"method\":\"GET\" , \"callbacks\":[\"filter1\",\"filter2\"]}," + + "{\"roboUnit\":\"roboUnit2\",\"method\":\"POST\"}, {\"roboUnit\":\"roboUnit3\",\"method\":\"GET\",\"callbacks\":[]}]"; - List expectedPathList = Arrays.asList(new HttpPathMethodDTO("roboUnit1", HttpMethod.GET), - new HttpPathMethodDTO("roboUnit2", HttpMethod.POST)); + var expectedPathList = Arrays.asList( + new HttpPathMethodDTO("roboUnit1", HttpMethod.GET, Arrays.asList("filter1", "filter2")), + new HttpPathMethodDTO("roboUnit2", HttpMethod.POST), + new HttpPathMethodDTO("roboUnit3", HttpMethod.GET, Collections.emptyList())); - List paths = JsonUtil.readPathConfig(HttpPathMethodDTO.class, configurationJson); + var paths = JsonUtil.readPathConfig(HttpPathMethodDTO.class, configurationJson); - assertEquals(expectedPathList.size(), paths.size()); - assertArrayEquals(expectedPathList.toArray(), paths.toArray()); - } - - @Test - void serverConfigurationWithMultiplePathsWithPropertiesTest() { - String configurationJson = "[{\"roboUnit\":\"roboUnit1\",\"method\":\"GET\" , \"callbacks\":[\"filter1\",\"filter2\"]}," - + "{\"roboUnit\":\"roboUnit2\",\"method\":\"POST\"}, {\"roboUnit\":\"roboUnit3\",\"method\":\"GET\",\"callbacks\":[]}]"; - - List expectedPathList = Arrays.asList( - new HttpPathMethodDTO("roboUnit1", HttpMethod.GET, Arrays.asList("filter1", "filter2")), - new HttpPathMethodDTO("roboUnit2", HttpMethod.POST), - new HttpPathMethodDTO("roboUnit3", HttpMethod.GET, Collections.emptyList())); - - List paths = JsonUtil.readPathConfig(HttpPathMethodDTO.class, configurationJson); - System.out.println("paths: " + paths); - - assertNotNull(paths); - assertEquals(expectedPathList.size(), paths.size()); - assertArrayEquals(expectedPathList.toArray(), paths.toArray()); - } + LOGGER.info("paths: {}", paths); + assertNotNull(paths); + assertEquals(expectedPathList.size(), paths.size()); + assertArrayEquals(expectedPathList.toArray(), paths.toArray()); + } } diff --git a/robo4j-socket-http/src/test/java/com/robo4j/socket/http/test/units/HttpServerUnitTests.java b/robo4j-socket-http/src/test/java/com/robo4j/socket/http/test/units/HttpServerUnitTests.java index 7a82e34e..b668170e 100644 --- a/robo4j-socket-http/src/test/java/com/robo4j/socket/http/test/units/HttpServerUnitTests.java +++ b/robo4j-socket-http/src/test/java/com/robo4j/socket/http/test/units/HttpServerUnitTests.java @@ -19,13 +19,13 @@ import com.robo4j.LifecycleState; import com.robo4j.RoboBuilder; import com.robo4j.RoboBuilderException; -import com.robo4j.RoboContext; import com.robo4j.RoboReference; -import com.robo4j.configuration.Configuration; import com.robo4j.configuration.ConfigurationBuilder; import com.robo4j.socket.http.units.HttpServerUnit; import com.robo4j.util.SystemUtil; import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import static com.robo4j.socket.http.test.units.HttpUnitTests.CODECS_UNITS_TEST_PACKAGE; import static com.robo4j.socket.http.util.RoboHttpUtils.PROPERTY_CODEC_PACKAGES; @@ -38,50 +38,47 @@ * @author Miroslav Wengner (@miragemiko) */ class HttpServerUnitTests { - private static final int PORT = 9000; - private static final String ID_HTTP_SERVER = "empty_server"; + private static final Logger LOGGER = LoggerFactory.getLogger(HttpServerUnitTests.class); + private static final int PORT = 9000; + private static final String ID_HTTP_SERVER = "empty_server"; - @Test - void httpServerUnitNoCodecsPackageTest() throws Exception { + @Test + void httpServerUnitNoCodecsPackageTest() throws Exception { - Throwable exception = assertThrows(RoboBuilderException.class, () -> { - RoboBuilder builder = new RoboBuilder(); + Throwable exception = assertThrows(RoboBuilderException.class, () -> { + var builder = new RoboBuilder(); + var config = new ConfigurationBuilder().addInteger(PROPERTY_SOCKET_PORT, PORT).build(); + builder.add(HttpServerUnit.class, config, ID_HTTP_SERVER); + var system = builder.build(); - Configuration config = new ConfigurationBuilder().addInteger(PROPERTY_SOCKET_PORT, PORT).build(); - builder.add(HttpServerUnit.class, config, ID_HTTP_SERVER); - RoboContext system = builder.build(); + system.start(); + LOGGER.info(SystemUtil.printStateReport(system)); + var systemReference = system.getReference(ID_HTTP_SERVER); + system.shutdown(); - system.start(); - System.out.println("system: State after start:"); - System.out.println(SystemUtil.printStateReport(system)); - RoboReference systemReference = system.getReference(ID_HTTP_SERVER); - system.shutdown(); - System.out.println("system: State after shutdown:"); - System.out.println(SystemUtil.printStateReport(system)); - assertEquals(LifecycleState.SHUTDOWN, systemReference.getState()); - }); + LOGGER.info(SystemUtil.printStateReport(system)); + assertEquals(LifecycleState.SHUTDOWN, systemReference.getState()); + }); - assertEquals("Error initializing RoboUnit", exception.getMessage()); + assertEquals("Error initializing RoboUnit", exception.getMessage()); - } + } - @Test - void httpServerUnitNoPathTest() throws Exception { - RoboBuilder builder = new RoboBuilder(); + @Test + void httpServerUnitNoPathTest() throws Exception { + var builder = new RoboBuilder(); + var config = new ConfigurationBuilder().addInteger(PROPERTY_SOCKET_PORT, PORT) + .addString(PROPERTY_CODEC_PACKAGES, CODECS_UNITS_TEST_PACKAGE).build(); + builder.add(HttpServerUnit.class, config, ID_HTTP_SERVER); + var system = builder.build(); - Configuration config = new ConfigurationBuilder().addInteger(PROPERTY_SOCKET_PORT, PORT) - .addString(PROPERTY_CODEC_PACKAGES, CODECS_UNITS_TEST_PACKAGE).build(); - builder.add(HttpServerUnit.class, config, ID_HTTP_SERVER); - RoboContext system = builder.build(); + system.start(); + LOGGER.info(SystemUtil.printStateReport(system)); + RoboReference systemReference = system.getReference(ID_HTTP_SERVER); + system.shutdown(); - system.start(); - System.out.println("system: State after start:"); - System.out.println(SystemUtil.printStateReport(system)); - RoboReference systemReference = system.getReference(ID_HTTP_SERVER); - system.shutdown(); - System.out.println("system: State after shutdown:"); - System.out.println(SystemUtil.printStateReport(system)); - assertEquals(LifecycleState.SHUTDOWN, systemReference.getState()); - } + LOGGER.info(SystemUtil.printStateReport(system)); + assertEquals(LifecycleState.SHUTDOWN, systemReference.getState()); + } } diff --git a/robo4j-socket-http/src/test/java/com/robo4j/socket/http/test/units/RoboDatagramClientTest.java b/robo4j-socket-http/src/test/java/com/robo4j/socket/http/test/units/RoboDatagramClientTest.java index fefbbe78..2d81c632 100644 --- a/robo4j-socket-http/src/test/java/com/robo4j/socket/http/test/units/RoboDatagramClientTest.java +++ b/robo4j-socket-http/src/test/java/com/robo4j/socket/http/test/units/RoboDatagramClientTest.java @@ -22,6 +22,8 @@ import com.robo4j.util.SystemUtil; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; @@ -35,6 +37,7 @@ * @author Miroslav Wengner (@miragemiko) */ class RoboDatagramClientTest { + private static final Logger LOGGER = LoggerFactory.getLogger(RoboDatagramClientTest.class); private static final int TIMEOUT = 10; private static final TimeUnit TIME_UNIT = TimeUnit.HOURS; private static final int MAX_NUMBER = 42; @@ -44,17 +47,14 @@ class RoboDatagramClientTest { @Test void datagramClientServerTest() throws Exception { - RoboContext producerSystem = RoboContextUtils.loadRoboContextByXml("robo_datagram_client_request_producer_text.xml"); - RoboContext consumerSystem = RoboContextUtils.loadRoboContextByXml("robo_datagram_client_request_consumer_text.xml"); + var producerSystem = RoboContextUtils.loadRoboContextByXml("robo_datagram_client_request_producer_text.xml"); + var consumerSystem = RoboContextUtils.loadRoboContextByXml("robo_datagram_client_request_consumer_text.xml"); consumerSystem.start(); producerSystem.start(); - System.out.println("consumer: State after start:"); - System.out.println(SystemUtil.printStateReport(consumerSystem)); - - System.out.println("producer: State after start:"); - System.out.println(SystemUtil.printStateReport(producerSystem)); + LOGGER.info(SystemUtil.printStateReport(consumerSystem)); + LOGGER.info(SystemUtil.printStateReport(producerSystem)); RoboReference decoratedProducer = producerSystem.getReference("decoratedProducer"); decoratedProducer.sendMessage(MAX_NUMBER); diff --git a/robo4j-socket-http/src/test/java/com/robo4j/socket/http/test/units/RoboDatagramPingPongTest.java b/robo4j-socket-http/src/test/java/com/robo4j/socket/http/test/units/RoboDatagramPingPongTest.java index 41706041..6c6c5faa 100644 --- a/robo4j-socket-http/src/test/java/com/robo4j/socket/http/test/units/RoboDatagramPingPongTest.java +++ b/robo4j-socket-http/src/test/java/com/robo4j/socket/http/test/units/RoboDatagramPingPongTest.java @@ -31,16 +31,13 @@ import com.robo4j.socket.http.util.RoboHttpUtils; import com.robo4j.util.SystemUtil; import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; -import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import static com.robo4j.socket.http.test.units.HttpUnitTests.CODECS_UNITS_TEST_PACKAGE; -import static com.robo4j.socket.http.util.RoboHttpUtils.PROPERTY_CODEC_PACKAGES; -import static com.robo4j.socket.http.util.RoboHttpUtils.PROPERTY_HOST; -import static com.robo4j.socket.http.util.RoboHttpUtils.PROPERTY_SOCKET_PORT; -import static com.robo4j.socket.http.util.RoboHttpUtils.PROPERTY_UNIT_PATHS_CONFIG; -import static org.junit.jupiter.api.Assertions.assertEquals; +import static com.robo4j.socket.http.util.RoboHttpUtils.*; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -49,84 +46,82 @@ * @author Miroslav Wengner (@miragemiko) */ class RoboDatagramPingPongTest { - - private static final int TIMEOUT = 20; - private static final TimeUnit TIME_UNIT = TimeUnit.SECONDS; - private static final String UDP_CLIENT = "udp_client"; - private static final String UDP_SERVER = "udp_server"; - - private static final int TOTAL_NUMBER = 122; - - @Test - void datagramPingPongTest() throws Exception { - RoboContext pongSystem = configurePongSystem(TOTAL_NUMBER); - RoboContext pingSystem = configurePingSystem(); - - pongSystem.start(); - pingSystem.start(); - System.out.println("UDP pongSystem: State after start:"); - System.out.println(SystemUtil.printStateReport(pongSystem)); - System.out.println("UDP pingSystem: State after start:"); - System.out.println(SystemUtil.printStateReport(pingSystem)); - - RoboReference pongStringConsumerReference = pongSystem.getReference(StringConsumer.NAME); - CountDownLatch totalMessageLatch = pongStringConsumerReference.getAttribute(StringConsumer.DESCRIPTOR_MESSAGES_LATCH).get(); - - RoboReference udpClient = pingSystem.getReference(UDP_CLIENT); - for (int i = 0; i < TOTAL_NUMBER; i++) { - DatagramDenominator denominator = new DatagramDenominator(DatagramBodyType.JSON.getType(), "/units/stringConsumer"); - DatagramDecoratedRequest request = new DatagramDecoratedRequest(denominator); - String message = "{\"message\": \"Hello i:" + i + "\"}"; - request.addMessage(message.getBytes()); - udpClient.sendMessage(request); - } - - totalMessageLatch.await(TIMEOUT, TIME_UNIT); - final int pongConsumerTotalNumber = pongStringConsumerReference.getAttribute(StringConsumer.DESCRIPTOR_MESSAGES_TOTAL).get(); - - - System.out.println("UDP pongSystem: State after shutdown:"); - System.out.println(SystemUtil.printStateReport(pongSystem)); - System.out.println("UDP pingSystem: State after shutdown:"); - System.out.println(SystemUtil.printStateReport(pingSystem)); - pingSystem.shutdown(); - pongSystem.shutdown(); - - assertTrue(pongConsumerTotalNumber > 0 && pongConsumerTotalNumber <= TOTAL_NUMBER ); - - } - - private RoboContext configurePingSystem() throws Exception { - RoboBuilder builder = new RoboBuilder(); - - Configuration config = new ConfigurationBuilder().addString(PROPERTY_CODEC_PACKAGES, CODECS_UNITS_TEST_PACKAGE) - .addString(PROPERTY_HOST, "localhost").addInteger(PROPERTY_SOCKET_PORT, RoboHttpUtils.DEFAULT_UDP_PORT) - .addString(PROPERTY_UNIT_PATHS_CONFIG, "[{\"roboUnit\":\"stringConsumer\",\"callbacks\": [\"stringConsumer\"]}]").build(); - builder.add(DatagramClientUnit.class, config, UDP_CLIENT); - - config = ConfigurationFactory.createEmptyConfiguration(); - builder.add(StringConsumer.class, config, StringConsumer.NAME); - - return builder.build(); - } - - /** - * create simple UDP server with consumer unit - * - * - * @return roboContext - * @throws Exception - * exception - */ - private RoboContext configurePongSystem(int totalNumberOfMessage) throws Exception { - RoboBuilder builder = new RoboBuilder(); - Configuration config = new ConfigurationBuilder().addString(PROPERTY_CODEC_PACKAGES, CODECS_UNITS_TEST_PACKAGE) - .addString(PROPERTY_UNIT_PATHS_CONFIG, "[{\"roboUnit\":\"stringConsumer\",\"filters\":[]}]").build(); - builder.add(DatagramServerUnit.class, config, UDP_SERVER); - - config = new ConfigurationBuilder().addInteger(StringConsumer.PROP_TOTAL_NUMBER_MESSAGES, totalNumberOfMessage).build(); - builder.add(StringConsumer.class, config, StringConsumer.NAME); - - return builder.build(); - } + private static final Logger LOGGER = LoggerFactory.getLogger(RoboDatagramPingPongTest.class); + private static final int TIMEOUT = 20; + private static final TimeUnit TIME_UNIT = TimeUnit.SECONDS; + private static final String UDP_CLIENT = "udp_client"; + private static final String UDP_SERVER = "udp_server"; + + private static final int TOTAL_NUMBER = 122; + + @Test + void datagramPingPongTest() throws Exception { + var pongSystem = configurePongSystem(TOTAL_NUMBER); + var pingSystem = configurePingSystem(); + + pongSystem.start(); + pingSystem.start(); + LOGGER.info("UDP pongSystem: State after start:"); + LOGGER.info(SystemUtil.printStateReport(pongSystem)); + LOGGER.info("UDP pingSystem: State after start:"); + LOGGER.info(SystemUtil.printStateReport(pingSystem)); + + var pongStringConsumerReference = pongSystem.getReference(StringConsumer.NAME); + var totalMessageLatch = pongStringConsumerReference.getAttribute(StringConsumer.DESCRIPTOR_MESSAGES_LATCH).get(); + + RoboReference udpClient = pingSystem.getReference(UDP_CLIENT); + for (int i = 0; i < TOTAL_NUMBER; i++) { + DatagramDenominator denominator = new DatagramDenominator(DatagramBodyType.JSON.getType(), "/units/stringConsumer"); + DatagramDecoratedRequest request = new DatagramDecoratedRequest(denominator); + String message = "{\"message\": \"Hello i:" + i + "\"}"; + request.addMessage(message.getBytes()); + udpClient.sendMessage(request); + } + + totalMessageLatch.await(TIMEOUT, TIME_UNIT); + final int pongConsumerTotalNumber = pongStringConsumerReference.getAttribute(StringConsumer.DESCRIPTOR_MESSAGES_TOTAL).get(); + + + LOGGER.debug("UDP pongSystem: State after shutdown:"); + LOGGER.debug(SystemUtil.printStateReport(pongSystem)); + LOGGER.debug("UDP pingSystem: State after shutdown:"); + LOGGER.debug(SystemUtil.printStateReport(pingSystem)); + pingSystem.shutdown(); + pongSystem.shutdown(); + + assertTrue(pongConsumerTotalNumber > 0 && pongConsumerTotalNumber <= TOTAL_NUMBER); + + } + + private RoboContext configurePingSystem() throws Exception { + RoboBuilder builder = new RoboBuilder(); + + Configuration config = new ConfigurationBuilder().addString(PROPERTY_CODEC_PACKAGES, CODECS_UNITS_TEST_PACKAGE) + .addString(PROPERTY_HOST, "localhost").addInteger(PROPERTY_SOCKET_PORT, RoboHttpUtils.DEFAULT_UDP_PORT) + .addString(PROPERTY_UNIT_PATHS_CONFIG, "[{\"roboUnit\":\"stringConsumer\",\"callbacks\": [\"stringConsumer\"]}]").build(); + builder.add(DatagramClientUnit.class, config, UDP_CLIENT); + + config = ConfigurationFactory.createEmptyConfiguration(); + builder.add(StringConsumer.class, config, StringConsumer.NAME); + + return builder.build(); + } + + /** + * create simple UDP server with consumer unit + * + * @return roboContext + * @throws Exception exception + */ + private RoboContext configurePongSystem(int totalNumberOfMessage) throws Exception { + RoboBuilder builder = new RoboBuilder(); + Configuration config = new ConfigurationBuilder().addString(PROPERTY_CODEC_PACKAGES, CODECS_UNITS_TEST_PACKAGE) + .addString(PROPERTY_UNIT_PATHS_CONFIG, "[{\"roboUnit\":\"stringConsumer\",\"filters\":[]}]").build(); + builder.add(DatagramServerUnit.class, config, UDP_SERVER); + + config = new ConfigurationBuilder().addInteger(StringConsumer.PROP_TOTAL_NUMBER_MESSAGES, totalNumberOfMessage).build(); + builder.add(StringConsumer.class, config, StringConsumer.NAME); + + return builder.build(); + } } diff --git a/robo4j-socket-http/src/test/java/com/robo4j/socket/http/test/units/RoboHttpClientWithResponseTests.java b/robo4j-socket-http/src/test/java/com/robo4j/socket/http/test/units/RoboHttpClientWithResponseTests.java index 3f6738b3..fc113b21 100644 --- a/robo4j-socket-http/src/test/java/com/robo4j/socket/http/test/units/RoboHttpClientWithResponseTests.java +++ b/robo4j-socket-http/src/test/java/com/robo4j/socket/http/test/units/RoboHttpClientWithResponseTests.java @@ -16,17 +16,17 @@ */ package com.robo4j.socket.http.test.units; -import com.robo4j.RoboContext; -import com.robo4j.RoboReference; import com.robo4j.socket.http.test.units.config.SocketMessageDecoratedProducerUnit; import com.robo4j.socket.http.test.units.config.StringConsumer; import com.robo4j.util.SystemUtil; import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; -import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * testing http method GET with response @@ -36,48 +36,52 @@ */ class RoboHttpClientWithResponseTests { - private static final int TIMEOUT = 20; - private static final TimeUnit TIME_UNIT = TimeUnit.SECONDS; - private static final Integer MAX_NUMBER = 20; - // private static final String ROBO_SYSTEM_DESC = - // "[{\"id\":\"stringConsumer\",\"state\":\"STARTED\"},{\"id\":\"httpServer\",\"state\":\"STARTED\"}]"; + private static final Logger LOGGER = LoggerFactory.getLogger(RoboHttpClientWithResponseTests.class); + private static final int TIMEOUT = 20; + private static final TimeUnit TIME_UNIT = TimeUnit.SECONDS; + private static final Integer MAX_NUMBER = 20; + // private static final String ROBO_SYSTEM_DESC = + // "[{\"id\":\"stringConsumer\",\"state\":\"STARTED\"},{\"id\":\"httpServer\",\"state\":\"STARTED\"}]"; - @Test - void simpleRoboSystemGetRequestTest() throws Exception { + @Test + void simpleRoboSystemGetRequestTest() throws Exception { - RoboContext producerSystem = RoboContextUtils - .loadRoboContextByXml("robo_http_client_request_producer_text.xml"); - RoboContext consumerSystem = RoboContextUtils - .loadRoboContextByXml("robo_http_client_request_consumer_text.xml"); + var producerSystem = RoboContextUtils + .loadRoboContextByXml("robo_http_client_request_producer_text.xml"); + var consumerSystem = RoboContextUtils + .loadRoboContextByXml("robo_http_client_request_consumer_text.xml"); - consumerSystem.start(); - producerSystem.start(); + consumerSystem.start(); + producerSystem.start(); - System.out.println("consumer: State after start:"); - System.out.println(SystemUtil.printStateReport(consumerSystem)); + LOGGER.info("consumer: State after start:"); + LOGGER.info(SystemUtil.printStateReport(consumerSystem)); + LOGGER.info("producer: State after start:"); + LOGGER.info(SystemUtil.printStateReport(producerSystem)); - System.out.println("producer: State after start:"); - System.out.println(SystemUtil.printStateReport(producerSystem)); + var decoratedProducer = producerSystem.getReference("decoratedProducer"); + var producerSetupLatch = decoratedProducer + .getAttribute(SocketMessageDecoratedProducerUnit.DESCRIPTOR_SETUP_LATCH).get(); + decoratedProducer.sendMessage(MAX_NUMBER); + var producerConfigured = producerSetupLatch.await(TIMEOUT, TIME_UNIT); + var producerLatch = decoratedProducer + .getAttribute(SocketMessageDecoratedProducerUnit.DESCRIPTOR_MESSAGES_LATCH).get(); + var messagesSent = producerLatch.await(TIMEOUT, TIME_UNIT); - RoboReference decoratedProducer = producerSystem.getReference("decoratedProducer"); - CountDownLatch producerSetupLatch = decoratedProducer - .getAttribute(SocketMessageDecoratedProducerUnit.DESCRIPTOR_SETUP_LATCH).get(); - decoratedProducer.sendMessage(MAX_NUMBER); - producerSetupLatch.await(TIMEOUT, TIME_UNIT); - CountDownLatch producerLatch = decoratedProducer - .getAttribute(SocketMessageDecoratedProducerUnit.DESCRIPTOR_MESSAGES_LATCH).get(); - producerLatch.await(TIMEOUT, TIME_UNIT); + var producerStringConsumer = producerSystem.getReference(StringConsumer.NAME); + var messagesLatchStringConsumer = producerStringConsumer + .getAttribute(StringConsumer.DESCRIPTOR_MESSAGES_LATCH).get(); + var messagesReceived = messagesLatchStringConsumer.await(TIMEOUT, TIME_UNIT); - final RoboReference producerStringConsumer = producerSystem.getReference(StringConsumer.NAME); - final CountDownLatch messagesLatchStringConsumer = producerStringConsumer - .getAttribute(StringConsumer.DESCRIPTOR_MESSAGES_LATCH).get(); - messagesLatchStringConsumer.await(TIMEOUT, TIME_UNIT); + var totalNumber = producerStringConsumer.getAttribute(StringConsumer.DESCRIPTOR_MESSAGES_TOTAL).get(); - final Integer totalNumber = producerStringConsumer.getAttribute(StringConsumer.DESCRIPTOR_MESSAGES_TOTAL).get(); - assertEquals(MAX_NUMBER, totalNumber); + assertTrue(producerConfigured); + assertTrue(messagesSent); + assertTrue(messagesReceived); + assertEquals(MAX_NUMBER, totalNumber); - producerSystem.shutdown(); - consumerSystem.shutdown(); - } + producerSystem.shutdown(); + consumerSystem.shutdown(); + } } diff --git a/robo4j-socket-http/src/test/java/com/robo4j/socket/http/test/units/RoboHttpDynamicTests.java b/robo4j-socket-http/src/test/java/com/robo4j/socket/http/test/units/RoboHttpDynamicTests.java index e0c909be..b720401d 100644 --- a/robo4j-socket-http/src/test/java/com/robo4j/socket/http/test/units/RoboHttpDynamicTests.java +++ b/robo4j-socket-http/src/test/java/com/robo4j/socket/http/test/units/RoboHttpDynamicTests.java @@ -33,6 +33,8 @@ import com.robo4j.util.SystemUtil; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; @@ -49,7 +51,6 @@ * @author Miro Wengner (@miragemiko) */ class RoboHttpDynamicTests { - private static final int TIMEOUT = 20; private static final TimeUnit TIME_UNIT = TimeUnit.HOURS; private static final String ID_HTTP_SERVER = "http"; @@ -59,6 +60,7 @@ class RoboHttpDynamicTests { private static final int MESSAGES_NUMBER = 42; private static final String HOST_SYSTEM = "localhost"; static final String JSON_STRING = "{\"value\":\"stop\"}"; + private static final Logger LOGGER = LoggerFactory.getLogger(RoboHttpDynamicTests.class); private static final String DECORATED_PRODUCER = "decoratedProducer"; /** @@ -73,34 +75,32 @@ class RoboHttpDynamicTests { void simpleHttpNonUnitTest() throws Exception { /* tested system configuration */ - RoboContext mainSystem = getServerRoboSystem(MESSAGES_NUMBER); + var mainSystem = getServerRoboSystem(MESSAGES_NUMBER); /* system which is testing main system */ - RoboContext clientSystem = getClientRoboSystem(); - - System.out.println("Client system state after start:"); - System.out.println(SystemUtil.printStateReport(clientSystem)); + var clientSystem = getClientRoboSystem(); - System.out.println("Main system state after start:"); - System.out.println(SystemUtil.printStateReport(mainSystem)); + LOGGER.info("Client system state after start:"); + LOGGER.info(SystemUtil.printStateReport(clientSystem)); + LOGGER.info("Main system state after start:"); + LOGGER.info(SystemUtil.printStateReport(mainSystem)); /* client system sending a messages to the main system */ - RoboReference decoratedProducer = clientSystem.getReference(DECORATED_PRODUCER); + var decoratedProducer = clientSystem.getReference(DECORATED_PRODUCER); decoratedProducer.sendMessage(MESSAGES_NUMBER); // TODO: review how to receiving attributes - CountDownLatch countDownLatchDecoratedProducer = getAttributeOrTimeout(decoratedProducer, SocketMessageDecoratedProducerUnit.DESCRIPTOR_MESSAGES_LATCH); + var countDownLatchDecoratedProducer = getAttributeOrTimeout(decoratedProducer, SocketMessageDecoratedProducerUnit.DESCRIPTOR_MESSAGES_LATCH); var messagesProduced = countDownLatchDecoratedProducer.await(TIMEOUT, TIME_UNIT); - - final RoboReference stringConsumer = mainSystem.getReference(StringConsumer.NAME); - final CountDownLatch countDownLatch = getAttributeOrTimeout(stringConsumer, StringConsumer.DESCRIPTOR_MESSAGES_LATCH); + var stringConsumer = mainSystem.getReference(StringConsumer.NAME); + var countDownLatch = getAttributeOrTimeout(stringConsumer, StringConsumer.DESCRIPTOR_MESSAGES_LATCH); var messagesReceived = countDownLatch.await(TIMEOUT, TIME_UNIT); - final int receivedMessages = getAttributeOrTimeout(stringConsumer, StringConsumer.DESCRIPTOR_MESSAGES_TOTAL); + var receivedMessages = getAttributeOrTimeout(stringConsumer, StringConsumer.DESCRIPTOR_MESSAGES_TOTAL); clientSystem.shutdown(); mainSystem.shutdown(); - System.out.println("System is Down!"); + LOGGER.info("System is Down!"); assertTrue(messagesProduced); assertTrue(messagesReceived); assertNotNull(mainSystem.getUnits()); @@ -121,8 +121,8 @@ void pingExternalSystem() throws Exception { RoboContext pingSystemContext = pingSystemBuilder.build(); pingSystemContext.start(); - System.out.println("PingSystem state after start:"); - System.out.println(SystemUtil.printStateReport(pingSystemContext)); + LOGGER.info("PingSystem state after start:"); + LOGGER.info(SystemUtil.printStateReport(pingSystemContext)); RoboReference httpClient = pingSystemContext.getReference(ID_CLIENT_UNIT); @@ -136,8 +136,8 @@ void pingExternalSystem() throws Exception { } Thread.sleep(1000); pingSystemContext.stop(); - System.out.println("PingSystem state after stop:"); - System.out.println(SystemUtil.printStateReport(pingSystemContext)); + LOGGER.info("PingSystem state after stop:"); + LOGGER.info(SystemUtil.printStateReport(pingSystemContext)); } @@ -166,7 +166,7 @@ private RoboContext getServerRoboSystem(int totalMessageNumber) throws Exception assertEquals(LifecycleState.INITIALIZED, result.getState()); result.start(); - System.out.println(SystemUtil.printSocketEndPoint(result.getReference(ID_HTTP_SERVER), + LOGGER.info(SystemUtil.printSocketEndPoint(result.getReference(ID_HTTP_SERVER), result.getReference(ID_TARGET_UNIT))); return result; } diff --git a/robo4j-socket-http/src/test/java/com/robo4j/socket/http/test/units/RoboHttpPingPongTest.java b/robo4j-socket-http/src/test/java/com/robo4j/socket/http/test/units/RoboHttpPingPongTest.java index 5a5e8a8d..483e3100 100644 --- a/robo4j-socket-http/src/test/java/com/robo4j/socket/http/test/units/RoboHttpPingPongTest.java +++ b/robo4j-socket-http/src/test/java/com/robo4j/socket/http/test/units/RoboHttpPingPongTest.java @@ -18,7 +18,6 @@ import com.robo4j.RoboBuilder; import com.robo4j.RoboContext; -import com.robo4j.RoboReference; import com.robo4j.configuration.Configuration; import com.robo4j.configuration.ConfigurationBuilder; import com.robo4j.socket.http.HttpMethod; @@ -30,15 +29,14 @@ import com.robo4j.socket.http.util.HttpPathConfigJsonBuilder; import com.robo4j.util.SystemUtil; import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; -import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; -import static com.robo4j.socket.http.util.RoboHttpUtils.PROPERTY_HOST; -import static com.robo4j.socket.http.util.RoboHttpUtils.PROPERTY_SOCKET_PORT; -import static com.robo4j.socket.http.util.RoboHttpUtils.PROPERTY_TARGET; -import static com.robo4j.socket.http.util.RoboHttpUtils.PROPERTY_UNIT_PATHS_CONFIG; +import static com.robo4j.socket.http.util.RoboHttpUtils.*; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Ping Pong test from outside/foreign unit is send signal. The signal has been @@ -52,104 +50,100 @@ * @author Marcus Hirt (@hirt) * @author Miro Wengner (@miragemiko) */ -public class RoboHttpPingPongTest { - - public static final String HOST_SYSTEM = "127.0.0.1"; - private static final int TIMEOUT = 10; - private static final TimeUnit TIME_UNIT = TimeUnit.HOURS; - private static final String ID_HTTP_CLIENT = "http_client"; - private static final String ID_HTTP_SERVER = "http_server"; - private static final String CONTROLLER_PING_PONG = "controller"; - private static final int PORT = 8042; - private static final int MESSAGES = 50; - private static final String REQUEST_CONSUMER = "request_consumer"; - private static final String DECORATED_PRODUCER = "decoratedProducer"; - - public void runPongServer() throws Exception { - RoboContext system = configurePongSystem(0); - system.start(); - System.out.println("systemPong: State after start:"); - System.out.println(SystemUtil.printStateReport(system)); - System.out.println("Press ..."); - System.in.read(); - system.shutdown(); - - } - - @Test - void pingPongTest() throws Exception { - - RoboContext systemPong = configurePongSystem(MESSAGES); - RoboContext systemPing = configurePingSystem(); - - systemPong.start(); - System.out.println("systemPong: State after start:"); - System.out.println(SystemUtil.printStateReport(systemPong)); - - systemPing.start(); - System.out.println("systemPing: State after start:"); - System.out.println(SystemUtil.printStateReport(systemPing)); - - System.out.println("systemPing: send messages"); - RoboReference decoratedProducer = systemPing.getReference(DECORATED_PRODUCER); - decoratedProducer.sendMessage(MESSAGES); - - RoboReference pongConsumer = systemPong.getReference(REQUEST_CONSUMER); - CountDownLatch attributeFuture = pongConsumer.getAttribute(StringConsumer.DESCRIPTOR_MESSAGES_LATCH).get(); - - attributeFuture.await(TIMEOUT, TIME_UNIT); - System.out.println("systemPing : Going Down!"); - systemPing.stop(); - systemPing.shutdown(); - - System.out.println("systemPong : Going Down!"); - - final int number = pongConsumer.getAttribute(StringConsumer.DESCRIPTOR_MESSAGES_TOTAL).get(); - systemPong.stop(); - assertEquals(MESSAGES, number); - System.out.println("PingPong is down!"); - systemPong.shutdown(); - - } - - // Private Methods - private RoboContext configurePongSystem(int totalMessageNumber) throws Exception { - RoboBuilder builder = new RoboBuilder(); - - final HttpPathConfigJsonBuilder pathBuilder = HttpPathConfigJsonBuilder.Builder().addPath(CONTROLLER_PING_PONG, - HttpMethod.POST); - - Configuration config = new ConfigurationBuilder().addInteger(PROPERTY_SOCKET_PORT, PORT) - .addString("packages", HttpUnitTests.CODECS_UNITS_TEST_PACKAGE).addString(PROPERTY_UNIT_PATHS_CONFIG, pathBuilder.build()) - .build(); - - builder.add(HttpServerUnit.class, config, ID_HTTP_SERVER); - - config = new ConfigurationBuilder().addInteger(StringConsumer.PROP_TOTAL_NUMBER_MESSAGES, totalMessageNumber) - .build(); - builder.add(StringConsumer.class, config, REQUEST_CONSUMER); - - config = new ConfigurationBuilder().addString("target", REQUEST_CONSUMER).build(); - builder.add(HttpCommandTestController.class, config, CONTROLLER_PING_PONG); - - return builder.build(); - } - - private RoboContext configurePingSystem() throws Exception { - - /* system which is testing main system */ - RoboBuilder builder = new RoboBuilder(); - - Configuration config = new ConfigurationBuilder().addString(PROPERTY_HOST, HOST_SYSTEM) - .addInteger(PROPERTY_SOCKET_PORT, PORT).build(); - builder.add(HttpClientUnit.class, config, ID_HTTP_CLIENT); - - config = new ConfigurationBuilder().addString(PROPERTY_TARGET, ID_HTTP_CLIENT) - .addString(PROPERTY_UNIT_PATHS_CONFIG, - "[{\"roboUnit\":\"" + CONTROLLER_PING_PONG + "\",\"method\":\"POST\"}]") - .addString("message", RoboHttpDynamicTests.JSON_STRING).build(); - builder.add(SocketMessageDecoratedProducerUnit.class, config, DECORATED_PRODUCER); - - return builder.build(); - } +class RoboHttpPingPongTest { + public static final String HOST_SYSTEM = "127.0.0.1"; + private static final Logger LOGGER = LoggerFactory.getLogger(RoboHttpPingPongTest.class); + private static final int TIMEOUT = 10; + private static final TimeUnit TIME_UNIT = TimeUnit.HOURS; + private static final String ID_HTTP_CLIENT = "http_client"; + private static final String ID_HTTP_SERVER = "http_server"; + private static final String CONTROLLER_PING_PONG = "controller"; + private static final int PORT = 8042; + private static final int MESSAGES = 50; + private static final String REQUEST_CONSUMER = "request_consumer"; + private static final String DECORATED_PRODUCER = "decoratedProducer"; + + public void runPongServer() throws Exception { + var system = configurePongSystem(0); + system.start(); + + LOGGER.info("systemPong: State after start:"); + LOGGER.info(SystemUtil.printStateReport(system)); + LOGGER.info("Press ..."); + System.in.read(); + system.shutdown(); + } + + @Test + void pingPongTest() throws Exception { + + var systemPong = configurePongSystem(MESSAGES); + var systemPing = configurePingSystem(); + + systemPong.start(); + LOGGER.info(SystemUtil.printStateReport(systemPong)); + systemPing.start(); + LOGGER.info(SystemUtil.printStateReport(systemPing)); + LOGGER.info("systemPing: send messages"); + var decoratedProducer = systemPing.getReference(DECORATED_PRODUCER); + decoratedProducer.sendMessage(MESSAGES); + + var pongConsumer = systemPong.getReference(REQUEST_CONSUMER); + var attributeFuture = pongConsumer.getAttribute(StringConsumer.DESCRIPTOR_MESSAGES_LATCH).get(); + var receivedMessages = attributeFuture.await(TIMEOUT, TIME_UNIT); + LOGGER.info("systemPing : Going Down!"); + systemPing.stop(); + systemPing.shutdown(); + + LOGGER.info("systemPong : Going Down!"); + final int number = pongConsumer.getAttribute(StringConsumer.DESCRIPTOR_MESSAGES_TOTAL).get(); + systemPong.stop(); + + assertTrue(receivedMessages); + assertEquals(MESSAGES, number); + LOGGER.info("PingPong is down!"); + systemPong.shutdown(); + + } + + // Private Methods + private RoboContext configurePongSystem(int totalMessageNumber) throws Exception { + RoboBuilder builder = new RoboBuilder(); + + final HttpPathConfigJsonBuilder pathBuilder = HttpPathConfigJsonBuilder.Builder().addPath(CONTROLLER_PING_PONG, + HttpMethod.POST); + + Configuration config = new ConfigurationBuilder().addInteger(PROPERTY_SOCKET_PORT, PORT) + .addString("packages", HttpUnitTests.CODECS_UNITS_TEST_PACKAGE).addString(PROPERTY_UNIT_PATHS_CONFIG, pathBuilder.build()) + .build(); + + builder.add(HttpServerUnit.class, config, ID_HTTP_SERVER); + + config = new ConfigurationBuilder().addInteger(StringConsumer.PROP_TOTAL_NUMBER_MESSAGES, totalMessageNumber) + .build(); + builder.add(StringConsumer.class, config, REQUEST_CONSUMER); + + config = new ConfigurationBuilder().addString("target", REQUEST_CONSUMER).build(); + builder.add(HttpCommandTestController.class, config, CONTROLLER_PING_PONG); + + return builder.build(); + } + + private RoboContext configurePingSystem() throws Exception { + + /* system which is testing main system */ + RoboBuilder builder = new RoboBuilder(); + + Configuration config = new ConfigurationBuilder().addString(PROPERTY_HOST, HOST_SYSTEM) + .addInteger(PROPERTY_SOCKET_PORT, PORT).build(); + builder.add(HttpClientUnit.class, config, ID_HTTP_CLIENT); + + config = new ConfigurationBuilder().addString(PROPERTY_TARGET, ID_HTTP_CLIENT) + .addString(PROPERTY_UNIT_PATHS_CONFIG, + "[{\"roboUnit\":\"" + CONTROLLER_PING_PONG + "\",\"method\":\"POST\"}]") + .addString("message", RoboHttpDynamicTests.JSON_STRING).build(); + builder.add(SocketMessageDecoratedProducerUnit.class, config, DECORATED_PRODUCER); + + return builder.build(); + } } diff --git a/robo4j-socket-http/src/test/java/com/robo4j/socket/http/test/units/RoboHttpUnitGetTestApp.java b/robo4j-socket-http/src/test/java/com/robo4j/socket/http/test/units/RoboHttpUnitGetTestApp.java index 2f6db958..ad2302c7 100644 --- a/robo4j-socket-http/src/test/java/com/robo4j/socket/http/test/units/RoboHttpUnitGetTestApp.java +++ b/robo4j-socket-http/src/test/java/com/robo4j/socket/http/test/units/RoboHttpUnitGetTestApp.java @@ -32,12 +32,12 @@ import com.robo4j.socket.http.units.HttpServerUnit; import com.robo4j.socket.http.util.HttpPathConfigJsonBuilder; import com.robo4j.util.SystemUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import static com.robo4j.socket.http.test.units.HttpUnitTests.CODECS_UNITS_TEST_PACKAGE; import static com.robo4j.socket.http.test.units.RoboHttpPingPongTest.HOST_SYSTEM; -import static com.robo4j.socket.http.util.RoboHttpUtils.PROPERTY_HOST; -import static com.robo4j.socket.http.util.RoboHttpUtils.PROPERTY_SOCKET_PORT; -import static com.robo4j.socket.http.util.RoboHttpUtils.PROPERTY_UNIT_PATHS_CONFIG; +import static com.robo4j.socket.http.util.RoboHttpUtils.*; /** * RoboHttpUnitGetTestApp should test Http get requests @@ -45,23 +45,22 @@ * @author Marcus Hirt (@hirt) * @author Miroslav Wengner (@miragemiko) */ -public class RoboHttpUnitGetTestApp { - - private static final int SERVER_PORT = 8061; - private static final String UNIT_ID_HTTP_CLIENT = "http_client"; - - /** - * Run the system with only server unit - * - * @throws Exception - * exception - */ - public void systemWithHttpServerOnlyTest() throws Exception { - final String httpServerUnitName = "http_server"; - final HttpPathConfigJsonBuilder pathBuilder = HttpPathConfigJsonBuilder.Builder().addPath(httpServerUnitName, - HttpMethod.GET); - - //@formatter:off +class RoboHttpUnitGetTestApp { + private static final Logger LOGGER = LoggerFactory.getLogger(RoboHttpUnitGetTestApp.class); + private static final int SERVER_PORT = 8061; + private static final String UNIT_ID_HTTP_CLIENT = "http_client"; + + /** + * Run the system with only server unit + * + * @throws Exception exception + */ + public void systemWithHttpServerOnlyTest() throws Exception { + final String httpServerUnitName = "http_server"; + final HttpPathConfigJsonBuilder pathBuilder = HttpPathConfigJsonBuilder.Builder().addPath(httpServerUnitName, + HttpMethod.GET); + + //@formatter:off Configuration systemConfiguration = new ConfigurationBuilder() .addInteger("poolSizeScheduler", 3) .addInteger("poolSizeWorker", 2) @@ -70,35 +69,32 @@ public void systemWithHttpServerOnlyTest() throws Exception { RoboBuilder builder = new RoboBuilder("roboSystem1", systemConfiguration); //@formatter:on - //@formatter:off + //@formatter:off Configuration config = new ConfigurationBuilder() .addInteger(PROPERTY_SOCKET_PORT, SERVER_PORT) .addString("packages", "com.robo4j.socket.http.codec") .addString(PROPERTY_UNIT_PATHS_CONFIG, pathBuilder.build()) .build(); //@formatter:on - builder.add(HttpServerUnit.class, config, httpServerUnitName); - RoboContext system = builder.build(); - - system.start(); - System.out.println("systemPong: State after start:"); - System.out.println(SystemUtil.printStateReport(system)); - System.out.println("Press ..."); - System.in.read(); - system.shutdown(); - } - - /** - * Run the system with known attributes - * - * @throws Exception - * exception - */ - public void oneKnownAttributeTest() throws Exception { - final HttpPathConfigJsonBuilder pathBuilder = HttpPathConfigJsonBuilder.Builder().addPath("controller", - HttpMethod.GET); - - //@formatter:off + builder.add(HttpServerUnit.class, config, httpServerUnitName); + RoboContext system = builder.build(); + + system.start(); + printSystemReport(system); + System.in.read(); + system.shutdown(); + } + + /** + * Run the system with known attributes + * + * @throws Exception exception + */ + public void oneKnownAttributeTest() throws Exception { + final HttpPathConfigJsonBuilder pathBuilder = HttpPathConfigJsonBuilder.Builder().addPath("controller", + HttpMethod.GET); + + //@formatter:off Configuration systemConfiguration = new ConfigurationBuilder() .addInteger("poolSizeScheduler", 4) .addInteger("poolSizeWorker", 2) @@ -107,89 +103,92 @@ public void oneKnownAttributeTest() throws Exception { RoboBuilder builder = new RoboBuilder("roboSystem1", systemConfiguration); //@formatter:on - //@formatter:off + //@formatter:off Configuration config = new ConfigurationBuilder() .addInteger(PROPERTY_SOCKET_PORT, SERVER_PORT) .addString("packages", CODECS_UNITS_TEST_PACKAGE) .addString(PROPERTY_UNIT_PATHS_CONFIG, pathBuilder.build()) .build(); //@formatter:on - builder.add(HttpServerUnit.class, config, "http_server"); - - config = new ConfigurationBuilder().addInteger(StringConsumer.PROP_TOTAL_NUMBER_MESSAGES, 1).build(); - builder.add(StringConsumer.class, config, "request_consumer"); - - config = new ConfigurationBuilder().addString("target", "request_consumer").build(); - builder.add(HttpOneAttributeGetController.class, config, "controller"); - - RoboContext system = builder.build(); - - system.start(); - System.out.println("systemPong: State after start:"); - System.out.println(SystemUtil.printStateReport(system)); - System.out.println("Press ..."); - System.in.read(); - system.shutdown(); - - } - - /** - * Run the system with known attributes - * - * @throws Exception - * exception - */ - public void twoKnownAttributesTest() throws Exception { - RoboContext systemGetProvider = twoAttributesSystem(); - RoboContext systemGetAccessor = attributeRequestSystem(); - - systemGetProvider.start(); - System.out.println("systemGetProvider: State after start:"); - System.out.println(SystemUtil.printStateReport(systemGetProvider)); - systemGetAccessor.start(); - System.out.println("systemGetAccessor: State after start:"); - System.out.println(SystemUtil.printStateReport(systemGetAccessor)); - - RoboReference httpClient = systemGetAccessor.getReference(UNIT_ID_HTTP_CLIENT); - - HttpRequestDenominator denominator = new HttpRequestDenominator(HttpMethod.GET, - "/units/controller?attributes=number", HttpVersion.HTTP_1_1); - HttpDecoratedRequest request = new HttpDecoratedRequest(denominator); - request.addCallback(StringConsumer.NAME); - httpClient.sendMessage(request); - - System.out.println("Press ..."); - System.in.read(); - systemGetProvider.shutdown(); - } - - private RoboContext attributeRequestSystem() throws Exception { - RoboBuilder builder = new RoboBuilder(); - - Configuration config = new ConfigurationBuilder().addString(PROPERTY_HOST, HOST_SYSTEM) - .addInteger(PROPERTY_SOCKET_PORT, SERVER_PORT).build(); - builder.add(HttpClientUnit.class, config, UNIT_ID_HTTP_CLIENT); - builder.add(StringConsumer.class, StringConsumer.NAME); - return builder.build(); - } - - private RoboContext twoAttributesSystem() throws Exception { - Configuration systemConfiguration = new ConfigurationBuilder().addInteger("poolSizeScheduler", 4) - .addInteger("poolSizeWorker", 2).addInteger("poolSizeBlocking", 3).build(); - RoboBuilder builder = new RoboBuilder(systemConfiguration); - - final HttpPathConfigJsonBuilder pathBuilder = HttpPathConfigJsonBuilder.Builder().addPath("controller", - HttpMethod.GET); - Configuration config = new ConfigurationBuilder().addInteger(PROPERTY_SOCKET_PORT, SERVER_PORT) - .addString("packages", CODECS_UNITS_TEST_PACKAGE).addString(PROPERTY_UNIT_PATHS_CONFIG, pathBuilder.build()) - .build(); - builder.add(HttpServerUnit.class, config, "http_server"); - - config = new ConfigurationBuilder().addInteger(StringConsumer.PROP_TOTAL_NUMBER_MESSAGES, 1).build(); - builder.add(StringConsumer.class, config, "request_consumer"); - - config = new ConfigurationBuilder().addString("target", "request_consumer").build(); - builder.add(HttpTwoAttributesGetController.class, config, "controller"); - return builder.build(); - } + builder.add(HttpServerUnit.class, config, "http_server"); + + config = new ConfigurationBuilder().addInteger(StringConsumer.PROP_TOTAL_NUMBER_MESSAGES, 1).build(); + builder.add(StringConsumer.class, config, "request_consumer"); + + config = new ConfigurationBuilder().addString("target", "request_consumer").build(); + builder.add(HttpOneAttributeGetController.class, config, "controller"); + + RoboContext system = builder.build(); + + system.start(); + printSystemReport(system); + System.in.read(); + system.shutdown(); + + } + + /** + * Run the system with known attributes + * + * @throws Exception exception + */ + public void twoKnownAttributesTest() throws Exception { + RoboContext systemGetProvider = twoAttributesSystem(); + RoboContext systemGetAccessor = attributeRequestSystem(); + + systemGetProvider.start(); + LOGGER.info("systemGetProvider: State after start:"); + LOGGER.info(SystemUtil.printStateReport(systemGetProvider)); + systemGetAccessor.start(); + LOGGER.info("systemGetAccessor: State after start:"); + LOGGER.info(SystemUtil.printStateReport(systemGetAccessor)); + + RoboReference httpClient = systemGetAccessor.getReference(UNIT_ID_HTTP_CLIENT); + + HttpRequestDenominator denominator = new HttpRequestDenominator(HttpMethod.GET, + "/units/controller?attributes=number", HttpVersion.HTTP_1_1); + HttpDecoratedRequest request = new HttpDecoratedRequest(denominator); + request.addCallback(StringConsumer.NAME); + httpClient.sendMessage(request); + + printSystemReport(systemGetProvider); + System.in.read(); + systemGetProvider.shutdown(); + } + + private RoboContext attributeRequestSystem() throws Exception { + RoboBuilder builder = new RoboBuilder(); + + Configuration config = new ConfigurationBuilder().addString(PROPERTY_HOST, HOST_SYSTEM) + .addInteger(PROPERTY_SOCKET_PORT, SERVER_PORT).build(); + builder.add(HttpClientUnit.class, config, UNIT_ID_HTTP_CLIENT); + builder.add(StringConsumer.class, StringConsumer.NAME); + return builder.build(); + } + + private RoboContext twoAttributesSystem() throws Exception { + Configuration systemConfiguration = new ConfigurationBuilder().addInteger("poolSizeScheduler", 4) + .addInteger("poolSizeWorker", 2).addInteger("poolSizeBlocking", 3).build(); + RoboBuilder builder = new RoboBuilder(systemConfiguration); + + final HttpPathConfigJsonBuilder pathBuilder = HttpPathConfigJsonBuilder.Builder().addPath("controller", + HttpMethod.GET); + Configuration config = new ConfigurationBuilder().addInteger(PROPERTY_SOCKET_PORT, SERVER_PORT) + .addString("packages", CODECS_UNITS_TEST_PACKAGE).addString(PROPERTY_UNIT_PATHS_CONFIG, pathBuilder.build()) + .build(); + builder.add(HttpServerUnit.class, config, "http_server"); + + config = new ConfigurationBuilder().addInteger(StringConsumer.PROP_TOTAL_NUMBER_MESSAGES, 1).build(); + builder.add(StringConsumer.class, config, "request_consumer"); + + config = new ConfigurationBuilder().addString("target", "request_consumer").build(); + builder.add(HttpTwoAttributesGetController.class, config, "controller"); + return builder.build(); + } + + private static void printSystemReport(RoboContext system) { + LOGGER.info("systemPong: State after start:"); + LOGGER.info(SystemUtil.printStateReport(system)); + LOGGER.info("Press ..."); + } } diff --git a/robo4j-socket-http/src/test/java/com/robo4j/socket/http/test/units/config/ServiceContainerUnit.java b/robo4j-socket-http/src/test/java/com/robo4j/socket/http/test/units/config/ServiceContainerUnit.java index 348e6fc6..021cd97d 100644 --- a/robo4j-socket-http/src/test/java/com/robo4j/socket/http/test/units/config/ServiceContainerUnit.java +++ b/robo4j-socket-http/src/test/java/com/robo4j/socket/http/test/units/config/ServiceContainerUnit.java @@ -17,8 +17,10 @@ package com.robo4j.socket.http.test.units.config; import com.robo4j.RoboContext; -import com.robo4j.socket.http.units.ExtendedRoboUnit; import com.robo4j.socket.http.test.units.config.service.NumberService; +import com.robo4j.socket.http.units.ExtendedRoboUnit; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.Objects; @@ -28,14 +30,15 @@ * @author Marcus Hirt (@hirt) * @author Miroslav Wengner (@miragemiko) */ -public class ServiceContainerUnit extends ExtendedRoboUnit { - +// TODO : review usage +class ServiceContainerUnit extends ExtendedRoboUnit { public static final String NAME = "containerUnit"; public static final String NUMBER_SERVICE = "numberService"; + private static final Logger LOGGER = LoggerFactory.getLogger(ServiceContainerUnit.class); public ServiceContainerUnit(RoboContext context, String id) { - super(Object.class, context, id); - } + super(Object.class, context, id); + } @Override public void start() { @@ -46,8 +49,8 @@ public void start() { @Override public void onMessage(Object message) { - System.out.println(getClass().getSimpleName() + ":message:" + message); - System.out.println(getClass().getSimpleName() + ":number:" + getService().getNumber()); + LOGGER.info("message:{}", message); + LOGGER.info("number:{}", getService().getNumber()); } diff --git a/robo4j-socket-http/src/test/java/com/robo4j/socket/http/test/units/config/SocketMessageDecoratedProducerUnit.java b/robo4j-socket-http/src/test/java/com/robo4j/socket/http/test/units/config/SocketMessageDecoratedProducerUnit.java index fc3551e3..c6f10176 100644 --- a/robo4j-socket-http/src/test/java/com/robo4j/socket/http/test/units/config/SocketMessageDecoratedProducerUnit.java +++ b/robo4j-socket-http/src/test/java/com/robo4j/socket/http/test/units/config/SocketMessageDecoratedProducerUnit.java @@ -16,11 +16,7 @@ */ package com.robo4j.socket.http.test.units.config; -import com.robo4j.AttributeDescriptor; -import com.robo4j.ConfigurationException; -import com.robo4j.DefaultAttributeDescriptor; -import com.robo4j.RoboContext; -import com.robo4j.RoboUnit; +import com.robo4j.*; import com.robo4j.configuration.Configuration; import com.robo4j.socket.http.HttpVersion; import com.robo4j.socket.http.dto.HttpPathMethodDTO; @@ -28,12 +24,14 @@ import com.robo4j.socket.http.message.DatagramDenominator; import com.robo4j.socket.http.message.HttpDecoratedRequest; import com.robo4j.socket.http.message.HttpRequestDenominator; +import com.robo4j.socket.http.test.units.config.enums.CommunicationType; import com.robo4j.socket.http.units.ClientContext; import com.robo4j.socket.http.units.ClientPathConfig; -import com.robo4j.socket.http.test.units.config.enums.CommunicationType; import com.robo4j.socket.http.util.DatagramBodyType; import com.robo4j.socket.http.util.HttpPathUtils; import com.robo4j.socket.http.util.JsonUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.List; import java.util.concurrent.CountDownLatch; @@ -50,110 +48,109 @@ * @author Miro Wengner (@miragemiko) */ public class SocketMessageDecoratedProducerUnit extends RoboUnit { + public static final String PROP_COMMUNICATION_TYPE = "communicationType"; + public static final String ATTR_TOTAL_SENT_MESSAGES = "getNumberOfSentMessages"; + public static final String ATTR_MESSAGES_LATCH = "messagesLatch"; + public static final String ATTR_SETUP_LATCH = "setupLatch"; + public static final DefaultAttributeDescriptor DESCRIPTOR_MESSAGES_LATCH = DefaultAttributeDescriptor + .create(CountDownLatch.class, ATTR_MESSAGES_LATCH); + public static final DefaultAttributeDescriptor DESCRIPTOR_SETUP_LATCH = DefaultAttributeDescriptor + .create(CountDownLatch.class, ATTR_SETUP_LATCH); - public static final String PROP_COMMUNICATION_TYPE = "communicationType"; - public static final String ATTR_TOTAL_SENT_MESSAGES = "getNumberOfSentMessages"; - public static final String ATTR_MESSAGES_LATCH = "messagesLatch"; - public static final String ATTR_SETUP_LATCH = "setupLatch"; - public static final DefaultAttributeDescriptor DESCRIPTOR_MESSAGES_LATCH = DefaultAttributeDescriptor - .create(CountDownLatch.class, ATTR_MESSAGES_LATCH); - public static final DefaultAttributeDescriptor DESCRIPTOR_SETUP_LATCH = DefaultAttributeDescriptor - .create(CountDownLatch.class, ATTR_SETUP_LATCH); - - private static final int DEFAULT = 0; - private final ClientContext clientContext = new ClientContext(); - private volatile CountDownLatch setupLatch = new CountDownLatch(1); - private volatile CountDownLatch messagesLatch; - private AtomicInteger counter; - private String target; - private String message; - private CommunicationType type; + private static final Logger LOGGER = LoggerFactory.getLogger(SocketMessageDecoratedProducerUnit.class); + private static final int DEFAULT = 0; + private final ClientContext clientContext = new ClientContext(); + private volatile CountDownLatch setupLatch = new CountDownLatch(1); + private volatile CountDownLatch messagesLatch; + private AtomicInteger counter; + private String target; + private String message; + private CommunicationType type; - public SocketMessageDecoratedProducerUnit(RoboContext context, String id) { - super(Integer.class, context, id); - } + public SocketMessageDecoratedProducerUnit(RoboContext context, String id) { + super(Integer.class, context, id); + } - @Override - protected void onInitialization(Configuration configuration) throws ConfigurationException { - target = configuration.getString(PROPERTY_TARGET, null); - message = configuration.getString("message", null); + @Override + protected void onInitialization(Configuration configuration) throws ConfigurationException { + target = configuration.getString(PROPERTY_TARGET, null); + message = configuration.getString("message", null); - List paths = JsonUtil.readPathConfig(HttpPathMethodDTO.class, - configuration.getString(PROPERTY_UNIT_PATHS_CONFIG, null)); - HttpPathUtils.updateHttpClientContextPaths(clientContext, paths); - counter = new AtomicInteger(DEFAULT); - type = CommunicationType.valueOf(configuration.getString(PROP_COMMUNICATION_TYPE, CommunicationType.HTTP.toString()).toUpperCase()); - } + List paths = JsonUtil.readPathConfig(HttpPathMethodDTO.class, + configuration.getString(PROPERTY_UNIT_PATHS_CONFIG, null)); + HttpPathUtils.updateHttpClientContextPaths(clientContext, paths); + counter = new AtomicInteger(DEFAULT); + type = CommunicationType.valueOf(configuration.getString(PROP_COMMUNICATION_TYPE, CommunicationType.HTTP.toString()).toUpperCase()); + } - /** - * produces desired number of GET request on RoboSystem - * - * @param number - * number of get messages - */ - @Override - public void onMessage(Integer number) { - messagesLatch = new CountDownLatch(number); - setupLatch.countDown(); - clientContext.getPathConfigs().forEach(pathConfig -> { - IntStream.range(DEFAULT, number).forEach(i -> { - switch (type){ - case HTTP: - getContext().getReference(target).sendMessage(getHttpRequest(pathConfig)); - break; - case DATAGRAM: - getContext().getReference(target).sendMessage(getDatagramRequest(pathConfig)); - break; - default: - throw new IllegalStateException("not allowed"); - } - messagesLatch.countDown(); - }); - System.out.println(getClass().getSimpleName() + "messages: " + number); - }); + /** + * produces desired number of GET request on RoboSystem + * + * @param number number of get messages + */ + @Override + public void onMessage(Integer number) { + messagesLatch = new CountDownLatch(number); + setupLatch.countDown(); + clientContext.getPathConfigs().forEach(pathConfig -> { + IntStream.range(DEFAULT, number).forEach(i -> { + switch (type) { + case HTTP: + getContext().getReference(target).sendMessage(getHttpRequest(pathConfig)); + break; + case DATAGRAM: + getContext().getReference(target).sendMessage(getDatagramRequest(pathConfig)); + break; + default: + throw new IllegalStateException("not allowed"); + } + messagesLatch.countDown(); + }); + LOGGER.info("messages: {}", number); + }); - } + } - private DatagramDecoratedRequest getDatagramRequest(ClientPathConfig pathConfig){ - final DatagramDenominator denominator = new DatagramDenominator(DatagramBodyType.JSON.getType(), pathConfig.getPath()); - final DatagramDecoratedRequest result = new DatagramDecoratedRequest(denominator); - result.addMessage(message.getBytes()); - return result; - } + private DatagramDecoratedRequest getDatagramRequest(ClientPathConfig pathConfig) { + final DatagramDenominator denominator = new DatagramDenominator(DatagramBodyType.JSON.getType(), pathConfig.getPath()); + final DatagramDecoratedRequest result = new DatagramDecoratedRequest(denominator); + result.addMessage(message.getBytes()); + return result; + } - private HttpDecoratedRequest getHttpRequest(ClientPathConfig pathConfig){ - HttpRequestDenominator denominator = new HttpRequestDenominator(pathConfig.getMethod(), - pathConfig.getPath(), HttpVersion.HTTP_1_1); - HttpDecoratedRequest result = new HttpDecoratedRequest(denominator); - switch (pathConfig.getMethod()) { - case GET: - result.addCallbacks(pathConfig.getCallbacks()); - break; - case POST: - result.addMessage(message); - break; - default: - throw new IllegalStateException("not allowed state: " + pathConfig); - } - return result; - } + private HttpDecoratedRequest getHttpRequest(ClientPathConfig pathConfig) { + HttpRequestDenominator denominator = new HttpRequestDenominator(pathConfig.getMethod(), + pathConfig.getPath(), HttpVersion.HTTP_1_1); + HttpDecoratedRequest result = new HttpDecoratedRequest(denominator); + switch (pathConfig.getMethod()) { + case GET: + result.addCallbacks(pathConfig.getCallbacks()); + break; + case POST: + result.addMessage(message); + break; + default: + throw new IllegalStateException("not allowed state: " + pathConfig); + } + return result; + } - @SuppressWarnings("unchecked") - @Override - public synchronized R onGetAttribute(AttributeDescriptor attribute) { - if (attribute.getAttributeName().equals(ATTR_TOTAL_SENT_MESSAGES) - && attribute.getAttributeType() == Integer.class) { - return (R) (Integer) counter.get(); - } - if (attribute.getAttributeName().equals(ATTR_MESSAGES_LATCH) - && attribute.getAttributeType() == CountDownLatch.class) { - return (R) messagesLatch; - } - if (attribute.getAttributeName().equals(ATTR_SETUP_LATCH) - && attribute.getAttributeType() == CountDownLatch.class) { - return (R) setupLatch; - } - return null; - } + @SuppressWarnings("unchecked") + @Override + public synchronized R onGetAttribute(AttributeDescriptor attribute) { + if (attribute.getAttributeName().equals(ATTR_TOTAL_SENT_MESSAGES) + && attribute.getAttributeType() == Integer.class) { + return (R) (Integer) counter.get(); + } + if (attribute.getAttributeName().equals(ATTR_MESSAGES_LATCH) + && attribute.getAttributeType() == CountDownLatch.class) { + return (R) messagesLatch; + } + if (attribute.getAttributeName().equals(ATTR_SETUP_LATCH) + && attribute.getAttributeType() == CountDownLatch.class) { + return (R) setupLatch; + } + return null; + } } diff --git a/robo4j-socket-http/src/test/java/com/robo4j/socket/http/test/units/config/StringProducerUnit.java b/robo4j-socket-http/src/test/java/com/robo4j/socket/http/test/units/config/StringProducerUnit.java index b34f4419..7f9e67f4 100644 --- a/robo4j-socket-http/src/test/java/com/robo4j/socket/http/test/units/config/StringProducerUnit.java +++ b/robo4j-socket-http/src/test/java/com/robo4j/socket/http/test/units/config/StringProducerUnit.java @@ -21,6 +21,8 @@ import com.robo4j.RoboContext; import com.robo4j.RoboUnit; import com.robo4j.configuration.Configuration; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.concurrent.atomic.AtomicInteger; @@ -29,47 +31,48 @@ * @author Miroslav Wengner (@miragemiko) */ public class StringProducerUnit extends RoboUnit { - /* default sent messages */ - private static final int DEFAULT = 0; - private AtomicInteger counter; - private String target; + private static final Logger LOGGER = LoggerFactory.getLogger(StringProducerUnit.class); + /* default sent messages */ + private static final int DEFAULT = 0; + private AtomicInteger counter; + private String target; - /** - * @param context - * @param id - */ - public StringProducerUnit(RoboContext context, String id) { - super(String.class, context, id); - } + /** + * @param context + * @param id + */ + public StringProducerUnit(RoboContext context, String id) { + super(String.class, context, id); + } - @Override - protected void onInitialization(Configuration configuration) throws ConfigurationException { - target = configuration.getString("target", null); - if (target == null) { - throw ConfigurationException.createMissingConfigNameException("target"); - } - counter = new AtomicInteger(DEFAULT); + @Override + protected void onInitialization(Configuration configuration) throws ConfigurationException { + target = configuration.getString("target", null); + if (target == null) { + throw ConfigurationException.createMissingConfigNameException("target"); + } + counter = new AtomicInteger(DEFAULT); - } + } - @Override - public void onMessage(String message) { - if (message == null) { - System.out.println("No Message!"); - } else { - counter.incrementAndGet(); - getContext().getReference(target).sendMessage(message); - } - } + @Override + public void onMessage(String message) { + if (message == null) { + LOGGER.info("No Message!"); + } else { + counter.incrementAndGet(); + getContext().getReference(target).sendMessage(message); + } + } - @SuppressWarnings("unchecked") - @Override - public synchronized R onGetAttribute(AttributeDescriptor attribute) { - if (attribute.getAttributeName().equals("getNumberOfSentMessages") - && attribute.getAttributeType() == Integer.class) { - return (R) (Integer) counter.get(); - } - return null; - } + @SuppressWarnings("unchecked") + @Override + public synchronized R onGetAttribute(AttributeDescriptor attribute) { + if (attribute.getAttributeName().equals("getNumberOfSentMessages") + && attribute.getAttributeType() == Integer.class) { + return (R) (Integer) counter.get(); + } + return null; + } }