davsclaus commented on code in PR #26203:
URL: https://github.com/apache/camel/pull/26203#discussion_r4083561046


##########
components/camel-rest-openapi/src/main/docs/rest-openapi-component.adoc:
##########
@@ -202,6 +202,100 @@ If any of the validation checks fail, then a 
`RestOpenApiValidationException` is
 has a `getValidationErrors` method that returns the error messages from the 
validator.
 
 
+== Unmatched requests
+
+By default, an incoming request that does not match any operation in the 
OpenAPI specification is answered by the
+HTTP layer of the runtime, with HTTP 404, and a request that matches a path 
but not the HTTP method is answered
+with HTTP 405 and an `Allow` header listing the allowed methods.
+
+To let Camel answer these requests instead, set the `unmatchedRequestHandling` 
option to `camel` on the
+rest-openapi consumer endpoint or via the rest DSL `openApi` section. The 
rest-openapi component then registers a
+catch-all for the API base path on the HTTP layer so requests that match no 
operation are routed to Camel, where
+they are answered by the unmatched request handler.
+
+[tabs]
+====
+Java::
++
+[source,java]
+----
+from("rest-openapi:petstore-v3.json?missingOperation=ignore&unmatchedRequestHandling=camel")
+    .to("direct:businessLogic");
+
+// ... or using the rest DSL
+
+rest().openApi()
+    .specification("petstore-v3.json")
+    .missingOperation("ignore")
+    .unmatchedRequestHandling("camel");
+----
+
+YAML::
++
+[source,yaml]
+----
+- route:
+    from:
+      uri: rest-openapi:petstore-v3.json
+      parameters:
+        missingOperation: ignore
+        unmatchedRequestHandling: camel
+      steps:
+        - to:
+            uri: direct:businessLogic
+
+# ... or using the rest DSL
+
+- rest:
+    openApi:
+      specification: petstore-v3.json
+      missingOperation: ignore
+      unmatchedRequestHandling: camel
+----
+====
+
+The option is supported by the built-in `platform-http` consumer component: 
Camel Main when using
+xref:platform-http-vertx.adoc[camel-platform-http-vertx], and Spring Boot when 
using the platform-http starter
+(`camel-platform-http-starter`). Other consumer components ignore the option.

Review Comment:
   Not quite: `RestOpenApiEndpoint` forwards `unmatchedRequestHandling` into 
the delegate consumer's parameters, so a third-party 
`RestOpenApiConsumerFactory` that validates its parameters could reject it 
rather than ignore it. Low risk, since platform-http is the only in-tree 
factory, but the wording should reflect that (or the option shouldn't be 
forwarded).



##########
components/camel-rest-openapi/src/main/docs/rest-openapi-component.adoc:
##########
@@ -202,6 +202,100 @@ If any of the validation checks fail, then a 
`RestOpenApiValidationException` is
 has a `getValidationErrors` method that returns the error messages from the 
validator.
 
 
+== Unmatched requests
+
+By default, an incoming request that does not match any operation in the 
OpenAPI specification is answered by the
+HTTP layer of the runtime, with HTTP 404, and a request that matches a path 
but not the HTTP method is answered
+with HTTP 405 and an `Allow` header listing the allowed methods.
+
+To let Camel answer these requests instead, set the `unmatchedRequestHandling` 
option to `camel` on the
+rest-openapi consumer endpoint or via the rest DSL `openApi` section. The 
rest-openapi component then registers a
+catch-all for the API base path on the HTTP layer so requests that match no 
operation are routed to Camel, where
+they are answered by the unmatched request handler.
+
+[tabs]
+====
+Java::
++
+[source,java]
+----
+from("rest-openapi:petstore-v3.json?missingOperation=ignore&unmatchedRequestHandling=camel")
+    .to("direct:businessLogic");
+
+// ... or using the rest DSL
+
+rest().openApi()
+    .specification("petstore-v3.json")
+    .missingOperation("ignore")
+    .unmatchedRequestHandling("camel");
+----
+
+YAML::
++
+[source,yaml]
+----
+- route:
+    from:
+      uri: rest-openapi:petstore-v3.json
+      parameters:
+        missingOperation: ignore
+        unmatchedRequestHandling: camel
+      steps:
+        - to:
+            uri: direct:businessLogic
+
+# ... or using the rest DSL
+
+- rest:
+    openApi:
+      specification: petstore-v3.json
+      missingOperation: ignore
+      unmatchedRequestHandling: camel
+----
+====
+
+The option is supported by the built-in `platform-http` consumer component: 
Camel Main when using
+xref:platform-http-vertx.adoc[camel-platform-http-vertx], and Spring Boot when 
using the platform-http starter

