This is an automated email from the ASF dual-hosted git repository.

davsclaus pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git


The following commit(s) were added to refs/heads/main by this push:
     new 9483eb826958 CAMEL-27327: camel-mongodb - Read InputStream and 
StreamCache List bodies as text, and accept a JSON array with surrounding 
whitespace (#30917)
9483eb826958 is described below

commit 9483eb82695807675a062c96b3b83da0a69ebad1
Author: Ayush Kulshreshtha <[email protected]>
AuthorDate: Sat Nov 28 00:25:08 2026 +0530

    CAMEL-27327: camel-mongodb - Read InputStream and StreamCache List bodies 
as text, and accept a JSON array with surrounding whitespace (#30917)
    
    Follow-up of CAMEL-27194:
    
    - getBsonListBody, used by update and findOneAndUpdate without the criteria
      header and by aggregate, now also reads an InputStream or StreamCache body
      as text, as from platform-http or a file consumer with stream caching.
    - MongoDbBasicConverters.isArrayNotation strips surrounding whitespace, so a
      JSON array that ends with a newline, as in a file or a Kafka record, is
      seen as an array.
    - update and findOneAndUpdate without the criteria header fail with their
      "not a List of Document objects with size = 2" error, instead of a
      NullPointerException, when the body does not convert to a List, as a
      String that is not a JSON array.
    - The component docs say that the update and aggregate bodies can be a JSON
      array as text, with a YAML aggregate example (catalog copy updated).
    
    CAMEL-27327: Read the List body as text once, and use BodyFacts to detect a 
payload body
    
    Address review:
    - aggregate read an InputStream or StreamCache body as text for the 
pipeline,
      then converted the consumed stream again for the single-stage fallback,
      which failed at the end of the stream. The text is now read once and both
      conversions use it.
    - A payload body other than a String is detected with BodyFacts.kindOf, so a
      File or GenericFile body from a file consumer, a Reader and the other
      payload types are read as text too.
    - Tests for a single-stage StreamCache aggregate, a File update body, and a
      plain InputStream body on a route without stream caching.
    
    CAMEL-27327: Restore LF line endings in MongoDbProducerListBodyTest and 
describe the body types it covers
    
    Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
 .../camel/catalog/docs/mongodb-component.adoc      | 25 +++++++
 .../src/main/docs/mongodb-component.adoc           | 25 +++++++
 .../camel/component/mongodb/MongoDbProducer.java   | 43 +++++++++--
 .../mongodb/converters/MongoDbBasicConverters.java |  8 +-
 .../mongodb/MongoDbProducerListBodyTest.java       | 86 +++++++++++++++++++++-
 5 files changed, 174 insertions(+), 13 deletions(-)

diff --git 
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/mongodb-component.adoc
 
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/mongodb-component.adoc
index fa0761d02597..dd5b82861948 100644
--- 
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/mongodb-component.adoc
+++ 
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/mongodb-component.adoc
@@ -724,6 +724,10 @@ updated. All
 
http://www.mongodb.org/display/DOCS/Updating#Updating-ModifierOperations[modifier
 operations] from MongoDB are supported.
 
+The body can also be a JSON array of these two documents as text: a `String`, 
a `byte[]`, an `InputStream` or a
+stream-cached body, as a Kafka or file consumer or an HTTP request delivers 
it. This also makes the update usable
+from YAML and XML routes.
+
 [NOTE]
 ====
 *Multiupdates* 
@@ -836,6 +840,27 @@ Perform an aggregation with the given pipeline contained 
in the
 body.
 *Aggregations could be long and heavy operations. Use with care.*
 
+The pipeline can be a `List<Bson>`, or a JSON array of its stages as text: a 
`String`, a `byte[]`, an
+`InputStream` or a stream-cached body. For example, in YAML:
+
+[source,yaml]
+----
+- route:
+    from:
+      uri: direct:aggregate
+      steps:
+        - setBody:
+            constant: '[{"$match": {"scientist": "Darwin"}}, {"$group": 
{"_id": "$scientist", "count": {"$sum": 1}}}]'
+        - to:
+            uri: mongodb:myDb
+            parameters:
+              database: science
+              collection: notableScientists
+              operation: aggregate
+----
+
+In Java, with the Bson builders:
+
 ._Java-only: requires Bson aggregation pipeline_
 
 [source,java]
