From 6f7d40748ebdb34977dc30d6c64aaf943a54386d Mon Sep 17 00:00:00 2001 From: Miro Wengner Date: Mon, 7 Oct 2024 22:58:02 +0200 Subject: [PATCH] [69] robo4j-socket-http partial --- .../WriteDatagramSelectionKeyHandler.java | 37 +- .../src/main/java/module-info.java | 1 + .../socket/http/test/HttpHeaderTests.java | 76 +-- .../http/test/json/JsonCodecsTests.java | 424 ++++++------ .../http/test/json/JsonReaderArrayTests.java | 396 +++++------ .../http/test/json/JsonReaderTests.java | 615 +++++++++--------- .../socket/http/test/json/JsonTest.java | 261 ++++---- .../socket/http/test/json/TimeUtils.java | 9 +- .../message/DatagramDecoratedRequestTest.java | 30 +- .../http/test/request/ByteBufferTests.java | 199 +++--- .../http/test/units/HttpContextTests.java | 126 ++-- .../src/test/java/module-info.java | 1 + 12 files changed, 1101 insertions(+), 1074 deletions(-) diff --git a/robo4j-socket-http/src/main/java/com/robo4j/socket/http/channel/WriteDatagramSelectionKeyHandler.java b/robo4j-socket-http/src/main/java/com/robo4j/socket/http/channel/WriteDatagramSelectionKeyHandler.java index 66796bff..e3038f70 100644 --- a/robo4j-socket-http/src/main/java/com/robo4j/socket/http/channel/WriteDatagramSelectionKeyHandler.java +++ b/robo4j-socket-http/src/main/java/com/robo4j/socket/http/channel/WriteDatagramSelectionKeyHandler.java @@ -20,6 +20,8 @@ import com.robo4j.RoboReference; import com.robo4j.socket.http.request.DatagramResponseProcess; import com.robo4j.socket.http.units.ServerContext; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.nio.channels.SelectionKey; import java.util.Map; @@ -29,20 +31,21 @@ * @author Miroslav Wengner (@miragemiko) */ public class WriteDatagramSelectionKeyHandler implements SelectionKeyHandler { - private final Map outBuffers; - private final SelectionKey key; + private static final Logger LOGGER = LoggerFactory.getLogger(WriteDatagramSelectionKeyHandler.class); + private final Map outBuffers; + private final SelectionKey key; - public WriteDatagramSelectionKeyHandler(RoboContext context, ServerContext serverContext, - Map outBuffers, SelectionKey key) { - this.outBuffers = outBuffers; - this.key = key; - } + public WriteDatagramSelectionKeyHandler(RoboContext context, ServerContext serverContext, + Map outBuffers, SelectionKey key) { + this.outBuffers = outBuffers; + this.key = key; + } - @Override - public SelectionKey handle() { + @Override + public SelectionKey handle() { // final DatagramChannel channel = (DatagramChannel) key.channel(); // ByteBuffer buffer = ByteBuffer.allocate(serverContext.getPropertySafe(Integer.class, PROPERTY_BUFFER_CAPACITY)); - final DatagramResponseProcess responseProcess = outBuffers.get(key); + final DatagramResponseProcess responseProcess = outBuffers.get(key); // buffer.clear(); // buffer.put("ACCEPTED".getBytes()); @@ -53,12 +56,12 @@ public SelectionKey handle() { // throw new SocketException("handle", e); // } - RoboReference reference = responseProcess.getTarget(); - Object responseMessage = responseProcess.getResult(); - reference.sendMessage(responseMessage); - System.out.println("Wrote: " + responseMessage); + RoboReference reference = responseProcess.getTarget(); + Object responseMessage = responseProcess.getResult(); + reference.sendMessage(responseMessage); + LOGGER.debug("responseMessage:{}", responseMessage); - key.cancel(); - return key; - } + key.cancel(); + return key; + } } diff --git a/robo4j-socket-http/src/main/java/module-info.java b/robo4j-socket-http/src/main/java/module-info.java index fc3dc94e..0da234bc 100644 --- a/robo4j-socket-http/src/main/java/module-info.java +++ b/robo4j-socket-http/src/main/java/module-info.java @@ -1,5 +1,6 @@ module robo4j.http { requires transitive robo4j.core; + requires org.slf4j; exports com.robo4j.socket.http; exports com.robo4j.socket.http.codec; diff --git a/robo4j-socket-http/src/test/java/com/robo4j/socket/http/test/HttpHeaderTests.java b/robo4j-socket-http/src/test/java/com/robo4j/socket/http/test/HttpHeaderTests.java index 0b132627..1998dc87 100644 --- a/robo4j-socket-http/src/test/java/com/robo4j/socket/http/test/HttpHeaderTests.java +++ b/robo4j-socket-http/src/test/java/com/robo4j/socket/http/test/HttpHeaderTests.java @@ -21,7 +21,6 @@ import com.robo4j.socket.http.HttpVersion; import com.robo4j.socket.http.ProtocolType; import com.robo4j.socket.http.enums.StatusCode; -import com.robo4j.socket.http.message.HttpDenominator; import com.robo4j.socket.http.message.HttpRequestDenominator; import com.robo4j.socket.http.provider.DefaultValuesProvider; import com.robo4j.socket.http.util.HttpHeaderBuilder; @@ -29,6 +28,8 @@ import com.robo4j.socket.http.util.HttpMessageUtils; import com.robo4j.socket.http.util.RoboHttpUtils; import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import static com.robo4j.socket.http.HttpHeaderFieldValues.CONNECTION_KEEP_ALIVE; import static com.robo4j.socket.http.provider.DefaultValuesProvider.ROBO4J_CLIENT; @@ -43,31 +44,32 @@ * @author Miro Wengner (@miragemiko) */ class HttpHeaderTests { + private static final Logger LOGGER = LoggerFactory.getLogger(HttpHeaderTests.class); - @Test - void createHeaderTest() { - String header = HttpHeaderBuilder.Build().addFirstLine("units/controller") - .addAll(DefaultValuesProvider.BASIC_HEADER_MAP).build(HttpMethod.GET, HttpVersion.HTTP_1_1); + @Test + void createHeaderTest() { + String header = HttpHeaderBuilder.Build().addFirstLine("units/controller") + .addAll(DefaultValuesProvider.BASIC_HEADER_MAP).build(HttpMethod.GET, HttpVersion.HTTP_1_1); - assertNotNull(header); - assertEquals(8, header.split(HTTP_NEW_LINE).length); - assertEquals(header.split(HTTP_NEW_LINE)[2], - createHeaderField(HttpHeaderFieldNames.USER_AGENT, ROBO4J_CLIENT)); - assertEquals(header.split(HTTP_NEW_LINE)[3], - createHeaderField(HttpHeaderFieldNames.CONNECTION, CONNECTION_KEEP_ALIVE)); - } + assertNotNull(header); + assertEquals(8, header.split(HTTP_NEW_LINE).length); + assertEquals(header.split(HTTP_NEW_LINE)[2], + createHeaderField(HttpHeaderFieldNames.USER_AGENT, ROBO4J_CLIENT)); + assertEquals(header.split(HTTP_NEW_LINE)[3], + createHeaderField(HttpHeaderFieldNames.CONNECTION, CONNECTION_KEEP_ALIVE)); + } - @Test - void characterParser() { - assertEquals("[", HttpMessageUtils.getHttpSeparator(13)); - assertEquals("]",HttpMessageUtils.getHttpSeparator(14)); - } + @Test + void characterParser() { + assertEquals("[", HttpMessageUtils.getHttpSeparator(13)); + assertEquals("]", HttpMessageUtils.getHttpSeparator(14)); + } - @Test - void test() { - String uid = "1234"; - String expectedResult = "HTTP/1.1 200 OK" + HTTP_NEW_LINE + "uid: " + uid + HTTP_NEW_LINE; - //@formatter:off + @Test + void test() { + String uid = "1234"; + String expectedResult = "HTTP/1.1 200 OK" + HTTP_NEW_LINE + "uid: " + uid + HTTP_NEW_LINE; + //@formatter:off String getHeader = HttpHeaderBuilder.Build() .addFirstLine(HttpVersion.HTTP_1_1.getValue()) .addFirstLine(StatusCode.OK.getCode()) @@ -75,21 +77,21 @@ void test() { .add(HttpHeaderFieldNames.ROBO_UNIT_UID, uid) .build(); //@formatter:on - assertEquals(expectedResult, getHeader); - } + assertEquals(expectedResult, getHeader); + } - @Test - void extractHeaderParameter() { - String message = "message"; - HttpDenominator denominator = new HttpRequestDenominator(HttpMethod.POST, HttpVersion.HTTP_1_1); - String postRequest = HttpMessageBuilder.Build().setDenominator(denominator) - .addHeaderElement(HttpHeaderFieldNames.HOST, RoboHttpUtils.createHost("127.0.0.1", ProtocolType.HTTP.getPort())) - .addHeaderElement(HttpHeaderFieldNames.CONTENT_LENGTH, String.valueOf(message.length())) - .build(message); - System.out.println("HEADER: " + postRequest); - } + @Test + void extractHeaderParameter() { + var message = "message"; + var denominator = new HttpRequestDenominator(HttpMethod.POST, HttpVersion.HTTP_1_1); + var postRequest = HttpMessageBuilder.Build().setDenominator(denominator) + .addHeaderElement(HttpHeaderFieldNames.HOST, RoboHttpUtils.createHost("127.0.0.1", ProtocolType.HTTP.getPort())) + .addHeaderElement(HttpHeaderFieldNames.CONTENT_LENGTH, String.valueOf(message.length())) + .build(message); + LOGGER.debug("postRequest:{}", postRequest); + } - private String createHeaderField(String key, String value) { - return key + ": " + value; - } + private String createHeaderField(String key, String value) { + return key + ": " + value; + } } 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 a97c7927..15d791c1 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 @@ -17,13 +17,8 @@ package com.robo4j.socket.http.test.json; import com.robo4j.socket.http.HttpMethod; -import com.robo4j.socket.http.test.codec.CameraMessage; -import com.robo4j.socket.http.test.codec.CameraMessageCodec; -import com.robo4j.socket.http.test.codec.HttpPathDTOCodec; -import com.robo4j.socket.http.test.codec.NSBETypesAndCollectionTestMessageCodec; -import com.robo4j.socket.http.test.codec.NSBETypesTestMessageCodec; -import com.robo4j.socket.http.test.codec.NSBWithSimpleCollectionsTypesMessageCodec; import com.robo4j.socket.http.dto.HttpPathMethodDTO; +import com.robo4j.socket.http.test.codec.*; import com.robo4j.socket.http.test.units.config.codec.NSBETypesAndCollectionTestMessage; import com.robo4j.socket.http.test.units.config.codec.NSBETypesTestMessage; import com.robo4j.socket.http.test.units.config.codec.NSBWithSimpleCollectionsTypesMessage; @@ -32,219 +27,224 @@ import com.robo4j.util.StreamUtils; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; -import java.util.Arrays; -import java.util.Base64; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.Map; +import java.util.*; -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.assertTrue; +import static org.junit.jupiter.api.Assertions.*; /** * @author Marcus Hirt (@hirt) * @author Miroslav Wengner (@miragemiko) */ class JsonCodecsTests { - - private static String testJson = "{\"number\":42,\"message\":\"no message\",\"active\":false," - + "\"array\":[\"one\",\"two\"],\"list\":[\"text1\",\"text2\"],\"map\":{\"key\":\"value\"}," - + "\"persons\":[{\"name\":\"name1\",\"value\":22,\"child\":{\"name\":\"name11\",\"value\":0," - + "\"child\":{\"name\":\"name111\",\"value\":42}}},{\"name\":\"name2\",\"value\":5}]," - + "\"personMap\":{\"person1\":{\"name\":\"name1\",\"value\":22,\"child\":{\"name\":\"name11\",\"value\":0," - + "\"child\":{\"name\":\"name111\",\"value\":42}}},\"person2\":{\"name\":\"name2\",\"value\":5}}}"; - - private NSBWithSimpleCollectionsTypesMessageCodec collectionsTypesMessageCodec; - private NSBETypesTestMessageCodec enumTypesMessageCodec; - private NSBETypesAndCollectionTestMessageCodec collectionEnumTypesMessageCodec; - private CameraMessageCodec cameraMessageCodec; - private HttpPathDTOCodec httpPathDTOCodec; - - @BeforeEach - void setUp() { - collectionsTypesMessageCodec = new NSBWithSimpleCollectionsTypesMessageCodec(); - enumTypesMessageCodec = new NSBETypesTestMessageCodec(); - collectionEnumTypesMessageCodec = new NSBETypesAndCollectionTestMessageCodec(); - cameraMessageCodec = new CameraMessageCodec(); - httpPathDTOCodec = new HttpPathDTOCodec(); - } - - @SuppressWarnings("unchecked") - @Test - void encodeServerPathDTOMessageNoFilterTest() { - // String expectedJson = "{\"roboUnit\":\"roboUnit1\",\"method\":\"GET\"}"; - HttpPathMethodDTO message = new HttpPathMethodDTO(); - message.setRoboUnit("roboUnit1"); - message.setMethod(HttpMethod.GET); - message.setCallbacks(Collections.EMPTY_LIST); - - String resultJson = httpPathDTOCodec.encode(message); - HttpPathMethodDTO decodedMessage = httpPathDTOCodec.decode(resultJson); - - System.out.println("resultJson: " + resultJson); - System.out.println("decodedMessage: " + decodedMessage); - - // Assert.assertTrue(expectedJson.equals(resultJson)); - assertEquals(message, decodedMessage); - } - - @Test - void encodeMessageWithEnumTypeTest() { - String expectedJson = "{\"number\":42,\"message\":\"enum type 1\",\"active\":true,\"command\":\"MOVE\"}"; - NSBETypesTestMessage message = new NSBETypesTestMessage(); - message.setNumber(42); - message.setMessage("enum type 1"); - message.setActive(true); - message.setCommand(TestCommandEnum.MOVE); - - String resultJson = enumTypesMessageCodec.encode(message); - NSBETypesTestMessage decodedMessage = enumTypesMessageCodec.decode(resultJson); - - System.out.println("resultJson: " + resultJson); - System.out.println("decodedMessage: " + decodedMessage); - assertNotNull(resultJson); - assertEquals(expectedJson, resultJson); - assertEquals(message, decodedMessage); - } - - @Test - void encodeMessageWithEnumCollectionTypeTest() { - - String expectedJson = "{\"number\":42,\"message\":\"enum type 1\",\"active\":true,\"command\":\"MOVE\",\"commands\":[\"MOVE\",\"STOP\",\"BACK\"]}"; - NSBETypesAndCollectionTestMessage message = new NSBETypesAndCollectionTestMessage(); - message.setNumber(42); - message.setMessage("enum type 1"); - message.setActive(true); - message.setCommand(TestCommandEnum.MOVE); - message.setCommands(Arrays.asList(TestCommandEnum.MOVE, TestCommandEnum.STOP, TestCommandEnum.BACK)); - - String resultJson = collectionEnumTypesMessageCodec.encode(message); - NSBETypesAndCollectionTestMessage decodeMessage = collectionEnumTypesMessageCodec.decode(expectedJson); - - System.out.println("resultJson: " + resultJson); - System.out.println("decodeMessage: " + decodeMessage); - assertNotNull(resultJson); - assertEquals(expectedJson, resultJson); - assertEquals(message, decodeMessage); - } - - @Test - void nestedObjectToJson() { - - 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); - - NSBWithSimpleCollectionsTypesMessage obj1 = new NSBWithSimpleCollectionsTypesMessage(); - obj1.setNumber(42); - obj1.setMessage("no message"); - obj1.setActive(false); - obj1.setArray(new String[] { "one", "two" }); - obj1.setList(Arrays.asList("text1", "text2")); - obj1.setMap(Collections.singletonMap("key", "value")); - obj1.setPersons(Arrays.asList(testPerson1, testPerson2)); - obj1.setPersonMap(personMap); - - long start = System.nanoTime(); - String json = collectionsTypesMessageCodec.encode(obj1); - TimeUtils.printTimeDiffNano("decodeFromJson", start); - System.out.println("JSON1: " + json); - - assertTrue(testJson.equals(json)); - - } - - @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); - - long start = System.nanoTime(); - NSBWithSimpleCollectionsTypesMessage obj1 = collectionsTypesMessageCodec.decode(testJson); - TimeUtils.printTimeDiffNano("decodeFromJson", start); - - assertEquals(Integer.valueOf(42), obj1.getNumber()); - assertEquals("no message", obj1.getMessage()); - assertTrue(!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 - void cameraCodecJsonCycleTest() { - - final byte[] imageBytes = StreamUtils.inputStreamToByteArray( - Thread.currentThread().getContextClassLoader().getResourceAsStream("snapshot.png")); - String encodeString = new String(Base64.getEncoder().encode(imageBytes)); - - CameraMessage cameraMessage = new CameraMessage(); - cameraMessage.setImage(encodeString); - cameraMessage.setType("jpg"); - cameraMessage.setValue("22"); - - long start = System.nanoTime(); - String cameraJson0 = cameraMessageCodec.encode(cameraMessage); - TimeUtils.printTimeDiffNano("cameraJson0", start); - - start = System.nanoTime(); - cameraMessageCodec.decode(cameraJson0); - TimeUtils.printTimeDiffNano("decodeCameraMessage0", start); - - start = System.nanoTime(); - String cameraJson = cameraMessageCodec.encode(cameraMessage); - TimeUtils.printTimeDiffNano("decodeFromJson", start); - System.out.println("cameraJson: " + cameraJson); - - start = System.nanoTime(); - CameraMessage codecCameraMessage = cameraMessageCodec.decode(cameraJson); - TimeUtils.printTimeDiffNano("decodeFromJson", start); - - assertEquals(cameraMessage, codecCameraMessage); - - } + private static final Logger LOGGER = LoggerFactory.getLogger(JsonCodecsTests.class); + + private static String testJson = "{\"number\":42,\"message\":\"no message\",\"active\":false," + + "\"array\":[\"one\",\"two\"],\"list\":[\"text1\",\"text2\"],\"map\":{\"key\":\"value\"}," + + "\"persons\":[{\"name\":\"name1\",\"value\":22,\"child\":{\"name\":\"name11\",\"value\":0," + + "\"child\":{\"name\":\"name111\",\"value\":42}}},{\"name\":\"name2\",\"value\":5}]," + + "\"personMap\":{\"person1\":{\"name\":\"name1\",\"value\":22,\"child\":{\"name\":\"name11\",\"value\":0," + + "\"child\":{\"name\":\"name111\",\"value\":42}}},\"person2\":{\"name\":\"name2\",\"value\":5}}}"; + + private NSBWithSimpleCollectionsTypesMessageCodec collectionsTypesMessageCodec; + private NSBETypesTestMessageCodec enumTypesMessageCodec; + private NSBETypesAndCollectionTestMessageCodec collectionEnumTypesMessageCodec; + private CameraMessageCodec cameraMessageCodec; + private HttpPathDTOCodec httpPathDTOCodec; + + @BeforeEach + void setUp() { + collectionsTypesMessageCodec = new NSBWithSimpleCollectionsTypesMessageCodec(); + enumTypesMessageCodec = new NSBETypesTestMessageCodec(); + collectionEnumTypesMessageCodec = new NSBETypesAndCollectionTestMessageCodec(); + cameraMessageCodec = new CameraMessageCodec(); + httpPathDTOCodec = new HttpPathDTOCodec(); + } + + @SuppressWarnings("unchecked") + @Test + void encodeServerPathDTOMessageNoFilterTest() { + // String expectedJson = "{\"roboUnit\":\"roboUnit1\",\"method\":\"GET\"}"; + HttpPathMethodDTO message = new HttpPathMethodDTO(); + message.setRoboUnit("roboUnit1"); + message.setMethod(HttpMethod.GET); + message.setCallbacks(Collections.EMPTY_LIST); + + String resultJson = httpPathDTOCodec.encode(message); + HttpPathMethodDTO decodedMessage = httpPathDTOCodec.decode(resultJson); + + printJson(resultJson); + printDecodedMessage(decodedMessage); + + // Assert.assertTrue(expectedJson.equals(resultJson)); + assertEquals(message, decodedMessage); + } + + @Test + void encodeMessageWithEnumTypeTest() { + String expectedJson = "{\"number\":42,\"message\":\"enum type 1\",\"active\":true,\"command\":\"MOVE\"}"; + NSBETypesTestMessage message = new NSBETypesTestMessage(); + message.setNumber(42); + message.setMessage("enum type 1"); + message.setActive(true); + message.setCommand(TestCommandEnum.MOVE); + + String resultJson = enumTypesMessageCodec.encode(message); + NSBETypesTestMessage decodedMessage = enumTypesMessageCodec.decode(resultJson); + + printJson(resultJson); + printDecodedMessage(decodedMessage); + assertNotNull(resultJson); + assertEquals(expectedJson, resultJson); + assertEquals(message, decodedMessage); + } + + @Test + void encodeMessageWithEnumCollectionTypeTest() { + + String expectedJson = "{\"number\":42,\"message\":\"enum type 1\",\"active\":true,\"command\":\"MOVE\",\"commands\":[\"MOVE\",\"STOP\",\"BACK\"]}"; + NSBETypesAndCollectionTestMessage message = new NSBETypesAndCollectionTestMessage(); + message.setNumber(42); + message.setMessage("enum type 1"); + message.setActive(true); + message.setCommand(TestCommandEnum.MOVE); + message.setCommands(Arrays.asList(TestCommandEnum.MOVE, TestCommandEnum.STOP, TestCommandEnum.BACK)); + + String resultJson = collectionEnumTypesMessageCodec.encode(message); + NSBETypesAndCollectionTestMessage decodedMessage = collectionEnumTypesMessageCodec.decode(expectedJson); + + + printJson(resultJson); + printDecodedMessage(decodedMessage); + assertNotNull(resultJson); + assertEquals(expectedJson, resultJson); + assertEquals(message, decodedMessage); + } + + @Test + void nestedObjectToJson() { + + 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); + + NSBWithSimpleCollectionsTypesMessage obj1 = new NSBWithSimpleCollectionsTypesMessage(); + obj1.setNumber(42); + obj1.setMessage("no message"); + obj1.setActive(false); + obj1.setArray(new String[]{"one", "two"}); + obj1.setList(Arrays.asList("text1", "text2")); + obj1.setMap(Collections.singletonMap("key", "value")); + obj1.setPersons(Arrays.asList(testPerson1, testPerson2)); + obj1.setPersonMap(personMap); + + long start = System.nanoTime(); + String json = collectionsTypesMessageCodec.encode(obj1); + TimeUtils.printTimeDiffNano("decodeFromJson", start); + printJson(json); + + assertEquals(testJson, json); + + } + + @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); + + long start = System.nanoTime(); + NSBWithSimpleCollectionsTypesMessage obj1 = collectionsTypesMessageCodec.decode(testJson); + TimeUtils.printTimeDiffNano("decodeFromJson", start); + + assertEquals(Integer.valueOf(42), obj1.getNumber()); + assertEquals("no message", obj1.getMessage()); + assertTrue(!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 + void cameraCodecJsonCycleTest() { + + final byte[] imageBytes = StreamUtils.inputStreamToByteArray( + Thread.currentThread().getContextClassLoader().getResourceAsStream("snapshot.png")); + String encodeString = new String(Base64.getEncoder().encode(imageBytes)); + + CameraMessage cameraMessage = new CameraMessage(); + cameraMessage.setImage(encodeString); + cameraMessage.setType("jpg"); + cameraMessage.setValue("22"); + + long start = System.nanoTime(); + String cameraJson0 = cameraMessageCodec.encode(cameraMessage); + TimeUtils.printTimeDiffNano("cameraJson0", start); + + start = System.nanoTime(); + cameraMessageCodec.decode(cameraJson0); + TimeUtils.printTimeDiffNano("decodeCameraMessage0", start); + + start = System.nanoTime(); + String cameraJson = cameraMessageCodec.encode(cameraMessage); + TimeUtils.printTimeDiffNano("decodeFromJson", start); + printJson(cameraJson); + + start = System.nanoTime(); + CameraMessage codecCameraMessage = cameraMessageCodec.decode(cameraJson); + TimeUtils.printTimeDiffNano("decodeFromJson", start); + + assertEquals(cameraMessage, codecCameraMessage); + + } + + private static void printDecodedMessage(T decodedMessage) { + LOGGER.debug("decodedMessage:{}", decodedMessage); + } + + private static void printJson(String resultJson) { + LOGGER.debug("resultJson:{}", resultJson); + } } diff --git a/robo4j-socket-http/src/test/java/com/robo4j/socket/http/test/json/JsonReaderArrayTests.java b/robo4j-socket-http/src/test/java/com/robo4j/socket/http/test/json/JsonReaderArrayTests.java index 23f0e7a5..95ae3b52 100644 --- a/robo4j-socket-http/src/test/java/com/robo4j/socket/http/test/json/JsonReaderArrayTests.java +++ b/robo4j-socket-http/src/test/java/com/robo4j/socket/http/test/json/JsonReaderArrayTests.java @@ -19,11 +19,14 @@ import com.robo4j.socket.http.json.JsonDocument; import com.robo4j.socket.http.json.JsonReader; 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 com.robo4j.socket.http.test.json.JsonReaderTests.printDocument; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -32,200 +35,201 @@ * @author Miroslav Wengner (@miragemiko) */ class JsonReaderArrayTests { - - private static final String jsonArrayStringOnly = "[\"one\", \"two\" , \"three\"]"; - private static final String jsonArrayIntegerOnly = "[ 1,2,3 ,4, 5 , 6, 7]"; - private static final String jsonArrayBooleanOnly = "[ true, false, false, false, true]"; - private static final String jsonArrayNumberOnly = "[ 0.2, 0.1, 0.3]"; - private static final String jsonArrayObjectOnly = "[{\"name\":\"name1\",\"value\":42}, {\"name\":\"name2\",\"value\":22}, " - + "{\"name\":\"name3\",\"value\":8}]"; - private static final String jsonArrayOfArraysStringsOnly = "[[\"one\" ,\"two\", \"three\"] , [\"one\",\"two\"],[\"one\"]]"; - private static final String jsonArrayOfArraysIntegersOnly = "[[ 1 , 2, 3] , [1,2],[1]]"; - private static final String jsonArrayOfArraysBooleansOnly = "[[ true, false, true] , [true, false],[true]]"; - private static final String jsonArrayOfArraysObjectsOnly = "[[ {\"name\":\"name11\",\"value\":11}, " - + "{\"name\":\"name12\",\"value\":12}, {\"name\":\"name13\",\"value\":13}] , [{\"name\":\"name21\",\"value\":21}, " - + "{\"name\":\"name22\",\"value\":22}],[{\"name\":\"name31\",\"value\":31}]]"; - - private static final String jsonArrayOfArraysObjectsWithObjectWithArray = "[[ {\"name\":\"name11\",\"value\":11}, " - + "{\"name\":\"name12\",\"value\":12}, {\"name\":\"name13\",\"value\":13}] , [{\"name\":\"name21\",\"value\":21}, " - + "{\"name\":\"name22\",\"value\":22}],[{\"name\":\"name31\",\"value\":31, \"array\":[31,32,33], " - + "\"child\":{\"name\":\"name311\", \"array\":[31,32,33]}}]]"; - - @Test - void basicArrayStringOnlyTest() { - JsonReader parser = new JsonReader(jsonArrayStringOnly); - JsonDocument document = parser.read(); - - System.out.println("DOC: " + document); - List testArray = Arrays.asList("one", "two", "three"); - assertEquals(JsonDocument.Type.ARRAY, document.getType()); - assertEquals(testArray.size(), document.getArray().size()); - assertTrue(document.getArray().containsAll(testArray)); - } - - @Test - void basicArrayBooleanOnlyTest() { - JsonReader parser = new JsonReader(jsonArrayBooleanOnly); - JsonDocument document = parser.read(); - - List testArray = Arrays.asList(true, false, false, false, true); - assertEquals(JsonDocument.Type.ARRAY, document.getType()); - assertEquals(testArray.size(), document.getArray().size()); - assertTrue(document.getArray().containsAll(testArray)); - } - - @Test - void basicArrayIntegerOnlyTest() { - JsonReader parser = new JsonReader(jsonArrayIntegerOnly); - JsonDocument document = parser.read(); - - System.out.println("DOC: " + document); - List testArray = Arrays.asList(1, 2, 3, 4, 5, 6, 7); - assertEquals(JsonDocument.Type.ARRAY, document.getType()); - assertEquals(testArray.size(), document.getArray().size()); - assertTrue(document.getArray().containsAll(testArray)); - } - - @Test - void basicArrayNumberOnlyTest() { - JsonReader parser = new JsonReader(jsonArrayNumberOnly); - JsonDocument document = parser.read(); - - List testArray = Arrays.asList(0.2, 0.1, 0.3); - assertEquals(JsonDocument.Type.ARRAY, document.getType()); - assertEquals(testArray.size(), document.getArray().size()); - assertTrue(document.getArray().containsAll(testArray)); - } - - @Test - void basicArrayObjectOnlyTest() { - - JsonDocument jsonDocumentChild1 = new JsonDocument(JsonDocument.Type.OBJECT); - jsonDocumentChild1.put("name", "name1"); - jsonDocumentChild1.put("value", 42); - - JsonDocument jsonDocumentChild2 = new JsonDocument(JsonDocument.Type.OBJECT); - jsonDocumentChild2.put("name", "name2"); - jsonDocumentChild2.put("value", 22); - - JsonDocument jsonDocumentChild3 = new JsonDocument(JsonDocument.Type.OBJECT); - jsonDocumentChild3.put("name", "name3"); - jsonDocumentChild3.put("value", 8); - - List expectedArrayResult = Arrays.asList(jsonDocumentChild1, jsonDocumentChild2, - jsonDocumentChild3); - - JsonReader parser = new JsonReader(jsonArrayObjectOnly); - JsonDocument document = parser.read(); - - System.out.println("DOC: " + document); - assertEquals(JsonDocument.Type.ARRAY, document.getType()); - assertEquals(expectedArrayResult.size(), document.getArray().size()); - assertTrue(document.getArray().containsAll(expectedArrayResult)); - } - - @Test - void basicArrayOfArrayStringOnlyTest() { - - List stringArray1 = Arrays.asList("one", "two", "three"); - List stringArray2 = Arrays.asList("one", "two"); - List stringArray3 = Collections.singletonList("one"); - JsonReader parser = new JsonReader(jsonArrayOfArraysStringsOnly); - JsonDocument document = parser.read(); - - assertTrue(compareArrays(stringArray1, document, 0)); - assertTrue(compareArrays(stringArray2, document, 1)); - assertTrue(compareArrays(stringArray3, document, 2)); - System.out.println("DOC: " + document); - } - - @Test - void basicArrayOfArraysIntegersOnlyTest() { - List stringArray1 = Arrays.asList(1, 2, 3); - List stringArray2 = Arrays.asList(1, 2); - List stringArray3 = Collections.singletonList(1); - - JsonReader parser = new JsonReader(jsonArrayOfArraysIntegersOnly); - JsonDocument document = parser.read(); - - assertTrue(compareArrays(stringArray1, document, 0)); - assertTrue(compareArrays(stringArray2, document, 1)); - assertTrue(compareArrays(stringArray3, document, 2)); - System.out.println("DOC: " + document); - } - - @Test - void basicArrayOfArraysBooleanOnlyTest() { - List stringArray1 = Arrays.asList(true, false, true); - List stringArray2 = Arrays.asList(true, false); - List stringArray3 = Collections.singletonList(true); - - JsonReader parser = new JsonReader(jsonArrayOfArraysBooleansOnly); - JsonDocument document = parser.read(); - - assertTrue(compareArrays(stringArray1, document, 0)); - assertTrue(compareArrays(stringArray2, document, 1)); - assertTrue(compareArrays(stringArray3, document, 2)); - System.out.println("DOC: " + document); - } - - @Test - void basicArrayOfArraysObjectsOnlyTest() { - List array1 = Arrays.asList(testObjectJsonDocument(11), testObjectJsonDocument(12), - testObjectJsonDocument(13)); - List array2 = Arrays.asList(testObjectJsonDocument(21), testObjectJsonDocument(22)); - List array3 = Collections.singletonList(testObjectJsonDocument(31)); - - JsonReader parser = new JsonReader(jsonArrayOfArraysObjectsOnly); - JsonDocument document = parser.read(); - - assertTrue(compareArrays(array1, document, 0)); - assertTrue(compareArrays(array2, document, 1)); - assertTrue(compareArrays(array3, document, 2)); - - System.out.println("DOC: " + document); - } - - @Test - void basicArrayOfArraysObjectsWithObjectWithArrayTest() { - List array1 = Arrays.asList(testObjectJsonDocument(11), testObjectJsonDocument(12), - testObjectJsonDocument(13)); - List array2 = Arrays.asList(testObjectJsonDocument(21), testObjectJsonDocument(22)); - - JsonDocument lastJsonDocument = testObjectJsonDocument(31); - JsonDocument lastJsonDocumentArray = new JsonDocument(JsonDocument.Type.ARRAY); - lastJsonDocumentArray.add(31); - lastJsonDocumentArray.add(32); - lastJsonDocumentArray.add(33); - JsonDocument lastJsonDocumentObject = new JsonDocument(JsonDocument.Type.OBJECT); - lastJsonDocumentObject.put("name", "name311"); - lastJsonDocumentObject.put("array", lastJsonDocumentArray); - lastJsonDocument.put("array", lastJsonDocumentArray); - lastJsonDocument.put("child", lastJsonDocumentObject); - List array3 = Collections.singletonList(lastJsonDocument); - - JsonReader parser = new JsonReader(jsonArrayOfArraysObjectsWithObjectWithArray); - long start = System.nanoTime(); - JsonDocument document = parser.read(); - TimeUtils.printTimeDiffNano("robo4j:", start); - - assertTrue(compareArrays(array1, document, 0)); - assertTrue(compareArrays(array2, document, 1)); - assertTrue(compareArrays(array3, document, 2)); - - System.out.println("DOC: " + document); - } - - private boolean compareArrays(List sourceArray, JsonDocument arrayDocument, int index) { - JsonDocument desiredArrayDocument = (JsonDocument) arrayDocument.getArray().get(index); - assertEquals(JsonDocument.Type.ARRAY, desiredArrayDocument.getType()); - return sourceArray.containsAll(desiredArrayDocument.getArray()); - } - - private JsonDocument testObjectJsonDocument(Integer value) { - JsonDocument result = new JsonDocument(JsonDocument.Type.OBJECT); - result.put("name", "name" + value); - result.put("value", value); - return result; - } + private static final Logger LOGGER = LoggerFactory.getLogger(JsonReaderArrayTests.class); + + private static final String jsonArrayStringOnly = "[\"one\", \"two\" , \"three\"]"; + private static final String jsonArrayIntegerOnly = "[ 1,2,3 ,4, 5 , 6, 7]"; + private static final String jsonArrayBooleanOnly = "[ true, false, false, false, true]"; + private static final String jsonArrayNumberOnly = "[ 0.2, 0.1, 0.3]"; + private static final String jsonArrayObjectOnly = "[{\"name\":\"name1\",\"value\":42}, {\"name\":\"name2\",\"value\":22}, " + + "{\"name\":\"name3\",\"value\":8}]"; + private static final String jsonArrayOfArraysStringsOnly = "[[\"one\" ,\"two\", \"three\"] , [\"one\",\"two\"],[\"one\"]]"; + private static final String jsonArrayOfArraysIntegersOnly = "[[ 1 , 2, 3] , [1,2],[1]]"; + private static final String jsonArrayOfArraysBooleansOnly = "[[ true, false, true] , [true, false],[true]]"; + private static final String jsonArrayOfArraysObjectsOnly = "[[ {\"name\":\"name11\",\"value\":11}, " + + "{\"name\":\"name12\",\"value\":12}, {\"name\":\"name13\",\"value\":13}] , [{\"name\":\"name21\",\"value\":21}, " + + "{\"name\":\"name22\",\"value\":22}],[{\"name\":\"name31\",\"value\":31}]]"; + + private static final String jsonArrayOfArraysObjectsWithObjectWithArray = "[[ {\"name\":\"name11\",\"value\":11}, " + + "{\"name\":\"name12\",\"value\":12}, {\"name\":\"name13\",\"value\":13}] , [{\"name\":\"name21\",\"value\":21}, " + + "{\"name\":\"name22\",\"value\":22}],[{\"name\":\"name31\",\"value\":31, \"array\":[31,32,33], " + + "\"child\":{\"name\":\"name311\", \"array\":[31,32,33]}}]]"; + + @Test + void basicArrayStringOnlyTest() { + var parser = new JsonReader(jsonArrayStringOnly); + var document = parser.read(); + var testArray = Arrays.asList("one", "two", "three"); + + printDocument(document); + assertEquals(JsonDocument.Type.ARRAY, document.getType()); + assertEquals(testArray.size(), document.getArray().size()); + assertTrue(document.getArray().containsAll(testArray)); + } + + @Test + void basicArrayBooleanOnlyTest() { + JsonReader parser = new JsonReader(jsonArrayBooleanOnly); + JsonDocument document = parser.read(); + List testArray = Arrays.asList(true, false, false, false, true); + + assertEquals(JsonDocument.Type.ARRAY, document.getType()); + assertEquals(testArray.size(), document.getArray().size()); + assertTrue(document.getArray().containsAll(testArray)); + } + + @Test + void basicArrayIntegerOnlyTest() { + var parser = new JsonReader(jsonArrayIntegerOnly); + var document = parser.read(); + var testArray = Arrays.asList(1, 2, 3, 4, 5, 6, 7); + + printDocument(document); + assertEquals(JsonDocument.Type.ARRAY, document.getType()); + assertEquals(testArray.size(), document.getArray().size()); + assertTrue(document.getArray().containsAll(testArray)); + } + + @Test + void basicArrayNumberOnlyTest() { + var parser = new JsonReader(jsonArrayNumberOnly); + var document = parser.read(); + var testArray = Arrays.asList(0.2, 0.1, 0.3); + + assertEquals(JsonDocument.Type.ARRAY, document.getType()); + assertEquals(testArray.size(), document.getArray().size()); + assertTrue(document.getArray().containsAll(testArray)); + } + + @Test + void basicArrayObjectOnlyTest() { + + JsonDocument jsonDocumentChild1 = new JsonDocument(JsonDocument.Type.OBJECT); + jsonDocumentChild1.put("name", "name1"); + jsonDocumentChild1.put("value", 42); + + JsonDocument jsonDocumentChild2 = new JsonDocument(JsonDocument.Type.OBJECT); + jsonDocumentChild2.put("name", "name2"); + jsonDocumentChild2.put("value", 22); + + JsonDocument jsonDocumentChild3 = new JsonDocument(JsonDocument.Type.OBJECT); + jsonDocumentChild3.put("name", "name3"); + jsonDocumentChild3.put("value", 8); + + List expectedArrayResult = Arrays.asList(jsonDocumentChild1, jsonDocumentChild2, + jsonDocumentChild3); + + JsonReader parser = new JsonReader(jsonArrayObjectOnly); + JsonDocument document = parser.read(); + + printDocument(document); + assertEquals(JsonDocument.Type.ARRAY, document.getType()); + assertEquals(expectedArrayResult.size(), document.getArray().size()); + assertTrue(document.getArray().containsAll(expectedArrayResult)); + } + + @Test + void basicArrayOfArrayStringOnlyTest() { + + List stringArray1 = Arrays.asList("one", "two", "three"); + List stringArray2 = Arrays.asList("one", "two"); + List stringArray3 = Collections.singletonList("one"); + JsonReader parser = new JsonReader(jsonArrayOfArraysStringsOnly); + JsonDocument document = parser.read(); + + assertTrue(compareArrays(stringArray1, document, 0)); + assertTrue(compareArrays(stringArray2, document, 1)); + assertTrue(compareArrays(stringArray3, document, 2)); + printDocument(document); + } + + @Test + void basicArrayOfArraysIntegersOnlyTest() { + List stringArray1 = Arrays.asList(1, 2, 3); + List stringArray2 = Arrays.asList(1, 2); + List stringArray3 = Collections.singletonList(1); + + JsonReader parser = new JsonReader(jsonArrayOfArraysIntegersOnly); + JsonDocument document = parser.read(); + + assertTrue(compareArrays(stringArray1, document, 0)); + assertTrue(compareArrays(stringArray2, document, 1)); + assertTrue(compareArrays(stringArray3, document, 2)); + printDocument(document); + } + + @Test + void basicArrayOfArraysBooleanOnlyTest() { + List stringArray1 = Arrays.asList(true, false, true); + List stringArray2 = Arrays.asList(true, false); + List stringArray3 = Collections.singletonList(true); + + JsonReader parser = new JsonReader(jsonArrayOfArraysBooleansOnly); + JsonDocument document = parser.read(); + + assertTrue(compareArrays(stringArray1, document, 0)); + assertTrue(compareArrays(stringArray2, document, 1)); + assertTrue(compareArrays(stringArray3, document, 2)); + printDocument(document); + } + + @Test + void basicArrayOfArraysObjectsOnlyTest() { + List array1 = Arrays.asList(testObjectJsonDocument(11), testObjectJsonDocument(12), + testObjectJsonDocument(13)); + List array2 = Arrays.asList(testObjectJsonDocument(21), testObjectJsonDocument(22)); + List array3 = Collections.singletonList(testObjectJsonDocument(31)); + + JsonReader parser = new JsonReader(jsonArrayOfArraysObjectsOnly); + JsonDocument document = parser.read(); + + assertTrue(compareArrays(array1, document, 0)); + assertTrue(compareArrays(array2, document, 1)); + assertTrue(compareArrays(array3, document, 2)); + + printDocument(document); + } + + @Test + void basicArrayOfArraysObjectsWithObjectWithArrayTest() { + List array1 = Arrays.asList(testObjectJsonDocument(11), testObjectJsonDocument(12), + testObjectJsonDocument(13)); + List array2 = Arrays.asList(testObjectJsonDocument(21), testObjectJsonDocument(22)); + + JsonDocument lastJsonDocument = testObjectJsonDocument(31); + JsonDocument lastJsonDocumentArray = new JsonDocument(JsonDocument.Type.ARRAY); + lastJsonDocumentArray.add(31); + lastJsonDocumentArray.add(32); + lastJsonDocumentArray.add(33); + JsonDocument lastJsonDocumentObject = new JsonDocument(JsonDocument.Type.OBJECT); + lastJsonDocumentObject.put("name", "name311"); + lastJsonDocumentObject.put("array", lastJsonDocumentArray); + lastJsonDocument.put("array", lastJsonDocumentArray); + lastJsonDocument.put("child", lastJsonDocumentObject); + List array3 = Collections.singletonList(lastJsonDocument); + + JsonReader parser = new JsonReader(jsonArrayOfArraysObjectsWithObjectWithArray); + long start = System.nanoTime(); + JsonDocument document = parser.read(); + TimeUtils.printTimeDiffNano("robo4j:", start); + + assertTrue(compareArrays(array1, document, 0)); + assertTrue(compareArrays(array2, document, 1)); + assertTrue(compareArrays(array3, document, 2)); + + printDocument(document); + } + + private boolean compareArrays(List sourceArray, JsonDocument arrayDocument, int index) { + JsonDocument desiredArrayDocument = (JsonDocument) arrayDocument.getArray().get(index); + assertEquals(JsonDocument.Type.ARRAY, desiredArrayDocument.getType()); + return sourceArray.containsAll(desiredArrayDocument.getArray()); + } + + private JsonDocument testObjectJsonDocument(Integer value) { + JsonDocument result = new JsonDocument(JsonDocument.Type.OBJECT); + result.put("name", "name" + value); + result.put("value", value); + return result; + } } diff --git a/robo4j-socket-http/src/test/java/com/robo4j/socket/http/test/json/JsonReaderTests.java b/robo4j-socket-http/src/test/java/com/robo4j/socket/http/test/json/JsonReaderTests.java index 29da36e8..a80e478e 100644 --- a/robo4j-socket-http/src/test/java/com/robo4j/socket/http/test/json/JsonReaderTests.java +++ b/robo4j-socket-http/src/test/java/com/robo4j/socket/http/test/json/JsonReaderTests.java @@ -19,320 +19,331 @@ import com.robo4j.socket.http.json.JsonDocument; import com.robo4j.socket.http.json.JsonReader; import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.Arrays; import java.util.List; import java.util.Map; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.*; /** * @author Marcus Hirt (@hirt) * @author Miroslav Wengner (@miragemiko) */ class JsonReaderTests { + private static final Logger LOGGER = LoggerFactory.getLogger(JsonReaderTests.class); + + private static final String jsonBooleanValues = "{\"number\":22,\"message\":\"no message\",\"active\":true,\"passive\": false, \"bool1\":false,\"bool2\" :true}"; + private static final String jsonBasicValues = "{ \"number\"\n : 42, \"message\" \t: \"no message\", \"active\" : false , \"floatNumber\" : 0.42}"; + private static final String jsonBasicMinusValues = "{ \"number\"\n : -42, \"message\" \t: \"no message\", \"active\" : false , \"floatNumber\" : -0.42}"; + private static final String jsonBasicValuesWithNullValues = "{ \"number\"\n : 42, \"message\" \t: \"no message\"," + + " \"active\" : false , \"floatNumber\" : 0.42, \"empty1\":null, \"empty2\" : null }"; + private static final String jsonBasicValueWithStringArray = "{ \"floatNumber\" : 0.42, \"number\"\n : 42, \"active\" : false, " + + "\"message\" \t: \"no message\", \"arrayOne\":[\"one\",\"two\"]}"; + private static final String jsonBasicValueWithStringAndIntegerArrays = "{ \"floatNumber\" : 0.42, \"number\"\n : 42, " + + "\"active\" : false, \"message\" \t: \"no message\", \"arrayOne\":[\"one\", \"two\"], \"arrayTwo\" : [1, 2 ,3 ]}"; + private static final String jsonBasicValueWithStringAndIntegerAndObjectArrays = "{ \"floatNumber\" : 0.42, \"number\"\n : 42, " + + "\"arrayOne\":[\"one\", \"two\"], \"message\" \t: \"no message\", \"arrayTwo\" : [1, 2 ,3 ], " + + "\"arrayThree\" : [{\"name\":\"name1\",\"value\": 22}, {\"name\":\"name2\",\"value\": 42}], \"active\" : false}"; - private static final String jsonBooleanValues = "{\"number\":22,\"message\":\"no message\",\"active\":true,\"passive\": false, \"bool1\":false,\"bool2\" :true}"; - private static final String jsonBasicValues = "{ \"number\"\n : 42, \"message\" \t: \"no message\", \"active\" : false , \"floatNumber\" : 0.42}"; - private static final String jsonBasicMinusValues = "{ \"number\"\n : -42, \"message\" \t: \"no message\", \"active\" : false , \"floatNumber\" : -0.42}"; - private static final String jsonBasicValuesWithNullValues = "{ \"number\"\n : 42, \"message\" \t: \"no message\"," - + " \"active\" : false , \"floatNumber\" : 0.42, \"empty1\":null, \"empty2\" : null }"; - private static final String jsonBasicValueWithStringArray = "{ \"floatNumber\" : 0.42, \"number\"\n : 42, \"active\" : false, " - + "\"message\" \t: \"no message\", \"arrayOne\":[\"one\",\"two\"]}"; - private static final String jsonBasicValueWithStringAndIntegerArrays = "{ \"floatNumber\" : 0.42, \"number\"\n : 42, " - + "\"active\" : false, \"message\" \t: \"no message\", \"arrayOne\":[\"one\", \"two\"], \"arrayTwo\" : [1, 2 ,3 ]}"; - private static final String jsonBasicValueWithStringAndIntegerAndObjectArrays = "{ \"floatNumber\" : 0.42, \"number\"\n : 42, " - + "\"arrayOne\":[\"one\", \"two\"], \"message\" \t: \"no message\", \"arrayTwo\" : [1, 2 ,3 ], " - + "\"arrayThree\" : [{\"name\":\"name1\",\"value\": 22}, {\"name\":\"name2\",\"value\": 42}], \"active\" : false}"; - - private static final String jsonBasicValueAndObjectValueWithStringAndIntegerAndObjectArrays = "{ \"floatNumber\" : 0.42, \"number\"\n : 42, " - + "\"arrayOne\":[\"one\", \"two\"], \"message\" \t: \"no message\", \"arrayTwo\" : [1, 2 ,3 ], " - + "\"arrayThree\" : [{\"name\":\"name1\",\"value\": 22}, {\"name\":\"name2\",\"value\": 42}], \"active\" : false," - + "\"child\" :{\"name\":\"name11\",\"value\":1} }"; - - private static final String jsonArrayIntegerStringObject = "{\"arrayString\" : [\"one\", \"two\", \"three\"], \"arrayInteger\":[1,2,3]}"; - - private static final String jsonNestedObjects = "{\"value\" : { \"floatNumber\" : 0.42, \"object1\" : {\"name\" : \"some\"}}}"; - private static final String jsonNestedObjectAndArrayObject = "{\"arrayThree\" : [{\"name\":\"name1\",\"value\": 22}, {\"name\":\"name2\",\"value\": 42}]}"; - private static final String jsonNestedObjectWithBasicValueWithStringArray = "{\"value\" : { \"floatNumber\" : 0.42, \"number\"\n : 42, \"active\" : false, " - + "\"message\" \t: \"no message\", \"arrayOne\":[\"one\",\"two\"]}}"; - - private static final String jsonNestedObject2BasicValueWithStringArray = "{\"name\" : \"nestedName1\", \"object1\" : {\"value\" : " - + "{ \"floatNumber\" : 0.42, \"number\"\n : 42, \"active\" : false, \"message\" \t: \"no message\", \"arrayOne\":[\"one\",\"two\"]}}}"; - - @Test - void basicBooleanValuesTest() { - - long start = System.nanoTime(); - JsonReader parser = new JsonReader(jsonBooleanValues); - JsonDocument document = parser.read(); - TimeUtils.printTimeDiffNano("basicBooleanValues robo4j", start); - - System.out.println("DOC: " + document); - - assertEquals(JsonDocument.Type.OBJECT, document.getType()); - assertEquals(22, document.getKey("number")); - assertEquals("no message", document.getKey("message")); - assertEquals(true, document.getKey("active")); - assertEquals(false, document.getKey("passive")); - assertEquals(false, document.getKey("bool1")); - assertEquals(true, document.getKey("bool2")); - - } - - @Test - public void basicAndNullValues() { - JsonReader parser = new JsonReader(jsonBasicValuesWithNullValues); - JsonDocument document = parser.read(); - Map map = document.getMap(); + private static final String jsonBasicValueAndObjectValueWithStringAndIntegerAndObjectArrays = "{ \"floatNumber\" : 0.42, \"number\"\n : 42, " + + "\"arrayOne\":[\"one\", \"two\"], \"message\" \t: \"no message\", \"arrayTwo\" : [1, 2 ,3 ], " + + "\"arrayThree\" : [{\"name\":\"name1\",\"value\": 22}, {\"name\":\"name2\",\"value\": 42}], \"active\" : false," + + "\"child\" :{\"name\":\"name11\",\"value\":1} }"; + + private static final String jsonArrayIntegerStringObject = "{\"arrayString\" : [\"one\", \"two\", \"three\"], \"arrayInteger\":[1,2,3]}"; - System.out.println("DOC: " + document); - assertEquals(JsonDocument.Type.OBJECT, document.getType()); - assertEquals(42, map.get("number")); - assertEquals("no message", map.get("message")); - assertEquals(false, map.get("active")); - assertEquals(0.42, map.get("floatNumber")); - assertNull(map.get("empty1")); - assertNull(map.get("empty2")); - } - - @Test - void basicArrayIntegerStringTest() { - JsonReader parser = new JsonReader(jsonArrayIntegerStringObject); - JsonDocument document = parser.read(); - Map map = document.getMap(); - - List arrayString = ((JsonDocument) map.get("arrayString")).getArray(); - List arrayInteger = ((JsonDocument) map.get("arrayInteger")).getArray(); - - assertEquals(JsonDocument.Type.OBJECT, document.getType()); - assertTrue((Arrays.asList("one", "two", "three").containsAll(arrayString))); - assertTrue((Arrays.asList(1, 2, 3).containsAll(arrayInteger))); - System.out.println("DOC: " + document); - } - - @Test - void basicNestedObjectWithStringArray() { + private static final String jsonNestedObjects = "{\"value\" : { \"floatNumber\" : 0.42, \"object1\" : {\"name\" : \"some\"}}}"; + private static final String jsonNestedObjectAndArrayObject = "{\"arrayThree\" : [{\"name\":\"name1\",\"value\": 22}, {\"name\":\"name2\",\"value\": 42}]}"; + private static final String jsonNestedObjectWithBasicValueWithStringArray = "{\"value\" : { \"floatNumber\" : 0.42, \"number\"\n : 42, \"active\" : false, " + + "\"message\" \t: \"no message\", \"arrayOne\":[\"one\",\"two\"]}}"; - JsonDocument nestedJsonDocument2 = new JsonDocument(JsonDocument.Type.OBJECT); - nestedJsonDocument2.put("name", "some"); - - JsonDocument nestedJsonDocument1 = new JsonDocument(JsonDocument.Type.OBJECT); - nestedJsonDocument1.put("floatNumber", 0.42); - nestedJsonDocument1.put("object1", nestedJsonDocument2); - - JsonReader parser = new JsonReader(jsonNestedObjects); - JsonDocument document = parser.read(); - - assertEquals(JsonDocument.Type.OBJECT, document.getType()); - assertEquals(nestedJsonDocument1, document.getKey("value")); - - System.out.println("document: " + document); - - } - - @Test - void basicNestedObjectValuesAndObjectArray() { - - JsonDocument nestedJsonDocument21 = new JsonDocument(JsonDocument.Type.OBJECT); - nestedJsonDocument21.put("name", "name1"); - nestedJsonDocument21.put("value", 22); - - JsonDocument nestedJsonDocument22 = new JsonDocument(JsonDocument.Type.OBJECT); - nestedJsonDocument22.put("name", "name2"); - nestedJsonDocument22.put("value", 42); - - JsonDocument nestedJsonDocument2 = new JsonDocument(JsonDocument.Type.ARRAY); - nestedJsonDocument2.add(nestedJsonDocument21); - nestedJsonDocument2.add(nestedJsonDocument22); - - JsonDocument nestedJsonDocument1 = new JsonDocument(JsonDocument.Type.OBJECT); - nestedJsonDocument1.put("arrayThree", nestedJsonDocument2); - - JsonReader parser = new JsonReader(jsonNestedObjectAndArrayObject); - JsonDocument document = parser.read(); - - JsonDocument arrayJsonDocument = (JsonDocument) document.getKey("arrayThree"); - - assertEquals(JsonDocument.Type.OBJECT, document.getType()); - assertEquals(JsonDocument.Type.ARRAY, arrayJsonDocument.getType()); - assertEquals(nestedJsonDocument2, document.getKey("arrayThree")); - System.out.println("document: " + document); - } - - @Test - void basicNestedObjectWithBasicValueWithStringArray() { - - JsonDocument nestedJsonDocument2 = new JsonDocument(JsonDocument.Type.ARRAY); - nestedJsonDocument2.add("one"); - nestedJsonDocument2.add("two"); - - JsonDocument nestedJsonDocument1 = new JsonDocument(JsonDocument.Type.OBJECT); - nestedJsonDocument1.put("floatNumber", 0.42); - nestedJsonDocument1.put("number", 42); - nestedJsonDocument1.put("active", false); - nestedJsonDocument1.put("message", "no message"); - nestedJsonDocument1.put("arrayOne", nestedJsonDocument2); - - JsonReader parser = new JsonReader(jsonNestedObjectWithBasicValueWithStringArray); - JsonDocument document = parser.read(); - - JsonDocument nestedArray = ((JsonDocument) ((JsonDocument) document.getKey("value")).getKey("arrayOne")); - - assertEquals(JsonDocument.Type.OBJECT, document.getType()); - assertEquals(nestedJsonDocument1, document.getKey("value")); - assertEquals(JsonDocument.Type.ARRAY, nestedArray.getType()); - System.out.println("document: " + document); - - } - - @Test - void basicNestedObject2WithBasicValueWithStringArray() { - - JsonDocument nestedJsonDocument4 = new JsonDocument(JsonDocument.Type.ARRAY); - nestedJsonDocument4.add("one"); - nestedJsonDocument4.add("two"); - - JsonDocument nestedJsonDocument3 = new JsonDocument(JsonDocument.Type.OBJECT); - nestedJsonDocument3.put("floatNumber", 0.42); - nestedJsonDocument3.put("number", 42); - nestedJsonDocument3.put("active", false); - nestedJsonDocument3.put("message", "no message"); - nestedJsonDocument3.put("arrayOne", nestedJsonDocument4); - - JsonDocument nestedJsonDocument2 = new JsonDocument(JsonDocument.Type.OBJECT); - nestedJsonDocument2.put("value", nestedJsonDocument3); - - JsonDocument nestedJsonDocument1 = new JsonDocument(JsonDocument.Type.OBJECT); - nestedJsonDocument1.put("name", "nestedName1"); - nestedJsonDocument1.put("object1", nestedJsonDocument2); - - JsonReader parser = new JsonReader(jsonNestedObject2BasicValueWithStringArray); - JsonDocument document = parser.read(); - - JsonDocument expectedNestedObject2 = (JsonDocument) document.getKey("object1"); - - assertEquals(JsonDocument.Type.OBJECT, document.getType()); - assertEquals("nestedName1", document.getKey("name")); - assertEquals(expectedNestedObject2, nestedJsonDocument2); - assertEquals(JsonDocument.Type.OBJECT, expectedNestedObject2.getType()); - System.out.println("document: " + document); - } - - @Test - void basicValuesJsonParse() { - JsonReader parser = new JsonReader(jsonBasicValues); - JsonDocument document = parser.read(); - Map map = document.getMap(); - - assertEquals(JsonDocument.Type.OBJECT, document.getType()); - assertEquals(42, map.get("number")); - assertEquals("no message", map.get("message")); - assertEquals(false, map.get("active")); - assertEquals(0.42, map.get("floatNumber")); - } - - @Test - void basicValuesMinusJsonParse() { - JsonReader parser = new JsonReader(jsonBasicMinusValues); - JsonDocument document = parser.read(); - Map map = document.getMap(); - - assertEquals(JsonDocument.Type.OBJECT, document.getType()); - assertEquals(-42, map.get("number")); - assertEquals("no message", map.get("message")); - assertEquals(false, map.get("active")); - assertEquals(-0.42, map.get("floatNumber")); - } - - @Test - void jsonBasicValuesAndStringArrayTest() { - JsonReader parser = new JsonReader(jsonBasicValueWithStringArray); - JsonDocument document = parser.read(); - Map map = document.getMap(); - - assertEquals(JsonDocument.Type.OBJECT, document.getType()); - assertEquals(42, map.get("number")); - assertEquals(false, map.get("active")); - assertEquals("no message", map.get("message")); - assertEquals(0.42, map.get("floatNumber")); - List resultArray = ((JsonDocument) map.get("arrayOne")).getArray(); - assertTrue(Arrays.asList("one", "two").containsAll(resultArray)); - - System.out.println("document: " + document); - } - - @Test - void jsonBasicValuesAndStringAndIntegerArraysTest() { - JsonReader parser = new JsonReader(jsonBasicValueWithStringAndIntegerArrays); - JsonDocument document = parser.read(); - Map map = document.getMap(); - List resultStringArray = ((JsonDocument) map.get("arrayOne")).getArray(); - List resultIntegerArray = ((JsonDocument) map.get("arrayTwo")).getArray(); - - assertEquals(JsonDocument.Type.OBJECT, document.getType()); - assertEquals(42, map.get("number")); - assertEquals(false, map.get("active")); - assertEquals("no message", map.get("message")); - assertEquals(0.42, map.get("floatNumber")); - assertTrue(Arrays.asList("one", "two").containsAll(resultStringArray)); - assertTrue(Arrays.asList(1, 2, 3).containsAll(resultIntegerArray)); - - System.out.println("document: " + document); - } - - @Test - void jsonBasicValuesAndStringAndIntegerAndObjectArraysTest() { - - JsonReader parser = new JsonReader(jsonBasicValueWithStringAndIntegerAndObjectArrays); - JsonDocument document = parser.read(); - System.out.println("document: " + document); - Map map = document.getMap(); - List resultStringArray = ((JsonDocument) map.get("arrayOne")).getArray(); - List resultIntegerArray = ((JsonDocument) map.get("arrayTwo")).getArray(); - List resultObjectArray = ((JsonDocument) map.get("arrayThree")).getArray(); - JsonDocument arrayObj1 = (JsonDocument) resultObjectArray.get(0); - - assertEquals(JsonDocument.Type.OBJECT, document.getType()); - assertEquals(42, map.get("number")); - assertEquals(false, map.get("active")); - assertEquals("no message", map.get("message")); - assertEquals(0.42, map.get("floatNumber")); - assertEquals(2, resultObjectArray.size()); - assertEquals("name1", arrayObj1.getMap().get("name")); - assertEquals(22, arrayObj1.getMap().get("value")); - assertTrue(Arrays.asList(1, 2, 3).containsAll(resultIntegerArray)); - assertTrue(Arrays.asList("one", "two").containsAll(resultStringArray)); - - } - - @Test - void jsonBasicValuesAndObjectValueAndStringAndIntegerAndObjectArraysTest() { - - JsonReader parser = new JsonReader(jsonBasicValueAndObjectValueWithStringAndIntegerAndObjectArrays); - JsonDocument document = parser.read(); - System.out.println("document: " + document); - Map map = document.getMap(); - List resultStringArray = ((JsonDocument) map.get("arrayOne")).getArray(); - List resultIntegerArray = ((JsonDocument) map.get("arrayTwo")).getArray(); - List resultObjectArray = ((JsonDocument) map.get("arrayThree")).getArray(); - JsonDocument arrayObj1 = (JsonDocument) resultObjectArray.get(0); - JsonDocument childObj = (JsonDocument) map.get("child"); - - assertEquals(JsonDocument.Type.OBJECT, document.getType()); - assertEquals(42, map.get("number")); - assertEquals(false, map.get("active")); - assertEquals("no message", map.get("message")); - assertEquals(0.42, map.get("floatNumber")); - assertEquals(2, resultObjectArray.size()); - assertEquals("name1", arrayObj1.getMap().get("name")); - assertEquals(22, arrayObj1.getMap().get("value")); - assertEquals("name11", childObj.getMap().get("name")); - assertEquals(1, childObj.getMap().get("value")); - assertTrue(Arrays.asList(1, 2, 3).containsAll(resultIntegerArray)); - assertTrue(Arrays.asList("one", "two").containsAll(resultStringArray)); - - } + private static final String jsonNestedObject2BasicValueWithStringArray = "{\"name\" : \"nestedName1\", \"object1\" : {\"value\" : " + + "{ \"floatNumber\" : 0.42, \"number\"\n : 42, \"active\" : false, \"message\" \t: \"no message\", \"arrayOne\":[\"one\",\"two\"]}}}"; + + @Test + void basicBooleanValuesTest() { + var start = System.nanoTime(); + var parser = new JsonReader(jsonBooleanValues); + var document = parser.read(); + TimeUtils.printTimeDiffNano("basicBooleanValues robo4j", start); + + printDocument(document); + + assertEquals(JsonDocument.Type.OBJECT, document.getType()); + assertEquals(22, document.getKey("number")); + assertEquals("no message", document.getKey("message")); + assertEquals(true, document.getKey("active")); + assertEquals(false, document.getKey("passive")); + assertEquals(false, document.getKey("bool1")); + assertEquals(true, document.getKey("bool2")); + + } + + @Test + public void basicAndNullValues() { + var parser = new JsonReader(jsonBasicValuesWithNullValues); + var document = parser.read(); + var map = document.getMap(); + + printDocument(document); + + assertEquals(JsonDocument.Type.OBJECT, document.getType()); + assertEquals(42, map.get("number")); + assertEquals("no message", map.get("message")); + assertEquals(false, map.get("active")); + assertEquals(0.42, map.get("floatNumber")); + assertNull(map.get("empty1")); + assertNull(map.get("empty2")); + } + + @Test + void basicArrayIntegerStringTest() { + JsonReader parser = new JsonReader(jsonArrayIntegerStringObject); + JsonDocument document = parser.read(); + Map map = document.getMap(); + + List arrayString = ((JsonDocument) map.get("arrayString")).getArray(); + List arrayInteger = ((JsonDocument) map.get("arrayInteger")).getArray(); + + printDocument(document); + + assertEquals(JsonDocument.Type.OBJECT, document.getType()); + assertTrue((Arrays.asList("one", "two", "three").containsAll(arrayString))); + assertTrue((Arrays.asList(1, 2, 3).containsAll(arrayInteger))); + } + + @Test + void basicNestedObjectWithStringArray() { + + JsonDocument nestedJsonDocument2 = new JsonDocument(JsonDocument.Type.OBJECT); + nestedJsonDocument2.put("name", "some"); + + JsonDocument nestedJsonDocument1 = new JsonDocument(JsonDocument.Type.OBJECT); + nestedJsonDocument1.put("floatNumber", 0.42); + nestedJsonDocument1.put("object1", nestedJsonDocument2); + + JsonReader parser = new JsonReader(jsonNestedObjects); + JsonDocument document = parser.read(); + + printDocument(document); + + assertEquals(JsonDocument.Type.OBJECT, document.getType()); + assertEquals(nestedJsonDocument1, document.getKey("value")); + } + + @Test + void basicNestedObjectValuesAndObjectArray() { + + JsonDocument nestedJsonDocument2 = getNestedDocument2(); + + JsonReader parser = new JsonReader(jsonNestedObjectAndArrayObject); + JsonDocument document = parser.read(); + + JsonDocument arrayJsonDocument = (JsonDocument) document.getKey("arrayThree"); + + printDocument(document); + + assertEquals(JsonDocument.Type.OBJECT, document.getType()); + assertEquals(JsonDocument.Type.ARRAY, arrayJsonDocument.getType()); + assertEquals(nestedJsonDocument2, document.getKey("arrayThree")); + } + + @Test + void basicNestedObjectWithBasicValueWithStringArray() { + var nestedJsonDocument1 = getNestedDocument(); + + var parser = new JsonReader(jsonNestedObjectWithBasicValueWithStringArray); + var document = parser.read(); + var nestedArray = ((JsonDocument) ((JsonDocument) document.getKey("value")).getKey("arrayOne")); + + printDocument(document); + + assertEquals(JsonDocument.Type.OBJECT, document.getType()); + assertEquals(nestedJsonDocument1, document.getKey("value")); + assertEquals(JsonDocument.Type.ARRAY, nestedArray.getType()); + } + + private static JsonDocument getNestedDocument() { + var nestedJsonDocument2 = new JsonDocument(JsonDocument.Type.ARRAY); + nestedJsonDocument2.add("one"); + nestedJsonDocument2.add("two"); + + var nestedJsonDocument1 = new JsonDocument(JsonDocument.Type.OBJECT); + nestedJsonDocument1.put("floatNumber", 0.42); + nestedJsonDocument1.put("number", 42); + nestedJsonDocument1.put("active", false); + nestedJsonDocument1.put("message", "no message"); + nestedJsonDocument1.put("arrayOne", nestedJsonDocument2); + return nestedJsonDocument1; + } + + private static JsonDocument getNestedDocument2() { + JsonDocument nestedJsonDocument21 = new JsonDocument(JsonDocument.Type.OBJECT); + nestedJsonDocument21.put("name", "name1"); + nestedJsonDocument21.put("value", 22); + + JsonDocument nestedJsonDocument22 = new JsonDocument(JsonDocument.Type.OBJECT); + nestedJsonDocument22.put("name", "name2"); + nestedJsonDocument22.put("value", 42); + + JsonDocument nestedJsonDocument2 = new JsonDocument(JsonDocument.Type.ARRAY); + nestedJsonDocument2.add(nestedJsonDocument21); + nestedJsonDocument2.add(nestedJsonDocument22); + + JsonDocument nestedJsonDocument1 = new JsonDocument(JsonDocument.Type.OBJECT); + nestedJsonDocument1.put("arrayThree", nestedJsonDocument2); + return nestedJsonDocument2; + } + + @Test + void basicNestedObject2WithBasicValueWithStringArray() { + var nestedJsonDocument2 = getJsonDocument(); + var nestedJsonDocument1 = new JsonDocument(JsonDocument.Type.OBJECT); + + nestedJsonDocument1.put("name", "nestedName1"); + nestedJsonDocument1.put("object1", nestedJsonDocument2); + + var parser = new JsonReader(jsonNestedObject2BasicValueWithStringArray); + var document = parser.read(); + var expectedNestedObject2 = (JsonDocument) document.getKey("object1"); + + printDocument(document); + + assertEquals(JsonDocument.Type.OBJECT, document.getType()); + assertEquals("nestedName1", document.getKey("name")); + assertEquals(expectedNestedObject2, nestedJsonDocument2); + assertEquals(JsonDocument.Type.OBJECT, expectedNestedObject2.getType()); + } + + @Test + void basicValuesJsonParse() { + var parser = new JsonReader(jsonBasicValues); + var document = parser.read(); + var map = document.getMap(); + + assertEquals(JsonDocument.Type.OBJECT, document.getType()); + assertEquals(42, map.get("number")); + assertEquals("no message", map.get("message")); + assertEquals(false, map.get("active")); + assertEquals(0.42, map.get("floatNumber")); + } + + @Test + void basicValuesMinusJsonParse() { + var parser = new JsonReader(jsonBasicMinusValues); + var document = parser.read(); + var map = document.getMap(); + + assertEquals(JsonDocument.Type.OBJECT, document.getType()); + assertEquals(-42, map.get("number")); + assertEquals("no message", map.get("message")); + assertEquals(false, map.get("active")); + assertEquals(-0.42, map.get("floatNumber")); + } + + @Test + void jsonBasicValuesAndStringArrayTest() { + var parser = new JsonReader(jsonBasicValueWithStringArray); + var document = parser.read(); + var map = document.getMap(); + var resultArray = ((JsonDocument) map.get("arrayOne")).getArray(); + + printDocument(document); + + assertEquals(JsonDocument.Type.OBJECT, document.getType()); + assertEquals(42, map.get("number")); + assertEquals(false, map.get("active")); + assertEquals("no message", map.get("message")); + assertEquals(0.42, map.get("floatNumber")); + assertTrue(Arrays.asList("one", "two").containsAll(resultArray)); + } + + @Test + void jsonBasicValuesAndStringAndIntegerArraysTest() { + var parser = new JsonReader(jsonBasicValueWithStringAndIntegerArrays); + var document = parser.read(); + var map = document.getMap(); + var resultStringArray = ((JsonDocument) map.get("arrayOne")).getArray(); + var resultIntegerArray = ((JsonDocument) map.get("arrayTwo")).getArray(); + + printDocument(document); + + assertEquals(JsonDocument.Type.OBJECT, document.getType()); + assertEquals(42, map.get("number")); + assertEquals(false, map.get("active")); + assertEquals("no message", map.get("message")); + assertEquals(0.42, map.get("floatNumber")); + assertTrue(Arrays.asList("one", "two").containsAll(resultStringArray)); + assertTrue(Arrays.asList(1, 2, 3).containsAll(resultIntegerArray)); + } + + @Test + void jsonBasicValuesAndStringAndIntegerAndObjectArraysTest() { + var parser = new JsonReader(jsonBasicValueWithStringAndIntegerAndObjectArrays); + var document = parser.read(); + var map = document.getMap(); + var resultStringArray = ((JsonDocument) map.get("arrayOne")).getArray(); + var resultIntegerArray = ((JsonDocument) map.get("arrayTwo")).getArray(); + var resultObjectArray = ((JsonDocument) map.get("arrayThree")).getArray(); + var arrayObj1 = (JsonDocument) resultObjectArray.get(0); + + printDocument(document); + + assertEquals(JsonDocument.Type.OBJECT, document.getType()); + assertEquals(42, map.get("number")); + assertEquals(false, map.get("active")); + assertEquals("no message", map.get("message")); + assertEquals(0.42, map.get("floatNumber")); + assertEquals(2, resultObjectArray.size()); + assertEquals("name1", arrayObj1.getMap().get("name")); + assertEquals(22, arrayObj1.getMap().get("value")); + assertTrue(Arrays.asList(1, 2, 3).containsAll(resultIntegerArray)); + assertTrue(Arrays.asList("one", "two").containsAll(resultStringArray)); + + } + + @Test + void jsonBasicValuesAndObjectValueAndStringAndIntegerAndObjectArraysTest() { + + var parser = new JsonReader(jsonBasicValueAndObjectValueWithStringAndIntegerAndObjectArrays); + var document = parser.read(); + var map = document.getMap(); + var resultStringArray = ((JsonDocument) map.get("arrayOne")).getArray(); + var resultIntegerArray = ((JsonDocument) map.get("arrayTwo")).getArray(); + var resultObjectArray = ((JsonDocument) map.get("arrayThree")).getArray(); + JsonDocument arrayObj1 = (JsonDocument) resultObjectArray.get(0); + JsonDocument childObj = (JsonDocument) map.get("child"); + + + printDocument(document); + + assertEquals(JsonDocument.Type.OBJECT, document.getType()); + assertEquals(42, map.get("number")); + assertEquals(false, map.get("active")); + assertEquals("no message", map.get("message")); + assertEquals(0.42, map.get("floatNumber")); + assertEquals(2, resultObjectArray.size()); + assertEquals("name1", arrayObj1.getMap().get("name")); + assertEquals(22, arrayObj1.getMap().get("value")); + assertEquals("name11", childObj.getMap().get("name")); + assertEquals(1, childObj.getMap().get("value")); + assertTrue(Arrays.asList(1, 2, 3).containsAll(resultIntegerArray)); + assertTrue(Arrays.asList("one", "two").containsAll(resultStringArray)); + + } + + private static JsonDocument getJsonDocument() { + var nestedJsonDocument3 = getNestedDocument(); + + var nestedJsonDocument2 = new JsonDocument(JsonDocument.Type.OBJECT); + nestedJsonDocument2.put("value", nestedJsonDocument3); + return nestedJsonDocument2; + } + + static void printDocument(JsonDocument document) { + LOGGER.debug("DOC:{}", document); + } } diff --git a/robo4j-socket-http/src/test/java/com/robo4j/socket/http/test/json/JsonTest.java b/robo4j-socket-http/src/test/java/com/robo4j/socket/http/test/json/JsonTest.java index 04b2aaaa..db529e8c 100644 --- a/robo4j-socket-http/src/test/java/com/robo4j/socket/http/test/json/JsonTest.java +++ b/robo4j-socket-http/src/test/java/com/robo4j/socket/http/test/json/JsonTest.java @@ -19,11 +19,13 @@ import com.robo4j.socket.http.json.JsonDocument; import com.robo4j.socket.http.json.JsonReader; import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.Arrays; -import java.util.List; import java.util.Map; +import static com.robo4j.socket.http.test.json.JsonReaderTests.printDocument; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -32,132 +34,135 @@ * @author Miroslav Wengner (@miragemiko) */ class JsonTest { - - private static final String jsonBasicValues = "{ \"number\"\n : 42, \"message\" \t: \"no message\", \"active\" : false , \"floatNumber\" : 0.42}"; - private static final String jsonBasicValueWithStringArray = "{ \"floatNumber\" : 0.42, \"number\"\n : 42, \"active\" : false, " - + "\"message\" \t: \"no message\", \"arrayOne\":[\"one\",\"two\"]}"; - private static final String jsonBasicValueWithStringAndIntegerArrays = "{ \"floatNumber\" : 0.42, \"number\"\n : 42, " - + "\"active\" : false, \"message\" \t: \"no message\", \"arrayOne\":[\"one\", \"two\"], \"arrayTwo\" : [1, 2 ,3 ]}"; - private static final String jsonBasicValueWithStringAndIntegerAndObjectArrays = "{ \"floatNumber\" : 0.42, \"number\"\n : 42, " - + "\"active\" : false, \"arrayOne\":[\"one\", \"two\"], \"message\" \t: \"no message\", \"arrayTwo\" : [1, 2 ,3 ], " - + "\"arrayThree\" : [{\"name\":\"name1\",\"value\": 22}, {\"name\":\"name2\",\"value\": 42}]}"; - - private static final String jsonBasicObjectArrays = "{\"number\"\n : 42,\"arrayThree\" : [{\"name\":\"name1\",\"value\": 22}, {\"name\":\"name2\",\"value\": 42}]," - + " \"active\" : false}"; - - private static final String jsonBasicObjectArraysAndStringMap = "{\"number\"\n : 42," - + "\"arrayThree\" : [{\"name\":\"name1\",\"value\": 22}, {\"name\":\"name2\",\"value\": 42}]," - + " \"active\" : false, \"simpleMap\": {\"one\":\"one1\",\"two\":\"two2\"}}"; - - @Test - void basicValuesJsonParse() { - JsonReader parser = new JsonReader(jsonBasicValues); - JsonDocument document = parser.read(); - Map map = document.getMap(); - assertEquals(42, map.get("number")); - assertEquals("no message", map.get("message")); - assertEquals(false, map.get("active")); - assertEquals(0.42, map.get("floatNumber")); - } - - @Test - void jsonBasicValuesAndStringArrayTest() { - JsonReader parser = new JsonReader(jsonBasicValueWithStringArray); - JsonDocument document = parser.read(); - Map map = document.getMap(); - assertEquals(42, map.get("number")); - assertEquals(false, map.get("active")); - assertEquals("no message", map.get("message")); - assertEquals(0.42, map.get("floatNumber")); - List resultArray = ((JsonDocument) map.get("arrayOne")).getArray(); - assertTrue(Arrays.asList("one", "two").containsAll(resultArray)); - - System.out.println("document: " + document); - } - - @Test - void jsonBasicValuesAndStringAndIntegerArraysTest() { - JsonReader parser = new JsonReader(jsonBasicValueWithStringAndIntegerArrays); - JsonDocument document = parser.read(); - Map map = document.getMap(); - List resultStringArray = ((JsonDocument) map.get("arrayOne")).getArray(); - List resultIntegerArray = ((JsonDocument) map.get("arrayTwo")).getArray(); - - assertEquals(42, map.get("number")); - assertEquals(false, map.get("active")); - assertEquals("no message", map.get("message")); - assertEquals(0.42, map.get("floatNumber")); - assertTrue(Arrays.asList("one", "two").containsAll(resultStringArray)); - assertTrue(Arrays.asList(1, 2, 3).containsAll(resultIntegerArray)); - - System.out.println("document: " + document); - } - - @Test - void jsonBasicValuesAndStringAndIntegerAndObjectArraysTest() { - JsonReader parser = new JsonReader(jsonBasicValueWithStringAndIntegerAndObjectArrays); - JsonDocument document = parser.read(); - System.out.println("document: " + document); - Map map = document.getMap(); - List resultStringArray = ((JsonDocument) map.get("arrayOne")).getArray(); - List resultIntegerArray = ((JsonDocument) map.get("arrayTwo")).getArray(); - - assertEquals(42, map.get("number")); - assertEquals(false, map.get("active")); - assertEquals("no message", map.get("message")); - assertEquals(0.42, map.get("floatNumber")); - assertTrue(Arrays.asList("one", "two").containsAll(resultStringArray)); - assertTrue(Arrays.asList(1, 2, 3).containsAll(resultIntegerArray)); - - } - - @Test - void jsonBasicObjectArraysTest() { - - JsonReader parser = new JsonReader(jsonBasicObjectArrays); - JsonDocument document = parser.read(); - System.out.println("document: " + document); - Map map = document.getMap(); - List resultObjectArray = ((JsonDocument) map.get("arrayThree")).getArray(); - - JsonDocument obj1 = (JsonDocument) resultObjectArray.get(0); - JsonDocument obj2 = (JsonDocument) resultObjectArray.get(1); - - // [{"name":"name1","value": 22}, {"name":"name2","value": 42}] - assertEquals(42, map.get("number")); - assertEquals(false, map.get("active")); - assertEquals("name1", obj1.getMap().get("name").toString()); - assertEquals(22, (int) obj1.getMap().get("value")); - assertEquals("name2", obj2.getMap().get("name").toString()); - assertEquals(42, (int) obj2.getMap().get("value")); - assertEquals(2, resultObjectArray.size()); - - } - - @Test - void jsonBasicObjectArraysAndSimpleMapTest() { - - JsonReader parser = new JsonReader(jsonBasicObjectArraysAndStringMap); - JsonDocument document = parser.read(); - System.out.println("document: " + document); - Map map = document.getMap(); - List resultObjectArray = ((JsonDocument) map.get("arrayThree")).getArray(); - Map simpleMap = ((JsonDocument) map.get("simpleMap")).getMap(); - - JsonDocument obj1 = (JsonDocument) resultObjectArray.get(0); - JsonDocument obj2 = (JsonDocument) resultObjectArray.get(1); - - // [{"name":"name1","value": 22}, {"name":"name2","value": 42}] - assertEquals(42, map.get("number")); - assertEquals(false, map.get("active")); - assertEquals("name1", obj1.getMap().get("name").toString()); - assertEquals(22, (int) obj1.getMap().get("value")); - assertEquals("name2", obj2.getMap().get("name").toString()); - assertEquals(42, (int) obj2.getMap().get("value")); - assertEquals(2, resultObjectArray.size()); - assertEquals("one1", simpleMap.get("one")); - assertEquals("two2", simpleMap.get("two")); - - } + private static final Logger LOGGER = LoggerFactory.getLogger(JsonTest.class); + + private static final String jsonBasicValues = "{ \"number\"\n : 42, \"message\" \t: \"no message\", \"active\" : false , \"floatNumber\" : 0.42}"; + private static final String jsonBasicValueWithStringArray = "{ \"floatNumber\" : 0.42, \"number\"\n : 42, \"active\" : false, " + + "\"message\" \t: \"no message\", \"arrayOne\":[\"one\",\"two\"]}"; + private static final String jsonBasicValueWithStringAndIntegerArrays = "{ \"floatNumber\" : 0.42, \"number\"\n : 42, " + + "\"active\" : false, \"message\" \t: \"no message\", \"arrayOne\":[\"one\", \"two\"], \"arrayTwo\" : [1, 2 ,3 ]}"; + private static final String jsonBasicValueWithStringAndIntegerAndObjectArrays = "{ \"floatNumber\" : 0.42, \"number\"\n : 42, " + + "\"active\" : false, \"arrayOne\":[\"one\", \"two\"], \"message\" \t: \"no message\", \"arrayTwo\" : [1, 2 ,3 ], " + + "\"arrayThree\" : [{\"name\":\"name1\",\"value\": 22}, {\"name\":\"name2\",\"value\": 42}]}"; + + private static final String jsonBasicObjectArrays = "{\"number\"\n : 42,\"arrayThree\" : [{\"name\":\"name1\",\"value\": 22}, {\"name\":\"name2\",\"value\": 42}]," + + " \"active\" : false}"; + + private static final String jsonBasicObjectArraysAndStringMap = "{\"number\"\n : 42," + + "\"arrayThree\" : [{\"name\":\"name1\",\"value\": 22}, {\"name\":\"name2\",\"value\": 42}]," + + " \"active\" : false, \"simpleMap\": {\"one\":\"one1\",\"two\":\"two2\"}}"; + + @Test + void basicValuesJsonParse() { + JsonReader parser = new JsonReader(jsonBasicValues); + JsonDocument document = parser.read(); + Map map = document.getMap(); + assertEquals(42, map.get("number")); + assertEquals("no message", map.get("message")); + assertEquals(false, map.get("active")); + assertEquals(0.42, map.get("floatNumber")); + } + + @Test + void jsonBasicValuesAndStringArrayTest() { + var parser = new JsonReader(jsonBasicValueWithStringArray); + var document = parser.read(); + var map = document.getMap(); + var resultArray = ((JsonDocument) map.get("arrayOne")).getArray(); + + printDocument(document); + + assertEquals(42, map.get("number")); + assertEquals(false, map.get("active")); + assertEquals("no message", map.get("message")); + assertEquals(0.42, map.get("floatNumber")); + assertTrue(Arrays.asList("one", "two").containsAll(resultArray)); + + } + + @Test + void jsonBasicValuesAndStringAndIntegerArraysTest() { + var parser = new JsonReader(jsonBasicValueWithStringAndIntegerArrays); + var document = parser.read(); + var map = document.getMap(); + var resultStringArray = ((JsonDocument) map.get("arrayOne")).getArray(); + var resultIntegerArray = ((JsonDocument) map.get("arrayTwo")).getArray(); + + printDocument(document); + + assertEquals(42, map.get("number")); + assertEquals(false, map.get("active")); + assertEquals("no message", map.get("message")); + assertEquals(0.42, map.get("floatNumber")); + assertTrue(Arrays.asList("one", "two").containsAll(resultStringArray)); + assertTrue(Arrays.asList(1, 2, 3).containsAll(resultIntegerArray)); + } + + @Test + void jsonBasicValuesAndStringAndIntegerAndObjectArraysTest() { + var parser = new JsonReader(jsonBasicValueWithStringAndIntegerAndObjectArrays); + var document = parser.read(); + var map = document.getMap(); + var resultStringArray = ((JsonDocument) map.get("arrayOne")).getArray(); + var resultIntegerArray = ((JsonDocument) map.get("arrayTwo")).getArray(); + + printDocument(document); + + assertEquals(42, map.get("number")); + assertEquals(false, map.get("active")); + assertEquals("no message", map.get("message")); + assertEquals(0.42, map.get("floatNumber")); + assertTrue(Arrays.asList("one", "two").containsAll(resultStringArray)); + assertTrue(Arrays.asList(1, 2, 3).containsAll(resultIntegerArray)); + + } + + @Test + void jsonBasicObjectArraysTest() { + var parser = new JsonReader(jsonBasicObjectArrays); + var document = parser.read(); + var map = document.getMap(); + var resultObjectArray = ((JsonDocument) map.get("arrayThree")).getArray(); + + JsonDocument obj1 = (JsonDocument) resultObjectArray.get(0); + JsonDocument obj2 = (JsonDocument) resultObjectArray.get(1); + + printDocument(document); + + // [{"name":"name1","value": 22}, {"name":"name2","value": 42}] + assertEquals(42, map.get("number")); + assertEquals(false, map.get("active")); + assertEquals("name1", obj1.getMap().get("name").toString()); + assertEquals(22, (int) obj1.getMap().get("value")); + assertEquals("name2", obj2.getMap().get("name").toString()); + assertEquals(42, (int) obj2.getMap().get("value")); + assertEquals(2, resultObjectArray.size()); + } + + @Test + void jsonBasicObjectArraysAndSimpleMapTest() { + var parser = new JsonReader(jsonBasicObjectArraysAndStringMap); + var document = parser.read(); + var map = document.getMap(); + var resultObjectArray = ((JsonDocument) map.get("arrayThree")).getArray(); + var simpleMap = ((JsonDocument) map.get("simpleMap")).getMap(); + + JsonDocument obj1 = (JsonDocument) resultObjectArray.get(0); + JsonDocument obj2 = (JsonDocument) resultObjectArray.get(1); + + printDocument(document); + + // [{"name":"name1","value": 22}, {"name":"name2","value": 42}] + assertEquals(42, map.get("number")); + assertEquals(false, map.get("active")); + assertEquals("name1", obj1.getMap().get("name").toString()); + assertEquals(22, (int) obj1.getMap().get("value")); + assertEquals("name2", obj2.getMap().get("name").toString()); + assertEquals(42, (int) obj2.getMap().get("value")); + assertEquals(2, resultObjectArray.size()); + assertEquals("one1", simpleMap.get("one")); + assertEquals("two2", simpleMap.get("two")); + + } } diff --git a/robo4j-socket-http/src/test/java/com/robo4j/socket/http/test/json/TimeUtils.java b/robo4j-socket-http/src/test/java/com/robo4j/socket/http/test/json/TimeUtils.java index 2725b5dc..51fe7da8 100644 --- a/robo4j-socket-http/src/test/java/com/robo4j/socket/http/test/json/TimeUtils.java +++ b/robo4j-socket-http/src/test/java/com/robo4j/socket/http/test/json/TimeUtils.java @@ -16,14 +16,17 @@ */ package com.robo4j.socket.http.test.json; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * @author Marcus Hirt (@hirt) * @author Miroslav Wengner (@miragemiko) */ public final class TimeUtils { + private static final Logger LOGGER = LoggerFactory.getLogger(TimeUtils.class); - static void printTimeDiffNano(String message, long start) { - - System.out.println(String.format("message: %s duration: %d", message, System.nanoTime() - start)); + static void printTimeDiffNano(String message, long start) { + LOGGER.debug("message: {} duration: {}", message, System.nanoTime() - start); } } diff --git a/robo4j-socket-http/src/test/java/com/robo4j/socket/http/test/message/DatagramDecoratedRequestTest.java b/robo4j-socket-http/src/test/java/com/robo4j/socket/http/test/message/DatagramDecoratedRequestTest.java index 9125ec48..919f2b21 100644 --- a/robo4j-socket-http/src/test/java/com/robo4j/socket/http/test/message/DatagramDecoratedRequestTest.java +++ b/robo4j-socket-http/src/test/java/com/robo4j/socket/http/test/message/DatagramDecoratedRequestTest.java @@ -20,34 +20,36 @@ import com.robo4j.socket.http.message.DatagramDenominator; import com.robo4j.socket.http.util.DatagramBodyType; import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; /** - * @see DatagramDecoratedRequest - * * @author Marcus Hirt (@hirt) * @author Miroslav Wengner (@miragemiko) + * @see DatagramDecoratedRequest */ class DatagramDecoratedRequestTest { + private static final Logger LOGGER = LoggerFactory.getLogger(DatagramDecoratedRequestTest.class); - @Test - void datagramDecoratedRequestTest() { + @Test + void datagramDecoratedRequestTest() { - DatagramDenominator denominator = new DatagramDenominator(DatagramBodyType.JSON.getType(), - "/units/stringConsumer"); - DatagramDecoratedRequest request = new DatagramDecoratedRequest(denominator); - request.addMessage("{\"number\":22}".getBytes()); + DatagramDenominator denominator = new DatagramDenominator(DatagramBodyType.JSON.getType(), + "/units/stringConsumer"); + DatagramDecoratedRequest request = new DatagramDecoratedRequest(denominator); + request.addMessage("{\"number\":22}".getBytes()); - byte[] requestBytes = request.toMessage(); + byte[] requestBytes = request.toMessage(); - String requestMessage = new String(requestBytes); + String requestMessage = new String(requestBytes); - System.out.println("requestMessage: " + requestMessage); + LOGGER.debug("requestMessage:{}", requestMessage); - assertNotNull(requestBytes); - assertTrue(requestBytes.length > 0); + assertNotNull(requestBytes); + assertTrue(requestBytes.length > 0); - } + } } diff --git a/robo4j-socket-http/src/test/java/com/robo4j/socket/http/test/request/ByteBufferTests.java b/robo4j-socket-http/src/test/java/com/robo4j/socket/http/test/request/ByteBufferTests.java index d8cabd64..91ed4e86 100644 --- a/robo4j-socket-http/src/test/java/com/robo4j/socket/http/test/request/ByteBufferTests.java +++ b/robo4j-socket-http/src/test/java/com/robo4j/socket/http/test/request/ByteBufferTests.java @@ -27,116 +27,115 @@ import com.robo4j.socket.http.util.HttpMessageBuilder; import com.robo4j.socket.http.util.RoboHttpUtils; import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.nio.ByteBuffer; import java.util.regex.Matcher; import java.util.regex.Pattern; import static com.robo4j.socket.http.HttpHeaderFieldValues.CONNECTION_KEEP_ALIVE; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.*; /** * @author Marcus Hirt (@hirt) * @author Miro Wengner (@miragemiko) */ class ByteBufferTests { - - private static final String TEST_STRING = "Accept-Language: en-US,en;q=0.8\r\n\r\n{"; - private static final String TEST_POSTMAN_MESSAGE = "\r\n" + "{ \n" + " \"value\" : \"move\"\n" + "}"; - private static final String TEST_POSTMAN_STRING = "POST /controller HTTP/1.1\r\n" + "Host: localhost:8042\r\n" - + "Connection: " + CONNECTION_KEEP_ALIVE + "\r\n" + "Content-Length: 23\r\n" - + "Postman-Token: 60b492c5-e7a9-6037-3021-42f8885542a9\r\n" + "Cache-Control: no-cache\r\n" - + "Origin: chrome-extension://fhbjgbiflinjbdggehcddcbncdddomop\r\n" - + "User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.101 Safari/537.36\r\n" - + "Content-Type: text/plain;charset=UTF-8\r\n" + "Accept: */*\r\n" - + "Accept-Encoding: gzip, deflate, br\r\n" + "Accept-Language: en-US,en;q=0.8\r\n" + TEST_POSTMAN_MESSAGE; - private static final ByteBuffer TEST_BYTE_BUFFER = ByteBuffer.wrap(TEST_STRING.getBytes()); - - @Test - void testPostmanMessage() { - HttpDecoratedRequest decoratedRequest = ChannelBufferUtils - .extractDecoratedRequestByStringMessage(TEST_POSTMAN_STRING); - decoratedRequest.addMessage(TEST_POSTMAN_MESSAGE); - - assertNotNull(decoratedRequest.getHeader()); - assertTrue(!decoratedRequest.getHeader().isEmpty()); - assertNotNull(decoratedRequest.getMessage()); - System.out.println("HEADER: " + decoratedRequest.getHeader()); - System.out.println("BODY: " + decoratedRequest.getMessage()); - - } - - @Test - void byteBufferFromRequestTest() { - - String bodyMessage = "this is test message"; - String host = "localhost"; - String clientPath = "/test"; - - HttpDenominator denominator = new HttpRequestDenominator(HttpMethod.POST, clientPath, HttpVersion.HTTP_1_1); - String postMessage = HttpMessageBuilder.Build().setDenominator(denominator) - .addHeaderElement(HttpHeaderFieldNames.CONTENT_LENGTH, String.valueOf(bodyMessage.length())) - .addHeaderElement(HttpHeaderFieldNames.HOST, - RoboHttpUtils.createHost(host, ProtocolType.HTTP.getPort())) - .build(bodyMessage); - - HttpDecoratedRequest decoratedRequest = ChannelBufferUtils.extractDecoratedRequestByStringMessage(postMessage); - - assertNotNull(postMessage); - assertEquals(postMessage.length(), decoratedRequest.getLength()); - assertEquals(clientPath, decoratedRequest.getPathMethod().getPath()); - assertEquals(bodyMessage, decoratedRequest.getMessage()); - } - - @Test - void testMovingWindow() { - String correctString = "\n\n"; - assertTrue(ChannelBufferUtils.isBWindow(ChannelBufferUtils.END_WINDOW, - ByteBuffer.wrap(correctString.getBytes()).array())); - } - - @Test - void testReturnCharRemoval() { - - int position = 0; - int bPosition = 0; - int size = TEST_BYTE_BUFFER.capacity(); - byte[] tmpBytes = new byte[1024]; - - while (position < size) { - byte b = TEST_BYTE_BUFFER.get(position); - if (b == ChannelBufferUtils.CHAR_RETURN) { - } else { - tmpBytes[bPosition] = b; - bPosition++; - } - position++; - } - - byte[] resBytes = ChannelBufferUtils.validArray(tmpBytes, bPosition); - ByteBuffer resultBuffer = ByteBuffer.wrap(resBytes); - assertEquals(TEST_BYTE_BUFFER.capacity(), resultBuffer.capacity() + ChannelBufferUtils.END_WINDOW.length); - } - - @Test - void test() { - Pattern pattern = Pattern.compile("^(.*)[\\r\\n{2}]|[\\n\\n](.*)$"); - - String one = "some\r\n\r\nother"; - String two = "some\n\nother"; - - Matcher matcher1 = pattern.matcher(one); - Matcher matcher2 = pattern.matcher(two); - - // Assert.assertTrue(matcher1.find()); - // Assert.assertTrue(matcher2.find()); - // Assert.assertTrue(matcher2.groupCount() == matcher1.groupCount()); - // Assert.assertTrue(matcher2.groupCount() == matcher1.groupCount()); - System.out.println("ONE: " + matcher1.find() + " group: " + matcher1.groupCount() + " 1: " + matcher1.group(1) - + " 2: " + matcher1.group(0)); - System.out.println("TWO: " + matcher2.find() + " group: " + matcher2.groupCount()); - - } + private static final Logger LOGGER = LoggerFactory.getLogger(ByteBufferTests.class); + private static final String TEST_STRING = "Accept-Language: en-US,en;q=0.8\r\n\r\n{"; + private static final String TEST_POSTMAN_MESSAGE = "\r\n" + "{ \n" + " \"value\" : \"move\"\n" + "}"; + private static final String TEST_POSTMAN_STRING = "POST /controller HTTP/1.1\r\n" + "Host: localhost:8042\r\n" + + "Connection: " + CONNECTION_KEEP_ALIVE + "\r\n" + "Content-Length: 23\r\n" + + "Postman-Token: 60b492c5-e7a9-6037-3021-42f8885542a9\r\n" + "Cache-Control: no-cache\r\n" + + "Origin: chrome-extension://fhbjgbiflinjbdggehcddcbncdddomop\r\n" + + "User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.101 Safari/537.36\r\n" + + "Content-Type: text/plain;charset=UTF-8\r\n" + "Accept: */*\r\n" + + "Accept-Encoding: gzip, deflate, br\r\n" + "Accept-Language: en-US,en;q=0.8\r\n" + TEST_POSTMAN_MESSAGE; + private static final ByteBuffer TEST_BYTE_BUFFER = ByteBuffer.wrap(TEST_STRING.getBytes()); + + @Test + void testPostmanMessage() { + HttpDecoratedRequest decoratedRequest = ChannelBufferUtils + .extractDecoratedRequestByStringMessage(TEST_POSTMAN_STRING); + decoratedRequest.addMessage(TEST_POSTMAN_MESSAGE); + + assertNotNull(decoratedRequest.getHeader()); + assertFalse(decoratedRequest.getHeader().isEmpty()); + assertNotNull(decoratedRequest.getMessage()); + LOGGER.debug("HEADER:{}", decoratedRequest.getHeader()); + LOGGER.debug("BODY:{}", decoratedRequest.getMessage()); + + } + + @Test + void byteBufferFromRequestTest() { + + String bodyMessage = "this is test message"; + String host = "localhost"; + String clientPath = "/test"; + + HttpDenominator denominator = new HttpRequestDenominator(HttpMethod.POST, clientPath, HttpVersion.HTTP_1_1); + String postMessage = HttpMessageBuilder.Build().setDenominator(denominator) + .addHeaderElement(HttpHeaderFieldNames.CONTENT_LENGTH, String.valueOf(bodyMessage.length())) + .addHeaderElement(HttpHeaderFieldNames.HOST, + RoboHttpUtils.createHost(host, ProtocolType.HTTP.getPort())) + .build(bodyMessage); + + HttpDecoratedRequest decoratedRequest = ChannelBufferUtils.extractDecoratedRequestByStringMessage(postMessage); + + assertNotNull(postMessage); + assertEquals(postMessage.length(), decoratedRequest.getLength()); + assertEquals(clientPath, decoratedRequest.getPathMethod().getPath()); + assertEquals(bodyMessage, decoratedRequest.getMessage()); + } + + @Test + void testMovingWindow() { + String correctString = "\n\n"; + assertTrue(ChannelBufferUtils.isBWindow(ChannelBufferUtils.END_WINDOW, + ByteBuffer.wrap(correctString.getBytes()).array())); + } + + @Test + void testReturnCharRemoval() { + + int position = 0; + int bPosition = 0; + int size = TEST_BYTE_BUFFER.capacity(); + byte[] tmpBytes = new byte[1024]; + + while (position < size) { + byte b = TEST_BYTE_BUFFER.get(position); + if (b == ChannelBufferUtils.CHAR_RETURN) { + } else { + tmpBytes[bPosition] = b; + bPosition++; + } + position++; + } + + byte[] resBytes = ChannelBufferUtils.validArray(tmpBytes, bPosition); + ByteBuffer resultBuffer = ByteBuffer.wrap(resBytes); + assertEquals(TEST_BYTE_BUFFER.capacity(), resultBuffer.capacity() + ChannelBufferUtils.END_WINDOW.length); + } + + @Test + void test() { + Pattern pattern = Pattern.compile("^(.*)[\\r\\n{2}]|[\\n\\n](.*)$"); + + String one = "some\r\n\r\nother"; + String two = "some\n\nother"; + + Matcher matcher1 = pattern.matcher(one); + Matcher matcher2 = pattern.matcher(two); + + // Assert.assertTrue(matcher1.find()); + // Assert.assertTrue(matcher2.find()); + // Assert.assertTrue(matcher2.groupCount() == matcher1.groupCount()); + // Assert.assertTrue(matcher2.groupCount() == matcher1.groupCount()); + LOGGER.debug("ONE: {} group: {} 1: {} 2: {}", matcher1.find(), matcher1.groupCount(), matcher1.group(1), matcher1.group(0)); + LOGGER.debug("TWO: {} group: {}", matcher2.find(), matcher2.groupCount()); + + } } diff --git a/robo4j-socket-http/src/test/java/com/robo4j/socket/http/test/units/HttpContextTests.java b/robo4j-socket-http/src/test/java/com/robo4j/socket/http/test/units/HttpContextTests.java index 7d8a9095..7a32d36b 100644 --- a/robo4j-socket-http/src/test/java/com/robo4j/socket/http/test/units/HttpContextTests.java +++ b/robo4j-socket-http/src/test/java/com/robo4j/socket/http/test/units/HttpContextTests.java @@ -27,78 +27,74 @@ import com.robo4j.util.StringConstants; import com.robo4j.util.Utf8Constant; import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; -import java.io.InputStream; import java.util.Collections; -import java.util.List; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.*; /** - * - * * @author Marcus Hirt (@hirt) * @author Miroslav Wengner (@miragemiko) */ class HttpContextTests { - - @Test - void serverNotInitiatedContextTest() { - - ServerContext context = new ServerContext(); - System.out.println("context:" + context); - assertNotNull(context); - assertTrue(context.isEmpty()); - - } - - @Test - void serverDefaultContextTest() { - - ServerContext context = new ServerContext(); - HttpPathUtils.updateHttpServerContextPaths(null, context, Collections.emptyList()); - - System.out.println("context:" + context); - assertNotNull(context); - assertTrue(!context.isEmpty()); - assertTrue(context.containsPath(new PathHttpMethod(Utf8Constant.UTF8_SOLIDUS, HttpMethod.GET))); - - } - - @Test - void clientDefaultContextTest() { - - ClientContext context = new ClientContext(); - - System.out.println("context: " + context); - assertNotNull(context); - assertTrue(context.isEmpty()); - } - - @Test - void clientSimpleContextTest() throws Exception { - - RoboBuilder builderProducer = new RoboBuilder(); - InputStream contextIS = Thread.currentThread().getContextClassLoader() - .getResourceAsStream("robo_client_context.xml"); - builderProducer.add(contextIS); - - List paths = Collections.singletonList(new HttpPathMethodDTO(StringConstants.EMPTY, - HttpMethod.GET, Collections.singletonList(StringConsumer.NAME))); - - ClientContext context = new ClientContext(); - HttpPathUtils.updateHttpClientContextPaths(context, paths); - - PathHttpMethod basicGet = new PathHttpMethod(Utf8Constant.UTF8_SOLIDUS, HttpMethod.GET); - - System.out.println("context: " + context); - assertNotNull(context); - assertNotNull(context.getPathConfig(basicGet)); - assertTrue(!context.getPathConfig(basicGet).getCallbacks().isEmpty()); - assertEquals(HttpMethod.GET, context.getPathConfig(basicGet).getMethod()); - assertEquals(1, context.getPathConfig(basicGet).getCallbacks().size()); - assertEquals(StringConsumer.NAME, context.getPathConfig(basicGet).getCallbacks().get(0)); - } + private static final Logger LOGGER = LoggerFactory.getLogger(HttpContextTests.class); + + @Test + void serverNotInitiatedContextTest() { + ServerContext context = new ServerContext(); + + printContext(context); + assertNotNull(context); + assertTrue(context.isEmpty()); + + } + + @Test + void serverDefaultContextTest() { + var context = new ServerContext(); + HttpPathUtils.updateHttpServerContextPaths(null, context, Collections.emptyList()); + + printContext(context); + assertNotNull(context); + assertFalse(context.isEmpty()); + assertTrue(context.containsPath(new PathHttpMethod(Utf8Constant.UTF8_SOLIDUS, HttpMethod.GET))); + + } + + @Test + void clientDefaultContextTest() { + var context = new ClientContext(); + + printContext(context); + assertNotNull(context); + assertTrue(context.isEmpty()); + } + + @Test + void clientSimpleContextTest() throws Exception { + var builderProducer = new RoboBuilder(); + var contextIS = Thread.currentThread().getContextClassLoader() + .getResourceAsStream("robo_client_context.xml"); + builderProducer.add(contextIS); + var paths = Collections.singletonList(new HttpPathMethodDTO(StringConstants.EMPTY, + HttpMethod.GET, Collections.singletonList(StringConsumer.NAME))); + var context = new ClientContext(); + HttpPathUtils.updateHttpClientContextPaths(context, paths); + + var basicGet = new PathHttpMethod(Utf8Constant.UTF8_SOLIDUS, HttpMethod.GET); + + printContext(context); + assertNotNull(context); + assertNotNull(context.getPathConfig(basicGet)); + assertFalse(context.getPathConfig(basicGet).getCallbacks().isEmpty()); + assertEquals(HttpMethod.GET, context.getPathConfig(basicGet).getMethod()); + assertEquals(1, context.getPathConfig(basicGet).getCallbacks().size()); + assertEquals(StringConsumer.NAME, context.getPathConfig(basicGet).getCallbacks().get(0)); + } + + private static void printContext(T context) { + LOGGER.debug("context:{}", context); + } } diff --git a/robo4j-socket-http/src/test/java/module-info.java b/robo4j-socket-http/src/test/java/module-info.java index ac340134..c8fb55d9 100644 --- a/robo4j-socket-http/src/test/java/module-info.java +++ b/robo4j-socket-http/src/test/java/module-info.java @@ -4,6 +4,7 @@ requires org.junit.jupiter.api; requires org.junit.jupiter.engine; + requires org.slf4j; exports com.robo4j.socket.http.test.utils;