Review Comment:
   `platform-http-vertx.adoc` doesn't exist, so this xref fails doc validation. 
Use `xref:platform-http-component.adoc[camel-platform-http-vertx]` or plain 
text, and regenerate the catalog copy of this doc.



##########
components/camel-rest-openapi/src/main/java/org/apache/camel/component/rest/openapi/RestOpenApiProcessor.java:
##########
@@ -265,5 +315,19 @@ protected void doStop() throws Exception {
             }
         }
         paths.clear();
+
+        if (unmatchedRequestCatchAllRegistered) {
+            try {
+                PlatformHttpComponent phc = 
camelContext.getComponent("platform-http", PlatformHttpComponent.class);
+                if (phc != null) {

Review Comment:
   This stray `if (phc != null) {` (left over from applying the null-guard 
suggestion) is never closed, so the `finally` below has no `try` and the module 
doesn't compile. Delete this line; the next line already checks `phc != null`.



##########
components/camel-rest-openapi/src/test/java/org/apache/camel/component/rest/openapi/RestOpenApiUnmatchedRequestHandlerTest.java:
##########
@@ -0,0 +1,288 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.rest.openapi;
+
+import java.io.ByteArrayInputStream;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Optional;
+
+import io.swagger.v3.oas.models.OpenAPI;
+import org.apache.camel.CamelContext;
+import org.apache.camel.Exchange;
+import org.apache.camel.RoutesBuilder;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.platform.http.PlatformHttpComponent;
+import org.apache.camel.component.platform.http.PlatformHttpEndpoint;
+import org.apache.camel.component.platform.http.spi.PlatformHttpConsumer;
+import org.apache.camel.component.platform.http.spi.PlatformHttpConsumerAware;
+import org.apache.camel.impl.DefaultCamelContext;
+import org.apache.camel.impl.engine.DefaultFactoryFinder;
+import org.apache.camel.spi.ClassResolver;
+import org.apache.camel.spi.FactoryFinder;
+import org.apache.camel.support.DefaultExchange;
+import org.apache.camel.support.service.ServiceHelper;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.ArgumentMatchers.isNull;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+class RestOpenApiUnmatchedRequestHandlerTest extends ManagedCamelTestSupport {
+
+    private CamelContext camelContext;
+    private RestOpenApiProcessor openApiProcessor;
+
+    @BeforeEach
+    public void createMocks() throws Exception {
+        initializeContextForComponent("rest-openapi");
+    }
+
+    @Override
+    protected RoutesBuilder createRouteBuilder() {
+        return new RouteBuilder() {
+            @Override
+            public void configure() throws Exception {
+                from("direct:listUsers").to("mock:listUsers");
+                from("direct:listOrders").to("mock:listOrders");
+                from("direct:createOrder").to("mock:createOrder");
+            }
+        };
+    }
+
+    @Override
+    protected CamelContext createCamelContext(String componentName) {
+        camelContext = new DefaultCamelContext();
+        PlatformHttpComponent httpCmpn = mock(PlatformHttpComponent.class);
+        camelContext.addComponent("platform-http", httpCmpn);
+        return camelContext;
+    }
+
+    private RestOpenApiProcessor createProcessor() throws Exception {
+        return createProcessor(null);
+    }
+
+    private RestOpenApiProcessor createProcessor(String 
unmatchedRequestHandling) throws Exception {
+        OpenAPI openApi = 
RestOpenApiEndpoint.loadSpecificationFrom(camelContext, 
"unmatched-request-handler.yaml");
+        String basePath = RestOpenApiHelper.determineBasePath(camelContext, 
null, null, openApi);
+
+        DefaultRestOpenapiProcessorStrategy strategy = new 
DefaultRestOpenapiProcessorStrategy();
+        strategy.setCamelContext(camelContext);
+
+        RestOpenApiComponent component = new RestOpenApiComponent();
+        RestOpenApiEndpoint endpoint = new RestOpenApiEndpoint(
+                "rest-openapi:unmatched-request-handler.yaml", 
"unmatched-request-handler.yaml", component, null);
+        if (unmatchedRequestHandling != null) {
+            endpoint.setUnmatchedRequestHandling(unmatchedRequestHandling);
+        }
+
+        RestOpenApiProcessor processor = new RestOpenApiProcessor(endpoint, 
openApi, basePath, null, strategy);
+        processor.setCamelContext(camelContext);
+        
processor.setPlatformHttpConsumer(createMockPlatformHttpConsumerAware());
+        processor.afterPropertiesConfigured(camelContext);
+        openApiProcessor = processor;
+        return processor;
+    }
+
+    private PlatformHttpConsumerAware createMockPlatformHttpConsumerAware() {
+        PlatformHttpConsumerAware platformHttpConsumerAware = 
mock(PlatformHttpConsumerAware.class);
+        PlatformHttpConsumer platformHttpConsumer = 
mock(PlatformHttpConsumer.class);
+        PlatformHttpEndpoint platformHttpEndpoint = 
mock(PlatformHttpEndpoint.class);
+        
when(platformHttpConsumerAware.getPlatformHttpConsumer()).thenReturn(platformHttpConsumer);
+        
when(platformHttpConsumer.getEndpoint()).thenReturn(platformHttpEndpoint);
+        
when(platformHttpEndpoint.getServiceUrl()).thenReturn("http://localhost:8080";);
+        return platformHttpConsumerAware;
+    }
+
+    private Exchange send(RestOpenApiProcessor processor, String path, String 
verb) throws Exception {
+        Exchange exchange = new DefaultExchange(camelContext);
+        exchange.getMessage().setHeader(Exchange.HTTP_PATH, path);
+        exchange.getMessage().setHeader(Exchange.HTTP_METHOD, verb);
+        exchange.getMessage().setBody("request-payload");
+        processor.process(exchange, done -> {
+        });
+        return exchange;
+    }
+
+    @Test
+    void testDefaultHandlerReturns404WithEmptyBody() throws Exception {
+        RestOpenApiProcessor processor = createProcessor();
+        Exchange exchange = send(processor, "/unknown", "GET");
+
+        assertEquals(404, 
exchange.getMessage().getHeader(Exchange.HTTP_RESPONSE_CODE, Integer.class));
+        assertNull(exchange.getMessage().getBody());
+        assertTrue(exchange.isRouteStop());
+    }
+
+    @Test
+    void testDefaultHandlerReturns405WithAllowHeader() throws Exception {
+        RestOpenApiProcessor processor = createProcessor();
+        Exchange exchange = send(processor, "/orders", "PUT");
+
+        assertEquals(405, 
exchange.getMessage().getHeader(Exchange.HTTP_RESPONSE_CODE, Integer.class));
+        assertEquals("GET, POST", exchange.getMessage().getHeader("Allow", 
String.class));
+        assertNull(exchange.getMessage().getBody());
+        assertTrue(exchange.isRouteStop());
+    }
+
+    @Test
+    void testCustomHandlerFromRegistryIsCalled() throws Exception {
+        RecordingHandler handler = new RecordingHandler();
+        camelContext.getRegistry().bind("customHandler", handler);
+
+        RestOpenApiProcessor processor = createProcessor();
+        Exchange exchange = send(processor, "/unknown", "GET");
+
+        assertEquals(404, 
exchange.getMessage().getHeader(Exchange.HTTP_RESPONSE_CODE, Integer.class));
+        assertEquals("{\"error\":\"not found\"}", 
exchange.getMessage().getBody(String.class));
+        assertEquals(List.of(404), handler.statusCodes);
+    }
+
+    @Test
+    void testCustomHandlerReceivesCorrectStatusCode() throws Exception {
+        RecordingHandler handler = new RecordingHandler();
+        camelContext.getRegistry().bind("customHandler", handler);
+
+        RestOpenApiProcessor processor = createProcessor();
+
+        Exchange notFound = send(processor, "/unknown", "GET");
+        Exchange methodNotAllowed = send(processor, "/orders", "PUT");
+
+        assertEquals(List.of(404, 405), handler.statusCodes);
+        assertEquals(404, 
notFound.getMessage().getHeader(Exchange.HTTP_RESPONSE_CODE, Integer.class));
+        assertEquals(405, 
methodNotAllowed.getMessage().getHeader(Exchange.HTTP_RESPONSE_CODE, 
Integer.class));
+    }
+
+    @Test
+    void testCustomHandlerReceivesCorrectAllowedMethods() throws Exception {
+        RecordingHandler handler = new RecordingHandler();
+        camelContext.getRegistry().bind("customHandler", handler);
+
+        RestOpenApiProcessor processor = createProcessor();
+
+        send(processor, "/unknown", "GET");
+        send(processor, "/orders", "PUT");
+
+        assertEquals(List.of(List.of(), List.of("GET", "POST")), 
handler.allowedMethods);
+    }
+
+    @Test
+    void testCustomHandlerFromFactoryFinderIsCalled() throws Exception {
+        // Since we want to be able to test both a bean registered directly 
into
+        // the registry and the factory finder we can not just put the factory
+        // file into src/test/resources/META-INF/services that breaks other 
tests
+        ClassResolver classResolver = mock(ClassResolver.class);
+        String properties = "class=" + FactoryFoundHandler.class.getName();
+        when(classResolver.loadResourceAsStream(
+                FactoryFinder.DEFAULT_PATH + 
RestOpenApiUnmatchedRequestHandler.FACTORY))
+                .thenAnswer(invocation -> new 
ByteArrayInputStream(properties.getBytes(StandardCharsets.UTF_8)));
+        when(classResolver.resolveClass(FactoryFoundHandler.class.getName()))
+                .thenAnswer(invocation -> FactoryFoundHandler.class);
+
+        FactoryFinder realFinder = 
camelContext.getCamelContextExtension().getBootstrapFactoryFinder();
+        FactoryFinder factoryFinder = new DefaultFactoryFinder(classResolver, 
FactoryFinder.DEFAULT_PATH) {
+            @Override
+            public Optional<Class<?>> findOptionalClass(String key) {
+                return RestOpenApiUnmatchedRequestHandler.FACTORY.equals(key)
+                        ? super.findOptionalClass(key)
+                        : realFinder.findOptionalClass(key);
+            }
+        };
+        
camelContext.getCamelContextExtension().setBootstrapFactoryFinder(factoryFinder);
+
+        RestOpenApiProcessor processor = createProcessor();
+        Exchange exchange = send(processor, "/unknown", "GET");
+
+        assertEquals(404, 
exchange.getMessage().getHeader(Exchange.HTTP_RESPONSE_CODE, Integer.class));
+        assertEquals("{\"error\":\"from factory finder\"}", 
exchange.getMessage().getBody(String.class));
+    }
+
+    @Test
+    void testCatchAllRegisteredOnPlatformHttpWhenCamelHandling() throws 
Exception {
+        RestOpenApiProcessor processor = createProcessor("camel");
+        PlatformHttpComponent phc = camelContext.getComponent("platform-http", 
PlatformHttpComponent.class);
+
+        // a catch-all for the api base path (without verbs) must be 
registered so unmatched requests are routed to Camel
+        verify(phc).addHttpEndpoint(eq(""), isNull(), isNull(), isNull(), 
isNull());

Review Comment:
   `createMockPlatformHttpConsumerAware()` (line 116) makes 
`getPlatformHttpConsumer()` return a non-null mock, and the processor passes it 
as the last argument (`RestOpenApiProcessor` line 254). So this `isNull()` 
should not match; the same goes for `removeHttpEndpoint(eq(""), isNull())` at 
line 236. Match the stubbed consumer instead.



##########
components/camel-rest-openapi/src/main/docs/rest-openapi-component.adoc:
##########
@@ -202,6 +202,100 @@ If any of the validation checks fail, then a 
`RestOpenApiValidationException` is
 has a `getValidationErrors` method that returns the error messages from the 
validator.
 
 
+== Unmatched requests
+
+By default, an incoming request that does not match any operation in the 
OpenAPI specification is answered by the
+HTTP layer of the runtime, with HTTP 404, and a request that matches a path 
but not the HTTP method is answered
+with HTTP 405 and an `Allow` header listing the allowed methods.
+
+To let Camel answer these requests instead, set the `unmatchedRequestHandling` 
option to `camel` on the
+rest-openapi consumer endpoint or via the rest DSL `openApi` section. The 
rest-openapi component then registers a
+catch-all for the API base path on the HTTP layer so requests that match no 
operation are routed to Camel, where
+they are answered by the unmatched request handler.
+
+[tabs]
+====
+Java::
++
+[source,java]
+----
+from("rest-openapi:petstore-v3.json?missingOperation=ignore&unmatchedRequestHandling=camel")
+    .to("direct:businessLogic");
+
+// ... or using the rest DSL
+
+rest().openApi()
+    .specification("petstore-v3.json")
+    .missingOperation("ignore")
+    .unmatchedRequestHandling("camel");
+----
+
+YAML::
++
+[source,yaml]
+----
+- route:
+    from:
+      uri: rest-openapi:petstore-v3.json
+      parameters:
+        missingOperation: ignore
+        unmatchedRequestHandling: camel
+      steps:
+        - to:
+            uri: direct:businessLogic
+
+# ... or using the rest DSL
+
+- rest:
+    openApi:
+      specification: petstore-v3.json
+      missingOperation: ignore
+      unmatchedRequestHandling: camel
+----
+====
+
+The option is supported by the built-in `platform-http` consumer component: 
Camel Main when using
+xref:platform-http-vertx.adoc[camel-platform-http-vertx], and Spring Boot when 
using the platform-http starter
+(`camel-platform-http-starter`). Other consumer components ignore the option.
+
+On Camel Main and Quarkus, the catch-all route is evaluated last on the HTTP 
server, so it never shadows the
+operations of other APIs served by the same server, even when their base paths 
are nested under this API.
+
+When the request has been routed to Camel, the response body (and headers) can 
be customized by registering a
+bean in the xref:manual::registry.adoc[Registry] that implements the 
`RestOpenApiUnmatchedRequestHandler` interface.
+The handler is called with the exchange, the status code (`404` or `405`) and 
the list of allowed HTTP
+methods (empty for `404`), and can then set the response body, status code and 
headers as needed.
+The handler can also be registered using a factory finder on the classpath. 
This is done by adding a
+resource file 
`META-INF/services/org/apache/camel/rest-openapi-unmatched-request-handler-factory`
+with the content `class=com.example.MyHandler`.
+
+A single handler bean in the registry takes precedence over a handler found 
via the factory finder, which in
+turn takes precedence over the default handler. Regardless of how the handler 
is registered *only one* handler
+is used: when two or more beans of this type are found in the registry, none 
of them is used, instead the

Review Comment:
   Nit: "instead ... instead" is doubled in this sentence.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to