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 6f8d4d2151e1 CAMEL-27194: camel-mongodb - update, findOneAndUpdate and 
aggregate read a byte[] body as JSON text (#30514)
6f8d4d2151e1 is described below

commit 6f8d4d2151e1816eb5eafb10a1f1139095d66135
Author: Ayush Kulshreshtha <[email protected]>
AuthorDate: Sat Nov 21 13:19:46 2026 +0530

    CAMEL-27194: camel-mongodb - update, findOneAndUpdate and aggregate read a 
byte[] body as JSON text (#30514)
    
    The update operation without the criteria header converts the body to a
    List of the criteria and the update. A String JSON array converts, but
    the same text as a byte[] body, as from a Kafka consumer or a file, did
    not, and failed with "MongoDB operation = insert, failed because body is
    not a List of Document objects with size = 2". A byte[] body is now read
    as text first, and the message names the update operation.
    
    The insert of a byte[] body, the other part of the issue, was fixed in
    CAMEL-27259.
    
    * CAMEL-27194: camel-mongodb - findOneAndUpdate and aggregate also read a 
byte[] body as JSON text
    
    As suggested in the review, the helper reads the List body of
    findOneAndUpdate without the criteria header and of aggregate too. A
    byte[] findOneAndUpdate body failed like the update one, and a byte[]
    aggregate pipeline was converted to a list of 39 elements instead of
    the stages of the JSON array.
    
    * CAMEL-27194: Keep the parse error of a malformed List body as the cause
    
    Use mandatoryConvertTo so that a JsonParseException from a malformed JSON
    array becomes the cause of the InvalidPayloadException, and import the
    MongoDB classes in MongoDbProducerListBodyTest.
    
    Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
 .../camel/component/mongodb/MongoDbProducer.java   |  30 +++-
 .../mongodb/MongoDbProducerListBodyTest.java       | 181 +++++++++++++++++++++
 2 files changed, 204 insertions(+), 7 deletions(-)

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 2d4bae6d0779..3e217aec0640 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
@@ -486,11 +486,10 @@ public class MongoDbProducer extends DefaultProducer {
                 Bson updateCriteria = exchange.getIn().getHeader(CRITERIA, 
Bson.class);
                 Bson objNew;
                 if (null == updateCriteria) {
-                    @SuppressWarnings("unchecked")
-                    List<Bson> saveObj = 
exchange.getIn().getMandatoryBody((Class<List<Bson>>) 
Class.class.cast(List.class));
+                    List<Bson> saveObj = getBsonListBody(exchange);
                     if (saveObj.size() != 2) {
                         throw new CamelMongoDbException(
-                                "MongoDB operation = insert, failed because 
body is not a List of Document objects with size = 2");
+                                "MongoDB operation = update, failed because 
body is not a List of Document objects with size = 2");
                     }
 
                     updateCriteria = saveObj.get(0);
@@ -523,6 +522,25 @@ 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.
+     */
+    @SuppressWarnings("unchecked")
+    private static List<Bson> getBsonListBody(Exchange exchange) throws 
InvalidPayloadException {
+        Object body = exchange.getIn().getBody();
+        if (body instanceof byte[]) {
+            body = exchange.getIn().getBody(String.class);
+        }
+        try {
+            return 
exchange.getContext().getTypeConverter().mandatoryConvertTo(List.class, 
exchange, body);
+        } catch (Exception e) {
+            // keep the parse error of a malformed JSON array as the cause
+            throw new InvalidPayloadException(exchange, List.class, 
exchange.getIn(), e);
+        }
+    }
+
     private Function<Exchange, Object> createDoRemove() {
         return exchange -> {
             try {
@@ -544,8 +562,7 @@ public class MongoDbProducer extends DefaultProducer {
         return exchange -> {
             try {
                 MongoCollection<Document> dbCol = 
calculateCollection(exchange);
-                @SuppressWarnings("unchecked")
-                List<Bson> query = 
exchange.getIn().getMandatoryBody((Class<List<Bson>>) 
Class.class.cast(List.class));
+                List<Bson> query = getBsonListBody(exchange);
 
                 // Allow body to be a pipeline
                 // @see http://docs.mongodb.org/manual/core/aggregation/
@@ -682,8 +699,7 @@ public class MongoDbProducer extends DefaultProducer {
                 Bson filter = exchange.getIn().getHeader(CRITERIA, Bson.class);
                 Bson update;
                 if (filter == null) {
-                    @SuppressWarnings("unchecked")
-                    List<Bson> saveObj = 
exchange.getIn().getMandatoryBody((Class<List<Bson>>) 
Class.class.cast(List.class));
+                    List<Bson> saveObj = getBsonListBody(exchange);
                     if (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/test/java/org/apache/camel/component/mongodb/MongoDbProducerListBodyTest.java
 
b/components/camel-mongodb/src/test/java/org/apache/camel/component/mongodb/MongoDbProducerListBodyTest.java
new file mode 100644
index 000000000000..461d952bf4dd
--- /dev/null
+++ 
b/components/camel-mongodb/src/test/java/org/apache/camel/component/mongodb/MongoDbProducerListBodyTest.java
@@ -0,0 +1,181 @@
+/*
+ * 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.
+ */
+package org.apache.camel.component.mongodb;
+
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+
+import com.mongodb.MongoClientSettings;
+import com.mongodb.client.AggregateIterable;
+import com.mongodb.client.MongoClient;
+import com.mongodb.client.MongoCollection;
+import com.mongodb.client.MongoCursor;
+import com.mongodb.client.MongoDatabase;
+import com.mongodb.client.MongoIterable;
+import com.mongodb.client.model.Filters;
+import com.mongodb.client.model.FindOneAndUpdateOptions;
+import com.mongodb.client.model.UpdateOptions;
+import com.mongodb.client.result.UpdateResult;
+import org.apache.camel.CamelContext;
+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.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.mockito.ArgumentCaptor;
+
+import static org.apache.camel.component.mongodb.MongoDbConstants.CRITERIA;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertInstanceOf;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyList;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
+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.
+ */
+class MongoDbProducerListBodyTest extends CamelTestSupport {
+
+    private final MongoCollection<Document> collection = 
mock(MongoCollection.class);
+
+    @Test
+    void testUpdateByteArrayBodyWithCriteriaAndUpdate() {
+        String body = "[{\"name\": \"order-1\"}, {\"$set\": {\"qty\": 3}}]";
+        template.requestBody("direct:update", 
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
+    void testUpdateByteArrayBodyWithCriteriaHeader() {
+        String body = "{\"$set\": {\"qty\": 3}}";
+        template.requestBodyAndHeader("direct:update", 
body.getBytes(StandardCharsets.UTF_8), CRITERIA,
+                Filters.eq("name", "order-1"));
+
+        ArgumentCaptor<Bson> update = ArgumentCaptor.forClass(Bson.class);
+        verify(collection).updateOne(any(Bson.class), update.capture(), 
any(UpdateOptions.class));
+        assertEquals(3, 
toBsonDocument(update.getValue()).getDocument("$set").getInt32("qty").getValue());
+    }
+
+    @Test
+    void testFindOneAndUpdateByteArrayBodyWithCriteriaAndUpdate() {
+        String body = "[{\"name\": \"order-1\"}, {\"$set\": {\"qty\": 3}}]";
+        template.requestBody("direct:findOneAndUpdate", 
body.getBytes(StandardCharsets.UTF_8));
+
+        ArgumentCaptor<Bson> criteria = ArgumentCaptor.forClass(Bson.class);
+        ArgumentCaptor<Bson> update = ArgumentCaptor.forClass(Bson.class);
+        verify(collection).findOneAndUpdate(criteria.capture(), 
update.capture(), any(FindOneAndUpdateOptions.class));
+        assertEquals("order-1", 
toBsonDocument(criteria.getValue()).getString("name").getValue());
+        assertEquals(3, 
toBsonDocument(update.getValue()).getDocument("$set").getInt32("qty").getValue());
+    }
+
+    @Test
+    @SuppressWarnings("unchecked")
+    void testAggregateByteArrayPipeline() {
+        String body = "[{\"$match\": {\"qty\": 3}}, {\"$limit\": 5}]";
+        template.requestBody("direct:aggregate", 
body.getBytes(StandardCharsets.UTF_8));
+
+        ArgumentCaptor<List<Bson>> pipeline = 
ArgumentCaptor.forClass(List.class);
+        verify(collection).aggregate(pipeline.capture());
+        assertEquals(2, pipeline.getValue().size());
+        assertEquals(3, 
toBsonDocument(pipeline.getValue().get(0)).getDocument("$match").getInt32("qty").getValue());
+        assertEquals(5, 
toBsonDocument(pipeline.getValue().get(1)).getInt32("$limit").getValue());
+    }
+
+    @Test
+    void testMalformedByteArrayBodyKeepsTheParseError() {
+        byte[] body = "[{\"name\": }]".getBytes(StandardCharsets.UTF_8);
+        CamelExecutionException e = assertThrows(CamelExecutionException.class,
+                () -> template.requestBody("direct:update", body));
+
+        boolean payload = false;
+        boolean found = false;
+        for (Throwable c = e.getCause(); c != null && !found; c = 
c.getCause()) {
+            payload |= c instanceof InvalidPayloadException;
+            found = c instanceof JsonParseException;
+        }
+        assertTrue(payload, "an InvalidPayloadException should be in the cause 
chain");
+        assertTrue(found, "the JsonParseException should be in the cause 
chain");
+    }
+
+    @Test
+    void testUpdateBodyOfWrongSizeNamesTheUpdateOperation() {
+        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());
+    }
+
+    private static BsonDocument toBsonDocument(Bson bson) {
+        return bson.toBsonDocument(Document.class, 
MongoClientSettings.getDefaultCodecRegistry());
+    }
+
+    @Override
+    protected CamelContext createCamelContext() throws Exception {
+        final CamelContext context = super.createCamelContext();
+
+        when(collection.withWriteConcern(any())).thenReturn(collection);
+        when(collection.updateOne(any(Bson.class), any(Bson.class), 
any(UpdateOptions.class)))
+                .thenReturn(UpdateResult.acknowledged(1, 1L, null));
+        AggregateIterable<Document> aggregation = 
mock(AggregateIterable.class);
+        when(aggregation.iterator()).thenReturn(mock(MongoCursor.class));
+        when(collection.aggregate(anyList())).thenReturn(aggregation);
+
+        final MongoDatabase database = mock(MongoDatabase.class);
+        when(database.getCollection(anyString(), 
eq(Document.class))).thenReturn(collection);
+
+        final MongoClient client = mock(MongoClient.class);
+        when(client.getDatabase(anyString())).thenReturn(database);
+        when(client.listDatabaseNames()).thenReturn(mock(MongoIterable.class));
+
+        context.getRegistry().bind("mongoClient", client);
+        return context;
+    }
+
+    @Override
+    protected RoutesBuilder createRouteBuilder() {
+        return new RouteBuilder() {
+            @Override
+            public void configure() {
+                from("direct:update")
+                        
.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:aggregate")
+                        
.to("mongodb:mongoClient?database=test&collection=c&operation=aggregate&dynamicity=false");
+            }
+        };
+    }
+}

Reply via email to