This is an automated email from the ASF dual-hosted git repository. davsclaus pushed a commit to branch camel-3.21.x in repository https://gitbox.apache.org/repos/asf/camel.git
commit 9f413334ce3a480d07b2c81d94582c2414dc7b38 Author: Claus Ibsen <[email protected]> AuthorDate: Sun Mar 3 08:45:29 2024 +0100 CAMEL-20495: camel-jsonpath - If resultType is List then automatic wr… (#13364) CAMEL-20495: camel-jsonpath - If resultType is List then automatic wrap single element into a List. --- .../src/main/docs/jsonpath-language.adoc | 9 ++- .../apache/camel/jsonpath/JsonPathExpression.java | 18 ++++-- .../jsonpath/JsonPathSplitMultipleListTest.java | 66 ++++++++++++++++++++ .../JsonPathSplitSingleListOptionTest.java | 70 ++++++++++++++++++++++ .../jsonpath/JsonPathSplitSingleListTest.java | 69 +++++++++++++++++++++ 5 files changed, 226 insertions(+), 6 deletions(-) diff --git a/components/camel-jsonpath/src/main/docs/jsonpath-language.adoc b/components/camel-jsonpath/src/main/docs/jsonpath-language.adoc index 1e52cc68582..677479fde2c 100644 --- a/components/camel-jsonpath/src/main/docs/jsonpath-language.adoc +++ b/components/camel-jsonpath/src/main/docs/jsonpath-language.adoc @@ -255,10 +255,15 @@ You can use JSONPath to split a JSON document, such as: [source,java] ---- from("direct:start") - .split().jsonpath("$.store.book[*]") + .split().jsonpath("$.store.book[*]", List.class) .to("log:book"); ---- +IMPORTANT: Notice how we specify `List.class` as the result-type. This is because if there is only +a single element (only 1 book), then jsonpath will return the single entity as a `Map` instead of `List<Map>`. +Therefore, we tell Camel that the result should always be a `List`, and Camel will then automatic wrap the +single element into a new `List` object. + Then each book is logged, however the message body is a `Map` instance. Sometimes you may want to output this as plain String JSON value instead, which can be done with the `writeAsString` option as shown: @@ -266,7 +271,7 @@ with the `writeAsString` option as shown: [source,java] ---- from("direct:start") - .split().jsonpathWriteAsString("$.store.book[*]") + .split().jsonpathWriteAsString("$.store.book[*]", List.class) .to("log:book"); ---- diff --git a/components/camel-jsonpath/src/main/java/org/apache/camel/jsonpath/JsonPathExpression.java b/components/camel-jsonpath/src/main/java/org/apache/camel/jsonpath/JsonPathExpression.java index 25c35f8e6a2..68a5a4c0222 100644 --- a/components/camel-jsonpath/src/main/java/org/apache/camel/jsonpath/JsonPathExpression.java +++ b/components/camel-jsonpath/src/main/java/org/apache/camel/jsonpath/JsonPathExpression.java @@ -17,6 +17,7 @@ package org.apache.camel.jsonpath; import java.util.Collection; +import java.util.LinkedList; import java.util.List; import com.jayway.jsonpath.Option; @@ -172,13 +173,22 @@ public class JsonPathExpression extends ExpressionAdapter { if (unpackArray) { // in some cases we get a single element that is wrapped in a List, so unwrap that // if we for example want to grab the single entity and convert that to a int/boolean/String etc - boolean resultIsCollection = Collection.class.isAssignableFrom(resultType); - boolean singleElement = result instanceof List && ((List) result).size() == 1; - if (singleElement && !resultIsCollection) { - result = ((List) result).get(0); + boolean resultTypeIsCollection = Collection.class.isAssignableFrom(resultType); + boolean singleElement = result instanceof List && ((List<?>) result).size() == 1; + if (singleElement && !resultTypeIsCollection) { + result = ((List<?>) result).get(0); LOG.trace("Unwrapping result: {} from single element List before converting to: {}", result, resultType); } + } else { + // special for List + boolean resultTypeIsCollection = Collection.class.isAssignableFrom(resultType); + boolean resultIsCollection = result instanceof List; + if (resultTypeIsCollection && !resultIsCollection) { + var list = new LinkedList<>(); + list.add(result); + result = list; + } } return exchange.getContext().getTypeConverter().convertTo(resultType, exchange, result); } else { diff --git a/components/camel-jsonpath/src/test/java/org/apache/camel/jsonpath/JsonPathSplitMultipleListTest.java b/components/camel-jsonpath/src/test/java/org/apache/camel/jsonpath/JsonPathSplitMultipleListTest.java new file mode 100644 index 00000000000..ec6b818e09c --- /dev/null +++ b/components/camel-jsonpath/src/test/java/org/apache/camel/jsonpath/JsonPathSplitMultipleListTest.java @@ -0,0 +1,66 @@ +/* + * 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.jsonpath; + +import java.io.File; +import java.util.List; + +import org.apache.camel.builder.RouteBuilder; +import org.apache.camel.component.mock.MockEndpoint; +import org.apache.camel.test.junit5.CamelTestSupport; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertNotNull; + +public class JsonPathSplitMultipleListTest extends CamelTestSupport { + + @Override + protected RouteBuilder createRouteBuilder() { + return new RouteBuilder() { + @Override + public void configure() { + from("direct:start2") + // we select all books, but since we split after wards then ensure + // it will be wrapped inside a List object. + .split().jsonpath("$.store.book", List.class) + .to("mock:authors2") + .convertBodyTo(String.class); + + from("direct:start3") + // we select all books, but since we split after wards then ensure + // it will be wrapped inside a List object. + .split().jsonpath("$.store.book[*]", List.class) + .to("mock:authors3") + .convertBodyTo(String.class); + } + }; + } + + @Test + public void testSplit() throws Exception { + getMockEndpoint("mock:authors2").expectedMessageCount(3); + getMockEndpoint("mock:authors3").expectedMessageCount(3); + + String out = template.requestBody("direct:start2", new File("src/test/resources/books.json"), String.class); + assertNotNull(out); + out = template.requestBody("direct:start3", new File("src/test/resources/books.json"), String.class); + assertNotNull(out); + + MockEndpoint.assertIsSatisfied(context); + } + +} diff --git a/components/camel-jsonpath/src/test/java/org/apache/camel/jsonpath/JsonPathSplitSingleListOptionTest.java b/components/camel-jsonpath/src/test/java/org/apache/camel/jsonpath/JsonPathSplitSingleListOptionTest.java new file mode 100644 index 00000000000..822560d23ee --- /dev/null +++ b/components/camel-jsonpath/src/test/java/org/apache/camel/jsonpath/JsonPathSplitSingleListOptionTest.java @@ -0,0 +1,70 @@ +/* + * 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.jsonpath; + +import com.jayway.jsonpath.Option; +import org.apache.camel.builder.RouteBuilder; +import org.apache.camel.component.mock.MockEndpoint; +import org.apache.camel.test.junit5.CamelTestSupport; +import org.junit.jupiter.api.Test; + +import java.io.File; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class JsonPathSplitSingleListOptionTest extends CamelTestSupport { + + @Override + protected RouteBuilder createRouteBuilder() { + return new RouteBuilder() { + @Override + public void configure() { + // use option to force returning a list even for a single element selected + var jsonpath = expression().jsonpath().option(Option.ALWAYS_RETURN_LIST.name()).expression("$.store.book[0]").end(); + + from("direct:start") + .split(jsonpath) + .to("mock:authors") + .convertBodyTo(String.class); + } + }; + } + + @Test + public void testSplit() throws Exception { + getMockEndpoint("mock:authors").expectedMessageCount(1); + + String out = template.requestBody("direct:start", new File("src/test/resources/books.json"), String.class); + assertNotNull(out); + + MockEndpoint.assertIsSatisfied(context); + + Map row = getMockEndpoint("mock:authors").getReceivedExchanges().get(0).getIn().getBody(Map.class); + assertEquals("Nigel Rees", row.get("author")); + assertEquals(Double.valueOf("8.95"), row.get("price")); + + // should preserve quotes etc + assertTrue(out.contains("\"author\": \"Nigel Rees\"")); + assertTrue(out.contains("\"price\": 8.95")); + assertTrue(out.contains("\"title\": \"Sword's of Honour\"")); + assertTrue(out.contains("\"price\": 12.99,")); + } + +} diff --git a/components/camel-jsonpath/src/test/java/org/apache/camel/jsonpath/JsonPathSplitSingleListTest.java b/components/camel-jsonpath/src/test/java/org/apache/camel/jsonpath/JsonPathSplitSingleListTest.java new file mode 100644 index 00000000000..9325c3a97cb --- /dev/null +++ b/components/camel-jsonpath/src/test/java/org/apache/camel/jsonpath/JsonPathSplitSingleListTest.java @@ -0,0 +1,69 @@ +/* + * 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.jsonpath; + +import java.io.File; +import java.util.List; +import java.util.Map; + +import org.apache.camel.builder.RouteBuilder; +import org.apache.camel.component.mock.MockEndpoint; +import org.apache.camel.test.junit5.CamelTestSupport; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class JsonPathSplitSingleListTest extends CamelTestSupport { + + @Override + protected RouteBuilder createRouteBuilder() { + return new RouteBuilder() { + @Override + public void configure() { + from("direct:start") + // we select first book, but since we split after wards then ensure + // it will be wrapped inside a List object. + .split().jsonpath("$.store.book[0]", List.class) + .to("mock:authors") + .convertBodyTo(String.class); + } + }; + } + + @Test + public void testSplit() throws Exception { + getMockEndpoint("mock:authors").expectedMessageCount(1); + + String out = template.requestBody("direct:start", new File("src/test/resources/books.json"), String.class); + assertNotNull(out); + + MockEndpoint.assertIsSatisfied(context); + + Map row = getMockEndpoint("mock:authors").getReceivedExchanges().get(0).getIn().getBody(Map.class); + assertEquals("Nigel Rees", row.get("author")); + assertEquals(Double.valueOf("8.95"), row.get("price")); + + // should preserve quotes etc + assertTrue(out.contains("\"author\": \"Nigel Rees\"")); + assertTrue(out.contains("\"price\": 8.95")); + assertTrue(out.contains("\"title\": \"Sword's of Honour\"")); + assertTrue(out.contains("\"price\": 12.99,")); + } + +}
