This is an automated email from the ASF dual-hosted git repository.
Croway 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 20dc5f7210b0 CAMEL-27114: camel-core - Rest DSL: bindingMode json
fails at startup without a JSON data format, and the startup errors name the
artifact to add
20dc5f7210b0 is described below
commit 20dc5f7210b0e0e0d23811de10aac7640271aa9b
Author: croway <[email protected]>
AuthorDate: Tue Nov 17 15:39:20 2026 +0100
CAMEL-27114: camel-core - Rest DSL: bindingMode json fails at startup
without a JSON data format, and the startup errors name the artifact to add
- bindingMode json or json_xml without a JSON data format fails when the
route is created
("JSON DataFormat jackson not found" and the artifact to add), as the xml
binding does, instead of
failing every request with "Cannot bind to json as message body is not
json compatible".
- bindingMode auto that finds neither a JSON nor an XML data format logs a
WARN.
- The XML and the RestProducer binding messages name the artifact too.
- "Cannot find RestConsumerFactory / RestProducerFactory /
RestApiConsumerFactory" lists the components
the Rest DSL looks for with their artifacts, and the option that chooses
one. A component name that is
not found says which artifact to add, or which names the option takes.
- camel-openapi-java: camel-jackson3 test dependency, for the tests that
use json binding.
---
components/camel-openapi-java/pom.xml | 6 +
.../camel/component/rest/RestApiEndpoint.java | 8 +-
.../apache/camel/component/rest/RestEndpoint.java | 44 +++-
.../apache/camel/component/rest/RestProducer.java | 7 +-
.../rest/RestFactoryNotFoundMessageTest.java | 163 +++++++++++++++
.../rest/RestBindingMissingDataFormatTest.java | 224 +++++++++++++++++++++
.../processor/RestBindingAdviceFactory.java | 31 ++-
.../ROOT/pages/camel-4x-upgrade-guide-4_24.adoc | 10 +
.../modules/ROOT/pages/rest-dsl-binding.adoc | 8 +-
9 files changed, 491 insertions(+), 10 deletions(-)
diff --git a/components/camel-openapi-java/pom.xml
b/components/camel-openapi-java/pom.xml
index 84b19f1fbc0a..54c623764035 100644
--- a/components/camel-openapi-java/pom.xml
+++ b/components/camel-openapi-java/pom.xml
@@ -118,6 +118,12 @@
<artifactId>camel-management</artifactId>
<scope>test</scope>
</dependency>
+ <!-- the Rest DSL json binding of some tests needs a JSON data format
-->
+ <dependency>
+ <groupId>org.apache.camel</groupId>
+ <artifactId>camel-jackson3</artifactId>
+ <scope>test</scope>
+ </dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
diff --git
a/components/camel-rest/src/main/java/org/apache/camel/component/rest/RestApiEndpoint.java
b/components/camel-rest/src/main/java/org/apache/camel/component/rest/RestApiEndpoint.java
index e568916ea875..e60538430d63 100644
---
a/components/camel-rest/src/main/java/org/apache/camel/component/rest/RestApiEndpoint.java
+++
b/components/camel-rest/src/main/java/org/apache/camel/component/rest/RestApiEndpoint.java
@@ -238,7 +238,10 @@ public class RestApiEndpoint extends DefaultEndpoint {
throw new IllegalArgumentException(
"Component " + getConsumerComponentName() + " is
not a RestApiConsumerFactory");
} else {
- throw new NoSuchBeanException(getConsumerComponentName(),
RestApiConsumerFactory.class.getName());
+ throw new NoSuchBeanException(
+ getConsumerComponentName(),
RestApiConsumerFactory.class.getName(),
+
RestEndpoint.componentNameHint(getConsumerComponentName(),
DEFAULT_REST_API_CONSUMER_COMPONENTS,
+ "component"));
}
}
cname = getConsumerComponentName();
@@ -296,7 +299,8 @@ public class RestApiEndpoint extends DefaultEndpoint {
return consumer;
} else {
- throw new IllegalStateException("Cannot find
RestApiConsumerFactory in Registry or as a Component to use");
+ throw new IllegalStateException(
+ RestEndpoint.factoryNotFound("RestApiConsumerFactory",
DEFAULT_REST_API_CONSUMER_COMPONENTS, "component"));
}
}
diff --git
a/components/camel-rest/src/main/java/org/apache/camel/component/rest/RestEndpoint.java
b/components/camel-rest/src/main/java/org/apache/camel/component/rest/RestEndpoint.java
index d83a749de8f3..f202b15593a1 100644
---
a/components/camel-rest/src/main/java/org/apache/camel/component/rest/RestEndpoint.java
+++
b/components/camel-rest/src/main/java/org/apache/camel/component/rest/RestEndpoint.java
@@ -18,6 +18,7 @@ package org.apache.camel.component.rest;
import java.util.Map;
import java.util.Set;
+import java.util.StringJoiner;
import org.apache.camel.Category;
import org.apache.camel.Component;
@@ -42,6 +43,7 @@ import org.apache.camel.support.DefaultEndpoint;
import org.apache.camel.support.PluginHelper;
import org.apache.camel.support.ResolverHelper;
import org.apache.camel.support.component.PropertyConfigurerSupport;
+import org.apache.camel.util.ArtifactUtils;
import org.apache.camel.util.HostUtils;
import org.apache.camel.util.MimeTypeHelper;
import org.apache.camel.util.ObjectHelper;
@@ -345,7 +347,8 @@ public class RestEndpoint extends DefaultEndpoint {
ProducerFactoryResult factoryResult = findProducerFactory();
if (factoryResult.factory == null) {
- throw new IllegalStateException("Cannot find RestProducerFactory
in Registry or as a Component to use");
+ throw new IllegalStateException(
+ factoryNotFound("RestProducerFactory",
DEFAULT_REST_PRODUCER_COMPONENTS, "producerComponent"));
}
LOG.debug("Using RestProducerFactory: {}", factoryResult.factory);
@@ -434,7 +437,9 @@ public class RestEndpoint extends DefaultEndpoint {
if (comp != null) {
throw new IllegalArgumentException("Component " + pname + " is not
a RestProducerFactory");
}
- throw new NoSuchBeanException(pname,
RestProducerFactory.class.getName());
+ throw new NoSuchBeanException(
+ pname, RestProducerFactory.class.getName(),
+ componentNameHint(pname, DEFAULT_REST_PRODUCER_COMPONENTS,
"producerComponent"));
}
@SuppressWarnings("unchecked")
@@ -499,7 +504,8 @@ public class RestEndpoint extends DefaultEndpoint {
ConsumerFactoryResult factoryResult = findConsumerFactory();
if (factoryResult.factory == null) {
- throw new IllegalStateException("Cannot find RestConsumerFactory
in Registry or as a Component to use");
+ throw new IllegalStateException(
+ factoryNotFound("RestConsumerFactory",
DEFAULT_REST_CONSUMER_COMPONENTS, "component"));
}
RestConfiguration config =
CamelContextHelper.getRestConfiguration(getCamelContext(), factoryResult.name);
@@ -560,7 +566,9 @@ public class RestEndpoint extends DefaultEndpoint {
if (comp != null) {
throw new IllegalArgumentException("Component " + cname + " is not
a RestConsumerFactory");
}
- throw new NoSuchBeanException(cname,
RestConsumerFactory.class.getName());
+ throw new NoSuchBeanException(
+ cname, RestConsumerFactory.class.getName(),
+ componentNameHint(cname, DEFAULT_REST_CONSUMER_COMPONENTS,
"component"));
}
private ConsumerFactoryResult findConsumerFromExistingComponents() {
@@ -601,6 +609,34 @@ public class RestEndpoint extends DefaultEndpoint {
return new ConsumerFactoryResult(null, null);
}
+ /**
+ * The message when no factory is found: the components the Rest DSL looks
for, each with the artifact that has it,
+ * and the option that chooses one.
+ */
+ static String factoryNotFound(String factory, String[] components, String
option) {
+ StringJoiner names = new StringJoiner(", ");
+ for (String name : components) {
+ String artifact = ArtifactUtils.componentArtifact(name);
+ names.add(artifact != null ? name + " (" + artifact + ")" : name);
+ }
+ return "Cannot find " + factory + " in Registry or as a Component to
use. Add one of these components to the"
+ + " classpath: " + names + ". To choose one, set the " + option
+ + " option of the rest configuration to its name.";
+ }
+
+ /**
+ * The hint when the component the option names is not found: the artifact
to add when it is a Camel component, or
+ * else the names the option takes (it is the name of a component, not of
a bean or a servlet).
+ */
+ static String componentNameHint(String name, String[] components, String
option) {
+ String hint = ArtifactUtils.componentHint(name);
+ if (ArtifactUtils.componentArtifact(name) != null) {
+ return hint;
+ }
+ return hint + ". The " + option + " option of the rest configuration
takes the name of a component that"
+ + " supports the Rest DSL: " + String.join(", ", components);
+ }
+
private String[] buildServiceUrls(RestConfiguration config) throws
Exception {
String scheme = config.getScheme() != null ? config.getScheme() :
"http";
String host = config.getHost() != null ? config.getHost() : "";
diff --git
a/components/camel-rest/src/main/java/org/apache/camel/component/rest/RestProducer.java
b/components/camel-rest/src/main/java/org/apache/camel/component/rest/RestProducer.java
index 8bc734d81506..bb1d9822992e 100644
---
a/components/camel-rest/src/main/java/org/apache/camel/component/rest/RestProducer.java
+++
b/components/camel-rest/src/main/java/org/apache/camel/component/rest/RestProducer.java
@@ -41,6 +41,7 @@ import org.apache.camel.support.DefaultAsyncProducer;
import org.apache.camel.support.PluginHelper;
import org.apache.camel.support.PropertyBindingSupport;
import org.apache.camel.support.service.ServiceHelper;
+import org.apache.camel.util.ArtifactUtils;
import org.apache.camel.util.FileUtil;
import org.apache.camel.util.ObjectHelper;
import org.apache.camel.util.URISupport;
@@ -367,7 +368,8 @@ public class RestProducer extends DefaultAsyncProducer {
// is json binding required?
if (mode.contains("json") && json == null) {
- throw new IllegalArgumentException("JSON DataFormat " + name + "
not found.");
+ throw new IllegalArgumentException(
+ "JSON DataFormat " + name + " not found" +
ArtifactUtils.dataFormatHint(name) + ".");
}
if (json != null) {
@@ -421,7 +423,8 @@ public class RestProducer extends DefaultAsyncProducer {
// is xml binding required?
if (mode.contains("xml") && jaxb == null) {
- throw new IllegalArgumentException("XML DataFormat " + name + "
not found.");
+ throw new IllegalArgumentException(
+ "XML DataFormat " + name + " not found" +
ArtifactUtils.dataFormatHint(name) + ".");
}
if (jaxb != null) {
diff --git
a/components/camel-rest/src/test/java/org/apache/camel/component/rest/RestFactoryNotFoundMessageTest.java
b/components/camel-rest/src/test/java/org/apache/camel/component/rest/RestFactoryNotFoundMessageTest.java
new file mode 100644
index 000000000000..c9038f0ea7fa
--- /dev/null
+++
b/components/camel-rest/src/test/java/org/apache/camel/component/rest/RestFactoryNotFoundMessageTest.java
@@ -0,0 +1,163 @@
+/*
+ * 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.rest;
+
+import org.apache.camel.CamelContext;
+import org.apache.camel.Consumer;
+import org.apache.camel.NoSuchBeanException;
+import org.apache.camel.impl.DefaultCamelContext;
+import org.apache.camel.spi.RestConsumerFactory;
+import org.apache.camel.spi.RestProducerFactory;
+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 static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+/**
+ * When the Rest DSL finds no HTTP component to use, the message says which
components it looks for and the artifact of
+ * each; a component name that cannot be found says what to add or what the
option takes. This module has no HTTP
+ * component on its test classpath.
+ */
+class RestFactoryNotFoundMessageTest {
+
+ private SimpleRegistry registry;
+ private CamelContext camelContext;
+
+ @BeforeEach
+ void setUp() {
+ registry = new SimpleRegistry();
+ camelContext = new DefaultCamelContext(registry);
+ RestComponent component = new RestComponent();
+ component.setCamelContext(camelContext);
+ camelContext.addComponent("rest", component);
+ RestApiComponent apiComponent = new RestApiComponent();
+ apiComponent.setCamelContext(camelContext);
+ camelContext.addComponent("rest-api", apiComponent);
+ camelContext.start();
+ }
+
+ @AfterEach
+ void tearDown() {
+ camelContext.stop();
+ }
+
+ @Test
+ void consumerWithoutFactorySaysWhichComponentsToAdd() {
+ RestEndpoint endpoint = (RestEndpoint)
camelContext.getEndpoint("rest:get:users?host=localhost");
+
+ assertThatThrownBy(() -> endpoint.createConsumer(exchange -> {
+ }))
+ .isExactlyInstanceOf(IllegalStateException.class)
+ .hasMessageStartingWith("Cannot find RestConsumerFactory in
Registry or as a Component to use")
+ .hasMessageContaining("platform-http (camel-platform-http),
servlet (camel-servlet), jetty (camel-jetty)")
+ .hasMessageContaining("set the component option of the rest
configuration");
+ }
+
+ @Test
+ void producerWithoutFactorySaysWhichComponentsToAdd() {
+ RestEndpoint endpoint = (RestEndpoint)
camelContext.getEndpoint("rest:get:users?host=localhost");
+
+ assertThatThrownBy(endpoint::createProducer)
+ .isExactlyInstanceOf(IllegalStateException.class)
+ .hasMessageStartingWith("Cannot find RestProducerFactory in
Registry or as a Component to use")
+ .hasMessageContaining("http (camel-http), vertx-http
(camel-vertx-http)")
+ .hasMessageContaining("set the producerComponent option of the
rest configuration");
+ }
+
+ @Test
+ void apiConsumerWithoutFactorySaysWhichComponentsToAdd() {
+ RestApiEndpoint endpoint = (RestApiEndpoint)
camelContext.getEndpoint("rest-api:api-doc");
+
+ assertThatThrownBy(() -> endpoint.createConsumer(exchange -> {
+ }))
+ .isExactlyInstanceOf(IllegalStateException.class)
+ .hasMessageStartingWith("Cannot find RestApiConsumerFactory in
Registry or as a Component to use")
+ .hasMessageContaining("platform-http (camel-platform-http),
servlet (camel-servlet)");
+ }
+
+ @Test
+ void unknownComponentNameSaysWhatTheOptionTakes() {
+ // such as the name of a servlet given as the component
+ RestEndpoint endpoint = (RestEndpoint) camelContext
+
.getEndpoint("rest:get:users?host=localhost&consumerComponentName=MyServlet");
+
+ assertThatThrownBy(() -> endpoint.createConsumer(exchange -> {
+ }))
+ .isExactlyInstanceOf(NoSuchBeanException.class)
+ .hasMessageStartingWith("No bean could be found in the
registry for: MyServlet of type: "
+ + RestConsumerFactory.class.getName())
+ .hasMessageContaining("did you mean 'servlet'?")
+ .hasMessageContaining("takes the name of a component that
supports the Rest DSL: platform-http, servlet");
+ }
+
+ @Test
+ void missingConsumerComponentSaysWhichArtifactToAdd() {
+ RestEndpoint endpoint = (RestEndpoint) camelContext
+
.getEndpoint("rest:get:users?host=localhost&consumerComponentName=servlet");
+
+ assertThatThrownBy(() -> endpoint.createConsumer(exchange -> {
+ }))
+ .isExactlyInstanceOf(NoSuchBeanException.class)
+ .hasMessageStartingWith("No bean could be found in the
registry for: servlet of type: "
+ + RestConsumerFactory.class.getName())
+ .hasMessageContaining("add camel-servlet to the classpath")
+ .hasMessageNotContaining("takes the name of a component");
+ }
+
+ @Test
+ void missingProducerComponentSaysWhichArtifactToAdd() {
+ RestEndpoint endpoint = (RestEndpoint) camelContext
+
.getEndpoint("rest:get:users?host=localhost&producerComponentName=vertx-http");
+
+ assertThatThrownBy(endpoint::createProducer)
+ .isExactlyInstanceOf(NoSuchBeanException.class)
+ .hasMessageStartingWith("No bean could be found in the
registry for: vertx-http of type: "
+ + RestProducerFactory.class.getName())
+ .hasMessageContaining("add camel-vertx-http to the classpath");
+ }
+
+ @Test
+ void unknownProducerComponentNameSaysWhatTheOptionTakes() {
+ RestEndpoint endpoint = (RestEndpoint) camelContext
+
.getEndpoint("rest:get:users?host=localhost&producerComponentName=myClient");
+
+ assertThatThrownBy(endpoint::createProducer)
+ .isExactlyInstanceOf(NoSuchBeanException.class)
+ .hasMessageStartingWith("No bean could be found in the
registry for: myClient of type: "
+ + RestProducerFactory.class.getName())
+ .hasMessageContaining("takes the name of a component that
supports the Rest DSL: http, vertx-http");
+ }
+
+ @Test
+ void registeredFactoryIsUsed() throws Exception {
+ RestConsumerFactory factory = mock(RestConsumerFactory.class);
+ Consumer consumer = mock(Consumer.class);
+ when(factory.createConsumer(any(), any(), any(), any(), any(), any(),
any(), any(), any())).thenReturn(consumer);
+ registry.bind("myFactory", factory);
+
+ RestEndpoint endpoint = (RestEndpoint)
camelContext.getEndpoint("rest:get:users?host=localhost");
+
+ assertThat(endpoint.createConsumer(exchange -> {
+ })).isSameAs(consumer);
+ }
+}
diff --git
a/core/camel-core/src/test/java/org/apache/camel/component/rest/RestBindingMissingDataFormatTest.java
b/core/camel-core/src/test/java/org/apache/camel/component/rest/RestBindingMissingDataFormatTest.java
new file mode 100644
index 000000000000..fda758fe6004
--- /dev/null
+++
b/core/camel-core/src/test/java/org/apache/camel/component/rest/RestBindingMissingDataFormatTest.java
@@ -0,0 +1,224 @@
+/*
+ * 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.rest;
+
+import java.util.List;
+import java.util.concurrent.CopyOnWriteArrayList;
+
+import org.apache.camel.CamelContext;
+import org.apache.camel.Exchange;
+import org.apache.camel.Producer;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.log.ConsumingAppender;
+import org.apache.camel.component.mock.MockEndpoint;
+import org.apache.camel.impl.DefaultCamelContext;
+import org.apache.camel.model.rest.RestBindingMode;
+import org.apache.camel.support.DefaultRegistry;
+import org.apache.camel.support.processor.RestBindingAdviceFactory;
+import org.apache.camel.support.service.ServiceHelper;
+import org.apache.logging.log4j.Level;
+import org.apache.logging.log4j.core.Appender;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertInstanceOf;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * A binding mode that needs a data format that cannot be found fails when the
route is created, and says which artifact
+ * to add; binding mode auto that finds no data format at all says so. The
test class path of camel-core has a stand-in
+ * jackson data format, so a missing one is a name that does not resolve: gson
is a Camel data format that is not on it,
+ * noSuchJson is not a Camel data format at all.
+ */
+public class RestBindingMissingDataFormatTest {
+
+ private final List<String> warnings = new CopyOnWriteArrayList<>();
+ private Appender appender;
+ private CamelContext context;
+
+ @BeforeEach
+ public void before() {
+ // a name of its own, so two of these cannot replace each other's
appender
+ appender = ConsumingAppender.newAppender(
+ RestBindingAdviceFactory.class.getName(), "MissingDataFormat-"
+ System.nanoTime(), Level.WARN,
+ event ->
warnings.add(event.getMessage().getFormattedMessage()));
+ DefaultRegistry registry = new DefaultRegistry();
+ registry.bind("dummy-rest", new DummyRestConsumerFactory());
+ context = new DefaultCamelContext(registry);
+ }
+
+ @AfterEach
+ public void after() {
+ context.stop();
+ if (appender != null) {
+ appender.stop();
+ }
+ }
+
+ @Test
+ public void jsonBindingWithoutTheJsonDataFormatFailsAtStartup() throws
Exception {
+ addRest(RestBindingMode.json, "gson", "/j");
+
+ String message = startupFailure();
+ assertTrue(message.startsWith("JSON DataFormat gson not found"),
message);
+ assertTrue(message.contains("the gson data format is in camel-gson;
add camel-gson to the classpath"), message);
+ }
+
+ @Test
+ public void jsonBindingWithAnUnknownJsonDataFormatFailsAtStartup() throws
Exception {
+ addRest(RestBindingMode.json, "noSuchJson", "/j");
+
+ String message = startupFailure();
+ assertTrue(message.startsWith("JSON DataFormat noSuchJson not found"),
message);
+ assertTrue(message.contains("not a built-in Camel data format"),
message);
+ }
+
+ @Test
+ public void jsonXmlBindingWithoutTheJsonDataFormatFailsAtStartup() throws
Exception {
+ addRest(RestBindingMode.json_xml, "noSuchJson", "/j");
+
+ String message = startupFailure();
+ assertTrue(message.startsWith("JSON DataFormat noSuchJson not found"),
message);
+ }
+
+ @Test
+ public void xmlBindingWithoutJaxbSaysWhichArtifactToAdd() throws Exception
{
+ addRest(RestBindingMode.xml, null, "/x");
+
+ String message = startupFailure();
+ assertTrue(message.startsWith("XML DataFormat jaxb not found"),
message);
+ assertTrue(message.contains("add camel-jaxb to the classpath"),
message);
+ }
+
+ @Test
+ public void
producerJsonBindingWithoutTheJsonDataFormatSaysWhichArtifactToAdd() throws
Exception {
+ context.addComponent("mock-rest", new RestEndpointTest.MockRest());
+ context.getRestConfiguration().setJsonDataFormat("gson");
+ context.start();
+ RestEndpoint endpoint = context.getEndpoint(
+
"rest:get:hello?host=http://localhost&producerComponentName=mock-rest&bindingMode=json",
RestEndpoint.class);
+ Producer producer = endpoint.createProducer();
+
+ String message = rootCause(assertThrows(Exception.class, () ->
ServiceHelper.initService(producer))).getMessage();
+ assertTrue(message.startsWith("JSON DataFormat gson not found"),
message);
+ assertTrue(message.contains("add camel-gson to the classpath"),
message);
+ }
+
+ @Test
+ public void autoBindingWithNoDataFormatWarnsAndPassesTheBodyThrough()
throws Exception {
+ context.addRoutes(new RouteBuilder() {
+ @Override
+ public void configure() {
+
restConfiguration().host("localhost").bindingMode(RestBindingMode.auto).jsonDataFormat("noSuchJson");
+ rest("/p").post().type(Pojo.class).to("mock:p");
+ }
+ });
+ context.start();
+
+ assertEquals(1, warnings.size(), warnings.toString());
+ String warning = warnings.get(0);
+ assertTrue(warning.contains("bindingMode auto"), warning);
+ assertTrue(warning.contains("noSuchJson"), warning);
+ assertTrue(warning.contains("jaxb (camel-jaxb)"), warning);
+
+ // as before: the body is not bound
+ MockEndpoint mock = context.getEndpoint("mock:p", MockEndpoint.class);
+ mock.expectedMessageCount(1);
+ Exchange out = context.createProducerTemplate().request("seda:post-p",
e -> {
+ e.getIn().setHeader(Exchange.CONTENT_TYPE, "application/json");
+ e.getIn().setBody("{\"a\":1}");
+ });
+ mock.assertIsSatisfied();
+ assertNull(out.getException());
+ assertInstanceOf(String.class,
mock.getReceivedExchanges().get(0).getIn().getBody());
+ }
+
+ @Test
+ public void autoBindingWithAJsonDataFormatDoesNotWarn() throws Exception {
+ // the stand-in jackson is found, jaxb is not: auto binds what it can,
as documented
+ addRest(RestBindingMode.auto, null, "/p");
+ context.start();
+
+ assertTrue(warnings.isEmpty(), warnings.toString());
+ }
+
+ @Test
+ public void jsonBindingWithTheJsonDataFormatStarts() throws Exception {
+ addRest(RestBindingMode.json, null, "/j");
+ context.start();
+
+ assertTrue(context.getStatus().isStarted());
+ assertTrue(warnings.isEmpty(), warnings.toString());
+ }
+
+ @Test
+ public void
bindingOffWithClientRequestValidationStartsWithoutAJsonDataFormat() throws
Exception {
+ // the JSON data format is optional there: it is only used to check
that a JSON body parses
+ context.addRoutes(new RouteBuilder() {
+ @Override
+ public void configure() {
+
restConfiguration().host("localhost").bindingMode(RestBindingMode.off).jsonDataFormat("noSuchJson")
+ .clientRequestValidation(true);
+ rest("/v").post().to("mock:v");
+ }
+ });
+ context.start();
+
+ assertTrue(context.getStatus().isStarted());
+ assertTrue(warnings.isEmpty(), warnings.toString());
+ }
+
+ private void addRest(RestBindingMode mode, String jsonDataFormat, String
path) throws Exception {
+ context.addRoutes(new RouteBuilder() {
+ @Override
+ public void configure() {
+
restConfiguration().host("localhost").bindingMode(mode).jsonDataFormat(jsonDataFormat);
+ rest(path).post().to("mock:result");
+ }
+ });
+ }
+
+ private String startupFailure() {
+ Exception e = assertThrows(Exception.class, context::start);
+ IllegalArgumentException iae =
assertInstanceOf(IllegalArgumentException.class, rootCause(e));
+ return iae.getMessage();
+ }
+
+ private static Throwable rootCause(Throwable t) {
+ Throwable root = t;
+ while (root.getCause() != null && root.getCause() != root) {
+ root = root.getCause();
+ }
+ return root;
+ }
+
+ public static class Pojo {
+ private int a;
+
+ public int getA() {
+ return a;
+ }
+
+ public void setA(int a) {
+ this.a = a;
+ }
+ }
+}
diff --git
a/core/camel-support/src/main/java/org/apache/camel/support/processor/RestBindingAdviceFactory.java
b/core/camel-support/src/main/java/org/apache/camel/support/processor/RestBindingAdviceFactory.java
index 8e5dbcd3d1b5..ee5f003197ea 100644
---
a/core/camel-support/src/main/java/org/apache/camel/support/processor/RestBindingAdviceFactory.java
+++
b/core/camel-support/src/main/java/org/apache/camel/support/processor/RestBindingAdviceFactory.java
@@ -36,12 +36,17 @@ import org.apache.camel.support.PluginHelper;
import org.apache.camel.support.PropertyBindingSupport;
import org.apache.camel.support.PropertyConfigurerHelper;
import org.apache.camel.support.ResolverHelper;
+import org.apache.camel.util.ArtifactUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
* Factory to create {@link RestBindingAdvice} from the given configuration.
*/
public class RestBindingAdviceFactory {
+ private static final Logger LOG =
LoggerFactory.getLogger(RestBindingAdviceFactory.class);
+
// matched by name: camel-support cannot depend on camel-jackson3, and
JSON has no binding factory SPI
private static final String JACKSON3_PACKAGE =
"org.apache.camel.component.jackson3.";
private static final String FAIL_ON_UNKNOWN_PROPERTIES =
"FAIL_ON_UNKNOWN_PROPERTIES";
@@ -66,6 +71,7 @@ public class RestBindingAdviceFactory {
RestConfiguration config = camelContext.getRestConfiguration();
DataFormat json = null;
DataFormat outJson = null;
+ String jsonName = null;
// include json if we have client request validator as we need a json
parser
if (mode.contains("json") || "auto".equals(mode) ||
bc.isClientRequestValidation()) {
String name = config.getJsonDataFormat();
@@ -91,6 +97,13 @@ public class RestBindingAdviceFactory {
json = createDataFormat(camelContext, name);
outJson = createDataFormat(camelContext, name);
}
+ jsonName = name;
+
+ // is json binding required? (fail now, as the xml binding does,
rather than on every request)
+ if (mode.contains("json") && json == null) {
+ throw new IllegalArgumentException(
+ "JSON DataFormat " + name + " not found" +
ArtifactUtils.dataFormatHint(name) + ".");
+ }
if (json != null) {
setupJson(camelContext, config,
@@ -121,7 +134,15 @@ public class RestBindingAdviceFactory {
// is xml binding required?
if (mode.contains("xml") && xml == null) {
- throw new IllegalArgumentException("XML DataFormat " + name +
" not found.");
+ throw new IllegalArgumentException(
+ "XML DataFormat " + name + " not found" +
ArtifactUtils.dataFormatHint(name) + ".");
+ }
+
+ // auto binds the formats it finds, so with neither it binds
nothing, which is not what auto is set for
+ if ("auto".equals(mode) && json == null && xml == null) {
+ LOG.warn("Rest DSL bindingMode auto binds no request or
response body: neither the JSON data format {}{}"
+ + " nor the XML data format {}{} is on the classpath.
Add one of them, or set bindingMode to off.",
+ jsonName, artifactNote(jsonName), name,
artifactNote(name));
}
if (xml != null) {
@@ -332,6 +353,14 @@ public class RestBindingAdviceFactory {
|| key.startsWith("xml.out.");
}
+ /**
+ * The artifact of a Camel data format in parentheses, or what the hint
says of a name that is not one.
+ */
+ private static String artifactNote(String name) {
+ String artifact = ArtifactUtils.dataFormatArtifact(name);
+ return artifact != null ? " (" + artifact + ")" :
ArtifactUtils.dataFormatHint(name);
+ }
+
private static Object lookupByName(CamelContext camelContext, String name)
{
if (name == null) {
return null;
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 c773cd661d82..d02df3eeba0e 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
@@ -127,6 +127,16 @@ the WARN says to use `toD`. The route works as before.
Only the endpoint path is
of `sql`, and the components whose path option is marked
`supportSimpleExpression` in their metadata, which now
includes the template of `sql-stored` and the bucket name of `aws2-s3`.
+=== camel-core - Rest DSL binding mode json fails at startup without a JSON
data format
+
+A Rest DSL service with `bindingMode` `json` or `json_xml` whose JSON data
format (`jackson` unless `jsonDataFormat`
+names another) is not on the classpath now fails when Camel creates the route,
with
+`JSON DataFormat jackson not found (the jackson data format is in
camel-jackson3; add camel-jackson3 to the classpath).`
+Before, the route started and every request failed with `Cannot bind to json
as message body is not json compatible`.
+This is what `xml` binding already did without its XML data format. Add the
JSON data format, such as `camel-jackson3`
+(or `camel-jackson` for Jackson 2), or set `bindingMode` to `off`. With
`bindingMode` `auto`, a route that finds
+neither a JSON nor an XML data format still starts, and logs a WARN as it
binds nothing.
+
=== camel-core-model - doTry keeps doCatch and doFinally in its outputs
`doCatch` and `doFinally` written as properties of `doTry` in the YAML DSL are
now kept in the outputs of the
diff --git a/docs/user-manual/modules/ROOT/pages/rest-dsl-binding.adoc
b/docs/user-manual/modules/ROOT/pages/rest-dsl-binding.adoc
index 9d5789ff2fee..3bf8d16a2a44 100644
--- a/docs/user-manual/modules/ROOT/pages/rest-dsl-binding.adoc
+++ b/docs/user-manual/modules/ROOT/pages/rest-dsl-binding.adoc
@@ -24,13 +24,19 @@ The binding modes are:
the necessary data formats are included in the classpath. Notice that if
for example `camel-jaxb` is not on the classpath, then XML binding is
not enabled. Notice that for XML then `jaxb` is default, and you must be
explicit to set `xmlDataFormat=jacksonXml`
-if you want to use jackson XML instead.
+if you want to use jackson XML instead. When neither the JSON nor the XML data
format is found, nothing is bound,
+and Camel logs a WARN when it creates the route.
|`json` |Binding to/from JSON is enabled, and requires a JSON capable data
format on the classpath. By default, Camel will use `jackson` as the data
format.
|`xm` |Binding to/from XML is enabled, and requires `camel-jaxb` or
`camel-jacksonxml` on the classpath.
|`json_xml` |Binding to/from JSON and XML is enabled and requires both data
formats to be on the classpath.
|===
+With `json`, `xml` or `json_xml`, a data format the binding needs and cannot
find fails the route when Camel creates
+it, with a message that names the artifact to add, for example
+`JSON DataFormat jackson not found (the jackson data format is in
camel-jackson3; add camel-jackson3 to the classpath).`
+Jackson 2 users add `camel-jackson` instead.
+
IMPORTANT: In `auto` binding mode, the `consumes` option is used as a
*fallback* for format detection when the incoming request has no `Content-Type`
header (or the header does not indicate JSON or XML). It does *not* reject
requests whose `Content-Type` does not match `consumes`. For example, an
endpoint configured with `.consumes("application/json").bindingMode(auto)` will
still accept and deserialize an XML request if the client sends `Content-Type:
application/xml` and an XML-capable [...]
When using `camel-jaxb` for XML bindings, then