You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@hc.apache.org by ol...@apache.org on 2026/02/02 18:32:53 UTC
(httpcomponents-core) 02/02: Jackson 2 bindings for HttpCore - initial contribution
This is an automated email from the ASF dual-hosted git repository.
olegk pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/httpcomponents-core.git
commit f083b40eeb91c3b145edbee2f921f252e1d9b4bc
Author: Oleg Kalnichevski <ol...@apache.org>
AuthorDate: Fri Jan 30 18:39:18 2026 +0100
Jackson 2 bindings for HttpCore - initial contribution
---
httpcore5-jackson2/pom.xml | 103 ++++
.../hc/core5/jackson2/JsonAsyncTokenizer.java | 122 ++++
.../org/apache/hc/core5/jackson2/JsonConsumer.java | 62 +--
.../hc/core5/jackson2/JsonContentException.java | 61 +-
.../hc/core5/jackson2/JsonNodeAssembler.java | 227 ++++++++
.../apache/hc/core5/jackson2/JsonResultSink.java | 59 +-
.../hc/core5/jackson2/JsonTokenConsumer.java | 63 +--
.../hc/core5/jackson2/JsonTokenEventHandler.java | 101 ++++
.../jackson2/JsonTokenEventHandlerAdaptor.java | 101 ++++
.../apache/hc/core5/jackson2/JsonTokenizer.java | 75 +--
.../hc/core5/jackson2/TokenBufferAssembler.java | 89 +++
.../core5/jackson2/TopLevelArrayTokenFilter.java | 79 +--
.../core5/jackson2/bulk/JsonBulkArrayReader.java | 100 ++++
.../jackson2/http/AbstractJsonEntityConsumer.java | 111 ++++
.../jackson2/http/AbstractJsonEntityProducer.java | 123 +++++
.../jackson2/http/AbstractJsonMessageConsumer.java | 138 +++++
.../http/AbstractJsonSequenceEntityConsumer.java | 93 ++++
.../hc/core5/jackson2/http/InternalBuffer.java | 80 ++-
.../core5/jackson2/http/JsonMessageProducer.java | 74 +--
.../jackson2/http/JsonNodeEntityConsumer.java | 65 +--
.../jackson2/http/JsonNodeEntityProducer.java | 68 +--
.../http/JsonNodeSequenceEntityConsumer.java | 63 +--
.../jackson2/http/JsonObjectEntityConsumer.java | 82 +++
.../jackson2/http/JsonObjectEntityProducer.java | 67 +--
.../core5/jackson2/http/JsonRequestConsumer.java | 69 +++
.../core5/jackson2/http/JsonRequestConsumers.java | 208 +++++++
.../jackson2/http/JsonRequestObjectProducer.java | 67 +--
.../core5/jackson2/http/JsonRequestProducers.java | 104 ++++
.../core5/jackson2/http/JsonResponseConsumer.java | 92 ++++
.../core5/jackson2/http/JsonResponseConsumers.java | 494 +++++++++++++++++
.../jackson2/http/JsonResponseObjectProducer.java | 67 +--
.../core5/jackson2/http/JsonResponseProducers.java | 104 ++++
.../jackson2/http/JsonSequenceEntityConsumer.java | 64 +++
.../jackson2/http/JsonSequenceEntityProducer.java | 175 ++++++
.../jackson2/http/JsonSequenceRequestConsumer.java | 76 +++
.../http/JsonSequenceResponseConsumer.java | 106 ++++
.../jackson2/http/JsonTokenEntityConsumer.java | 71 +++
.../jackson2/http/JsonTokenEntityProducer.java | 69 +--
.../jackson2/http/NoopJsonEntityConsumer.java | 88 +++
.../hc/core5/jackson2/http/ObjectChannel.java | 69 +--
.../hc/core5/jackson2/http/ObjectProducer.java | 62 +--
.../hc/core5/jackson2/JsonNodeAssemblerTest.java | 115 ++++
.../jackson2/JsonTokenBufferAssemblerTest.java | 330 +++++++++++
.../hc/core5/jackson2/JsonTokenizerTest.java | 612 +++++++++++++++++++++
.../jackson2/bulk/JsonBulkArrayReaderTest.java | 127 +++++
.../jackson2/http/BasicDataStreamChannel.java | 69 +--
.../jackson2/http/CompletableFutureCallback.java | 65 +--
.../core5/jackson2/http/HttpResponseException.java | 62 +--
.../jackson2/http/JsonEntityConsumersTest.java | 578 +++++++++++++++++++
.../jackson2/http/JsonEntityProducersTest.java | 188 +++++++
.../jackson2/http/JsonRequestConsumersTest.java | 232 ++++++++
.../jackson2/http/JsonResponseConsumersTest.java | 363 ++++++++++++
.../apache/hc/core5/jackson2/http/RequestData.java | 123 +++++
.../jackson2/http/WritableByteChannelMock.java | 125 +++++
.../http/examles/JsonBulkArrayReaderExample.java | 61 ++
.../http/examles/JsonNodeResponseExample.java | 104 ++++
.../http/examles/JsonObjectRequestExample.java | 111 ++++
.../http/examles/JsonSequenceRequestExample.java | 114 ++++
.../http/examles/JsonSequenceResponseExample.java | 106 ++++
.../examles/JsonTokenEventResponseExample.java | 172 ++++++
httpcore5-jackson2/src/test/resources/sample1.json | 15 +
httpcore5-jackson2/src/test/resources/sample2.json | 35 ++
httpcore5-jackson2/src/test/resources/sample3.json | 48 ++
httpcore5-jackson2/src/test/resources/sample4.json | 1 +
httpcore5-jackson2/src/test/resources/sample5.json | 3 +
httpcore5-jackson2/src/test/resources/sample6.json | 50 ++
httpcore5-jackson2/src/test/resources/sample7.json | 19 +
.../java/org/apache/hc/core5/http/Message.java | 23 +-
pom.xml | 12 +
69 files changed, 7077 insertions(+), 977 deletions(-)
diff --git a/httpcore5-jackson2/pom.xml b/httpcore5-jackson2/pom.xml
new file mode 100644
index 000000000..c14bcc962
--- /dev/null
+++ b/httpcore5-jackson2/pom.xml
@@ -0,0 +1,103 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements. See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership. The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied. See the License for the
+ specific language governing permissions and limitations
+ under the License.
+ ====================================================================
+
+ This software consists of voluntary contributions made by many
+ individuals on behalf of the Apache Software Foundation. For more
+ information on the Apache Software Foundation, please see
+ <http://www.apache.org />.
+--><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <parent>
+ <artifactId>httpcore5-parent</artifactId>
+ <groupId>org.apache.httpcomponents.core5</groupId>
+ <version>5.5-alpha1-SNAPSHOT</version>
+ </parent>
+ <modelVersion>4.0.0</modelVersion>
+
+ <artifactId>httpcore5-jackson2</artifactId>
+ <name>Jackson 2 bindings for Apache HttpComponents Core</name>
+ <description>Apache HttpComponents JSON bindings</description>
+
+ <properties>
+ <Automatic-Module-Name>org.apache.httpcomponents.core5.httpcore5.json</Automatic-Module-Name>
+ </properties>
+
+ <dependencies>
+ <dependency>
+ <groupId>org.apache.httpcomponents.core5</groupId>
+ <artifactId>httpcore5</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>com.fasterxml.jackson.core</groupId>
+ <artifactId>jackson-databind</artifactId>
+ <version>2.21.0</version>
+ </dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.assertj</groupId>
+ <artifactId>assertj-core</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.mockito</groupId>
+ <artifactId>mockito-core</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-api</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.logging.log4j</groupId>
+ <artifactId>log4j-slf4j-impl</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.logging.log4j</groupId>
+ <artifactId>log4j-core</artifactId>
+ <scope>test</scope>
+ </dependency>
+ </dependencies>
+
+ <reporting>
+ <plugins>
+ <plugin>
+ <artifactId>maven-project-info-reports-plugin</artifactId>
+ <inherited>false</inherited>
+ <reportSets>
+ <reportSet>
+ <reports>
+ <report>index</report>
+ <report>dependencies</report>
+ <report>dependency-info</report>
+ <report>summary</report>
+ </reports>
+ </reportSet>
+ </reportSets>
+ </plugin>
+ </plugins>
+ </reporting>
+
+</project>
diff --git a/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/JsonAsyncTokenizer.java b/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/JsonAsyncTokenizer.java
new file mode 100644
index 000000000..fa8845951
--- /dev/null
+++ b/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/JsonAsyncTokenizer.java
@@ -0,0 +1,122 @@
+/*
+ * ====================================================================
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * <http://www.apache.org/>.
+ *
+ */
+package org.apache.hc.core5.jackson2;
+
+import java.io.IOException;
+import java.nio.ByteBuffer;
+
+import com.fasterxml.jackson.core.JsonFactory;
+import com.fasterxml.jackson.core.JsonParser;
+import com.fasterxml.jackson.core.JsonToken;
+import com.fasterxml.jackson.core.JsonTokenId;
+import com.fasterxml.jackson.core.async.ByteArrayFeeder;
+
+import org.apache.hc.core5.util.Args;
+
+/**
+ * Event-driven, reactive JSON tokenizer that consumes data from a sequence
+ * {@link ByteBuffer} objects and emits events to {@link JsonTokenConsumer}.
+ *
+ * @since 5.5
+ */
+public final class JsonAsyncTokenizer {
+
+ private final JsonFactory jsonFactory;
+
+ private JsonTokenConsumer consumer;
+ private JsonParser parser;
+ private ByteArrayFeeder inputFeeder;
+
+ public JsonAsyncTokenizer(final JsonFactory jsonFactory) {
+ this.jsonFactory = jsonFactory;
+ }
+
+ /**
+ * Triggered to initialize the tokenizer and pass the token event consumer.
+ *
+ * @param consumer the token event consumer.
+ */
+ public void initialize(final JsonTokenConsumer consumer) throws IOException {
+ Args.notNull(consumer, "Consumer");
+ this.parser = jsonFactory.createNonBlockingByteArrayParser();
+ this.inputFeeder = (ByteArrayFeeder) parser.getNonBlockingInputFeeder();
+ this.consumer = consumer;
+ }
+
+ private void processData() throws IOException {
+ for (; ; ) {
+ final JsonToken jsonToken = parser.nextToken();
+ if (jsonToken == null || jsonToken == JsonToken.NOT_AVAILABLE) {
+ break;
+ } else {
+ consumer.accept(jsonToken.id(), parser);
+ }
+ }
+ }
+
+ /**
+ * Triggered to feed a chunk of data. As a result of this method call the tokenizer
+ * may emit events to the token event consumer.
+ *
+ * @param data the chunk of data
+ */
+ public void consume(final ByteBuffer data) throws IOException {
+ if (data == null) {
+ return;
+ }
+ if (consumer == null) {
+ return;
+ }
+ if (data.hasArray()) {
+ final int off = data.arrayOffset();
+ inputFeeder.feedInput(data.array(), off + data.position(), off + data.limit());
+ data.position(data.limit());
+ } else {
+ final byte[] tmp = new byte[data.remaining()];
+ data.get(tmp);
+ inputFeeder.feedInput(tmp, 0, tmp.length);
+ }
+ processData();
+ }
+
+ /**
+ * Triggered to signal the end of data stream. As a result of this method call the tokenizer
+ * may emit events to the token event consumer.
+ */
+ public void streamEnd() throws IOException {
+ if (consumer == null) {
+ return;
+ }
+ inputFeeder.endOfInput();
+ processData();
+ consumer.accept(JsonTokenId.ID_NO_TOKEN, parser);
+ inputFeeder = null;
+ parser = null;
+ consumer = null;
+ }
+
+}
diff --git a/httpcore5/src/main/java/org/apache/hc/core5/http/Message.java b/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/JsonConsumer.java
similarity index 50%
copy from httpcore5/src/main/java/org/apache/hc/core5/http/Message.java
copy to httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/JsonConsumer.java
index b60d9724b..ee0a07fa4 100644
--- a/httpcore5/src/main/java/org/apache/hc/core5/http/Message.java
+++ b/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/JsonConsumer.java
@@ -24,66 +24,18 @@
* <http://www.apache.org/>.
*
*/
+package org.apache.hc.core5.jackson2;
-package org.apache.hc.core5.http;
-
-import org.apache.hc.core5.util.Args;
+import java.io.IOException;
/**
- * Generic message consisting of a message head and a message body.
- *
- * @param <H> message head type.
- * @param <B> message body type.
+ * Represents an event recipient that can react to JSON input.
*
- * @since 5.0
+ * @since 5.5
*/
-public final class Message<H extends MessageHeaders, B> {
-
- private final H head;
- private final B body;
-
- /**
- * Constructs a new instance.
- *
- * @param head The message head.
- * @since 5.3
- */
- public Message(final H head) {
- this(head, null);
- }
-
- /**
- * Constructs a new instance.
- *
- * @param head The message head.
- * @param body The message body.
- */
- public Message(final H head, final B body) {
- this.head = Args.notNull(head, "Message head");
- this.body = body;
- }
-
- /**
- * Gets the message head.
- *
- * @return the message head.
- */
- public H getHead() {
- return head;
- }
-
- /**
- * Gets the message body.
- *
- * @return the message body.
- */
- public B getBody() {
- return body;
- }
+@FunctionalInterface
+public interface JsonConsumer<T> {
- @Override
- public String toString() {
- return "[head=" + head + ", body=" + body + ']';
- }
+ void accept(T input) throws IOException;
}
diff --git a/httpcore5/src/main/java/org/apache/hc/core5/http/Message.java b/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/JsonContentException.java
similarity index 51%
copy from httpcore5/src/main/java/org/apache/hc/core5/http/Message.java
copy to httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/JsonContentException.java
index b60d9724b..b1a875acd 100644
--- a/httpcore5/src/main/java/org/apache/hc/core5/http/Message.java
+++ b/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/JsonContentException.java
@@ -24,66 +24,23 @@
* <http://www.apache.org/>.
*
*/
+package org.apache.hc.core5.jackson2;
-package org.apache.hc.core5.http;
-
-import org.apache.hc.core5.util.Args;
+import com.fasterxml.jackson.core.JsonProcessingException;
/**
- * Generic message consisting of a message head and a message body.
- *
- * @param <H> message head type.
- * @param <B> message body type.
+ * Signals a failure processing a malformed or unexpected JSON message
*
- * @since 5.0
+ * @since 5.5
*/
-public final class Message<H extends MessageHeaders, B> {
-
- private final H head;
- private final B body;
-
- /**
- * Constructs a new instance.
- *
- * @param head The message head.
- * @since 5.3
- */
- public Message(final H head) {
- this(head, null);
- }
-
- /**
- * Constructs a new instance.
- *
- * @param head The message head.
- * @param body The message body.
- */
- public Message(final H head, final B body) {
- this.head = Args.notNull(head, "Message head");
- this.body = body;
- }
-
- /**
- * Gets the message head.
- *
- * @return the message head.
- */
- public H getHead() {
- return head;
- }
+public class JsonContentException extends JsonProcessingException {
- /**
- * Gets the message body.
- *
- * @return the message body.
- */
- public B getBody() {
- return body;
+ public JsonContentException(final String msg) {
+ super(msg);
}
- @Override
- public String toString() {
- return "[head=" + head + ", body=" + body + ']';
+ public JsonContentException(final String msg, final Throwable rootCause) {
+ super(msg, rootCause);
}
}
diff --git a/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/JsonNodeAssembler.java b/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/JsonNodeAssembler.java
new file mode 100644
index 000000000..1b65b1309
--- /dev/null
+++ b/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/JsonNodeAssembler.java
@@ -0,0 +1,227 @@
+/*
+ * ====================================================================
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * <http://www.apache.org/>.
+ *
+ */
+package org.apache.hc.core5.jackson2;
+
+import java.util.LinkedList;
+import java.util.function.Consumer;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.node.ArrayNode;
+import com.fasterxml.jackson.databind.node.ContainerNode;
+import com.fasterxml.jackson.databind.node.JsonNodeCreator;
+import com.fasterxml.jackson.databind.node.JsonNodeFactory;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+
+/**
+ * {@link JsonTokenEventHandler} implementation that assembles an {@link JsonNode}
+ * instance based on JSON token events it receives and passes the resultant
+ * object to a {@link Consumer}.
+ *
+ * @since 5.5
+ */
+public final class JsonNodeAssembler implements JsonTokenEventHandler {
+
+ public static JsonNodeAssembler create() {
+ return new JsonNodeAssembler(JsonNodeFactory.instance, null);
+ }
+
+ public static JsonNodeAssembler create(final JsonNodeCreator jsonNodeCreator, final Consumer<JsonNode> consumer) {
+ return new JsonNodeAssembler(jsonNodeCreator, consumer);
+ }
+
+ public static JsonTokenConsumer createTokenConsumer() {
+ return new JsonTokenEventHandlerAdaptor(new JsonNodeAssembler(JsonNodeFactory.instance, null));
+ }
+
+ public static JsonTokenConsumer createTokenConsumer(final Consumer<JsonNode> consumer) {
+ return new JsonTokenEventHandlerAdaptor(new JsonNodeAssembler(JsonNodeFactory.instance, consumer));
+ }
+
+ private final JsonNodeCreator jsonNodeCreator;
+ private final Consumer<JsonNode> consumer;
+ private final LinkedList<ContainerNode<?>> nodeStack;
+
+ private JsonNode root;
+ private ContainerNode<?> currentObject;
+ private String currentField;
+ private JsonNode result;
+
+ public JsonNodeAssembler(final JsonNodeCreator jsonNodeCreator, final Consumer<JsonNode> consumer) {
+ this.jsonNodeCreator = jsonNodeCreator != null ? jsonNodeCreator : JsonNodeFactory.instance;
+ this.consumer = consumer;
+ this.nodeStack = new LinkedList<>();
+ }
+
+ @Override
+ public void objectStart() {
+ if (currentObject != null) {
+ final ObjectNode newJsonObject;
+ if (currentObject instanceof ObjectNode) {
+ newJsonObject = ((ObjectNode) currentObject).putObject(currentField);
+ } else if (currentObject instanceof ArrayNode) {
+ newJsonObject = ((ArrayNode) currentObject).addObject();
+ } else {
+ throw new IllegalStateException("Unexpected node class: " + currentObject.getClass());
+ }
+ nodeStack.addLast(currentObject);
+ currentObject = newJsonObject;
+ } else {
+ currentObject = jsonNodeCreator.objectNode();
+ if (root == null) {
+ root = currentObject;
+ }
+ }
+ }
+
+ @Override
+ public void objectEnd() {
+ currentObject = !nodeStack.isEmpty() ? nodeStack.removeLast() : null;
+ }
+
+ @Override
+ public void arrayStart() {
+ if (currentObject != null) {
+ final ArrayNode newJsonObject;
+ if (currentObject instanceof ObjectNode) {
+ newJsonObject = ((ObjectNode) currentObject).putArray(currentField);
+ } else if (currentObject instanceof ArrayNode) {
+ newJsonObject = ((ArrayNode) currentObject).addArray();
+ } else {
+ throw new IllegalStateException("Unexpected node class: " + currentObject.getClass());
+ }
+ nodeStack.addLast(currentObject);
+ currentObject = newJsonObject;
+ } else {
+ currentObject = jsonNodeCreator.arrayNode();
+ if (root == null) {
+ root = currentObject;
+ }
+ }
+ }
+
+ @Override
+ public void arrayEnd() {
+ currentObject = !nodeStack.isEmpty() ? nodeStack.removeLast() : null;
+ }
+
+ @Override
+ public void field(final String name) {
+ currentField = name;
+ }
+
+ @Override
+ public void embeddedObject(final Object object) {
+ if (currentObject == null) {
+ throw new IllegalStateException("Current node is null");
+ } else if (currentObject instanceof ObjectNode) {
+ ((ObjectNode) currentObject).putPOJO(currentField, object);
+ } else if (currentObject instanceof ArrayNode) {
+ ((ArrayNode) currentObject).addPOJO(object);
+ } else {
+ throw new IllegalStateException("Unexpected node class: " + currentObject.getClass());
+ }
+ }
+
+ @Override
+ public void value(final String value) {
+ if (currentObject instanceof ObjectNode) {
+ ((ObjectNode) currentObject).put(currentField, value);
+ } else if (currentObject instanceof ArrayNode) {
+ ((ArrayNode) currentObject).add(value);
+ } else {
+ throw new IllegalStateException("Unexpected node class: " + currentObject.getClass());
+ }
+ }
+
+ @Override
+ public void value(final int value) {
+ if (currentObject instanceof ObjectNode) {
+ ((ObjectNode) currentObject).put(currentField, value);
+ } else if (currentObject instanceof ArrayNode) {
+ ((ArrayNode) currentObject).add(value);
+ } else {
+ throw new IllegalStateException("Unexpected node class: " + currentObject.getClass());
+ }
+ }
+
+ @Override
+ public void value(final long value) {
+ if (currentObject instanceof ObjectNode) {
+ ((ObjectNode) currentObject).put(currentField, value);
+ } else if (currentObject instanceof ArrayNode) {
+ ((ArrayNode) currentObject).add(value);
+ } else {
+ throw new IllegalStateException("Unexpected node class: " + currentObject.getClass());
+ }
+ }
+
+ @Override
+ public void value(final double value) {
+ if (currentObject instanceof ObjectNode) {
+ ((ObjectNode) currentObject).put(currentField, value);
+ } else if (currentObject instanceof ArrayNode) {
+ ((ArrayNode) currentObject).add(value);
+ } else {
+ throw new IllegalStateException("Unexpected node class: " + currentObject.getClass());
+ }
+ }
+
+ @Override
+ public void value(final boolean value) {
+ if (currentObject instanceof ObjectNode) {
+ ((ObjectNode) currentObject).put(currentField, value);
+ } else if (currentObject instanceof ArrayNode) {
+ ((ArrayNode) currentObject).add(value);
+ } else {
+ throw new IllegalStateException("Unexpected node class: " + currentObject.getClass());
+ }
+ }
+
+ @Override
+ public void valueNull() {
+ if (currentObject instanceof ObjectNode) {
+ ((ObjectNode) currentObject).putNull(currentField);
+ } else if (currentObject instanceof ArrayNode) {
+ ((ArrayNode) currentObject).addNull();
+ } else {
+ throw new IllegalStateException("Unexpected node class: " + currentObject.getClass());
+ }
+ }
+
+ @Override
+ public void endOfStream() {
+ result = root;
+ if (consumer != null) {
+ consumer.accept(result);
+ }
+ }
+
+ public JsonNode getResult() {
+ return result;
+ }
+
+}
diff --git a/httpcore5/src/main/java/org/apache/hc/core5/http/Message.java b/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/JsonResultSink.java
similarity index 52%
copy from httpcore5/src/main/java/org/apache/hc/core5/http/Message.java
copy to httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/JsonResultSink.java
index b60d9724b..1e258d2e4 100644
--- a/httpcore5/src/main/java/org/apache/hc/core5/http/Message.java
+++ b/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/JsonResultSink.java
@@ -24,66 +24,31 @@
* <http://www.apache.org/>.
*
*/
+package org.apache.hc.core5.jackson2;
-package org.apache.hc.core5.http;
-
-import org.apache.hc.core5.util.Args;
+import java.util.function.Consumer;
/**
- * Generic message consisting of a message head and a message body.
- *
- * @param <H> message head type.
- * @param <B> message body type.
+ * Represents a recipient of zero or many results of JSON message processing.
*
- * @since 5.0
+ * @param <T> the type of object that represents a result of JSON message processing.
+ * @since 5.5
*/
-public final class Message<H extends MessageHeaders, B> {
-
- private final H head;
- private final B body;
-
- /**
- * Constructs a new instance.
- *
- * @param head The message head.
- * @since 5.3
- */
- public Message(final H head) {
- this(head, null);
- }
+public interface JsonResultSink<T> extends Consumer<T> {
/**
- * Constructs a new instance.
+ * Signals the beginning of the stream of result objects.
*
- * @param head The message head.
- * @param body The message body.
+ * @param sizeHint the expected size of the object stream, if known.
+ * {@code -1} otherwise.
*/
- public Message(final H head, final B body) {
- this.head = Args.notNull(head, "Message head");
- this.body = body;
+ default void begin(final int sizeHint) {
}
/**
- * Gets the message head.
- *
- * @return the message head.
- */
- public H getHead() {
- return head;
- }
-
- /**
- * Gets the message body.
- *
- * @return the message body.
+ * Signals the end of the stream of result objects.
*/
- public B getBody() {
- return body;
- }
-
- @Override
- public String toString() {
- return "[head=" + head + ", body=" + body + ']';
+ default void end() {
}
}
diff --git a/httpcore5/src/main/java/org/apache/hc/core5/http/Message.java b/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/JsonTokenConsumer.java
similarity index 51%
copy from httpcore5/src/main/java/org/apache/hc/core5/http/Message.java
copy to httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/JsonTokenConsumer.java
index b60d9724b..2f4105696 100644
--- a/httpcore5/src/main/java/org/apache/hc/core5/http/Message.java
+++ b/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/JsonTokenConsumer.java
@@ -24,66 +24,27 @@
* <http://www.apache.org/>.
*
*/
+package org.apache.hc.core5.jackson2;
-package org.apache.hc.core5.http;
+import java.io.IOException;
-import org.apache.hc.core5.util.Args;
+import com.fasterxml.jackson.core.JsonParser;
/**
- * Generic message consisting of a message head and a message body.
+ * Represents an event recipient that can react to a stream of consecutive JSON tokens.
*
- * @param <H> message head type.
- * @param <B> message body type.
- *
- * @since 5.0
+ * @since 5.5
*/
-public final class Message<H extends MessageHeaders, B> {
-
- private final H head;
- private final B body;
-
- /**
- * Constructs a new instance.
- *
- * @param head The message head.
- * @since 5.3
- */
- public Message(final H head) {
- this(head, null);
- }
+@FunctionalInterface
+public interface JsonTokenConsumer {
/**
- * Constructs a new instance.
+ * Triggered to signal {@link JsonParser} transition to a new token.
*
- * @param head The message head.
- * @param body The message body.
+ * @param tokenId Id representing of the current token held by the parser.
+ * @param jsonParser the JSON parser.
+ * @see com.fasterxml.jackson.core.JsonTokenId
*/
- public Message(final H head, final B body) {
- this.head = Args.notNull(head, "Message head");
- this.body = body;
- }
-
- /**
- * Gets the message head.
- *
- * @return the message head.
- */
- public H getHead() {
- return head;
- }
-
- /**
- * Gets the message body.
- *
- * @return the message body.
- */
- public B getBody() {
- return body;
- }
-
- @Override
- public String toString() {
- return "[head=" + head + ", body=" + body + ']';
- }
+ void accept(int tokenId, JsonParser jsonParser) throws IOException;
}
diff --git a/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/JsonTokenEventHandler.java b/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/JsonTokenEventHandler.java
new file mode 100644
index 000000000..56142d26a
--- /dev/null
+++ b/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/JsonTokenEventHandler.java
@@ -0,0 +1,101 @@
+/*
+ * ====================================================================
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * <http://www.apache.org/>.
+ *
+ */
+package org.apache.hc.core5.jackson2;
+
+/**
+ * Represents a handler of JSON token events.
+ *
+ * @since 5.5
+ */
+public interface JsonTokenEventHandler {
+
+ /**
+ * Triggered to signal the beginning of an object.
+ */
+ void objectStart();
+
+ /**
+ * Triggered to signal the end of an object.
+ */
+ void objectEnd();
+
+ /**
+ * Triggered to signal the beginning of an array.
+ */
+ void arrayStart();
+
+ /**
+ * Triggered to signal the end of an array.
+ */
+ void arrayEnd();
+
+ /**
+ * Triggered to signal occurrence of a field with the specified name.
+ */
+ void field(String name);
+
+ /**
+ * Triggered to signal occurrence of an embedded object.
+ */
+ void embeddedObject(Object object);
+
+ /**
+ * Triggered to signal occurrence of a textual value.
+ */
+ void value(String value);
+
+ /**
+ * Triggered to signal occurrence of an integer value.
+ */
+ void value(int value);
+
+ /**
+ * Triggered to signal occurrence of a long value.
+ */
+ void value(long value);
+
+ /**
+ * Triggered to signal occurrence of an double precision value.
+ */
+ void value(double value);
+
+ /**
+ * Triggered to signal occurrence of an boolean value.
+ */
+ void value(boolean value);
+
+ /**
+ * Triggered to signal occurrence of a null value.
+ */
+ void valueNull();
+
+ /**
+ * Triggered to signal the end of the token stream.
+ */
+ void endOfStream();
+
+}
diff --git a/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/JsonTokenEventHandlerAdaptor.java b/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/JsonTokenEventHandlerAdaptor.java
new file mode 100644
index 000000000..ffbe1f928
--- /dev/null
+++ b/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/JsonTokenEventHandlerAdaptor.java
@@ -0,0 +1,101 @@
+/*
+ * ====================================================================
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * <http://www.apache.org/>.
+ *
+ */
+package org.apache.hc.core5.jackson2;
+
+import java.io.IOException;
+
+import com.fasterxml.jackson.core.JsonParser;
+import com.fasterxml.jackson.core.JsonTokenId;
+
+/**
+ * {@link JsonTokenConsumer} implementation that converts JSON tokens into
+ * event signals for {@link JsonTokenEventHandler}.
+ *
+ * @since 5.5
+ */
+public final class JsonTokenEventHandlerAdaptor implements JsonTokenConsumer {
+
+ private final JsonTokenEventHandler eventHandler;
+
+ public JsonTokenEventHandlerAdaptor(final JsonTokenEventHandler eventHandler) {
+ this.eventHandler = eventHandler;
+ }
+
+ public void accept(final int tokenId, final JsonParser jsonParser) throws IOException {
+ switch (tokenId) {
+ case JsonTokenId.ID_START_OBJECT:
+ eventHandler.objectStart();
+ break;
+ case JsonTokenId.ID_END_OBJECT:
+ eventHandler.objectEnd();
+ break;
+ case JsonTokenId.ID_START_ARRAY:
+ eventHandler.arrayStart();
+ break;
+ case JsonTokenId.ID_END_ARRAY:
+ eventHandler.arrayEnd();
+ break;
+ case JsonTokenId.ID_FIELD_NAME:
+ eventHandler.field(jsonParser.getText());
+ break;
+ case JsonTokenId.ID_STRING:
+ eventHandler.value(jsonParser.getText());
+ break;
+ case JsonTokenId.ID_NUMBER_INT:
+ final JsonParser.NumberType numberType = jsonParser.getNumberType();
+ final Number numberValue = jsonParser.getNumberValue();
+ if (numberType == JsonParser.NumberType.LONG) {
+ eventHandler.value(numberValue.longValue());
+ } else {
+ eventHandler.value(numberValue.intValue());
+ }
+ break;
+ case JsonTokenId.ID_NUMBER_FLOAT:
+ eventHandler.value(jsonParser.getDoubleValue());
+ break;
+ case JsonTokenId.ID_TRUE:
+ eventHandler.value(true);
+ break;
+ case JsonTokenId.ID_FALSE:
+ eventHandler.value(false);
+ break;
+ case JsonTokenId.ID_NULL:
+ eventHandler.valueNull();
+ break;
+ case JsonTokenId.ID_EMBEDDED_OBJECT:
+ eventHandler.embeddedObject(jsonParser.getEmbeddedObject());
+ break;
+ case JsonTokenId.ID_NO_TOKEN:
+ eventHandler.endOfStream();
+ break;
+ default:
+ throw new IllegalStateException("Unexpected JSON token id: " + tokenId);
+ }
+
+ }
+
+}
diff --git a/httpcore5/src/main/java/org/apache/hc/core5/http/Message.java b/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/JsonTokenizer.java
similarity index 52%
copy from httpcore5/src/main/java/org/apache/hc/core5/http/Message.java
copy to httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/JsonTokenizer.java
index b60d9724b..28911d7c8 100644
--- a/httpcore5/src/main/java/org/apache/hc/core5/http/Message.java
+++ b/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/JsonTokenizer.java
@@ -24,66 +24,43 @@
* <http://www.apache.org/>.
*
*/
+package org.apache.hc.core5.jackson2;
-package org.apache.hc.core5.http;
+import java.io.IOException;
+import java.io.InputStream;
+
+import com.fasterxml.jackson.core.JsonFactory;
+import com.fasterxml.jackson.core.JsonParser;
+import com.fasterxml.jackson.core.JsonToken;
+import com.fasterxml.jackson.core.JsonTokenId;
import org.apache.hc.core5.util.Args;
/**
- * Generic message consisting of a message head and a message body.
- *
- * @param <H> message head type.
- * @param <B> message body type.
+ * Classic (blocking) JSON tokenizer that consumes data from {@link InputStream}
+ * and emits events to {@link JsonTokenConsumer}.
*
- * @since 5.0
+ * @since 5.5
*/
-public final class Message<H extends MessageHeaders, B> {
-
- private final H head;
- private final B body;
-
- /**
- * Constructs a new instance.
- *
- * @param head The message head.
- * @since 5.3
- */
- public Message(final H head) {
- this(head, null);
- }
-
- /**
- * Constructs a new instance.
- *
- * @param head The message head.
- * @param body The message body.
- */
- public Message(final H head, final B body) {
- this.head = Args.notNull(head, "Message head");
- this.body = body;
- }
+public final class JsonTokenizer {
- /**
- * Gets the message head.
- *
- * @return the message head.
- */
- public H getHead() {
- return head;
- }
+ private final JsonFactory jsonFactory;
- /**
- * Gets the message body.
- *
- * @return the message body.
- */
- public B getBody() {
- return body;
+ public JsonTokenizer(final JsonFactory jsonFactory) {
+ this.jsonFactory = jsonFactory;
}
- @Override
- public String toString() {
- return "[head=" + head + ", body=" + body + ']';
+ public void tokenize(final InputStream inputStream,
+ final JsonTokenConsumer consumer) throws IOException {
+ Args.notNull(consumer, "Consumer");
+ final JsonParser parser = jsonFactory.createParser(inputStream);
+ while (!parser.isClosed()) {
+ final JsonToken jsonToken = parser.nextToken();
+ if (jsonToken != null) {
+ consumer.accept(jsonToken.id(), parser);
+ }
+ }
+ consumer.accept(JsonTokenId.ID_NO_TOKEN, parser);
}
}
diff --git a/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/TokenBufferAssembler.java b/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/TokenBufferAssembler.java
new file mode 100644
index 000000000..0131d2350
--- /dev/null
+++ b/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/TokenBufferAssembler.java
@@ -0,0 +1,89 @@
+/*
+ * ====================================================================
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * <http://www.apache.org/>.
+ *
+ */
+
+package org.apache.hc.core5.jackson2;
+
+import java.io.IOException;
+
+import com.fasterxml.jackson.core.JsonParser;
+import com.fasterxml.jackson.core.JsonTokenId;
+import com.fasterxml.jackson.databind.util.TokenBuffer;
+
+import org.apache.hc.core5.util.Args;
+
+/**
+ * {@link JsonTokenConsumer} implementation that copies Json token events
+ * into {@link TokenBuffer} and passes those buffers to the {@link JsonResultSink}.
+ *
+ * @since 5.5
+ */
+public final class TokenBufferAssembler implements JsonTokenConsumer {
+
+ private final JsonResultSink<TokenBuffer> sink;
+
+ private boolean started;
+ private int depth;
+ private TokenBuffer buffer;
+
+ public TokenBufferAssembler(final JsonResultSink<TokenBuffer> sink) {
+ Args.notNull(sink, "Result sink");
+ this.sink = sink;
+ this.buffer = new TokenBuffer(null, false);
+ }
+
+ public void accept(final int tokenId, final JsonParser jsonParser) throws IOException {
+ if (!started) {
+ started = true;
+ sink.begin(-1);
+ }
+ if (tokenId != JsonTokenId.ID_NO_TOKEN) {
+ buffer.copyCurrentEvent(jsonParser);
+ }
+ switch (tokenId) {
+ case JsonTokenId.ID_START_OBJECT:
+ case JsonTokenId.ID_START_ARRAY:
+ depth++;
+ break;
+ case JsonTokenId.ID_END_OBJECT:
+ case JsonTokenId.ID_END_ARRAY:
+ depth--;
+ if (depth == 0) {
+ buffer.close();
+ sink.accept(buffer);
+ buffer = new TokenBuffer(null, false);
+ }
+ break;
+ case JsonTokenId.ID_NO_TOKEN:
+ if (!buffer.isClosed()) {
+ buffer.close();
+ }
+ sink.end();
+ break;
+ }
+ }
+
+}
diff --git a/httpcore5/src/main/java/org/apache/hc/core5/http/Message.java b/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/TopLevelArrayTokenFilter.java
similarity index 51%
copy from httpcore5/src/main/java/org/apache/hc/core5/http/Message.java
copy to httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/TopLevelArrayTokenFilter.java
index b60d9724b..095ff1518 100644
--- a/httpcore5/src/main/java/org/apache/hc/core5/http/Message.java
+++ b/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/TopLevelArrayTokenFilter.java
@@ -25,65 +25,46 @@
*
*/
-package org.apache.hc.core5.http;
+package org.apache.hc.core5.jackson2;
+
+import java.io.IOException;
+
+import com.fasterxml.jackson.core.JsonParser;
+import com.fasterxml.jackson.core.JsonTokenId;
import org.apache.hc.core5.util.Args;
/**
- * Generic message consisting of a message head and a message body.
- *
- * @param <H> message head type.
- * @param <B> message body type.
+ * {@link JsonTokenConsumer} decorator that filters out top level opening and closing array tokens.
*
- * @since 5.0
+ * @since 5.5
*/
-public final class Message<H extends MessageHeaders, B> {
+public final class TopLevelArrayTokenFilter implements JsonTokenConsumer {
- private final H head;
- private final B body;
-
- /**
- * Constructs a new instance.
- *
- * @param head The message head.
- * @since 5.3
- */
- public Message(final H head) {
- this(head, null);
- }
-
- /**
- * Constructs a new instance.
- *
- * @param head The message head.
- * @param body The message body.
- */
- public Message(final H head, final B body) {
- this.head = Args.notNull(head, "Message head");
- this.body = body;
- }
-
- /**
- * Gets the message head.
- *
- * @return the message head.
- */
- public H getHead() {
- return head;
- }
+ private final JsonTokenConsumer tokenConsumer;
+ private int depth;
- /**
- * Gets the message body.
- *
- * @return the message body.
- */
- public B getBody() {
- return body;
+ public TopLevelArrayTokenFilter(final JsonTokenConsumer tokenConsumer) {
+ Args.notNull(tokenConsumer, "Consumer");
+ this.tokenConsumer = tokenConsumer;
}
- @Override
- public String toString() {
- return "[head=" + head + ", body=" + body + ']';
+ public void accept(final int tokenId, final JsonParser jsonParser) throws IOException {
+ if (depth == 0 &&
+ (tokenId == JsonTokenId.ID_START_ARRAY || tokenId == JsonTokenId.ID_END_ARRAY)) {
+ return;
+ }
+ switch (tokenId) {
+ case JsonTokenId.ID_START_OBJECT:
+ case JsonTokenId.ID_START_ARRAY:
+ depth++;
+ break;
+ case JsonTokenId.ID_END_OBJECT:
+ case JsonTokenId.ID_END_ARRAY:
+ depth--;
+ break;
+ }
+ tokenConsumer.accept(tokenId, jsonParser);
}
}
diff --git a/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/bulk/JsonBulkArrayReader.java b/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/bulk/JsonBulkArrayReader.java
new file mode 100644
index 000000000..4a9012fcb
--- /dev/null
+++ b/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/bulk/JsonBulkArrayReader.java
@@ -0,0 +1,100 @@
+/*
+ * ====================================================================
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * <http://www.apache.org/>.
+ *
+ */
+package org.apache.hc.core5.jackson2.bulk;
+
+import java.io.IOException;
+import java.io.UncheckedIOException;
+import java.nio.ByteBuffer;
+
+import com.fasterxml.jackson.core.JsonParser;
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.util.TokenBuffer;
+
+import org.apache.hc.core5.jackson2.JsonAsyncTokenizer;
+import org.apache.hc.core5.jackson2.JsonResultSink;
+import org.apache.hc.core5.jackson2.TokenBufferAssembler;
+import org.apache.hc.core5.jackson2.TopLevelArrayTokenFilter;
+
+/**
+ * Event-driven bulk JSON reader that can read arrays of objects while buffering only a single
+ * array element in memory.
+ *
+ * @since 5.5
+ */
+public final class JsonBulkArrayReader {
+
+ private final ObjectMapper objectMapper;
+ private final JsonAsyncTokenizer jsonTokenizer;
+
+ public JsonBulkArrayReader(final ObjectMapper objectMapper) {
+ this.objectMapper = objectMapper;
+ this.jsonTokenizer = new JsonAsyncTokenizer(objectMapper.getFactory());
+ }
+
+ public <T> void initialize(final TypeReference<T> typeReference, final JsonResultSink<T> resultSink) throws IOException {
+ this.jsonTokenizer.initialize(new TopLevelArrayTokenFilter(new TokenBufferAssembler(new JsonResultSink<TokenBuffer>() {
+
+ @Override
+ public void begin(final int sizeHint) {
+ resultSink.begin(sizeHint);
+ }
+
+ @Override
+ public void accept(final TokenBuffer tokenBuffer) {
+ try {
+ final JsonParser jsonParser = tokenBuffer != null ? tokenBuffer.asParserOnFirstToken() : null;
+ final T result = jsonParser != null ? objectMapper.readValue(jsonParser, typeReference) : null;
+ if (result != null) {
+ resultSink.accept(result);
+ }
+ } catch (final IOException ex) {
+ throw new UncheckedIOException(ex);
+ }
+ }
+
+ @Override
+ public void end() {
+ resultSink.end();
+ }
+
+ })));
+ }
+
+ public void consume(final ByteBuffer data) throws IOException {
+ try {
+ jsonTokenizer.consume(data);
+ } catch (final UncheckedIOException ex) {
+ throw ex.getCause();
+ }
+ }
+
+ public void streamEnd() throws IOException {
+ jsonTokenizer.streamEnd();
+ }
+
+}
diff --git a/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/AbstractJsonEntityConsumer.java b/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/AbstractJsonEntityConsumer.java
new file mode 100644
index 000000000..48d54c79f
--- /dev/null
+++ b/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/AbstractJsonEntityConsumer.java
@@ -0,0 +1,111 @@
+/*
+ * ====================================================================
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * <http://www.apache.org/>.
+ *
+ */
+package org.apache.hc.core5.jackson2.http;
+
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.util.List;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.Consumer;
+
+import com.fasterxml.jackson.core.JsonFactory;
+
+import org.apache.hc.core5.concurrent.FutureCallback;
+import org.apache.hc.core5.http.ContentType;
+import org.apache.hc.core5.http.EntityDetails;
+import org.apache.hc.core5.http.Header;
+import org.apache.hc.core5.http.HttpException;
+import org.apache.hc.core5.http.nio.AsyncEntityConsumer;
+import org.apache.hc.core5.http.nio.CapacityChannel;
+import org.apache.hc.core5.jackson2.JsonAsyncTokenizer;
+import org.apache.hc.core5.jackson2.JsonContentException;
+import org.apache.hc.core5.jackson2.JsonTokenConsumer;
+import org.apache.hc.core5.util.Args;
+
+abstract class AbstractJsonEntityConsumer<T> implements AsyncEntityConsumer<T> {
+
+ private final JsonAsyncTokenizer jsonTokenizer;
+ private final AtomicReference<FutureCallback<T>> resultCallbackRef;
+ private final AtomicReference<T> resultRef;
+
+ AbstractJsonEntityConsumer(final JsonFactory jsonFactory) {
+ this.jsonTokenizer = new JsonAsyncTokenizer(Args.notNull(jsonFactory, "Json factory"));
+ this.resultCallbackRef = new AtomicReference<>(null);
+ this.resultRef = new AtomicReference<>(null);
+ }
+
+ abstract JsonTokenConsumer createJsonTokenConsumer(Consumer<T> resultConsumer);
+
+ @Override
+ public final void streamStart(final EntityDetails entityDetails, final FutureCallback<T> resultCallback) throws HttpException, IOException {
+ final ContentType contentType = ContentType.parseLenient(entityDetails.getContentType());
+ if (contentType != null && !ContentType.APPLICATION_JSON.isSameMimeType(contentType)) {
+ throw new JsonContentException("Unexpected content type: " + contentType.getMimeType());
+ }
+ resultCallbackRef.set(resultCallback);
+ jsonTokenizer.initialize(createJsonTokenConsumer(result -> {
+ resultRef.set(result);
+ final FutureCallback<T> resultCallback1 = resultCallbackRef.getAndSet(null);
+ if (resultCallback1 != null) {
+ resultCallback1.completed(result);
+ }
+ }));
+ }
+
+ @Override
+ public final void updateCapacity(final CapacityChannel capacityChannel) throws IOException {
+ capacityChannel.update(Integer.MAX_VALUE);
+ }
+
+ @Override
+ public final void consume(final ByteBuffer data) throws IOException {
+ jsonTokenizer.consume(data);
+ }
+
+ @Override
+ public final void streamEnd(final List<? extends Header> trailers) throws HttpException, IOException {
+ jsonTokenizer.streamEnd();
+ }
+
+ @Override
+ public final void failed(final Exception cause) {
+ final FutureCallback<T> resultCallback = resultCallbackRef.getAndSet(null);
+ if (resultCallback != null) {
+ resultCallback.failed(cause);
+ }
+ }
+
+ @Override
+ public final T getContent() {
+ return resultRef.get();
+ }
+
+ @Override
+ public void releaseResources() {
+ }
+
+}
diff --git a/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/AbstractJsonEntityProducer.java b/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/AbstractJsonEntityProducer.java
new file mode 100644
index 000000000..d1b02ded8
--- /dev/null
+++ b/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/AbstractJsonEntityProducer.java
@@ -0,0 +1,123 @@
+/*
+ * ====================================================================
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * <http://www.apache.org/>.
+ *
+ */
+package org.apache.hc.core5.jackson2.http;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.util.Set;
+
+import org.apache.hc.core5.http.ContentType;
+import org.apache.hc.core5.http.nio.AsyncEntityProducer;
+import org.apache.hc.core5.http.nio.DataStreamChannel;
+
+abstract class AbstractJsonEntityProducer implements AsyncEntityProducer {
+
+ private final InternalBuffer buffer;
+ private volatile State state;
+
+ AbstractJsonEntityProducer(final int initSize) {
+ this.buffer = new InternalBuffer(initSize);
+ this.state = State.ACTIVE;
+ }
+
+ abstract void generateJson(OutputStream outputStream) throws IOException;
+
+ @Override
+ public final long getContentLength() {
+ return -1;
+ }
+
+ @Override
+ public final Set<String> getTrailerNames() {
+ return null;
+ }
+
+ @Override
+ public final String getContentType() {
+ return ContentType.APPLICATION_JSON.toString();
+ }
+
+ @Override
+ public final String getContentEncoding() {
+ return null;
+ }
+
+ @Override
+ public final boolean isRepeatable() {
+ return true;
+ }
+
+ @Override
+ public boolean isChunked() {
+ return false;
+ }
+
+ @Override
+ public final int available() {
+ return buffer.length();
+ }
+
+ @Override
+ public final void produce(final DataStreamChannel channel) throws IOException {
+ if (state == State.ACTIVE) {
+ generateJson(new OutputStream() {
+
+ @Override
+ public void write(final byte[] b, final int off, final int len) throws IOException {
+ buffer.write(b, off, len);
+ }
+
+ @Override
+ public void write(final int b) throws IOException {
+ buffer.write(b);
+ }
+
+ @Override
+ public void close() throws IOException {
+ state = State.FLUSHING;
+ }
+
+ });
+ }
+ if (state.compareTo(State.END_STREAM) < 0 && buffer.hasData()) {
+ channel.write(buffer.getByteBuffer());
+ }
+ if (state == State.FLUSHING && !buffer.hasData()) {
+ channel.endStream(null);
+ state = State.END_STREAM;
+ }
+ }
+
+ @Override
+ public void releaseResources() {
+ buffer.clear();
+ state = State.ACTIVE;
+ }
+
+ private enum State { ACTIVE, FLUSHING, END_STREAM }
+
+}
diff --git a/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/AbstractJsonMessageConsumer.java b/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/AbstractJsonMessageConsumer.java
new file mode 100644
index 000000000..86e9b98ea
--- /dev/null
+++ b/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/AbstractJsonMessageConsumer.java
@@ -0,0 +1,138 @@
+/*
+ * ====================================================================
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * <http://www.apache.org/>.
+ *
+ */
+package org.apache.hc.core5.jackson2.http;
+
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.util.List;
+import java.util.concurrent.atomic.AtomicReference;
+
+import org.apache.hc.core5.concurrent.CallbackContribution;
+import org.apache.hc.core5.concurrent.FutureCallback;
+import org.apache.hc.core5.function.Supplier;
+import org.apache.hc.core5.http.ContentType;
+import org.apache.hc.core5.http.EntityDetails;
+import org.apache.hc.core5.http.Header;
+import org.apache.hc.core5.http.HttpException;
+import org.apache.hc.core5.http.HttpMessage;
+import org.apache.hc.core5.http.nio.AsyncDataConsumer;
+import org.apache.hc.core5.http.nio.AsyncEntityConsumer;
+import org.apache.hc.core5.http.nio.CapacityChannel;
+import org.apache.hc.core5.http.protocol.HttpContext;
+import org.apache.hc.core5.jackson2.JsonContentException;
+import org.apache.hc.core5.util.Args;
+
+abstract class AbstractJsonMessageConsumer<H extends HttpMessage, T> implements AsyncDataConsumer {
+
+ private final Supplier<AsyncEntityConsumer<T>> jsonConsumerSupplier;
+ private final AtomicReference<AsyncEntityConsumer<?>> entityConsumerRef;
+
+ public AbstractJsonMessageConsumer(final Supplier<AsyncEntityConsumer<T>> jsonConsumerSupplier) {
+ this.jsonConsumerSupplier = Args.notNull(jsonConsumerSupplier, "Json consumer supplier");
+ this.entityConsumerRef = new AtomicReference<>();
+ }
+
+ protected <E> void handleContent(final AsyncEntityConsumer<E> entityConsumer,
+ final EntityDetails entityDetails,
+ final FutureCallback<E> resultCallback) throws HttpException, IOException {
+ entityConsumerRef.set(entityConsumer);
+ entityConsumer.streamStart(entityDetails, resultCallback);
+ }
+
+ protected void consumeMessage(final H messageHead,
+ final EntityDetails entityDetails,
+ final HttpContext context,
+ final FutureCallback<T> resultCallback) throws HttpException, IOException {
+ final ContentType contentType = ContentType.parseLenient(entityDetails.getContentType());
+ if (contentType == null || ContentType.APPLICATION_JSON.isSameMimeType(contentType)) {
+ final AsyncEntityConsumer<T> entityConsumer = jsonConsumerSupplier.get();
+ entityConsumerRef.set(entityConsumer);
+ entityConsumer.streamStart(entityDetails, new CallbackContribution<T>(resultCallback) {
+
+ @Override
+ public void completed(final T result) {
+ resultCallback.completed(result);
+ }
+
+ });
+ } else {
+ final AsyncEntityConsumer<T> entityConsumer = new NoopJsonEntityConsumer<>();
+ entityConsumerRef.set(entityConsumer);
+ entityConsumer.streamStart(entityDetails, new CallbackContribution<T>(resultCallback) {
+
+ @Override
+ public void completed(final T ignore) {
+ resultCallback.failed(new JsonContentException("Unexpected content type: " + contentType.getMimeType()));
+ }
+
+ });
+ }
+ }
+
+ @Override
+ public void updateCapacity(final CapacityChannel capacityChannel) throws IOException {
+ final AsyncEntityConsumer<?> entityConsumer = entityConsumerRef.get();
+ if (entityConsumer != null) {
+ entityConsumer.updateCapacity(capacityChannel);
+ } else {
+ capacityChannel.update(Integer.MAX_VALUE);
+ }
+ }
+
+ @Override
+ public void consume(final ByteBuffer data) throws IOException {
+ final AsyncEntityConsumer<?> entityConsumer = entityConsumerRef.get();
+ if (entityConsumer != null) {
+ entityConsumer.consume(data);
+ }
+ }
+
+ @Override
+ public void streamEnd(final List<? extends Header> trailers) throws HttpException, IOException {
+ final AsyncEntityConsumer<?> entityConsumer = entityConsumerRef.get();
+ if (entityConsumer != null) {
+ entityConsumer.streamEnd(trailers);
+ }
+ }
+
+ public void failed(final Exception cause) {
+ final AsyncEntityConsumer<?> entityConsumer = entityConsumerRef.get();
+ if (entityConsumer != null) {
+ entityConsumer.failed(cause);
+ }
+ releaseResources();
+ }
+
+ @Override
+ public void releaseResources() {
+ final AsyncEntityConsumer<?> entityConsumer = entityConsumerRef.getAndSet(null);
+ if (entityConsumer != null) {
+ entityConsumer.releaseResources();
+ }
+ }
+
+}
diff --git a/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/AbstractJsonSequenceEntityConsumer.java b/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/AbstractJsonSequenceEntityConsumer.java
new file mode 100644
index 000000000..f82b9f2df
--- /dev/null
+++ b/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/AbstractJsonSequenceEntityConsumer.java
@@ -0,0 +1,93 @@
+/*
+ * ====================================================================
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * <http://www.apache.org/>.
+ *
+ */
+package org.apache.hc.core5.jackson2.http;
+
+import java.io.IOException;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.function.Consumer;
+
+import com.fasterxml.jackson.core.JsonFactory;
+import com.fasterxml.jackson.core.JsonParser;
+import com.fasterxml.jackson.databind.util.TokenBuffer;
+
+import org.apache.hc.core5.jackson2.JsonResultSink;
+import org.apache.hc.core5.jackson2.JsonTokenConsumer;
+import org.apache.hc.core5.jackson2.TokenBufferAssembler;
+import org.apache.hc.core5.util.Args;
+
+class AbstractJsonSequenceEntityConsumer<T> extends AbstractJsonEntityConsumer<Long> {
+
+ private final ReadJsonValue<T> readJsonValue;
+ private final JsonResultSink<T> resultSink;
+ private final AtomicLong count;
+
+ AbstractJsonSequenceEntityConsumer(final JsonFactory jsonFactory, final ReadJsonValue<T> readJsonValue, final JsonResultSink<T> resultSink) {
+ super(jsonFactory);
+ this.readJsonValue = Args.notNull(readJsonValue, "Json value reader");
+ this.resultSink = Args.notNull(resultSink, "Result sink");
+ this.count = new AtomicLong(0);
+ }
+
+ @Override
+ protected JsonTokenConsumer createJsonTokenConsumer(final Consumer<Long> resultConsumer) {
+ return new TokenBufferAssembler(new JsonResultSink<TokenBuffer>() {
+
+
+ @Override
+ public void begin(final int sizeHint) {
+ resultSink.begin(sizeHint);
+ }
+
+ @Override
+ public void accept(final TokenBuffer tokenBuffer) {
+ try {
+ final JsonParser jsonParser = tokenBuffer != null ? tokenBuffer.asParserOnFirstToken() : null;
+ final T result = jsonParser != null ? readJsonValue.readValue(jsonParser) : null;
+ if (result != null) {
+ count.incrementAndGet();
+ resultSink.accept(result);
+ }
+ } catch (final IOException ex) {
+ failed(ex);
+ }
+ }
+
+ @Override
+ public void end() {
+ resultSink.end();
+ resultConsumer.accept(count.get());
+ }
+
+ });
+ }
+
+ @FunctionalInterface
+ interface ReadJsonValue<T> {
+ T readValue(JsonParser jsonParser) throws IOException;
+ }
+
+}
diff --git a/httpcore5/src/main/java/org/apache/hc/core5/http/Message.java b/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/InternalBuffer.java
similarity index 52%
copy from httpcore5/src/main/java/org/apache/hc/core5/http/Message.java
copy to httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/InternalBuffer.java
index b60d9724b..37f744052 100644
--- a/httpcore5/src/main/java/org/apache/hc/core5/http/Message.java
+++ b/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/InternalBuffer.java
@@ -24,66 +24,54 @@
* <http://www.apache.org/>.
*
*/
+package org.apache.hc.core5.jackson2.http;
-package org.apache.hc.core5.http;
+import java.io.IOException;
+import java.nio.ByteBuffer;
-import org.apache.hc.core5.util.Args;
+import org.apache.hc.core5.http.impl.nio.ExpandableBuffer;
-/**
- * Generic message consisting of a message head and a message body.
- *
- * @param <H> message head type.
- * @param <B> message body type.
- *
- * @since 5.0
- */
-public final class Message<H extends MessageHeaders, B> {
+class InternalBuffer extends ExpandableBuffer {
- private final H head;
- private final B body;
+ public InternalBuffer(final int bufferSize) {
+ super(bufferSize);
+ }
- /**
- * Constructs a new instance.
- *
- * @param head The message head.
- * @since 5.3
- */
- public Message(final H head) {
- this(head, null);
+ void write(final byte[] b, final int off, final int len) throws IOException {
+ if (b == null) {
+ return;
+ }
+ setInputMode();
+ final int requiredCapacity = buffer().position() + len;
+ ensureCapacity(requiredCapacity);
+ buffer().put(b, off, len);
}
- /**
- * Constructs a new instance.
- *
- * @param head The message head.
- * @param body The message body.
- */
- public Message(final H head, final B body) {
- this.head = Args.notNull(head, "Message head");
- this.body = body;
+ void write(final int b) throws IOException {
+ setInputMode();
+ final int requiredCapacity = buffer().position() + 1;
+ ensureCapacity(requiredCapacity);
+ buffer().put((byte) b);
}
- /**
- * Gets the message head.
- *
- * @return the message head.
- */
- public H getHead() {
- return head;
+ @Override
+ protected int length() {
+ return super.length();
}
- /**
- * Gets the message body.
- *
- * @return the message body.
- */
- public B getBody() {
- return body;
+ @Override
+ protected boolean hasData() {
+ return super.hasData();
}
@Override
- public String toString() {
- return "[head=" + head + ", body=" + body + ']';
+ public void clear() {
+ super.clear();
+ }
+
+ ByteBuffer getByteBuffer() {
+ setOutputMode();
+ return buffer();
}
}
diff --git a/httpcore5/src/main/java/org/apache/hc/core5/http/Message.java b/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/JsonMessageProducer.java
similarity index 52%
copy from httpcore5/src/main/java/org/apache/hc/core5/http/Message.java
copy to httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/JsonMessageProducer.java
index b60d9724b..087b84fb3 100644
--- a/httpcore5/src/main/java/org/apache/hc/core5/http/Message.java
+++ b/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/JsonMessageProducer.java
@@ -24,66 +24,48 @@
* <http://www.apache.org/>.
*
*/
+package org.apache.hc.core5.jackson2.http;
-package org.apache.hc.core5.http;
+import java.io.IOException;
-import org.apache.hc.core5.util.Args;
+import org.apache.hc.core5.http.EntityDetails;
+import org.apache.hc.core5.http.nio.AsyncDataProducer;
+import org.apache.hc.core5.http.nio.AsyncEntityProducer;
+import org.apache.hc.core5.http.nio.DataStreamChannel;
-/**
- * Generic message consisting of a message head and a message body.
- *
- * @param <H> message head type.
- * @param <B> message body type.
- *
- * @since 5.0
- */
-public final class Message<H extends MessageHeaders, B> {
+class JsonMessageProducer implements AsyncDataProducer {
- private final H head;
- private final B body;
+ private final AsyncEntityProducer entityProducer;
- /**
- * Constructs a new instance.
- *
- * @param head The message head.
- * @since 5.3
- */
- public Message(final H head) {
- this(head, null);
+ JsonMessageProducer(final AsyncEntityProducer entityProducer) {
+ this.entityProducer = entityProducer;
}
- /**
- * Constructs a new instance.
- *
- * @param head The message head.
- * @param body The message body.
- */
- public Message(final H head, final B body) {
- this.head = Args.notNull(head, "Message head");
- this.body = body;
+ EntityDetails getEntityDetails() {
+ return entityProducer;
}
- /**
- * Gets the message head.
- *
- * @return the message head.
- */
- public H getHead() {
- return head;
+ boolean isRepeatable() {
+ return entityProducer == null || entityProducer.isRepeatable();
}
- /**
- * Gets the message body.
- *
- * @return the message body.
- */
- public B getBody() {
- return body;
+ @Override
+ public final int available() {
+ return entityProducer != null ? entityProducer.available() : 0;
+ }
+
+ @Override
+ public final void produce(final DataStreamChannel channel) throws IOException {
+ if (entityProducer != null) {
+ entityProducer.produce(channel);
+ }
}
@Override
- public String toString() {
- return "[head=" + head + ", body=" + body + ']';
+ public final void releaseResources() {
+ if (entityProducer != null) {
+ entityProducer.releaseResources();
+ }
}
}
diff --git a/httpcore5/src/main/java/org/apache/hc/core5/http/Message.java b/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/JsonNodeEntityConsumer.java
similarity index 51%
copy from httpcore5/src/main/java/org/apache/hc/core5/http/Message.java
copy to httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/JsonNodeEntityConsumer.java
index b60d9724b..e95dc2d93 100644
--- a/httpcore5/src/main/java/org/apache/hc/core5/http/Message.java
+++ b/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/JsonNodeEntityConsumer.java
@@ -24,66 +24,31 @@
* <http://www.apache.org/>.
*
*/
+package org.apache.hc.core5.jackson2.http;
-package org.apache.hc.core5.http;
+import java.util.function.Consumer;
-import org.apache.hc.core5.util.Args;
+import com.fasterxml.jackson.core.JsonFactory;
+import com.fasterxml.jackson.databind.JsonNode;
+
+import org.apache.hc.core5.jackson2.JsonNodeAssembler;
+import org.apache.hc.core5.jackson2.JsonTokenConsumer;
/**
- * Generic message consisting of a message head and a message body.
- *
- * @param <H> message head type.
- * @param <B> message body type.
+ * {@link org.apache.hc.core5.http.nio.AsyncEntityConsumer} implementation that
+ * de-serializes incoming HTTP message entity into an {@link JsonNode} instance.
*
- * @since 5.0
+ * @since 5.5
*/
-public final class Message<H extends MessageHeaders, B> {
-
- private final H head;
- private final B body;
-
- /**
- * Constructs a new instance.
- *
- * @param head The message head.
- * @since 5.3
- */
- public Message(final H head) {
- this(head, null);
- }
-
- /**
- * Constructs a new instance.
- *
- * @param head The message head.
- * @param body The message body.
- */
- public Message(final H head, final B body) {
- this.head = Args.notNull(head, "Message head");
- this.body = body;
- }
-
- /**
- * Gets the message head.
- *
- * @return the message head.
- */
- public H getHead() {
- return head;
- }
+public class JsonNodeEntityConsumer extends AbstractJsonEntityConsumer<JsonNode> {
- /**
- * Gets the message body.
- *
- * @return the message body.
- */
- public B getBody() {
- return body;
+ public JsonNodeEntityConsumer(final JsonFactory jsonFactory) {
+ super(jsonFactory);
}
@Override
- public String toString() {
- return "[head=" + head + ", body=" + body + ']';
+ protected JsonTokenConsumer createJsonTokenConsumer(final Consumer<JsonNode> resultConsumer) {
+ return JsonNodeAssembler.createTokenConsumer(resultConsumer);
}
}
diff --git a/httpcore5/src/main/java/org/apache/hc/core5/http/Message.java b/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/JsonNodeEntityProducer.java
similarity index 53%
copy from httpcore5/src/main/java/org/apache/hc/core5/http/Message.java
copy to httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/JsonNodeEntityProducer.java
index b60d9724b..203b79968 100644
--- a/httpcore5/src/main/java/org/apache/hc/core5/http/Message.java
+++ b/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/JsonNodeEntityProducer.java
@@ -24,66 +24,42 @@
* <http://www.apache.org/>.
*
*/
+package org.apache.hc.core5.jackson2.http;
-package org.apache.hc.core5.http;
+import java.io.IOException;
+import java.io.OutputStream;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.hc.core5.util.Args;
/**
- * Generic message consisting of a message head and a message body.
- *
- * @param <H> message head type.
- * @param <B> message body type.
+ * {@link org.apache.hc.core5.http.nio.AsyncEntityProducer} implementation that
+ * generates a message body containing serialized content of the given {@link JsonNode}
+ * object.
*
- * @since 5.0
+ * @since 5.5
*/
-public final class Message<H extends MessageHeaders, B> {
+public class JsonNodeEntityProducer extends AbstractJsonEntityProducer {
- private final H head;
- private final B body;
-
- /**
- * Constructs a new instance.
- *
- * @param head The message head.
- * @since 5.3
- */
- public Message(final H head) {
- this(head, null);
- }
+ private final JsonNode jsonNode;
+ private final ObjectMapper objectMapper;
- /**
- * Constructs a new instance.
- *
- * @param head The message head.
- * @param body The message body.
- */
- public Message(final H head, final B body) {
- this.head = Args.notNull(head, "Message head");
- this.body = body;
+ public JsonNodeEntityProducer(final JsonNode jsonNode, final ObjectMapper objectMapper) {
+ super(4096);
+ this.jsonNode = Args.notNull(jsonNode, "Json node");
+ this.objectMapper = Args.notNull(objectMapper, "Object mapper");
}
- /**
- * Gets the message head.
- *
- * @return the message head.
- */
- public H getHead() {
- return head;
- }
-
- /**
- * Gets the message body.
- *
- * @return the message body.
- */
- public B getBody() {
- return body;
+ @Override
+ final void generateJson(final OutputStream outputStream) throws IOException {
+ objectMapper.writeValue(outputStream, jsonNode);
+ outputStream.close();
}
@Override
- public String toString() {
- return "[head=" + head + ", body=" + body + ']';
+ public void failed(final Exception cause) {
}
}
diff --git a/httpcore5/src/main/java/org/apache/hc/core5/http/Message.java b/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/JsonNodeSequenceEntityConsumer.java
similarity index 52%
copy from httpcore5/src/main/java/org/apache/hc/core5/http/Message.java
copy to httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/JsonNodeSequenceEntityConsumer.java
index b60d9724b..3c31f4cae 100644
--- a/httpcore5/src/main/java/org/apache/hc/core5/http/Message.java
+++ b/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/JsonNodeSequenceEntityConsumer.java
@@ -24,66 +24,25 @@
* <http://www.apache.org/>.
*
*/
+package org.apache.hc.core5.jackson2.http;
-package org.apache.hc.core5.http;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.hc.core5.jackson2.JsonResultSink;
import org.apache.hc.core5.util.Args;
/**
- * Generic message consisting of a message head and a message body.
+ * {@link org.apache.hc.core5.http.nio.AsyncEntityConsumer} implementation that
+ * converts incoming HTTP message entity into a sequence of {@link JsonNode} instance
+ * and passes those objects to the {@link JsonResultSink}.
*
- * @param <H> message head type.
- * @param <B> message body type.
- *
- * @since 5.0
+ * @since 5.5
*/
-public final class Message<H extends MessageHeaders, B> {
-
- private final H head;
- private final B body;
-
- /**
- * Constructs a new instance.
- *
- * @param head The message head.
- * @since 5.3
- */
- public Message(final H head) {
- this(head, null);
- }
-
- /**
- * Constructs a new instance.
- *
- * @param head The message head.
- * @param body The message body.
- */
- public Message(final H head, final B body) {
- this.head = Args.notNull(head, "Message head");
- this.body = body;
- }
-
- /**
- * Gets the message head.
- *
- * @return the message head.
- */
- public H getHead() {
- return head;
- }
-
- /**
- * Gets the message body.
- *
- * @return the message body.
- */
- public B getBody() {
- return body;
- }
+public class JsonNodeSequenceEntityConsumer extends AbstractJsonSequenceEntityConsumer<JsonNode> {
- @Override
- public String toString() {
- return "[head=" + head + ", body=" + body + ']';
+ public JsonNodeSequenceEntityConsumer(final ObjectMapper objectMapper, final JsonResultSink<JsonNode> resultSink) {
+ super(Args.notNull(objectMapper, "Object mapper").getFactory(), objectMapper::readTree, resultSink);
}
}
diff --git a/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/JsonObjectEntityConsumer.java b/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/JsonObjectEntityConsumer.java
new file mode 100644
index 000000000..d78e223eb
--- /dev/null
+++ b/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/JsonObjectEntityConsumer.java
@@ -0,0 +1,82 @@
+/*
+ * ====================================================================
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * <http://www.apache.org/>.
+ *
+ */
+package org.apache.hc.core5.jackson2.http;
+
+import java.io.IOException;
+import java.util.function.Consumer;
+
+import com.fasterxml.jackson.core.JsonParser;
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.JavaType;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+import org.apache.hc.core5.jackson2.JsonTokenConsumer;
+import org.apache.hc.core5.jackson2.TokenBufferAssembler;
+import org.apache.hc.core5.util.Args;
+
+/**
+ * {@link org.apache.hc.core5.http.nio.AsyncEntityConsumer} implementation that
+ * de-serializes incoming HTTP message entity into an instance of the given class.
+ *
+ * @param <T> type of objects produced by this class.
+ * @since 5.5
+ */
+public class JsonObjectEntityConsumer<T> extends AbstractJsonEntityConsumer<T> {
+
+ private final ReadJsonValue<T> readJsonValue;
+
+ public JsonObjectEntityConsumer(final ObjectMapper objectMapper, final JavaType javaType) {
+ super(Args.notNull(objectMapper, "Object mapper").getFactory());
+ this.readJsonValue = jsonParser -> objectMapper.readValue(jsonParser, javaType);
+ }
+
+ public JsonObjectEntityConsumer(final ObjectMapper objectMapper, final Class<T> objectClazz) {
+ this(Args.notNull(objectMapper, "Object mapper"), objectMapper.getTypeFactory().constructType(objectClazz));
+ }
+
+ public JsonObjectEntityConsumer(final ObjectMapper objectMapper, final TypeReference<T> typeReference) {
+ this(Args.notNull(objectMapper, "Object mapper"), objectMapper.getTypeFactory().constructType(typeReference));
+ }
+
+ @Override
+ protected JsonTokenConsumer createJsonTokenConsumer(final Consumer<T> resultConsumer) {
+ return new TokenBufferAssembler(tokenBuffer -> {
+ try {
+ final JsonParser jsonParser = tokenBuffer != null ? tokenBuffer.asParserOnFirstToken() : null;
+ final T result = jsonParser != null ? readJsonValue.readValue(jsonParser) : null;
+ resultConsumer.accept(result);
+ } catch (final IOException ex) {
+ failed(ex);
+ }
+ });
+ }
+
+ @FunctionalInterface
+ private interface ReadJsonValue<T> {
+ T readValue(JsonParser jsonParser) throws IOException;
+ }
+}
diff --git a/httpcore5/src/main/java/org/apache/hc/core5/http/Message.java b/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/JsonObjectEntityProducer.java
similarity index 53%
copy from httpcore5/src/main/java/org/apache/hc/core5/http/Message.java
copy to httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/JsonObjectEntityProducer.java
index b60d9724b..3a6bd71f4 100644
--- a/httpcore5/src/main/java/org/apache/hc/core5/http/Message.java
+++ b/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/JsonObjectEntityProducer.java
@@ -24,66 +24,41 @@
* <http://www.apache.org/>.
*
*/
+package org.apache.hc.core5.jackson2.http;
-package org.apache.hc.core5.http;
+import java.io.IOException;
+import java.io.OutputStream;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.hc.core5.util.Args;
/**
- * Generic message consisting of a message head and a message body.
- *
- * @param <H> message head type.
- * @param <B> message body type.
+ * {@link org.apache.hc.core5.http.nio.AsyncEntityProducer} implementation that
+ * generates a message body containing serialized content of the given JSON object.
*
- * @since 5.0
+ * @param <T> type of objects used by this class.
+ * @since 5.5
*/
-public final class Message<H extends MessageHeaders, B> {
+public class JsonObjectEntityProducer<T> extends AbstractJsonEntityProducer {
- private final H head;
- private final B body;
-
- /**
- * Constructs a new instance.
- *
- * @param head The message head.
- * @since 5.3
- */
- public Message(final H head) {
- this(head, null);
- }
+ private final T jsonObject;
+ private final ObjectMapper objectMapper;
- /**
- * Constructs a new instance.
- *
- * @param head The message head.
- * @param body The message body.
- */
- public Message(final H head, final B body) {
- this.head = Args.notNull(head, "Message head");
- this.body = body;
+ public JsonObjectEntityProducer(final T jsonObject, final ObjectMapper objectMapper) {
+ super(4096);
+ this.jsonObject = Args.notNull(jsonObject, "Json object");
+ this.objectMapper = Args.notNull(objectMapper, "Object mapper");
}
- /**
- * Gets the message head.
- *
- * @return the message head.
- */
- public H getHead() {
- return head;
- }
-
- /**
- * Gets the message body.
- *
- * @return the message body.
- */
- public B getBody() {
- return body;
+ @Override
+ final void generateJson(final OutputStream outputStream) throws IOException {
+ objectMapper.writeValue(outputStream, jsonObject);
+ outputStream.close();
}
@Override
- public String toString() {
- return "[head=" + head + ", body=" + body + ']';
+ public void failed(final Exception cause) {
}
}
diff --git a/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/JsonRequestConsumer.java b/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/JsonRequestConsumer.java
new file mode 100644
index 000000000..41332b08f
--- /dev/null
+++ b/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/JsonRequestConsumer.java
@@ -0,0 +1,69 @@
+/*
+ * ====================================================================
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * <http://www.apache.org/>.
+ *
+ */
+package org.apache.hc.core5.jackson2.http;
+
+import java.io.IOException;
+
+import org.apache.hc.core5.concurrent.CallbackContribution;
+import org.apache.hc.core5.concurrent.FutureCallback;
+import org.apache.hc.core5.function.Supplier;
+import org.apache.hc.core5.http.EntityDetails;
+import org.apache.hc.core5.http.HttpException;
+import org.apache.hc.core5.http.HttpRequest;
+import org.apache.hc.core5.http.Message;
+import org.apache.hc.core5.http.nio.AsyncEntityConsumer;
+import org.apache.hc.core5.http.nio.AsyncRequestConsumer;
+import org.apache.hc.core5.http.protocol.HttpContext;
+
+final class JsonRequestConsumer<T> extends AbstractJsonMessageConsumer<HttpRequest, T>
+ implements AsyncRequestConsumer<Message<HttpRequest, T>> {
+
+ public JsonRequestConsumer(final Supplier<AsyncEntityConsumer<T>> jsonConsumerSupplier) {
+ super(jsonConsumerSupplier);
+ }
+
+ @Override
+ public void consumeRequest(final HttpRequest request,
+ final EntityDetails entityDetails,
+ final HttpContext context,
+ final FutureCallback<Message<HttpRequest, T>> resultCallback) throws HttpException, IOException {
+ consumeMessage(request, entityDetails, context, new CallbackContribution<T>(resultCallback) {
+
+ @Override
+ public void completed(final T result) {
+ resultCallback.completed(new Message<>(request, result));
+ }
+
+ });
+ }
+
+ @Override
+ public void failed(final Exception cause) {
+ super.failed(cause);
+ }
+
+}
diff --git a/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/JsonRequestConsumers.java b/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/JsonRequestConsumers.java
new file mode 100644
index 000000000..f7049f879
--- /dev/null
+++ b/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/JsonRequestConsumers.java
@@ -0,0 +1,208 @@
+/*
+ * ====================================================================
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * <http://www.apache.org/>.
+ *
+ */
+package org.apache.hc.core5.jackson2.http;
+
+import com.fasterxml.jackson.core.JsonFactory;
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.JavaType;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+import org.apache.hc.core5.http.HttpRequest;
+import org.apache.hc.core5.http.Message;
+import org.apache.hc.core5.http.nio.AsyncRequestConsumer;
+import org.apache.hc.core5.jackson2.JsonConsumer;
+import org.apache.hc.core5.jackson2.JsonResultSink;
+import org.apache.hc.core5.jackson2.JsonTokenEventHandler;
+
+/**
+ * Factory class for JSON {@link AsyncRequestConsumer}s.
+ *
+ * @since 5.5
+ */
+public final class JsonRequestConsumers {
+
+ /**
+ * Creates {@link AsyncRequestConsumer} that produces a {@link Message} object
+ * consisting of the {@link HttpRequest} head and the de-serialized JSON body.
+ *
+ * @param objectMapper the object mapper to be used to de-serialize JSON content.
+ * @param javaType the java type of the de-serialized object.
+ * @param <T> the type of result objects produced by the consumer.
+ * @return the request consumer.
+ */
+ public static <T> AsyncRequestConsumer<Message<HttpRequest, T>> create(
+ final ObjectMapper objectMapper,
+ final JavaType javaType) {
+ return new JsonRequestConsumer<>(() -> new JsonObjectEntityConsumer<>(objectMapper, javaType));
+ }
+
+ /**
+ * Creates {@link AsyncRequestConsumer} that produces a {@link Message} object
+ * consisting of the {@link HttpRequest} head and the de-serialized JSON body.
+ *
+ * @param objectMapper the object mapper to be used to de-serialize JSON content.
+ * @param objectClazz the class of the de-serialized object.
+ * @param <T> the type of result objects produced by the consumer.
+ * @return the request consumer.
+ */
+ public static <T> AsyncRequestConsumer<Message<HttpRequest, T>> create(
+ final ObjectMapper objectMapper,
+ final Class<T> objectClazz) {
+ return new JsonRequestConsumer<>(() -> new JsonObjectEntityConsumer<>(objectMapper, objectClazz));
+ }
+
+ /**
+ * Creates {@link AsyncRequestConsumer} that produces a {@link Message} object
+ * consisting of the {@link HttpRequest} head and the de-serialized JSON body.
+ *
+ * @param objectMapper the object mapper to be used to de-serialize JSON content.
+ * @param typeReference the type reference of the de-serialized object.
+ * @param <T> the type of result objects produced by the consumer.
+ * @return the request consumer.
+ */
+ public static <T> AsyncRequestConsumer<Message<HttpRequest, T>> create(
+ final ObjectMapper objectMapper,
+ final TypeReference<T> typeReference) {
+ return new JsonRequestConsumer<>(() -> new JsonObjectEntityConsumer<>(objectMapper, typeReference));
+ }
+
+ /**
+ * Creates {@link AsyncRequestConsumer} that produces a {@link Message} object
+ * consisting of the {@link HttpRequest} head and the {@link JsonNode} body.
+ *
+ * @param jsonFactory JSON factory.
+ * @return the request consumer.
+ */
+ public static AsyncRequestConsumer<Message<HttpRequest, JsonNode>> create(final JsonFactory jsonFactory) {
+ return new JsonRequestConsumer<>(() -> new JsonNodeEntityConsumer(jsonFactory));
+ }
+
+ /**
+ * Creates {@link AsyncRequestConsumer} that converts incoming HTTP request
+ * into a sequence of instances of the given class and passes those objects
+ * to the given {@link JsonResultSink}.
+ *
+ * @param objectMapper the object mapper to be used to de-serialize JSON content.
+ * @param javaType the java type of the de-serialized object.
+ * @param requestValidator optional operation that accepts the message head as input.
+ * @param resultSink the recipient of result objects.
+ * @param <T> type of result objects produced by the consumer.
+ * @return the request consumer.
+ */
+ public static <T> AsyncRequestConsumer<Long> create(
+ final ObjectMapper objectMapper,
+ final JavaType javaType,
+ final JsonConsumer<HttpRequest> requestValidator,
+ final JsonResultSink<T> resultSink) {
+ return new JsonSequenceRequestConsumer<>(
+ () -> new JsonSequenceEntityConsumer<>(objectMapper, javaType, resultSink),
+ requestValidator);
+ }
+
+ /**
+ * Creates {@link AsyncRequestConsumer} that converts incoming HTTP request
+ * into a sequence of instances of the given class and passes those objects
+ * to the given {@link JsonResultSink}.
+ *
+ * @param objectMapper the object mapper to be used to de-serialize JSON content.
+ * @param objectClazz the class of the de-serialized object.
+ * @param requestValidator optional operation that accepts the message head as input.
+ * @param resultSink the recipient of result objects.
+ * @param <T> type of result objects produced by the consumer.
+ * @return the request consumer.
+ */
+ public static <T> AsyncRequestConsumer<Long> create(
+ final ObjectMapper objectMapper,
+ final Class<T> objectClazz,
+ final JsonConsumer<HttpRequest> requestValidator,
+ final JsonResultSink<T> resultSink) {
+ return new JsonSequenceRequestConsumer<>(
+ () -> new JsonSequenceEntityConsumer<>(objectMapper, objectClazz, resultSink),
+ requestValidator);
+ }
+
+ /**
+ * Creates {@link AsyncRequestConsumer} that converts incoming HTTP request
+ * into a sequence of instances of the given class and passes those objects
+ * to the given {@link JsonResultSink}.
+ *
+ * @param objectMapper the object mapper to be used to de-serialize JSON content.
+ * @param typeReference the type reference of the de-serialized object.
+ * @param requestValidator optional operation that accepts the message head as input.
+ * @param resultSink the recipient of result objects.
+ * @param <T> type of result objects produced by the consumer.
+ * @return the request consumer.
+ */
+ public static <T> AsyncRequestConsumer<Long> create(
+ final ObjectMapper objectMapper,
+ final TypeReference<T> typeReference,
+ final JsonConsumer<HttpRequest> requestValidator,
+ final JsonResultSink<T> resultSink) {
+ return new JsonSequenceRequestConsumer<>(
+ () -> new JsonSequenceEntityConsumer<>(objectMapper, typeReference, resultSink),
+ requestValidator);
+ }
+
+ /**
+ * Creates {@link AsyncRequestConsumer} that converts incoming HTTP request
+ * into a sequence of {@link JsonNode} instances and passes those objects
+ * to the given {@link JsonResultSink}.
+ *
+ * @param objectMapper the object mapper to be used to de-serialize JSON content.
+ * @param requestValidator optional operation that accepts the message head as input.
+ * @param resultSink the recipient of result objects.
+ * @return the request consumer.
+ */
+ public static AsyncRequestConsumer<Long> create(
+ final ObjectMapper objectMapper,
+ final JsonConsumer<HttpRequest> requestValidator,
+ final JsonResultSink<JsonNode> resultSink) {
+ return new JsonSequenceRequestConsumer<>(
+ () -> new JsonNodeSequenceEntityConsumer(objectMapper, resultSink),
+ requestValidator);
+ }
+
+ /**
+ * Creates {@link AsyncRequestConsumer} that converts incoming HTTP request
+ * into a sequence of JSON tokens passed as events to the given {@link JsonTokenEventHandler}.
+ *
+ * @param jsonFactory JSON factory.
+ * @param requestValidator optional operation that accepts the message head as input.
+ * @param eventHandler JSON event handler
+ * @return the request consumer.
+ */
+ public static AsyncRequestConsumer<Void> create(
+ final JsonFactory jsonFactory,
+ final JsonConsumer<HttpRequest> requestValidator,
+ final JsonTokenEventHandler eventHandler) {
+ return new JsonSequenceRequestConsumer<>(
+ () -> new JsonTokenEntityConsumer(jsonFactory, eventHandler),
+ requestValidator);
+ }
+
+}
diff --git a/httpcore5/src/main/java/org/apache/hc/core5/http/Message.java b/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/JsonRequestObjectProducer.java
similarity index 53%
copy from httpcore5/src/main/java/org/apache/hc/core5/http/Message.java
copy to httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/JsonRequestObjectProducer.java
index b60d9724b..7290df3a7 100644
--- a/httpcore5/src/main/java/org/apache/hc/core5/http/Message.java
+++ b/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/JsonRequestObjectProducer.java
@@ -24,66 +24,39 @@
* <http://www.apache.org/>.
*
*/
+package org.apache.hc.core5.jackson2.http;
-package org.apache.hc.core5.http;
+import java.io.IOException;
+import org.apache.hc.core5.http.HttpException;
+import org.apache.hc.core5.http.HttpRequest;
+import org.apache.hc.core5.http.nio.AsyncEntityProducer;
+import org.apache.hc.core5.http.nio.AsyncRequestProducer;
+import org.apache.hc.core5.http.nio.RequestChannel;
+import org.apache.hc.core5.http.protocol.HttpContext;
import org.apache.hc.core5.util.Args;
-/**
- * Generic message consisting of a message head and a message body.
- *
- * @param <H> message head type.
- * @param <B> message body type.
- *
- * @since 5.0
- */
-public final class Message<H extends MessageHeaders, B> {
+final class JsonRequestObjectProducer extends JsonMessageProducer implements AsyncRequestProducer {
- private final H head;
- private final B body;
+ private final HttpRequest request;
- /**
- * Constructs a new instance.
- *
- * @param head The message head.
- * @since 5.3
- */
- public Message(final H head) {
- this(head, null);
+ public JsonRequestObjectProducer(final HttpRequest request, final AsyncEntityProducer entityProducer) {
+ super(entityProducer);
+ this.request = Args.notNull(request, "Request");
}
- /**
- * Constructs a new instance.
- *
- * @param head The message head.
- * @param body The message body.
- */
- public Message(final H head, final B body) {
- this.head = Args.notNull(head, "Message head");
- this.body = body;
- }
-
- /**
- * Gets the message head.
- *
- * @return the message head.
- */
- public H getHead() {
- return head;
+ @Override
+ public void sendRequest(final RequestChannel channel, final HttpContext context) throws HttpException, IOException {
+ channel.sendRequest(request, getEntityDetails(), context);
}
- /**
- * Gets the message body.
- *
- * @return the message body.
- */
- public B getBody() {
- return body;
+ @Override
+ public boolean isRepeatable() {
+ return super.isRepeatable();
}
@Override
- public String toString() {
- return "[head=" + head + ", body=" + body + ']';
+ public void failed(final Exception cause) {
}
}
diff --git a/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/JsonRequestProducers.java b/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/JsonRequestProducers.java
new file mode 100644
index 000000000..4b711cbf5
--- /dev/null
+++ b/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/JsonRequestProducers.java
@@ -0,0 +1,104 @@
+/*
+ * ====================================================================
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * <http://www.apache.org/>.
+ *
+ */
+package org.apache.hc.core5.jackson2.http;
+
+import com.fasterxml.jackson.core.JsonFactory;
+import com.fasterxml.jackson.core.JsonGenerator;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+import org.apache.hc.core5.http.HttpRequest;
+import org.apache.hc.core5.http.nio.AsyncRequestProducer;
+import org.apache.hc.core5.jackson2.JsonConsumer;
+
+/**
+ * Factory class for JSON {@link AsyncRequestProducer}s.
+ */
+public final class JsonRequestProducers {
+
+ /**
+ * Creates {@link AsyncRequestProducer} that generates an HTTP request
+ * enclosing a serialized JSON object as a message body.
+ *
+ * @param request the request message head.
+ * @param jsonObject teh JSON object to be enclosed as a message body.
+ * @param objectMapper the object mapper to be used to serialize JSON content.
+ * @param <T> the type of objects used by the producer.
+ * @return the request producer.
+ */
+ public static <T> AsyncRequestProducer create(final HttpRequest request,
+ final T jsonObject,
+ final ObjectMapper objectMapper) {
+ return new JsonRequestObjectProducer(request, new JsonObjectEntityProducer<>(jsonObject, objectMapper));
+ }
+
+ /**
+ * Creates {@link AsyncRequestProducer} that generates an HTTP request
+ * enclosing a serialized JSON object as a message body.
+ *
+ * @param request the request message head.
+ * @param jsonObject the JSON object to be enclosed as a message body.
+ * @param objectMapper the object mapper to be used to serialize JSON content.
+ * @return the request producer.
+ */
+ public static AsyncRequestProducer create(final HttpRequest request,
+ final JsonNode jsonObject,
+ final ObjectMapper objectMapper) {
+ return new JsonRequestObjectProducer(request, new JsonNodeEntityProducer(jsonObject, objectMapper));
+ }
+
+ /**
+ * Creates {@link AsyncRequestProducer} that generates an HTTP request
+ * enclosing a sequence of serialized JSON object as a message body.
+ *
+ * @param request the request message head.
+ * @param objectMapper the object mapper to be used to serialize JSON content.
+ * @param objectProducer the JSON object producer.
+ * @return the request producer.
+ */
+ public static <T> AsyncRequestProducer create(final HttpRequest request,
+ final ObjectMapper objectMapper,
+ final ObjectProducer<T> objectProducer) {
+ return new JsonRequestObjectProducer(request, new JsonSequenceEntityProducer<>(objectMapper, objectProducer));
+ }
+
+ /**
+ * Creates {@link AsyncRequestProducer} that generates an HTTP request
+ * enclosing JSON content generated using the provided {@link JsonGenerator}.
+ *
+ * @param request the request message head.
+ * @param jsonFactory JSON factory.
+ * @param consumer the recipient of JSON content generator.
+ * @return the request producer.
+ */
+ public static AsyncRequestProducer create(final HttpRequest request,
+ final JsonFactory jsonFactory,
+ final JsonConsumer<JsonGenerator> consumer) {
+ return new JsonRequestObjectProducer(request, new JsonTokenEntityProducer(jsonFactory, consumer));
+ }
+
+}
diff --git a/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/JsonResponseConsumer.java b/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/JsonResponseConsumer.java
new file mode 100644
index 000000000..ac45e27de
--- /dev/null
+++ b/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/JsonResponseConsumer.java
@@ -0,0 +1,92 @@
+/*
+ * ====================================================================
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * <http://www.apache.org/>.
+ *
+ */
+package org.apache.hc.core5.jackson2.http;
+
+import java.io.IOException;
+
+import org.apache.hc.core5.concurrent.CallbackContribution;
+import org.apache.hc.core5.concurrent.FutureCallback;
+import org.apache.hc.core5.function.Supplier;
+import org.apache.hc.core5.http.EntityDetails;
+import org.apache.hc.core5.http.HttpException;
+import org.apache.hc.core5.http.HttpResponse;
+import org.apache.hc.core5.http.HttpStatus;
+import org.apache.hc.core5.http.Message;
+import org.apache.hc.core5.http.nio.AsyncEntityConsumer;
+import org.apache.hc.core5.http.nio.AsyncResponseConsumer;
+import org.apache.hc.core5.http.protocol.HttpContext;
+import org.apache.hc.core5.util.Args;
+
+class JsonResponseConsumer<T, E> extends AbstractJsonMessageConsumer<HttpResponse, T>
+ implements AsyncResponseConsumer<Message<HttpResponse, T>> {
+
+ private final Supplier<AsyncEntityConsumer<E>> errorConsumerSupplier;
+
+ public JsonResponseConsumer(
+ final Supplier<AsyncEntityConsumer<T>> jsonConsumerSupplier,
+ final Supplier<AsyncEntityConsumer<E>> errorConsumerSupplier) {
+ super(jsonConsumerSupplier);
+ this.errorConsumerSupplier = Args.notNull(errorConsumerSupplier, "Error consumer supplier");
+ }
+
+ @Override
+ public void informationResponse(final HttpResponse response, final HttpContext context) throws HttpException, IOException {
+ }
+
+ @Override
+ public void consumeResponse(final HttpResponse response,
+ final EntityDetails entityDetails,
+ final HttpContext context,
+ final FutureCallback<Message<HttpResponse, T>> resultCallback) throws HttpException, IOException {
+ if (response.getCode() >= HttpStatus.SC_REDIRECTION) {
+ final AsyncEntityConsumer<E> entityConsumer = errorConsumerSupplier.get();
+ handleContent(entityConsumer, entityDetails, new CallbackContribution<E>(resultCallback) {
+
+ @Override
+ public void completed(final E result) {
+ resultCallback.completed(new Message<>(response, null, result));
+ }
+
+ });
+ } else {
+ consumeMessage(response, entityDetails, context, new CallbackContribution<T>(resultCallback) {
+
+ @Override
+ public void completed(final T result) {
+ resultCallback.completed(new Message<>(response, result));
+ }
+
+ });
+ }
+ }
+
+ @Override
+ public void failed(final Exception cause) {
+ super.failed(cause);
+ }
+
+}
diff --git a/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/JsonResponseConsumers.java b/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/JsonResponseConsumers.java
new file mode 100644
index 000000000..8f544e1e8
--- /dev/null
+++ b/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/JsonResponseConsumers.java
@@ -0,0 +1,494 @@
+/*
+ * ====================================================================
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * <http://www.apache.org/>.
+ *
+ */
+package org.apache.hc.core5.jackson2.http;
+
+import com.fasterxml.jackson.core.JsonFactory;
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.JavaType;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+import org.apache.hc.core5.function.Callback;
+import org.apache.hc.core5.function.Supplier;
+import org.apache.hc.core5.http.HttpResponse;
+import org.apache.hc.core5.http.Message;
+import org.apache.hc.core5.http.nio.AsyncEntityConsumer;
+import org.apache.hc.core5.http.nio.AsyncRequestConsumer;
+import org.apache.hc.core5.http.nio.AsyncResponseConsumer;
+import org.apache.hc.core5.http.nio.entity.StringAsyncEntityConsumer;
+import org.apache.hc.core5.jackson2.JsonConsumer;
+import org.apache.hc.core5.jackson2.JsonResultSink;
+import org.apache.hc.core5.jackson2.JsonTokenConsumer;
+import org.apache.hc.core5.jackson2.JsonTokenEventHandler;
+
+/**
+ * Factory class for JSON {@link AsyncResponseConsumer}s.
+ */
+public final class JsonResponseConsumers {
+
+ /**
+ * Creates {@link AsyncResponseConsumer} that produces a {@link Message} object
+ * consisting of the {@link HttpResponse} head and the de-serialized JSON body.
+ *
+ * @param objectMapper the object mapper to be used to de-serialize JSON content.
+ * @param javaType the java type of the de-serialized object.
+ * @param errorConsumerSupplier supplier of the custom error consumer
+ * @param <T> the type of result objects produced by the consumer.
+ * @param <E> the type of error object.
+ * @return the response consumer.
+ */
+ public static <T, E> AsyncResponseConsumer<Message<HttpResponse, T>> create(
+ final ObjectMapper objectMapper,
+ final JavaType javaType,
+ final Supplier<AsyncEntityConsumer<E>> errorConsumerSupplier) {
+ return new JsonResponseConsumer<>(
+ () -> new JsonObjectEntityConsumer<>(objectMapper, javaType),
+ errorConsumerSupplier);
+ }
+
+ /**
+ * Creates {@link AsyncResponseConsumer} that produces a {@link Message} object
+ * consisting of the {@link HttpResponse} head and the de-serialized JSON body.
+ *
+ * @param objectMapper the object mapper to be used to de-serialize JSON content.
+ * @param javaType the java type of the de-serialized object.
+ * @param <T> the type of result objects produced by the consumer.
+ * @return the response consumer.
+ */
+ public static <T> AsyncResponseConsumer<Message<HttpResponse, T>> create(
+ final ObjectMapper objectMapper,
+ final JavaType javaType) {
+ return create(objectMapper, javaType, StringAsyncEntityConsumer::new);
+ }
+
+ /**
+ * Creates {@link AsyncResponseConsumer} that produces a {@link Message} object
+ * consisting of the {@link HttpResponse} head and the de-serialized JSON body.
+ *
+ * @param objectMapper the object mapper to be used to de-serialize JSON content.
+ * @param objectClazz the class of the de-serialized object.
+ * @param errorConsumerSupplier supplier of the custom error consumer
+ * @param <T> the type of result objects produced by the consumer.
+ * @param <E> the type of error object.
+ * @return the response consumer.
+ */
+ public static <T, E> AsyncResponseConsumer<Message<HttpResponse, T>> create(
+ final ObjectMapper objectMapper,
+ final Class<T> objectClazz,
+ final Supplier<AsyncEntityConsumer<E>> errorConsumerSupplier) {
+ return new JsonResponseConsumer<>(
+ () -> new JsonObjectEntityConsumer<>(objectMapper, objectClazz),
+ errorConsumerSupplier);
+ }
+
+ /**
+ * Creates {@link AsyncResponseConsumer} that produces a {@link Message} object
+ * consisting of the {@link HttpResponse} head and the de-serialized JSON body.
+ *
+ * @param objectMapper the object mapper to be used to de-serialize JSON content.
+ * @param objectClazz the class of the de-serialized object.
+ * @param <T> the type of result objects produced by the consumer.
+ * @return the response consumer.
+ */
+ public static <T> AsyncResponseConsumer<Message<HttpResponse, T>> create(
+ final ObjectMapper objectMapper,
+ final Class<T> objectClazz) {
+ return create(objectMapper, objectClazz, StringAsyncEntityConsumer::new);
+ }
+
+ /**
+ * Creates {@link AsyncResponseConsumer} that produces a {@link Message} object
+ * consisting of the {@link HttpResponse} head and the de-serialized JSON body.
+ *
+ * @param objectMapper the object mapper to be used to de-serialize JSON content.
+ * @param typeReference the type reference of the de-serialized object.
+ * @param errorConsumerSupplier supplier of the custom error consumer
+ * @param <T> the type of result objects produced by the consumer.
+ * @param <E> the type of error object.
+ * @return the response consumer.
+ */
+ public static <T, E> AsyncResponseConsumer<Message<HttpResponse, T>> create(
+ final ObjectMapper objectMapper,
+ final TypeReference<T> typeReference,
+ final Supplier<AsyncEntityConsumer<E>> errorConsumerSupplier) {
+ return new JsonResponseConsumer<>(
+ () -> new JsonObjectEntityConsumer<>(objectMapper, typeReference),
+ errorConsumerSupplier);
+ }
+
+ /**
+ * Creates {@link AsyncResponseConsumer} that produces a {@link Message} object
+ * consisting of the {@link HttpResponse} head and the de-serialized JSON body.
+ *
+ * @param objectMapper the object mapper to be used to de-serialize JSON content.
+ * @param typeReference the type reference of the de-serialized object.
+ * @param <T> the type of result objects produced by the consumer.
+ * @return the response consumer.
+ */
+ public static <T> AsyncResponseConsumer<Message<HttpResponse, T>> create(
+ final ObjectMapper objectMapper,
+ final TypeReference<T> typeReference) {
+ return create(objectMapper, typeReference, StringAsyncEntityConsumer::new);
+ }
+
+ /**
+ * Creates {@link AsyncResponseConsumer} that produces a {@link Message} object
+ * consisting of the {@link HttpResponse} head and the {@link JsonNode} body.
+ *
+ * @param jsonFactory JSON factory.
+ * @param errorConsumerSupplier supplier of the custom error consumer
+ * @param <E> the type of error object.
+ * @return the response consumer.
+ */
+ public static <E> AsyncResponseConsumer<Message<HttpResponse, JsonNode>> create(
+ final JsonFactory jsonFactory,
+ final Supplier<AsyncEntityConsumer<E>> errorConsumerSupplier) {
+ return new JsonResponseConsumer<>(
+ () -> new JsonNodeEntityConsumer(jsonFactory),
+ errorConsumerSupplier);
+ }
+
+ /**
+ * Creates {@link AsyncResponseConsumer} that produces a {@link Message} object
+ * consisting of the {@link HttpResponse} head and the {@link JsonNode} body.
+ *
+ * @param jsonFactory JSON factory.
+ * @return the response consumer.
+ */
+ public static AsyncResponseConsumer<Message<HttpResponse, JsonNode>> create(final JsonFactory jsonFactory) {
+ return create(jsonFactory, StringAsyncEntityConsumer::new);
+ }
+
+ /**
+ * Creates {@link AsyncResponseConsumer} that converts incoming HTTP response
+ * into a sequence of instances of the given class and passes those objects
+ * to the given {@link JsonResultSink}.
+ *
+ * @param objectMapper the object mapper to be used to de-serialize JSON content.
+ * @param javaType the java type of the de-serialized object.
+ * @param errorConsumerSupplier supplier of the custom error consumer
+ * @param responseValidator optional operation that accepts the message head as input.
+ * @param errorCallback optional operation that accepts the error message as input in case of an error.
+ * @param resultSink the recipient of result objects.
+ * @param <T> type of result objects produced by the consumer.
+ * @param <E> the type of error object.
+ * @return the response consumer.
+ */
+ public static <T, E> AsyncResponseConsumer<Long> create(
+ final ObjectMapper objectMapper,
+ final JavaType javaType,
+ final Supplier<AsyncEntityConsumer<E>> errorConsumerSupplier,
+ final JsonConsumer<HttpResponse> responseValidator,
+ final Callback<E> errorCallback,
+ final JsonResultSink<T> resultSink) {
+ return new JsonSequenceResponseConsumer<>(
+ () -> new JsonSequenceEntityConsumer<T>(objectMapper, javaType, resultSink),
+ errorConsumerSupplier,
+ responseValidator,
+ errorCallback);
+ }
+
+ /**
+ * Creates {@link AsyncResponseConsumer} that converts incoming HTTP response
+ * into a sequence of instances of the given class and passes those objects
+ * to the given {@link JsonResultSink}.
+ *
+ * @param objectMapper the object mapper to be used to de-serialize JSON content.
+ * @param javaType the java type of the de-serialized object.
+ * @param responseValidator optional operation that accepts the message head as input.
+ * @param errorCallback optional operation that accepts the error message as input in case of an error.
+ * @param resultSink the recipient of result objects.
+ * @param <T> type of result objects produced by the consumer.
+ * @return the response consumer.
+ */
+ public static <T> AsyncResponseConsumer<Long> create(
+ final ObjectMapper objectMapper,
+ final JavaType javaType,
+ final JsonConsumer<HttpResponse> responseValidator,
+ final Callback<String> errorCallback,
+ final JsonResultSink<T> resultSink) {
+ return new JsonSequenceResponseConsumer<>(
+ () -> new JsonSequenceEntityConsumer<T>(objectMapper, javaType, resultSink),
+ StringAsyncEntityConsumer::new,
+ responseValidator,
+ errorCallback);
+ }
+
+ /**
+ * Creates {@link AsyncResponseConsumer} that converts incoming HTTP response
+ * into a sequence of instances of the given class and passes those objects
+ * to the given {@link JsonResultSink}.
+ *
+ * @param objectMapper the object mapper to be used to de-serialize JSON content.
+ * @param objectClazz the class of the de-serialized object.
+ * @param errorConsumerSupplier supplier of the custom error consumer
+ * @param responseValidator optional operation that accepts the message head as input.
+ * @param errorCallback optional operation that accepts the error message as input in case of an error.
+ * @param resultSink the recipient of result objects.
+ * @param <T> type of result objects produced by the consumer.
+ * @param <E> the type of error object.
+ * @return the response consumer.
+ */
+ public static <T, E> AsyncResponseConsumer<Long> create(
+ final ObjectMapper objectMapper,
+ final Class<T> objectClazz,
+ final Supplier<AsyncEntityConsumer<E>> errorConsumerSupplier,
+ final JsonConsumer<HttpResponse> responseValidator,
+ final Callback<E> errorCallback,
+ final JsonResultSink<T> resultSink) {
+ return new JsonSequenceResponseConsumer<>(
+ () -> new JsonSequenceEntityConsumer<>(objectMapper, objectClazz, resultSink),
+ errorConsumerSupplier,
+ responseValidator,
+ errorCallback);
+ }
+
+ /**
+ * Creates {@link AsyncResponseConsumer} that converts incoming HTTP response
+ * into a sequence of instances of the given class and passes those objects
+ * to the given {@link JsonResultSink}.
+ *
+ * @param objectMapper the object mapper to be used to de-serialize JSON content.
+ * @param objectClazz the class of the de-serialized object.
+ * @param responseValidator optional operation that accepts the message head as input.
+ * @param errorCallback optional operation that accepts the error message as input in case of an error.
+ * @param resultSink the recipient of result objects.
+ * @param <T> type of result objects produced by the consumer.
+ * @return the response consumer.
+ */
+ public static <T> AsyncResponseConsumer<Long> create(
+ final ObjectMapper objectMapper,
+ final Class<T> objectClazz,
+ final JsonConsumer<HttpResponse> responseValidator,
+ final Callback<String> errorCallback,
+ final JsonResultSink<T> resultSink) {
+ return new JsonSequenceResponseConsumer<>(
+ () -> new JsonSequenceEntityConsumer<>(objectMapper, objectClazz, resultSink),
+ StringAsyncEntityConsumer::new,
+ responseValidator,
+ errorCallback);
+ }
+
+ /**
+ * Creates {@link AsyncResponseConsumer} that converts incoming HTTP response
+ * into a sequence of instances of the given class and passes those objects
+ * to the given {@link JsonResultSink}.
+ *
+ * @param objectMapper the object mapper to be used to de-serialize JSON content.
+ * @param typeReference the type reference of the de-serialized object.
+ * @param errorConsumerSupplier supplier of the custom error consumer
+ * @param responseValidator optional operation that accepts the message head as input.
+ * @param errorCallback optional operation that accepts the error message as input in case of an error.
+ * @param resultSink the recipient of result objects.
+ * @param <T> type of result objects produced by the consumer.
+ * @param <E> the type of error object.
+ * @return the response consumer.
+ */
+ public static <T, E> AsyncResponseConsumer<Long> create(
+ final ObjectMapper objectMapper,
+ final TypeReference<T> typeReference,
+ final Supplier<AsyncEntityConsumer<E>> errorConsumerSupplier,
+ final JsonConsumer<HttpResponse> responseValidator,
+ final Callback<E> errorCallback,
+ final JsonResultSink<T> resultSink) {
+ return new JsonSequenceResponseConsumer<>(
+ () -> new JsonSequenceEntityConsumer<>(objectMapper, typeReference, resultSink),
+ errorConsumerSupplier,
+ responseValidator,
+ errorCallback);
+ }
+
+ /**
+ * Creates {@link AsyncResponseConsumer} that converts incoming HTTP response
+ * into a sequence of instances of the given class and passes those objects
+ * to the given {@link JsonResultSink}.
+ *
+ * @param objectMapper the object mapper to be used to de-serialize JSON content.
+ * @param typeReference the type reference of the de-serialized object.
+ * @param responseValidator optional operation that accepts the message head as input.
+ * @param errorCallback optional operation that accepts the error message as input in case of an error.
+ * @param resultSink the recipient of result objects.
+ * @param <T> type of result objects produced by the consumer.
+ * @return the response consumer.
+ */
+ public static <T> AsyncResponseConsumer<Long> create(
+ final ObjectMapper objectMapper,
+ final TypeReference<T> typeReference,
+ final JsonConsumer<HttpResponse> responseValidator,
+ final Callback<String> errorCallback,
+ final JsonResultSink<T> resultSink) {
+ return new JsonSequenceResponseConsumer<>(
+ () -> new JsonSequenceEntityConsumer<>(objectMapper, typeReference, resultSink),
+ StringAsyncEntityConsumer::new,
+ responseValidator,
+ errorCallback);
+ }
+
+ /**
+ * Creates {@link AsyncResponseConsumer} that converts incoming HTTP response
+ * into a sequence of JSON tokens passed as events to the given {@link JsonTokenEventHandler}.
+ *
+ * @param jsonFactory JSON factory.
+ * @param errorConsumerSupplier supplier of the custom error consumer
+ * @param responseValidator optional operation that accepts the message head as input.
+ * @param errorCallback optional operation that accepts the error message as input in case of an error.
+ * @param eventHandler JSON event handler
+ * @param <E> the type of error object.
+ * @return the response consumer.
+ */
+ public static <E> AsyncResponseConsumer<Void> create(
+ final JsonFactory jsonFactory,
+ final Supplier<AsyncEntityConsumer<E>> errorConsumerSupplier,
+ final JsonConsumer<HttpResponse> responseValidator,
+ final Callback<E> errorCallback,
+ final JsonTokenEventHandler eventHandler) {
+ return new JsonSequenceResponseConsumer<>(
+ () -> new JsonTokenEntityConsumer(jsonFactory, eventHandler),
+ errorConsumerSupplier,
+ responseValidator,
+ errorCallback);
+ }
+
+ /**
+ * Creates {@link AsyncResponseConsumer} that converts incoming HTTP response
+ * into a sequence of JSON tokens passed as events to the given {@link JsonTokenEventHandler}.
+ *
+ * @param jsonFactory JSON factory.
+ * @param responseValidator optional operation that accepts the message head as input.
+ * @param errorCallback optional operation that accepts the error message as input in case of an error.
+ * @param eventHandler JSON event handler
+ * @return the response consumer.
+ */
+ public static AsyncResponseConsumer<Void> create(
+ final JsonFactory jsonFactory,
+ final JsonConsumer<HttpResponse> responseValidator,
+ final Callback<String> errorCallback,
+ final JsonTokenEventHandler eventHandler) {
+ return new JsonSequenceResponseConsumer<>(
+ () -> new JsonTokenEntityConsumer(jsonFactory, eventHandler),
+ StringAsyncEntityConsumer::new,
+ responseValidator,
+ errorCallback);
+ }
+
+ /**
+ * Creates {@link AsyncRequestConsumer} that converts incoming HTTP response
+ * into a sequence of {@link JsonNode} instances and passes those objects
+ * to the given {@link JsonResultSink}.
+ *
+ * @param objectMapper the object mapper to be used to de-serialize JSON content.
+ * @param errorConsumerSupplier supplier of the custom error consumer
+ * @param responseValidator optional operation that accepts the message head as input.
+ * @param errorCallback optional operation that accepts the error message as input in case of an error.
+ * @param resultSink the recipient of result objects.
+ * @param <E> the type of error object.
+ * @return the request consumer.
+ */
+ public static <E> AsyncResponseConsumer<Long> create(
+ final ObjectMapper objectMapper,
+ final Supplier<AsyncEntityConsumer<E>> errorConsumerSupplier,
+ final JsonConsumer<HttpResponse> responseValidator,
+ final Callback<E> errorCallback,
+ final JsonResultSink<JsonNode> resultSink) {
+ return new JsonSequenceResponseConsumer<>(
+ () -> new JsonNodeSequenceEntityConsumer(objectMapper, resultSink),
+ errorConsumerSupplier,
+ responseValidator,
+ errorCallback);
+ }
+
+ /**
+ * Creates {@link AsyncRequestConsumer} that converts incoming HTTP response
+ * into a sequence of {@link JsonNode} instances and passes those objects
+ * to the given {@link JsonResultSink}.
+ *
+ * @param objectMapper the object mapper to be used to de-serialize JSON content.
+ * @param responseValidator optional operation that accepts the message head as input.
+ * @param errorCallback optional operation that accepts the error message as input in case of an error.
+ * @param resultSink the recipient of result objects.
+ * @return the request consumer.
+ */
+ public static AsyncResponseConsumer<Long> create(
+ final ObjectMapper objectMapper,
+ final JsonConsumer<HttpResponse> responseValidator,
+ final Callback<String> errorCallback,
+ final JsonResultSink<JsonNode> resultSink) {
+ return new JsonSequenceResponseConsumer<>(
+ () -> new JsonNodeSequenceEntityConsumer(objectMapper, resultSink),
+ StringAsyncEntityConsumer::new,
+ responseValidator,
+ errorCallback);
+ }
+
+ /**
+ * Creates {@link AsyncResponseConsumer} that converts incoming HTTP response
+ * into a sequence of JSON tokens passed as events to the given {@link JsonTokenConsumer}.
+ *
+ * @param jsonFactory JSON factory.
+ * @param errorConsumerSupplier supplier of the custom error consumer
+ * @param responseValidator optional operation that accepts the message head as input.
+ * @param errorCallback optional operation that accepts the error message as input in case of an error.
+ * @param tokenConsumer JSON token Consumer
+ * @param <E> the type of error object.
+ * @return the response consumer.
+ */
+ public static <E> AsyncResponseConsumer<Void> create(
+ final JsonFactory jsonFactory,
+ final Supplier<AsyncEntityConsumer<E>> errorConsumerSupplier,
+ final JsonConsumer<HttpResponse> responseValidator,
+ final Callback<E> errorCallback,
+ final JsonTokenConsumer tokenConsumer) {
+ return new JsonSequenceResponseConsumer<>(
+ () -> new JsonTokenEntityConsumer(jsonFactory, tokenConsumer),
+ errorConsumerSupplier,
+ responseValidator,
+ errorCallback);
+ }
+
+ /**
+ * Creates {@link AsyncResponseConsumer} that converts incoming HTTP response
+ * into a sequence of JSON tokens passed as events to the given {@link JsonTokenConsumer}.
+ *
+ * @param jsonFactory JSON factory.
+ * @param responseValidator optional operation that accepts the message head as input.
+ * @param errorCallback optional operation that accepts the error message as input in case of an error.
+ * @param tokenConsumer JSON token Consumer
+ * @return the response consumer.
+ */
+ public static <E> AsyncResponseConsumer<Void> create(
+ final JsonFactory jsonFactory,
+ final JsonConsumer<HttpResponse> responseValidator,
+ final Callback<String> errorCallback,
+ final JsonTokenConsumer tokenConsumer) {
+ return new JsonSequenceResponseConsumer<>(
+ () -> new JsonTokenEntityConsumer(jsonFactory, tokenConsumer),
+ StringAsyncEntityConsumer::new,
+ responseValidator,
+ errorCallback);
+ }
+
+}
diff --git a/httpcore5/src/main/java/org/apache/hc/core5/http/Message.java b/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/JsonResponseObjectProducer.java
similarity index 53%
copy from httpcore5/src/main/java/org/apache/hc/core5/http/Message.java
copy to httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/JsonResponseObjectProducer.java
index b60d9724b..86d2e29e0 100644
--- a/httpcore5/src/main/java/org/apache/hc/core5/http/Message.java
+++ b/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/JsonResponseObjectProducer.java
@@ -24,66 +24,39 @@
* <http://www.apache.org/>.
*
*/
+package org.apache.hc.core5.jackson2.http;
-package org.apache.hc.core5.http;
+import java.io.IOException;
+import org.apache.hc.core5.http.HttpException;
+import org.apache.hc.core5.http.HttpResponse;
+import org.apache.hc.core5.http.nio.AsyncEntityProducer;
+import org.apache.hc.core5.http.nio.AsyncResponseProducer;
+import org.apache.hc.core5.http.nio.ResponseChannel;
+import org.apache.hc.core5.http.protocol.HttpContext;
import org.apache.hc.core5.util.Args;
-/**
- * Generic message consisting of a message head and a message body.
- *
- * @param <H> message head type.
- * @param <B> message body type.
- *
- * @since 5.0
- */
-public final class Message<H extends MessageHeaders, B> {
+final class JsonResponseObjectProducer extends JsonMessageProducer implements AsyncResponseProducer {
- private final H head;
- private final B body;
+ private final HttpResponse response;
- /**
- * Constructs a new instance.
- *
- * @param head The message head.
- * @since 5.3
- */
- public Message(final H head) {
- this(head, null);
+ public JsonResponseObjectProducer(final HttpResponse response, final AsyncEntityProducer entityProducer) {
+ super(entityProducer);
+ this.response = Args.notNull(response, "Response");
}
- /**
- * Constructs a new instance.
- *
- * @param head The message head.
- * @param body The message body.
- */
- public Message(final H head, final B body) {
- this.head = Args.notNull(head, "Message head");
- this.body = body;
- }
-
- /**
- * Gets the message head.
- *
- * @return the message head.
- */
- public H getHead() {
- return head;
+ @Override
+ public void sendResponse(final ResponseChannel channel, final HttpContext context) throws HttpException, IOException {
+ channel.sendResponse(response, getEntityDetails(), context);
}
- /**
- * Gets the message body.
- *
- * @return the message body.
- */
- public B getBody() {
- return body;
+ @Override
+ public boolean isRepeatable() {
+ return super.isRepeatable();
}
@Override
- public String toString() {
- return "[head=" + head + ", body=" + body + ']';
+ public void failed(final Exception cause) {
}
}
diff --git a/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/JsonResponseProducers.java b/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/JsonResponseProducers.java
new file mode 100644
index 000000000..f9d777aac
--- /dev/null
+++ b/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/JsonResponseProducers.java
@@ -0,0 +1,104 @@
+/*
+ * ====================================================================
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * <http://www.apache.org/>.
+ *
+ */
+package org.apache.hc.core5.jackson2.http;
+
+import com.fasterxml.jackson.core.JsonFactory;
+import com.fasterxml.jackson.core.JsonGenerator;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+import org.apache.hc.core5.http.HttpResponse;
+import org.apache.hc.core5.http.nio.AsyncResponseProducer;
+import org.apache.hc.core5.jackson2.JsonConsumer;
+
+/**
+ * Factory class for JSON {@link AsyncResponseProducer}s.
+ */
+public final class JsonResponseProducers {
+
+ /**
+ * Creates {@link AsyncResponseProducer} that generates an HTTP response
+ * enclosing a serialized JSON object as a message body.
+ *
+ * @param response the response message head.
+ * @param jsonObject teh JSON object to be enclosed as a message body.
+ * @param objectMapper the object mapper to be used to serialize JSON content.
+ * @param <T> the type of objects used by the producer.
+ * @return the response producer.
+ */
+ public static <T> AsyncResponseProducer create(final HttpResponse response,
+ final T jsonObject,
+ final ObjectMapper objectMapper) {
+ return new JsonResponseObjectProducer(response, new JsonObjectEntityProducer<>(jsonObject, objectMapper));
+ }
+
+ /**
+ * Creates {@link AsyncResponseProducer} that generates an HTTP response
+ * enclosing a serialized JSON object as a message body.
+ *
+ * @param response the response message head.
+ * @param jsonObject the JSON object to be enclosed as a message body.
+ * @param objectMapper the object mapper to be used to serialize JSON content.
+ * @return the response producer.
+ */
+ public static AsyncResponseProducer create(final HttpResponse response,
+ final JsonNode jsonObject,
+ final ObjectMapper objectMapper) {
+ return new JsonResponseObjectProducer(response, new JsonNodeEntityProducer(jsonObject, objectMapper));
+ }
+
+ /**
+ * Creates {@link AsyncResponseProducer} that generates an HTTP response
+ * enclosing a sequence of serialized JSON object as a message body.
+ *
+ * @param response the response message head.
+ * @param objectMapper the object mapper to be used to serialize JSON content.
+ * @param objectProducer the JSON object producer.
+ * @return the response producer.
+ */
+ public static <T> AsyncResponseProducer create(final HttpResponse response,
+ final ObjectMapper objectMapper,
+ final ObjectProducer<T> objectProducer) {
+ return new JsonResponseObjectProducer(response, new JsonSequenceEntityProducer<>(objectMapper, objectProducer));
+ }
+
+ /**
+ * Creates {@link AsyncResponseProducer} that generates an HTTP response
+ * enclosing JSON content generated using the provided {@link JsonGenerator}.
+ *
+ * @param response the response message head.
+ * @param jsonFactory JSON factory.
+ * @param consumer the recipient of JSON content generator.
+ * @return the response producer.
+ */
+ public static AsyncResponseProducer create(final HttpResponse response,
+ final JsonFactory jsonFactory,
+ final JsonConsumer<JsonGenerator> consumer) {
+ return new JsonResponseObjectProducer(response, new JsonTokenEntityProducer(jsonFactory, consumer));
+ }
+
+}
diff --git a/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/JsonSequenceEntityConsumer.java b/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/JsonSequenceEntityConsumer.java
new file mode 100644
index 000000000..fccb5183b
--- /dev/null
+++ b/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/JsonSequenceEntityConsumer.java
@@ -0,0 +1,64 @@
+/*
+ * ====================================================================
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * <http://www.apache.org/>.
+ *
+ */
+package org.apache.hc.core5.jackson2.http;
+
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.JavaType;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+import org.apache.hc.core5.jackson2.JsonResultSink;
+import org.apache.hc.core5.util.Args;
+
+/**
+ * {@link org.apache.hc.core5.http.nio.AsyncEntityConsumer} implementation that
+ * converts incoming HTTP message entity into a sequence of instances
+ * of the given class and passes those objects to the {@link JsonResultSink}.
+ *
+ * @param <T> type of objects produced by this class.
+ * @since 5.5
+ */
+public class JsonSequenceEntityConsumer<T> extends AbstractJsonSequenceEntityConsumer<T> {
+
+ public JsonSequenceEntityConsumer(final ObjectMapper objectMapper, final JavaType javaType, final JsonResultSink<T> resultSink) {
+ super(Args.notNull(objectMapper, "Object mapper").getFactory(),
+ jsonParser -> objectMapper.readValue(jsonParser, javaType),
+ resultSink);
+ }
+
+ public JsonSequenceEntityConsumer(final ObjectMapper objectMapper, final Class<T> objectClazz, final JsonResultSink<T> resultSink) {
+ this(Args.notNull(objectMapper, "Object mapper"),
+ objectMapper.getTypeFactory().constructType(objectClazz),
+ resultSink);
+ }
+
+ public JsonSequenceEntityConsumer(final ObjectMapper objectMapper, final TypeReference<T> typeReference, final JsonResultSink<T> resultSink) {
+ this(Args.notNull(objectMapper, "Object mapper"),
+ objectMapper.getTypeFactory().constructType(typeReference),
+ resultSink);
+ }
+
+}
diff --git a/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/JsonSequenceEntityProducer.java b/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/JsonSequenceEntityProducer.java
new file mode 100644
index 000000000..8e9f7e00b
--- /dev/null
+++ b/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/JsonSequenceEntityProducer.java
@@ -0,0 +1,175 @@
+/*
+ * ====================================================================
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * <http://www.apache.org/>.
+ *
+ */
+package org.apache.hc.core5.jackson2.http;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.util.Set;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+import org.apache.hc.core5.http.ContentType;
+import org.apache.hc.core5.http.nio.AsyncEntityProducer;
+import org.apache.hc.core5.http.nio.DataStreamChannel;
+import org.apache.hc.core5.util.Args;
+
+/**
+ * {@link AsyncEntityProducer} implementation that
+ * generates a message body containing serialized content of a sequence of JSON objects.
+ *
+ * @param <T> type of objects used by this class.
+ * @since 5.5
+ */
+public class JsonSequenceEntityProducer<T> implements AsyncEntityProducer {
+
+ private enum State { ACTIVE, FLUSHING, END_STREAM }
+
+ private final ObjectMapper objectMapper;
+ private final int initSize;
+ private final InternalBuffer buffer;
+ private final ObjectProducer<T> objectProducer;
+ private final OutputStream outputStream;
+
+ private volatile State state;
+
+ public JsonSequenceEntityProducer(final ObjectMapper objectMapper, final int initSize, final ObjectProducer<T> objectProducer) {
+ this.objectMapper = Args.notNull(objectMapper, "Object mapper");
+ this.initSize = initSize;
+ this.buffer = new InternalBuffer(initSize);
+ this.objectProducer = Args.notNull(objectProducer, "Object producer");
+ this.state = State.ACTIVE;
+ this.outputStream = new OutputStream() {
+
+ @Override
+ public void write(final byte[] b, final int off, final int len) throws IOException {
+ buffer.write(b, off, len);
+ }
+
+ @Override
+ public void write(final int b) throws IOException {
+ buffer.write(b);
+ }
+
+ };
+ }
+
+ public JsonSequenceEntityProducer(final ObjectMapper objectMapper, final ObjectProducer<T> objectProducer) {
+ this(objectMapper, 4096, objectProducer);
+ }
+
+ @Override
+ public final long getContentLength() {
+ return -1;
+ }
+
+ @Override
+ public final Set<String> getTrailerNames() {
+ return null;
+ }
+
+ @Override
+ public final String getContentType() {
+ return ContentType.APPLICATION_JSON.toString();
+ }
+
+ @Override
+ public final String getContentEncoding() {
+ return null;
+ }
+
+ @Override
+ public boolean isRepeatable() {
+ return false;
+ }
+
+ @Override
+ public boolean isChunked() {
+ return false;
+ }
+
+ @Override
+ public final int available() {
+ synchronized (buffer) {
+ return buffer.length();
+ }
+ }
+
+ @Override
+ public final void produce(final DataStreamChannel channel) throws IOException {
+ synchronized (buffer) {
+ if (state == State.ACTIVE && buffer.length() < initSize) {
+ objectProducer.produce(new ObjectChannel<T>() {
+
+ @Override
+ public int write(final T obj) throws IOException {
+ synchronized (buffer) {
+ objectMapper.writeValue(outputStream, obj);
+ channel.write(buffer.getByteBuffer());
+ return 1;
+ }
+ }
+
+ @Override
+ public void endStream() throws IOException {
+ synchronized (buffer) {
+ if (buffer.hasData()) {
+ channel.write(buffer.getByteBuffer());
+ }
+ if (buffer.hasData()) {
+ channel.requestOutput();
+ state = State.FLUSHING;
+ } else {
+ channel.endStream(null);
+ state = State.END_STREAM;
+ }
+ }
+ }
+
+ });
+ }
+ if (state.compareTo(State.END_STREAM) < 0 && buffer.hasData()) {
+ channel.write(buffer.getByteBuffer());
+ }
+ if (state == State.FLUSHING && !buffer.hasData()) {
+ channel.endStream(null);
+ state = State.END_STREAM;
+ }
+ }
+
+ }
+
+ @Override
+ public void failed(final Exception cause) {
+ }
+
+ @Override
+ public void releaseResources() {
+ buffer.clear();
+ state = State.ACTIVE;
+ }
+
+}
diff --git a/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/JsonSequenceRequestConsumer.java b/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/JsonSequenceRequestConsumer.java
new file mode 100644
index 000000000..8fd5e90ad
--- /dev/null
+++ b/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/JsonSequenceRequestConsumer.java
@@ -0,0 +1,76 @@
+/*
+ * ====================================================================
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * <http://www.apache.org/>.
+ *
+ */
+package org.apache.hc.core5.jackson2.http;
+
+import java.io.IOException;
+
+import org.apache.hc.core5.concurrent.CallbackContribution;
+import org.apache.hc.core5.concurrent.FutureCallback;
+import org.apache.hc.core5.function.Supplier;
+import org.apache.hc.core5.http.EntityDetails;
+import org.apache.hc.core5.http.HttpException;
+import org.apache.hc.core5.http.HttpRequest;
+import org.apache.hc.core5.http.nio.AsyncEntityConsumer;
+import org.apache.hc.core5.http.nio.AsyncRequestConsumer;
+import org.apache.hc.core5.http.protocol.HttpContext;
+import org.apache.hc.core5.jackson2.JsonConsumer;
+
+final class JsonSequenceRequestConsumer<T> extends AbstractJsonMessageConsumer<HttpRequest, T>
+ implements AsyncRequestConsumer<T> {
+
+ private final JsonConsumer<HttpRequest> requestValidator;
+
+ public JsonSequenceRequestConsumer(final Supplier<AsyncEntityConsumer<T>> jsonConsumerSupplier,
+ final JsonConsumer<HttpRequest> requestValidator) {
+ super(jsonConsumerSupplier);
+ this.requestValidator = requestValidator;
+ }
+
+ @Override
+ public void consumeRequest(final HttpRequest request,
+ final EntityDetails entityDetails,
+ final HttpContext context,
+ final FutureCallback<T> resultCallback) throws HttpException, IOException {
+ if (requestValidator != null) {
+ requestValidator.accept(request);
+ }
+ consumeMessage(request, entityDetails, context, new CallbackContribution<T>(resultCallback) {
+
+ @Override
+ public void completed(final T result) {
+ resultCallback.completed(result);
+ }
+
+ });
+ }
+
+ @Override
+ public void failed(final Exception cause) {
+ super.failed(cause);
+ }
+
+}
diff --git a/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/JsonSequenceResponseConsumer.java b/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/JsonSequenceResponseConsumer.java
new file mode 100644
index 000000000..80daef980
--- /dev/null
+++ b/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/JsonSequenceResponseConsumer.java
@@ -0,0 +1,106 @@
+/*
+ * ====================================================================
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * <http://www.apache.org/>.
+ *
+ */
+package org.apache.hc.core5.jackson2.http;
+
+import java.io.IOException;
+
+import org.apache.hc.core5.concurrent.CallbackContribution;
+import org.apache.hc.core5.concurrent.FutureCallback;
+import org.apache.hc.core5.function.Callback;
+import org.apache.hc.core5.function.Supplier;
+import org.apache.hc.core5.http.EntityDetails;
+import org.apache.hc.core5.http.HttpException;
+import org.apache.hc.core5.http.HttpResponse;
+import org.apache.hc.core5.http.HttpStatus;
+import org.apache.hc.core5.http.nio.AsyncEntityConsumer;
+import org.apache.hc.core5.http.nio.AsyncResponseConsumer;
+import org.apache.hc.core5.http.protocol.HttpContext;
+import org.apache.hc.core5.jackson2.JsonConsumer;
+import org.apache.hc.core5.util.Args;
+
+class JsonSequenceResponseConsumer<T, E> extends AbstractJsonMessageConsumer<HttpResponse, T>
+ implements AsyncResponseConsumer<T> {
+
+ private final Supplier<AsyncEntityConsumer<E>> errorConsumerSupplier;
+ private final JsonConsumer<HttpResponse> responseValidator;
+ private final Callback<E> errorCallback;
+
+ public JsonSequenceResponseConsumer(
+ final Supplier<AsyncEntityConsumer<T>> jsonConsumerSupplier,
+ final Supplier<AsyncEntityConsumer<E>> errorConsumerSupplier,
+ final JsonConsumer<HttpResponse> responseValidator,
+ final Callback<E> errorCallback) {
+ super(jsonConsumerSupplier);
+ this.errorConsumerSupplier = Args.notNull(errorConsumerSupplier, "Error consumer supplier");
+ this.responseValidator = responseValidator;
+ this.errorCallback = errorCallback;
+ }
+
+ @Override
+ public void informationResponse(final HttpResponse response, final HttpContext context) throws HttpException, IOException {
+ }
+
+ @Override
+ public void consumeResponse(final HttpResponse response,
+ final EntityDetails entityDetails,
+ final HttpContext context,
+ final FutureCallback<T> resultCallback) throws HttpException, IOException {
+ if (responseValidator != null) {
+ responseValidator.accept(response);
+ }
+ if (response.getCode() >= HttpStatus.SC_REDIRECTION) {
+ final AsyncEntityConsumer<E> entityConsumer = errorConsumerSupplier.get();
+ handleContent(entityConsumer, entityDetails, new CallbackContribution<E>(resultCallback) {
+
+ @Override
+ public void completed(final E result) {
+ if (errorCallback != null) {
+ errorCallback.execute(result);
+ }
+ }
+
+ });
+ } else {
+ consumeMessage(response, entityDetails, context, new CallbackContribution<T>(resultCallback) {
+
+ @Override
+ public void completed(final T result) {
+ if (resultCallback != null) {
+ resultCallback.completed(result);
+ }
+ }
+
+ });
+ }
+ }
+
+ @Override
+ public void failed(final Exception cause) {
+ super.failed(cause);
+ }
+
+}
diff --git a/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/JsonTokenEntityConsumer.java b/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/JsonTokenEntityConsumer.java
new file mode 100644
index 000000000..e91382eb1
--- /dev/null
+++ b/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/JsonTokenEntityConsumer.java
@@ -0,0 +1,71 @@
+/*
+ * ====================================================================
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * <http://www.apache.org/>.
+ *
+ */
+package org.apache.hc.core5.jackson2.http;
+
+import java.util.function.Consumer;
+
+import com.fasterxml.jackson.core.JsonFactory;
+import com.fasterxml.jackson.core.JsonTokenId;
+
+import org.apache.hc.core5.jackson2.JsonTokenConsumer;
+import org.apache.hc.core5.jackson2.JsonTokenEventHandler;
+import org.apache.hc.core5.jackson2.JsonTokenEventHandlerAdaptor;
+import org.apache.hc.core5.util.Args;
+
+/**
+ * {@link org.apache.hc.core5.http.nio.AsyncEntityConsumer} implementation that
+ * converts incoming HTTP message entity into a sequence of JSON tokens passed as
+ * events to the given {@link JsonTokenEventHandler}.
+ *
+ * @since 5.5
+ */
+public class JsonTokenEntityConsumer extends AbstractJsonEntityConsumer<Void> {
+
+ private final JsonTokenConsumer jsonTokenConsumer;
+
+ public JsonTokenEntityConsumer(final JsonFactory jsonFactory, final JsonTokenEventHandler eventHandler) {
+ super(jsonFactory);
+ this.jsonTokenConsumer = new JsonTokenEventHandlerAdaptor(Args.notNull(eventHandler, "JSON event handler"));
+ }
+
+ public JsonTokenEntityConsumer(final JsonFactory jsonFactory, final JsonTokenConsumer tokenConsumer) {
+ super(jsonFactory);
+ this.jsonTokenConsumer = Args.notNull(tokenConsumer, "JSON token consumer");
+ }
+
+
+ @Override
+ protected JsonTokenConsumer createJsonTokenConsumer(final Consumer<Void> resultConsumer) {
+ return (tokenId, jsonParser) -> {
+ jsonTokenConsumer.accept(tokenId, jsonParser);
+ if (tokenId == JsonTokenId.ID_NO_TOKEN) {
+ resultConsumer.accept(null);
+ }
+ };
+ }
+
+}
diff --git a/httpcore5/src/main/java/org/apache/hc/core5/http/Message.java b/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/JsonTokenEntityProducer.java
similarity index 53%
copy from httpcore5/src/main/java/org/apache/hc/core5/http/Message.java
copy to httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/JsonTokenEntityProducer.java
index b60d9724b..289ed1e0b 100644
--- a/httpcore5/src/main/java/org/apache/hc/core5/http/Message.java
+++ b/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/JsonTokenEntityProducer.java
@@ -24,66 +24,37 @@
* <http://www.apache.org/>.
*
*/
+package org.apache.hc.core5.jackson2.http;
-package org.apache.hc.core5.http;
+import java.io.IOException;
+import java.io.OutputStream;
-import org.apache.hc.core5.util.Args;
-
-/**
- * Generic message consisting of a message head and a message body.
- *
- * @param <H> message head type.
- * @param <B> message body type.
- *
- * @since 5.0
- */
-public final class Message<H extends MessageHeaders, B> {
+import com.fasterxml.jackson.core.JsonFactory;
+import com.fasterxml.jackson.core.JsonGenerator;
- private final H head;
- private final B body;
+import org.apache.hc.core5.jackson2.JsonConsumer;
+import org.apache.hc.core5.util.Args;
- /**
- * Constructs a new instance.
- *
- * @param head The message head.
- * @since 5.3
- */
- public Message(final H head) {
- this(head, null);
- }
+public class JsonTokenEntityProducer extends AbstractJsonEntityProducer {
- /**
- * Constructs a new instance.
- *
- * @param head The message head.
- * @param body The message body.
- */
- public Message(final H head, final B body) {
- this.head = Args.notNull(head, "Message head");
- this.body = body;
- }
+ private final JsonFactory jsonFactory;
+ private final JsonConsumer<JsonGenerator> consumer;
- /**
- * Gets the message head.
- *
- * @return the message head.
- */
- public H getHead() {
- return head;
+ public JsonTokenEntityProducer(final JsonFactory jsonFactory, final JsonConsumer<JsonGenerator> consumer) {
+ super(4096);
+ this.jsonFactory = Args.notNull(jsonFactory, "Json factory");
+ this.consumer = Args.notNull(consumer, "Consumer");
}
- /**
- * Gets the message body.
- *
- * @return the message body.
- */
- public B getBody() {
- return body;
+ @Override
+ final void generateJson(final OutputStream outputStream) throws IOException {
+ final JsonGenerator generator = jsonFactory.createGenerator(outputStream);
+ consumer.accept(generator);
+ generator.close();
}
@Override
- public String toString() {
- return "[head=" + head + ", body=" + body + ']';
+ public void failed(final Exception cause) {
}
}
diff --git a/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/NoopJsonEntityConsumer.java b/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/NoopJsonEntityConsumer.java
new file mode 100644
index 000000000..bd81d664c
--- /dev/null
+++ b/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/NoopJsonEntityConsumer.java
@@ -0,0 +1,88 @@
+/*
+ * ====================================================================
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * <http://www.apache.org/>.
+ *
+ */
+package org.apache.hc.core5.jackson2.http;
+
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.util.List;
+import java.util.concurrent.atomic.AtomicReference;
+
+import org.apache.hc.core5.concurrent.FutureCallback;
+import org.apache.hc.core5.http.EntityDetails;
+import org.apache.hc.core5.http.Header;
+import org.apache.hc.core5.http.HttpException;
+import org.apache.hc.core5.http.nio.AsyncEntityConsumer;
+import org.apache.hc.core5.http.nio.CapacityChannel;
+
+final class NoopJsonEntityConsumer<T> implements AsyncEntityConsumer<T> {
+
+ private final AtomicReference<FutureCallback<T>> resultCallbackRef;
+
+ NoopJsonEntityConsumer() {
+ resultCallbackRef = new AtomicReference<>();
+ }
+
+ @Override
+ public void streamStart(final EntityDetails entityDetails, final FutureCallback<T> resultCallback) throws HttpException, IOException {
+ resultCallbackRef.set(resultCallback);
+ }
+
+ @Override
+ public void updateCapacity(final CapacityChannel capacityChannel) throws IOException {
+ capacityChannel.update(Integer.MAX_VALUE);
+ }
+
+ @Override
+ public void consume(final ByteBuffer data) throws IOException {
+ }
+
+ @Override
+ public void streamEnd(final List<? extends Header> trailers) throws HttpException, IOException {
+ final FutureCallback<T> callback = resultCallbackRef.get();
+ if (callback != null) {
+ callback.completed(null);
+ }
+ }
+
+ @Override
+ public void failed(final Exception cause) {
+ final FutureCallback<T> resultCallback = resultCallbackRef.getAndSet(null);
+ if (resultCallback != null) {
+ resultCallback.failed(cause);
+ }
+ }
+
+ @Override
+ public T getContent() {
+ return null;
+ }
+
+ @Override
+ public void releaseResources() {
+ }
+
+}
diff --git a/httpcore5/src/main/java/org/apache/hc/core5/http/Message.java b/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/ObjectChannel.java
similarity index 52%
copy from httpcore5/src/main/java/org/apache/hc/core5/http/Message.java
copy to httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/ObjectChannel.java
index b60d9724b..8d74a0af5 100644
--- a/httpcore5/src/main/java/org/apache/hc/core5/http/Message.java
+++ b/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/ObjectChannel.java
@@ -25,65 +25,36 @@
*
*/
-package org.apache.hc.core5.http;
+package org.apache.hc.core5.jackson2.http;
-import org.apache.hc.core5.util.Args;
+import java.io.IOException;
+
+import org.apache.hc.core5.annotation.Contract;
+import org.apache.hc.core5.annotation.ThreadingBehavior;
/**
- * Generic message consisting of a message head and a message body.
- *
- * @param <H> message head type.
- * @param <B> message body type.
+ * Abstract object stream channel.
+ * <p>
+ * Implementations are expected to be thread-safe.
+ * </p>
*
- * @since 5.0
+ * @param <T> object type accepted by the channel.
+ * @since 5.5
*/
-public final class Message<H extends MessageHeaders, B> {
-
- private final H head;
- private final B body;
-
- /**
- * Constructs a new instance.
- *
- * @param head The message head.
- * @since 5.3
- */
- public Message(final H head) {
- this(head, null);
- }
+@Contract(threading = ThreadingBehavior.SAFE)
+public interface ObjectChannel<T> {
/**
- * Constructs a new instance.
+ * Writes serialized object into the underlying data stream.
*
- * @param head The message head.
- * @param body The message body.
+ * @param obj object
+ * @return The number of elements written, possibly zero
*/
- public Message(final H head, final B body) {
- this.head = Args.notNull(head, "Message head");
- this.body = body;
- }
+ int write(T obj) throws IOException;
/**
- * Gets the message head.
- *
- * @return the message head.
+ * Terminates the underlying data stream and optionally writes
+ * a closing sequence.
*/
- public H getHead() {
- return head;
- }
-
- /**
- * Gets the message body.
- *
- * @return the message body.
- */
- public B getBody() {
- return body;
- }
-
- @Override
- public String toString() {
- return "[head=" + head + ", body=" + body + ']';
- }
-
+ void endStream() throws IOException;
}
diff --git a/httpcore5/src/main/java/org/apache/hc/core5/http/Message.java b/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/ObjectProducer.java
similarity index 50%
copy from httpcore5/src/main/java/org/apache/hc/core5/http/Message.java
copy to httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/ObjectProducer.java
index b60d9724b..e7b8f6b4f 100644
--- a/httpcore5/src/main/java/org/apache/hc/core5/http/Message.java
+++ b/httpcore5-jackson2/src/main/java/org/apache/hc/core5/jackson2/http/ObjectProducer.java
@@ -25,65 +25,19 @@
*
*/
-package org.apache.hc.core5.http;
+package org.apache.hc.core5.jackson2.http;
-import org.apache.hc.core5.util.Args;
+import java.io.IOException;
/**
- * Generic message consisting of a message head and a message body.
+ * Abstract asynchronous object producer.
*
- * @param <H> message head type.
- * @param <B> message body type.
- *
- * @since 5.0
+ * @param <T> object type produced by this class.
+ * @since 5.5
*/
-public final class Message<H extends MessageHeaders, B> {
-
- private final H head;
- private final B body;
-
- /**
- * Constructs a new instance.
- *
- * @param head The message head.
- * @since 5.3
- */
- public Message(final H head) {
- this(head, null);
- }
-
- /**
- * Constructs a new instance.
- *
- * @param head The message head.
- * @param body The message body.
- */
- public Message(final H head, final B body) {
- this.head = Args.notNull(head, "Message head");
- this.body = body;
- }
-
- /**
- * Gets the message head.
- *
- * @return the message head.
- */
- public H getHead() {
- return head;
- }
-
- /**
- * Gets the message body.
- *
- * @return the message body.
- */
- public B getBody() {
- return body;
- }
+@FunctionalInterface
+public interface ObjectProducer<T> {
- @Override
- public String toString() {
- return "[head=" + head + ", body=" + body + ']';
- }
+ void produce(ObjectChannel<T> channel) throws IOException;
}
diff --git a/httpcore5-jackson2/src/test/java/org/apache/hc/core5/jackson2/JsonNodeAssemblerTest.java b/httpcore5-jackson2/src/test/java/org/apache/hc/core5/jackson2/JsonNodeAssemblerTest.java
new file mode 100644
index 000000000..c8f6222f5
--- /dev/null
+++ b/httpcore5-jackson2/src/test/java/org/apache/hc/core5/jackson2/JsonNodeAssemblerTest.java
@@ -0,0 +1,115 @@
+/*
+ * ====================================================================
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * <http://www.apache.org/>.
+ *
+ */
+package org.apache.hc.core5.jackson2;
+
+import java.io.InputStream;
+import java.net.URL;
+import java.nio.ByteBuffer;
+
+import com.fasterxml.jackson.core.JsonFactory;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.node.ArrayNode;
+import com.fasterxml.jackson.databind.node.JsonNodeFactory;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+
+import org.assertj.core.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+public class JsonNodeAssemblerTest {
+
+ @Test
+ void testJsonNodeAssembly() throws Exception {
+ final JsonFactory factory = new JsonFactory();
+ final JsonAsyncTokenizer jsonTokenizer = new JsonAsyncTokenizer(factory);
+
+ final URL resource1 = getClass().getResource("/sample1.json");
+ Assertions.assertThat(resource1).isNotNull();
+
+ final URL resource2 = getClass().getResource("/sample2.json");
+ Assertions.assertThat(resource2).isNotNull();
+
+ final JsonNodeAssembler jsonNodeAssembler1 = JsonNodeAssembler.create();
+
+ try (final InputStream inputStream = resource1.openStream()) {
+ jsonTokenizer.initialize(new JsonTokenEventHandlerAdaptor(jsonNodeAssembler1));
+ final byte[] bytebuf = new byte[1024];
+ int len;
+ while ((len = inputStream.read(bytebuf)) != -1) {
+ jsonTokenizer.consume(ByteBuffer.wrap(bytebuf, 0, len));
+ }
+ jsonTokenizer.streamEnd();
+ }
+
+ final JsonNode jsonNode1 = jsonNodeAssembler1.getResult();
+ final ObjectNode expectedObject1 = JsonNodeFactory.instance.objectNode();
+ expectedObject1.putObject("args");
+ expectedObject1.putObject("headers")
+ .put("Accept", "application/json")
+ .put("Accept-Encoding", "gzip, deflate")
+ .put("Accept-Language", "en-US,en;q=0.9")
+ .put("Connection", "close")
+ .put("Cookie", "_gauges_unique_year=1; _gauges_unique=1; _gauges_unique_hour=1; " +
+ "_gauges_unique_day=1; _gauges_unique_month=1")
+ .put("Host", "httpbin.org")
+ .put("Referer", "http://httpbin.org/")
+ .put("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) " +
+ "snap Chromium/71.0.3578.98 Chrome/71.0.3578.98 Safari/537.36");
+ expectedObject1.put("origin", "xxx.xxx.xxx.xxx");
+ expectedObject1.put("url", "http://httpbin.org/get");
+
+ Assertions.assertThat(jsonNode1).isEqualTo(expectedObject1);
+
+ final JsonNodeAssembler jsonNodeAssembler2 = JsonNodeAssembler.create();
+
+ try (final InputStream inputStream = resource2.openStream()) {
+ jsonTokenizer.initialize(new JsonTokenEventHandlerAdaptor(jsonNodeAssembler2));
+ final byte[] bytebuf = new byte[1024];
+ int len;
+ while ((len = inputStream.read(bytebuf)) != -1) {
+ jsonTokenizer.consume(ByteBuffer.wrap(bytebuf, 0, len));
+ }
+ jsonTokenizer.streamEnd();
+ }
+
+ final JsonNode jsonNode2 = jsonNodeAssembler2.getResult();
+ final ArrayNode expectedObject2 = JsonNodeFactory.instance.arrayNode();
+ expectedObject2.addArray().add(1).add(2).add(3);
+ expectedObject2.addArray().add(1.1).add(2.2).add(3.3);
+ expectedObject2.addArray()
+ .add(JsonNodeFactory.instance.objectNode().put("name1", "value1"))
+ .add(JsonNodeFactory.instance.objectNode().put("name2", "value2"))
+ .add(JsonNodeFactory.instance.objectNode().put("name3", "value3"));
+ expectedObject2.addArray()
+ .add(2)
+ .add(2.2)
+ .add(JsonNodeFactory.instance.objectNode().put("name2", "value2"));
+ expectedObject2.addArray().add(JsonNodeFactory.instance.objectNode().put("long", 2153599188L));
+
+ Assertions.assertThat(jsonNode2).isEqualTo(expectedObject2);
+ }
+
+}
diff --git a/httpcore5-jackson2/src/test/java/org/apache/hc/core5/jackson2/JsonTokenBufferAssemblerTest.java b/httpcore5-jackson2/src/test/java/org/apache/hc/core5/jackson2/JsonTokenBufferAssemblerTest.java
new file mode 100644
index 000000000..d0a6a59ad
--- /dev/null
+++ b/httpcore5-jackson2/src/test/java/org/apache/hc/core5/jackson2/JsonTokenBufferAssemblerTest.java
@@ -0,0 +1,330 @@
+/*
+ * ====================================================================
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * <http://www.apache.org/>.
+ *
+ */
+package org.apache.hc.core5.jackson2;
+
+import java.io.InputStream;
+import java.net.URL;
+import java.nio.ByteBuffer;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicReference;
+
+import com.fasterxml.jackson.core.JsonFactory;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.JsonNodeFactory;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import com.fasterxml.jackson.databind.util.TokenBuffer;
+
+import org.assertj.core.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+public class JsonTokenBufferAssemblerTest {
+
+ @Test
+ void testTokenBufferAssembly() throws Exception {
+ final JsonFactory factory = new JsonFactory();
+ final ObjectMapper objectMapper = new ObjectMapper(factory);
+ final JsonAsyncTokenizer jsonTokenizer = new JsonAsyncTokenizer(factory);
+
+ final URL resource = getClass().getResource("/sample1.json");
+ Assertions.assertThat(resource).isNotNull();
+
+ final AtomicReference<TokenBuffer> tokenBufferRef = new AtomicReference<>(null);
+ try (final InputStream inputStream = resource.openStream()) {
+ jsonTokenizer.initialize(new TokenBufferAssembler(tokenBufferRef::set));
+ final byte[] bytebuf = new byte[1024];
+ int len;
+ while ((len = inputStream.read(bytebuf)) != -1) {
+ jsonTokenizer.consume(ByteBuffer.wrap(bytebuf, 0, len));
+ }
+ jsonTokenizer.streamEnd();
+ }
+
+ final TokenBuffer tokenBuffer = tokenBufferRef.get();
+ Assertions.assertThat(tokenBuffer).isNotNull();
+ final JsonNode jsonNode = objectMapper.readTree(tokenBuffer.asParserOnFirstToken());
+
+ final ObjectNode expectedObject = JsonNodeFactory.instance.objectNode();
+ expectedObject.putObject("args");
+ expectedObject.putObject("headers")
+ .put("Accept", "application/json")
+ .put("Accept-Encoding", "gzip, deflate")
+ .put("Accept-Language", "en-US,en;q=0.9")
+ .put("Connection", "close")
+ .put("Cookie", "_gauges_unique_year=1; _gauges_unique=1; _gauges_unique_hour=1; " +
+ "_gauges_unique_day=1; _gauges_unique_month=1")
+ .put("Host", "httpbin.org")
+ .put("Referer", "http://httpbin.org/")
+ .put("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) " +
+ "snap Chromium/71.0.3578.98 Chrome/71.0.3578.98 Safari/537.36");
+ expectedObject.put("origin", "xxx.xxx.xxx.xxx");
+ expectedObject.put("url", "http://httpbin.org/get");
+
+ Assertions.assertThat(jsonNode).isEqualTo(expectedObject);
+ }
+
+ @Test
+ void testTokenBufferSequenceAssembly() throws Exception {
+ final JsonFactory factory = new JsonFactory();
+ final ObjectMapper objectMapper = new ObjectMapper(factory);
+ final JsonAsyncTokenizer jsonTokenizer = new JsonAsyncTokenizer(factory);
+
+ final URL resource = getClass().getResource("/sample3.json");
+ Assertions.assertThat(resource).isNotNull();
+
+ final AtomicInteger started = new AtomicInteger(0);
+ final List<TokenBuffer> tokenBufferList = new ArrayList<>();
+ final AtomicInteger ended = new AtomicInteger(0);
+ try (final InputStream inputStream = resource.openStream()) {
+ jsonTokenizer.initialize(new TokenBufferAssembler(new JsonResultSink<TokenBuffer>() {
+
+ @Override
+ public void begin(final int sizeHint) {
+ started.incrementAndGet();
+ }
+
+ @Override
+ public void accept(final TokenBuffer tokenBuffer) {
+ tokenBufferList.add(tokenBuffer);
+ }
+
+ @Override
+ public void end() {
+ ended.incrementAndGet();
+ }
+
+ }));
+ final byte[] bytebuf = new byte[1024];
+ int len;
+ while ((len = inputStream.read(bytebuf)) != -1) {
+ jsonTokenizer.consume(ByteBuffer.wrap(bytebuf, 0, len));
+ }
+ jsonTokenizer.streamEnd();
+ }
+
+ Assertions.assertThat(tokenBufferList).hasSize(3);
+ Assertions.assertThat(started.get()).isEqualTo(1);
+ Assertions.assertThat(ended.get()).isEqualTo(1);
+
+ final TokenBuffer tokenBuffer1 = tokenBufferList.get(0);
+ Assertions.assertThat(tokenBuffer1).isNotNull();
+ final JsonNode jsonNode1 = objectMapper.readTree(tokenBuffer1.asParserOnFirstToken());
+
+ final ObjectNode expectedObject1 = JsonNodeFactory.instance.objectNode();
+ expectedObject1.put("url", "http://httpbin.org/stream/3");
+ expectedObject1.putObject("args");
+ expectedObject1.putObject("headers")
+ .put("Host", "httpbin.org")
+ .put("Connection", "close")
+ .put("Referer", "http://httpbin.org/")
+ .put("Accept", "application/json")
+ .put("Accept-Encoding", "gzip, deflate")
+ .put("Accept-Language", "en-US,en;q=0.9")
+ .put("Cookie", "_gauges_unique_year=1; _gauges_unique=1; _gauges_unique_month=1; _gauges_unique_day=1; " +
+ "_gauges_unique_hour=1")
+ .put("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) " +
+ "snap Chromium/71.0.3578.98 Chrome/71.0.3578.98 Safari/537.36");
+ expectedObject1.put("origin", "xxx.xxx.xxx.xxx");
+ expectedObject1.put("id", 0);
+
+ Assertions.assertThat(jsonNode1).isEqualTo(expectedObject1);
+
+ final TokenBuffer tokenBuffer2 = tokenBufferList.get(1);
+ Assertions.assertThat(tokenBuffer2).isNotNull();
+ final JsonNode jsonNode2 = objectMapper.readTree(tokenBuffer2.asParserOnFirstToken());
+
+ final ObjectNode expectedObject2 = JsonNodeFactory.instance.objectNode();
+ expectedObject2.put("url", "http://httpbin.org/stream/3");
+ expectedObject2.putObject("args");
+ expectedObject2.putObject("headers")
+ .put("Host", "httpbin.org")
+ .put("Connection", "close")
+ .put("Referer", "http://httpbin.org/")
+ .put("Accept", "application/json")
+ .put("Accept-Encoding", "gzip, deflate")
+ .put("Accept-Language", "en-US,en;q=0.9")
+ .put("Cookie", "_gauges_unique_year=1; _gauges_unique=1; _gauges_unique_month=1; _gauges_unique_day=1; " +
+ "_gauges_unique_hour=1")
+ .put("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) " +
+ "snap Chromium/71.0.3578.98 Chrome/71.0.3578.98 Safari/537.36");
+ expectedObject2.put("origin", "xxx.xxx.xxx.xxx");
+ expectedObject2.put("id", 1);
+
+ Assertions.assertThat(jsonNode2).isEqualTo(expectedObject2);
+
+ final TokenBuffer tokenBuffer3 = tokenBufferList.get(2);
+ Assertions.assertThat(tokenBuffer3).isNotNull();
+ final JsonNode jsonNode3 = objectMapper.readTree(tokenBuffer3.asParserOnFirstToken());
+
+ final ObjectNode expectedObject3 = JsonNodeFactory.instance.objectNode();
+ expectedObject3.put("url", "http://httpbin.org/stream/3");
+ expectedObject3.putObject("args");
+ expectedObject3.putObject("headers")
+ .put("Host", "httpbin.org")
+ .put("Connection", "close")
+ .put("Referer", "http://httpbin.org/")
+ .put("Accept", "application/json")
+ .put("Accept-Encoding", "gzip, deflate")
+ .put("Accept-Language", "en-US,en;q=0.9")
+ .put("Cookie", "_gauges_unique_year=1; _gauges_unique=1; _gauges_unique_month=1; _gauges_unique_day=1; " +
+ "_gauges_unique_hour=1")
+ .put("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) " +
+ "snap Chromium/71.0.3578.98 Chrome/71.0.3578.98 Safari/537.36");
+ expectedObject3.put("origin", "xxx.xxx.xxx.xxx");
+ expectedObject3.put("id", 2);
+
+ Assertions.assertThat(jsonNode3).isEqualTo(expectedObject3);
+ }
+
+ @Test
+ void testTokenBufferAssemblyNoContent() throws Exception {
+ final JsonFactory factory = new JsonFactory();
+ final JsonAsyncTokenizer jsonTokenizer = new JsonAsyncTokenizer(factory);
+
+ final AtomicReference<TokenBuffer> tokenBufferRef = new AtomicReference<>(null);
+ jsonTokenizer.initialize(new TokenBufferAssembler(tokenBufferRef::set));
+ jsonTokenizer.streamEnd();
+
+ Assertions.assertThat(tokenBufferRef.get()).isNull();
+ }
+
+ @Test
+ void testTokenBufferArrayAssembly() throws Exception {
+ final JsonFactory factory = new JsonFactory();
+ final ObjectMapper objectMapper = new ObjectMapper(factory);
+ final JsonAsyncTokenizer jsonTokenizer = new JsonAsyncTokenizer(factory);
+
+ final URL resource = getClass().getResource("/sample6.json");
+ Assertions.assertThat(resource).isNotNull();
+
+ final AtomicInteger started = new AtomicInteger(0);
+ final List<TokenBuffer> tokenBufferList = new ArrayList<>();
+ final AtomicInteger ended = new AtomicInteger(0);
+ try (final InputStream inputStream = resource.openStream()) {
+ jsonTokenizer.initialize(new TopLevelArrayTokenFilter(new TokenBufferAssembler(new JsonResultSink<TokenBuffer>() {
+
+ @Override
+ public void begin(final int sizeHint) {
+ started.incrementAndGet();
+ }
+
+ @Override
+ public void accept(final TokenBuffer tokenBuffer) {
+ tokenBufferList.add(tokenBuffer);
+ }
+
+ @Override
+ public void end() {
+ ended.incrementAndGet();
+ }
+
+ })));
+ final byte[] bytebuf = new byte[1024];
+ int len;
+ while ((len = inputStream.read(bytebuf)) != -1) {
+ jsonTokenizer.consume(ByteBuffer.wrap(bytebuf, 0, len));
+ }
+ jsonTokenizer.streamEnd();
+ }
+
+ Assertions.assertThat(tokenBufferList).hasSize(3);
+ Assertions.assertThat(started.get()).isEqualTo(1);
+ Assertions.assertThat(ended.get()).isEqualTo(1);
+
+ final TokenBuffer tokenBuffer1 = tokenBufferList.get(0);
+ Assertions.assertThat(tokenBuffer1).isNotNull();
+ final JsonNode jsonNode1 = objectMapper.readTree(tokenBuffer1.asParserOnFirstToken());
+
+ final ObjectNode expectedObject1 = JsonNodeFactory.instance.objectNode();
+ expectedObject1.put("url", "http://httpbin.org/stream/3");
+ expectedObject1.putObject("args");
+ expectedObject1.putObject("headers")
+ .put("Host", "httpbin.org")
+ .put("Connection", "close")
+ .put("Referer", "http://httpbin.org/")
+ .put("Accept", "application/json")
+ .put("Accept-Encoding", "gzip, deflate")
+ .put("Accept-Language", "en-US,en;q=0.9")
+ .put("Cookie", "_gauges_unique_year=1; _gauges_unique=1; _gauges_unique_month=1; _gauges_unique_day=1; " +
+ "_gauges_unique_hour=1")
+ .put("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) " +
+ "snap Chromium/71.0.3578.98 Chrome/71.0.3578.98 Safari/537.36");
+ expectedObject1.put("origin", "xxx.xxx.xxx.xxx");
+ expectedObject1.put("id", 0);
+
+ Assertions.assertThat(jsonNode1).isEqualTo(expectedObject1);
+
+ final TokenBuffer tokenBuffer2 = tokenBufferList.get(1);
+ Assertions.assertThat(tokenBuffer2).isNotNull();
+ final JsonNode jsonNode2 = objectMapper.readTree(tokenBuffer2.asParserOnFirstToken());
+
+ final ObjectNode expectedObject2 = JsonNodeFactory.instance.objectNode();
+ expectedObject2.put("url", "http://httpbin.org/stream/3");
+ expectedObject2.putObject("args");
+ expectedObject2.putObject("headers")
+ .put("Host", "httpbin.org")
+ .put("Connection", "close")
+ .put("Referer", "http://httpbin.org/")
+ .put("Accept", "application/json")
+ .put("Accept-Encoding", "gzip, deflate")
+ .put("Accept-Language", "en-US,en;q=0.9")
+ .put("Cookie", "_gauges_unique_year=1; _gauges_unique=1; _gauges_unique_month=1; _gauges_unique_day=1; " +
+ "_gauges_unique_hour=1")
+ .put("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) " +
+ "snap Chromium/71.0.3578.98 Chrome/71.0.3578.98 Safari/537.36");
+ expectedObject2.put("origin", "xxx.xxx.xxx.xxx");
+ expectedObject2.put("id", 1);
+
+ Assertions.assertThat(jsonNode2).isEqualTo(expectedObject2);
+
+ final TokenBuffer tokenBuffer3 = tokenBufferList.get(2);
+ Assertions.assertThat(tokenBuffer3).isNotNull();
+ final JsonNode jsonNode3 = objectMapper.readTree(tokenBuffer3.asParserOnFirstToken());
+
+ final ObjectNode expectedObject3 = JsonNodeFactory.instance.objectNode();
+ expectedObject3.put("url", "http://httpbin.org/stream/3");
+ expectedObject3.putObject("args");
+ expectedObject3.putObject("headers")
+ .put("Host", "httpbin.org")
+ .put("Connection", "close")
+ .put("Referer", "http://httpbin.org/")
+ .put("Accept", "application/json")
+ .put("Accept-Encoding", "gzip, deflate")
+ .put("Accept-Language", "en-US,en;q=0.9")
+ .put("Cookie", "_gauges_unique_year=1; _gauges_unique=1; _gauges_unique_month=1; _gauges_unique_day=1; " +
+ "_gauges_unique_hour=1")
+ .put("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) " +
+ "snap Chromium/71.0.3578.98 Chrome/71.0.3578.98 Safari/537.36");
+ expectedObject3.put("origin", "xxx.xxx.xxx.xxx");
+ expectedObject3.put("id", 2);
+
+ Assertions.assertThat(jsonNode3).isEqualTo(expectedObject3);
+ }
+
+}
diff --git a/httpcore5-jackson2/src/test/java/org/apache/hc/core5/jackson2/JsonTokenizerTest.java b/httpcore5-jackson2/src/test/java/org/apache/hc/core5/jackson2/JsonTokenizerTest.java
new file mode 100644
index 000000000..ac4a7ee24
--- /dev/null
+++ b/httpcore5-jackson2/src/test/java/org/apache/hc/core5/jackson2/JsonTokenizerTest.java
@@ -0,0 +1,612 @@
+/*
+ * ====================================================================
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * <http://www.apache.org/>.
+ *
+ */
+package org.apache.hc.core5.jackson2;
+
+import java.io.InputStream;
+import java.net.URL;
+import java.nio.ByteBuffer;
+import java.util.ArrayList;
+import java.util.List;
+
+import com.fasterxml.jackson.core.JsonFactory;
+import com.fasterxml.jackson.core.JsonTokenId;
+
+import org.assertj.core.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+public class JsonTokenizerTest {
+
+ @Test
+ void testTokenizer() throws Exception {
+ final JsonFactory factory = new JsonFactory();
+ final JsonTokenizer jsonTokenizer = new JsonTokenizer(factory);
+
+ final URL resource1 = getClass().getResource("/sample1.json");
+ Assertions.assertThat(resource1).isNotNull();
+
+ final List<Integer> tokens1 = new ArrayList<>();
+ try (final InputStream inputStream = resource1.openStream()) {
+ jsonTokenizer.tokenize(inputStream, (tokenId, jsonParser) -> tokens1.add(tokenId));
+ }
+
+ Assertions.assertThat(tokens1).containsExactly(
+ JsonTokenId.ID_START_OBJECT,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_START_OBJECT,
+ JsonTokenId.ID_END_OBJECT,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_START_OBJECT,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_END_OBJECT,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_END_OBJECT,
+ JsonTokenId.ID_NO_TOKEN
+ );
+
+ final URL resource2 = getClass().getResource("/sample2.json");
+ Assertions.assertThat(resource2).isNotNull();
+
+ final List<Integer> tokens2 = new ArrayList<>();
+ try (final InputStream inputStream = resource2.openStream()) {
+ jsonTokenizer.tokenize(inputStream, (tokenId, jsonParser) -> tokens2.add(tokenId));
+ }
+
+ Assertions.assertThat(tokens2).containsExactly(
+ JsonTokenId.ID_START_ARRAY,
+ JsonTokenId.ID_START_ARRAY,
+ JsonTokenId.ID_NUMBER_INT,
+ JsonTokenId.ID_NUMBER_INT,
+ JsonTokenId.ID_NUMBER_INT,
+ JsonTokenId.ID_END_ARRAY,
+ JsonTokenId.ID_START_ARRAY,
+ JsonTokenId.ID_NUMBER_FLOAT,
+ JsonTokenId.ID_NUMBER_FLOAT,
+ JsonTokenId.ID_NUMBER_FLOAT,
+ JsonTokenId.ID_END_ARRAY,
+ JsonTokenId.ID_START_ARRAY,
+ JsonTokenId.ID_START_OBJECT,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_END_OBJECT,
+ JsonTokenId.ID_START_OBJECT,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_END_OBJECT,
+ JsonTokenId.ID_START_OBJECT,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_END_OBJECT,
+ JsonTokenId.ID_END_ARRAY,
+ JsonTokenId.ID_START_ARRAY,
+ JsonTokenId.ID_NUMBER_INT,
+ JsonTokenId.ID_NUMBER_FLOAT,
+ JsonTokenId.ID_START_OBJECT,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_END_OBJECT,
+ JsonTokenId.ID_END_ARRAY,
+ JsonTokenId.ID_START_ARRAY,
+ JsonTokenId.ID_START_OBJECT,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_NUMBER_INT,
+ JsonTokenId.ID_END_OBJECT,
+ JsonTokenId.ID_END_ARRAY,
+ JsonTokenId.ID_END_ARRAY,
+ JsonTokenId.ID_NO_TOKEN
+ );
+
+ final URL resource3 = getClass().getResource("/sample3.json");
+ Assertions.assertThat(resource3).isNotNull();
+
+ final List<Integer> tokens3 = new ArrayList<>();
+ try (final InputStream inputStream = resource3.openStream()) {
+ jsonTokenizer.tokenize(inputStream, (tokenId, jsonParser) -> tokens3.add(tokenId));
+ }
+
+ Assertions.assertThat(tokens3).containsExactly(
+ JsonTokenId.ID_START_OBJECT,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_START_OBJECT,
+ JsonTokenId.ID_END_OBJECT,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_START_OBJECT,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_END_OBJECT,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_NUMBER_INT,
+ JsonTokenId.ID_END_OBJECT,
+ JsonTokenId.ID_START_OBJECT,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_START_OBJECT,
+ JsonTokenId.ID_END_OBJECT,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_START_OBJECT,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_END_OBJECT,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_NUMBER_INT,
+ JsonTokenId.ID_END_OBJECT,
+ JsonTokenId.ID_START_OBJECT,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_START_OBJECT,
+ JsonTokenId.ID_END_OBJECT,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_START_OBJECT,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_END_OBJECT,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_NUMBER_INT,
+ JsonTokenId.ID_END_OBJECT,
+ JsonTokenId.ID_NO_TOKEN
+ );
+
+ final URL resource6 = getClass().getResource("/sample6.json");
+ Assertions.assertThat(resource6).isNotNull();
+
+ final List<Integer> tokens6 = new ArrayList<>();
+ try (final InputStream inputStream = resource6.openStream()) {
+ jsonTokenizer.tokenize(inputStream, (tokenId, jsonParser) -> tokens6.add(tokenId));
+ }
+
+ Assertions.assertThat(tokens6).containsExactly(
+ JsonTokenId.ID_START_ARRAY,
+ JsonTokenId.ID_START_OBJECT,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_START_OBJECT,
+ JsonTokenId.ID_END_OBJECT,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_START_OBJECT,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_END_OBJECT,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_NUMBER_INT,
+ JsonTokenId.ID_END_OBJECT,
+ JsonTokenId.ID_START_OBJECT,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_START_OBJECT,
+ JsonTokenId.ID_END_OBJECT,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_START_OBJECT,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_END_OBJECT,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_NUMBER_INT,
+ JsonTokenId.ID_END_OBJECT,
+ JsonTokenId.ID_START_OBJECT,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_START_OBJECT,
+ JsonTokenId.ID_END_OBJECT,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_START_OBJECT,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_END_OBJECT,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_NUMBER_INT,
+ JsonTokenId.ID_END_OBJECT,
+ JsonTokenId.ID_END_ARRAY,
+ JsonTokenId.ID_NO_TOKEN
+ );
+ }
+
+ @Test
+ void testAsyncTokenizer() throws Exception {
+ final JsonFactory factory = new JsonFactory();
+ final JsonAsyncTokenizer jsonTokenizer = new JsonAsyncTokenizer(factory);
+
+ final URL resource1 = getClass().getResource("/sample1.json");
+ Assertions.assertThat(resource1).isNotNull();
+
+ final URL resource2 = getClass().getResource("/sample2.json");
+ Assertions.assertThat(resource2).isNotNull();
+
+ final URL resource3 = getClass().getResource("/sample3.json");
+ Assertions.assertThat(resource3).isNotNull();
+
+ for (final int bufSize : new int[]{2048, 1024, 256, 32, 16, 8}) {
+ final List<Integer> tokens1 = new ArrayList<>();
+ try (final InputStream inputStream = resource1.openStream()) {
+ jsonTokenizer.initialize((tokenId, jsonParser) -> tokens1.add(tokenId));
+ final byte[] buf = new byte[bufSize];
+ int len;
+ while ((len = inputStream.read(buf)) != -1) {
+ jsonTokenizer.consume(ByteBuffer.wrap(buf, 0, len));
+ }
+ jsonTokenizer.streamEnd();
+ }
+
+ Assertions.assertThat(tokens1).containsExactly(
+ JsonTokenId.ID_START_OBJECT,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_START_OBJECT,
+ JsonTokenId.ID_END_OBJECT,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_START_OBJECT,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_END_OBJECT,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_END_OBJECT,
+ JsonTokenId.ID_NO_TOKEN
+ );
+
+ final List<Integer> tokens2 = new ArrayList<>();
+ try (final InputStream inputStream = resource2.openStream()) {
+ jsonTokenizer.initialize((tokenId, jsonParser) -> tokens2.add(tokenId));
+ final byte[] buf = new byte[bufSize];
+ int len;
+ while ((len = inputStream.read(buf)) != -1) {
+ jsonTokenizer.consume(ByteBuffer.wrap(buf, 0, len));
+ }
+ jsonTokenizer.streamEnd();
+ }
+
+ Assertions.assertThat(tokens2).containsExactly(
+ JsonTokenId.ID_START_ARRAY,
+ JsonTokenId.ID_START_ARRAY,
+ JsonTokenId.ID_NUMBER_INT,
+ JsonTokenId.ID_NUMBER_INT,
+ JsonTokenId.ID_NUMBER_INT,
+ JsonTokenId.ID_END_ARRAY,
+ JsonTokenId.ID_START_ARRAY,
+ JsonTokenId.ID_NUMBER_FLOAT,
+ JsonTokenId.ID_NUMBER_FLOAT,
+ JsonTokenId.ID_NUMBER_FLOAT,
+ JsonTokenId.ID_END_ARRAY,
+ JsonTokenId.ID_START_ARRAY,
+ JsonTokenId.ID_START_OBJECT,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_END_OBJECT,
+ JsonTokenId.ID_START_OBJECT,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_END_OBJECT,
+ JsonTokenId.ID_START_OBJECT,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_END_OBJECT,
+ JsonTokenId.ID_END_ARRAY,
+ JsonTokenId.ID_START_ARRAY,
+ JsonTokenId.ID_NUMBER_INT,
+ JsonTokenId.ID_NUMBER_FLOAT,
+ JsonTokenId.ID_START_OBJECT,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_END_OBJECT,
+ JsonTokenId.ID_END_ARRAY,
+ JsonTokenId.ID_START_ARRAY,
+ JsonTokenId.ID_START_OBJECT,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_NUMBER_INT,
+ JsonTokenId.ID_END_OBJECT,
+ JsonTokenId.ID_END_ARRAY,
+ JsonTokenId.ID_END_ARRAY,
+ JsonTokenId.ID_NO_TOKEN
+ );
+
+ final List<Integer> tokens3 = new ArrayList<>();
+ try (final InputStream inputStream = resource3.openStream()) {
+ jsonTokenizer.initialize((tokenId, jsonParser) -> tokens3.add(tokenId));
+ final byte[] buf = new byte[bufSize];
+ int len;
+ while ((len = inputStream.read(buf)) != -1) {
+ jsonTokenizer.consume(ByteBuffer.wrap(buf, 0, len));
+ }
+ jsonTokenizer.streamEnd();
+ }
+
+ Assertions.assertThat(tokens3).containsExactly(
+ JsonTokenId.ID_START_OBJECT,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_START_OBJECT,
+ JsonTokenId.ID_END_OBJECT,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_START_OBJECT,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_END_OBJECT,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_NUMBER_INT,
+ JsonTokenId.ID_END_OBJECT,
+ JsonTokenId.ID_START_OBJECT,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_START_OBJECT,
+ JsonTokenId.ID_END_OBJECT,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_START_OBJECT,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_END_OBJECT,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_NUMBER_INT,
+ JsonTokenId.ID_END_OBJECT,
+ JsonTokenId.ID_START_OBJECT,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_START_OBJECT,
+ JsonTokenId.ID_END_OBJECT,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_START_OBJECT,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_END_OBJECT,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_NUMBER_INT,
+ JsonTokenId.ID_END_OBJECT,
+ JsonTokenId.ID_NO_TOKEN
+ );
+ }
+ }
+
+ @Test
+ void testConsumePartial() throws Exception {
+ final JsonFactory factory = new JsonFactory();
+ final JsonAsyncTokenizer jsonTokenizer = new JsonAsyncTokenizer(factory);
+
+ final ByteBuffer b1 = ByteBuffer.wrap(new byte[]{0, 0, 0, '{', '"', 'n', 'a', 'm', 0, 0, 0}, 3, 5);
+ final ByteBuffer b2 = ByteBuffer.wrap(new byte[]{0, 0, 'e', '"', ' ', ' ', ':', ' ', 0}, 2, 6);
+ final ByteBuffer b3 = ByteBuffer.wrap(new byte[]{0, 0, 0, 0, '"', 'v', 'a', 'l', 'u', 'e', '"', ' ', ' ', '}'}, 4, 10);
+
+ final List<Integer> tokens1 = new ArrayList<>();
+ jsonTokenizer.initialize((tokenId, jsonParser) -> tokens1.add(tokenId));
+
+ jsonTokenizer.consume(b1);
+ jsonTokenizer.consume(b2);
+ jsonTokenizer.consume(b3);
+ jsonTokenizer.streamEnd();
+
+ Assertions.assertThat(tokens1).containsExactly(
+ JsonTokenId.ID_START_OBJECT,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_END_OBJECT,
+ JsonTokenId.ID_NO_TOKEN
+ );
+
+ final List<Integer> tokens2 = new ArrayList<>();
+ jsonTokenizer.initialize((tokenId, jsonParser) -> tokens2.add(tokenId));
+
+ final ByteBuffer b4 = ByteBuffer.wrap(new byte[]{0, 0, 0, '{', '"', 'n', 'a', 'm', 0, 0, 0}, 3, 5).slice();
+ final ByteBuffer b5 = ByteBuffer.wrap(new byte[]{0, 0, 'e', '"', ' ', ' ', ':', ' ', 0}, 2, 6).slice();
+ final ByteBuffer b6 = ByteBuffer.wrap(new byte[]{0, 0, 0, 0, '"', 'v', 'a', 'l', 'u', 'e', '"', ' ', ' ', '}'}, 4, 10).slice();
+ jsonTokenizer.consume(b4);
+ jsonTokenizer.consume(b5);
+ jsonTokenizer.consume(b6);
+ jsonTokenizer.streamEnd();
+
+ Assertions.assertThat(tokens2).containsExactly(
+ JsonTokenId.ID_START_OBJECT,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_END_OBJECT,
+ JsonTokenId.ID_NO_TOKEN
+ );
+ }
+
+}
diff --git a/httpcore5-jackson2/src/test/java/org/apache/hc/core5/jackson2/bulk/JsonBulkArrayReaderTest.java b/httpcore5-jackson2/src/test/java/org/apache/hc/core5/jackson2/bulk/JsonBulkArrayReaderTest.java
new file mode 100644
index 000000000..690ac18ad
--- /dev/null
+++ b/httpcore5-jackson2/src/test/java/org/apache/hc/core5/jackson2/bulk/JsonBulkArrayReaderTest.java
@@ -0,0 +1,127 @@
+/*
+ * ====================================================================
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * <http://www.apache.org/>.
+ *
+ */
+package org.apache.hc.core5.jackson2.bulk;
+
+import java.io.InputStream;
+import java.net.URI;
+import java.net.URL;
+import java.nio.ByteBuffer;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+
+import com.fasterxml.jackson.core.JsonFactory;
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+import org.apache.hc.core5.http.message.BasicHeader;
+import org.apache.hc.core5.jackson2.http.RequestData;
+import org.assertj.core.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+public class JsonBulkArrayReaderTest {
+
+ @Test
+ void testJsonArrayReading() throws Exception {
+ final JsonFactory factory = new JsonFactory();
+ final ObjectMapper objectMapper = new ObjectMapper(factory);
+
+ final URL resource = getClass().getResource("/sample6.json");
+ Assertions.assertThat(resource).isNotNull();
+
+ final List<RequestData> jsonDataList = new ArrayList<>();
+ final JsonBulkArrayReader bulkArrayReader = new JsonBulkArrayReader(objectMapper);
+ bulkArrayReader.initialize(new TypeReference<RequestData>() {
+ }, jsonDataList::add);
+ try (final InputStream inputStream = resource.openStream()) {
+ int l;
+ final byte[] tmp = new byte[4096];
+ while ((l = inputStream.read(tmp)) != -1) {
+ bulkArrayReader.consume(ByteBuffer.wrap(tmp, 0, l));
+ }
+ bulkArrayReader.streamEnd();
+ }
+
+ final RequestData expectedObject1 = new RequestData();
+ expectedObject1.setId(0);
+ expectedObject1.setUrl(URI.create("http://httpbin.org/stream/3"));
+ expectedObject1.setArgs(new HashMap<>());
+ expectedObject1.generateHeaders(
+ new BasicHeader("Host", "httpbin.org"),
+ new BasicHeader("Connection", "close"),
+ new BasicHeader("Referer", "http://httpbin.org/"),
+ new BasicHeader("Accept", "application/json"),
+ new BasicHeader("Accept-Encoding", "gzip, deflate"),
+ new BasicHeader("Accept-Language", "en-US,en;q=0.9"),
+ new BasicHeader("Cookie", "_gauges_unique_year=1; _gauges_unique=1; _gauges_unique_month=1; " +
+ "_gauges_unique_day=1; _gauges_unique_hour=1"),
+ new BasicHeader("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) " +
+ "snap Chromium/71.0.3578.98 Chrome/71.0.3578.98 Safari/537.36"));
+ expectedObject1.setOrigin("xxx.xxx.xxx.xxx");
+
+ Assertions.assertThat(jsonDataList.get(0)).usingRecursiveComparison().isEqualTo(expectedObject1);
+
+ final RequestData expectedObject2 = new RequestData();
+ expectedObject2.setId(1);
+ expectedObject2.setUrl(URI.create("http://httpbin.org/stream/3"));
+ expectedObject2.setArgs(new HashMap<>());
+ expectedObject2.generateHeaders(
+ new BasicHeader("Host", "httpbin.org"),
+ new BasicHeader("Connection", "close"),
+ new BasicHeader("Referer", "http://httpbin.org/"),
+ new BasicHeader("Accept", "application/json"),
+ new BasicHeader("Accept-Encoding", "gzip, deflate"),
+ new BasicHeader("Accept-Language", "en-US,en;q=0.9"),
+ new BasicHeader("Cookie", "_gauges_unique_year=1; _gauges_unique=1; _gauges_unique_month=1; " +
+ "_gauges_unique_day=1; _gauges_unique_hour=1"),
+ new BasicHeader("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) " +
+ "snap Chromium/71.0.3578.98 Chrome/71.0.3578.98 Safari/537.36"));
+ expectedObject2.setOrigin("xxx.xxx.xxx.xxx");
+
+ Assertions.assertThat(jsonDataList.get(1)).usingRecursiveComparison().isEqualTo(expectedObject2);
+
+ final RequestData expectedObject3 = new RequestData();
+ expectedObject3.setId(2);
+ expectedObject3.setUrl(URI.create("http://httpbin.org/stream/3"));
+ expectedObject3.setArgs(new HashMap<>());
+ expectedObject3.generateHeaders(
+ new BasicHeader("Host", "httpbin.org"),
+ new BasicHeader("Connection", "close"),
+ new BasicHeader("Referer", "http://httpbin.org/"),
+ new BasicHeader("Accept", "application/json"),
+ new BasicHeader("Accept-Encoding", "gzip, deflate"),
+ new BasicHeader("Accept-Language", "en-US,en;q=0.9"),
+ new BasicHeader("Cookie", "_gauges_unique_year=1; _gauges_unique=1; _gauges_unique_month=1; " +
+ "_gauges_unique_day=1; _gauges_unique_hour=1"),
+ new BasicHeader("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) " +
+ "snap Chromium/71.0.3578.98 Chrome/71.0.3578.98 Safari/537.36"));
+ expectedObject3.setOrigin("xxx.xxx.xxx.xxx");
+
+ Assertions.assertThat(jsonDataList.get(2)).usingRecursiveComparison().isEqualTo(expectedObject3);
+ }
+
+}
diff --git a/httpcore5/src/main/java/org/apache/hc/core5/http/Message.java b/httpcore5-jackson2/src/test/java/org/apache/hc/core5/jackson2/http/BasicDataStreamChannel.java
similarity index 52%
copy from httpcore5/src/main/java/org/apache/hc/core5/http/Message.java
copy to httpcore5-jackson2/src/test/java/org/apache/hc/core5/jackson2/http/BasicDataStreamChannel.java
index b60d9724b..bde2e4a0c 100644
--- a/httpcore5/src/main/java/org/apache/hc/core5/http/Message.java
+++ b/httpcore5-jackson2/src/test/java/org/apache/hc/core5/jackson2/http/BasicDataStreamChannel.java
@@ -24,66 +24,43 @@
* <http://www.apache.org/>.
*
*/
+package org.apache.hc.core5.jackson2.http;
-package org.apache.hc.core5.http;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.nio.channels.WritableByteChannel;
+import java.util.List;
-import org.apache.hc.core5.util.Args;
+import org.apache.hc.core5.http.Header;
+import org.apache.hc.core5.http.nio.DataStreamChannel;
-/**
- * Generic message consisting of a message head and a message body.
- *
- * @param <H> message head type.
- * @param <B> message body type.
- *
- * @since 5.0
- */
-public final class Message<H extends MessageHeaders, B> {
+public class BasicDataStreamChannel implements DataStreamChannel {
- private final H head;
- private final B body;
+ private final WritableByteChannel byteChannel;
- /**
- * Constructs a new instance.
- *
- * @param head The message head.
- * @since 5.3
- */
- public Message(final H head) {
- this(head, null);
+ public BasicDataStreamChannel(final WritableByteChannel byteChannel) {
+ this.byteChannel = byteChannel;
}
- /**
- * Constructs a new instance.
- *
- * @param head The message head.
- * @param body The message body.
- */
- public Message(final H head, final B body) {
- this.head = Args.notNull(head, "Message head");
- this.body = body;
+ @Override
+ public void requestOutput() {
}
- /**
- * Gets the message head.
- *
- * @return the message head.
- */
- public H getHead() {
- return head;
+ @Override
+ public int write(final ByteBuffer src) throws IOException {
+ return byteChannel.write(src);
}
- /**
- * Gets the message body.
- *
- * @return the message body.
- */
- public B getBody() {
- return body;
+ @Override
+ public void endStream() throws IOException {
+ if (byteChannel.isOpen()) {
+ byteChannel.close();
+ }
}
@Override
- public String toString() {
- return "[head=" + head + ", body=" + body + ']';
+ public void endStream(final List<? extends Header> trailers) throws IOException {
+ endStream();
}
}
diff --git a/httpcore5/src/main/java/org/apache/hc/core5/http/Message.java b/httpcore5-jackson2/src/test/java/org/apache/hc/core5/jackson2/http/CompletableFutureCallback.java
similarity index 52%
copy from httpcore5/src/main/java/org/apache/hc/core5/http/Message.java
copy to httpcore5-jackson2/src/test/java/org/apache/hc/core5/jackson2/http/CompletableFutureCallback.java
index b60d9724b..f66efabb4 100644
--- a/httpcore5/src/main/java/org/apache/hc/core5/http/Message.java
+++ b/httpcore5-jackson2/src/test/java/org/apache/hc/core5/jackson2/http/CompletableFutureCallback.java
@@ -24,66 +24,45 @@
* <http://www.apache.org/>.
*
*/
+package org.apache.hc.core5.jackson2.http;
-package org.apache.hc.core5.http;
+import java.util.concurrent.CompletableFuture;
-import org.apache.hc.core5.util.Args;
+import org.apache.hc.core5.concurrent.FutureCallback;
/**
- * Generic message consisting of a message head and a message body.
+ * Connects a {@link FutureCallback} to a {@link CompletableFuture}
*
- * @param <H> message head type.
- * @param <B> message body type.
- *
- * @since 5.0
+ * @param <T> The result type
*/
-public final class Message<H extends MessageHeaders, B> {
+public class CompletableFutureCallback<T> implements FutureCallback<T> {
- private final H head;
- private final B body;
+ private final CompletableFuture<T> future;
- /**
- * Constructs a new instance.
- *
- * @param head The message head.
- * @since 5.3
- */
- public Message(final H head) {
- this(head, null);
+ public CompletableFutureCallback() {
+ this(new CompletableFuture<>());
}
- /**
- * Constructs a new instance.
- *
- * @param head The message head.
- * @param body The message body.
- */
- public Message(final H head, final B body) {
- this.head = Args.notNull(head, "Message head");
- this.body = body;
+ public CompletableFutureCallback(final CompletableFuture<T> future) {
+ this.future = future;
}
- /**
- * Gets the message head.
- *
- * @return the message head.
- */
- public H getHead() {
- return head;
+ public CompletableFuture<T> getFuture() {
+ return future;
}
- /**
- * Gets the message body.
- *
- * @return the message body.
- */
- public B getBody() {
- return body;
+ @Override
+ public void completed(final T result) {
+ future.complete(result);
}
@Override
- public String toString() {
- return "[head=" + head + ", body=" + body + ']';
+ public void failed(final Exception ex) {
+ future.completeExceptionally(ex);
}
+ @Override
+ public void cancelled() {
+ future.cancel(false);
+ }
}
diff --git a/httpcore5/src/main/java/org/apache/hc/core5/http/Message.java b/httpcore5-jackson2/src/test/java/org/apache/hc/core5/jackson2/http/HttpResponseException.java
similarity index 51%
copy from httpcore5/src/main/java/org/apache/hc/core5/http/Message.java
copy to httpcore5-jackson2/src/test/java/org/apache/hc/core5/jackson2/http/HttpResponseException.java
index b60d9724b..33ac4ec23 100644
--- a/httpcore5/src/main/java/org/apache/hc/core5/http/Message.java
+++ b/httpcore5-jackson2/src/test/java/org/apache/hc/core5/jackson2/http/HttpResponseException.java
@@ -24,66 +24,26 @@
* <http://www.apache.org/>.
*
*/
+package org.apache.hc.core5.jackson2.http;
-package org.apache.hc.core5.http;
+import java.io.IOException;
-import org.apache.hc.core5.util.Args;
+import org.apache.hc.core5.http.HttpResponse;
-/**
- * Generic message consisting of a message head and a message body.
- *
- * @param <H> message head type.
- * @param <B> message body type.
- *
- * @since 5.0
- */
-public final class Message<H extends MessageHeaders, B> {
-
- private final H head;
- private final B body;
+public class HttpResponseException extends IOException {
- /**
- * Constructs a new instance.
- *
- * @param head The message head.
- * @since 5.3
- */
- public Message(final H head) {
- this(head, null);
- }
-
- /**
- * Constructs a new instance.
- *
- * @param head The message head.
- * @param body The message body.
- */
- public Message(final H head, final B body) {
- this.head = Args.notNull(head, "Message head");
- this.body = body;
- }
+ private final HttpResponse response;
- /**
- * Gets the message head.
- *
- * @return the message head.
- */
- public H getHead() {
- return head;
+ public HttpResponseException(final HttpResponse response) {
+ this.response = response;
}
- /**
- * Gets the message body.
- *
- * @return the message body.
- */
- public B getBody() {
- return body;
+ public int getStatusCode() {
+ return response.getCode();
}
- @Override
- public String toString() {
- return "[head=" + head + ", body=" + body + ']';
+ public HttpResponse getResponse() {
+ return response;
}
}
diff --git a/httpcore5-jackson2/src/test/java/org/apache/hc/core5/jackson2/http/JsonEntityConsumersTest.java b/httpcore5-jackson2/src/test/java/org/apache/hc/core5/jackson2/http/JsonEntityConsumersTest.java
new file mode 100644
index 000000000..2d237961e
--- /dev/null
+++ b/httpcore5-jackson2/src/test/java/org/apache/hc/core5/jackson2/http/JsonEntityConsumersTest.java
@@ -0,0 +1,578 @@
+/*
+ * ====================================================================
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * <http://www.apache.org/>.
+ *
+ */
+package org.apache.hc.core5.jackson2.http;
+
+import java.io.InputStream;
+import java.net.URI;
+import java.net.URL;
+import java.nio.ByteBuffer;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicReference;
+
+import com.fasterxml.jackson.core.JsonFactory;
+import com.fasterxml.jackson.core.JsonTokenId;
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ArrayNode;
+import com.fasterxml.jackson.databind.node.JsonNodeFactory;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+
+import org.apache.hc.core5.concurrent.FutureCallback;
+import org.apache.hc.core5.http.ContentType;
+import org.apache.hc.core5.http.impl.BasicEntityDetails;
+import org.apache.hc.core5.http.message.BasicHeader;
+import org.apache.hc.core5.jackson2.JsonContentException;
+import org.apache.hc.core5.jackson2.JsonResultSink;
+import org.assertj.core.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+public class JsonEntityConsumersTest {
+
+ @Test
+ void testJsonNodeCorrectlyProcessed() throws Exception {
+ final JsonFactory factory = new JsonFactory();
+
+ final URL resource = getClass().getResource("/sample1.json");
+ Assertions.assertThat(resource).isNotNull();
+
+ final JsonNodeEntityConsumer entityConsumer = new JsonNodeEntityConsumer(factory);
+ final AtomicReference<JsonNode> resultRef = new AtomicReference<>();
+ try (final InputStream inputStream = resource.openStream()) {
+ entityConsumer.streamStart(
+ new BasicEntityDetails(-1, ContentType.APPLICATION_JSON),
+ new FutureCallback<JsonNode>() {
+
+ @Override
+ public void completed(final JsonNode result) {
+ resultRef.set(result);
+ }
+
+ @Override
+ public void failed(final Exception ex) {
+ }
+
+ @Override
+ public void cancelled() {
+ }
+
+ });
+ final byte[] bytebuf = new byte[1024];
+ int len;
+ while ((len = inputStream.read(bytebuf)) != -1) {
+ entityConsumer.consume(ByteBuffer.wrap(bytebuf, 0, len));
+ }
+ entityConsumer.streamEnd(null);
+ }
+
+ final ObjectNode expectedObject = JsonNodeFactory.instance.objectNode();
+ expectedObject.putObject("args");
+ expectedObject.putObject("headers")
+ .put("Accept", "application/json")
+ .put("Accept-Encoding", "gzip, deflate")
+ .put("Accept-Language", "en-US,en;q=0.9")
+ .put("Connection", "close")
+ .put("Cookie", "_gauges_unique_year=1; _gauges_unique=1; _gauges_unique_hour=1; " +
+ "_gauges_unique_day=1; _gauges_unique_month=1")
+ .put("Host", "httpbin.org")
+ .put("Referer", "http://httpbin.org/")
+ .put("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) " +
+ "snap Chromium/71.0.3578.98 Chrome/71.0.3578.98 Safari/537.36");
+ expectedObject.put("origin", "xxx.xxx.xxx.xxx");
+ expectedObject.put("url", "http://httpbin.org/get");
+
+ Assertions.assertThat(resultRef.get()).isEqualTo(expectedObject);
+ }
+
+ @Test
+ void testWrongContentTypeThrowsException() throws Exception {
+ final JsonFactory factory = new JsonFactory();
+
+ final JsonNodeEntityConsumer entityConsumer = new JsonNodeEntityConsumer(factory);
+ Assertions.assertThatThrownBy(() -> entityConsumer.streamStart(
+ new BasicEntityDetails(-1, ContentType.TEXT_PLAIN),
+ null)).isInstanceOf(JsonContentException.class)
+ .hasMessage("Unexpected content type: text/plain");
+ }
+
+ @Test
+ void testJsonObjectEntityCorrectlyProcessed() throws Exception {
+ final JsonFactory factory = new JsonFactory();
+ final ObjectMapper objectMapper = new ObjectMapper(factory);
+
+ final URL resource = getClass().getResource("/sample1.json");
+ Assertions.assertThat(resource).isNotNull();
+
+ final AtomicReference<RequestData> resultRef = new AtomicReference<>();
+ final JsonObjectEntityConsumer<RequestData> entityConsumer = new JsonObjectEntityConsumer<>(objectMapper, RequestData.class);
+ try (final InputStream inputStream = resource.openStream()) {
+ entityConsumer.streamStart(
+ new BasicEntityDetails(-1, ContentType.APPLICATION_JSON),
+ new FutureCallback<RequestData>() {
+
+ @Override
+ public void completed(final RequestData result) {
+ resultRef.set(result);
+ }
+
+ @Override
+ public void failed(final Exception ex) {
+ }
+
+ @Override
+ public void cancelled() {
+ }
+
+ });
+ final byte[] bytebuf = new byte[1024];
+ int len;
+ while ((len = inputStream.read(bytebuf)) != -1) {
+ entityConsumer.consume(ByteBuffer.wrap(bytebuf, 0, len));
+ }
+ entityConsumer.streamEnd(null);
+ }
+
+ final RequestData expectedObject = new RequestData();
+ expectedObject.setArgs(new HashMap<>());
+ expectedObject.generateHeaders(
+ new BasicHeader("Accept", "application/json"),
+ new BasicHeader("Accept-Encoding", "gzip, deflate"),
+ new BasicHeader("Accept-Language", "en-US,en;q=0.9"),
+ new BasicHeader("Connection", "close"),
+ new BasicHeader("Cookie", "_gauges_unique_year=1; _gauges_unique=1; _gauges_unique_hour=1; " +
+ "_gauges_unique_day=1; _gauges_unique_month=1"),
+ new BasicHeader("Host", "httpbin.org"),
+ new BasicHeader("Referer", "http://httpbin.org/"),
+ new BasicHeader("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) " +
+ "snap Chromium/71.0.3578.98 Chrome/71.0.3578.98 Safari/537.36"));
+ expectedObject.setOrigin("xxx.xxx.xxx.xxx");
+ expectedObject.setUrl(URI.create("http://httpbin.org/get"));
+
+ Assertions.assertThat(resultRef.get()).usingRecursiveComparison().isEqualTo(expectedObject);
+ }
+
+ @Test
+ void testJsonTypeReferenceCorrectlyProcessed() throws Exception {
+ final JsonFactory factory = new JsonFactory();
+ final ObjectMapper objectMapper = new ObjectMapper(factory);
+
+ final URL resource = getClass().getResource("/sample4.json");
+ Assertions.assertThat(resource).isNotNull();
+
+ final AtomicReference<List<String>> resultRef = new AtomicReference<>();
+ final JsonObjectEntityConsumer<List<String>> entityConsumer = new JsonObjectEntityConsumer<>(objectMapper, new TypeReference<List<String>>() {
+ });
+ try (final InputStream inputStream = resource.openStream()) {
+ entityConsumer.streamStart(
+ new BasicEntityDetails(-1, ContentType.APPLICATION_JSON),
+ new FutureCallback<List<String>>() {
+
+ @Override
+ public void completed(final List<String> result) {
+ resultRef.set(result);
+ }
+
+ @Override
+ public void failed(final Exception ex) {
+ }
+
+ @Override
+ public void cancelled() {
+ }
+
+ });
+ final byte[] bytebuf = new byte[1024];
+ int len;
+ while ((len = inputStream.read(bytebuf)) != -1) {
+ entityConsumer.consume(ByteBuffer.wrap(bytebuf, 0, len));
+ }
+ entityConsumer.streamEnd(null);
+ }
+
+ Assertions.assertThat(resultRef.get()).containsExactly("1", "2", "3", "4");
+ }
+
+ @Test
+ void testJsonSequenceCorrectlyProcessed() throws Exception {
+ final JsonFactory factory = new JsonFactory();
+ final ObjectMapper objectMapper = new ObjectMapper(factory);
+
+ final URL resource = getClass().getResource("/sample3.json");
+ Assertions.assertThat(resource).isNotNull();
+
+ final AtomicReference<Long> resultRef = new AtomicReference<>();
+ final AtomicInteger started = new AtomicInteger(0);
+ final List<RequestData> jsonDataList = new ArrayList<>();
+ final AtomicInteger ended = new AtomicInteger(0);
+ final JsonSequenceEntityConsumer<RequestData> entityConsumer = new JsonSequenceEntityConsumer<>(
+ objectMapper,
+ RequestData.class,
+ new JsonResultSink<RequestData>() {
+
+ @Override
+ public void begin(final int sizeHint) {
+ started.incrementAndGet();
+ }
+
+ @Override
+ public void accept(final RequestData data) {
+ jsonDataList.add(data);
+ }
+
+ @Override
+ public void end() {
+ ended.incrementAndGet();
+ }
+
+ });
+ try (final InputStream inputStream = resource.openStream()) {
+ entityConsumer.streamStart(
+ new BasicEntityDetails(-1, ContentType.APPLICATION_JSON),
+ new FutureCallback<Long>() {
+
+ @Override
+ public void completed(final Long result) {
+ resultRef.set(result);
+ }
+
+ @Override
+ public void failed(final Exception ex) {
+ }
+
+ @Override
+ public void cancelled() {
+ }
+
+ });
+ final byte[] bytebuf = new byte[1024];
+ int len;
+ while ((len = inputStream.read(bytebuf)) != -1) {
+ entityConsumer.consume(ByteBuffer.wrap(bytebuf, 0, len));
+ }
+ entityConsumer.streamEnd(null);
+ }
+
+ Assertions.assertThat(resultRef.get()).isEqualTo(3L);
+
+ Assertions.assertThat(jsonDataList).hasSize(3);
+ Assertions.assertThat(started.get()).isEqualTo(1);
+ Assertions.assertThat(ended.get()).isEqualTo(1);
+
+
+ final RequestData expectedObject1 = new RequestData();
+ expectedObject1.setId(0);
+ expectedObject1.setUrl(URI.create("http://httpbin.org/stream/3"));
+ expectedObject1.setArgs(new HashMap<>());
+ expectedObject1.generateHeaders(
+ new BasicHeader("Host", "httpbin.org"),
+ new BasicHeader("Connection", "close"),
+ new BasicHeader("Referer", "http://httpbin.org/"),
+ new BasicHeader("Accept", "application/json"),
+ new BasicHeader("Accept-Encoding", "gzip, deflate"),
+ new BasicHeader("Accept-Language", "en-US,en;q=0.9"),
+ new BasicHeader("Cookie", "_gauges_unique_year=1; _gauges_unique=1; _gauges_unique_month=1; " +
+ "_gauges_unique_day=1; _gauges_unique_hour=1"),
+ new BasicHeader("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) " +
+ "snap Chromium/71.0.3578.98 Chrome/71.0.3578.98 Safari/537.36"));
+ expectedObject1.setOrigin("xxx.xxx.xxx.xxx");
+
+ Assertions.assertThat(jsonDataList.get(0)).usingRecursiveComparison().isEqualTo(expectedObject1);
+
+ final RequestData expectedObject2 = new RequestData();
+ expectedObject2.setId(1);
+ expectedObject2.setUrl(URI.create("http://httpbin.org/stream/3"));
+ expectedObject2.setArgs(new HashMap<>());
+ expectedObject2.generateHeaders(
+ new BasicHeader("Host", "httpbin.org"),
+ new BasicHeader("Connection", "close"),
+ new BasicHeader("Referer", "http://httpbin.org/"),
+ new BasicHeader("Accept", "application/json"),
+ new BasicHeader("Accept-Encoding", "gzip, deflate"),
+ new BasicHeader("Accept-Language", "en-US,en;q=0.9"),
+ new BasicHeader("Cookie", "_gauges_unique_year=1; _gauges_unique=1; _gauges_unique_month=1; " +
+ "_gauges_unique_day=1; _gauges_unique_hour=1"),
+ new BasicHeader("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) " +
+ "snap Chromium/71.0.3578.98 Chrome/71.0.3578.98 Safari/537.36"));
+ expectedObject2.setOrigin("xxx.xxx.xxx.xxx");
+
+ Assertions.assertThat(jsonDataList.get(1)).usingRecursiveComparison().isEqualTo(expectedObject2);
+
+ final RequestData expectedObject3 = new RequestData();
+ expectedObject3.setId(2);
+ expectedObject3.setUrl(URI.create("http://httpbin.org/stream/3"));
+ expectedObject3.setArgs(new HashMap<>());
+ expectedObject3.generateHeaders(
+ new BasicHeader("Host", "httpbin.org"),
+ new BasicHeader("Connection", "close"),
+ new BasicHeader("Referer", "http://httpbin.org/"),
+ new BasicHeader("Accept", "application/json"),
+ new BasicHeader("Accept-Encoding", "gzip, deflate"),
+ new BasicHeader("Accept-Language", "en-US,en;q=0.9"),
+ new BasicHeader("Cookie", "_gauges_unique_year=1; _gauges_unique=1; _gauges_unique_month=1; " +
+ "_gauges_unique_day=1; _gauges_unique_hour=1"),
+ new BasicHeader("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) " +
+ "snap Chromium/71.0.3578.98 Chrome/71.0.3578.98 Safari/537.36"));
+ expectedObject3.setOrigin("xxx.xxx.xxx.xxx");
+
+ Assertions.assertThat(jsonDataList.get(2)).usingRecursiveComparison().isEqualTo(expectedObject3);
+ }
+
+ @Test
+ void testJsonTypeReferenceSequenceCorrectlyProcessed() throws Exception {
+ final JsonFactory factory = new JsonFactory();
+ final ObjectMapper objectMapper = new ObjectMapper(factory);
+
+ final URL resource = getClass().getResource("/sample5.json");
+ Assertions.assertThat(resource).isNotNull();
+
+ final AtomicReference<Long> resultRef = new AtomicReference<>();
+ final AtomicInteger started = new AtomicInteger(0);
+ final List<List<String>> jsonDataList = new ArrayList<>();
+ final AtomicInteger ended = new AtomicInteger(0);
+ final JsonSequenceEntityConsumer<List<String>> entityConsumer = new JsonSequenceEntityConsumer<>(
+ objectMapper,
+ new TypeReference<List<String>>() {
+ },
+ new JsonResultSink<List<String>>() {
+
+ @Override
+ public void begin(final int sizeHint) {
+ started.incrementAndGet();
+ }
+
+ @Override
+ public void accept(final List<String> data) {
+ jsonDataList.add(data);
+ }
+
+ @Override
+ public void end() {
+ ended.incrementAndGet();
+ }
+
+ });
+ try (final InputStream inputStream = resource.openStream()) {
+ entityConsumer.streamStart(
+ new BasicEntityDetails(-1, ContentType.APPLICATION_JSON),
+ new FutureCallback<Long>() {
+
+ @Override
+ public void completed(final Long result) {
+ resultRef.set(result);
+ }
+
+ @Override
+ public void failed(final Exception ex) {
+ }
+
+ @Override
+ public void cancelled() {
+ }
+
+ });
+ final byte[] bytebuf = new byte[1024];
+ int len;
+ while ((len = inputStream.read(bytebuf)) != -1) {
+ entityConsumer.consume(ByteBuffer.wrap(bytebuf, 0, len));
+ }
+ entityConsumer.streamEnd(null);
+ }
+
+ Assertions.assertThat(resultRef.get()).isEqualTo(3L);
+
+ Assertions.assertThat(jsonDataList).hasSize(3);
+ Assertions.assertThat(started.get()).isEqualTo(1);
+ Assertions.assertThat(ended.get()).isEqualTo(1);
+
+ Assertions.assertThat(jsonDataList.get(0)).containsExactly("1", "2", "3", "4");
+ Assertions.assertThat(jsonDataList.get(1)).containsExactly("5", "6", "7", "8");
+ Assertions.assertThat(jsonDataList.get(2)).containsExactly("9", "10", "11", "12");
+ }
+
+ @Test
+ void testJsonNodeSequenceCorrectlyProcessed() throws Exception {
+ final JsonFactory factory = new JsonFactory();
+ final ObjectMapper objectMapper = new ObjectMapper(factory);
+
+ final URL resource = getClass().getResource("/sample7.json");
+ Assertions.assertThat(resource).isNotNull();
+
+ final AtomicReference<Long> resultRef = new AtomicReference<>();
+ final AtomicInteger started = new AtomicInteger(0);
+ final List<JsonNode> jsonDataList = new ArrayList<>();
+ final AtomicInteger ended = new AtomicInteger(0);
+ final JsonNodeSequenceEntityConsumer entityConsumer = new JsonNodeSequenceEntityConsumer(
+ objectMapper,
+ new JsonResultSink<JsonNode>() {
+
+ @Override
+ public void begin(final int sizeHint) {
+ started.incrementAndGet();
+ }
+
+ @Override
+ public void accept(final JsonNode data) {
+ jsonDataList.add(data);
+ }
+
+ @Override
+ public void end() {
+ ended.incrementAndGet();
+ }
+
+ });
+ try (final InputStream inputStream = resource.openStream()) {
+ entityConsumer.streamStart(
+ new BasicEntityDetails(-1, ContentType.APPLICATION_JSON),
+ new FutureCallback<Long>() {
+
+ @Override
+ public void completed(final Long result) {
+ resultRef.set(result);
+ }
+
+ @Override
+ public void failed(final Exception ex) {
+ }
+
+ @Override
+ public void cancelled() {
+ }
+
+ });
+ final byte[] bytebuf = new byte[1024];
+ int len;
+ while ((len = inputStream.read(bytebuf)) != -1) {
+ entityConsumer.consume(ByteBuffer.wrap(bytebuf, 0, len));
+ }
+ entityConsumer.streamEnd(null);
+ }
+
+ Assertions.assertThat(resultRef.get()).isEqualTo(5L);
+ Assertions.assertThat(jsonDataList).hasSize(5);
+
+ final ObjectNode expectedObject1 = JsonNodeFactory.instance.objectNode();
+ expectedObject1.putObject("args");
+ expectedObject1.putObject("headers")
+ .put("Accept", "application/json")
+ .put("Accept-Encoding", "gzip, deflate")
+ .put("Accept-Language", "en-US,en;q=0.9")
+ .put("Connection", "close")
+ .put("Cookie", "_gauges_unique_year=1; _gauges_unique=1; _gauges_unique_hour=1; " +
+ "_gauges_unique_day=1; _gauges_unique_month=1")
+ .put("Host", "httpbin.org")
+ .put("Referer", "http://httpbin.org/")
+ .put("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) " +
+ "snap Chromium/71.0.3578.98 Chrome/71.0.3578.98 Safari/537.36");
+ expectedObject1.put("origin", "xxx.xxx.xxx.xxx");
+ expectedObject1.put("url", "http://httpbin.org/get");
+
+ Assertions.assertThat(jsonDataList.get(0)).isEqualTo(expectedObject1);
+
+ final ObjectNode expectedObject2 = JsonNodeFactory.instance.objectNode();
+ expectedObject2.put("value", "Some text");
+
+ Assertions.assertThat(jsonDataList.get(1)).isEqualTo(expectedObject2);
+
+ final ArrayNode expectedObject3 = JsonNodeFactory.instance.arrayNode();
+ expectedObject3.add("1").add("2").add("3");
+
+ Assertions.assertThat(jsonDataList.get(2)).isEqualTo(expectedObject3);
+
+ final ArrayNode expectedObject4 = JsonNodeFactory.instance.arrayNode();
+ expectedObject4.add(1).add(2).add(3);
+
+ Assertions.assertThat(jsonDataList.get(3)).isEqualTo(expectedObject4);
+
+ final ArrayNode expectedObject5 = JsonNodeFactory.instance.arrayNode();
+ expectedObject5.addObject()
+ .put("value", "Some text");
+ expectedObject5.addObject()
+ .put("value", "Some other text");
+
+ Assertions.assertThat(jsonDataList.get(4)).isEqualTo(expectedObject5);
+ }
+
+ @Test
+ void testJsonTokenCorrectlyProcessed() throws Exception {
+ final JsonFactory factory = new JsonFactory();
+
+ final URL resource = getClass().getResource("/sample1.json");
+ Assertions.assertThat(resource).isNotNull();
+
+ final List<Integer> tokenIds = new LinkedList<>();
+ final JsonTokenEntityConsumer entityConsumer = new JsonTokenEntityConsumer(factory,
+ (tokenId, jsonParser) -> tokenIds.add(tokenId));
+ try (final InputStream inputStream = resource.openStream()) {
+ entityConsumer.streamStart(
+ new BasicEntityDetails(-1, ContentType.APPLICATION_JSON),
+ null);
+ final byte[] bytebuf = new byte[1024];
+ int len;
+ while ((len = inputStream.read(bytebuf)) != -1) {
+ entityConsumer.consume(ByteBuffer.wrap(bytebuf, 0, len));
+ }
+ entityConsumer.streamEnd(null);
+ }
+ Assertions.assertThat(tokenIds).containsExactly(
+ JsonTokenId.ID_START_OBJECT,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_START_OBJECT,
+ JsonTokenId.ID_END_OBJECT,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_START_OBJECT,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_END_OBJECT,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_FIELD_NAME,
+ JsonTokenId.ID_STRING,
+ JsonTokenId.ID_END_OBJECT,
+ JsonTokenId.ID_NO_TOKEN
+ );
+ }
+
+}
diff --git a/httpcore5-jackson2/src/test/java/org/apache/hc/core5/jackson2/http/JsonEntityProducersTest.java b/httpcore5-jackson2/src/test/java/org/apache/hc/core5/jackson2/http/JsonEntityProducersTest.java
new file mode 100644
index 000000000..20239a76d
--- /dev/null
+++ b/httpcore5-jackson2/src/test/java/org/apache/hc/core5/jackson2/http/JsonEntityProducersTest.java
@@ -0,0 +1,188 @@
+/*
+ * ====================================================================
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * <http://www.apache.org/>.
+ *
+ */
+package org.apache.hc.core5.jackson2.http;
+
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.nio.channels.WritableByteChannel;
+import java.nio.charset.StandardCharsets;
+import java.util.Arrays;
+import java.util.List;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import com.fasterxml.jackson.core.JsonFactory;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ArrayNode;
+import com.fasterxml.jackson.databind.node.JsonNodeFactory;
+
+import org.apache.hc.core5.http.Header;
+import org.apache.hc.core5.http.NameValuePair;
+import org.apache.hc.core5.http.message.BasicNameValuePair;
+import org.apache.hc.core5.http.nio.DataStreamChannel;
+import org.assertj.core.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+public class JsonEntityProducersTest {
+
+ static class MockDataStreamChannel implements DataStreamChannel {
+
+ private final WritableByteChannel byteChannel;
+
+ public MockDataStreamChannel(final WritableByteChannel byteChannel) {
+ this.byteChannel = byteChannel;
+ }
+
+ @Override
+ public void requestOutput() {
+ }
+
+ @Override
+ public int write(final ByteBuffer src) throws IOException {
+ return byteChannel.write(src);
+ }
+
+ @Override
+ public void endStream() throws IOException {
+ if (byteChannel.isOpen()) {
+ byteChannel.close();
+ }
+ }
+
+ @Override
+ public void endStream(final List<? extends Header> trailers) throws IOException {
+ endStream();
+ }
+
+ public boolean isOpen() {
+ return byteChannel.isOpen();
+ }
+
+ }
+
+ @Test
+ void testJsonObjectEntityProducer() throws Exception {
+ final JsonFactory factory = new JsonFactory();
+ final ObjectMapper objectMapper = new ObjectMapper(factory);
+
+ final JsonObjectEntityProducer<List<NameValuePair>> producer = new JsonObjectEntityProducer<>(
+ Arrays.asList(
+ new BasicNameValuePair("param1", "value"),
+ new BasicNameValuePair("param2", "blah-blah-blah-blah-blah-blah-blah-blah-blah-blah-blah"))
+ , objectMapper);
+
+ final int[][] params = new int[][]{{1024, -1}, {16, 16}, {32, 32}};
+
+ for (int i = 0; i < params.length; i++) {
+ final WritableByteChannelMock byteChannel = new WritableByteChannelMock(params[i][0], params[i][1]);
+ final MockDataStreamChannel dataChannel = new MockDataStreamChannel(byteChannel);
+ while (dataChannel.isOpen()) {
+ producer.produce(dataChannel);
+ byteChannel.flush();
+ }
+ Assertions.assertThat(byteChannel.dump(StandardCharsets.US_ASCII)).isEqualTo("[" +
+ "{\"name\":\"param1\",\"value\":\"value\"}," +
+ "{\"name\":\"param2\",\"value\":\"blah-blah-blah-blah-blah-blah-blah-blah-blah-blah-blah\"}" +
+ "]");
+ producer.releaseResources();
+ }
+ }
+
+ @Test
+ void testJsonNodeEntityProducer() throws Exception {
+ final JsonFactory factory = new JsonFactory();
+ final ObjectMapper objectMapper = new ObjectMapper(factory);
+
+ final ArrayNode arrayNode = JsonNodeFactory.instance.arrayNode();
+ arrayNode.add(JsonNodeFactory.instance.
+ objectNode().put("name", "param1").put("value", "value"));
+ arrayNode.add(JsonNodeFactory.instance.
+ objectNode().put("name", "param2").put("value", "blah-blah-blah-blah-blah-blah-blah-blah-blah-blah-blah"));
+
+ final JsonNodeEntityProducer producer = new JsonNodeEntityProducer(arrayNode, objectMapper);
+
+ final int[][] params = new int[][]{{1024, -1}, {16, 16}, {32, 32}};
+
+ for (int i = 0; i < params.length; i++) {
+ final WritableByteChannelMock byteChannel = new WritableByteChannelMock(params[i][0], params[i][1]);
+ final MockDataStreamChannel dataChannel = new MockDataStreamChannel(byteChannel);
+ while (dataChannel.isOpen()) {
+ producer.produce(dataChannel);
+ byteChannel.flush();
+ }
+ Assertions.assertThat(byteChannel.dump(StandardCharsets.US_ASCII)).isEqualTo("[" +
+ "{\"name\":\"param1\",\"value\":\"value\"}," +
+ "{\"name\":\"param2\",\"value\":\"blah-blah-blah-blah-blah-blah-blah-blah-blah-blah-blah\"}" +
+ "]");
+ producer.releaseResources();
+ }
+ }
+
+ @Test
+ void testJsonObjectSequenceEntityProducer() throws Exception {
+ final JsonFactory factory = new JsonFactory();
+ final ObjectMapper objectMapper = new ObjectMapper(factory);
+
+ final AtomicInteger count = new AtomicInteger(0);
+
+ final JsonSequenceEntityProducer<NameValuePair> producer = new JsonSequenceEntityProducer<>(
+ objectMapper,
+ 1024,
+ channel -> {
+ switch (count.incrementAndGet()) {
+ case 1:
+ channel.write(
+ new BasicNameValuePair("param1", "value"));
+ break;
+ case 2:
+ channel.write(
+ new BasicNameValuePair("param2", "blah-blah-blah-blah-blah-blah-blah-blah-blah-blah-blah"));
+ break;
+ default:
+ channel.endStream();
+ }
+
+ });
+
+ final int[][] params = new int[][]{{1024, -1}, {16, 16}, {32, 32}};
+
+ for (int i = 0; i < params.length; i++) {
+ final WritableByteChannelMock byteChannel = new WritableByteChannelMock(params[i][0], params[i][1]);
+ final MockDataStreamChannel dataChannel = new MockDataStreamChannel(byteChannel);
+ while (dataChannel.isOpen()) {
+ producer.produce(dataChannel);
+ byteChannel.flush();
+ }
+ Assertions.assertThat(byteChannel.dump(StandardCharsets.US_ASCII)).isEqualTo(
+ "{\"name\":\"param1\",\"value\":\"value\"}" +
+ "{\"name\":\"param2\",\"value\":\"blah-blah-blah-blah-blah-blah-blah-blah-blah-blah-blah\"}"
+ );
+ producer.releaseResources();
+ count.set(0);
+ }
+ }
+
+}
diff --git a/httpcore5-jackson2/src/test/java/org/apache/hc/core5/jackson2/http/JsonRequestConsumersTest.java b/httpcore5-jackson2/src/test/java/org/apache/hc/core5/jackson2/http/JsonRequestConsumersTest.java
new file mode 100644
index 000000000..d6bf10328
--- /dev/null
+++ b/httpcore5-jackson2/src/test/java/org/apache/hc/core5/jackson2/http/JsonRequestConsumersTest.java
@@ -0,0 +1,232 @@
+/*
+ * ====================================================================
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * <http://www.apache.org/>.
+ *
+ */
+package org.apache.hc.core5.jackson2.http;
+
+import java.io.InputStream;
+import java.net.URL;
+import java.nio.ByteBuffer;
+import java.nio.charset.StandardCharsets;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.concurrent.atomic.AtomicReference;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+import org.apache.hc.core5.concurrent.FutureCallback;
+import org.apache.hc.core5.http.ContentType;
+import org.apache.hc.core5.http.HttpRequest;
+import org.apache.hc.core5.http.Message;
+import org.apache.hc.core5.http.impl.BasicEntityDetails;
+import org.apache.hc.core5.http.message.BasicHttpRequest;
+import org.apache.hc.core5.http.nio.AsyncRequestConsumer;
+import org.apache.hc.core5.http.protocol.HttpCoreContext;
+import org.apache.hc.core5.http.support.BasicRequestBuilder;
+import org.apache.hc.core5.jackson2.JsonContentException;
+import org.assertj.core.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+public class JsonRequestConsumersTest {
+
+ @Test
+ void testRequestJsonContentCorrectlyProcessed() throws Exception {
+ final ObjectMapper objectMapper = new ObjectMapper();
+
+ final URL resource = getClass().getResource("/sample1.json");
+ Assertions.assertThat(resource).isNotNull();
+
+ final BasicHttpRequest request = BasicRequestBuilder.post().build();
+
+ final AsyncRequestConsumer<Message<HttpRequest, RequestData>> requestConsumer = new JsonRequestConsumer<>(
+ () -> new JsonObjectEntityConsumer<>(objectMapper, RequestData.class));
+ final AtomicReference<Message<HttpRequest, RequestData>> resultRef = new AtomicReference<>();
+ try (final InputStream inputStream = resource.openStream()) {
+ requestConsumer.consumeRequest(
+ request,
+ new BasicEntityDetails(-1, ContentType.APPLICATION_JSON),
+ HttpCoreContext.create(),
+ new FutureCallback<Message<HttpRequest, RequestData>>() {
+
+ @Override
+ public void completed(final Message<HttpRequest, RequestData> result) {
+ resultRef.set(result);
+ }
+
+ @Override
+ public void failed(final Exception ex) {
+ }
+
+ @Override
+ public void cancelled() {
+ }
+
+ });
+ final byte[] bytebuf = new byte[1024];
+ int len;
+ while ((len = inputStream.read(bytebuf)) != -1) {
+ requestConsumer.consume(ByteBuffer.wrap(bytebuf, 0, len));
+ }
+ requestConsumer.streamEnd(null);
+ }
+
+ Assertions.assertThat(resultRef.get()).isNotNull().satisfies(e -> {
+ Assertions.assertThat(e.getHead()).isSameAs(request);
+ Assertions.assertThat(e.getBody()).isNotNull();
+ Assertions.assertThat(e.error()).isNull();
+ });
+ }
+
+ @Test
+ void testRequestWrongContentTypeThrowsException() throws Exception {
+ final ObjectMapper objectMapper = new ObjectMapper();
+
+ final BasicHttpRequest request = BasicRequestBuilder.post().build();
+
+ final AsyncRequestConsumer<Message<HttpRequest, RequestData>> requestConsumer = new JsonRequestConsumer<>(
+ () -> new JsonObjectEntityConsumer<>(objectMapper, RequestData.class));
+ final AtomicReference<Exception> resultRef = new AtomicReference<>();
+ requestConsumer.consumeRequest(
+ request,
+ new BasicEntityDetails(-1, ContentType.TEXT_PLAIN),
+ HttpCoreContext.create(),
+ new FutureCallback<Message<HttpRequest, RequestData>>() {
+
+ @Override
+ public void completed(final Message<HttpRequest, RequestData> result) {
+ }
+
+ @Override
+ public void failed(final Exception ex) {
+ resultRef.set(ex);
+ }
+
+ @Override
+ public void cancelled() {
+ }
+
+ });
+ requestConsumer.consume(ByteBuffer.wrap("This is just plain text".getBytes(StandardCharsets.UTF_8)));
+ requestConsumer.streamEnd(null);
+
+ Assertions.assertThat(resultRef.get()).isNotNull().isInstanceOf(JsonContentException.class).hasMessage("Unexpected content type: text/plain");
+ }
+
+ @Test
+ void testRequestJsonSequenceContentCorrectlyProcessed() throws Exception {
+ final ObjectMapper objectMapper = new ObjectMapper();
+
+ final URL resource = getClass().getResource("/sample3.json");
+ Assertions.assertThat(resource).isNotNull();
+
+ final BasicHttpRequest request = BasicRequestBuilder.post().build();
+
+ final AtomicReference<HttpRequest> messageRef = new AtomicReference<>();
+ final List<RequestData> resultList = new LinkedList<>();
+ final AtomicReference<Long> resultRef = new AtomicReference<>();
+ final JsonSequenceRequestConsumer<Long> requestConsumer = new JsonSequenceRequestConsumer<>(
+ () -> new JsonSequenceEntityConsumer<>(
+ objectMapper,
+ RequestData.class,
+ resultList::add),
+ messageRef::set);
+ try (final InputStream inputStream = resource.openStream()) {
+ requestConsumer.consumeRequest(
+ request,
+ new BasicEntityDetails(-1, ContentType.APPLICATION_JSON),
+ HttpCoreContext.create(),
+ new FutureCallback<Long>() {
+
+ @Override
+ public void completed(final Long result) {
+ resultRef.set(result);
+ }
+
+ @Override
+ public void failed(final Exception ex) {
+ }
+
+ @Override
+ public void cancelled() {
+ }
+
+ });
+ final byte[] bytebuf = new byte[1024];
+ int len;
+ while ((len = inputStream.read(bytebuf)) != -1) {
+ requestConsumer.consume(ByteBuffer.wrap(bytebuf, 0, len));
+ }
+ requestConsumer.streamEnd(null);
+ }
+
+ Assertions.assertThat(messageRef.get()).isSameAs(request);
+ Assertions.assertThat(resultList).hasSize(3);
+ Assertions.assertThat(resultRef.get()).isEqualTo(3L);
+ }
+
+ @Test
+ void testRequestJsonSequenceWrongContentTypeThrowsException() throws Exception {
+ final ObjectMapper objectMapper = new ObjectMapper();
+
+ final BasicHttpRequest request = BasicRequestBuilder.post().build();
+
+ final AtomicReference<HttpRequest> messageRef = new AtomicReference<>();
+ final List<RequestData> resultList = new LinkedList<>();
+ final AtomicReference<Exception> resultRef = new AtomicReference<>();
+ final JsonSequenceRequestConsumer<Long> requestConsumer = new JsonSequenceRequestConsumer<>(
+ () -> new JsonSequenceEntityConsumer<>(
+ objectMapper,
+ RequestData.class,
+ resultList::add),
+ messageRef::set);
+ requestConsumer.consumeRequest(
+ request,
+ new BasicEntityDetails(-1, ContentType.TEXT_PLAIN),
+ HttpCoreContext.create(),
+ new FutureCallback<Long>() {
+
+ @Override
+ public void completed(final Long result) {
+ }
+
+ @Override
+ public void failed(final Exception ex) {
+ resultRef.set(ex);
+ }
+
+ @Override
+ public void cancelled() {
+ }
+
+ });
+ requestConsumer.consume(ByteBuffer.wrap("This is just plain text".getBytes(StandardCharsets.UTF_8)));
+ requestConsumer.streamEnd(null);
+
+ Assertions.assertThat(messageRef.get()).isSameAs(request);
+ Assertions.assertThat(resultList).isEmpty();
+ Assertions.assertThat(resultRef.get()).isNotNull().isInstanceOf(JsonContentException.class).hasMessage("Unexpected content type: text/plain");
+ }
+
+}
diff --git a/httpcore5-jackson2/src/test/java/org/apache/hc/core5/jackson2/http/JsonResponseConsumersTest.java b/httpcore5-jackson2/src/test/java/org/apache/hc/core5/jackson2/http/JsonResponseConsumersTest.java
new file mode 100644
index 000000000..bcee0f505
--- /dev/null
+++ b/httpcore5-jackson2/src/test/java/org/apache/hc/core5/jackson2/http/JsonResponseConsumersTest.java
@@ -0,0 +1,363 @@
+/*
+ * ====================================================================
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * <http://www.apache.org/>.
+ *
+ */
+package org.apache.hc.core5.jackson2.http;
+
+import java.io.InputStream;
+import java.net.URL;
+import java.nio.ByteBuffer;
+import java.nio.charset.StandardCharsets;
+import java.util.Collections;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.concurrent.atomic.AtomicReference;
+
+import com.fasterxml.jackson.core.JsonFactory;
+import com.fasterxml.jackson.core.JsonParser;
+import com.fasterxml.jackson.core.JsonTokenId;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+import org.apache.hc.core5.concurrent.FutureCallback;
+import org.apache.hc.core5.http.ContentType;
+import org.apache.hc.core5.http.HttpResponse;
+import org.apache.hc.core5.http.Message;
+import org.apache.hc.core5.http.impl.BasicEntityDetails;
+import org.apache.hc.core5.http.message.BasicHttpResponse;
+import org.apache.hc.core5.http.nio.AsyncResponseConsumer;
+import org.apache.hc.core5.http.nio.entity.StringAsyncEntityConsumer;
+import org.apache.hc.core5.http.protocol.HttpCoreContext;
+import org.apache.hc.core5.http.support.BasicResponseBuilder;
+import org.apache.hc.core5.jackson2.JsonContentException;
+import org.apache.hc.core5.jackson2.JsonTokenConsumer;
+import org.assertj.core.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mockito;
+
+public class JsonResponseConsumersTest {
+
+ ObjectMapper objectMapper;
+
+ @BeforeEach
+ void setup() {
+ objectMapper = new ObjectMapper();
+ }
+
+ @Test
+ void testResponseJsonContentCorrectlyProcessed() throws Exception {
+ final URL resource = getClass().getResource("/sample1.json");
+ Assertions.assertThat(resource).isNotNull();
+
+ final BasicHttpResponse response = BasicResponseBuilder.create(200).build();
+
+ final AsyncResponseConsumer<Message<HttpResponse, RequestData>> responseConsumer = new JsonResponseConsumer<>(
+ () -> new JsonObjectEntityConsumer<>(objectMapper, RequestData.class),
+ StringAsyncEntityConsumer::new);
+ final AtomicReference<Message<HttpResponse, RequestData>> resultRef = new AtomicReference<>();
+ try (final InputStream inputStream = resource.openStream()) {
+ responseConsumer.consumeResponse(
+ response,
+ new BasicEntityDetails(-1, ContentType.APPLICATION_JSON),
+ HttpCoreContext.create(),
+ new FutureCallback<Message<HttpResponse, RequestData>>() {
+
+ @Override
+ public void completed(final Message<HttpResponse, RequestData> result) {
+ resultRef.set(result);
+ }
+
+ @Override
+ public void failed(final Exception ex) {
+ }
+
+ @Override
+ public void cancelled() {
+ }
+
+ });
+ final byte[] bytebuf = new byte[1024];
+ int len;
+ while ((len = inputStream.read(bytebuf)) != -1) {
+ responseConsumer.consume(ByteBuffer.wrap(bytebuf, 0, len));
+ }
+ responseConsumer.streamEnd(null);
+ }
+
+ Assertions.assertThat(resultRef.get()).isNotNull().satisfies(e -> {
+ Assertions.assertThat(e.getHead()).isSameAs(response);
+ Assertions.assertThat(e.getBody()).isNotNull();
+ Assertions.assertThat(e.error()).isNull();
+ });
+ }
+
+ @Test
+ void testResponseWrongContentTypeThrowsException() throws Exception {
+ final BasicHttpResponse response = BasicResponseBuilder.create(200).build();
+
+ final AsyncResponseConsumer<Message<HttpResponse, RequestData>> responseConsumer = new JsonResponseConsumer<>(
+ () -> new JsonObjectEntityConsumer<>(objectMapper, RequestData.class),
+ StringAsyncEntityConsumer::new);
+ final AtomicReference<Exception> resultRef = new AtomicReference<>();
+ responseConsumer.consumeResponse(
+ response,
+ new BasicEntityDetails(-1, ContentType.TEXT_PLAIN),
+ HttpCoreContext.create(),
+ new FutureCallback<Message<HttpResponse, RequestData>>() {
+
+ @Override
+ public void completed(final Message<HttpResponse, RequestData> result) {
+ }
+
+ @Override
+ public void failed(final Exception ex) {
+ resultRef.set(ex);
+ }
+
+ @Override
+ public void cancelled() {
+ }
+
+ });
+ responseConsumer.consume(ByteBuffer.wrap("This is just plain text".getBytes(StandardCharsets.UTF_8)));
+ responseConsumer.streamEnd(null);
+
+ Assertions.assertThat(resultRef.get()).isNotNull().isInstanceOf(JsonContentException.class).hasMessage("Unexpected content type: text/plain");
+ }
+
+ @Test
+ void testResponseJsonSequenceContentCorrectlyProcessed() throws Exception {
+ final URL resource = getClass().getResource("/sample3.json");
+ Assertions.assertThat(resource).isNotNull();
+
+ final BasicHttpResponse response = BasicResponseBuilder.create(200).build();
+
+ final AtomicReference<HttpResponse> messageRef = new AtomicReference<>();
+ final AtomicReference<String> errorRef = new AtomicReference<>();
+ final List<RequestData> resultList = new LinkedList<>();
+ final AtomicReference<Long> resultRef = new AtomicReference<>();
+ final JsonSequenceResponseConsumer<Long, String> responseConsumer = new JsonSequenceResponseConsumer<>(
+ () -> new JsonSequenceEntityConsumer<>(
+ objectMapper,
+ RequestData.class,
+ resultList::add),
+ StringAsyncEntityConsumer::new,
+ messageRef::set,
+ errorRef::set);
+ try (final InputStream inputStream = resource.openStream()) {
+ responseConsumer.consumeResponse(
+ response,
+ new BasicEntityDetails(-1, ContentType.APPLICATION_JSON),
+ HttpCoreContext.create(),
+ new FutureCallback<Long>() {
+
+ @Override
+ public void completed(final Long result) {
+ resultRef.set(result);
+ }
+
+ @Override
+ public void failed(final Exception ex) {
+ }
+
+ @Override
+ public void cancelled() {
+ }
+
+ });
+ final byte[] bytebuf = new byte[1024];
+ int len;
+ while ((len = inputStream.read(bytebuf)) != -1) {
+ responseConsumer.consume(ByteBuffer.wrap(bytebuf, 0, len));
+ }
+ responseConsumer.streamEnd(null);
+ }
+
+ Assertions.assertThat(messageRef.get()).isSameAs(response);
+ Assertions.assertThat(resultList).hasSize(3);
+ Assertions.assertThat(resultRef.get()).isEqualTo(3L);
+ }
+
+ @Test
+ void testResponseJsonSequenceWrongContentTypeThrowsException() throws Exception {
+ final BasicHttpResponse response = BasicResponseBuilder.create(200).build();
+
+ final AtomicReference<HttpResponse> messageRef = new AtomicReference<>();
+ final AtomicReference<String> errorRef = new AtomicReference<>();
+ final List<RequestData> resultList = new LinkedList<>();
+ final AtomicReference<Exception> resultRef = new AtomicReference<>();
+ final JsonSequenceResponseConsumer<Long, String> responseConsumer = new JsonSequenceResponseConsumer<>(
+ () -> new JsonSequenceEntityConsumer<>(
+ objectMapper,
+ RequestData.class,
+ resultList::add),
+ StringAsyncEntityConsumer::new,
+ messageRef::set,
+ errorRef::set);
+ responseConsumer.consumeResponse(
+ response,
+ new BasicEntityDetails(-1, ContentType.TEXT_PLAIN),
+ HttpCoreContext.create(),
+ new FutureCallback<Long>() {
+
+ @Override
+ public void completed(final Long result) {
+ }
+
+ @Override
+ public void failed(final Exception ex) {
+ resultRef.set(ex);
+ }
+
+ @Override
+ public void cancelled() {
+ }
+
+ });
+ responseConsumer.consume(ByteBuffer.wrap("This is just plain text".getBytes(StandardCharsets.UTF_8)));
+ responseConsumer.streamEnd(null);
+
+ Assertions.assertThat(messageRef.get()).isSameAs(response);
+ Assertions.assertThat(resultList).isEmpty();
+ Assertions.assertThat(resultRef.get()).isNotNull().isInstanceOf(JsonContentException.class).hasMessage("Unexpected content type: text/plain");
+ }
+
+ @Test
+ void testErrorResponseNonJsonContentMappedAsError() throws Exception {
+ final String errorBody = "Unexpected internal failure";
+
+ final BasicHttpResponse response = BasicResponseBuilder.create(500).build();
+
+ final AsyncResponseConsumer<Message<HttpResponse, RequestData>> responseConsumer = new JsonResponseConsumer<>(
+ () -> new JsonObjectEntityConsumer<>(objectMapper, RequestData.class),
+ StringAsyncEntityConsumer::new);
+ final AtomicReference<Message<HttpResponse, RequestData>> resultRef = new AtomicReference<>();
+
+ responseConsumer.consumeResponse(
+ response,
+ new BasicEntityDetails(errorBody.length(), ContentType.TEXT_PLAIN),
+ HttpCoreContext.create(),
+ new FutureCallback<Message<HttpResponse, RequestData>>() {
+ @Override
+ public void completed(final Message<HttpResponse, RequestData> result) {
+ resultRef.set(result);
+ }
+
+ @Override
+ public void failed(final Exception ex) {
+ }
+
+ @Override
+ public void cancelled() {
+ }
+
+ });
+ responseConsumer.consume(ByteBuffer.wrap(errorBody.getBytes(StandardCharsets.UTF_8)));
+ responseConsumer.streamEnd(null);
+
+ Assertions.assertThat(resultRef.get()).isNotNull().satisfies(e -> {
+ Assertions.assertThat(e.getHead()).isSameAs(response);
+ Assertions.assertThat(e.getBody()).isNull();
+ Assertions.assertThat(e.error()).isEqualTo(errorBody);
+ });
+ }
+
+ @Test
+ void testErrorResponseJsonContentMappedAsError() throws Exception {
+ final String errorBody = "{\"code\": 500, \"message\": \"Unexpected internal failure\"}";
+
+ final BasicHttpResponse response = BasicResponseBuilder.create(500).build();
+
+ final AsyncResponseConsumer<Message<HttpResponse, RequestData>> responseConsumer = new JsonResponseConsumer<>(
+ () -> new JsonObjectEntityConsumer<>(objectMapper, RequestData.class),
+ StringAsyncEntityConsumer::new);
+ final AtomicReference<Message<HttpResponse, RequestData>> resultRef = new AtomicReference<>();
+
+ responseConsumer.consumeResponse(
+ response,
+ new BasicEntityDetails(errorBody.length(), ContentType.APPLICATION_JSON),
+ HttpCoreContext.create(),
+ new FutureCallback<Message<HttpResponse, RequestData>>() {
+ @Override
+ public void completed(final Message<HttpResponse, RequestData> result) {
+ resultRef.set(result);
+ }
+
+ @Override
+ public void failed(final Exception ex) {
+ }
+
+ @Override
+ public void cancelled() {
+ }
+
+ });
+ responseConsumer.consume(ByteBuffer.wrap(errorBody.getBytes(StandardCharsets.UTF_8)));
+ responseConsumer.streamEnd(null);
+
+ Assertions.assertThat(resultRef.get()).isNotNull().satisfies(e -> {
+ Assertions.assertThat(e.getHead()).isSameAs(response);
+ Assertions.assertThat(e.getBody()).isNull();
+ Assertions.assertThat(e.error()).isEqualTo(errorBody);
+ });
+ }
+
+ @Test
+ void testResponseJsonTokenContentCorrectlyProcessed() throws Exception {
+ final JsonFactory jsonFactory = objectMapper.getFactory();
+ final JsonTokenConsumer mockJsonTokenConsumer = Mockito.mock(JsonTokenConsumer.class);
+
+ final AsyncResponseConsumer<Void> responseConsumer = new JsonSequenceResponseConsumer<>(
+ () -> new JsonTokenEntityConsumer(jsonFactory, mockJsonTokenConsumer),
+ StringAsyncEntityConsumer::new,
+ response -> {
+ },
+ error -> {
+ });
+
+ final BasicHttpResponse response = BasicResponseBuilder.create(200).build();
+
+ responseConsumer.consumeResponse(
+ response,
+ new BasicEntityDetails(-1, ContentType.APPLICATION_JSON),
+ HttpCoreContext.create(),
+ null);
+ final ByteBuffer data = ByteBuffer.wrap("{\"foo\":\"bar\"}".getBytes(StandardCharsets.UTF_8));
+ responseConsumer.consume(data);
+ responseConsumer.streamEnd(Collections.emptyList());
+ Mockito.verify(mockJsonTokenConsumer).accept(
+ Mockito.eq(JsonTokenId.ID_START_OBJECT), Mockito.any(JsonParser.class));
+ Mockito.verify(mockJsonTokenConsumer).accept(
+ Mockito.eq(JsonTokenId.ID_FIELD_NAME), Mockito.any(JsonParser.class));
+ Mockito.verify(mockJsonTokenConsumer).accept(
+ Mockito.eq(JsonTokenId.ID_STRING), Mockito.any(JsonParser.class));
+ Mockito.verify(mockJsonTokenConsumer).accept(
+ Mockito.eq(JsonTokenId.ID_END_OBJECT), Mockito.any(JsonParser.class));
+ Mockito.verify(mockJsonTokenConsumer).accept(
+ Mockito.eq(JsonTokenId.ID_NO_TOKEN), Mockito.any(JsonParser.class));
+ Mockito.verifyNoMoreInteractions(mockJsonTokenConsumer);
+ }
+
+}
diff --git a/httpcore5-jackson2/src/test/java/org/apache/hc/core5/jackson2/http/RequestData.java b/httpcore5-jackson2/src/test/java/org/apache/hc/core5/jackson2/http/RequestData.java
new file mode 100644
index 000000000..ffeb23dda
--- /dev/null
+++ b/httpcore5-jackson2/src/test/java/org/apache/hc/core5/jackson2/http/RequestData.java
@@ -0,0 +1,123 @@
+/*
+ * ====================================================================
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * <http://www.apache.org/>.
+ *
+ */
+package org.apache.hc.core5.jackson2.http;
+
+import java.net.URI;
+import java.util.Arrays;
+import java.util.Map;
+import java.util.stream.Collectors;
+
+import com.fasterxml.jackson.databind.JsonNode;
+
+import org.apache.hc.core5.http.Header;
+import org.apache.hc.core5.http.NameValuePair;
+
+public class RequestData {
+
+ private int id;
+ private URI url;
+ private String origin;
+ private Map<String, String> headers;
+ private Map<String, String> args;
+ private String data;
+ private JsonNode json;
+
+ public int getId() {
+ return id;
+ }
+
+ public void setId(final int id) {
+ this.id = id;
+ }
+
+ public URI getUrl() {
+ return url;
+ }
+
+ public void setUrl(final URI url) {
+ this.url = url;
+ }
+
+ public String getOrigin() {
+ return origin;
+ }
+
+ public void setOrigin(final String origin) {
+ this.origin = origin;
+ }
+
+ public Map<String, String> getHeaders() {
+ return headers;
+ }
+
+ public void setHeaders(final Map<String, String> headers) {
+ this.headers = headers;
+ }
+
+ public void generateHeaders(final Header... headers) {
+ this.headers = Arrays.stream(headers)
+ .collect(Collectors.toMap(NameValuePair::getName, NameValuePair::getValue));
+ }
+
+ public Map<String, String> getArgs() {
+ return args;
+ }
+
+ public void setArgs(final Map<String, String> args) {
+ this.args = args;
+ }
+
+ public String getData() {
+ return data;
+ }
+
+ public void setData(final String data) {
+ this.data = data;
+ }
+
+ public JsonNode getJson() {
+ return json;
+ }
+
+ public void setJson(final JsonNode json) {
+ this.json = json;
+ }
+
+ @Override
+ public String toString() {
+ return "RequestData{" +
+ "id=" + id +
+ ", url=" + url +
+ ", origin='" + origin + '\'' +
+ ", headers=" + headers +
+ ", args=" + args +
+ ", data='" + data + '\'' +
+ ", json=" + json +
+ '}';
+ }
+
+}
diff --git a/httpcore5-jackson2/src/test/java/org/apache/hc/core5/jackson2/http/WritableByteChannelMock.java b/httpcore5-jackson2/src/test/java/org/apache/hc/core5/jackson2/http/WritableByteChannelMock.java
new file mode 100644
index 000000000..4981cd302
--- /dev/null
+++ b/httpcore5-jackson2/src/test/java/org/apache/hc/core5/jackson2/http/WritableByteChannelMock.java
@@ -0,0 +1,125 @@
+/*
+ * ====================================================================
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * <http://www.apache.org/>.
+ *
+ */
+
+package org.apache.hc.core5.jackson2.http;
+
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.nio.CharBuffer;
+import java.nio.channels.ClosedChannelException;
+import java.nio.channels.WritableByteChannel;
+import java.nio.charset.CharacterCodingException;
+import java.nio.charset.Charset;
+
+public class WritableByteChannelMock implements WritableByteChannel {
+
+ private final int capacityLimit;
+
+ private int capacityUsed;
+ private ByteBuffer buf;
+ private boolean closed;
+
+ public WritableByteChannelMock(final int initialSize, final int capacityLimit) {
+ this.buf = ByteBuffer.allocate(initialSize);
+ this.capacityLimit = capacityLimit;
+ }
+
+ public WritableByteChannelMock(final int initialSize) {
+ this(initialSize, 0);
+ }
+
+ private void expandCapacity(final int capacity) {
+ final ByteBuffer oldbuffer = this.buf;
+ this.buf = ByteBuffer.allocate(capacity);
+ oldbuffer.flip();
+ this.buf.put(oldbuffer);
+ }
+
+ private void ensureCapacity(final int requiredCapacity) {
+ if (requiredCapacity > this.buf.capacity()) {
+ expandCapacity(requiredCapacity);
+ }
+ }
+
+ @Override
+ public int write(final ByteBuffer src) throws IOException {
+ if (this.closed) {
+ throw new ClosedChannelException();
+ }
+ final int len = src.remaining();
+ ensureCapacity(this.buf.position() + len);
+ if (this.capacityLimit > 0) {
+ final int chunk = Math.min(this.capacityLimit - this.capacityUsed, len);
+ if (chunk > 0) {
+ final int limit = src.limit();
+ src.limit(src.position() + chunk);
+ this.buf.put(src);
+ src.limit(limit);
+ this.capacityUsed += chunk;
+ return chunk;
+ }
+ return 0;
+ }
+ this.buf.put(src);
+ return len;
+ }
+
+ @Override
+ public boolean isOpen() {
+ return !this.closed;
+ }
+
+ @Override
+ public void close() throws IOException {
+ this.closed = true;
+ }
+
+ public void flush() {
+ this.capacityUsed = 0;
+ }
+
+ public void reset() {
+ this.capacityUsed = 0;
+ this.buf.clear();
+ }
+
+ public byte[] toByteArray() {
+ final ByteBuffer dup = this.buf.duplicate();
+ dup.flip();
+ final byte[] bytes = new byte[dup.remaining()];
+ dup.get(bytes);
+ return bytes;
+ }
+
+ public String dump(final Charset charset) throws CharacterCodingException {
+ this.buf.flip();
+ final CharBuffer charBuffer = charset.newDecoder().decode(this.buf);
+ this.buf.compact();
+ return charBuffer.toString();
+ }
+
+}
diff --git a/httpcore5-jackson2/src/test/java/org/apache/hc/core5/jackson2/http/examles/JsonBulkArrayReaderExample.java b/httpcore5-jackson2/src/test/java/org/apache/hc/core5/jackson2/http/examles/JsonBulkArrayReaderExample.java
new file mode 100644
index 000000000..eb5fdc0d9
--- /dev/null
+++ b/httpcore5-jackson2/src/test/java/org/apache/hc/core5/jackson2/http/examles/JsonBulkArrayReaderExample.java
@@ -0,0 +1,61 @@
+/*
+ * ====================================================================
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * <http://www.apache.org/>.
+ *
+ */
+package org.apache.hc.core5.jackson2.http.examles;
+
+import java.io.InputStream;
+import java.net.URL;
+import java.nio.ByteBuffer;
+
+import com.fasterxml.jackson.core.JsonFactory;
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+import org.apache.hc.core5.jackson2.bulk.JsonBulkArrayReader;
+import org.apache.hc.core5.jackson2.http.RequestData;
+
+public class JsonBulkArrayReaderExample {
+
+ public static void main(final String... args) throws Exception {
+ final JsonFactory factory = new JsonFactory();
+ final ObjectMapper objectMapper = new ObjectMapper(factory);
+
+ final URL resource = JsonBulkArrayReaderExample.class.getResource("/sample6.json");
+
+ final JsonBulkArrayReader bulkArrayReader = new JsonBulkArrayReader(objectMapper);
+ bulkArrayReader.initialize(new TypeReference<RequestData>() {
+ }, entry -> System.out.println(entry));
+ try (final InputStream inputStream = resource.openStream()) {
+ int l;
+ final byte[] tmp = new byte[4096];
+ while ((l = inputStream.read(tmp)) != -1) {
+ bulkArrayReader.consume(ByteBuffer.wrap(tmp, 0, l));
+ }
+ bulkArrayReader.streamEnd();
+ }
+ }
+
+}
diff --git a/httpcore5-jackson2/src/test/java/org/apache/hc/core5/jackson2/http/examles/JsonNodeResponseExample.java b/httpcore5-jackson2/src/test/java/org/apache/hc/core5/jackson2/http/examles/JsonNodeResponseExample.java
new file mode 100644
index 000000000..7cc9bd311
--- /dev/null
+++ b/httpcore5-jackson2/src/test/java/org/apache/hc/core5/jackson2/http/examles/JsonNodeResponseExample.java
@@ -0,0 +1,104 @@
+/*
+ * ====================================================================
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * <http://www.apache.org/>.
+ *
+ */
+package org.apache.hc.core5.jackson2.http.examles;
+
+import java.net.URI;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+
+import com.fasterxml.jackson.core.JsonFactory;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+import org.apache.hc.core5.concurrent.FutureCallback;
+import org.apache.hc.core5.http.ContentType;
+import org.apache.hc.core5.http.HttpHeaders;
+import org.apache.hc.core5.http.HttpResponse;
+import org.apache.hc.core5.http.Message;
+import org.apache.hc.core5.http.impl.bootstrap.AsyncRequesterBootstrap;
+import org.apache.hc.core5.http.impl.bootstrap.HttpAsyncRequester;
+import org.apache.hc.core5.http.nio.support.AsyncRequestBuilder;
+import org.apache.hc.core5.io.CloseMode;
+import org.apache.hc.core5.jackson2.http.JsonResponseConsumers;
+import org.apache.hc.core5.reactor.IOReactorConfig;
+import org.apache.hc.core5.util.Timeout;
+
+public class JsonNodeResponseExample {
+
+ public static void main(final String... args) throws Exception {
+ final IOReactorConfig ioReactorConfig = IOReactorConfig.custom()
+ .setSoTimeout(5, TimeUnit.SECONDS)
+ .build();
+
+ // Create and start requester
+ final HttpAsyncRequester requester = AsyncRequesterBootstrap.bootstrap()
+ .setIOReactorConfig(ioReactorConfig)
+ .create();
+
+ Runtime.getRuntime().addShutdownHook(new Thread(() -> {
+ System.out.println("HTTP requester shutting down");
+ requester.close(CloseMode.GRACEFUL);
+ }));
+ requester.start();
+
+ final URI uri = URI.create("http://httpbin.org/get");
+
+ final JsonFactory factory = new JsonFactory();
+ final ObjectMapper objectMapper = new ObjectMapper(factory);
+
+ System.out.println("Executing GET " + uri);
+ final Future<?> future = requester.execute(
+ AsyncRequestBuilder.get(uri)
+ .addHeader(HttpHeaders.ACCEPT, ContentType.APPLICATION_JSON.toString())
+ .build(),
+ JsonResponseConsumers.create(objectMapper.getFactory()),
+ Timeout.ofMinutes(1),
+ new FutureCallback<Message<HttpResponse, JsonNode>>() {
+
+ @Override
+ public void completed(final Message<HttpResponse, JsonNode> message) {
+ System.out.println("Response status: " + message.getHead().getCode());
+ System.out.println(message.getBody());
+ }
+
+ @Override
+ public void failed(final Exception ex) {
+ ex.printStackTrace(System.out);
+ }
+
+ @Override
+ public void cancelled() {
+ }
+
+ });
+ future.get();
+
+ System.out.println("Shutting down I/O reactor");
+ requester.initiateShutdown();
+ }
+
+}
diff --git a/httpcore5-jackson2/src/test/java/org/apache/hc/core5/jackson2/http/examles/JsonObjectRequestExample.java b/httpcore5-jackson2/src/test/java/org/apache/hc/core5/jackson2/http/examles/JsonObjectRequestExample.java
new file mode 100644
index 000000000..6513f8dd6
--- /dev/null
+++ b/httpcore5-jackson2/src/test/java/org/apache/hc/core5/jackson2/http/examles/JsonObjectRequestExample.java
@@ -0,0 +1,111 @@
+/*
+ * ====================================================================
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * <http://www.apache.org/>.
+ *
+ */
+package org.apache.hc.core5.jackson2.http.examles;
+
+import java.net.URI;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+
+import com.fasterxml.jackson.core.JsonFactory;
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+import org.apache.hc.core5.concurrent.FutureCallback;
+import org.apache.hc.core5.http.ContentType;
+import org.apache.hc.core5.http.HttpHeaders;
+import org.apache.hc.core5.http.HttpResponse;
+import org.apache.hc.core5.http.Message;
+import org.apache.hc.core5.http.impl.bootstrap.AsyncRequesterBootstrap;
+import org.apache.hc.core5.http.impl.bootstrap.HttpAsyncRequester;
+import org.apache.hc.core5.http.message.BasicNameValuePair;
+import org.apache.hc.core5.http.nio.support.AsyncRequestBuilder;
+import org.apache.hc.core5.io.CloseMode;
+import org.apache.hc.core5.jackson2.http.JsonObjectEntityProducer;
+import org.apache.hc.core5.jackson2.http.JsonResponseConsumers;
+import org.apache.hc.core5.jackson2.http.RequestData;
+import org.apache.hc.core5.reactor.IOReactorConfig;
+import org.apache.hc.core5.util.Timeout;
+
+public class JsonObjectRequestExample {
+
+ public static void main(final String... args) throws Exception {
+ final IOReactorConfig ioReactorConfig = IOReactorConfig.custom()
+ .setSoTimeout(5, TimeUnit.SECONDS)
+ .build();
+
+ // Create and start requester
+ final HttpAsyncRequester requester = AsyncRequesterBootstrap.bootstrap()
+ .setIOReactorConfig(ioReactorConfig)
+ .create();
+
+ Runtime.getRuntime().addShutdownHook(new Thread(() -> {
+ System.out.println("HTTP requester shutting down");
+ requester.close(CloseMode.GRACEFUL);
+ }));
+ requester.start();
+
+ final URI uri = URI.create("http://httpbin.org/post");
+
+ System.out.println("Executing POST " + uri);
+ final JsonFactory factory = new JsonFactory();
+ final ObjectMapper objectMapper = new ObjectMapper(factory);
+ objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+
+ final Future<?> future = requester.execute(
+ AsyncRequestBuilder.post(uri)
+ .addHeader(HttpHeaders.ACCEPT, ContentType.APPLICATION_JSON.toString())
+ .setEntity(new JsonObjectEntityProducer<>(
+ new BasicNameValuePair("name", "value"),
+ objectMapper))
+ .build(),
+ JsonResponseConsumers.create(objectMapper, RequestData.class),
+ Timeout.ofMinutes(1),
+ new FutureCallback<Message<HttpResponse, RequestData>>() {
+
+ @Override
+ public void completed(final Message<HttpResponse, RequestData> message) {
+ System.out.println("Response status: " + message.getHead().getCode());
+ System.out.println(message.getBody());
+ }
+
+ @Override
+ public void failed(final Exception ex) {
+ ex.printStackTrace(System.out);
+ }
+
+ @Override
+ public void cancelled() {
+ }
+
+ });
+ future.get();
+
+ System.out.println("Shutting down I/O reactor");
+ requester.initiateShutdown();
+ }
+
+}
diff --git a/httpcore5-jackson2/src/test/java/org/apache/hc/core5/jackson2/http/examles/JsonSequenceRequestExample.java b/httpcore5-jackson2/src/test/java/org/apache/hc/core5/jackson2/http/examles/JsonSequenceRequestExample.java
new file mode 100644
index 000000000..d962a5aec
--- /dev/null
+++ b/httpcore5-jackson2/src/test/java/org/apache/hc/core5/jackson2/http/examles/JsonSequenceRequestExample.java
@@ -0,0 +1,114 @@
+/*
+ * ====================================================================
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * <http://www.apache.org/>.
+ *
+ */
+package org.apache.hc.core5.jackson2.http.examles;
+
+import java.net.URI;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+
+import com.fasterxml.jackson.core.JsonFactory;
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+import org.apache.hc.core5.concurrent.FutureCallback;
+import org.apache.hc.core5.http.ContentType;
+import org.apache.hc.core5.http.HttpHeaders;
+import org.apache.hc.core5.http.HttpResponse;
+import org.apache.hc.core5.http.Message;
+import org.apache.hc.core5.http.impl.bootstrap.AsyncRequesterBootstrap;
+import org.apache.hc.core5.http.impl.bootstrap.HttpAsyncRequester;
+import org.apache.hc.core5.http.message.BasicNameValuePair;
+import org.apache.hc.core5.http.nio.support.AsyncRequestBuilder;
+import org.apache.hc.core5.io.CloseMode;
+import org.apache.hc.core5.jackson2.http.JsonResponseConsumers;
+import org.apache.hc.core5.jackson2.http.JsonSequenceEntityProducer;
+import org.apache.hc.core5.jackson2.http.RequestData;
+import org.apache.hc.core5.reactor.IOReactorConfig;
+import org.apache.hc.core5.util.Timeout;
+
+public class JsonSequenceRequestExample {
+
+ public static void main(final String... args) throws Exception {
+ final IOReactorConfig ioReactorConfig = IOReactorConfig.custom()
+ .setSoTimeout(5, TimeUnit.SECONDS)
+ .build();
+
+ // Create and start requester
+ final HttpAsyncRequester requester = AsyncRequesterBootstrap.bootstrap()
+ .setIOReactorConfig(ioReactorConfig)
+ .create();
+
+ Runtime.getRuntime().addShutdownHook(new Thread(() -> {
+ System.out.println("HTTP requester shutting down");
+ requester.close(CloseMode.GRACEFUL);
+ }));
+ requester.start();
+
+ final URI uri = URI.create("http://httpbin.org/post");
+
+ final JsonFactory factory = new JsonFactory();
+ final ObjectMapper objectMapper = new ObjectMapper(factory);
+ objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+
+ System.out.println("Executing POST " + uri);
+ final Future<?> future = requester.execute(
+ AsyncRequestBuilder.post(uri)
+ .addHeader(HttpHeaders.ACCEPT, ContentType.APPLICATION_JSON.toString())
+ .setEntity(new JsonSequenceEntityProducer<>(objectMapper, channel -> {
+ channel.write(new BasicNameValuePair("name1", "value1"));
+ channel.write(new BasicNameValuePair("name2", "value2"));
+ channel.write(new BasicNameValuePair("name3", "value3"));
+ channel.endStream();
+ }))
+ .build(),
+ JsonResponseConsumers.create(objectMapper, RequestData.class),
+ Timeout.ofMinutes(1),
+ new FutureCallback<Message<HttpResponse, RequestData>>() {
+
+ @Override
+ public void completed(final Message<HttpResponse, RequestData> message) {
+ System.out.println("Response status: " + message.getHead().getCode());
+ System.out.println(message.getBody());
+ }
+
+ @Override
+ public void failed(final Exception ex) {
+ ex.printStackTrace(System.out);
+ }
+
+ @Override
+ public void cancelled() {
+ }
+
+ });
+ future.get();
+
+ System.out.println("Shutting down I/O reactor");
+ requester.initiateShutdown();
+ }
+
+}
diff --git a/httpcore5-jackson2/src/test/java/org/apache/hc/core5/jackson2/http/examles/JsonSequenceResponseExample.java b/httpcore5-jackson2/src/test/java/org/apache/hc/core5/jackson2/http/examles/JsonSequenceResponseExample.java
new file mode 100644
index 000000000..e8ed92b9e
--- /dev/null
+++ b/httpcore5-jackson2/src/test/java/org/apache/hc/core5/jackson2/http/examles/JsonSequenceResponseExample.java
@@ -0,0 +1,106 @@
+/*
+ * ====================================================================
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * <http://www.apache.org/>.
+ *
+ */
+package org.apache.hc.core5.jackson2.http.examles;
+
+import java.net.URI;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+
+import com.fasterxml.jackson.core.JsonFactory;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+import org.apache.hc.core5.concurrent.FutureCallback;
+import org.apache.hc.core5.http.ContentType;
+import org.apache.hc.core5.http.HttpHeaders;
+import org.apache.hc.core5.http.impl.bootstrap.AsyncRequesterBootstrap;
+import org.apache.hc.core5.http.impl.bootstrap.HttpAsyncRequester;
+import org.apache.hc.core5.http.nio.support.AsyncRequestBuilder;
+import org.apache.hc.core5.io.CloseMode;
+import org.apache.hc.core5.jackson2.http.JsonResponseConsumers;
+import org.apache.hc.core5.jackson2.http.RequestData;
+import org.apache.hc.core5.reactor.IOReactorConfig;
+import org.apache.hc.core5.util.Timeout;
+
+public class JsonSequenceResponseExample {
+
+ public static void main(final String... args) throws Exception {
+ final IOReactorConfig ioReactorConfig = IOReactorConfig.custom()
+ .setSoTimeout(5, TimeUnit.SECONDS)
+ .build();
+
+ // Create and start requester
+ final HttpAsyncRequester requester = AsyncRequesterBootstrap.bootstrap()
+ .setIOReactorConfig(ioReactorConfig)
+ .create();
+
+ Runtime.getRuntime().addShutdownHook(new Thread(() -> {
+ System.out.println("HTTP requester shutting down");
+ requester.close(CloseMode.GRACEFUL);
+ }));
+ requester.start();
+
+ final URI uri = URI.create("http://httpbin.org/stream/5");
+
+ final JsonFactory factory = new JsonFactory();
+ final ObjectMapper objectMapper = new ObjectMapper(factory);
+
+ System.out.println("Executing GET " + uri);
+ final Future<?> future = requester.execute(
+ AsyncRequestBuilder.get(uri)
+ .addHeader(HttpHeaders.ACCEPT, ContentType.APPLICATION_JSON.toString())
+ .build(),
+ JsonResponseConsumers.create(
+ objectMapper,
+ RequestData.class,
+ messageHead -> System.out.println("Response status: " + messageHead.getCode()),
+ error -> System.out.println("Error: " + error),
+ requestData -> System.out.println(requestData)),
+ Timeout.ofMinutes(1),
+ new FutureCallback<Long>() {
+
+ @Override
+ public void completed(final Long count) {
+ System.out.println("Objects received: " + count);
+ }
+
+ @Override
+ public void failed(final Exception ex) {
+ ex.printStackTrace(System.out);
+ }
+
+ @Override
+ public void cancelled() {
+ }
+
+ });
+ future.get();
+
+ System.out.println("Shutting down I/O reactor");
+ requester.initiateShutdown();
+ }
+
+}
diff --git a/httpcore5-jackson2/src/test/java/org/apache/hc/core5/jackson2/http/examles/JsonTokenEventResponseExample.java b/httpcore5-jackson2/src/test/java/org/apache/hc/core5/jackson2/http/examles/JsonTokenEventResponseExample.java
new file mode 100644
index 000000000..8bad326d4
--- /dev/null
+++ b/httpcore5-jackson2/src/test/java/org/apache/hc/core5/jackson2/http/examles/JsonTokenEventResponseExample.java
@@ -0,0 +1,172 @@
+/*
+ * ====================================================================
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * <http://www.apache.org/>.
+ *
+ */
+package org.apache.hc.core5.jackson2.http.examles;
+
+import java.net.URI;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+
+import com.fasterxml.jackson.core.JsonFactory;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+import org.apache.hc.core5.concurrent.FutureCallback;
+import org.apache.hc.core5.http.ContentType;
+import org.apache.hc.core5.http.HttpHeaders;
+import org.apache.hc.core5.http.impl.bootstrap.AsyncRequesterBootstrap;
+import org.apache.hc.core5.http.impl.bootstrap.HttpAsyncRequester;
+import org.apache.hc.core5.http.nio.support.AsyncRequestBuilder;
+import org.apache.hc.core5.io.CloseMode;
+import org.apache.hc.core5.jackson2.JsonTokenEventHandler;
+import org.apache.hc.core5.jackson2.http.JsonResponseConsumers;
+import org.apache.hc.core5.reactor.IOReactorConfig;
+import org.apache.hc.core5.util.Timeout;
+
+public class JsonTokenEventResponseExample {
+
+ public static void main(final String... args) throws Exception {
+ final IOReactorConfig ioReactorConfig = IOReactorConfig.custom()
+ .setSoTimeout(5, TimeUnit.SECONDS)
+ .build();
+
+ // Create and start requester
+ final HttpAsyncRequester requester = AsyncRequesterBootstrap.bootstrap()
+ .setIOReactorConfig(ioReactorConfig)
+ .create();
+
+ Runtime.getRuntime().addShutdownHook(new Thread(() -> {
+ System.out.println("HTTP requester shutting down");
+ requester.close(CloseMode.GRACEFUL);
+ }));
+ requester.start();
+
+ final URI uri = URI.create("http://httpbin.org/get");
+
+ System.out.println("Executing GET " + uri);
+ final JsonFactory factory = new JsonFactory();
+ final ObjectMapper objectMapper = new ObjectMapper(factory);
+
+ final Future<?> future = requester.execute(
+ AsyncRequestBuilder.get(uri)
+ .addHeader(HttpHeaders.ACCEPT, ContentType.APPLICATION_JSON.toString())
+ .build(),
+ JsonResponseConsumers.create(
+ objectMapper.getFactory(),
+ messageHead -> System.out.println("Response status: " + messageHead.getCode()),
+ error -> System.out.println("Error: " + error),
+ new JsonTokenEventHandler() {
+
+ @Override
+ public void objectStart() {
+ System.out.print("object start/");
+ }
+
+ @Override
+ public void objectEnd() {
+ System.out.print("object end/");
+ }
+
+ @Override
+ public void arrayStart() {
+ System.out.print("array start/");
+ }
+
+ @Override
+ public void arrayEnd() {
+ System.out.print("array end/");
+ }
+
+ @Override
+ public void field(final String name) {
+ System.out.print(name + "=");
+ }
+
+ @Override
+ public void embeddedObject(final Object object) {
+ System.out.print(object + "/");
+ }
+
+ @Override
+ public void value(final String value) {
+ System.out.print("\"" + value + "\"/");
+ }
+
+ @Override
+ public void value(final int value) {
+ System.out.print(value + "/");
+ }
+
+ @Override
+ public void value(final long value) {
+ System.out.print(value + "/");
+ }
+
+ @Override
+ public void value(final double value) {
+ System.out.print(value + "/");
+ }
+
+ @Override
+ public void value(final boolean value) {
+ System.out.print(value + "/");
+ }
+
+ @Override
+ public void valueNull() {
+ System.out.print("null/");
+ }
+
+ @Override
+ public void endOfStream() {
+ System.out.println("stream end/");
+ }
+
+ }),
+ Timeout.ofMinutes(1),
+ new FutureCallback<Void>() {
+
+ @Override
+ public void completed(final Void input) {
+ System.out.println("Object received");
+ }
+
+ @Override
+ public void failed(final Exception ex) {
+ ex.printStackTrace(System.out);
+ }
+
+ @Override
+ public void cancelled() {
+ }
+
+ });
+ future.get();
+
+ System.out.println("Shutting down I/O reactor");
+ requester.initiateShutdown();
+ }
+
+}
diff --git a/httpcore5-jackson2/src/test/resources/sample1.json b/httpcore5-jackson2/src/test/resources/sample1.json
new file mode 100644
index 000000000..0db001e70
--- /dev/null
+++ b/httpcore5-jackson2/src/test/resources/sample1.json
@@ -0,0 +1,15 @@
+{
+ "args": {},
+ "headers": {
+ "Accept": "application/json",
+ "Accept-Encoding": "gzip, deflate",
+ "Accept-Language": "en-US,en;q=0.9",
+ "Connection": "close",
+ "Cookie": "_gauges_unique_year=1; _gauges_unique=1; _gauges_unique_hour=1; _gauges_unique_day=1; _gauges_unique_month=1",
+ "Host": "httpbin.org",
+ "Referer": "http://httpbin.org/",
+ "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) snap Chromium/71.0.3578.98 Chrome/71.0.3578.98 Safari/537.36"
+ },
+ "origin": "xxx.xxx.xxx.xxx",
+ "url": "http://httpbin.org/get"
+}
\ No newline at end of file
diff --git a/httpcore5-jackson2/src/test/resources/sample2.json b/httpcore5-jackson2/src/test/resources/sample2.json
new file mode 100644
index 000000000..eb2daed99
--- /dev/null
+++ b/httpcore5-jackson2/src/test/resources/sample2.json
@@ -0,0 +1,35 @@
+[
+ [
+ 1,
+ 2,
+ 3
+ ],
+ [
+ 1.1,
+ 2.2,
+ 3.3
+ ],
+ [
+ {
+ "name1": "value1"
+ },
+ {
+ "name2": "value2"
+ },
+ {
+ "name3": "value3"
+ }
+ ],
+ [
+ 2,
+ 2.2,
+ {
+ "name2": "value2"
+ }
+ ],
+ [
+ {
+ "long": 2153599188
+ }
+ ]
+]
diff --git a/httpcore5-jackson2/src/test/resources/sample3.json b/httpcore5-jackson2/src/test/resources/sample3.json
new file mode 100644
index 000000000..7e54bce71
--- /dev/null
+++ b/httpcore5-jackson2/src/test/resources/sample3.json
@@ -0,0 +1,48 @@
+{
+ "url": "http://httpbin.org/stream/3",
+ "args": {},
+ "headers": {
+ "Host": "httpbin.org",
+ "Connection": "close",
+ "Referer": "http://httpbin.org/",
+ "Accept": "application/json",
+ "Accept-Encoding": "gzip, deflate",
+ "Accept-Language": "en-US,en;q=0.9",
+ "Cookie": "_gauges_unique_year=1; _gauges_unique=1; _gauges_unique_month=1; _gauges_unique_day=1; _gauges_unique_hour=1",
+ "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) snap Chromium/71.0.3578.98 Chrome/71.0.3578.98 Safari/537.36"
+ },
+ "origin": "xxx.xxx.xxx.xxx",
+ "id": 0
+}
+{
+ "url": "http://httpbin.org/stream/3",
+ "args": {},
+ "headers": {
+ "Host": "httpbin.org",
+ "Connection": "close",
+ "Referer": "http://httpbin.org/",
+ "Accept": "application/json",
+ "Accept-Encoding": "gzip, deflate",
+ "Accept-Language": "en-US,en;q=0.9",
+ "Cookie": "_gauges_unique_year=1; _gauges_unique=1; _gauges_unique_month=1; _gauges_unique_day=1; _gauges_unique_hour=1",
+ "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) snap Chromium/71.0.3578.98 Chrome/71.0.3578.98 Safari/537.36"
+ },
+ "origin": "xxx.xxx.xxx.xxx",
+ "id": 1
+}
+{
+ "url": "http://httpbin.org/stream/3",
+ "args": {},
+ "headers": {
+ "Host": "httpbin.org",
+ "Connection": "close",
+ "Referer": "http://httpbin.org/",
+ "Accept": "application/json",
+ "Accept-Encoding": "gzip, deflate",
+ "Accept-Language": "en-US,en;q=0.9",
+ "Cookie": "_gauges_unique_year=1; _gauges_unique=1; _gauges_unique_month=1; _gauges_unique_day=1; _gauges_unique_hour=1",
+ "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) snap Chromium/71.0.3578.98 Chrome/71.0.3578.98 Safari/537.36"
+ },
+ "origin": "xxx.xxx.xxx.xxx",
+ "id": 2
+}
\ No newline at end of file
diff --git a/httpcore5-jackson2/src/test/resources/sample4.json b/httpcore5-jackson2/src/test/resources/sample4.json
new file mode 100644
index 000000000..ad3e0624d
--- /dev/null
+++ b/httpcore5-jackson2/src/test/resources/sample4.json
@@ -0,0 +1 @@
+[ "1", "2", "3", "4" ]
\ No newline at end of file
diff --git a/httpcore5-jackson2/src/test/resources/sample5.json b/httpcore5-jackson2/src/test/resources/sample5.json
new file mode 100644
index 000000000..a59347b73
--- /dev/null
+++ b/httpcore5-jackson2/src/test/resources/sample5.json
@@ -0,0 +1,3 @@
+[ "1", "2", "3", "4" ]
+[ "5", "6", "7", "8" ]
+[ "9", "10", "11", "12" ]
\ No newline at end of file
diff --git a/httpcore5-jackson2/src/test/resources/sample6.json b/httpcore5-jackson2/src/test/resources/sample6.json
new file mode 100644
index 000000000..65b0284c4
--- /dev/null
+++ b/httpcore5-jackson2/src/test/resources/sample6.json
@@ -0,0 +1,50 @@
+[
+ {
+ "url": "http://httpbin.org/stream/3",
+ "args": {},
+ "headers": {
+ "Host": "httpbin.org",
+ "Connection": "close",
+ "Referer": "http://httpbin.org/",
+ "Accept": "application/json",
+ "Accept-Encoding": "gzip, deflate",
+ "Accept-Language": "en-US,en;q=0.9",
+ "Cookie": "_gauges_unique_year=1; _gauges_unique=1; _gauges_unique_month=1; _gauges_unique_day=1; _gauges_unique_hour=1",
+ "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) snap Chromium/71.0.3578.98 Chrome/71.0.3578.98 Safari/537.36"
+ },
+ "origin": "xxx.xxx.xxx.xxx",
+ "id": 0
+ },
+ {
+ "url": "http://httpbin.org/stream/3",
+ "args": {},
+ "headers": {
+ "Host": "httpbin.org",
+ "Connection": "close",
+ "Referer": "http://httpbin.org/",
+ "Accept": "application/json",
+ "Accept-Encoding": "gzip, deflate",
+ "Accept-Language": "en-US,en;q=0.9",
+ "Cookie": "_gauges_unique_year=1; _gauges_unique=1; _gauges_unique_month=1; _gauges_unique_day=1; _gauges_unique_hour=1",
+ "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) snap Chromium/71.0.3578.98 Chrome/71.0.3578.98 Safari/537.36"
+ },
+ "origin": "xxx.xxx.xxx.xxx",
+ "id": 1
+ },
+ {
+ "url": "http://httpbin.org/stream/3",
+ "args": {},
+ "headers": {
+ "Host": "httpbin.org",
+ "Connection": "close",
+ "Referer": "http://httpbin.org/",
+ "Accept": "application/json",
+ "Accept-Encoding": "gzip, deflate",
+ "Accept-Language": "en-US,en;q=0.9",
+ "Cookie": "_gauges_unique_year=1; _gauges_unique=1; _gauges_unique_month=1; _gauges_unique_day=1; _gauges_unique_hour=1",
+ "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) snap Chromium/71.0.3578.98 Chrome/71.0.3578.98 Safari/537.36"
+ },
+ "origin": "xxx.xxx.xxx.xxx",
+ "id": 2
+ }
+]
\ No newline at end of file
diff --git a/httpcore5-jackson2/src/test/resources/sample7.json b/httpcore5-jackson2/src/test/resources/sample7.json
new file mode 100644
index 000000000..76b96a5d3
--- /dev/null
+++ b/httpcore5-jackson2/src/test/resources/sample7.json
@@ -0,0 +1,19 @@
+{
+ "args": {},
+ "headers": {
+ "Accept": "application/json",
+ "Accept-Encoding": "gzip, deflate",
+ "Accept-Language": "en-US,en;q=0.9",
+ "Connection": "close",
+ "Cookie": "_gauges_unique_year=1; _gauges_unique=1; _gauges_unique_hour=1; _gauges_unique_day=1; _gauges_unique_month=1",
+ "Host": "httpbin.org",
+ "Referer": "http://httpbin.org/",
+ "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) snap Chromium/71.0.3578.98 Chrome/71.0.3578.98 Safari/537.36"
+ },
+ "origin": "xxx.xxx.xxx.xxx",
+ "url": "http://httpbin.org/get"
+}
+{"value": "Some text"}
+["1", "2", "3"]
+[1, 2, 3]
+[{"value": "Some text"}, {"value": "Some other text"}]
diff --git a/httpcore5/src/main/java/org/apache/hc/core5/http/Message.java b/httpcore5/src/main/java/org/apache/hc/core5/http/Message.java
index b60d9724b..cfd3df063 100644
--- a/httpcore5/src/main/java/org/apache/hc/core5/http/Message.java
+++ b/httpcore5/src/main/java/org/apache/hc/core5/http/Message.java
@@ -41,6 +41,7 @@ public final class Message<H extends MessageHeaders, B> {
private final H head;
private final B body;
+ private final Object error;
/**
* Constructs a new instance.
@@ -49,7 +50,7 @@ public final class Message<H extends MessageHeaders, B> {
* @since 5.3
*/
public Message(final H head) {
- this(head, null);
+ this(head, null, null);
}
/**
@@ -59,8 +60,19 @@ public Message(final H head) {
* @param body The message body.
*/
public Message(final H head, final B body) {
+ this(head, body, null);
+ }
+
+ /**
+ * Constructs a new instance.
+ *
+ * @param head The message head.
+ * @param body The message body.
+ */
+ public Message(final H head, final B body, final Object error) {
this.head = Args.notNull(head, "Message head");
this.body = body;
+ this.error = error;
}
/**
@@ -81,9 +93,16 @@ public B getBody() {
return body;
}
+ /**
+ * @since 5.5
+ */
+ public Object error() {
+ return error;
+ }
+
@Override
public String toString() {
- return "[head=" + head + ", body=" + body + ']';
+ return "[head=" + head + ", body=" + body + ", error=" + error + ']';
}
}
diff --git a/pom.xml b/pom.xml
index 224f1fd01..a88a5a8bc 100644
--- a/pom.xml
+++ b/pom.xml
@@ -63,6 +63,7 @@
<module>httpcore5</module>
<module>httpcore5-h2</module>
<module>httpcore5-reactive</module>
+ <module>httpcore5-jackson2</module>
<module>httpcore5-testing</module>
</modules>
@@ -76,6 +77,7 @@
<hamcrest.version>3.0</hamcrest.version>
<junit.migrationsupport.version>5.0.0</junit.migrationsupport.version>
<mockito.version>4.11.0</mockito.version>
+ <assertj.version>3.27.6</assertj.version>
<slf4j.version>1.7.36</slf4j.version>
<log4j.version>2.25.3</log4j.version>
<rxjava3.version>3.1.12</rxjava3.version>
@@ -102,6 +104,11 @@
<artifactId>httpcore5-reactive</artifactId>
<version>${project.version}</version>
</dependency>
+ <dependency>
+ <groupId>org.apache.httpcomponents.core5</groupId>
+ <artifactId>httpcore5-jackson2</artifactId>
+ <version>${project.version}</version>
+ </dependency>
<dependency>
<groupId>org.apache.httpcomponents.core5</groupId>
<artifactId>httpcore5-testing</artifactId>
@@ -137,6 +144,11 @@
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
+ <dependency>
+ <groupId>org.assertj</groupId>
+ <artifactId>assertj-core</artifactId>
+ <version>${assertj.version}</version>
+ </dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>