This is an automated email from the ASF dual-hosted git repository. lburgazzoli pushed a commit to branch master in repository https://gitbox.apache.org/repos/asf/camel.git
commit c4aadb30a12a204d33fd75007d8cbbd353912c69 Author: lburgazzoli <lburgazz...@gmail.com> AuthorDate: Tue Mar 17 11:55:04 2020 +0100 CAMEL-13844 RestConfiguration - Make it simpler and only have one --- components/camel-coap/pom.xml | 5 -- .../java/org/apache/camel/coap/CoAPComponent.java | 3 +- .../camel/coap/CoAPRestComponentTestBase.java | 2 +- .../apache/camel/coap/CoAPRestContextPathTest.java | 2 +- .../apache/camel/component/http/HttpComponent.java | 9 +- .../camel/component/jetty/JettyHttpComponent.java | 17 ++-- .../jetty/rest/RestHttpsClientAuthRouteTest.java | 2 +- .../rest/RestJettyRemoveAddRestAndRouteTest.java | 2 +- .../component/netty/http/NettyHttpComponent.java | 19 ++--- .../camel/openapi/OpenApiRestProducerFactory.java | 24 +++--- .../platform/http/PlatformHttpComponent.java | 7 +- .../rest/openapi/RestOpenApiEndpoint.java | 97 +++++++++------------- .../rest/openapi/RestOpenApiEndpointTest.java | 23 ++--- .../rest/openapi/RestOpenApiEndpointV3Test.java | 33 +++----- .../rest/swagger/RestSwaggerEndpoint.java | 29 ++----- .../rest/swagger/RestSwaggerEndpointTest.java | 11 +-- .../camel/component/rest/DefaultRestRegistry.java | 18 ++-- .../camel/component/rest/RestApiComponent.java | 2 +- .../camel/component/rest/RestApiEndpoint.java | 13 +-- .../apache/camel/component/rest/RestComponent.java | 81 +----------------- .../apache/camel/component/rest/RestEndpoint.java | 14 ++-- .../camel/component/servlet/ServletComponent.java | 12 +-- .../component/sparkrest/SparkRestComponent.java | 17 ++-- .../camel/swagger/SwaggerRestProducerFactory.java | 8 +- .../component/undertow/UndertowComponent.java | 25 +++--- .../camel/component/webhook/WebhookComponent.java | 4 +- .../main/java/org/apache/camel/CamelContext.java | 30 +------ .../org/apache/camel/spi/RestConfiguration.java | 4 +- .../camel/impl/engine/AbstractCamelContext.java | 53 +++++------- .../org/apache/camel/builder/RouteBuilder.java | 72 ++++++---------- .../camel/impl/lw/ImmutableCamelContext.java | 17 ---- .../impl/lw/RuntimeImmutableCamelContext.java | 15 ---- .../org/apache/camel/model/rest/RestConstants.java | 24 ------ .../apache/camel/model/rest/RestDefinition.java | 23 ++--- .../camel/reifier/rest/RestBindingReifier.java | 3 +- .../core/xml/AbstractCamelContextFactoryBean.java | 32 +++---- .../apache/camel/support/CamelContextHelper.java | 49 +++++++++++ 37 files changed, 295 insertions(+), 506 deletions(-) diff --git a/components/camel-coap/pom.xml b/components/camel-coap/pom.xml index 48bb71f..7cfd9f3 100644 --- a/components/camel-coap/pom.xml +++ b/components/camel-coap/pom.xml @@ -79,11 +79,6 @@ <artifactId>camel-test</artifactId> <scope>test</scope> </dependency> - <dependency> - <groupId>org.apache.camel</groupId> - <artifactId>camel-jetty</artifactId> - <scope>test</scope> - </dependency> </dependencies> </project> diff --git a/components/camel-coap/src/main/java/org/apache/camel/coap/CoAPComponent.java b/components/camel-coap/src/main/java/org/apache/camel/coap/CoAPComponent.java index cb4a5bb..43018a5 100644 --- a/components/camel-coap/src/main/java/org/apache/camel/coap/CoAPComponent.java +++ b/components/camel-coap/src/main/java/org/apache/camel/coap/CoAPComponent.java @@ -33,6 +33,7 @@ import org.apache.camel.Processor; import org.apache.camel.spi.RestConfiguration; import org.apache.camel.spi.RestConsumerFactory; import org.apache.camel.spi.annotations.Component; +import org.apache.camel.support.CamelContextHelper; import org.apache.camel.support.DefaultComponent; import org.apache.camel.util.FileUtil; import org.apache.camel.util.HostUtils; @@ -136,7 +137,7 @@ public class CoAPComponent extends DefaultComponent implements RestConsumerFacto RestConfiguration config = configuration; if (config == null) { - config = camelContext.getRestConfiguration("coap", true); + config = CamelContextHelper.getRestConfiguration(getCamelContext(), "coap"); } if (config.isEnableCORS()) { diff --git a/components/camel-coap/src/test/java/org/apache/camel/coap/CoAPRestComponentTestBase.java b/components/camel-coap/src/test/java/org/apache/camel/coap/CoAPRestComponentTestBase.java index 228cd12..9ed224d 100644 --- a/components/camel-coap/src/test/java/org/apache/camel/coap/CoAPRestComponentTestBase.java +++ b/components/camel-coap/src/test/java/org/apache/camel/coap/CoAPRestComponentTestBase.java @@ -123,7 +123,7 @@ abstract class CoAPRestComponentTestBase extends CamelTestSupport { return new RouteBuilder() { @Override public void configure() throws Exception { - RestConfigurationDefinition restConfig = restConfiguration("coap").scheme(getProtocol()).host("localhost").port(coapport); + RestConfigurationDefinition restConfig = restConfiguration().scheme(getProtocol()).host("localhost").port(coapport); decorateRestConfiguration(restConfig); rest("/TestParams").get().to("direct:get1").post().to("direct:post1"); diff --git a/components/camel-coap/src/test/java/org/apache/camel/coap/CoAPRestContextPathTest.java b/components/camel-coap/src/test/java/org/apache/camel/coap/CoAPRestContextPathTest.java index b82c9b7..6156411 100644 --- a/components/camel-coap/src/test/java/org/apache/camel/coap/CoAPRestContextPathTest.java +++ b/components/camel-coap/src/test/java/org/apache/camel/coap/CoAPRestContextPathTest.java @@ -37,7 +37,7 @@ public class CoAPRestContextPathTest extends CoAPTestSupport { return new RouteBuilder() { @Override public void configure() throws Exception { - restConfiguration("coap").host("localhost").port(PORT).contextPath("/rest/services"); + restConfiguration().host("localhost").port(PORT).contextPath("/rest/services"); rest("/test").get("/a").route().setBody(constant("GET: /test/a")); } diff --git a/components/camel-http/src/main/java/org/apache/camel/component/http/HttpComponent.java b/components/camel-http/src/main/java/org/apache/camel/component/http/HttpComponent.java index d1de045..df1db14 100644 --- a/components/camel-http/src/main/java/org/apache/camel/component/http/HttpComponent.java +++ b/components/camel-http/src/main/java/org/apache/camel/component/http/HttpComponent.java @@ -43,6 +43,7 @@ import org.apache.camel.spi.Metadata; import org.apache.camel.spi.RestConfiguration; import org.apache.camel.spi.RestProducerFactory; import org.apache.camel.spi.annotations.Component; +import org.apache.camel.support.CamelContextHelper; import org.apache.camel.support.PropertyBindingSupport; import org.apache.camel.support.RestProducerFactoryHelper; import org.apache.camel.support.jsse.SSLContextParameters; @@ -428,13 +429,7 @@ public class HttpComponent extends HttpCommonComponent implements RestProducerFa RestConfiguration config = configuration; if (config == null) { - config = camelContext.getRestConfiguration("http", false); - if (config == null) { - camelContext.getRestConfiguration(); - } - if (config == null) { - config = camelContext.getRestConfiguration("http", true); - } + config = CamelContextHelper.getRestConfiguration(getCamelContext(), "http"); } Map<String, Object> map = new HashMap<>(); diff --git a/components/camel-jetty-common/src/main/java/org/apache/camel/component/jetty/JettyHttpComponent.java b/components/camel-jetty-common/src/main/java/org/apache/camel/component/jetty/JettyHttpComponent.java index eac20722..55da1ea 100644 --- a/components/camel-jetty-common/src/main/java/org/apache/camel/component/jetty/JettyHttpComponent.java +++ b/components/camel-jetty-common/src/main/java/org/apache/camel/component/jetty/JettyHttpComponent.java @@ -57,6 +57,7 @@ import org.apache.camel.spi.Metadata; import org.apache.camel.spi.RestApiConsumerFactory; import org.apache.camel.spi.RestConfiguration; import org.apache.camel.spi.RestConsumerFactory; +import org.apache.camel.support.CamelContextHelper; import org.apache.camel.support.RestComponentHelper; import org.apache.camel.support.jsse.SSLContextParameters; import org.apache.camel.support.service.ServiceHelper; @@ -1048,8 +1049,9 @@ public abstract class JettyHttpComponent extends HttpCommonComponent implements // if no explicit port/host configured, then use port from rest configuration RestConfiguration config = configuration; if (config == null) { - config = camelContext.getRestConfiguration("jetty", true); + config = CamelContextHelper.getRestConfiguration(getCamelContext(), "jetty"); } + if (config.getScheme() != null) { scheme = config.getScheme(); } @@ -1083,11 +1085,11 @@ public abstract class JettyHttpComponent extends HttpCommonComponent implements // allow HTTP Options as we want to handle CORS in rest-dsl map.put("optionsEnabled", "true"); } - + if (api) { map.put("matchOnUriPrefix", "true"); } - + RestComponentHelper.addHttpRestrictParam(map, verb, cors); String url = RestComponentHelper.createRestConsumerUrl("jetty", scheme, host, port, path, map); @@ -1126,16 +1128,16 @@ public abstract class JettyHttpComponent extends HttpCommonComponent implements holder.setAsyncSupported(true); holder.setInitParameter(CamelServlet.ASYNC_PARAM, Boolean.toString(endpoint.isAsync())); context.addServlet(holder, "/*"); - + File file = File.createTempFile("camel", ""); file.delete(); - + //must register the MultipartConfig to make jetty server multipart aware holder.getRegistration().setMultipartConfig(new MultipartConfigElement(file.getParentFile().getAbsolutePath(), -1, -1, 0)); // use rest enabled resolver in case we use rest camelServlet.setServletResolveConsumerStrategy(new HttpRestServletResolveConsumerStrategy()); - + //must make RFC7578 as default to avoid using the deprecated MultiPartInputStreamParser connector.getConnectionFactory(HttpConnectionFactory.class).getHttpConfiguration() .setMultiPartFormDataCompliance(MultiPartFormDataCompliance.RFC7578); @@ -1245,7 +1247,8 @@ public abstract class JettyHttpComponent extends HttpCommonComponent implements protected void doStart() throws Exception { super.doStart(); - RestConfiguration config = getCamelContext().getRestConfiguration("jetty", true); + RestConfiguration config = CamelContextHelper.getRestConfiguration(getCamelContext(), "jetty"); + // configure additional options on jetty configuration if (config.getComponentProperties() != null && !config.getComponentProperties().isEmpty()) { setProperties(this, config.getComponentProperties()); diff --git a/components/camel-jetty/src/test/java/org/apache/camel/component/jetty/rest/RestHttpsClientAuthRouteTest.java b/components/camel-jetty/src/test/java/org/apache/camel/component/jetty/rest/RestHttpsClientAuthRouteTest.java index 7c5038e..c889e63 100644 --- a/components/camel-jetty/src/test/java/org/apache/camel/component/jetty/rest/RestHttpsClientAuthRouteTest.java +++ b/components/camel-jetty/src/test/java/org/apache/camel/component/jetty/rest/RestHttpsClientAuthRouteTest.java @@ -94,7 +94,7 @@ public class RestHttpsClientAuthRouteTest extends CamelTestSupport { return new RouteBuilder() { @Override public void configure() throws Exception { - RestConfigurationDefinition restConfig = restConfiguration("jetty").scheme("https").host("localhost").port(port); + RestConfigurationDefinition restConfig = restConfiguration().scheme("https").host("localhost").port(port); decorateRestConfiguration(restConfig); rest("/TestParams").get().to("direct:get1").post().to("direct:post1"); diff --git a/components/camel-jetty/src/test/java/org/apache/camel/component/jetty/rest/RestJettyRemoveAddRestAndRouteTest.java b/components/camel-jetty/src/test/java/org/apache/camel/component/jetty/rest/RestJettyRemoveAddRestAndRouteTest.java index 5207f82..481795b 100644 --- a/components/camel-jetty/src/test/java/org/apache/camel/component/jetty/rest/RestJettyRemoveAddRestAndRouteTest.java +++ b/components/camel-jetty/src/test/java/org/apache/camel/component/jetty/rest/RestJettyRemoveAddRestAndRouteTest.java @@ -70,7 +70,7 @@ public class RestJettyRemoveAddRestAndRouteTest extends BaseJettyTest { return new RouteBuilder() { @Override public void configure() throws Exception { - restConfiguration("jetty").host("localhost").port(getPort()); + restConfiguration().host("localhost").port(getPort()); rest("/").get("/issues/{isin}").route().id("issues").process(e -> e.getOut().setBody("Here's your issue " + e.getIn().getHeader("isin"))).endRest().get("/listings") .route().id("listings").process(e -> e.getOut().setBody("some listings")); diff --git a/components/camel-netty-http/src/main/java/org/apache/camel/component/netty/http/NettyHttpComponent.java b/components/camel-netty-http/src/main/java/org/apache/camel/component/netty/http/NettyHttpComponent.java index 3fb0272..92eb4ed 100644 --- a/components/camel-netty-http/src/main/java/org/apache/camel/component/netty/http/NettyHttpComponent.java +++ b/components/camel-netty-http/src/main/java/org/apache/camel/component/netty/http/NettyHttpComponent.java @@ -40,6 +40,7 @@ import org.apache.camel.spi.RestConfiguration; import org.apache.camel.spi.RestConsumerFactory; import org.apache.camel.spi.RestProducerFactory; import org.apache.camel.spi.annotations.Component; +import org.apache.camel.support.CamelContextHelper; import org.apache.camel.support.PropertyBindingSupport; import org.apache.camel.support.RestComponentHelper; import org.apache.camel.support.RestProducerFactoryHelper; @@ -351,7 +352,7 @@ public class NettyHttpComponent extends NettyComponent implements HeaderFilterSt // if no explicit port/host configured, then use port from rest configuration RestConfiguration config = configuration; if (config == null) { - config = camelContext.getRestConfiguration("netty-http", true); + config = CamelContextHelper.getRestConfiguration(getCamelContext(), "netty-http"); } if (config.getScheme() != null) { scheme = config.getScheme(); @@ -383,11 +384,11 @@ public class NettyHttpComponent extends NettyComponent implements HeaderFilterSt // allow HTTP Options as we want to handle CORS in rest-dsl boolean cors = config.isEnableCORS(); - + if (api) { map.put("matchOnUriPrefix", "true"); } - + RestComponentHelper.addHttpRestrictParam(map, verb, cors); String url = RestComponentHelper.createRestConsumerUrl("netty-http", scheme, host, port, path, map); @@ -404,6 +405,7 @@ public class NettyHttpComponent extends NettyComponent implements HeaderFilterSt return consumer; } + @SuppressWarnings("unchecked") @Override public Producer createProducer(CamelContext camelContext, String host, String verb, String basePath, String uriTemplate, String queryParameters, @@ -422,13 +424,7 @@ public class NettyHttpComponent extends NettyComponent implements HeaderFilterSt url += "/" + uriTemplate; } - RestConfiguration config = getCamelContext().getRestConfiguration("netty-http", false); - if (config == null) { - config = getCamelContext().getRestConfiguration(); - } - if (config == null) { - config = getCamelContext().getRestConfiguration("netty-http", true); - } + RestConfiguration config = CamelContextHelper.getRestConfiguration(getCamelContext(), "netty-http"); Map<String, Object> map = new HashMap<>(); // build query string, and append any endpoint configuration properties @@ -471,7 +467,8 @@ public class NettyHttpComponent extends NettyComponent implements HeaderFilterSt protected void doStart() throws Exception { super.doStart(); - RestConfiguration config = getCamelContext().getRestConfiguration("netty-http", true); + RestConfiguration config = CamelContextHelper.getRestConfiguration(getCamelContext(), "netty-http"); + // configure additional options on netty-http configuration if (config.getComponentProperties() != null && !config.getComponentProperties().isEmpty()) { setProperties(this, config.getComponentProperties()); diff --git a/components/camel-openapi-java/src/main/java/org/apache/camel/openapi/OpenApiRestProducerFactory.java b/components/camel-openapi-java/src/main/java/org/apache/camel/openapi/OpenApiRestProducerFactory.java index 1cf1c3b..9047db1 100644 --- a/components/camel-openapi-java/src/main/java/org/apache/camel/openapi/OpenApiRestProducerFactory.java +++ b/components/camel-openapi-java/src/main/java/org/apache/camel/openapi/OpenApiRestProducerFactory.java @@ -37,6 +37,7 @@ import org.apache.camel.CamelContext; import org.apache.camel.Producer; import org.apache.camel.spi.RestConfiguration; import org.apache.camel.spi.RestProducerFactory; +import org.apache.camel.support.CamelContextHelper; import org.apache.camel.util.CollectionStringBuffer; import org.apache.camel.util.IOHelper; import org.slf4j.Logger; @@ -100,13 +101,13 @@ public class OpenApiRestProducerFactory implements RestProducerFactory { final JsonNode node = mapper.readTree(is); LOG.debug("Loaded openApi api-doc:\n{}", node.toPrettyString()); return (OasDocument)Library.readDocument(node); - - + + } finally { IOHelper.close(is); } - - + + } private OasOperation getOpenApiOperation(OasDocument openApi, String verb, String path) { @@ -166,7 +167,7 @@ public class OpenApiRestProducerFactory implements RestProducerFactory { list.add(ct); } } - + } if (list == null || list.isEmpty()) { if (openApi instanceof Oas20Document) { @@ -187,13 +188,13 @@ public class OpenApiRestProducerFactory implements RestProducerFactory { list = ((Oas20Operation)operation).consumes; } else if (operation instanceof Oas30Operation) { Oas30Operation oas30Operation = (Oas30Operation)operation; - if (oas30Operation.requestBody != null - && oas30Operation.requestBody.content != null) { + if (oas30Operation.requestBody != null + && oas30Operation.requestBody.content != null) { for (String ct : oas30Operation.requestBody.content.keySet()) { list.add(ct); } } - + } if (list == null || list.isEmpty()) { if (openApi instanceof Oas20Document) { @@ -211,18 +212,19 @@ public class OpenApiRestProducerFactory implements RestProducerFactory { String basePath = null; String uriTemplate = null; if (host == null) { - + //if no explicit host has been configured then use host and base path from the openApi api-doc host = RestOpenApiSupport.getHostFromOasDocument(openApi); basePath = RestOpenApiSupport.getBasePathFromOasDocument(openApi); uriTemplate = path; - + } else { // path includes also uri template basePath = path; uriTemplate = null; } - RestConfiguration config = camelContext.getRestConfiguration(componentName, true); + + RestConfiguration config = CamelContextHelper.getRestConfiguration(camelContext, componentName); return factory.createProducer(camelContext, host, verb, basePath, uriTemplate, queryParameters, consumes, produces, config, parameters); } else { diff --git a/components/camel-platform-http/src/main/java/org/apache/camel/component/platform/http/PlatformHttpComponent.java b/components/camel-platform-http/src/main/java/org/apache/camel/component/platform/http/PlatformHttpComponent.java index 47229bd..cd37c62 100644 --- a/components/camel-platform-http/src/main/java/org/apache/camel/component/platform/http/PlatformHttpComponent.java +++ b/components/camel-platform-http/src/main/java/org/apache/camel/component/platform/http/PlatformHttpComponent.java @@ -28,6 +28,7 @@ import org.apache.camel.spi.RestApiConsumerFactory; import org.apache.camel.spi.RestConfiguration; import org.apache.camel.spi.RestConsumerFactory; import org.apache.camel.spi.annotations.Component; +import org.apache.camel.support.CamelContextHelper; import org.apache.camel.support.DefaultComponent; import org.apache.camel.support.RestComponentHelper; import org.apache.camel.util.FileUtil; @@ -103,7 +104,7 @@ public class PlatformHttpComponent extends DefaultComponent implements RestConsu // if no explicit port/host configured, then use port from rest configuration RestConfiguration config = configuration; if (config == null) { - config = camelContext.getRestConfiguration(PlatformHttpConstants.PLATFORM_HTTP_COMPONENT_NAME, true); + config = CamelContextHelper.getRestConfiguration(getCamelContext(), PlatformHttpConstants.PLATFORM_HTTP_COMPONENT_NAME); } Map<String, Object> map = RestComponentHelper.initRestEndpointProperties(PlatformHttpConstants.PLATFORM_HTTP_COMPONENT_NAME, config); @@ -113,11 +114,11 @@ public class PlatformHttpComponent extends DefaultComponent implements RestConsu // allow HTTP Options as we want to handle CORS in rest-dsl map.put("optionsEnabled", "true"); } - + if (api) { map.put("matchOnUriPrefix", "true"); } - + RestComponentHelper.addHttpRestrictParam(map, verb, cors); // do not append with context-path as the servlet path should be without context-path diff --git a/components/camel-rest-openapi/src/main/java/org/apache/camel/component/rest/openapi/RestOpenApiEndpoint.java b/components/camel-rest-openapi/src/main/java/org/apache/camel/component/rest/openapi/RestOpenApiEndpoint.java index 9bcdfa2..9ec2282 100644 --- a/components/camel-rest-openapi/src/main/java/org/apache/camel/component/rest/openapi/RestOpenApiEndpoint.java +++ b/components/camel-rest-openapi/src/main/java/org/apache/camel/component/rest/openapi/RestOpenApiEndpoint.java @@ -36,6 +36,8 @@ import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.Stream; +import static java.util.Optional.ofNullable; + import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import io.apicurio.datamodels.Library; @@ -69,13 +71,13 @@ import org.apache.camel.spi.RestConfiguration; import org.apache.camel.spi.UriEndpoint; import org.apache.camel.spi.UriParam; import org.apache.camel.spi.UriPath; +import org.apache.camel.support.CamelContextHelper; import org.apache.camel.support.DefaultEndpoint; import org.apache.camel.support.ResourceHelper; import org.apache.camel.util.ObjectHelper; import org.apache.camel.util.StringHelper; import org.apache.camel.util.UnsafeUriCharactersEncoder; -import static java.util.Optional.ofNullable; import static org.apache.camel.component.rest.openapi.RestOpenApiHelper.isHostParam; import static org.apache.camel.component.rest.openapi.RestOpenApiHelper.isMediaRange; import static org.apache.camel.util.ObjectHelper.isNotEmpty; @@ -208,8 +210,8 @@ public final class RestOpenApiEndpoint extends DefaultEndpoint { } } - - + + String supportedOperations = paths.getItems().stream().flatMap(p -> getOperationMap(p).values().stream()) .map(p -> p.operationId).collect(Collectors.joining(", ")); throw new IllegalArgumentException("The specified operation with ID: `" + operationId @@ -217,7 +219,7 @@ public final class RestOpenApiEndpoint extends DefaultEndpoint { + "`. Operations defined in the specification are: " + supportedOperations); } - + private Map<HttpMethod, OasOperation> getOperationMap(OasPathItem path) { Map<HttpMethod, OasOperation> result = new LinkedHashMap<HttpMethod, OasOperation>(); @@ -314,13 +316,11 @@ public final class RestOpenApiEndpoint extends DefaultEndpoint { Producer createProducerFor(final Document openapi, final OasOperation operation, final String method, final String uriTemplate) throws Exception { final String basePath = determineBasePath(openapi); - - final StringBuilder componentEndpointUri = new StringBuilder(200).append("rest:").append(method).append(":") - .append(basePath).append(":").append(uriTemplate); + final String componentEndpointUri = "rest:" + method + ":" + basePath + ":" + uriTemplate; final CamelContext camelContext = getCamelContext(); - final Endpoint endpoint = camelContext.getEndpoint(componentEndpointUri.toString()); + final Endpoint endpoint = camelContext.getEndpoint(componentEndpointUri); Map<String, Object> params = determineEndpointParameters(openapi, operation); boolean hasHost = params.containsKey("host"); @@ -343,32 +343,28 @@ public final class RestOpenApiEndpoint extends DefaultEndpoint { } final String specificationBasePath = getBasePathFromOasDocument((OasDocument)openapi); - + if (isNotEmpty(specificationBasePath)) { return specificationBasePath; } final CamelContext camelContext = getCamelContext(); - final RestConfiguration specificConfiguration = camelContext.getRestConfiguration(assignedComponentName, false); - if (specificConfiguration != null && isNotEmpty(specificConfiguration.getContextPath())) { - return specificConfiguration.getContextPath(); - } - - final RestConfiguration restConfiguration = camelContext.getRestConfiguration("rest-openapi", true); + final RestConfiguration restConfiguration = CamelContextHelper.getRestConfiguration(camelContext, assignedComponentName); final String restConfigurationBasePath = restConfiguration.getContextPath(); + if (isNotEmpty(restConfigurationBasePath)) { return restConfigurationBasePath; } return RestOpenApiComponent.DEFAULT_BASE_PATH; } - + public static String getBasePathFromOasDocument(final OasDocument openapi) { String basePath = null; if (openapi instanceof Oas20Document) { basePath = ((Oas20Document)openapi).basePath; } else if (openapi instanceof Oas30Document) { - if (((Oas30Document)openapi).getServers() != null + if (((Oas30Document)openapi).getServers() != null && ((Oas30Document)openapi).getServers().get(0) != null) { try { Oas30Server server = (Oas30Server)((Oas30Document)openapi).getServers().get(0); @@ -386,24 +382,24 @@ public final class RestOpenApiEndpoint extends DefaultEndpoint { if ("/".equals(basePath)) { basePath = ""; } - } - + } + } catch (MalformedURLException e) { //not a valid whole url, just the basePath basePath = ((Oas30Document)openapi).getServers().get(0).url; } } - + } return basePath; - + } - + public static String parseVariables(String url, Oas30Server server) { Pattern p = Pattern.compile("\\{(.*?)\\}"); Matcher m = p.matcher(url); while (m.find()) { - + String var = m.group(1); if (server != null && server.variables != null && server.variables.get(var) != null) { String varValue = server.variables.get(var).default_; @@ -437,7 +433,7 @@ public final class RestOpenApiEndpoint extends DefaultEndpoint { List<String> specificationLevelConsumers = new ArrayList<String>(); if (openapi instanceof Oas20Document) { specificationLevelConsumers = ((Oas20Document)openapi).produces; - } + } List<String> operationLevelConsumers = new ArrayList<String>(); if (operation instanceof Oas20Operation) { operationLevelConsumers = ((Oas20Operation)operation).produces; @@ -461,25 +457,25 @@ public final class RestOpenApiEndpoint extends DefaultEndpoint { // what we produce is what the API defined by OpenApi specification // consumes - + List<String> specificationLevelProducers = new ArrayList<String>(); if (openapi instanceof Oas20Document) { specificationLevelProducers = ((Oas20Document)openapi).consumes; - } + } List<String> operationLevelProducers = new ArrayList<String>(); if (operation instanceof Oas20Operation) { operationLevelProducers = ((Oas20Operation)operation).consumes; } else if (operation instanceof Oas30Operation) { Oas30Operation oas30Operation = (Oas30Operation)operation; - if (oas30Operation.requestBody != null - && oas30Operation.requestBody.content != null) { + if (oas30Operation.requestBody != null + && oas30Operation.requestBody.content != null) { for (String ct : oas30Operation.requestBody.content.keySet()) { operationLevelProducers.add(ct); } } - + } - + final String determinedProducers = determineOption(specificationLevelProducers, operationLevelProducers, component.getProduces(), produces); @@ -527,8 +523,8 @@ public final class RestOpenApiEndpoint extends DefaultEndpoint { return componentHost; } - - + + if (openapi instanceof Oas20Document) { final String openapiScheme = pickBestScheme(specificationUri.getScheme(), ((Oas20Document)openapi).schemes); final String openapiHost = ((Oas20Document)openapi).host; @@ -541,10 +537,10 @@ public final class RestOpenApiEndpoint extends DefaultEndpoint { //But there could be many servers url(like one for production and one for test) //Use first one here Oas30Document oas30Document = (Oas30Document)openapi; - if (oas30Document.getServers() != null + if (oas30Document.getServers() != null && oas30Document.getServers().get(0) != null) { try { - + URL serverUrl = new URL(parseVariables(oas30Document.getServers().get(0).url, (Oas30Server)oas30Document.getServers().get(0))); final String openapiScheme = serverUrl.getProtocol(); final String openapiHost = serverUrl.getHost(); @@ -558,22 +554,9 @@ public final class RestOpenApiEndpoint extends DefaultEndpoint { } final CamelContext camelContext = getCamelContext(); - - final RestConfiguration specificRestConfiguration = camelContext.getRestConfiguration(assignedComponentName, - false); - final String specificConfigurationHost = hostFrom(specificRestConfiguration); - if (specificConfigurationHost != null) { - return specificConfigurationHost; - } - - final RestConfiguration componentRestConfiguration = camelContext.getRestConfiguration("rest-openapi", false); - final String componentConfigurationHost = hostFrom(componentRestConfiguration); - if (componentConfigurationHost != null) { - return componentConfigurationHost; - } - - final RestConfiguration globalRestConfiguration = camelContext.getRestConfiguration(); + final RestConfiguration globalRestConfiguration = CamelContextHelper.getRestConfiguration(camelContext, assignedComponentName); final String globalConfigurationHost = hostFrom(globalRestConfiguration); + if (globalConfigurationHost != null) { return globalConfigurationHost; } @@ -695,12 +678,12 @@ public final class RestOpenApiEndpoint extends DefaultEndpoint { if (openapi instanceof Oas20Document) { Oas20Document oas20Document = (Oas20Document)openapi; Oas20SecurityDefinitions securityDefinitions = oas20Document.securityDefinitions; - + for (final SecurityRequirement securityRequirement : securityRequirements) { for (final String securityRequirementName : securityRequirement.getSecurityRequirementNames()) { final Oas20SecurityScheme securitySchemeDefinition = securityDefinitions .getSecurityScheme(securityRequirementName); - if (securitySchemeDefinition.in != null + if (securitySchemeDefinition.in != null && securitySchemeDefinition.in.equals("query")) { Oas20Parameter securityParameter = new Oas20Parameter(securitySchemeDefinition.name); securityParameter.required = true; @@ -708,7 +691,7 @@ public final class RestOpenApiEndpoint extends DefaultEndpoint { securityParameter.description = securitySchemeDefinition.description; apiKeyQueryParameters.add(securityParameter); } - + } } } else if (openapi instanceof Oas30Document) { @@ -723,13 +706,13 @@ public final class RestOpenApiEndpoint extends DefaultEndpoint { securityParameter.description = securitySchemeDefinition.description; apiKeyQueryParameters.add(securityParameter); } - + } } } else { throw new IllegalStateException("We only support OpenApi 2.0 or 3.0 document here"); } - + } if (operation.getParameters() != null) { @@ -775,7 +758,7 @@ public final class RestOpenApiEndpoint extends DefaultEndpoint { static Document loadSpecificationFrom(final CamelContext camelContext, final URI uri) throws IOException { final ObjectMapper mapper = new ObjectMapper(); - + final String uriAsString = uri.toString(); try (InputStream stream = ResourceHelper.resolveMandatoryResourceAsInputStream(camelContext, uriAsString)) { @@ -783,7 +766,7 @@ public final class RestOpenApiEndpoint extends DefaultEndpoint { return Library.readDocument(node); } catch (final Exception e) { - + throw new IllegalArgumentException("The given OpenApi specification could not be loaded from `" + uri + "`. Tried loading using Camel's resource resolution and using OpenApi's own resource resolution." + " OpenApi tends to swallow exceptions while parsing, try specifying Java system property `debugParser`" @@ -823,7 +806,7 @@ public final class RestOpenApiEndpoint extends DefaultEndpoint { return expression.toString(); } - + enum HttpMethod { POST, GET, diff --git a/components/camel-rest-openapi/src/test/java/org/apache/camel/component/rest/openapi/RestOpenApiEndpointTest.java b/components/camel-rest-openapi/src/test/java/org/apache/camel/component/rest/openapi/RestOpenApiEndpointTest.java index d57bf28..755f0dc 100644 --- a/components/camel-rest-openapi/src/test/java/org/apache/camel/component/rest/openapi/RestOpenApiEndpointTest.java +++ b/components/camel-rest-openapi/src/test/java/org/apache/camel/component/rest/openapi/RestOpenApiEndpointTest.java @@ -86,7 +86,7 @@ public class RestOpenApiEndpointTest { final RestConfiguration restConfiguration = new RestConfiguration(); final CamelContext camelContext = mock(CamelContext.class); - when(camelContext.getRestConfiguration("rest-openapi", true)).thenReturn(restConfiguration); + when(camelContext.getRestConfiguration()).thenReturn(restConfiguration); final Oas20Document openapi = new Oas20Document(); @@ -136,7 +136,7 @@ public class RestOpenApiEndpointTest { operation.createParameter(); assertThat(endpoint.determineEndpointParameters(openapi, operation)) .containsOnly(entry("host", "http://petstore.openapi.io")); - + component.setComponentName("xyz"); assertThat(endpoint.determineEndpointParameters(openapi, operation)) @@ -148,7 +148,7 @@ public class RestOpenApiEndpointTest { produces.add("application/xml"); openapi.consumes = consumers; openapi.produces = produces; - + assertThat(endpoint.determineEndpointParameters(openapi, operation)).containsOnly( entry("host", "http://petstore.openapi.io"), entry("producerComponentName", "xyz"), entry("consumes", "application/xml"), entry("produces", "application/json")); @@ -280,14 +280,9 @@ public class RestOpenApiEndpointTest { @Test public void shouldHonourHostPrecedence() { final RestConfiguration globalRestConfiguration = new RestConfiguration(); - - final RestConfiguration componentRestConfiguration = new RestConfiguration(); - final RestConfiguration specificRestConfiguration = new RestConfiguration(); - final CamelContext camelContext = mock(CamelContext.class); + when(camelContext.getRestConfiguration()).thenReturn(globalRestConfiguration); - when(camelContext.getRestConfiguration("rest-openapi", false)).thenReturn(componentRestConfiguration); - when(camelContext.getRestConfiguration("petstore", false)).thenReturn(specificRestConfiguration); final RestOpenApiComponent component = new RestOpenApiComponent(); component.setCamelContext(camelContext); @@ -306,10 +301,6 @@ public class RestOpenApiEndpointTest { globalRestConfiguration.setScheme("http"); assertThat(endpoint.determineHost(openapi)).isEqualTo("http://component-rest"); - specificRestConfiguration.setHost("specific-rest"); - specificRestConfiguration.setScheme("http"); - assertThat(endpoint.determineHost(openapi)).isEqualTo("http://specific-rest"); - openapi.host = "specification"; openapi.schemes = Arrays.asList("http"); assertThat(endpoint.determineHost(openapi)).isEqualTo("http://specification"); @@ -338,7 +329,7 @@ public class RestOpenApiEndpointTest { apiKeys.in = "header"; openapi.securityDefinitions = openapi.createSecurityDefinitions(); openapi.securityDefinitions.addItem("apiKeys", apiKeys); - + final Oas20Operation operation = new Oas20Operation("get"); Oas20Parameter oas20Parameter = new Oas20Parameter("q"); oas20Parameter.in = "query"; @@ -347,8 +338,8 @@ public class RestOpenApiEndpointTest { SecurityRequirement securityRequirement = operation.createSecurityRequirement(); securityRequirement.addSecurityRequirementItem("apiKeys", Collections.emptyList()); operation.addSecurityRequirement(securityRequirement); - - + + assertThat(endpoint.determineEndpointParameters(openapi, operation)) .containsOnly(entry("host", "http://petstore.openapi.io"), entry("queryParameters", "q={q}")); diff --git a/components/camel-rest-openapi/src/test/java/org/apache/camel/component/rest/openapi/RestOpenApiEndpointV3Test.java b/components/camel-rest-openapi/src/test/java/org/apache/camel/component/rest/openapi/RestOpenApiEndpointV3Test.java index ec9f76a..175dafe 100644 --- a/components/camel-rest-openapi/src/test/java/org/apache/camel/component/rest/openapi/RestOpenApiEndpointV3Test.java +++ b/components/camel-rest-openapi/src/test/java/org/apache/camel/component/rest/openapi/RestOpenApiEndpointV3Test.java @@ -88,7 +88,7 @@ public class RestOpenApiEndpointV3Test { final RestConfiguration restConfiguration = new RestConfiguration(); final CamelContext camelContext = mock(CamelContext.class); - when(camelContext.getRestConfiguration("rest-openapi", true)).thenReturn(restConfiguration); + when(camelContext.getRestConfiguration()).thenReturn(restConfiguration); final Oas30Document openapi = new Oas30Document(); @@ -107,7 +107,7 @@ public class RestOpenApiEndpointV3Test { .isEqualTo("/rest"); openapi.addServer("http://petstore.openapi.io", "v3 test"); - + component.setBasePath("/component"); assertThat(endpoint.determineBasePath(openapi)).as( @@ -136,7 +136,7 @@ public class RestOpenApiEndpointV3Test { operation.createParameter(); assertThat(endpoint.determineEndpointParameters(openapi, operation)) .containsOnly(entry("host", "http://petstore.openapi.io")); - + component.setComponentName("xyz"); assertThat(endpoint.determineEndpointParameters(openapi, operation)) @@ -151,7 +151,7 @@ public class RestOpenApiEndpointV3Test { operation.responses.addResponse("200", operation.responses.createResponse("200")); for (String consumer : consumers) { operation.requestBody.content.put(consumer, operation.requestBody.createMediaType(consumer)); - + } for (String produce : produces) { for (OasResponse response : operation.responses.getResponses()) { @@ -159,7 +159,7 @@ public class RestOpenApiEndpointV3Test { oas30Response.content.put(produce, oas30Response.createMediaType(produce)); } } - + assertThat(endpoint.determineEndpointParameters(openapi, operation)).containsOnly( entry("host", "http://petstore.openapi.io"), entry("producerComponentName", "xyz"), entry("consumes", "application/xml"), entry("produces", "application/json")); @@ -294,13 +294,8 @@ public class RestOpenApiEndpointV3Test { public void shouldHonourHostPrecedence() { final RestConfiguration globalRestConfiguration = new RestConfiguration(); - final RestConfiguration componentRestConfiguration = new RestConfiguration(); - final RestConfiguration specificRestConfiguration = new RestConfiguration(); - final CamelContext camelContext = mock(CamelContext.class); when(camelContext.getRestConfiguration()).thenReturn(globalRestConfiguration); - when(camelContext.getRestConfiguration("rest-openapi", false)).thenReturn(componentRestConfiguration); - when(camelContext.getRestConfiguration("petstore", false)).thenReturn(specificRestConfiguration); final RestOpenApiComponent component = new RestOpenApiComponent(); component.setCamelContext(camelContext); @@ -309,9 +304,9 @@ public class RestOpenApiEndpointV3Test { "http://specification-uri#getPetById", component, Collections.emptyMap()); final Oas30Document openapi = new Oas30Document(); - + assertThat(endpoint.determineHost(openapi)).isEqualTo("http://specification-uri"); - + globalRestConfiguration.setHost("global-rest"); globalRestConfiguration.setScheme("http"); assertThat(endpoint.determineHost(openapi)).isEqualTo("http://global-rest"); @@ -320,12 +315,6 @@ public class RestOpenApiEndpointV3Test { globalRestConfiguration.setScheme("http"); assertThat(endpoint.determineHost(openapi)).isEqualTo("http://component-rest"); - specificRestConfiguration.setHost("specific-rest"); - specificRestConfiguration.setScheme("http"); - assertThat(endpoint.determineHost(openapi)).isEqualTo("http://specific-rest"); - - - component.setHost("http://component"); assertThat(endpoint.determineHost(openapi)).isEqualTo("http://component"); @@ -349,9 +338,9 @@ public class RestOpenApiEndpointV3Test { apiKeys.name = "key"; apiKeys.in = "header"; openapi.components = openapi.createComponents(); - + openapi.components.addSecurityScheme("apiKeys", apiKeys); - + final Oas30Operation operation = new Oas30Operation("get"); Oas30Parameter oas30Parameter = new Oas30Parameter("q"); oas30Parameter.in = "query"; @@ -360,8 +349,8 @@ public class RestOpenApiEndpointV3Test { SecurityRequirement securityRequirement = operation.createSecurityRequirement(); securityRequirement.addSecurityRequirementItem("apiKeys", Collections.emptyList()); operation.addSecurityRequirement(securityRequirement); - - + + assertThat(endpoint.determineEndpointParameters(openapi, operation)) .containsOnly(entry("host", "http://petstore.openapi.io"), entry("queryParameters", "q={q}")); diff --git a/components/camel-rest-swagger/src/main/java/org/apache/camel/component/rest/swagger/RestSwaggerEndpoint.java b/components/camel-rest-swagger/src/main/java/org/apache/camel/component/rest/swagger/RestSwaggerEndpoint.java index 32802f0..74d8a70 100644 --- a/components/camel-rest-swagger/src/main/java/org/apache/camel/component/rest/swagger/RestSwaggerEndpoint.java +++ b/components/camel-rest-swagger/src/main/java/org/apache/camel/component/rest/swagger/RestSwaggerEndpoint.java @@ -31,6 +31,8 @@ import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; +import static java.util.Optional.ofNullable; + import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import io.swagger.models.HttpMethod; @@ -59,6 +61,7 @@ import org.apache.camel.spi.RestConfiguration; import org.apache.camel.spi.UriEndpoint; import org.apache.camel.spi.UriParam; import org.apache.camel.spi.UriPath; +import org.apache.camel.support.CamelContextHelper; import org.apache.camel.support.DefaultEndpoint; import org.apache.camel.support.ResourceHelper; import org.apache.camel.support.jsse.SSLContextParameters; @@ -67,7 +70,6 @@ import org.apache.camel.util.StringHelper; import org.apache.camel.util.UnsafeUriCharactersEncoder; import org.apache.http.client.methods.HttpGet; -import static java.util.Optional.ofNullable; import static org.apache.camel.component.rest.swagger.RestSwaggerHelper.isHostParam; import static org.apache.camel.component.rest.swagger.RestSwaggerHelper.isMediaRange; import static org.apache.camel.util.ObjectHelper.isNotEmpty; @@ -332,13 +334,9 @@ public final class RestSwaggerEndpoint extends DefaultEndpoint { } final CamelContext camelContext = getCamelContext(); - final RestConfiguration specificConfiguration = camelContext.getRestConfiguration(assignedComponentName, false); - if (specificConfiguration != null && isNotEmpty(specificConfiguration.getContextPath())) { - return specificConfiguration.getContextPath(); - } - - final RestConfiguration restConfiguration = camelContext.getRestConfiguration("rest-swagger", true); + final RestConfiguration restConfiguration = CamelContextHelper.getRestConfiguration(camelContext, assignedComponentName); final String restConfigurationBasePath = restConfiguration.getContextPath(); + if (isNotEmpty(restConfigurationBasePath)) { return restConfigurationBasePath; } @@ -431,22 +429,9 @@ public final class RestSwaggerEndpoint extends DefaultEndpoint { } final CamelContext camelContext = getCamelContext(); - - final RestConfiguration specificRestConfiguration = camelContext.getRestConfiguration(assignedComponentName, - false); - final String specificConfigurationHost = hostFrom(specificRestConfiguration); - if (specificConfigurationHost != null) { - return specificConfigurationHost; - } - - final RestConfiguration componentRestConfiguration = camelContext.getRestConfiguration("rest-swagger", false); - final String componentConfigurationHost = hostFrom(componentRestConfiguration); - if (componentConfigurationHost != null) { - return componentConfigurationHost; - } - - final RestConfiguration globalRestConfiguration = camelContext.getRestConfiguration(); + final RestConfiguration globalRestConfiguration = CamelContextHelper.getRestConfiguration(camelContext, assignedComponentName); final String globalConfigurationHost = hostFrom(globalRestConfiguration); + if (globalConfigurationHost != null) { return globalConfigurationHost; } diff --git a/components/camel-rest-swagger/src/test/java/org/apache/camel/component/rest/swagger/RestSwaggerEndpointTest.java b/components/camel-rest-swagger/src/test/java/org/apache/camel/component/rest/swagger/RestSwaggerEndpointTest.java index 42c3cd6..fb82e4f 100644 --- a/components/camel-rest-swagger/src/test/java/org/apache/camel/component/rest/swagger/RestSwaggerEndpointTest.java +++ b/components/camel-rest-swagger/src/test/java/org/apache/camel/component/rest/swagger/RestSwaggerEndpointTest.java @@ -84,7 +84,7 @@ public class RestSwaggerEndpointTest { final RestConfiguration restConfiguration = new RestConfiguration(); final CamelContext camelContext = mock(CamelContext.class); - when(camelContext.getRestConfiguration("rest-swagger", true)).thenReturn(restConfiguration); + when(camelContext.getRestConfiguration()).thenReturn(restConfiguration); final Swagger swagger = new Swagger(); @@ -267,13 +267,8 @@ public class RestSwaggerEndpointTest { public void shouldHonourHostPrecedence() { final RestConfiguration globalRestConfiguration = new RestConfiguration(); - final RestConfiguration componentRestConfiguration = new RestConfiguration(); - final RestConfiguration specificRestConfiguration = new RestConfiguration(); - final CamelContext camelContext = mock(CamelContext.class); when(camelContext.getRestConfiguration()).thenReturn(globalRestConfiguration); - when(camelContext.getRestConfiguration("rest-swagger", false)).thenReturn(componentRestConfiguration); - when(camelContext.getRestConfiguration("petstore", false)).thenReturn(specificRestConfiguration); final RestSwaggerComponent component = new RestSwaggerComponent(); component.setCamelContext(camelContext); @@ -292,10 +287,6 @@ public class RestSwaggerEndpointTest { globalRestConfiguration.setScheme("http"); assertThat(endpoint.determineHost(swagger)).isEqualTo("http://component-rest"); - specificRestConfiguration.setHost("specific-rest"); - specificRestConfiguration.setScheme("http"); - assertThat(endpoint.determineHost(swagger)).isEqualTo("http://specific-rest"); - swagger.host("specification").scheme(Scheme.HTTP); assertThat(endpoint.determineHost(swagger)).isEqualTo("http://specification"); diff --git a/components/camel-rest/src/main/java/org/apache/camel/component/rest/DefaultRestRegistry.java b/components/camel-rest/src/main/java/org/apache/camel/component/rest/DefaultRestRegistry.java index 469f073..1be9520 100644 --- a/components/camel-rest/src/main/java/org/apache/camel/component/rest/DefaultRestRegistry.java +++ b/components/camel-rest/src/main/java/org/apache/camel/component/rest/DefaultRestRegistry.java @@ -33,6 +33,7 @@ import org.apache.camel.Service; import org.apache.camel.ServiceStatus; import org.apache.camel.StatefulService; import org.apache.camel.StaticService; +import org.apache.camel.ValueHolder; import org.apache.camel.spi.RestConfiguration; import org.apache.camel.spi.RestRegistry; import org.apache.camel.support.LifecycleStrategySupport; @@ -73,8 +74,8 @@ public class DefaultRestRegistry extends ServiceSupport implements StaticService if (apiProducer == null) { Endpoint restApiEndpoint = null; Endpoint restEndpoint = null; - for (Map.Entry<String, Endpoint> entry : camelContext.getEndpointMap().entrySet()) { - String uri = entry.getKey(); + for (Map.Entry<? extends ValueHolder<String>, Endpoint> entry : camelContext.getEndpointRegistry().entrySet()) { + String uri = entry.getKey().get(); if (uri.startsWith("rest-api:")) { restApiEndpoint = entry.getValue(); break; @@ -89,11 +90,15 @@ public class DefaultRestRegistry extends ServiceSupport implements StaticService String componentName = rest.getProducerComponentName(); if (componentName != null) { - RestConfiguration config = camelContext.getRestConfiguration(componentName, true); + RestConfiguration config = camelContext.getRestConfiguration(); + String apiComponent = config.getApiComponent() != null ? config.getApiComponent() : RestApiEndpoint.DEFAULT_API_COMPONENT_NAME; String path = config.getApiContextPath() != null ? config.getApiContextPath() : "api-doc"; - restApiEndpoint = camelContext.getEndpoint(String.format("rest-api:%s/%s?componentName=%s&apiComponentName=%s&contextIdPattern=#name#", - path, camelContext.getName(), componentName, apiComponent)); + String uri = String.format( + "rest-api:%s/%s?componentName=%s&apiComponentName=%s&contextIdPattern=#name#", + path, camelContext.getName(), componentName, apiComponent); + + restApiEndpoint = camelContext.getEndpoint(uri); } } @@ -113,8 +118,7 @@ public class DefaultRestRegistry extends ServiceSupport implements StaticService Exchange dummy = apiProducer.getEndpoint().createExchange(); apiProducer.process(dummy); - String json = dummy.getMessage().getBody(String.class); - return json; + return dummy.getMessage().getBody(String.class); } catch (Exception e) { throw RuntimeCamelException.wrapRuntimeCamelException(e); } diff --git a/components/camel-rest/src/main/java/org/apache/camel/component/rest/RestApiComponent.java b/components/camel-rest/src/main/java/org/apache/camel/component/rest/RestApiComponent.java index 93bc285..c4526ec 100644 --- a/components/camel-rest/src/main/java/org/apache/camel/component/rest/RestApiComponent.java +++ b/components/camel-rest/src/main/java/org/apache/camel/component/rest/RestApiComponent.java @@ -39,7 +39,7 @@ public class RestApiComponent extends DefaultComponent { answer.setParameters(parameters); // if no explicit component name was given, then fallback and use default configured component name - if (answer.getConsumerComponentName() == null && getCamelContext().getRestConfiguration() != null) { + if (answer.getConsumerComponentName() == null) { answer.setConsumerComponentName(getCamelContext().getRestConfiguration().getComponent()); } 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 39e2b75..73b5009 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 @@ -34,6 +34,7 @@ import org.apache.camel.spi.RestConfiguration; import org.apache.camel.spi.UriEndpoint; import org.apache.camel.spi.UriParam; import org.apache.camel.spi.UriPath; +import org.apache.camel.support.CamelContextHelper; import org.apache.camel.support.DefaultEndpoint; import org.apache.camel.util.HostUtils; import org.apache.camel.util.ObjectHelper; @@ -132,13 +133,7 @@ public class RestApiEndpoint extends DefaultEndpoint { public Producer createProducer() throws Exception { RestApiProcessorFactory factory = null; - RestConfiguration config = getCamelContext().getRestConfiguration(consumerComponentName, false); - if (config == null) { - config = getCamelContext().getRestConfiguration(); - } - if (config == null) { - config = getCamelContext().getRestConfiguration(consumerComponentName, true); - } + RestConfiguration config = CamelContextHelper.getRestConfiguration(getCamelContext(), getConsumerComponentName()); // lookup in registry Set<RestApiProcessorFactory> factories = getCamelContext().getRegistry().findByType(RestApiProcessorFactory.class); @@ -155,7 +150,7 @@ public class RestApiEndpoint extends DefaultEndpoint { FactoryFinder finder = getCamelContext().adapt(ExtendedCamelContext.class).getFactoryFinder(RESOURCE_PATH); factory = finder.newInstance(name, RestApiProcessorFactory.class).orElse(null); } - + if (factory == null) { String name = apiComponentName != null ? apiComponentName : config.getApiComponent(); if (name == null) { @@ -263,7 +258,7 @@ public class RestApiEndpoint extends DefaultEndpoint { if (factory != null) { // calculate the url to the rest API service - RestConfiguration config = getCamelContext().getRestConfiguration(cname, true); + RestConfiguration config = CamelContextHelper.getRestConfiguration(getCamelContext(), cname); // calculate the url to the rest API service String path = getPath(); diff --git a/components/camel-rest/src/main/java/org/apache/camel/component/rest/RestComponent.java b/components/camel-rest/src/main/java/org/apache/camel/component/rest/RestComponent.java index d9aa538..72d631e 100644 --- a/components/camel-rest/src/main/java/org/apache/camel/component/rest/RestComponent.java +++ b/components/camel-rest/src/main/java/org/apache/camel/component/rest/RestComponent.java @@ -16,17 +16,13 @@ */ package org.apache.camel.component.rest; -import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; -import org.apache.camel.CamelContext; import org.apache.camel.Endpoint; import org.apache.camel.component.extension.ComponentVerifierExtension; import org.apache.camel.spi.Metadata; import org.apache.camel.spi.RestConfiguration; -import org.apache.camel.spi.RestConfiguration.RestBindingMode; -import org.apache.camel.spi.RestConfiguration.RestHostNameResolver; import org.apache.camel.support.CamelContextHelper; import org.apache.camel.support.DefaultComponent; import org.apache.camel.util.FileUtil; @@ -68,10 +64,7 @@ public class RestComponent extends DefaultComponent { answer.setProducerComponentName(pname); answer.setApiDoc(apiDoc); - RestConfiguration config = new RestConfiguration(); - mergeConfigurations(getCamelContext(), config, findGlobalRestConfiguration()); - mergeConfigurations(getCamelContext(), config, getCamelContext().getRestConfiguration(cname, false)); - mergeConfigurations(getCamelContext(), config, getCamelContext().getRestConfiguration(pname, false)); + RestConfiguration config = CamelContextHelper.getRestConfiguration(getCamelContext(), cname, pname); // if no explicit host was given, then fallback and use default configured host String h = getAndRemoveOrResolveReferenceParameter(parameters, "host", String.class, host); @@ -218,78 +211,6 @@ public class RestComponent extends DefaultComponent { // Helpers // **************************************** - private RestConfiguration findGlobalRestConfiguration() { - CamelContext context = getCamelContext(); - - RestConfiguration conf = CamelContextHelper.lookup(context, DEFAULT_REST_CONFIGURATION_ID, RestConfiguration.class); - if (conf == null) { - conf = CamelContextHelper.findByType(getCamelContext(), RestConfiguration.class); - } - - return conf; - } - - private RestConfiguration mergeConfigurations(CamelContext camelContext, RestConfiguration conf, RestConfiguration from) throws Exception { - if (conf == from) { - return conf; - } - if (from != null) { - // Merge properties - conf.setComponent(or(conf.getComponent(), from.getComponent())); - conf.setApiComponent(or(conf.getApiComponent(), from.getApiComponent())); - conf.setProducerComponent(or(conf.getProducerComponent(), from.getProducerComponent())); - conf.setProducerApiDoc(or(conf.getProducerApiDoc(), from.getProducerApiDoc())); - conf.setScheme(or(conf.getScheme(), from.getScheme())); - conf.setHost(or(conf.getHost(), from.getHost())); - conf.setUseXForwardHeaders(or(conf.isUseXForwardHeaders(), from.isUseXForwardHeaders())); - conf.setApiHost(or(conf.getApiHost(), from.getApiHost())); - conf.setPort(or(conf.getPort(), from.getPort())); - conf.setContextPath(or(conf.getContextPath(), from.getContextPath())); - conf.setApiContextPath(or(conf.getApiContextPath(), from.getApiContextPath())); - conf.setApiContextRouteId(or(conf.getApiContextRouteId(), from.getApiContextRouteId())); - conf.setApiContextIdPattern(or(conf.getApiContextIdPattern(), from.getApiContextIdPattern())); - conf.setApiContextListing(or(conf.isApiContextListing(), from.isApiContextListing())); - conf.setApiVendorExtension(or(conf.isApiVendorExtension(), from.isApiVendorExtension())); - conf.setHostNameResolver(or(conf.getHostNameResolver(), from.getHostNameResolver(), RestHostNameResolver.allLocalIp)); - conf.setBindingMode(or(conf.getBindingMode(), from.getBindingMode(), RestBindingMode.off)); - conf.setSkipBindingOnErrorCode(or(conf.isSkipBindingOnErrorCode(), from.isSkipBindingOnErrorCode())); - conf.setClientRequestValidation(or(conf.isClientRequestValidation(), from.isClientRequestValidation())); - conf.setEnableCORS(or(conf.isEnableCORS(), from.isEnableCORS())); - conf.setJsonDataFormat(or(conf.getJsonDataFormat(), from.getJsonDataFormat())); - conf.setXmlDataFormat(or(conf.getXmlDataFormat(), from.getXmlDataFormat())); - conf.setComponentProperties(mergeProperties(conf.getComponentProperties(), from.getComponentProperties())); - conf.setEndpointProperties(mergeProperties(conf.getEndpointProperties(), from.getEndpointProperties())); - conf.setConsumerProperties(mergeProperties(conf.getConsumerProperties(), from.getConsumerProperties())); - conf.setDataFormatProperties(mergeProperties(conf.getDataFormatProperties(), from.getDataFormatProperties())); - conf.setApiProperties(mergeProperties(conf.getApiProperties(), from.getApiProperties())); - conf.setCorsHeaders(mergeProperties(conf.getCorsHeaders(), from.getCorsHeaders())); - } - - return conf; - } - - private <T> T or(T t1, T t2) { - return t2 != null ? t2 : t1; - } - - private <T> T or(T t1, T t2, T def) { - return t2 != null && t2 != def ? t2 : t1; - } - - private <T> Map<String, T> mergeProperties(Map<String, T> base, Map<String, T> addons) { - if (base != null || addons != null) { - Map<String, T> result = new HashMap<>(); - if (base != null) { - result.putAll(base); - } - if (addons != null) { - result.putAll(addons); - } - return result; - } - return base; - } - public ComponentVerifierExtension getVerifier() { return (scope, parameters) -> getExtension(ComponentVerifierExtension.class).orElseThrow(UnsupportedOperationException::new).verify(scope, parameters); } 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 d814060..3506c14 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 @@ -35,6 +35,7 @@ import org.apache.camel.spi.RestProducerFactory; import org.apache.camel.spi.UriEndpoint; import org.apache.camel.spi.UriParam; import org.apache.camel.spi.UriPath; +import org.apache.camel.support.CamelContextHelper; import org.apache.camel.support.DefaultEndpoint; import org.apache.camel.support.component.PropertyConfigurerSupport; import org.apache.camel.util.HostUtils; @@ -300,6 +301,7 @@ public class RestEndpoint extends DefaultEndpoint { this.bindingMode = RestConfiguration.RestBindingMode.valueOf(bindingMode.toLowerCase()); } + @SuppressWarnings("unchecked") @Override public Producer createProducer() throws Exception { if (ObjectHelper.isEmpty(host)) { @@ -423,13 +425,9 @@ public class RestEndpoint extends DefaultEndpoint { if (factory != null) { LOG.debug("Using RestProducerFactory: {}", factory); - RestConfiguration config = getCamelContext().getRestConfiguration(pname, false); - if (config == null) { - config = getCamelContext().getRestConfiguration(); - } - if (config == null) { - config = getCamelContext().getRestConfiguration(pname, true); - } + // here we look for the producer part so we should not care about the component + // configured for the consumer part + RestConfiguration config = CamelContextHelper.getRestConfiguration(getCamelContext(), null, pname); Producer producer; if (apiDocFactory != null) { @@ -524,7 +522,7 @@ public class RestEndpoint extends DefaultEndpoint { String host = ""; int port = 80; - RestConfiguration config = getCamelContext().getRestConfiguration(cname, true); + RestConfiguration config = CamelContextHelper.getRestConfiguration(getCamelContext(), cname); if (config.getScheme() != null) { scheme = config.getScheme(); } diff --git a/components/camel-servlet/src/main/java/org/apache/camel/component/servlet/ServletComponent.java b/components/camel-servlet/src/main/java/org/apache/camel/component/servlet/ServletComponent.java index e37320a..d19a0e2 100644 --- a/components/camel-servlet/src/main/java/org/apache/camel/component/servlet/ServletComponent.java +++ b/components/camel-servlet/src/main/java/org/apache/camel/component/servlet/ServletComponent.java @@ -33,6 +33,7 @@ import org.apache.camel.spi.RestApiConsumerFactory; import org.apache.camel.spi.RestConfiguration; import org.apache.camel.spi.RestConsumerFactory; import org.apache.camel.spi.annotations.Component; +import org.apache.camel.support.CamelContextHelper; import org.apache.camel.support.RestComponentHelper; import org.apache.camel.util.FileUtil; import org.apache.camel.util.StringHelper; @@ -279,7 +280,7 @@ public class ServletComponent extends HttpCommonComponent implements RestConsume // if no explicit port/host configured, then use port from rest configuration RestConfiguration config = configuration; if (config == null) { - config = camelContext.getRestConfiguration("servlet", true); + config = CamelContextHelper.getRestConfiguration(getCamelContext(), "servlet"); } Map<String, Object> map = RestComponentHelper.initRestEndpointProperties("servlet", config); @@ -289,14 +290,14 @@ public class ServletComponent extends HttpCommonComponent implements RestConsume // allow HTTP Options as we want to handle CORS in rest-dsl map.put("optionsEnabled", "true"); } - + if (api) { map.put("matchOnUriPrefix", "true"); } - + RestComponentHelper.addHttpRestrictParam(map, verb, cors); - String url = RestComponentHelper.createRestConsumerUrl("servlet", path, map); + String url = RestComponentHelper.createRestConsumerUrl("servlet", path, map); ServletEndpoint endpoint = camelContext.getEndpoint(url, ServletEndpoint.class); setProperties(endpoint, parameters); @@ -324,7 +325,8 @@ public class ServletComponent extends HttpCommonComponent implements RestConsume protected void doStart() throws Exception { super.doStart(); - RestConfiguration config = getCamelContext().getRestConfiguration("servlet", true); + RestConfiguration config = CamelContextHelper.getRestConfiguration(getCamelContext(), "servlet"); + // configure additional options on jetty configuration if (config.getComponentProperties() != null && !config.getComponentProperties().isEmpty()) { setProperties(this, config.getComponentProperties()); diff --git a/components/camel-spark-rest/src/main/java/org/apache/camel/component/sparkrest/SparkRestComponent.java b/components/camel-spark-rest/src/main/java/org/apache/camel/component/sparkrest/SparkRestComponent.java index 0e3df18..12fac30 100644 --- a/components/camel-spark-rest/src/main/java/org/apache/camel/component/sparkrest/SparkRestComponent.java +++ b/components/camel-spark-rest/src/main/java/org/apache/camel/component/sparkrest/SparkRestComponent.java @@ -30,6 +30,7 @@ import org.apache.camel.spi.RestApiConsumerFactory; import org.apache.camel.spi.RestConfiguration; import org.apache.camel.spi.RestConsumerFactory; import org.apache.camel.spi.annotations.Component; +import org.apache.camel.support.CamelContextHelper; import org.apache.camel.support.DefaultComponent; import org.apache.camel.support.RestComponentHelper; import org.apache.camel.util.FileUtil; @@ -42,7 +43,7 @@ import spark.Service; public class SparkRestComponent extends DefaultComponent implements RestConsumerFactory, RestApiConsumerFactory { private static final Pattern PATTERN = Pattern.compile("\\{(.*?)\\}"); - + /** * SPARK instance for the component */ @@ -232,7 +233,7 @@ public class SparkRestComponent extends DefaultComponent implements RestConsumer sparkInstance.port(getPort()); } else { // if no explicit port configured, then use port from rest configuration - RestConfiguration config = getCamelContext().getRestConfiguration("spark-rest", true); + RestConfiguration config = CamelContextHelper.getRestConfiguration(getCamelContext(), "spark-rest"); int port = config.getPort(); if (port > 0) { sparkInstance.port(port); @@ -244,7 +245,7 @@ public class SparkRestComponent extends DefaultComponent implements RestConsumer sparkInstance.ipAddress(host); } else { // if no explicit port configured, then use port from rest configuration - RestConfiguration config = getCamelContext().getRestConfiguration("spark-rest", true); + RestConfiguration config = CamelContextHelper.getRestConfiguration(getCamelContext(), "spark-rest"); host = config.getHost(); if (ObjectHelper.isEmpty(host)) { if (config.getHostNameResolver() == RestConfiguration.RestHostNameResolver.allLocalIp) { @@ -261,11 +262,11 @@ public class SparkRestComponent extends DefaultComponent implements RestConsumer if (keystoreFile != null || truststoreFile != null) { sparkInstance.secure(keystoreFile, keystorePassword, truststoreFile, truststorePassword); } - + CamelSpark.threadPool(sparkInstance, minThreads, maxThreads, timeOutMillis); // configure component options - RestConfiguration config = getCamelContext().getRestConfiguration("spark-rest", true); + RestConfiguration config = CamelContextHelper.getRestConfiguration(getCamelContext(), "spark-rest"); // configure additional options on spark configuration if (config.getComponentProperties() != null && !config.getComponentProperties().isEmpty()) { setProperties(sparkConfiguration, config.getComponentProperties()); @@ -307,7 +308,7 @@ public class SparkRestComponent extends DefaultComponent implements RestConsumer RestConfiguration config = configuration; if (config == null) { - config = camelContext.getRestConfiguration("spark-rest", true); + config = CamelContextHelper.getRestConfiguration(camelContext, "spark-rest"); } Map<String, Object> map = new HashMap<>(); @@ -335,10 +336,10 @@ public class SparkRestComponent extends DefaultComponent implements RestConsumer path = contextPath + "/" + path; } } - + if (api) { map.put("matchOnUriPrefix", "true"); - } + } String url = RestComponentHelper.createRestConsumerUrl("spark-rest", verb, path, map); diff --git a/components/camel-swagger-java/src/main/java/org/apache/camel/swagger/SwaggerRestProducerFactory.java b/components/camel-swagger-java/src/main/java/org/apache/camel/swagger/SwaggerRestProducerFactory.java index 6a915f2..69838c8 100644 --- a/components/camel-swagger-java/src/main/java/org/apache/camel/swagger/SwaggerRestProducerFactory.java +++ b/components/camel-swagger-java/src/main/java/org/apache/camel/swagger/SwaggerRestProducerFactory.java @@ -29,6 +29,7 @@ import org.apache.camel.CamelContext; import org.apache.camel.Producer; import org.apache.camel.spi.RestConfiguration; import org.apache.camel.spi.RestProducerFactory; +import org.apache.camel.support.CamelContextHelper; import org.apache.camel.util.CollectionStringBuffer; import org.apache.camel.util.IOHelper; import org.slf4j.Logger; @@ -180,8 +181,11 @@ public class SwaggerRestProducerFactory implements RestProducerFactory { basePath = path; uriTemplate = null; } - RestConfiguration config = camelContext.getRestConfiguration(componentName, true); - return factory.createProducer(camelContext, host, verb, basePath, uriTemplate, queryParameters, consumes, produces, config, parameters); + + RestConfiguration config = CamelContextHelper.getRestConfiguration(camelContext, componentName); + + return factory.createProducer( + camelContext, host, verb, basePath, uriTemplate, queryParameters, consumes, produces, config, parameters); } else { throw new IllegalStateException("Cannot find RestProducerFactory in Registry or as a Component to use"); diff --git a/components/camel-undertow/src/main/java/org/apache/camel/component/undertow/UndertowComponent.java b/components/camel-undertow/src/main/java/org/apache/camel/component/undertow/UndertowComponent.java index 3f963e8..de3e329 100644 --- a/components/camel-undertow/src/main/java/org/apache/camel/component/undertow/UndertowComponent.java +++ b/components/camel-undertow/src/main/java/org/apache/camel/component/undertow/UndertowComponent.java @@ -41,6 +41,7 @@ import org.apache.camel.spi.RestConfiguration; import org.apache.camel.spi.RestConsumerFactory; import org.apache.camel.spi.RestProducerFactory; import org.apache.camel.spi.annotations.Component; +import org.apache.camel.support.CamelContextHelper; import org.apache.camel.support.DefaultComponent; import org.apache.camel.support.RestComponentHelper; import org.apache.camel.support.RestProducerFactoryHelper; @@ -166,7 +167,8 @@ public class UndertowComponent extends DefaultComponent implements RestConsumerF RestConfiguration config = configuration; if (config == null) { - config = camelContext.getRestConfiguration(getComponentName(), true); + config = CamelContextHelper.getRestConfiguration(camelContext, getComponentName()); + } if (config.getScheme() != null) { scheme = config.getScheme(); @@ -197,10 +199,10 @@ public class UndertowComponent extends DefaultComponent implements RestConsumerF Map<String, Object> map = RestComponentHelper.initRestEndpointProperties(getComponentName(), config); // build query string, and append any endpoint configuration properties - + // must use upper case for restrict String restrict = verb.toUpperCase(Locale.US); - + boolean explicitOptions = restrict.contains("OPTIONS"); boolean cors = config.isEnableCORS(); @@ -211,11 +213,11 @@ public class UndertowComponent extends DefaultComponent implements RestConsumerF // the rest-dsl is using OPTIONS map.put("optionsEnabled", "true"); } - + if (api) { map.put("matchOnUriPrefix", "true"); } - + RestComponentHelper.addHttpRestrictParam(map, verb, !explicitOptions); String url = RestComponentHelper.createRestConsumerUrl(getComponentName(), scheme, host, port, path, map); @@ -259,13 +261,7 @@ public class UndertowComponent extends DefaultComponent implements RestConsumerF url += "/" + uriTemplate; } - RestConfiguration config = getCamelContext().getRestConfiguration(getComponentName(), false); - if (config == null) { - config = getCamelContext().getRestConfiguration(); - } - if (config == null) { - config = getCamelContext().getRestConfiguration(getComponentName(), true); - } + RestConfiguration config = CamelContextHelper.getRestConfiguration(camelContext, getComponentName()); Map<String, Object> map = new HashMap<>(); // build query string, and append any endpoint configuration properties @@ -304,7 +300,8 @@ public class UndertowComponent extends DefaultComponent implements RestConsumerF protected void doStart() throws Exception { super.doStart(); - RestConfiguration config = getCamelContext().getRestConfiguration(getComponentName(), true); + RestConfiguration config = CamelContextHelper.getRestConfiguration(getCamelContext(), getComponentName()); + // configure additional options on undertow configuration if (config.getComponentProperties() != null && !config.getComponentProperties().isEmpty()) { setProperties(this, config.getComponentProperties()); @@ -314,7 +311,7 @@ public class UndertowComponent extends DefaultComponent implements RestConsumerF public HttpHandler registerEndpoint(UndertowConsumer consumer, HttpHandlerRegistrationInfo registrationInfo, SSLContext sslContext, HttpHandler handler) { final URI uri = registrationInfo.getUri(); final UndertowHostKey key = new UndertowHostKey(uri.getHost(), uri.getPort(), sslContext); - final UndertowHost host = undertowRegistry.computeIfAbsent(key, k -> createUndertowHost(k)); + final UndertowHost host = undertowRegistry.computeIfAbsent(key, this::createUndertowHost); host.validateEndpointURI(uri); handlers.add(registrationInfo); diff --git a/components/camel-webhook/src/main/java/org/apache/camel/component/webhook/WebhookComponent.java b/components/camel-webhook/src/main/java/org/apache/camel/component/webhook/WebhookComponent.java index 2bf7cb3..3e98aa2 100644 --- a/components/camel-webhook/src/main/java/org/apache/camel/component/webhook/WebhookComponent.java +++ b/components/camel-webhook/src/main/java/org/apache/camel/component/webhook/WebhookComponent.java @@ -24,6 +24,7 @@ import org.apache.camel.Endpoint; import org.apache.camel.spi.Metadata; import org.apache.camel.spi.RestConfiguration; import org.apache.camel.spi.annotations.Component; +import org.apache.camel.support.CamelContextHelper; import org.apache.camel.support.DefaultComponent; import org.apache.camel.util.ObjectHelper; import org.apache.camel.util.URISupport; @@ -48,7 +49,8 @@ public class WebhookComponent extends DefaultComponent { } WebhookConfiguration config = configuration != null ? configuration.copy() : new WebhookConfiguration(); - RestConfiguration restConfig = getCamelContext().getRestConfiguration(config.getWebhookComponentName(), true); + + RestConfiguration restConfig = CamelContextHelper.getRestConfiguration(getCamelContext(), config.getWebhookComponentName()); config.storeConfiguration(restConfig); WebhookEndpoint endpoint = new WebhookEndpoint(uri, this, config); diff --git a/core/camel-api/src/main/java/org/apache/camel/CamelContext.java b/core/camel-api/src/main/java/org/apache/camel/CamelContext.java index a51c1d7..dc15f44 100644 --- a/core/camel-api/src/main/java/org/apache/camel/CamelContext.java +++ b/core/camel-api/src/main/java/org/apache/camel/CamelContext.java @@ -622,30 +622,6 @@ public interface CamelContext extends CamelContextLifecycle, RuntimeConfiguratio RestConfiguration getRestConfiguration(); /** - * Sets a custom {@link org.apache.camel.spi.RestConfiguration} - * - * @param restConfiguration the REST configuration - */ - @Deprecated - void addRestConfiguration(RestConfiguration restConfiguration); - - /** - * Gets the REST configuration for the given component - * - * @param component the component name to get the configuration - * @param defaultIfNotFound determine if the default configuration is returned if there isn't a - * specific configuration for the given component - * @return the configuration, or <tt>null</tt> if none has been configured. - */ - RestConfiguration getRestConfiguration(String component, boolean defaultIfNotFound); - - /** - * Gets all the RestConfiguration's - */ - @Deprecated - Collection<RestConfiguration> getRestConfigurations(); - - /** * Gets the {@link org.apache.camel.spi.RestRegistry} to use */ RestRegistry getRestRegistry(); @@ -740,7 +716,7 @@ public interface CamelContext extends CamelContextLifecycle, RuntimeConfiguratio * @throws IllegalArgumentException is thrown if property placeholders was used and there was an error resolving them */ String resolvePropertyPlaceholders(String text); - + /** * Returns the configured properties component or create one if none has been configured. * @@ -1092,9 +1068,9 @@ public interface CamelContext extends CamelContextLifecycle, RuntimeConfiguratio * @return the uuidGenerator */ UuidGenerator getUuidGenerator(); - + /** - * Sets a custom {@link UuidGenerator} (should only be set once) + * Sets a custom {@link UuidGenerator} (should only be set once) * * @param uuidGenerator the UUID Generator */ diff --git a/core/camel-api/src/main/java/org/apache/camel/spi/RestConfiguration.java b/core/camel-api/src/main/java/org/apache/camel/spi/RestConfiguration.java index 7be7c34..01a7836 100644 --- a/core/camel-api/src/main/java/org/apache/camel/spi/RestConfiguration.java +++ b/core/camel-api/src/main/java/org/apache/camel/spi/RestConfiguration.java @@ -29,6 +29,8 @@ public class RestConfiguration { public static final String CORS_ACCESS_CONTROL_MAX_AGE = "3600"; public static final String CORS_ACCESS_CONTROL_ALLOW_HEADERS = "Origin, Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers"; + public static final String DEFAULT_REST_CONFIGURATION_ID = "rest-configuration"; + public enum RestBindingMode { auto, off, json, xml, json_xml } @@ -172,7 +174,7 @@ public class RestConfiguration { * WWhether to use X-Forward headers to set host etc. for Swagger. * <p/> * This option is default <tt>true</tt>. - * + * * @param useXForwardHeaders whether to use X-Forward headers */ public void setUseXForwardHeaders(boolean useXForwardHeaders) { diff --git a/core/camel-base/src/main/java/org/apache/camel/impl/engine/AbstractCamelContext.java b/core/camel-base/src/main/java/org/apache/camel/impl/engine/AbstractCamelContext.java index f546993..8f3dacb 100644 --- a/core/camel-base/src/main/java/org/apache/camel/impl/engine/AbstractCamelContext.java +++ b/core/camel-base/src/main/java/org/apache/camel/impl/engine/AbstractCamelContext.java @@ -197,7 +197,7 @@ public abstract class AbstractCamelContext extends BaseService private boolean autoCreateComponents = true; private final Map<String, Language> languages = new ConcurrentHashMap<>(); private final List<LifecycleStrategy> lifecycleStrategies = new CopyOnWriteArrayList<>(); - private Map<String, RestConfiguration> restConfigurations = new ConcurrentHashMap<>(); + private volatile RestConfiguration restConfiguration; private List<InterceptStrategy> interceptStrategies = new ArrayList<>(); private List<RoutePolicyFactory> routePolicyFactories = new ArrayList<>(); private Set<LogListener> logListeners = new LinkedHashSet<>(); @@ -2006,39 +2006,19 @@ public abstract class AbstractCamelContext extends BaseService @Override public RestConfiguration getRestConfiguration() { - return restConfigurations.get(""); + if (restConfiguration == null) { + synchronized (lock) { + if (restConfiguration == null) { + setRestConfiguration(createRestConfiguration()); + } + } + } + return restConfiguration; } @Override public void setRestConfiguration(RestConfiguration restConfiguration) { - restConfigurations.put("", restConfiguration); - } - - @Override - public Collection<RestConfiguration> getRestConfigurations() { - return restConfigurations.values(); - } - - @Override - public void addRestConfiguration(RestConfiguration restConfiguration) { - restConfigurations.put(restConfiguration.getComponent(), restConfiguration); - } - - @Override - public RestConfiguration getRestConfiguration(String component, boolean defaultIfNotExist) { - if (component == null) { - component = ""; - } - RestConfiguration config = restConfigurations.get(component); - if (config == null && defaultIfNotExist) { - // grab the default configuration - config = getRestConfiguration(); - if (config == null || (config.getComponent() != null && !config.getComponent().equals(component))) { - config = new RestConfiguration(); - restConfigurations.put(component, config); - } - } - return config; + this.restConfiguration = restConfiguration; } @Override @@ -4526,6 +4506,19 @@ public abstract class AbstractCamelContext extends BaseService protected abstract ValidatorRegistry<ValidatorKey> createValidatorRegistry(); + protected RestConfiguration createRestConfiguration() { + // lookup a global which may have been on a container such spring-boot / CDI / etc. + RestConfiguration conf = CamelContextHelper.lookup(this, RestConfiguration.DEFAULT_REST_CONFIGURATION_ID, RestConfiguration.class); + if (conf == null) { + conf = CamelContextHelper.findByType(this, RestConfiguration.class); + } + if (conf == null) { + conf = new RestConfiguration(); + } + + return conf; + } + @Override public RouteController getInternalRouteController() { return new RouteController() { diff --git a/core/camel-core-engine/src/main/java/org/apache/camel/builder/RouteBuilder.java b/core/camel-core-engine/src/main/java/org/apache/camel/builder/RouteBuilder.java index e2e7268..d12a951 100644 --- a/core/camel-core-engine/src/main/java/org/apache/camel/builder/RouteBuilder.java +++ b/core/camel-core-engine/src/main/java/org/apache/camel/builder/RouteBuilder.java @@ -17,9 +17,7 @@ package org.apache.camel.builder; import java.util.ArrayList; -import java.util.HashMap; import java.util.List; -import java.util.Map; import java.util.Optional; import java.util.concurrent.atomic.AtomicBoolean; @@ -67,7 +65,7 @@ public abstract class RouteBuilder extends BuilderSupport implements RoutesBuild protected Logger log = LoggerFactory.getLogger(getClass()); private AtomicBoolean initialized = new AtomicBoolean(false); private RestsDefinition restCollection = new RestsDefinition(); - private Map<String, RestConfigurationDefinition> restConfigurations; + private RestConfigurationDefinition restConfiguration; private List<TransformerBuilder> transformerBuilders = new ArrayList<>(); private List<ValidatorBuilder> validatorBuilders = new ArrayList<>(); private RoutesDefinition routeCollection = new RoutesDefinition(); @@ -160,26 +158,10 @@ public abstract class RouteBuilder extends BuilderSupport implements RoutesBuild * @return the builder */ public RestConfigurationDefinition restConfiguration() { - return restConfiguration(""); - } - - /** - * Configures the REST service for the given component - * - * @return the builder - */ - public RestConfigurationDefinition restConfiguration(String component) { - if (restConfigurations == null) { - restConfigurations = new HashMap<>(); - } - RestConfigurationDefinition restConfiguration = restConfigurations.get(component); if (restConfiguration == null) { restConfiguration = new RestConfigurationDefinition(); - if (!component.isEmpty()) { - restConfiguration.component(component); - } - restConfigurations.put(component, restConfiguration); } + return restConfiguration; } @@ -528,39 +510,37 @@ public abstract class RouteBuilder extends BuilderSupport implements RoutesBuild getRestCollection().setCamelContext(camelContext); // setup rest configuration before adding the rests - if (getRestConfigurations() != null) { - for (Map.Entry<String, RestConfigurationDefinition> entry : getRestConfigurations().entrySet()) { - entry.getValue().asRestConfiguration( - getContext(), - camelContext.getRestConfiguration(entry.getKey(), true)); - } + if (restConfiguration != null) { + restConfiguration.asRestConfiguration(getContext(), camelContext.getRestConfiguration()); } + // cannot add rests as routes yet as we need to initialize this // specially camelContext.getExtension(Model.class).addRestDefinitions(getRestCollection().getRests(), false); // convert rests api-doc into routes so they are routes for runtime - for (RestConfiguration config : camelContext.getRestConfigurations()) { - if (config.getApiContextPath() != null) { - // avoid adding rest-api multiple times, in case multiple - // RouteBuilder classes is added - // to the CamelContext, as we only want to setup rest-api once - // so we check all existing routes if they have rest-api route - // already added - boolean hasRestApi = false; - for (RouteDefinition route : camelContext.getExtension(Model.class).getRouteDefinitions()) { - FromDefinition from = route.getInput(); - if (from.getEndpointUri() != null && from.getEndpointUri().startsWith("rest-api:")) { - hasRestApi = true; - } - } - if (!hasRestApi) { - RouteDefinition route = RestDefinition.asRouteApiDefinition(camelContext, config); - log.debug("Adding routeId: {} as rest-api route", route.getId()); - getRouteCollection().route(route); + RestConfiguration config = camelContext.getRestConfiguration(); + + if (config.getApiContextPath() != null) { + // avoid adding rest-api multiple times, in case multiple + // RouteBuilder classes is added + // to the CamelContext, as we only want to setup rest-api once + // so we check all existing routes if they have rest-api route + // already added + boolean hasRestApi = false; + for (RouteDefinition route : camelContext.getExtension(Model.class).getRouteDefinitions()) { + FromDefinition from = route.getInput(); + if (from.getEndpointUri() != null && from.getEndpointUri().startsWith("rest-api:")) { + hasRestApi = true; } } + if (!hasRestApi) { + RouteDefinition route = RestDefinition.asRouteApiDefinition(camelContext, config); + log.debug("Adding routeId: {} as rest-api route", route.getId()); + getRouteCollection().route(route); + } } + // add rest as routes and have them prepared as well via // routeCollection.route method getRestCollection().getRests().forEach(rest -> rest.asRouteDefinition(getContext()).forEach(route -> getRouteCollection().route(route))); @@ -610,8 +590,8 @@ public abstract class RouteBuilder extends BuilderSupport implements RoutesBuild return restCollection; } - public Map<String, RestConfigurationDefinition> getRestConfigurations() { - return restConfigurations; + public RestConfigurationDefinition getRestConfiguration() { + return restConfiguration; } public void setRestCollection(RestsDefinition restCollection) { diff --git a/core/camel-core-engine/src/main/java/org/apache/camel/impl/lw/ImmutableCamelContext.java b/core/camel-core-engine/src/main/java/org/apache/camel/impl/lw/ImmutableCamelContext.java index 5d8368e..f4da70e 100644 --- a/core/camel-core-engine/src/main/java/org/apache/camel/impl/lw/ImmutableCamelContext.java +++ b/core/camel-core-engine/src/main/java/org/apache/camel/impl/lw/ImmutableCamelContext.java @@ -541,23 +541,6 @@ public class ImmutableCamelContext implements ExtendedCamelContext, CatalogCamel } @Override - @Deprecated - public void addRestConfiguration(RestConfiguration restConfiguration) { - delegate.addRestConfiguration(restConfiguration); - } - - @Override - public RestConfiguration getRestConfiguration(String component, boolean defaultIfNotFound) { - return delegate.getRestConfiguration(component, defaultIfNotFound); - } - - @Override - @Deprecated - public Collection<RestConfiguration> getRestConfigurations() { - return delegate.getRestConfigurations(); - } - - @Override public RestRegistry getRestRegistry() { return delegate.getRestRegistry(); } diff --git a/core/camel-core-engine/src/main/java/org/apache/camel/impl/lw/RuntimeImmutableCamelContext.java b/core/camel-core-engine/src/main/java/org/apache/camel/impl/lw/RuntimeImmutableCamelContext.java index 0470117..47992fd 100644 --- a/core/camel-core-engine/src/main/java/org/apache/camel/impl/lw/RuntimeImmutableCamelContext.java +++ b/core/camel-core-engine/src/main/java/org/apache/camel/impl/lw/RuntimeImmutableCamelContext.java @@ -714,16 +714,6 @@ public class RuntimeImmutableCamelContext implements ExtendedCamelContext, Catal } @Override - public RestConfiguration getRestConfiguration(String component, boolean defaultIfNotFound) { - throw new UnsupportedOperationException(); - } - - @Override - public Collection<RestConfiguration> getRestConfigurations() { - throw new UnsupportedOperationException(); - } - - @Override public RestRegistry getRestRegistry() { throw new UnsupportedOperationException(); } @@ -1627,11 +1617,6 @@ public class RuntimeImmutableCamelContext implements ExtendedCamelContext, Catal } @Override - public void addRestConfiguration(RestConfiguration restConfiguration) { - throw new UnsupportedOperationException(); - } - - @Override public void setRestRegistry(RestRegistry restRegistry) { throw new UnsupportedOperationException(); } diff --git a/core/camel-core-engine/src/main/java/org/apache/camel/model/rest/RestConstants.java b/core/camel-core-engine/src/main/java/org/apache/camel/model/rest/RestConstants.java deleted file mode 100644 index 7ec4d99..0000000 --- a/core/camel-core-engine/src/main/java/org/apache/camel/model/rest/RestConstants.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * 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.model.rest; - -public final class RestConstants { - public static final String DEFAULT_REST_CONFIGURATION_ID = "rest-configuration"; - - private RestConstants() { - } -} diff --git a/core/camel-core-engine/src/main/java/org/apache/camel/model/rest/RestDefinition.java b/core/camel-core-engine/src/main/java/org/apache/camel/model/rest/RestDefinition.java index f270e22..1ff251f 100644 --- a/core/camel-core-engine/src/main/java/org/apache/camel/model/rest/RestDefinition.java +++ b/core/camel-core-engine/src/main/java/org/apache/camel/model/rest/RestDefinition.java @@ -43,7 +43,6 @@ import org.apache.camel.model.ToDefinition; import org.apache.camel.model.ToDynamicDefinition; import org.apache.camel.spi.Metadata; import org.apache.camel.spi.RestConfiguration; -import org.apache.camel.support.CamelContextHelper; import org.apache.camel.util.FileUtil; import org.apache.camel.util.ObjectHelper; import org.apache.camel.util.StringHelper; @@ -677,23 +676,11 @@ public class RestDefinition extends OptionalIdentifiedDefinition<RestDefinition> validateUniquePaths(); List<RouteDefinition> answer = new ArrayList<>(); - if (camelContext.getRestConfigurations().isEmpty()) { - // make sure to initialize a rest configuration when its empty - // lookup a global which may have been setup via camel-spring-boot - // etc - RestConfiguration conf = CamelContextHelper.lookup(camelContext, RestConstants.DEFAULT_REST_CONFIGURATION_ID, RestConfiguration.class); - if (conf == null) { - conf = CamelContextHelper.findByType(camelContext, RestConfiguration.class); - } - if (conf != null) { - camelContext.setRestConfiguration(conf); - } else { - camelContext.setRestConfiguration(new RestConfiguration()); - } - } - for (RestConfiguration config : camelContext.getRestConfigurations()) { - addRouteDefinition(camelContext, answer, config.getComponent(), config.getProducerComponent()); - } + + RestConfiguration config = camelContext.getRestConfiguration(); + + addRouteDefinition(camelContext, answer, config.getComponent(), config.getProducerComponent()); + return answer; } diff --git a/core/camel-core-engine/src/main/java/org/apache/camel/reifier/rest/RestBindingReifier.java b/core/camel-core-engine/src/main/java/org/apache/camel/reifier/rest/RestBindingReifier.java index af2b124..aad39ee 100644 --- a/core/camel-core-engine/src/main/java/org/apache/camel/reifier/rest/RestBindingReifier.java +++ b/core/camel-core-engine/src/main/java/org/apache/camel/reifier/rest/RestBindingReifier.java @@ -29,6 +29,7 @@ import org.apache.camel.processor.RestBindingAdvice; import org.apache.camel.reifier.AbstractReifier; import org.apache.camel.spi.DataFormat; import org.apache.camel.spi.RestConfiguration; +import org.apache.camel.support.CamelContextHelper; import org.apache.camel.support.PropertyBindingSupport; public class RestBindingReifier extends AbstractReifier { @@ -41,7 +42,7 @@ public class RestBindingReifier extends AbstractReifier { } public RestBindingAdvice createRestBindingAdvice() throws Exception { - RestConfiguration config = camelContext.getRestConfiguration(definition.getComponent(), true); + RestConfiguration config = CamelContextHelper.getRestConfiguration(camelContext, definition.getComponent()); // these options can be overridden per rest verb String mode = config.getBindingMode().name(); diff --git a/core/camel-core-xml/src/main/java/org/apache/camel/core/xml/AbstractCamelContextFactoryBean.java b/core/camel-core-xml/src/main/java/org/apache/camel/core/xml/AbstractCamelContextFactoryBean.java index b8e8ffa..135d674 100644 --- a/core/camel-core-xml/src/main/java/org/apache/camel/core/xml/AbstractCamelContextFactoryBean.java +++ b/core/camel-core-xml/src/main/java/org/apache/camel/core/xml/AbstractCamelContextFactoryBean.java @@ -438,24 +438,24 @@ public abstract class AbstractCamelContextFactoryBean<T extends ModelCamelContex getContext().addRestDefinitions(getRests(), false); // convert rests api-doc into routes so they are routes for runtime - for (RestConfiguration config : getContext().getRestConfigurations()) { - if (config.getApiContextPath() != null) { - // avoid adding rest-api multiple times, in case multiple RouteBuilder classes is added - // to the CamelContext, as we only want to setup rest-api once - // so we check all existing routes if they have rest-api route already added - boolean hasRestApi = false; - for (RouteDefinition route : getContext().getRouteDefinitions()) { - FromDefinition from = route.getInput(); - if (from.getUri() != null && from.getUri().startsWith("rest-api:")) { - hasRestApi = true; - } - } - if (!hasRestApi) { - RouteDefinition route = RestDefinition.asRouteApiDefinition(getContext(), config); - LOG.debug("Adding routeId: {} as rest-api route", route.getId()); - getRoutes().add(route); + RestConfiguration config = getContext().getRestConfiguration(); + + if (config.getApiContextPath() != null) { + // avoid adding rest-api multiple times, in case multiple RouteBuilder classes is added + // to the CamelContext, as we only want to setup rest-api once + // so we check all existing routes if they have rest-api route already added + boolean hasRestApi = false; + for (RouteDefinition route : getContext().getRouteDefinitions()) { + FromDefinition from = route.getInput(); + if (from.getUri() != null && from.getUri().startsWith("rest-api:")) { + hasRestApi = true; } } + if (!hasRestApi) { + RouteDefinition route = RestDefinition.asRouteApiDefinition(getContext(), config); + LOG.debug("Adding routeId: {} as rest-api route", route.getId()); + getRoutes().add(route); + } } // add each rest as route diff --git a/core/camel-support/src/main/java/org/apache/camel/support/CamelContextHelper.java b/core/camel-support/src/main/java/org/apache/camel/support/CamelContextHelper.java index 39c9d6b..49d3f5f 100644 --- a/core/camel-support/src/main/java/org/apache/camel/support/CamelContextHelper.java +++ b/core/camel-support/src/main/java/org/apache/camel/support/CamelContextHelper.java @@ -17,6 +17,7 @@ package org.apache.camel.support; import java.util.Map; +import java.util.Objects; import java.util.Properties; import java.util.Set; @@ -29,6 +30,7 @@ import org.apache.camel.NoSuchBeanException; import org.apache.camel.NoSuchEndpointException; import org.apache.camel.RuntimeCamelException; import org.apache.camel.spi.NormalizedEndpointUri; +import org.apache.camel.spi.RestConfiguration; import org.apache.camel.spi.RouteStartupOrder; import org.apache.camel.util.ObjectHelper; @@ -587,4 +589,51 @@ public final class CamelContextHelper { return parent != null ? parent.getId() : null; } + /** + * Gets the {@link RestConfiguration} from the {@link CamelContext} and check if the component which consumes the + * configuration is compatible with the one for which the rest configuration is set-up. + * + * @param camelContext the camel context + * @param component the component that will consume the {@link RestConfiguration} + * @return the {@link RestConfiguration} + * @throws IllegalArgumentException is the component is not compatible with the {@link RestConfiguration} set-up + */ + public static RestConfiguration getRestConfiguration(CamelContext camelContext, String component) { + RestConfiguration configuration = camelContext.getRestConfiguration(); + + validateRestConfigurationComponent(component, configuration.getComponent()); + + return configuration; + } + + /** + * Gets the {@link RestConfiguration} from the {@link CamelContext} and check if the component which consumes the + * configuration is compatible with the one for which the rest configuration is set-up. + * + * @param camelContext the camel context + * @param component the component that will consume the {@link RestConfiguration} + * @param producerComponent the producer component that will consume the {@link RestConfiguration} + * @return the {@link RestConfiguration} + * @throws IllegalArgumentException is the component is not compatible with the {@link RestConfiguration} set-up + */ + public static RestConfiguration getRestConfiguration(CamelContext camelContext, String component, String producerComponent) { + RestConfiguration configuration = camelContext.getRestConfiguration(); + + validateRestConfigurationComponent(component, configuration.getComponent()); + validateRestConfigurationComponent(producerComponent, configuration.getProducerComponent()); + + return configuration; + } + + private static void validateRestConfigurationComponent(String component, String configurationComponent) { + if (ObjectHelper.isEmpty(component) || ObjectHelper.isEmpty(configurationComponent)) { + return; + } + + if (!Objects.equals(component, configurationComponent)) { + throw new IllegalArgumentException( + "No RestConfiguration for component: " + component + " found, RestConfiguration targets: " + configurationComponent + ); + } + } }