Claus Ibsen created CAMEL-27194:
-----------------------------------
Summary: camel-mongodb - insert with a byte[] body fails with a
ClassCastException
Key: CAMEL-27194
URL: https://issues.apache.org/jira/browse/CAMEL-27194
Project: Camel
Issue Type: Bug
Components: camel-mongodb
Reporter: Claus Ibsen
h3. What happens
The {{insert}} operation fails when the body is a {{byte[]}} holding a JSON
document, which is what many consumers (HTTP, Kafka, files, Kamelet sources)
produce:
{noformat}
org.apache.camel.component.mongodb.CamelMongoDbException:
java.lang.ClassCastException: class [B cannot be cast to class
[Ljava.lang.Object; ([B and [Ljava.lang.Object; are in module java.base of
loader 'bootstrap')
{noformat}
The {{save}} operation accepts the same {{byte[]}} body, and
{{MongoDbBasicConverters.fromByteArrayToDocument}} can convert it to a
{{Document}}.
h3. How to reproduce
{code}
- route:
from:
uri: "timer:t?repeatCount=1"
steps:
- setBody:
constant: '{"item":"bytes","qty":1}'
- convertBodyTo:
type: "byte[]"
- to:
"mongodb:mongo?hosts=localhost:27017&database=shop&collection=orders&operation=insert"
{code}
h3. Where
{{components/camel-mongodb/src/main/java/org/apache/camel/component/mongodb/MongoDbProducer.java}},
{{createDoInsert()}}:
{code:java}
Object insert = exchange.getIn().getBody();
boolean array = insert != null && insert.getClass().isArray();
if (array) {
Object[] arr = (Object[]) insert; // byte[] is a primitive array
insert = Arrays.asList(arr);
}
{code}
h3. Suggested fix
Treat only arrays of objects as a batch, e.g. {{insert instanceof Object[]}},
so that a {{byte[]}} body goes on to the type converter and becomes one
{{Document}}. Add a test with a {{byte[]}} body.
A related detail in {{createDoUpdate()}}: the body must convert to a List of
two documents, which works for a {{String}} JSON array ({{fromStringToList}})
but not for the same text as {{byte[]}}; it fails with {{MongoDB operation =
insert, failed because body is not a List of Document objects with size = 2}}.
The message names {{insert}} while the operation is {{update}}. Converting a
{{byte[]}} body to {{String}} before the List conversion would make {{update}}
accept it too.
--
This message was sent by Atlassian Jira
(v10.3.26#10030026)