diff --git a/components/camel-mongodb/src/main/docs/mongodb-component.adoc 
b/components/camel-mongodb/src/main/docs/mongodb-component.adoc
index fa0761d02597..dd5b82861948 100644
--- a/components/camel-mongodb/src/main/docs/mongodb-component.adoc
+++ b/components/camel-mongodb/src/main/docs/mongodb-component.adoc
@@ -724,6 +724,10 @@ updated. All
 
http://www.mongodb.org/display/DOCS/Updating#Updating-ModifierOperations[modifier
 operations] from MongoDB are supported.
 
+The body can also be a JSON array of these two documents as text: a `String`, 
a `byte[]`, an `InputStream` or a
+stream-cached body, as a Kafka or file consumer or an HTTP request delivers 
it. This also makes the update usable
+from YAML and XML routes.
+
 [NOTE]
 ====
 *Multiupdates* 
@@ -836,6 +840,27 @@ Perform an aggregation with the given pipeline contained 
in the
 body.
 *Aggregations could be long and heavy operations. Use with care.*
 
+The pipeline can be a `List<Bson>`, or a JSON array of its stages as text: a 
`String`, a `byte[]`, an
+`InputStream` or a stream-cached body. For example, in YAML:
+
+[source,yaml]
+----
+- route:
+    from:
+      uri: direct:aggregate
+      steps:
+        - setBody:
+            constant: '[{"$match": {"scientist": "Darwin"}}, {"$group": 
{"_id": "$scientist", "count": {"$sum": 1}}}]'
+        - to:
+            uri: mongodb:myDb
+            parameters:
+              database: science
+              collection: notableScientists
+              operation: aggregate
+----
+
+In Java, with the Bson builders:
+
 ._Java-only: requires Bson aggregation pipeline_
 
 [source,java]
diff --git 
a/components/camel-mongodb/src/main/java/org/apache/camel/component/mongodb/MongoDbProducer.java
 
b/components/camel-mongodb/src/main/java/org/apache/camel/component/mongodb/MongoDbProducer.java
index 3e217aec0640..60dd1870dc54 100644
--- 
a/components/camel-mongodb/src/main/java/org/apache/camel/component/mongodb/MongoDbProducer.java
+++ 
b/components/camel-mongodb/src/main/java/org/apache/camel/component/mongodb/MongoDbProducer.java
@@ -48,6 +48,8 @@ import org.apache.camel.Exchange;
 import org.apache.camel.InvalidPayloadException;
 import org.apache.camel.Processor;
 import org.apache.camel.TypeConverter;
+import org.apache.camel.spi.BodyTypeRegistry;
+import org.apache.camel.support.BodyFacts;
 import org.apache.camel.support.DefaultProducer;
 import org.apache.camel.support.MessageHelper;
 import org.apache.camel.util.ObjectHelper;
