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 5702c4ab678d CAMEL-27150: camel-groovy - JsonSlurper.parseText reads a
message body of bytes or a stream (#30322)
5702c4ab678d is described below
commit 5702c4ab678d492a8b13bb38f1adfaf8eb63655c
Author: Claus Ibsen <[email protected]>
AuthorDate: Wed Nov 18 10:08:37 2026 +0100
CAMEL-27150: camel-groovy - JsonSlurper.parseText reads a message body of
bytes or a stream (#30322)
new groovy.json.JsonSlurper().parseText(body) is the common way to parse a
JSON body in a Groovy
script, but parseText takes only a String. A JMS consumer gets a byte[] for
a BytesMessage (JMS
sends a file, bytes or a stream that way), a Kafka record read with the
ByteArrayDeserializer is a
byte[], and an HTTP request body can be a stream. On those the script
failed with "No signature of
method: parseText ... ([B)". JsonSlurper.parse reads bytes and streams, but
has no String form, so
no single call took both kinds of body. In the local-model benchmark
(connect-service-jms-request-reply step 3, r32 to r35), 11 of 21 runs wrote
parseText(body) on the
bytes from JMS, and the route failed.
camel-groovy now registers a Groovy extension module that adds
JsonSlurper.parseText(byte[]) and
parseText(InputStream), which parse as parse(byte[]) and parse(InputStream)
do. They only add calls
that failed before. The hint for a MissingMethodException of parseText on
bytes (r26) stays, for a
runtime that does not load the module. The groovy language doc has a
section on parsing JSON.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
.../apache/camel/catalog/docs/groovy-language.adoc | 51 +++++++++++++++++++
.../src/main/docs/groovy-language.adoc | 51 +++++++++++++++++++
.../camel/groovy/json/JsonSlurperExtensions.java | 50 ++++++++++++++++++
.../camel/language/groovy/GroovyExpression.java | 3 +-
.../org.codehaus.groovy.runtime.ExtensionModule | 21 ++++++++
.../groovy/GroovyJsonSlurperParseTextTest.java | 59 ++++++++++++++++++++++
.../groovy/GroovyMissingMethodHintTest.java | 31 ++++--------
7 files changed, 244 insertions(+), 22 deletions(-)
diff --git
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/groovy-language.adoc
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/groovy-language.adoc
index 97609c39486d..b53dbe74b4b0 100644
---
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/groovy-language.adoc
+++
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/groovy-language.adoc
@@ -85,6 +85,57 @@ In Groovy, a double-quoted string with placeholders, such as
`+"Hello ${body}"+`
not a `java.lang.String`. When a script returns a GString, Camel gives it as a
`String`. So the body, header or
variable is text: it is equal to a `String`, and components such as JMS send
it as text.
+=== Parsing JSON in a script
+
+`new groovy.json.JsonSlurper().parseText(body)` parses a JSON message body
into a `Map` or a `List`. In Groovy,
+`parseText` takes only text, but many message bodies are bytes or a stream: a
JMS consumer gets a `byte[]` for a
+`BytesMessage`, a Kafka record read with the `ByteArrayDeserializer` is a
`byte[]`, and an HTTP request body can be a
+stream. Camel adds `parseText` for a `byte[]` and for an `InputStream`, so the
same script works on all of them:
+
+[tabs]
+====
+Java::
++
+[source,java]
+----
+from("jms:queue:orders")
+ .setHeader("orderId", groovy("new
groovy.json.JsonSlurper().parseText(body).orderId"))
+ .to("jms:queue:accepted");
+----
+
+XML::
++
+[source,xml]
+----
+<route>
+ <from uri="jms:queue:orders"/>
+ <setHeader name="orderId">
+ <groovy>new groovy.json.JsonSlurper().parseText(body).orderId</groovy>
+ </setHeader>
+ <to uri="jms:queue:accepted"/>
+</route>
+----
+
+YAML::
++
+[source,yaml]
+----
+- route:
+ from:
+ uri: jms:queue:orders
+ steps:
+ - setHeader:
+ name: orderId
+ expression:
+ groovy:
+ expression: "new
groovy.json.JsonSlurper().parseText(body).orderId"
+ - to:
+ uri: jms:queue:accepted
+----
+====
+
+To parse the body before the script instead, use `unmarshal` with a JSON data
format.
+
=== Customizing Groovy Shell
For very special use-cases you may need to use a custom `GroovyShell` instance
in your
diff --git a/components/camel-groovy/src/main/docs/groovy-language.adoc
b/components/camel-groovy/src/main/docs/groovy-language.adoc
index 97609c39486d..b53dbe74b4b0 100644
--- a/components/camel-groovy/src/main/docs/groovy-language.adoc
+++ b/components/camel-groovy/src/main/docs/groovy-language.adoc
@@ -85,6 +85,57 @@ In Groovy, a double-quoted string with placeholders, such as
`+"Hello ${body}"+`
not a `java.lang.String`. When a script returns a GString, Camel gives it as a
`String`. So the body, header or
variable is text: it is equal to a `String`, and components such as JMS send
it as text.
+=== Parsing JSON in a script
+
+`new groovy.json.JsonSlurper().parseText(body)` parses a JSON message body
into a `Map` or a `List`. In Groovy,
+`parseText` takes only text, but many message bodies are bytes or a stream: a
JMS consumer gets a `byte[]` for a
+`BytesMessage`, a Kafka record read with the `ByteArrayDeserializer` is a
`byte[]`, and an HTTP request body can be a
+stream. Camel adds `parseText` for a `byte[]` and for an `InputStream`, so the
same script works on all of them:
+
+[tabs]
+====
+Java::
++
+[source,java]
+----
+from("jms:queue:orders")
+ .setHeader("orderId", groovy("new
groovy.json.JsonSlurper().parseText(body).orderId"))
+ .to("jms:queue:accepted");
+----
+
+XML::
++
+[source,xml]
+----
+<route>
+ <from uri="jms:queue:orders"/>
+ <setHeader name="orderId">
+ <groovy>new groovy.json.JsonSlurper().parseText(body).orderId</groovy>
+ </setHeader>
+ <to uri="jms:queue:accepted"/>
+</route>
+----
+
+YAML::
++
+[source,yaml]
+----
+- route:
+ from:
+ uri: jms:queue:orders
+ steps:
+ - setHeader:
+ name: orderId
+ expression:
+ groovy:
+ expression: "new
groovy.json.JsonSlurper().parseText(body).orderId"
+ - to:
+ uri: jms:queue:accepted
+----
+====
+
+To parse the body before the script instead, use `unmarshal` with a JSON data
format.
+
=== Customizing Groovy Shell
For very special use-cases you may need to use a custom `GroovyShell` instance
in your
diff --git
a/components/camel-groovy/src/main/java/org/apache/camel/groovy/json/JsonSlurperExtensions.java
b/components/camel-groovy/src/main/java/org/apache/camel/groovy/json/JsonSlurperExtensions.java
new file mode 100644
index 000000000000..93854667df59
--- /dev/null
+++
b/components/camel-groovy/src/main/java/org/apache/camel/groovy/json/JsonSlurperExtensions.java
@@ -0,0 +1,50 @@
+/*
+ * 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.groovy.json;
+
+import java.io.InputStream;
+
+import groovy.json.JsonSlurper;
+
+/**
+ * Groovy extension methods that let {@code new JsonSlurper().parseText(body)}
read a message body that is not text: the
+ * byte[] a JMS consumer gets for a BytesMessage, a Kafka record read with the
ByteArrayDeserializer, or the stream of
+ * an HTTP request. In Groovy, parseText takes only a String, and
JsonSlurper.parse reads bytes and streams but has no
+ * form for a String, so no single call took both kinds of body (CAMEL-27150).
+ * <p/>
+ * Registered as a Groovy extension module in
META-INF/groovy/org.codehaus.groovy.runtime.ExtensionModule. The methods
+ * only add calls that failed before, with "No signature of method: parseText
... ([B)".
+ */
+public final class JsonSlurperExtensions {
+
+ private JsonSlurperExtensions() {
+ }
+
+ /**
+ * Parses JSON bytes, as {@link JsonSlurper#parse(byte[])} does.
+ */
+ public static Object parseText(JsonSlurper self, byte[] bytes) {
+ return self.parse(bytes);
+ }
+
+ /**
+ * Parses JSON from a stream, as {@link JsonSlurper#parse(InputStream)}
does.
+ */
+ public static Object parseText(JsonSlurper self, InputStream stream) {
+ return self.parse(stream);
+ }
+}
diff --git
a/components/camel-groovy/src/main/java/org/apache/camel/language/groovy/GroovyExpression.java
b/components/camel-groovy/src/main/java/org/apache/camel/language/groovy/GroovyExpression.java
index 5b6a43a70a86..e9f3189f8c49 100644
---
a/components/camel-groovy/src/main/java/org/apache/camel/language/groovy/GroovyExpression.java
+++
b/components/camel-groovy/src/main/java/org/apache/camel/language/groovy/GroovyExpression.java
@@ -155,7 +155,8 @@ public class GroovyExpression extends ExpressionSupport {
e.getMessageWithoutLocationText() + " (" + hint + ")",
name, e.getType());
} catch (groovy.lang.MissingMethodException e) {
// new JsonSlurper().parseText(body) on a body of bytes: parseText
takes text (r26 of the local-model
- // benchmark, a JMS message read as JSON in
connect-service-jms-request-reply step 3)
+ // benchmark, a JMS message read as JSON in
connect-service-jms-request-reply step 3). camel-groovy adds
+ // parseText for bytes as a Groovy extension module (CAMEL-27150):
this is for a runtime that does not load it
String hint = bytesToParseTextHint(exchange, e);
if (hint == null) {
throw e;
diff --git
a/components/camel-groovy/src/main/resources/META-INF/groovy/org.codehaus.groovy.runtime.ExtensionModule
b/components/camel-groovy/src/main/resources/META-INF/groovy/org.codehaus.groovy.runtime.ExtensionModule
new file mode 100644
index 000000000000..3a7d2415c386
--- /dev/null
+++
b/components/camel-groovy/src/main/resources/META-INF/groovy/org.codehaus.groovy.runtime.ExtensionModule
@@ -0,0 +1,21 @@
+#
+# 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.
+#
+
+# JsonSlurper.parseText for a message body of bytes or a stream (CAMEL-27150)
+moduleName=camel-groovy
+moduleVersion=1.0
+extensionClasses=org.apache.camel.groovy.json.JsonSlurperExtensions
diff --git
a/components/camel-groovy/src/test/java/org/apache/camel/language/groovy/GroovyJsonSlurperParseTextTest.java
b/components/camel-groovy/src/test/java/org/apache/camel/language/groovy/GroovyJsonSlurperParseTextTest.java
new file mode 100644
index 000000000000..23fa6d5516fc
--- /dev/null
+++
b/components/camel-groovy/src/test/java/org/apache/camel/language/groovy/GroovyJsonSlurperParseTextTest.java
@@ -0,0 +1,59 @@
+/*
+ * 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.language.groovy;
+
+import java.io.ByteArrayInputStream;
+import java.nio.charset.StandardCharsets;
+
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.mock.MockEndpoint;
+import org.apache.camel.test.junit6.CamelTestSupport;
+import org.junit.jupiter.api.Test;
+
+/**
+ * CAMEL-27150: new JsonSlurper().parseText(body) reads a body of bytes or a
stream, as well as text: the byte[] a JMS
+ * consumer gets for a BytesMessage failed with "No signature of method:
parseText ... ([B)".
+ */
+public class GroovyJsonSlurperParseTextTest extends CamelTestSupport {
+
+ private static final String ORDER = "{\"orderId\": \"ORD-1001\",
\"lines\": [{\"sku\": \"CAMEL-MUG\", \"qty\": 1}]}";
+
+ @Test
+ public void testParseTextOfTextBytesAndStream() throws Exception {
+ MockEndpoint mock = getMockEndpoint("mock:result");
+ mock.expectedBodiesReceived("ORD-1001 has 1 line(s)", "ORD-1001 has 1
line(s)", "ORD-1001 has 1 line(s)");
+
+ template.sendBody("direct:start", ORDER);
+ template.sendBody("direct:start",
ORDER.getBytes(StandardCharsets.UTF_8));
+ template.sendBody("direct:start", new
ByteArrayInputStream(ORDER.getBytes(StandardCharsets.UTF_8)));
+
+ MockEndpoint.assertIsSatisfied(context);
+ }
+
+ @Override
+ protected RouteBuilder createRouteBuilder() {
+ return new RouteBuilder() {
+ @Override
+ public void configure() {
+ from("direct:start")
+ .setBody().groovy("def order = new
groovy.json.JsonSlurper().parseText(body); "
+ + "\"${order.orderId} has
${order.lines.size()} line(s)\"")
+ .to("mock:result");
+ }
+ };
+ }
+}
diff --git
a/components/camel-groovy/src/test/java/org/apache/camel/processor/groovy/GroovyMissingMethodHintTest.java
b/components/camel-groovy/src/test/java/org/apache/camel/processor/groovy/GroovyMissingMethodHintTest.java
index 5be27e4edead..2fd288ea6d47 100644
---
a/components/camel-groovy/src/test/java/org/apache/camel/processor/groovy/GroovyMissingMethodHintTest.java
+++
b/components/camel-groovy/src/test/java/org/apache/camel/processor/groovy/GroovyMissingMethodHintTest.java
@@ -30,11 +30,12 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertThrows;
-import static org.junit.jupiter.api.Assertions.assertTrue;
/**
- * new JsonSlurper().parseText(body) on a body of bytes gets a
MissingMethodException whose first line says that
- * parseText takes text, and how to read the bytes (r26 of the local-model
benchmark: a JMS message read as JSON).
+ * new JsonSlurper().parseText(body) on a body of bytes got a
MissingMethodException, whose first line says that
+ * parseText takes text and how to read the bytes (r26 of the local-model
benchmark: a JMS message read as JSON). Since
+ * CAMEL-27150 camel-groovy adds parseText for bytes and streams as a Groovy
extension module, so the call parses them;
+ * the hint stays for a runtime where Groovy does not load that module.
*/
public class GroovyMissingMethodHintTest extends CamelTestSupport {
@@ -42,27 +43,15 @@ public class GroovyMissingMethodHintTest extends
CamelTestSupport {
.getBytes(StandardCharsets.UTF_8);
@Test
- public void parseTextOfBytesSaysToParseTheBytes() {
- Exception e = assertThrows(Exception.class, () ->
template.sendBody("direct:body", ORDER));
- MissingMethodException cause =
assertInstanceOf(MissingMethodException.class, e.getCause());
- // the hint is on the first line, which is the line a log shows
- String first = cause.getMessage().lines().findFirst().orElseThrow();
- assertTrue(first.startsWith("No signature of method: parseText for
class: groovy.json.JsonSlurper"), first);
- assertTrue(first.contains("(the body is bytes (a byte[])"), first);
- assertTrue(first.contains("parseText takes text, so parse the bytes
with new groovy.json.JsonSlurper().parse(body),"
- + " or unmarshal it first (unmarshal: json"),
- first);
+ public void parseTextOfBytesParsesThem() {
+ Object out = template.requestBody("direct:body", ORDER);
+ assertEquals(List.of(Map.of("sku", "A1")), out);
}
@Test
- public void parseTextOfBytesInAHeaderSaysToParseTheBytes() {
- Exception e = assertThrows(Exception.class,
- () -> template.sendBodyAndHeader("direct:header", "x",
"stock", ORDER));
- MissingMethodException cause =
assertInstanceOf(MissingMethodException.class, e.getCause());
- assertTrue(cause.getMessage().contains("(the value is bytes (a
byte[]), and parseText takes text: parse the bytes"
- + " with new
groovy.json.JsonSlurper().parse(...))"),
- cause.getMessage());
- assertFalse(cause.getMessage().contains("the body is"),
cause.getMessage());
+ public void parseTextOfBytesInAHeaderParsesThem() {
+ Object out = template.requestBodyAndHeader("direct:header", "x",
"stock", ORDER);
+ assertEquals(Map.of("orderId", "ORD-1001", "lines",
List.of(Map.of("sku", "A1"))), out);
}
@Test