This is an automated email from the ASF dual-hosted git repository.

davsclaus pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git


The following commit(s) were added to refs/heads/main by this push:
     new 2caf6bb4cc87 CAMEL-27204: camel-rest-openapi - spaces in media type 
parameters no longer turn into '+' (#30735)
2caf6bb4cc87 is described below

commit 2caf6bb4cc87ca6e9ccc2b5e3fe74d7db5c0c59b
Author: Claus Ibsen <[email protected]>
AuthorDate: Tue Nov 24 18:44:39 2026 +0100

    CAMEL-27204: camel-rest-openapi - spaces in media type parameters no longer 
turn into '+' (#30735)
    
    MimeTypeHelper.sanitizeMimeType turned every space into a '+', to repair a
    '+' that URI decoding turned into a space (application/xslt xml). It also 
hit
    the space after the ';' of a parameter, so application/json; q=0.5 was sent
    as application/json;+q=0.5 in the Accept and Content-Type headers by the 
rest
    and rest-openapi producers (and registered that way by platform-http).
    
    The '+' repair now applies only to the type/subtype token and to unquoted
    parameter values. The spaces around ';' and '=' are removed, a quoted value
    is kept as is, and a ',' or ';' inside quotes no longer splits.
    
    Co-Authored-By: Claude Opus 5.5 <[email protected]>
    Signed-off-by: Claus Ibsen <[email protected]>
---
 .../RestOpenApiMediaTypeParametersTest.java        | 127 +++++++++++++++++++++
 .../src/test/resources/media-type-parameters.yaml  |  38 ++++++
 .../java/org/apache/camel/util/MimeTypeHelper.java |  72 +++++++++++-
 .../org/apache/camel/util/MimeTypeHelperTest.java  |  32 ++++++
 4 files changed, 266 insertions(+), 3 deletions(-)

diff --git 
a/components/camel-rest-openapi/src/test/java/org/apache/camel/component/rest/openapi/RestOpenApiMediaTypeParametersTest.java
 
b/components/camel-rest-openapi/src/test/java/org/apache/camel/component/rest/openapi/RestOpenApiMediaTypeParametersTest.java
new file mode 100644
index 000000000000..2bc8e8f1d6d7
--- /dev/null
+++ 
b/components/camel-rest-openapi/src/test/java/org/apache/camel/component/rest/openapi/RestOpenApiMediaTypeParametersTest.java
@@ -0,0 +1,127 @@
+/*
+ * 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.util.Arrays;
+import java.util.Objects;
+
+import com.github.tomakehurst.wiremock.WireMockServer;
+import org.apache.camel.CamelContext;
+import org.apache.camel.RoutesBuilder;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.rest.RestEndpoint;
+import org.apache.camel.impl.DefaultCamelContext;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.MethodSource;
+
+import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
+import static com.github.tomakehurst.wiremock.client.WireMock.equalTo;
+import static com.github.tomakehurst.wiremock.client.WireMock.matching;
+import static com.github.tomakehurst.wiremock.client.WireMock.post;
+import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor;
+import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
+import static 
com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;
+
+/**
+ * A space after the ; of a media type parameter must not reach the server as 
a + (CAMEL-27204).
+ */
+public class RestOpenApiMediaTypeParametersTest extends 
ManagedCamelTestSupport {
+
+    // the HTTP clients may write the charset in upper case, or add their own 
space after the ;
+    private static final String CONTENT_TYPE = "application/json; 
?charset=(?i:utf-8)";
+
+    public static WireMockServer server = new 
WireMockServer(wireMockConfig().dynamicPort());
+
+    @BeforeAll
+    public static void startWireMockServer() {
+        server.start();
+        server.stubFor(post(urlEqualTo("/api/orders"))
+                
.willReturn(aResponse().withStatus(200).withHeader("Content-Type", 
"application/json").withBody("{}")));
+    }
+
+    @AfterAll
+    public static void stopWireMockServer() {
+        server.stop();
+    }
+
+    @BeforeEach
+    public void resetWireMock() {
+        server.resetRequests();
+    }
+
+    @ParameterizedTest
+    @MethodSource("knownProducers")
+    public void shouldSendMediaTypesFromSpecificationWithoutPlus(String 
componentName) throws Exception {
+        initializeContextForComponent(componentName);
+
+        template.sendBody("direct:fromSpec", "{}");
+
+        server.verify(postRequestedFor(urlEqualTo("/api/orders"))
+                .withHeader("Accept", 
equalTo("application/json;charset=utf-8"))
+                .withHeader("Content-Type", matching(CONTENT_TYPE)));
+    }
+
+    @ParameterizedTest
+    @MethodSource("knownProducers")
+    public void shouldSendMediaTypesFromEndpointWithoutPlus(String 
componentName) throws Exception {
+        initializeContextForComponent(componentName);
+
+        template.sendBody("direct:fromEndpoint", "{}");
+
+        server.verify(postRequestedFor(urlEqualTo("/api/orders"))
+                .withHeader("Accept", 
equalTo("application/vnd.api+json,application/json;q=0.5"))
+                .withHeader("Content-Type", matching(CONTENT_TYPE)));
+    }
+
+    @Override
+    protected CamelContext createCamelContext(String componentName) {
+        final CamelContext camelContext = new DefaultCamelContext();
+
+        final RestOpenApiComponent component = new RestOpenApiComponent();
+        component.setComponentName(componentName);
+        component.setHost("http://localhost:"; + server.port());
+        component.setBasePath("/api");
+        component.setSpecificationUri(Objects
+                
.requireNonNull(RestOpenApiMediaTypeParametersTest.class.getResource("/media-type-parameters.yaml"))
+                .toString());
+
+        camelContext.addComponent("orders", component);
+
+        return camelContext;
+    }
+
+    @Override
+    protected RoutesBuilder createRouteBuilder() {
+        return new RouteBuilder() {
+            @Override
+            public void configure() {
+                from("direct:fromSpec").to("orders:addOrder");
+
+                from("direct:fromEndpoint").to(
+                        
"orders:addOrder?consumes=RAW(application/vnd.api+json, application/json; 
q=0.5)"
+                                               + 
"&produces=RAW(application/json; charset=utf-8)");
+            }
+        };
+    }
+
+    public static Iterable<String> knownProducers() {
+        return Arrays.asList(RestEndpoint.DEFAULT_REST_PRODUCER_COMPONENTS);
+    }
+}
diff --git 
a/components/camel-rest-openapi/src/test/resources/media-type-parameters.yaml 
b/components/camel-rest-openapi/src/test/resources/media-type-parameters.yaml
new file mode 100644
index 000000000000..6fe742deeabc
--- /dev/null
+++ 
b/components/camel-rest-openapi/src/test/resources/media-type-parameters.yaml
@@ -0,0 +1,38 @@
+#
+# 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.
+#
+
+openapi: 3.0.0
+info:
+  title: Media type parameters test API
+  version: 1.0.0
+paths:
+  /orders:
+    post:
+      summary: Adds an order
+      operationId: addOrder
+      requestBody:
+        content:
+          application/json; charset=utf-8:
+            schema:
+              type: object
+      responses:
+        '200':
+          description: The order
+          content:
+            application/json; charset=utf-8:
+              schema:
+                type: object
diff --git 
a/core/camel-util/src/main/java/org/apache/camel/util/MimeTypeHelper.java 
b/core/camel-util/src/main/java/org/apache/camel/util/MimeTypeHelper.java
index e952dcfdde24..5e06972e59fc 100644
--- a/core/camel-util/src/main/java/org/apache/camel/util/MimeTypeHelper.java
+++ b/core/camel-util/src/main/java/org/apache/camel/util/MimeTypeHelper.java
@@ -16,12 +16,19 @@
  */
 package org.apache.camel.util;
 
+import java.util.ArrayList;
+import java.util.List;
 import java.util.StringJoiner;
 
 public class MimeTypeHelper {
 
     /**
-     * Sanitizes the mime types after URL encoding to convert space into plus 
sign.
+     * Sanitizes the mime types after URL decoding.
+     * <p>
+     * URL decoding turns a plus sign into a space, so a space inside the 
<tt>type/subtype</tt> token (such as
+     * <tt>application/xslt xml</tt>) is turned back into a plus sign. The 
parameters of a media type (such as
+     * <tt>application/json; q=0.5</tt>) keep their meaning: the spaces around 
<tt>;</tt> and <tt>=</tt> are removed,
+     * and a quoted parameter value is kept as is.
      *
      * @param  types mime types such as from HTTP Accept header
      * @return       the sanitized mime types
@@ -29,14 +36,73 @@ public class MimeTypeHelper {
     public static String sanitizeMimeType(String types) {
         if (types != null) {
             StringJoiner sj = new StringJoiner(",");
-            for (String part : types.split(",")) {
-                sj.add(part.trim().replace(' ', '+'));
+            for (String part : splitOutsideQuotes(types, ',')) {
+                String type = sanitizeSingleMimeType(part);
+                if (!type.isEmpty()) {
+                    sj.add(type);
+                }
             }
             types = sj.toString();
         }
         return types;
     }
 
+    private static String sanitizeSingleMimeType(String type) {
+        List<String> parts = splitOutsideQuotes(type, ';');
+        // a space is not valid in the type/subtype token, so it is a plus 
sign that URL decoding turned into a space
+        StringBuilder sb = new StringBuilder(parts.get(0).trim().replace(' ', 
'+'));
+        for (int i = 1; i < parts.size(); i++) {
+            String param = parts.get(i).trim();
+            if (param.isEmpty()) {
+                continue;
+            }
+            sb.append(';');
+            int pos = param.indexOf('=');
+            if (pos == -1) {
+                sb.append(param.replace(' ', '+'));
+            } else {
+                String name = param.substring(0, pos).trim();
+                String value = param.substring(pos + 1).trim();
+                sb.append(name).append('=');
+                if (value.startsWith("\"")) {
+                    // a quoted value may contain spaces
+                    sb.append(value);
+                } else {
+                    // a space is not valid in a token value either
+                    sb.append(value.replace(' ', '+'));
+                }
+            }
+        }
+        return sb.toString();
+    }
+
+    /**
+     * Splits the text by the separator, ignoring separators inside a quoted 
string (with backslash escapes).
+     */
+    private static List<String> splitOutsideQuotes(String text, char 
separator) {
+        List<String> answer = new ArrayList<>();
+        StringBuilder sb = new StringBuilder();
+        boolean quoted = false;
+        boolean escaped = false;
+        for (int i = 0; i < text.length(); i++) {
+            char ch = text.charAt(i);
+            if (escaped) {
+                escaped = false;
+            } else if (quoted && ch == '\\') {
+                escaped = true;
+            } else if (ch == '"') {
+                quoted = !quoted;
+            } else if (ch == separator && !quoted) {
+                answer.add(sb.toString());
+                sb.setLength(0);
+                continue;
+            }
+            sb.append(ch);
+        }
+        answer.add(sb.toString());
+        return answer;
+    }
+
     /**
      * Probes the file name to determine the mime type (such as 
application/xml, text/plain).
      *
diff --git 
a/core/camel-util/src/test/java/org/apache/camel/util/MimeTypeHelperTest.java 
b/core/camel-util/src/test/java/org/apache/camel/util/MimeTypeHelperTest.java
index f0eaac382ea3..349122979664 100644
--- 
a/core/camel-util/src/test/java/org/apache/camel/util/MimeTypeHelperTest.java
+++ 
b/core/camel-util/src/test/java/org/apache/camel/util/MimeTypeHelperTest.java
@@ -32,6 +32,38 @@ class MimeTypeHelperTest {
                 MimeTypeHelper.sanitizeMimeType("application/xslt xml , 
application/xml"));
     }
 
+    @Test
+    void testSanitizeMimeTypesWithParameters() {
+        // spaces around ; and = in the parameters are removed, not turned 
into +
+        assertEquals("application/json;q=0.5", 
MimeTypeHelper.sanitizeMimeType("application/json; q=0.5"));
+        assertEquals("application/json;charset=utf-8", 
MimeTypeHelper.sanitizeMimeType("application/json ; charset = utf-8"));
+        assertEquals("application/json;charset=utf-8;q=0.5",
+                MimeTypeHelper.sanitizeMimeType("application/json; 
charset=utf-8; q=0.5"));
+        assertEquals("application/json;q=0.5", 
MimeTypeHelper.sanitizeMimeType("application/json;q=0.5"));
+        // the type/subtype token is still repaired
+        assertEquals("application/xslt+xml;q=0.9", 
MimeTypeHelper.sanitizeMimeType("application/xslt xml; q=0.9"));
+        assertEquals("application/vnd.api+json;ext=a+b", 
MimeTypeHelper.sanitizeMimeType("application/vnd.api json; ext=a b"));
+        // several media types
+        assertEquals("application/vnd.api+json,application/json;q=0.5",
+                MimeTypeHelper.sanitizeMimeType("application/vnd.api+json, 
application/json; q=0.5"));
+        
assertEquals("application/xslt+xml,application/json;charset=utf-8,text/plain;q=0.1",
+                MimeTypeHelper.sanitizeMimeType("application/xslt xml, 
application/json; charset=utf-8 , text/plain; q=0.1"));
+        // empty parameters and media types are dropped
+        assertEquals("application/json,text/plain", 
MimeTypeHelper.sanitizeMimeType("application/json;, ,text/plain"));
+        assertEquals("", MimeTypeHelper.sanitizeMimeType(""));
+    }
+
+    @Test
+    void testSanitizeMimeTypesWithQuotedParameters() {
+        // a quoted value keeps its spaces, and a , or ; inside quotes does 
not split
+        assertEquals("text/plain;foo=\"a b\"", 
MimeTypeHelper.sanitizeMimeType("text/plain; foo=\"a b\""));
+        assertEquals("text/plain;foo=\"a, b; c\";q=0.5,application/json",
+                MimeTypeHelper.sanitizeMimeType("text/plain; foo=\"a, b; c\"; 
q=0.5, application/json"));
+        // an escaped quote inside the quoted value
+        assertEquals("text/plain;foo=\"a \\\" b, c\",application/json",
+                MimeTypeHelper.sanitizeMimeType("text/plain; foo=\"a \\\" b, 
c\", application/json"));
+    }
+
     @Test
     void testMimeType() {
         assertEquals("application/xslt+xml", 
MimeTypeHelper.probeMimeType("xslt"));

Reply via email to