@@ -487,7 +489,7 @@ public class MongoDbProducer extends DefaultProducer {
                 Bson objNew;
                 if (null == updateCriteria) {
                     List<Bson> saveObj = getBsonListBody(exchange);
-                    if (saveObj.size() != 2) {
+                    if (saveObj == null || saveObj.size() != 2) {
                         throw new CamelMongoDbException(
                                 "MongoDB operation = update, failed because 
body is not a List of Document objects with size = 2");
                     }
@@ -524,15 +526,30 @@ public class MongoDbProducer extends DefaultProducer {
 
     /**
      * The body as a List of Bson: the criteria and the update of an update or 
a findOneAndUpdate without the criteria
-     * header, or the pipeline of an aggregate. A byte[] body, such as JSON 
text from a Kafka consumer or a file, is
-     * read as text first, so that a JSON array converts as it does from a 
String.
+     * header. See {@link #getListBodyAsText}.
      */
-    @SuppressWarnings("unchecked")
     private static List<Bson> getBsonListBody(Exchange exchange) throws 
InvalidPayloadException {
+        return toBsonList(exchange, getListBodyAsText(exchange));
+    }
+
+    /**
+     * The body of an update or a findOneAndUpdate without the criteria 
header, or of an aggregate. A payload body other
+     * than a String, such as JSON text as bytes, a stream, a StreamCache or a 
file from a Kafka, file or HTTP consumer,
+     * is read as text once, so that a JSON array converts as it does from a 
String, and a stream is not read twice.
+     */
+    private static Object getListBodyAsText(Exchange exchange) {
         Object body = exchange.getIn().getBody();
-        if (body instanceof byte[]) {
+        if (!(body instanceof String) && BodyFacts.kindOf(body) == 
BodyTypeRegistry.Kind.PAYLOAD) {
             body = exchange.getIn().getBody(String.class);
         }
+        return body;
+    }
+
+    /**
+     * Convert the body to a List of Bson, or null when it is not a list, such 
as text that is not a JSON array.
+     */
+    @SuppressWarnings("unchecked")
+    private static List<Bson> toBsonList(Exchange exchange, Object body) 
throws InvalidPayloadException {
         try {
             return 
exchange.getContext().getTypeConverter().mandatoryConvertTo(List.class, 
exchange, body);
         } catch (Exception e) {
@@ -541,6 +558,14 @@ public class MongoDbProducer extends DefaultProducer {
         }
     }
 
+    private static Bson toBson(Exchange exchange, Object body) throws 
InvalidPayloadException {
+        try {
+            return 
exchange.getContext().getTypeConverter().mandatoryConvertTo(Bson.class, 
exchange, body);
+        } catch (Exception e) {
+            throw new InvalidPayloadException(exchange, Bson.class, 
exchange.getIn(), e);
+        }
+    }
+
     private Function<Exchange, Object> createDoRemove() {
         return exchange -> {
             try {
@@ -562,7 +587,9 @@ public class MongoDbProducer extends DefaultProducer {
         return exchange -> {
             try {
                 MongoCollection<Document> dbCol = 
calculateCollection(exchange);
-                List<Bson> query = getBsonListBody(exchange);
+                // read a stream body as text once, for both the pipeline and 
the single stage
+                Object body = getListBodyAsText(exchange);
+                List<Bson> query = toBsonList(exchange, body);
 
                 // Allow body to be a pipeline
                 // @see http://docs.mongodb.org/manual/core/aggregation/
@@ -570,7 +597,7 @@ public class MongoDbProducer extends DefaultProducer {
                 if (query != null) {
                     queryList = new ArrayList<>(query);
                 } else {
-                    queryList = 
Collections.singletonList(exchange.getIn().getMandatoryBody(Bson.class));
+                    queryList = Collections.singletonList(toBson(exchange, 
body));
                 }
 
                 // The number to skip must be in body query
@@ -700,7 +727,7 @@ public class MongoDbProducer extends DefaultProducer {
                 Bson update;
                 if (filter == null) {
                     List<Bson> saveObj = getBsonListBody(exchange);
-                    if (saveObj.size() != 2) {
+                    if (saveObj == null || saveObj.size() != 2) {
                         throw new CamelMongoDbException(
                                 "MongoDB operation = findOneAndUpdate, failed 
because body is not a List of Document objects with size = 2");
                     }
diff --git 
a/components/camel-mongodb/src/main/java/org/apache/camel/component/mongodb/converters/MongoDbBasicConverters.java
 
b/components/camel-mongodb/src/main/java/org/apache/camel/component/mongodb/converters/MongoDbBasicConverters.java
index c179ab18f4cb..31a0036c1638 100644
--- 
a/components/camel-mongodb/src/main/java/org/apache/camel/component/mongodb/converters/MongoDbBasicConverters.java
+++ 
b/components/camel-mongodb/src/main/java/org/apache/camel/component/mongodb/converters/MongoDbBasicConverters.java
@@ -168,8 +168,12 @@ public final class MongoDbBasicConverters {
     }
 
     private static boolean isArrayNotation(String value) {
-        return value != null && !value.isEmpty() && value.length() > 1 && 
value.charAt(0) == '['
-                && value.charAt(value.length() - 1) == ']';
+        if (value == null) {
+            return false;
+        }
+        // a JSON array from a file or a Kafka record often ends with a newline
+        String text = value.strip();
+        return text.length() > 1 && text.charAt(0) == '[' && 
text.charAt(text.length() - 1) == ']';
     }
 
 }
diff --git 
a/components/camel-mongodb/src/test/java/org/apache/camel/component/mongodb/MongoDbProducerListBodyTest.java
 
b/components/camel-mongodb/src/test/java/org/apache/camel/component/mongodb/MongoDbProducerListBodyTest.java
index 461d952bf4dd..73f19866fae8 100644
--- 
a/components/camel-mongodb/src/test/java/org/apache/camel/component/mongodb/MongoDbProducerListBodyTest.java
+++ 
b/components/camel-mongodb/src/test/java/org/apache/camel/component/mongodb/MongoDbProducerListBodyTest.java
@@ -16,7 +16,10 @@
  */
 package org.apache.camel.component.mongodb;
 
+import java.io.ByteArrayInputStream;
 import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
 import java.util.List;
 
 import com.mongodb.MongoClientSettings;
@@ -35,12 +38,14 @@ import org.apache.camel.CamelExecutionException;
 import org.apache.camel.InvalidPayloadException;
 import org.apache.camel.RoutesBuilder;
 import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.converter.stream.ByteArrayInputStreamCache;
 import org.apache.camel.test.junit6.CamelTestSupport;
 import org.bson.BsonDocument;
 import org.bson.Document;
 import org.bson.conversions.Bson;
 import org.bson.json.JsonParseException;
 import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
 import org.mockito.ArgumentCaptor;
 
 import static org.apache.camel.component.mongodb.MongoDbConstants.CRITERIA;
@@ -57,9 +62,9 @@ import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
 
 /**
- * The update, findOneAndUpdate and aggregate operations read a byte[] body, 
such as JSON text from a Kafka consumer or
- * a file, as they read the same text as a String: a JSON array of the 
criteria and the update, the update when the
- * criteria are in a header, or the pipeline.
+ * The update, findOneAndUpdate and aggregate operations read a byte[], 
InputStream, StreamCache or File body, such as
+ * JSON text from a Kafka, HTTP or file consumer, as they read the same text 
as a String: a JSON array of the criteria
+ * and the update, the update when the criteria are in a header, or the 
pipeline or a single stage.
  */
 class MongoDbProducerListBodyTest extends CamelTestSupport {
 
@@ -113,6 +118,69 @@ class MongoDbProducerListBodyTest extends CamelTestSupport 
{
         assertEquals(5, 
toBsonDocument(pipeline.getValue().get(1)).getInt32("$limit").getValue());
     }
 
+    @Test
+    void testUpdateInputStreamBodyWithCriteriaAndUpdate() {
+        String body = "[{\"name\": \"order-1\"}, {\"$set\": {\"qty\": 3}}]";
+        // a route without stream caching, so that the body reaches the 
producer as a plain InputStream
+        template.requestBody("direct:updateNoStreamCaching", new 
ByteArrayInputStream(body.getBytes(StandardCharsets.UTF_8)));
+
+        ArgumentCaptor<Bson> criteria = ArgumentCaptor.forClass(Bson.class);
+        ArgumentCaptor<Bson> update = ArgumentCaptor.forClass(Bson.class);
+        verify(collection).updateOne(criteria.capture(), update.capture(), 
any(UpdateOptions.class));
+        assertEquals("order-1", 
toBsonDocument(criteria.getValue()).getString("name").getValue());
+        assertEquals(3, 
toBsonDocument(update.getValue()).getDocument("$set").getInt32("qty").getValue());
+    }
+
+    @Test
+    @SuppressWarnings("unchecked")
+    void testAggregateStreamCachePipelineEndingWithNewline() {
+        // as a file or an HTTP request delivers it, with stream caching, and 
with a trailing newline
+        String body = "[{\"$match\": {\"qty\": 3}}, {\"$limit\": 5}]\n";
+        template.requestBody("direct:aggregate",
+                new ByteArrayInputStreamCache(new 
ByteArrayInputStream(body.getBytes(StandardCharsets.UTF_8))));
+
+        ArgumentCaptor<List<Bson>> pipeline = 
ArgumentCaptor.forClass(List.class);
+        verify(collection).aggregate(pipeline.capture());
+        assertEquals(2, pipeline.getValue().size());
+        assertEquals(5, 
toBsonDocument(pipeline.getValue().get(1)).getInt32("$limit").getValue());
+    }
+
+    @Test
+    @SuppressWarnings("unchecked")
+    void testAggregateStreamCacheBodyWithASingleStage() {
+        // a single stage is not a JSON array: the fallback converts the same 
text, the stream is not read twice
+        String body = "{\"$match\": {\"qty\": 3}}";
+        template.requestBody("direct:aggregate",
+                new ByteArrayInputStreamCache(new 
ByteArrayInputStream(body.getBytes(StandardCharsets.UTF_8))));
+
+        ArgumentCaptor<List<Bson>> pipeline = 
ArgumentCaptor.forClass(List.class);
+        verify(collection).aggregate(pipeline.capture());
+        assertEquals(1, pipeline.getValue().size());
+        assertEquals(3, 
toBsonDocument(pipeline.getValue().get(0)).getDocument("$match").getInt32("qty").getValue());
+    }
+
+    @Test
+    void testUpdateFileBodyWithCriteriaAndUpdate(@TempDir Path dir) throws 
Exception {
+        // as a file consumer delivers it
+        Path file = dir.resolve("update.json");
+        Files.writeString(file, "[{\"name\": \"order-1\"}, {\"$set\": 
{\"qty\": 3}}]\n");
+        template.requestBody("direct:update", file.toFile());
+
+        ArgumentCaptor<Bson> criteria = ArgumentCaptor.forClass(Bson.class);
+        verify(collection).updateOne(criteria.capture(), any(Bson.class), 
any(UpdateOptions.class));
+        assertEquals("order-1", 
toBsonDocument(criteria.getValue()).getString("name").getValue());
+    }
+
+    @Test
+    void testUpdateStringBodyWithSurroundingWhitespace() {
+        String body = "\n  [{\"name\": \"order-1\"}, {\"$set\": {\"qty\": 
3}}]\r\n";
+        template.requestBody("direct:update", body);
+
+        ArgumentCaptor<Bson> criteria = ArgumentCaptor.forClass(Bson.class);
+        verify(collection).updateOne(criteria.capture(), any(Bson.class), 
any(UpdateOptions.class));
+        assertEquals("order-1", 
toBsonDocument(criteria.getValue()).getString("name").getValue());
+    }
+
     @Test
     void testMalformedByteArrayBodyKeepsTheParseError() {
         byte[] body = "[{\"name\": }]".getBytes(StandardCharsets.UTF_8);
@@ -129,6 +197,16 @@ class MongoDbProducerListBodyTest extends CamelTestSupport 
{
         assertTrue(found, "the JsonParseException should be in the cause 
chain");
     }
 
+    @Test
+    void testUpdateBodyThatIsNotAnArrayFailsWithTheSizeError() {
+        // a String that is not a JSON array does not convert to a List; it 
failed with a NullPointerException
+        CamelExecutionException e = assertThrows(CamelExecutionException.class,
+                () -> template.requestBody("direct:update", "{\"name\": 
\"order-1\"}"));
+
+        CamelMongoDbException cause = 
assertInstanceOf(CamelMongoDbException.class, e.getCause());
+        assertTrue(cause.getMessage().startsWith("MongoDB operation = 
update,"), cause.getMessage());
+    }
+
     @Test
     void testUpdateBodyOfWrongSizeNamesTheUpdateOperation() {
         CamelExecutionException e = assertThrows(CamelExecutionException.class,
@@ -173,6 +251,8 @@ class MongoDbProducerListBodyTest extends CamelTestSupport {
                         
.to("mongodb:mongoClient?database=test&collection=c&operation=update&dynamicity=false");
                 from("direct:findOneAndUpdate")
                         
.to("mongodb:mongoClient?database=test&collection=c&operation=findOneAndUpdate&dynamicity=false");
+                from("direct:updateNoStreamCaching").noStreamCaching()
+                        
.to("mongodb:mongoClient?database=test&collection=c&operation=update&dynamicity=false");
                 from("direct:aggregate")
                         
.to("mongodb:mongoClient?database=test&collection=c&operation=aggregate&dynamicity=false");
             }

Reply via email to