This is an automated email from the ASF dual-hosted git repository.
jamesnetherton 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 b7b8a5d00da8 CAMEL-27176: camel-jq - Upgrade jackson-jq to 2.x with
the Jackson 3 provider (#30376)
b7b8a5d00da8 is described below
commit b7b8a5d00da8ba685bf8dcb6d971a2868589e48c
Author: James Netherton <[email protected]>
AuthorDate: Thu Nov 19 10:47:33 2026 +0000
CAMEL-27176: camel-jq - Upgrade jackson-jq to 2.x with the Jackson 3
provider (#30376)
- Switch to the net.thisptr.jackson.jq.v2 artifacts (2.0.0-alpha2) and the
Jackson 3 JSON provider, and depend on camel-jackson3 instead of
camel-jackson
- Replace Scope with the v2 Environment, a custom one can be bound in the
registry
- Port the Camel jq functions to the v2 Function SPI and register them
through the jackson-jq ServiceLoader lookup, for environments Camel does
not build. Camel also defines them on the environments it builds, so
they win over a function of the same signature in another jar or in the
registry, as before
- Read a Jackson 2 node input as its JSON text, as camel-jsonpath does
- camel-kamelet-main: map the net.thisptr.jackson.jq.v2 package to the v2
artifacts for camel run
- Migrate the tests to Jackson 3 and the v2 API
- camel-aws-bedrock: test that jq reads the AI21 completions, which are
Jackson 3 nodes, with a mocked client
- Upgrade guide: jq results are Jackson 3 nodes, the hostname function no
longer exists, the jackson-jq extension functions need a jq module
import, constant() needs a quoted argument, and the Scope API is
replaced by Environment
- Read an empty or blank body as null, as jackson-jq 1 did, and convert a
Jackson 2 resultType from the JSON text of the result
- Upgrade guide: camel-jq brings camel-jackson3, so an application that
also has camel-jackson uses the Jackson 3 data format for
marshal().json()
Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
.../org/apache/camel/catalog/docs/jq-language.adoc | 12 +-
.../camel/catalog/docs/simple-functions.adoc | 6 +-
.../org/apache/camel/catalog/CamelCatalogTest.java | 2 +-
.../bedrock/runtime/BedrockCompletionsJqTest.java | 98 ++++++
components/camel-jq/pom.xml | 41 ++-
components/camel-jq/src/main/docs/jq-language.adoc | 12 +-
.../org/apache/camel/language/jq/JqExpression.java | 64 ++--
.../org/apache/camel/language/jq/JqFunctions.java | 362 ++++++++++-----------
.../org/apache/camel/language/jq/JqLanguage.java | 36 +-
.../net.thisptr.jackson.jq.v2.spi.Function | 22 ++
.../org/apache/camel/language/JqLanguageTest.java | 10 +-
.../apache/camel/language/jq/JqBuiltInFnTest.java | 8 +-
...ScopeTest.java => JqCustomEnvironmentTest.java} | 81 ++---
.../camel/language/jq/JqExpressionBodyFnTest.java | 6 +-
.../jq/JqExpressionFromHeaderAsStringTest.java | 2 +-
.../language/jq/JqExpressionFromHeaderTest.java | 4 +-
.../language/jq/JqExpressionFromPropertyTest.java | 6 +-
.../camel/language/jq/JqExpressionPojoTest.java | 6 +-
.../camel/language/jq/JqExpressionSimpleTest.java | 4 +-
.../apache/camel/language/jq/JqExpressionTest.java | 122 +++++--
.../camel/language/jq/JqLanguageValidateTest.java | 4 +-
.../camel/language/jq/JqNullBodyHintTest.java | 2 +-
.../camel/language/jq/JqRegistryFunctionTest.java | 119 +++++++
.../camel/language/jq/JqSimpleTransformTest.java | 2 +-
.../apache/camel/language/jq/JqTestSupport.java | 4 +-
.../modules/languages/pages/simple-functions.adoc | 6 +-
.../ROOT/pages/camel-4x-upgrade-guide-4_24.adoc | 61 +++-
.../main/known-third-party-libraries.properties | 2 +-
parent/pom.xml | 3 +-
29 files changed, 737 insertions(+), 370 deletions(-)
diff --git
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/jq-language.adoc
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/jq-language.adoc
index 6f4dc98ce7b0..d8eecf628478 100644
---
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/jq-language.adoc
+++
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/jq-language.adoc
@@ -22,8 +22,10 @@ include::partial$language-options.adoc[]
=== Message body types
-Camel JQ leverages `camel-jackson` for type conversion.
-To enable camel-jackson POJO type conversion, refer to the Camel Jackson
documentation.
+Camel JQ leverages `camel-jackson3` (Jackson 3) for type conversion.
+To enable POJO type conversion, refer to the Camel Jackson 3 documentation.
+When the registry holds exactly one `tools.jackson` `ObjectMapper`, such as
the `JsonMapper` of Spring Boot 4, the type
+converters use it, so its settings apply to how jq reads the input and
converts the results.
=== Using header as input
@@ -275,7 +277,7 @@ Java::
----
from("direct:start")
.transform()
- .jq(".foo = header(\"MyHeader\", \"MyDefaultValue\")")
+ .jq(".foo = header(\"MyHeader\"; \"MyDefaultValue\")")
.to("mock:result");
----
@@ -286,7 +288,7 @@ XML::
<route>
<from uri="direct:start"/>
<transform>
- <jq>.foo = header("MyHeader", "MyDefaultValue")</jq>
+ <jq>.foo = header("MyHeader"; "MyDefaultValue")</jq>
</transform>
<to uri="mock:result"/>
</route>
@@ -303,7 +305,7 @@ YAML::
- transform:
expression:
jq:
- expression: '.foo = header("MyHeader", "MyDefaultValue")'
+ expression: '.foo = header("MyHeader"; "MyDefaultValue")'
- to:
uri: mock:result
----
diff --git
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/simple-functions.adoc
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/simple-functions.adoc
index 8c84542f747e..035e41cd9da0 100644
---
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/simple-functions.adoc
+++
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/simple-functions.adoc
@@ -737,7 +737,7 @@ from("direct:map")
.transform().simple("""
{
"roll": ${jq(.id)},
- "country": "${jq(.country // constant(sweden))}",
+ "country": "${jq(.country // constant("sweden"))}",
"fullname": "${jq(.name)}"
}""")
.to("log:data");
@@ -752,7 +752,7 @@ XML::
<transform>
<simple>{
"roll": ${jq(.id)},
- "country": "${jq(.country // constant(sweden))}",
+ "country": "${jq(.country // constant("sweden"))}",
"fullname": "${jq(.name)}"
}</simple>
</transform>
@@ -772,7 +772,7 @@ YAML::
simple: |-
{
"roll": ${jq(.id)},
- "country": "${jq(.country // constant(sweden))}",
+ "country": "${jq(.country // constant("sweden"))}",
"fullname": "${jq(.name)}"
}
- to:
diff --git
a/catalog/camel-catalog/src/test/java/org/apache/camel/catalog/CamelCatalogTest.java
b/catalog/camel-catalog/src/test/java/org/apache/camel/catalog/CamelCatalogTest.java
index 295ab3b2752c..b759bcfff29d 100644
---
a/catalog/camel-catalog/src/test/java/org/apache/camel/catalog/CamelCatalogTest.java
+++
b/catalog/camel-catalog/src/test/java/org/apache/camel/catalog/CamelCatalogTest.java
@@ -1540,7 +1540,7 @@ public class CamelCatalogTest {
result = catalog.validateLanguageExpression(null, "jq", ". ^^+
[{\"array\": body()}]");
assertFalse(result.isSuccess());
assertEquals(". ^^+ [{\"array\": body()}]", result.getText());
- assertEquals("Cannot compile query: . ^^+ [{\"array\": body()}]",
result.getError());
+ assertTrue(result.getError().startsWith("Lexical error at line 1,
column 3."), result.getError());
}
@Test
diff --git
a/components/camel-aws/camel-aws-bedrock/src/test/java/org/apache/camel/component/aws2/bedrock/runtime/BedrockCompletionsJqTest.java
b/components/camel-aws/camel-aws-bedrock/src/test/java/org/apache/camel/component/aws2/bedrock/runtime/BedrockCompletionsJqTest.java
new file mode 100644
index 000000000000..2a6494917f6f
--- /dev/null
+++
b/components/camel-aws/camel-aws-bedrock/src/test/java/org/apache/camel/component/aws2/bedrock/runtime/BedrockCompletionsJqTest.java
@@ -0,0 +1,98 @@
+/*
+ * 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.aws2.bedrock.runtime;
+
+import java.util.List;
+
+import org.apache.camel.CamelContext;
+import org.apache.camel.ProducerTemplate;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.mock.MockEndpoint;
+import org.apache.camel.impl.DefaultCamelContext;
+import org.apache.camel.support.SimpleRegistry;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.Mock;
+import org.mockito.junit.jupiter.MockitoExtension;
+import software.amazon.awssdk.core.SdkBytes;
+import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeClient;
+import software.amazon.awssdk.services.bedrockruntime.model.InvokeModelRequest;
+import
software.amazon.awssdk.services.bedrockruntime.model.InvokeModelResponse;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.when;
+
+/**
+ * The AI21 completions are Jackson 3 nodes, which a jq expression reads after
a split, as in BedrockProducerIT.
+ */
+@ExtendWith(MockitoExtension.class)
+public class BedrockCompletionsJqTest {
+
+ @Mock
+ private BedrockRuntimeClient client;
+
+ private CamelContext camelContext;
+ private ProducerTemplate template;
+
+ @BeforeEach
+ public void setup() throws Exception {
+ SimpleRegistry registry = new SimpleRegistry();
+ registry.bind("bedrockClient", client);
+ camelContext = new DefaultCamelContext(registry);
+ camelContext.addRoutes(new RouteBuilder() {
+ @Override
+ public void configure() {
+ from("direct:start")
+
.to("aws-bedrock://label?bedrockRuntimeClient=#bedrockClient&operation=invokeTextModel"
+ +
"&modelId=ai21.j2-ultra-v1®ion=us-east-1&accessKey=unused&secretKey=unused")
+ .split(body())
+ .transform().jq(".data.text", String.class)
+ .to("mock:result");
+ }
+ });
+ camelContext.start();
+ template = camelContext.createProducerTemplate();
+ }
+
+ @AfterEach
+ public void teardown() {
+ template.stop();
+ camelContext.stop();
+ }
+
+ @Test
+ public void completionsAreReadWithJq() throws Exception {
+ when(client.invokeModel(any(InvokeModelRequest.class)))
+ .thenReturn(InvokeModelResponse.builder()
+
.body(SdkBytes.fromUtf8String("{\"completions\":[{\"data\":{\"text\":\"first\"}},"
+ +
"{\"data\":{\"text\":\"second\"}}]}"))
+ .build());
+
+ MockEndpoint result = camelContext.getEndpoint("mock:result",
MockEndpoint.class);
+ result.expectedBodiesReceived(List.of("first", "second"));
+
+ template.send("direct:start", ex -> {
+ ex.getMessage().setHeader(BedrockConstants.MODEL_CONTENT_TYPE,
"application/json");
+
ex.getMessage().setHeader(BedrockConstants.MODEL_ACCEPT_CONTENT_TYPE,
"application/json");
+ ex.getMessage().setBody("{}");
+ });
+
+ result.assertIsSatisfied();
+ }
+}
diff --git a/components/camel-jq/pom.xml b/components/camel-jq/pom.xml
index cdcd73784931..3f57f5da6ad4 100644
--- a/components/camel-jq/pom.xml
+++ b/components/camel-jq/pom.xml
@@ -43,16 +43,41 @@
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
- <artifactId>camel-jackson</artifactId>
+ <artifactId>camel-jackson3</artifactId>
</dependency>
<dependency>
- <groupId>net.thisptr</groupId>
- <artifactId>jackson-jq</artifactId>
+ <groupId>net.thisptr.jackson.jq.v2</groupId>
+ <artifactId>jackson-jq-core</artifactId>
<version>${jackson-jq-version}</version>
</dependency>
<dependency>
- <groupId>net.thisptr</groupId>
- <artifactId>jackson-jq-extra</artifactId>
+ <groupId>net.thisptr.jackson.jq.v2</groupId>
+ <artifactId>jackson-jq-json-provider-impl-jackson3</artifactId>
+ <version>${jackson-jq-version}</version>
+ </dependency>
+ <dependency>
+ <groupId>net.thisptr.jackson.jq.v2</groupId>
+ <artifactId>jackson-jq-regex-impl-joni</artifactId>
+ <version>${jackson-jq-version}</version>
+ </dependency>
+ <dependency>
+ <groupId>net.thisptr.jackson.jq.v2</groupId>
+ <artifactId>jackson-jq-ext-module-random</artifactId>
+ <version>${jackson-jq-version}</version>
+ </dependency>
+ <dependency>
+ <groupId>net.thisptr.jackson.jq.v2</groupId>
+ <artifactId>jackson-jq-ext-module-time</artifactId>
+ <version>${jackson-jq-version}</version>
+ </dependency>
+ <dependency>
+ <groupId>net.thisptr.jackson.jq.v2</groupId>
+ <artifactId>jackson-jq-ext-module-uri</artifactId>
+ <version>${jackson-jq-version}</version>
+ </dependency>
+ <dependency>
+ <groupId>net.thisptr.jackson.jq.v2</groupId>
+ <artifactId>jackson-jq-ext-module-uuid</artifactId>
<version>${jackson-jq-version}</version>
</dependency>
@@ -68,6 +93,12 @@
<artifactId>assertj-core</artifactId>
<scope>test</scope>
</dependency>
+ <!-- a body can still be a Jackson 2 node -->
+ <dependency>
+ <groupId>com.fasterxml.jackson.core</groupId>
+ <artifactId>jackson-databind</artifactId>
+ <scope>test</scope>
+ </dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-test-junit6</artifactId>
diff --git a/components/camel-jq/src/main/docs/jq-language.adoc
b/components/camel-jq/src/main/docs/jq-language.adoc
index 6f4dc98ce7b0..d8eecf628478 100644
--- a/components/camel-jq/src/main/docs/jq-language.adoc
+++ b/components/camel-jq/src/main/docs/jq-language.adoc
@@ -22,8 +22,10 @@ include::partial$language-options.adoc[]
=== Message body types
-Camel JQ leverages `camel-jackson` for type conversion.
-To enable camel-jackson POJO type conversion, refer to the Camel Jackson
documentation.
+Camel JQ leverages `camel-jackson3` (Jackson 3) for type conversion.
+To enable POJO type conversion, refer to the Camel Jackson 3 documentation.
+When the registry holds exactly one `tools.jackson` `ObjectMapper`, such as
the `JsonMapper` of Spring Boot 4, the type
+converters use it, so its settings apply to how jq reads the input and
converts the results.
=== Using header as input
@@ -275,7 +277,7 @@ Java::
----
from("direct:start")
.transform()
- .jq(".foo = header(\"MyHeader\", \"MyDefaultValue\")")
+ .jq(".foo = header(\"MyHeader\"; \"MyDefaultValue\")")
.to("mock:result");
----
@@ -286,7 +288,7 @@ XML::
<route>
<from uri="direct:start"/>
<transform>
- <jq>.foo = header("MyHeader", "MyDefaultValue")</jq>
+ <jq>.foo = header("MyHeader"; "MyDefaultValue")</jq>
</transform>
<to uri="mock:result"/>
</route>
@@ -303,7 +305,7 @@ YAML::
- transform:
expression:
jq:
- expression: '.foo = header("MyHeader", "MyDefaultValue")'
+ expression: '.foo = header("MyHeader"; "MyDefaultValue")'
- to:
uri: mock:result
----
diff --git
a/components/camel-jq/src/main/java/org/apache/camel/language/jq/JqExpression.java
b/components/camel-jq/src/main/java/org/apache/camel/language/jq/JqExpression.java
index 9696ba967722..e483f18b23f0 100644
---
a/components/camel-jq/src/main/java/org/apache/camel/language/jq/JqExpression.java
+++
b/components/camel-jq/src/main/java/org/apache/camel/language/jq/JqExpression.java
@@ -21,12 +21,9 @@ import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
-import com.fasterxml.jackson.databind.JsonNode;
-import com.fasterxml.jackson.databind.node.BooleanNode;
-import net.thisptr.jackson.jq.JsonQuery;
-import net.thisptr.jackson.jq.Scope;
-import net.thisptr.jackson.jq.Versions;
-import net.thisptr.jackson.jq.exception.JsonQueryException;
+import net.thisptr.jackson.jq.v2.core.Environment;
+import net.thisptr.jackson.jq.v2.core.JsonQuery;
+import net.thisptr.jackson.jq.v2.spi.exception.JsonQueryException;
import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.Expression;
@@ -39,15 +36,21 @@ import org.apache.camel.support.BodyFacts;
import org.apache.camel.support.ExpressionAdapter;
import org.apache.camel.support.MessageHelper;
import org.apache.camel.support.builder.ExpressionBuilder;
+import tools.jackson.databind.JsonNode;
+import tools.jackson.databind.node.BooleanNode;
+import tools.jackson.databind.node.NullNode;
public class JqExpression extends ExpressionAdapter implements
ExpressionResultTypeAware {
+ private static final String JACKSON2_NODE_PACKAGE =
"com.fasterxml.jackson.databind.node.";
+ private static final String JACKSON2_DATABIND_PACKAGE =
"com.fasterxml.jackson.databind.";
+
private final String expression;
- private Scope scope;
+ private Environment<JsonNode> environment;
private String resultTypeName;
private Class<?> resultType;
- private JsonQuery query;
+ private JsonQuery<JsonNode> query;
private TypeConverter typeConverter;
private Expression source;
@@ -55,8 +58,8 @@ public class JqExpression extends ExpressionAdapter
implements ExpressionResultT
this(null, expression);
}
- public JqExpression(Scope scope, String expression) {
- this.scope = scope;
+ public JqExpression(Environment<JsonNode> environment, String expression) {
+ this.environment = environment;
this.expression = expression;
}
@@ -66,14 +69,14 @@ public class JqExpression extends ExpressionAdapter
implements ExpressionResultT
if (this.query == null) {
super.init(camelContext);
- if (this.scope == null) {
+ if (this.environment == null) {
JqLanguage lan = (JqLanguage)
camelContext.resolveLanguage("jq");
- this.scope = Scope.newChildScope(lan.getRootScope());
+ this.environment = lan.getEnvironment();
}
this.typeConverter = camelContext.getTypeConverter();
try {
- this.query = JsonQuery.compile(this.expression,
Versions.JQ_1_7);
+ this.query = this.environment.compile(this.expression);
} catch (JsonQueryException e) {
throw new ExpressionIllegalSyntaxException(this.expression, e);
}
@@ -90,12 +93,12 @@ public class JqExpression extends ExpressionAdapter
implements ExpressionResultT
}
}
- public Scope getScope() {
- return scope;
+ public Environment<JsonNode> getEnvironment() {
+ return environment;
}
- public void setScope(Scope scope) {
- this.scope = scope;
+ public void setEnvironment(Environment<JsonNode> environment) {
+ this.environment = environment;
}
@Override
@@ -154,7 +157,7 @@ public class JqExpression extends ExpressionAdapter
implements ExpressionResultT
final List<JsonNode> outputs = new ArrayList<>(1);
final JsonNode payload = getPayload(exchange);
- this.query.apply(scope, payload, outputs::add);
+ this.query.apply(payload, outputs::add);
if (outputs.size() == 1) {
JsonNode out = outputs.get(0);
@@ -167,7 +170,7 @@ public class JqExpression extends ExpressionAdapter
implements ExpressionResultT
if (resultType == JsonNode.class) {
return out;
}
- return this.typeConverter.convertTo(resultType, exchange,
outputs.get(0));
+ return convertResult(exchange, out);
} else if (outputs.size() > 1) {
// no need to convert outputs
if (resultType == JsonNode.class) {
@@ -176,7 +179,7 @@ public class JqExpression extends ExpressionAdapter
implements ExpressionResultT
return outputs.stream()
.filter(o -> !o.isNull()) // skip null
- .map(item -> this.typeConverter.convertTo(resultType,
exchange, item))
+ .map(item -> convertResult(exchange, item))
.collect(Collectors.toList());
}
} catch (Exception e) {
@@ -195,12 +198,19 @@ public class JqExpression extends ExpressionAdapter
implements ExpressionResultT
* @return the {@link JsonNode} to be processed by the expression
*/
private JsonNode getPayload(Exchange exchange) throws Exception {
- JsonNode payload = source.evaluate(exchange, JsonNode.class);
+ Object value = source.evaluate(exchange, Object.class);
+ // Jackson 3 cannot convert a Jackson 2 node; the text of a node of
either line is its JSON
+ JsonNode payload = typeConverter.convertTo(JsonNode.class, exchange,
+ isJackson2Node(value) ? value.toString() : value);
// if body is stream cached then reset, so we can re-read it again
MessageHelper.resetStreamCache(exchange.getMessage());
+ if (payload != null && payload.isMissingNode()) {
+ // an empty or blank source holds no JSON value: read it as null,
as jackson-jq 1 did
+ payload = NullNode.getInstance();
+ }
if (payload == null) {
// tell apart a source that is null from one that is set but holds
no JSON
- if (source.evaluate(exchange, Object.class) == null) {
+ if (value == null) {
throw new InvalidPayloadException(exchange, JsonNode.class,
exchange.getIn(), nullSourceHint(exchange));
}
throw new InvalidPayloadException(exchange, JsonNode.class);
@@ -208,6 +218,16 @@ public class JqExpression extends ExpressionAdapter
implements ExpressionResultT
return payload;
}
+ private Object convertResult(Exchange exchange, JsonNode node) {
+ // Jackson 3 cannot convert to a Jackson 2 node: go through its JSON
text, as for the input
+ Object value =
resultType.getName().startsWith(JACKSON2_DATABIND_PACKAGE) ? node.toString() :
node;
+ return this.typeConverter.convertTo(resultType, exchange, value);
+ }
+
+ private static boolean isJackson2Node(Object value) {
+ return value != null &&
value.getClass().getName().startsWith(JACKSON2_NODE_PACKAGE);
+ }
+
private String nullSourceHint(Exchange exchange) {
if ("body".equals(source.toString())) {
// a timer alone, or a jq step placed before the file was read:
nothing to evaluate. What the body is, the
diff --git
a/components/camel-jq/src/main/java/org/apache/camel/language/jq/JqFunctions.java
b/components/camel-jq/src/main/java/org/apache/camel/language/jq/JqFunctions.java
index a0fa85ed33a7..86cc00dd8b25 100644
---
a/components/camel-jq/src/main/java/org/apache/camel/language/jq/JqFunctions.java
+++
b/components/camel-jq/src/main/java/org/apache/camel/language/jq/JqFunctions.java
@@ -19,106 +19,172 @@ package org.apache.camel.language.jq;
import java.util.List;
import java.util.Map;
-import com.fasterxml.jackson.databind.JsonNode;
-import com.fasterxml.jackson.databind.node.NullNode;
-import com.fasterxml.jackson.databind.node.TextNode;
-import net.thisptr.jackson.jq.BuiltinFunctionLoader;
-import net.thisptr.jackson.jq.Expression;
-import net.thisptr.jackson.jq.Function;
-import net.thisptr.jackson.jq.PathOutput;
-import net.thisptr.jackson.jq.Scope;
-import net.thisptr.jackson.jq.Version;
-import net.thisptr.jackson.jq.Versions;
-import net.thisptr.jackson.jq.exception.JsonQueryException;
-import net.thisptr.jackson.jq.internal.tree.FunctionCall;
-import net.thisptr.jackson.jq.path.Path;
+import net.thisptr.jackson.jq.v2.core.EnvironmentBuilder;
+import net.thisptr.jackson.jq.v2.core.version.Versions;
+import net.thisptr.jackson.jq.v2.json.JsonNodeType;
+import net.thisptr.jackson.jq.v2.json.JsonProvider;
+import net.thisptr.jackson.jq.v2.json.impl.jackson3.Jackson3JsonProvider;
+import net.thisptr.jackson.jq.v2.spi.BindContext;
+import net.thisptr.jackson.jq.v2.spi.Expression;
+import net.thisptr.jackson.jq.v2.spi.Function;
+import net.thisptr.jackson.jq.v2.spi.FunctionSignature;
+import net.thisptr.jackson.jq.v2.spi.Output;
+import net.thisptr.jackson.jq.v2.spi.RuntimeContext;
+import net.thisptr.jackson.jq.v2.spi.annotations.FunctionRegistration;
+import net.thisptr.jackson.jq.v2.spi.exception.JsonQueryException;
+import net.thisptr.jackson.jq.v2.spi.path.Path;
import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.StreamCache;
import org.apache.camel.util.concurrent.ContextValue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-
+import tools.jackson.databind.JsonNode;
+
+/**
+ * The Camel supplied jq functions.
+ * <p/>
+ * A new function must be annotated with {@link FunctionRegistration}, listed
in
+ * {@code META-INF/services/net.thisptr.jackson.jq.v2.spi.Function} and added
to {@link #CAMEL_FUNCTIONS}. The
+ * {@code ServiceLoader} lookup brings the functions to an environment that
Camel does not build, such as one from a CDI
+ * producer, as a built environment cannot be changed. There a function of the
same signature in another jar may win, as
+ * jackson-jq resolves such a clash in classpath order.
+ */
public final class JqFunctions {
public static final ContextValue<Exchange> EXCHANGE_LOCAL =
ContextValue.newThreadLocal("JqExchange");
private static final Logger LOGGER =
LoggerFactory.getLogger(JqFunctions.class);
+ private static final Map<FunctionSignature, Function> CAMEL_FUNCTIONS =
Map.ofEntries(
+ Map.entry(FunctionSignature.of(Header.NAME, 1), new Header()),
+ Map.entry(FunctionSignature.of(Header.NAME, 2), new Header()),
+ Map.entry(FunctionSignature.of(Property.NAME, 1), new Property()),
+ Map.entry(FunctionSignature.of(Property.NAME, 2), new Property()),
+ Map.entry(FunctionSignature.of(Constant.NAME, 1), new Constant()),
+ Map.entry(FunctionSignature.of(Constant.NAME, 2), new Constant()),
+ Map.entry(FunctionSignature.of(Variable.NAME, 1), new Variable()),
+ Map.entry(FunctionSignature.of(Variable.NAME, 2), new Variable()),
+ Map.entry(FunctionSignature.of(Body.NAME, 0), new Body()));
+
private JqFunctions() {
}
- public static void load(CamelContext camelContext, Scope scope) {
- Map<String, Function> fromServiceLoader =
BuiltinFunctionLoader.getInstance()
- .loadFunctionsFromServiceLoader(
- camelContext.getApplicationContextClassLoader() != null
- ?
camelContext.getApplicationContextClassLoader()
- : BuiltinFunctionLoader.class.getClassLoader(),
- Versions.JQ_1_7);
-
- Map<String, Function> fromJq = BuiltinFunctionLoader.getInstance()
- .loadFunctionsFromJsonJq(
- camelContext.getApplicationContextClassLoader() != null
- ?
camelContext.getApplicationContextClassLoader()
- : BuiltinFunctionLoader.class.getClassLoader(),
- Versions.JQ_1_7,
- scope);
+ /**
+ * Creates an environment builder with the jq builtins, the functions and
modules found on the classpath, and the
+ * Camel functions in this class. The Camel functions are defined on the
builder, so they win over a function of the
+ * same signature in another jar.
+ */
+ public static EnvironmentBuilder<JsonNode>
newEnvironmentBuilder(CamelContext camelContext) {
+ ClassLoader classLoader = camelContext != null &&
camelContext.getApplicationContextClassLoader() != null
+ ? camelContext.getApplicationContextClassLoader()
+ : JqFunctions.class.getClassLoader();
+ EnvironmentBuilder<JsonNode> builder
+ =
EnvironmentBuilder.withDefaultLoaders(Jackson3JsonProvider.getInstance(),
Versions.JQ_1_7, classLoader);
+ CAMEL_FUNCTIONS.forEach(builder::defineFunction);
+ return builder;
+ }
- if (fromServiceLoader != null) {
- LOGGER.debug("Loading {} jq functions from ServiceLoader",
fromServiceLoader.size());
- fromServiceLoader.forEach(scope::addFunction);
+ /**
+ * Adds the functions bound in the registry. A function bound as {@code
name/arity} gets that arity, otherwise it is
+ * variadic. A function with the signature of a Camel function is skipped,
as the Camel function wins.
+ */
+ public static void loadFromRegistry(CamelContext camelContext,
EnvironmentBuilder<JsonNode> builder) {
+ Map<String, Function> fromRegistry =
camelContext.getRegistry().findByTypeWithName(Function.class);
+ if (fromRegistry != null) {
+ LOGGER.debug("Loading {} jq functions from Registry",
fromRegistry.size());
+ fromRegistry.forEach((name, function) -> {
+ FunctionSignature signature = signature(name);
+ if (CAMEL_FUNCTIONS.containsKey(signature)) {
+ LOGGER.warn("Ignoring the jq function {} from the
registry, as it has the name of a Camel jq function",
+ name);
+ } else {
+ builder.defineFunction(signature, function);
+ }
+ });
}
+ }
- if (fromJq != null) {
- LOGGER.debug("Loading {} jq functions from Json JQ",
fromJq.size());
- fromJq.forEach(scope::addFunction);
+ private static FunctionSignature signature(String name) {
+ int pos = name.lastIndexOf('/');
+ if (pos > 0) {
+ try {
+ return FunctionSignature.of(name.substring(0, pos),
Integer.parseInt(name.substring(pos + 1)));
+ } catch (NumberFormatException e) {
+ throw new IllegalArgumentException(
+ "Invalid jq function name in the registry, expected
name/arity: " + name, e);
+ }
}
+ return FunctionSignature.ofVariadic(name);
}
- public static void loadFromRegistry(CamelContext camelContext, Scope
scope) {
- Map<String, Function> fromRegistry =
camelContext.getRegistry().findByTypeWithName(Function.class);
- if (fromRegistry != null) {
- LOGGER.debug("Loading {} jq functions from Registry",
fromRegistry.size());
- fromRegistry.forEach(scope::addFunction);
+ private static <J> String asText(JsonProvider<J> provider, J node) {
+ JsonNodeType type = provider.getNodeType(node);
+ if (type == JsonNodeType.STRING) {
+ return provider.getString(node);
+ } else if (type == JsonNodeType.NULL) {
+ return null;
}
+ return provider.format(node);
}
- public static void loadLocal(Scope scope) {
- scope.addFunction(Header.NAME, 1, new Header());
- scope.addFunction(Header.NAME, 2, new Header());
- scope.addFunction(Property.NAME, 1, new Property());
- scope.addFunction(Property.NAME, 2, new Property());
- scope.addFunction(Constant.NAME, 1, new Constant());
- scope.addFunction(Constant.NAME, 2, new Constant());
- scope.addFunction(Variable.NAME, 1, new Variable());
- scope.addFunction(Variable.NAME, 2, new Variable());
- scope.addFunction(Body.NAME, new Body());
+ private static <J> void emitText(JsonProvider<J> provider, Output<J>
output, String text) throws JsonQueryException {
+ output.emit(text == null ? provider.createNull() :
provider.createString(text), null);
}
public abstract static class ExchangeAwareFunction implements Function {
-
@Override
- public void apply(Scope scope, List<Expression> args, JsonNode in,
Path path, PathOutput output, Version version)
+ public <C extends RuntimeContext, J> Expression<C, J>
bind(BindContext<J> bindCtx, List<Expression<C, J>> args)
throws JsonQueryException {
-
- Exchange exchange = EXCHANGE_LOCAL.get();
-
- if (exchange != null) {
- doApply(scope, args, in, path, output, version, exchange);
- }
+ JsonProvider<J> provider = bindCtx.getJsonProvider();
+ return (context, in, ipath, output) -> {
+ Exchange exchange = EXCHANGE_LOCAL.get();
+ if (exchange != null) {
+ doApply(provider, context, args, in, ipath, output,
exchange);
+ }
+ };
}
- protected abstract void doApply(
- Scope scope,
- List<Expression> args,
- JsonNode in,
- Path path,
- PathOutput output,
- Version version,
+ protected abstract <C extends RuntimeContext, J> void doApply(
+ JsonProvider<J> provider,
+ C context,
+ List<Expression<C, J>> args,
+ J in,
+ Path<J> ipath,
+ Output<J> output,
Exchange exchange)
throws JsonQueryException;
}
+ /**
+ * Evaluates the name argument, and the optional default value argument,
and emits the value looked up with them.
+ */
+ public abstract static class NamedValueFunction extends
ExchangeAwareFunction {
+ @Override
+ protected <C extends RuntimeContext, J> void doApply(
+ JsonProvider<J> provider,
+ C context,
+ List<Expression<C, J>> args,
+ J in,
+ Path<J> ipath,
+ Output<J> output,
+ Exchange exchange)
+ throws JsonQueryException {
+ args.get(0).apply(context, in, ipath, (name, namePath) -> {
+ if (args.size() == 2) {
+ args.get(1).apply(context, in, ipath, (defval, defvalPath)
-> {
+ emitText(provider, output,
+ lookup(exchange, asText(provider, name),
asText(provider, defval)));
+ });
+ } else {
+ emitText(provider, output, lookup(exchange,
asText(provider, name), null));
+ }
+ });
+ }
+
+ protected abstract String lookup(Exchange exchange, String name,
String defaultValue);
+ }
+
/**
* A function that allow to retrieve an {@link org.apache.camel.Message}
header value as part of JQ expression
* evaluation.
@@ -133,48 +199,14 @@ public final class JqFunctions {
* </pre>
*
*/
- public static class Header extends ExchangeAwareFunction {
+ @FunctionRegistration(name = Header.NAME, nargs = 1)
+ @FunctionRegistration(name = Header.NAME, nargs = 2)
+ public static class Header extends NamedValueFunction {
public static final String NAME = "header";
@Override
- protected void doApply(
- Scope scope,
- List<Expression> args,
- JsonNode in,
- Path path,
- PathOutput output,
- Version version,
- Exchange exchange)
- throws JsonQueryException {
-
- args.get(0).apply(scope, in, name -> {
- if (args.size() == 2) {
- args.get(1).apply(scope, in, defval -> {
- extract(
- exchange,
- name.asText(),
- defval.asText(),
- output);
- });
- } else {
- extract(
- exchange,
- name.asText(),
- null,
- output);
- }
- });
- }
-
- private void extract(Exchange exchange, String headerName, String
headerValue, PathOutput output)
- throws JsonQueryException {
- String header = exchange.getMessage().getHeader(headerName,
headerValue, String.class);
-
- if (header == null) {
- output.emit(NullNode.getInstance(), null);
- } else {
- output.emit(new TextNode(header), null);
- }
+ protected String lookup(Exchange exchange, String name, String
defaultValue) {
+ return exchange.getMessage().getHeader(name, defaultValue,
String.class);
}
}
@@ -192,48 +224,14 @@ public final class JqFunctions {
* </pre>
*
*/
- public static class Property extends ExchangeAwareFunction {
+ @FunctionRegistration(name = Property.NAME, nargs = 1)
+ @FunctionRegistration(name = Property.NAME, nargs = 2)
+ public static class Property extends NamedValueFunction {
public static final String NAME = "property";
@Override
- protected void doApply(
- Scope scope,
- List<Expression> args,
- JsonNode in,
- Path path,
- PathOutput output,
- Version version,
- Exchange exchange)
- throws JsonQueryException {
-
- args.get(0).apply(scope, in, name -> {
- if (args.size() == 2) {
- args.get(1).apply(scope, in, defval -> {
- extract(
- exchange,
- name.asText(),
- defval.asText(),
- output);
- });
- } else {
- extract(
- exchange,
- name.asText(),
- null,
- output);
- }
- });
- }
-
- private void extract(Exchange exchange, String propertyName, String
propertyValue, PathOutput output)
- throws JsonQueryException {
- String header = exchange.getProperty(propertyName, propertyValue,
String.class);
-
- if (header == null) {
- output.emit(NullNode.getInstance(), null);
- } else {
- output.emit(new TextNode(header), null);
- }
+ protected String lookup(Exchange exchange, String name, String
defaultValue) {
+ return exchange.getProperty(name, defaultValue, String.class);
}
}
@@ -249,15 +247,17 @@ public final class JqFunctions {
* </pre>
*
*/
+ @FunctionRegistration(name = Constant.NAME, nargs = 1)
+ @FunctionRegistration(name = Constant.NAME, nargs = 2)
public static class Constant implements Function {
public static final String NAME = "constant";
@Override
- public void apply(Scope scope, List<Expression> args, JsonNode in,
Path path, PathOutput output, Version version)
+ public <C extends RuntimeContext, J> Expression<C, J>
bind(BindContext<J> bindCtx, List<Expression<C, J>> args)
throws JsonQueryException {
- FunctionCall fc = (FunctionCall) args.get(0);
- String t = fc.toString();
- output.emit(new TextNode(t), null);
+ JsonProvider<J> provider = bindCtx.getJsonProvider();
+ return (context, in, ipath, output) -> args.get(0).apply(context,
in, ipath,
+ (value, path) -> emitText(provider, output,
asText(provider, value)));
}
}
@@ -275,48 +275,14 @@ public final class JqFunctions {
* </pre>
*
*/
- public static class Variable extends ExchangeAwareFunction {
+ @FunctionRegistration(name = Variable.NAME, nargs = 1)
+ @FunctionRegistration(name = Variable.NAME, nargs = 2)
+ public static class Variable extends NamedValueFunction {
public static final String NAME = "variable";
@Override
- protected void doApply(
- Scope scope,
- List<Expression> args,
- JsonNode in,
- Path path,
- PathOutput output,
- Version version,
- Exchange exchange)
- throws JsonQueryException {
-
- args.get(0).apply(scope, in, name -> {
- if (args.size() == 2) {
- args.get(1).apply(scope, in, defval -> {
- extract(
- exchange,
- name.asText(),
- defval.asText(),
- output);
- });
- } else {
- extract(
- exchange,
- name.asText(),
- null,
- output);
- }
- });
- }
-
- private void extract(Exchange exchange, String variableName, String
variableValue, PathOutput output)
- throws JsonQueryException {
- String variable = exchange.getVariable(variableName,
variableValue, String.class);
-
- if (variable == null) {
- output.emit(NullNode.getInstance(), null);
- } else {
- output.emit(new TextNode(variable), null);
- }
+ protected String lookup(Exchange exchange, String name, String
defaultValue) {
+ return exchange.getVariable(name, defaultValue, String.class);
}
}
@@ -332,23 +298,25 @@ public final class JqFunctions {
* </pre>
*
*/
+ @FunctionRegistration(name = Body.NAME, nargs = 0)
public static class Body implements Function {
public static final String NAME = "body";
@Override
- public void apply(Scope scope, List<Expression> args, JsonNode in,
Path path, PathOutput output, Version version)
+ public <C extends RuntimeContext, J> Expression<C, J>
bind(BindContext<J> bindCtx, List<Expression<C, J>> args)
throws JsonQueryException {
- Exchange exchange = EXCHANGE_LOCAL.get();
- if (exchange != null) {
- // in case you refer to the body multiple times then we need
to handle stream-caching
- Object body = exchange.getMessage().getBody();
- if (body instanceof StreamCache sc) {
- sc.reset();
+ JsonProvider<J> provider = bindCtx.getJsonProvider();
+ return (context, in, ipath, output) -> {
+ Exchange exchange = EXCHANGE_LOCAL.get();
+ if (exchange != null) {
+ // in case you refer to the body multiple times then we
need to handle stream-caching
+ Object body = exchange.getMessage().getBody();
+ if (body instanceof StreamCache sc) {
+ sc.reset();
+ }
+ emitText(provider, output,
exchange.getMessage().getBody(String.class));
}
- String t = exchange.getMessage().getBody(String.class);
- output.emit(new TextNode(t), null);
- }
+ };
}
}
-
}
diff --git
a/components/camel-jq/src/main/java/org/apache/camel/language/jq/JqLanguage.java
b/components/camel-jq/src/main/java/org/apache/camel/language/jq/JqLanguage.java
index c7aa54d1d87b..9a07c359e365 100644
---
a/components/camel-jq/src/main/java/org/apache/camel/language/jq/JqLanguage.java
+++
b/components/camel-jq/src/main/java/org/apache/camel/language/jq/JqLanguage.java
@@ -16,10 +16,8 @@
*/
package org.apache.camel.language.jq;
-import net.thisptr.jackson.jq.JsonQuery;
-import net.thisptr.jackson.jq.Scope;
-import net.thisptr.jackson.jq.Versions;
-import net.thisptr.jackson.jq.module.loaders.BuiltinModuleLoader;
+import net.thisptr.jackson.jq.v2.core.Environment;
+import net.thisptr.jackson.jq.v2.core.EnvironmentBuilder;
import org.apache.camel.Expression;
import org.apache.camel.StaticService;
import org.apache.camel.spi.BodyType;
@@ -28,6 +26,7 @@ import org.apache.camel.spi.BodyTypes;
import org.apache.camel.spi.annotations.Language;
import org.apache.camel.support.CamelContextHelper;
import org.apache.camel.support.SingleInputTypedLanguageSupport;
+import tools.jackson.databind.JsonNode;
@Language("jq")
@BodyTypes(expressionIn = @BodyType(value = { Carrier.TEXT, Carrier.BYTES,
Carrier.STREAM, Carrier.FILE, Carrier.MAP },
@@ -39,29 +38,26 @@ import
org.apache.camel.support.SingleInputTypedLanguageSupport;
+ " gives none"))
public class JqLanguage extends SingleInputTypedLanguageSupport implements
StaticService {
- private Scope rootScope;
+ private Environment<JsonNode> environment;
@Override
+ @SuppressWarnings("unchecked")
public void init() {
if (getCamelContext() != null) {
- this.rootScope =
CamelContextHelper.findSingleByType(getCamelContext(), Scope.class);
+ this.environment =
CamelContextHelper.findSingleByType(getCamelContext(), Environment.class);
}
- if (this.rootScope == null) {
- this.rootScope = Scope.newEmptyScope();
- this.rootScope.setModuleLoader(BuiltinModuleLoader.getInstance());
+ if (this.environment == null) {
+ // a custom environment is used as-is, as an environment cannot be
changed once built
+ EnvironmentBuilder<JsonNode> builder =
JqFunctions.newEnvironmentBuilder(getCamelContext());
if (getCamelContext() != null) {
- JqFunctions.load(getCamelContext(), rootScope);
+ JqFunctions.loadFromRegistry(getCamelContext(), builder);
}
+ this.environment = builder.build();
}
-
- if (getCamelContext() != null) {
- JqFunctions.loadFromRegistry(getCamelContext(), rootScope);
- }
- JqFunctions.loadLocal(rootScope);
}
- public Scope getRootScope() {
- return rootScope;
+ public Environment<JsonNode> getEnvironment() {
+ return environment;
}
@Override
@@ -76,7 +72,7 @@ public class JqLanguage extends
SingleInputTypedLanguageSupport implements Stati
@Override
public Expression createExpression(Expression source, String expression,
Object[] properties) {
- JqExpression answer = new JqExpression(Scope.newChildScope(rootScope),
expression);
+ JqExpression answer = new JqExpression(environment, expression);
answer.setResultType(property(Class.class, properties, 0, null));
answer.setSource(source);
if (getCamelContext() != null) {
@@ -88,14 +84,14 @@ public class JqLanguage extends
SingleInputTypedLanguageSupport implements Stati
// use by tooling
public boolean validateExpression(String expression) throws Exception {
init();
- JsonQuery jq = JsonQuery.compile(expression, Versions.JQ_1_7);
+ environment.compile(expression);
return true;
}
// use by tooling
public boolean validatePredicate(String expression) throws Exception {
init();
- JsonQuery.compile(expression, Versions.JQ_1_7);
+ environment.compile(expression);
return true;
}
diff --git
a/components/camel-jq/src/main/resources/META-INF/services/net.thisptr.jackson.jq.v2.spi.Function
b/components/camel-jq/src/main/resources/META-INF/services/net.thisptr.jackson.jq.v2.spi.Function
new file mode 100644
index 000000000000..566007225cff
--- /dev/null
+++
b/components/camel-jq/src/main/resources/META-INF/services/net.thisptr.jackson.jq.v2.spi.Function
@@ -0,0 +1,22 @@
+#
+# 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.
+#
+
+org.apache.camel.language.jq.JqFunctions$Header
+org.apache.camel.language.jq.JqFunctions$Property
+org.apache.camel.language.jq.JqFunctions$Constant
+org.apache.camel.language.jq.JqFunctions$Variable
+org.apache.camel.language.jq.JqFunctions$Body
diff --git
a/components/camel-jq/src/test/java/org/apache/camel/language/JqLanguageTest.java
b/components/camel-jq/src/test/java/org/apache/camel/language/JqLanguageTest.java
index 682fe430b78e..3e90f9721b4b 100644
---
a/components/camel-jq/src/test/java/org/apache/camel/language/JqLanguageTest.java
+++
b/components/camel-jq/src/test/java/org/apache/camel/language/JqLanguageTest.java
@@ -16,13 +16,13 @@
*/
package org.apache.camel.language;
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.fasterxml.jackson.databind.node.ObjectNode;
-import com.fasterxml.jackson.databind.node.TextNode;
import org.apache.camel.CamelContext;
import org.apache.camel.builder.LanguageBuilderFactory;
-import org.apache.camel.component.jackson.JacksonConstants;
+import org.apache.camel.component.jackson3.JacksonConstants;
import org.apache.camel.model.language.JqExpression;
+import tools.jackson.databind.ObjectMapper;
+import tools.jackson.databind.node.ObjectNode;
+import tools.jackson.databind.node.StringNode;
/**
* Ensures that the "jq" language is compliant with the single input / typed
language expectations.
@@ -52,6 +52,6 @@ class JqLanguageTest extends
AbstractSingleInputTypedLanguageTest<JqExpression.B
@Override
protected TestContext testWithoutTypeContext() {
- return new TestContext(defaultContentToSend(), new TextNode("1"),
TextNode.class);
+ return new TestContext(defaultContentToSend(), new StringNode("1"),
StringNode.class);
}
}
diff --git
a/components/camel-jq/src/test/java/org/apache/camel/language/jq/JqBuiltInFnTest.java
b/components/camel-jq/src/test/java/org/apache/camel/language/jq/JqBuiltInFnTest.java
index 6e30288a84b3..ec817f46b069 100644
---
a/components/camel-jq/src/test/java/org/apache/camel/language/jq/JqBuiltInFnTest.java
+++
b/components/camel-jq/src/test/java/org/apache/camel/language/jq/JqBuiltInFnTest.java
@@ -16,8 +16,6 @@
*/
package org.apache.camel.language.jq;
-import java.net.InetAddress;
-
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.junit.jupiter.api.Test;
@@ -29,7 +27,7 @@ public class JqBuiltInFnTest extends JqTestSupport {
@Override
public void configure() {
from("direct:start")
- .transform().jq(".foo = hostname")
+ .transform().jq("import \"jackson-jq/uuid\" as uuid;
.foo = (uuid::uuid4 | length)")
.to("mock:result");
}
};
@@ -37,10 +35,8 @@ public class JqBuiltInFnTest extends JqTestSupport {
@Test
public void testExpression() throws Exception {
- InetAddress addr = InetAddress.getLocalHost();
-
getMockEndpoint("mock:result")
- .expectedBodiesReceived(node("foo", addr.getHostName()));
+ .expectedBodiesReceived(MAPPER.createObjectNode().put("foo",
36));
template.sendBodyAndHeader("direct:start", node("foo", "bar"),
"MyHeader", "MyValue");
diff --git
a/components/camel-jq/src/test/java/org/apache/camel/language/jq/JqCustomScopeTest.java
b/components/camel-jq/src/test/java/org/apache/camel/language/jq/JqCustomEnvironmentTest.java
similarity index 50%
rename from
components/camel-jq/src/test/java/org/apache/camel/language/jq/JqCustomScopeTest.java
rename to
components/camel-jq/src/test/java/org/apache/camel/language/jq/JqCustomEnvironmentTest.java
index 388b0c42972d..5efc1dd0de43 100644
---
a/components/camel-jq/src/test/java/org/apache/camel/language/jq/JqCustomScopeTest.java
+++
b/components/camel-jq/src/test/java/org/apache/camel/language/jq/JqCustomEnvironmentTest.java
@@ -18,24 +18,23 @@ package org.apache.camel.language.jq;
import java.util.List;
-import com.fasterxml.jackson.databind.JsonNode;
-import com.fasterxml.jackson.databind.node.BooleanNode;
-import net.thisptr.jackson.jq.Expression;
-import net.thisptr.jackson.jq.Function;
-import net.thisptr.jackson.jq.PathOutput;
-import net.thisptr.jackson.jq.Scope;
-import net.thisptr.jackson.jq.Version;
-import net.thisptr.jackson.jq.exception.JsonQueryException;
-import net.thisptr.jackson.jq.path.Path;
+import net.thisptr.jackson.jq.v2.core.Environment;
+import net.thisptr.jackson.jq.v2.json.JsonProvider;
+import net.thisptr.jackson.jq.v2.spi.BindContext;
+import net.thisptr.jackson.jq.v2.spi.Expression;
+import net.thisptr.jackson.jq.v2.spi.Function;
+import net.thisptr.jackson.jq.v2.spi.FunctionSignature;
+import net.thisptr.jackson.jq.v2.spi.RuntimeContext;
import org.apache.camel.BindToRegistry;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.junit.jupiter.api.Test;
+import tools.jackson.databind.JsonNode;
-public class JqCustomScopeTest extends JqTestSupport {
+public class JqCustomEnvironmentTest extends JqTestSupport {
@Test
- public void testCustomScopeFunction() throws Exception {
+ public void testCustomEnvironmentFunction() throws Exception {
getMockEndpoint("mock:result").expectedBodiesReceived(MAPPER.createObjectNode().put("foo",
"camel bar"));
template.sendBody("direct:containsCamel",
MAPPER.createObjectNode().put("foo", "baz"));
@@ -45,17 +44,7 @@ public class JqCustomScopeTest extends JqTestSupport {
}
@Test
- public void testCustomScopeFunctionFromRegistry() throws Exception {
-
getMockEndpoint("mock:result").expectedBodiesReceived(MAPPER.createObjectNode().put("foo",
"beer"));
-
- template.sendBody("direct:containsBeer",
MAPPER.createObjectNode().put("foo", "baz"));
- template.sendBody("direct:containsBeer",
MAPPER.createObjectNode().put("foo", "beer"));
-
- MockEndpoint.assertIsSatisfied(context);
- }
-
- @Test
- public void testCustomScopeBuiltInFunction() throws Exception {
+ public void testCustomEnvironmentBuiltInFunction() throws Exception {
getMockEndpoint("mock:result").expectedBodiesReceived(MAPPER.createObjectNode().put("foo",
"123456"));
template.sendBody("direct:builtInFunction",
MAPPER.createObjectNode().put("foo", "12345"));
@@ -65,32 +54,28 @@ public class JqCustomScopeTest extends JqTestSupport {
}
@BindToRegistry
- public Scope customScope() {
- Scope scope = Scope.newEmptyScope();
- JqFunctions.load(context, scope);
- scope.addFunction("containsCamel", new Function() {
- @Override
- public void apply(Scope scope, List<Expression> args, JsonNode in,
Path path, PathOutput output, Version version)
- throws JsonQueryException {
- args.get(0).apply(scope, in, (value) -> {
-
output.emit(BooleanNode.valueOf(value.asText().contains("camel")), null);
- });
- }
- });
- return scope;
+ public Environment<JsonNode> customEnvironment() {
+ return JqFunctions.newEnvironmentBuilder(context)
+ .defineFunction(FunctionSignature.of("containsCamel", 1), new
ContainsFunction("camel"))
+ .build();
}
- @BindToRegistry
- public Function containsBeer() {
- return new Function() {
- @Override
- public void apply(Scope scope, List<Expression> args, JsonNode in,
Path path, PathOutput output, Version version)
- throws JsonQueryException {
- args.get(0).apply(scope, in, (value) -> {
-
output.emit(BooleanNode.valueOf(value.asText().contains("beer")), null);
- });
- }
- };
+ /**
+ * A jq function that tells whether its argument contains the given text.
+ */
+ public static class ContainsFunction implements Function {
+ private final String text;
+
+ public ContainsFunction(String text) {
+ this.text = text;
+ }
+
+ @Override
+ public <C extends RuntimeContext, J> Expression<C, J>
bind(BindContext<J> bindCtx, List<Expression<C, J>> args) {
+ JsonProvider<J> provider = bindCtx.getJsonProvider();
+ return (ctx, in, ipath, output) -> args.get(0).apply(ctx, in,
ipath,
+ (value, path) ->
output.emit(provider.createBoolean(provider.getString(value).contains(text)),
null));
+ }
}
@Override
@@ -102,10 +87,6 @@ public class JqCustomScopeTest extends JqTestSupport {
.filter().jq("containsCamel(.foo)")
.to("mock:result");
- from("direct:containsBeer")
- .filter().jq("containsBeer(.foo)")
- .to("mock:result");
-
from("direct:builtInFunction")
.filter().jq(".foo | length > 5")
.to("mock:result");
diff --git
a/components/camel-jq/src/test/java/org/apache/camel/language/jq/JqExpressionBodyFnTest.java
b/components/camel-jq/src/test/java/org/apache/camel/language/jq/JqExpressionBodyFnTest.java
index 000439234ad1..0480f3cdad45 100644
---
a/components/camel-jq/src/test/java/org/apache/camel/language/jq/JqExpressionBodyFnTest.java
+++
b/components/camel-jq/src/test/java/org/apache/camel/language/jq/JqExpressionBodyFnTest.java
@@ -16,13 +16,13 @@
*/
package org.apache.camel.language.jq;
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.fasterxml.jackson.databind.node.ArrayNode;
-import com.fasterxml.jackson.databind.node.ObjectNode;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
+import tools.jackson.databind.ObjectMapper;
+import tools.jackson.databind.node.ArrayNode;
+import tools.jackson.databind.node.ObjectNode;
public class JqExpressionBodyFnTest extends JqTestSupport {
@Override
diff --git
a/components/camel-jq/src/test/java/org/apache/camel/language/jq/JqExpressionFromHeaderAsStringTest.java
b/components/camel-jq/src/test/java/org/apache/camel/language/jq/JqExpressionFromHeaderAsStringTest.java
index 61cab5288107..d44801bd3e38 100644
---
a/components/camel-jq/src/test/java/org/apache/camel/language/jq/JqExpressionFromHeaderAsStringTest.java
+++
b/components/camel-jq/src/test/java/org/apache/camel/language/jq/JqExpressionFromHeaderAsStringTest.java
@@ -16,10 +16,10 @@
*/
package org.apache.camel.language.jq;
-import com.fasterxml.jackson.databind.node.ObjectNode;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.junit.jupiter.api.Test;
+import tools.jackson.databind.node.ObjectNode;
public class JqExpressionFromHeaderAsStringTest extends JqTestSupport {
@Override
diff --git
a/components/camel-jq/src/test/java/org/apache/camel/language/jq/JqExpressionFromHeaderTest.java
b/components/camel-jq/src/test/java/org/apache/camel/language/jq/JqExpressionFromHeaderTest.java
index 35e613f28376..8172eaa42e4e 100644
---
a/components/camel-jq/src/test/java/org/apache/camel/language/jq/JqExpressionFromHeaderTest.java
+++
b/components/camel-jq/src/test/java/org/apache/camel/language/jq/JqExpressionFromHeaderTest.java
@@ -16,11 +16,11 @@
*/
package org.apache.camel.language.jq;
-import com.fasterxml.jackson.databind.node.TextNode;
import org.apache.camel.NoSuchHeaderException;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.junit.jupiter.api.Test;
+import tools.jackson.databind.node.StringNode;
public class JqExpressionFromHeaderTest extends JqTestSupport {
@Override
@@ -44,7 +44,7 @@ public class JqExpressionFromHeaderTest extends JqTestSupport
{
@Test
public void testExpressionFromHeader() throws Exception {
getMockEndpoint("mock:result")
- .expectedBodiesReceived(new TextNode("bar"));
+ .expectedBodiesReceived(new StringNode("bar"));
getMockEndpoint("mock:fail")
.expectedMessageCount(0);
diff --git
a/components/camel-jq/src/test/java/org/apache/camel/language/jq/JqExpressionFromPropertyTest.java
b/components/camel-jq/src/test/java/org/apache/camel/language/jq/JqExpressionFromPropertyTest.java
index aef6c16064c9..30c62df652c6 100644
---
a/components/camel-jq/src/test/java/org/apache/camel/language/jq/JqExpressionFromPropertyTest.java
+++
b/components/camel-jq/src/test/java/org/apache/camel/language/jq/JqExpressionFromPropertyTest.java
@@ -16,12 +16,12 @@
*/
package org.apache.camel.language.jq;
-import com.fasterxml.jackson.databind.node.ObjectNode;
-import com.fasterxml.jackson.databind.node.TextNode;
import org.apache.camel.NoSuchPropertyException;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.junit.jupiter.api.Test;
+import tools.jackson.databind.node.ObjectNode;
+import tools.jackson.databind.node.StringNode;
public class JqExpressionFromPropertyTest extends JqTestSupport {
@Override
@@ -45,7 +45,7 @@ public class JqExpressionFromPropertyTest extends
JqTestSupport {
@Test
public void testExpressionFromProperty() throws Exception {
getMockEndpoint("mock:result")
- .expectedBodiesReceived(new TextNode("bar"));
+ .expectedBodiesReceived(new StringNode("bar"));
getMockEndpoint("mock:fail")
.expectedMessageCount(0);
diff --git
a/components/camel-jq/src/test/java/org/apache/camel/language/jq/JqExpressionPojoTest.java
b/components/camel-jq/src/test/java/org/apache/camel/language/jq/JqExpressionPojoTest.java
index 718091351923..fe7f9ced2522 100644
---
a/components/camel-jq/src/test/java/org/apache/camel/language/jq/JqExpressionPojoTest.java
+++
b/components/camel-jq/src/test/java/org/apache/camel/language/jq/JqExpressionPojoTest.java
@@ -18,12 +18,12 @@ package org.apache.camel.language.jq;
import java.util.Objects;
-import com.fasterxml.jackson.databind.node.ObjectNode;
import org.apache.camel.CamelContext;
import org.apache.camel.builder.RouteBuilder;
-import org.apache.camel.component.jackson.JacksonConstants;
+import org.apache.camel.component.jackson3.JacksonConstants;
import org.apache.camel.component.mock.MockEndpoint;
import org.junit.jupiter.api.Test;
+import tools.jackson.databind.node.ObjectNode;
public class JqExpressionPojoTest extends JqTestSupport {
@@ -53,7 +53,7 @@ public class JqExpressionPojoTest extends JqTestSupport {
getMockEndpoint("mock:result").expectedBodiesReceived(new Book("foo",
"bar"));
ObjectNode node = MAPPER.createObjectNode();
- node.with("book").put("author", "foo").put("title", "bar");
+ node.withObjectProperty("book").put("author", "foo").put("title",
"bar");
template.sendBody("direct:start", node);
diff --git
a/components/camel-jq/src/test/java/org/apache/camel/language/jq/JqExpressionSimpleTest.java
b/components/camel-jq/src/test/java/org/apache/camel/language/jq/JqExpressionSimpleTest.java
index e516110f6a8d..d6d20e067b72 100644
---
a/components/camel-jq/src/test/java/org/apache/camel/language/jq/JqExpressionSimpleTest.java
+++
b/components/camel-jq/src/test/java/org/apache/camel/language/jq/JqExpressionSimpleTest.java
@@ -16,10 +16,10 @@
*/
package org.apache.camel.language.jq;
-import com.fasterxml.jackson.databind.node.TextNode;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.junit.jupiter.api.Test;
+import tools.jackson.databind.node.StringNode;
public class JqExpressionSimpleTest extends JqTestSupport {
@Override
@@ -36,7 +36,7 @@ public class JqExpressionSimpleTest extends JqTestSupport {
@Test
public void testExpression() throws Exception {
- getMockEndpoint("mock:result").expectedBodiesReceived(new
TextNode("bar"));
+ getMockEndpoint("mock:result").expectedBodiesReceived(new
StringNode("bar"));
template.sendBody("direct:start", node("foo", "bar", "baz", "bak"));
diff --git
a/components/camel-jq/src/test/java/org/apache/camel/language/jq/JqExpressionTest.java
b/components/camel-jq/src/test/java/org/apache/camel/language/jq/JqExpressionTest.java
index f35f446273f1..0c6fd3a76ea3 100644
---
a/components/camel-jq/src/test/java/org/apache/camel/language/jq/JqExpressionTest.java
+++
b/components/camel-jq/src/test/java/org/apache/camel/language/jq/JqExpressionTest.java
@@ -18,19 +18,27 @@ package org.apache.camel.language.jq;
import java.util.List;
-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.ObjectNode;
-import net.thisptr.jackson.jq.Scope;
+import net.thisptr.jackson.jq.v2.core.Environment;
+import net.thisptr.jackson.jq.v2.core.EnvironmentBuilder;
+import net.thisptr.jackson.jq.v2.core.version.Versions;
+import net.thisptr.jackson.jq.v2.json.impl.jackson3.Jackson3JsonProvider;
+import net.thisptr.jackson.jq.v2.spi.exception.JsonQueryException;
import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.support.DefaultExchange;
+import org.apache.camel.support.SimpleTypeConverter;
import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+import tools.jackson.databind.JsonNode;
+import tools.jackson.databind.ObjectMapper;
+import tools.jackson.databind.node.ArrayNode;
+import tools.jackson.databind.node.ObjectNode;
import static net.javacrumbs.jsonunit.assertj.JsonAssertions.assertThatJson;
import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class JqExpressionTest {
public static final ObjectMapper MAPPER = new ObjectMapper();
@@ -53,6 +61,66 @@ public class JqExpressionTest {
}
}
+ @Test
+ public void jackson2NodeBodyIsReadAsJson() throws Exception {
+ try (CamelContext context = new DefaultCamelContext()) {
+ Exchange exchange = new DefaultExchange(context);
+ exchange.getMessage().setBody(new
com.fasterxml.jackson.databind.ObjectMapper().createObjectNode()
+ .put("name", "Andrea"));
+
+ JqExpression expression = new JqExpression(".name");
+ expression.init(context);
+
+ JsonNode result = expression.evaluate(exchange, JsonNode.class);
+
+ assertThatJson(result)
+ .isString()
+ .isEqualTo("Andrea");
+ }
+ }
+
+ @Test
+ public void jackson2NodeResultTypeIsConvertedFromJson() throws Exception {
+ try (CamelContext context = new DefaultCamelContext()) {
+ // stands in for the converter of camel-jackson, which reads JSON
text into a Jackson 2 node
+ com.fasterxml.jackson.databind.ObjectMapper jackson2 = new
com.fasterxml.jackson.databind.ObjectMapper();
+
context.getTypeConverterRegistry().addTypeConverter(com.fasterxml.jackson.databind.JsonNode.class,
String.class,
+ new SimpleTypeConverter(false, (type, exchange, value) ->
jackson2.readTree((String) value)));
+
+ Exchange exchange = new DefaultExchange(context);
+ exchange.getMessage().setBody(MAPPER.createObjectNode().set("g",
MAPPER.createObjectNode().put("x", 1)));
+
+ JqExpression expression = new JqExpression(".g");
+
expression.setResultType(com.fasterxml.jackson.databind.JsonNode.class);
+ expression.init(context);
+
+ Object result = expression.evaluate(exchange, Object.class);
+
+
assertThat(result).isInstanceOf(com.fasterxml.jackson.databind.JsonNode.class);
+ assertThat(result).hasToString("{\"x\":1}");
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = { "", " ", "\n" })
+ public void emptyBodyIsReadAsNull(String body) throws Exception {
+ try (CamelContext context = new DefaultCamelContext()) {
+ Exchange exchange = new DefaultExchange(context);
+ exchange.getMessage().setBody(body);
+
+ assertThat(evaluate(context, exchange, "type")).isEqualTo("null");
+ assertThat(evaluate(context, exchange, "try .a catch
\"c\"")).isNull();
+ assertThat(evaluate(context, exchange, ". //
\"def\"")).isEqualTo("def");
+ }
+ }
+
+ private static Object evaluate(CamelContext context, Exchange exchange,
String query) {
+ JqExpression expression = new JqExpression(query);
+ expression.setResultType(String.class);
+ expression.init(context);
+ return expression.evaluate(exchange, Object.class);
+ }
+
@Test
public void extractProperty() throws Exception {
try (CamelContext context = new DefaultCamelContext()) {
@@ -133,13 +201,14 @@ public class JqExpressionTest {
try (CamelContext context = new DefaultCamelContext()) {
ArrayNode node = MAPPER.createArrayNode();
- var n1 = MAPPER.createObjectNode().with("commit");
- n1.with("commit").put("name", "Stephen Dolan");
- n1.with("commit").put("message", "Merge pull request #163 from
stedolan/utf8-fixes\n\nUtf8 fixes. Closes #161");
+ var n1 = MAPPER.createObjectNode().withObjectProperty("commit");
+ n1.withObjectProperty("commit").put("name", "Stephen Dolan");
+ n1.withObjectProperty("commit").put("message",
+ "Merge pull request #163 from stedolan/utf8-fixes\n\nUtf8
fixes. Closes #161");
var n2 = MAPPER.createObjectNode();
- n2.with("commit").put("name", "Nicolas Williams");
- n2.with("commit").put("message", "Reject all overlong UTF8
sequences.");
+ n2.withObjectProperty("commit").put("name", "Nicolas Williams");
+ n2.withObjectProperty("commit").put("message", "Reject all
overlong UTF8 sequences.");
node.add(n1);
node.add(n2);
@@ -161,8 +230,8 @@ public class JqExpressionTest {
public void setField() throws Exception {
try (CamelContext context = new DefaultCamelContext()) {
ObjectNode node = MAPPER.createObjectNode();
- node.with("commit").put("name", "Nicolas Williams");
- node.with("commit").put("message", "Reject all overlong UTF8
sequences.");
+ node.withObjectProperty("commit").put("name", "Nicolas Williams");
+ node.withObjectProperty("commit").put("message", "Reject all
overlong UTF8 sequences.");
Exchange exchange = new DefaultExchange(context);
exchange.getMessage().setBody(node);
@@ -183,8 +252,8 @@ public class JqExpressionTest {
public void setFieldFromHeader() throws Exception {
try (CamelContext context = new DefaultCamelContext()) {
ObjectNode node = MAPPER.createObjectNode();
- node.with("commit").put("name", "Nicolas Williams");
- node.with("commit").put("message", "Reject all overlong UTF8
sequences.");
+ node.withObjectProperty("commit").put("name", "Nicolas Williams");
+ node.withObjectProperty("commit").put("message", "Reject all
overlong UTF8 sequences.");
Exchange exchange = new DefaultExchange(context);
exchange.getMessage().setHeader("CommitterName", "Andrea");
@@ -206,8 +275,8 @@ public class JqExpressionTest {
public void setFieldFromProperty() throws Exception {
try (CamelContext context = new DefaultCamelContext()) {
ObjectNode node = MAPPER.createObjectNode();
- node.with("commit").put("name", "Nicolas Williams");
- node.with("commit").put("message", "Reject all overlong UTF8
sequences.");
+ node.withObjectProperty("commit").put("name", "Nicolas Williams");
+ node.withObjectProperty("commit").put("message", "Reject all
overlong UTF8 sequences.");
Exchange exchange = new DefaultExchange(context);
exchange.setProperty("CommitterName", "Andrea");
@@ -229,8 +298,8 @@ public class JqExpressionTest {
public void removeField() throws Exception {
try (CamelContext context = new DefaultCamelContext()) {
ObjectNode node = MAPPER.createObjectNode();
- node.with("commit").put("name", "Nicolas Williams");
- node.with("commit").put("message", "Reject all overlong UTF8
sequences.");
+ node.withObjectProperty("commit").put("name", "Nicolas Williams");
+ node.withObjectProperty("commit").put("message", "Reject all
overlong UTF8 sequences.");
Exchange exchange = new DefaultExchange(context);
exchange.getMessage().setBody(node);
@@ -248,17 +317,22 @@ public class JqExpressionTest {
}
@Test
- public void customScope() throws Exception {
+ public void customEnvironment() throws Exception {
try (CamelContext context = new DefaultCamelContext()) {
- Scope root = Scope.newEmptyScope();
+ // built without JqFunctions, and without the classpath function
loader, so no Camel functions
+ Environment<JsonNode> environment = EnvironmentBuilder
+ .withDefaultLoaders(Jackson3JsonProvider.getInstance(),
Versions.JQ_1_7)
+ .clearFunctionLoaders()
+ .build();
JqExpression expression = new JqExpression(".foo");
- expression.setScope(root);
+ expression.setEnvironment(environment);
expression.init(context);
- assertThat(expression.getScope()).isSameAs(root);
- assertThat(expression.getScope().getParentScope()).isNull();
-
assertThat(expression.getScope().getLocalFunctions()).doesNotContainKeys("header/1",
"header/2");
+ assertThat(expression.getEnvironment()).isSameAs(environment);
+ assertThatThrownBy(() -> environment.compile("header(\"foo\")"))
+ .isInstanceOf(JsonQueryException.class)
+ .hasMessageContaining("header/1");
}
}
diff --git
a/components/camel-jq/src/test/java/org/apache/camel/language/jq/JqLanguageValidateTest.java
b/components/camel-jq/src/test/java/org/apache/camel/language/jq/JqLanguageValidateTest.java
index 95611d603132..fb8863757cc9 100644
---
a/components/camel-jq/src/test/java/org/apache/camel/language/jq/JqLanguageValidateTest.java
+++
b/components/camel-jq/src/test/java/org/apache/camel/language/jq/JqLanguageValidateTest.java
@@ -16,7 +16,7 @@
*/
package org.apache.camel.language.jq;
-import net.thisptr.jackson.jq.exception.JsonQueryException;
+import net.thisptr.jackson.jq.v2.spi.exception.JsonQueryException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
@@ -32,7 +32,7 @@ public class JqLanguageValidateTest {
JsonQueryException e = assertThrows(JsonQueryException.class, () -> {
Assertions.assertFalse(lan.validateExpression(". ^^+ [{\"array\":
body()}]"));
});
- Assertions.assertTrue(e.getMessage().startsWith("Cannot compile
query"));
+ Assertions.assertTrue(e.getMessage().startsWith("Lexical error"));
}
}
diff --git
a/components/camel-jq/src/test/java/org/apache/camel/language/jq/JqNullBodyHintTest.java
b/components/camel-jq/src/test/java/org/apache/camel/language/jq/JqNullBodyHintTest.java
index 88ab00dc7fca..28a3cbaaaf9f 100644
---
a/components/camel-jq/src/test/java/org/apache/camel/language/jq/JqNullBodyHintTest.java
+++
b/components/camel-jq/src/test/java/org/apache/camel/language/jq/JqNullBodyHintTest.java
@@ -48,7 +48,7 @@ public class JqNullBodyHintTest extends JqTestSupport {
String message =
rootCauseMessage(assertThrows(CamelExecutionException.class,
() -> template.sendBody("direct:body", null)));
- assertTrue(message.contains("No body available of type:
com.fasterxml.jackson.databind.JsonNode"),
+ assertTrue(message.contains("No body available of type:
tools.jackson.databind.JsonNode"),
"should keep the original message, but was: " + message);
assertTrue(message.contains("the jq expression got no message body to
evaluate: the body is null"),
"should say the body is null, but was: " + message);
diff --git
a/components/camel-jq/src/test/java/org/apache/camel/language/jq/JqRegistryFunctionTest.java
b/components/camel-jq/src/test/java/org/apache/camel/language/jq/JqRegistryFunctionTest.java
new file mode 100644
index 000000000000..5352397d7089
--- /dev/null
+++
b/components/camel-jq/src/test/java/org/apache/camel/language/jq/JqRegistryFunctionTest.java
@@ -0,0 +1,119 @@
+/*
+ * 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.jq;
+
+import java.util.List;
+
+import net.thisptr.jackson.jq.v2.json.JsonProvider;
+import net.thisptr.jackson.jq.v2.spi.BindContext;
+import net.thisptr.jackson.jq.v2.spi.Expression;
+import net.thisptr.jackson.jq.v2.spi.Function;
+import net.thisptr.jackson.jq.v2.spi.RuntimeContext;
+import org.apache.camel.BindToRegistry;
+import org.apache.camel.CamelContext;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.mock.MockEndpoint;
+import org.apache.camel.impl.DefaultCamelContext;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+public class JqRegistryFunctionTest extends JqTestSupport {
+
+ @Test
+ public void testFunctionFromRegistry() throws Exception {
+
getMockEndpoint("mock:result").expectedBodiesReceived(MAPPER.createObjectNode().put("foo",
"beer"));
+
+ template.sendBody("direct:containsBeer",
MAPPER.createObjectNode().put("foo", "baz"));
+ template.sendBody("direct:containsBeer",
MAPPER.createObjectNode().put("foo", "beer"));
+
+ MockEndpoint.assertIsSatisfied(context);
+ }
+
+ @Test
+ public void testFunctionWithArityFromRegistry() throws Exception {
+
getMockEndpoint("mock:result").expectedBodiesReceived(MAPPER.createObjectNode().put("foo",
"wine"));
+
+ template.sendBody("direct:containsWine",
MAPPER.createObjectNode().put("foo", "baz"));
+ template.sendBody("direct:containsWine",
MAPPER.createObjectNode().put("foo", "wine"));
+
+ MockEndpoint.assertIsSatisfied(context);
+ }
+
+ @Test
+ public void testCamelFunctionWinsOverRegistry() throws Exception {
+ getMockEndpoint("mock:header").expectedBodiesReceived("camel");
+
+ template.sendBodyAndHeader("direct:header", MAPPER.createObjectNode(),
"foo", "camel");
+
+ MockEndpoint.assertIsSatisfied(context);
+ }
+
+ @Test
+ public void testInvalidArityFromRegistry() throws Exception {
+ try (CamelContext camelContext = new DefaultCamelContext()) {
+ camelContext.getRegistry().bind("containsWine/abc",
containsWine());
+ JqLanguage language = new JqLanguage();
+ language.setCamelContext(camelContext);
+
+ IllegalArgumentException e =
assertThrows(IllegalArgumentException.class, language::init);
+ assertEquals("Invalid jq function name in the registry, expected
name/arity: containsWine/abc", e.getMessage());
+ }
+ }
+
+ @BindToRegistry
+ public Function containsBeer() {
+ return new JqCustomEnvironmentTest.ContainsFunction("beer");
+ }
+
+ @BindToRegistry("containsWine/1")
+ public Function containsWine() {
+ return new JqCustomEnvironmentTest.ContainsFunction("wine");
+ }
+
+ @BindToRegistry("header/1")
+ public Function header() {
+ return new Function() {
+ @Override
+ public <C extends RuntimeContext, J> Expression<C, J>
bind(BindContext<J> bindCtx, List<Expression<C, J>> args) {
+ JsonProvider<J> provider = bindCtx.getJsonProvider();
+ return (ctx, in, ipath, output) ->
output.emit(provider.createString("registry"), null);
+ }
+ };
+ }
+
+ @Override
+ protected RouteBuilder createRouteBuilder() {
+ return new RouteBuilder() {
+ @Override
+ public void configure() {
+ from("direct:containsBeer")
+ .filter().jq("containsBeer(.foo)")
+ .to("mock:result");
+
+ from("direct:header")
+ .transform().jq("header(\"foo\")", String.class)
+ .to("mock:header");
+
+ from("direct:containsWine")
+ .filter().jq("containsWine(.foo)")
+ .to("mock:result");
+ }
+ };
+ }
+}
diff --git
a/components/camel-jq/src/test/java/org/apache/camel/language/jq/JqSimpleTransformTest.java
b/components/camel-jq/src/test/java/org/apache/camel/language/jq/JqSimpleTransformTest.java
index 5daeea8d3ffb..44d223c11b75 100644
---
a/components/camel-jq/src/test/java/org/apache/camel/language/jq/JqSimpleTransformTest.java
+++
b/components/camel-jq/src/test/java/org/apache/camel/language/jq/JqSimpleTransformTest.java
@@ -38,7 +38,7 @@ public class JqSimpleTransformTest extends JqTestSupport {
.transform().simple("""
{
"roll": ${jq(.id)},
- "country": "${jq(.country //
constant(sweden))}",
+ "country": "${jq(.country //
constant("sweden"))}",
"fullname": "${jq(.name)}"
}""")
.to("mock:result");
diff --git
a/components/camel-jq/src/test/java/org/apache/camel/language/jq/JqTestSupport.java
b/components/camel-jq/src/test/java/org/apache/camel/language/jq/JqTestSupport.java
index 2eecaf6d9931..ee08b0abe92a 100644
---
a/components/camel-jq/src/test/java/org/apache/camel/language/jq/JqTestSupport.java
+++
b/components/camel-jq/src/test/java/org/apache/camel/language/jq/JqTestSupport.java
@@ -16,9 +16,9 @@
*/
package org.apache.camel.language.jq;
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.fasterxml.jackson.databind.node.ObjectNode;
import org.apache.camel.test.junit6.CamelTestSupport;
+import tools.jackson.databind.ObjectMapper;
+import tools.jackson.databind.node.ObjectNode;
public abstract class JqTestSupport extends CamelTestSupport {
public static final ObjectMapper MAPPER = new ObjectMapper();
diff --git
a/core/camel-core-languages/src/main/docs/modules/languages/pages/simple-functions.adoc
b/core/camel-core-languages/src/main/docs/modules/languages/pages/simple-functions.adoc
index 8c84542f747e..035e41cd9da0 100644
---
a/core/camel-core-languages/src/main/docs/modules/languages/pages/simple-functions.adoc
+++
b/core/camel-core-languages/src/main/docs/modules/languages/pages/simple-functions.adoc
@@ -737,7 +737,7 @@ from("direct:map")
.transform().simple("""
{
"roll": ${jq(.id)},
- "country": "${jq(.country // constant(sweden))}",
+ "country": "${jq(.country // constant("sweden"))}",
"fullname": "${jq(.name)}"
}""")
.to("log:data");
@@ -752,7 +752,7 @@ XML::
<transform>
<simple>{
"roll": ${jq(.id)},
- "country": "${jq(.country // constant(sweden))}",
+ "country": "${jq(.country // constant("sweden"))}",
"fullname": "${jq(.name)}"
}</simple>
</transform>
@@ -772,7 +772,7 @@ YAML::
simple: |-
{
"roll": ${jq(.id)},
- "country": "${jq(.country // constant(sweden))}",
+ "country": "${jq(.country // constant("sweden"))}",
"fullname": "${jq(.name)}"
}
- to:
diff --git
a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
index 76d7f1e2429c..60b460f0f2fd 100644
--- a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
+++ b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
@@ -9435,10 +9435,10 @@ to your application, unless a library it uses still
needs it; at most `jackson-a
Jackson 2, for example an `ObjectMapper` it got through `camel-salesforce`,
declare `jackson-databind` yourself.
*Components that stay on Jackson 2.* `camel-jackson`, `camel-jacksonxml`,
`camel-jackson-avro`, `camel-jackson-protobuf`,
-`camel-azure-cosmosdb`, `camel-elasticsearch`, `camel-jq`, `camel-jslt`,
`camel-metrics`, `camel-opa`, `camel-openai`,
+`camel-azure-cosmosdb`, `camel-elasticsearch`, `camel-jslt`, `camel-metrics`,
`camel-opa`, `camel-openai`,
`camel-openapi-java`, `camel-opensearch`, `camel-quickjs`,
`camel-rest-openapi` and `camel-tahu` still use Jackson 2. Where
they take or return Jackson nodes, these are
`com.fasterxml.jackson.databind.JsonNode`, not the
-`tools.jackson.databind.JsonNode` that `camel-jackson3` produces. In a route
that mixes the two, such as a `jq` expression
+`tools.jackson.databind.JsonNode` that `camel-jackson3` produces. In a route
that mixes the two, such as a `jslt` transform
after `unmarshal().json()` in Camel JBang, pass the body between them as JSON
text.
*Jackson 2 nodes.* A component on Jackson 3 accepts JSON text, bytes, streams,
Maps, Lists and `tools.jackson.databind.JsonNode`
@@ -9693,6 +9693,63 @@ Jackson 2 is no longer used.
The limits on what is parsed are those of Jackson 3: nesting up to 500 levels
(it was 1000) and strings up to 100 million
characters (it was 20 million). To change them, register a mapper with your
own `StreamReadConstraints`.
+=== Jackson 3 - camel-jq
+
+`camel-jq` now uses jackson-jq 2 with its Jackson 3 provider, instead of
jackson-jq 1 on Jackson 2. It depends on
+`camel-jackson3` instead of `camel-jackson`, and no longer brings Jackson 2 to
your application: if your code uses Jackson 2,
+declare it yourself. The jackson-jq artifacts moved to the
`net.thisptr.jackson.jq.v2` group: `net.thisptr:jackson-jq` and
+`net.thisptr:jackson-jq-extra` are replaced by `jackson-jq-core`,
`jackson-jq-json-provider-impl-jackson3`,
+`jackson-jq-regex-impl-joni` and the `jackson-jq-ext-module-*` modules, which
`camel-jq` brings.
+
+*With `camel-jackson` in the same application.* As `camel-jq` brings
`camel-jackson3`, an application that also has
+`camel-jackson` now has both, and the Jackson 3 `jackson` data format is used
for `marshal().json()` and `unmarshal().json()`
+(see _One data format name, two artifacts_ above): JSON is written with the
defaults of Jackson 3, and on Spring Boot the
+`camel.dataformat.jackson.*` options of `camel-jackson-starter` no longer
apply, as they configure the Jackson 2 data format.
+To keep the Jackson 2 data format, configure a `JacksonDataFormat` of
`camel-jackson` explicitly in the route.
+
+*Results and input.* An expression without a `resultType` returns a
`tools.jackson.databind.JsonNode`, where it returned a
+`com.fasterxml.jackson.databind.JsonNode`; its conversion to another type uses
the type converters of `camel-jackson3`. An
+input that is a node of either line works: a Jackson 2 node is read as its
JSON text. A Jackson 2 `resultType`, such as
+`com.fasterxml.jackson.databind.JsonNode`, is converted from the JSON text of
the result, which needs `camel-jackson` on the
+classpath. The type converters of `camel-jackson3` use the `tools.jackson`
`ObjectMapper` of the registry when there is
+exactly one: on Spring Boot 4 this is the `JsonMapper` of Spring Boot, so the
`spring.jackson.*` settings apply to how jq
+reads its input and converts its results.
+
+*Functions in expressions.*
+
+* `constant` takes a JSON value: write `constant("sweden")` instead of
`constant(sweden)`.
+* `hostname` no longer exists.
+* The functions of `jackson-jq-extra` are now in jq modules, which an
expression imports before it calls their functions
+ with the module prefix, for example `import "jackson-jq/uuid" as uuid; .id =
uuid::uuid4`:
++
+[cols="1,2"]
+|===
+| Module | Functions
+
+| `jackson-jq/uuid` | `uuid4`
+| `jackson-jq/random` | `random`
+| `jackson-jq/time` | `timestamp`, `strftime`, `strptime`
+| `jackson-jq/uri` | `uriparse`, `uridecode`
+|===
+
+The Camel functions (`header`, `property`, `variable`, `constant` and `body`)
need no import.
+
+*Custom functions and scope.* The jackson-jq 1 types are gone, so Java code
that extends `camel-jq` must be ported:
+
+* A function in the registry must implement
`net.thisptr.jackson.jq.v2.spi.Function`, whose `bind` method replaces `apply`.
+ As before, a function bound as `name/arity`, such as `contains/1`, takes
that number of arguments, and one bound under
+ its name alone takes any number. A function with the name and arity of a
Camel function, such as `header/1`, is
+ ignored with a WARN, as the Camel function wins as before.
+* A custom root scope is now a
`net.thisptr.jackson.jq.v2.core.Environment<tools.jackson.databind.JsonNode>`
in the
+ registry, instead of a `net.thisptr.jackson.jq.Scope`. An environment cannot
be changed once built, so Camel uses it as it
+ is: it no longer adds the Camel functions and the functions of the registry
to it. Build it with
+ `JqFunctions.newEnvironmentBuilder(camelContext)`, which loads the jq
builtins, the Camel functions and the modules on the
+ classpath, and define your own functions on that builder with
`defineFunction`.
+* The `JqExpression(Scope, String)` constructor is replaced by
`JqExpression(Environment<JsonNode>, String)`.
+* `JqExpression.getScope()` and `setScope()` are replaced by
`getEnvironment()` and `setEnvironment()`, and
+ `JqLanguage.getRootScope()` by `getEnvironment()`. `JqFunctions.load()` and
`loadLocal()` are removed, and
+ `JqFunctions.loadFromRegistry()` takes an `EnvironmentBuilder`.
+
=== Jackson 3 - camel-kafka
`camel-kafka` now uses Jackson 3 (`tools.jackson`) instead of Jackson 2, and
no longer brings Jackson 2 to your application.
diff --git
a/dsl/camel-kamelet-main/src/main/known-third-party-libraries.properties
b/dsl/camel-kamelet-main/src/main/known-third-party-libraries.properties
index e54c45fc38fb..72f6b87c9276 100644
--- a/dsl/camel-kamelet-main/src/main/known-third-party-libraries.properties
+++ b/dsl/camel-kamelet-main/src/main/known-third-party-libraries.properties
@@ -189,7 +189,7 @@ com.google.protobuf =
com.google.protobuf:protobuf-java:${protobuf-version}
org.apache.thrift = org.apache.thrift:libthrift:${libthrift-version}
io.joltcommunity.jolt =
io.github.jolt-community.jolt:jolt-community-core:${jolt-version}
com.schibsted.spt.data.jslt = com.schibsted.spt.data:jslt:${jslt-version}
-net.thisptr.jackson.jq = net.thisptr:jackson-jq:${jackson-jq-version}
+net.thisptr.jackson.jq.v2 =
net.thisptr.jackson.jq.v2:jackson-jq-core:${jackson-jq-version},
net.thisptr.jackson.jq.v2:jackson-jq-json-provider-impl-jackson3:${jackson-jq-version}
org.xmlunit = org.xmlunit:xmlunit-core:${xmlunit-version}
# Commons and utilities
diff --git a/parent/pom.xml b/parent/pom.xml
index dbe89da42736..302c2201e261 100644
--- a/parent/pom.xml
+++ b/parent/pom.xml
@@ -275,7 +275,8 @@
<influx-java-driver-version>2.25</influx-java-driver-version>
<influx-client-java-driver-version>8.0.0</influx-client-java-driver-version>
<jackson-annotations-version>2.23</jackson-annotations-version>
- <jackson-jq-version>1.6.5</jackson-jq-version>
+ <!-- jackson-jq 2.x is still in alpha: check the upstream API and
operator precedence changes when bumping -->
+ <jackson-jq-version>2.0.0-alpha2</jackson-jq-version>
<jackson2-version>2.23.0</jackson2-version>
<jackson3-version>3.2.4</jackson3-version>
<jackrabbit-version>2.22.5</jackrabbit-version>