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


##########
components/camel-kamelet/src/main/java/org/apache/camel/component/kamelet/Kamelet.java:
##########
@@ -184,6 +207,296 @@ public static void 
extractKameletEnvironmentVariables(Map<String, Object> proper
         }
     }
 
+    /**
+     * Reads the original advanced options map stored under a single internal 
key.
+     */
+    private static Map<String, Object> extractAdvancedOptions(Map<String, 
Object> parameters, String key) {
+        Map<String, Object> options = new LinkedHashMap<>();
+        if (parameters == null) {
+            return options;
+        }
+
+        Object value = parameters.get(key);
+        if (value instanceof Map<?, ?> map) {
+            for (Map.Entry<?, ?> entry : map.entrySet()) {
+                if (entry.getKey() != null) {
+                    options.put(entry.getKey().toString(), entry.getValue());
+                }
+            }
+        }
+
+        return options;
+    }
+
+    /**
+     * Drops Kamelet template properties from the advanced-option candidates, 
treating camelCase and kebab-case names as
+     * aliases the same way {@code DefaultModel} does for route templates.
+     */
+    private static Map<String, Object> excludeTemplateParameters(
+            Map<String, Object> candidates, RouteTemplateDefinition template) {
+        if (candidates == null || candidates.isEmpty()) {
+            return new LinkedHashMap<>();
+        }
+
+        Set<String> templateNames = templateParameterNames(template);
+        if (templateNames.isEmpty()) {
+            return candidates;
+        }
+
+        Map<String, Object> filtered = new LinkedHashMap<>();
+        for (Map.Entry<String, Object> entry : candidates.entrySet()) {
+            String name = entry.getKey();
+            if (name != null && !isTemplateParameter(name, templateNames)) {
+                filtered.put(name, entry.getValue());
+            }
+        }
+        return filtered;
+    }
+
+    private static Set<String> templateParameterNames(RouteTemplateDefinition 
template) {
+        Set<String> names = new HashSet<>();
+        if (template == null || template.getTemplateParameters() == null) {
+            return names;
+        }
+        for (RouteTemplateParameterDefinition param : 
template.getTemplateParameters()) {
+            if (param.getName() != null) {
+                names.add(param.getName());
+                names.add(StringHelper.dashToCamelCase(param.getName()));
+                names.add(StringHelper.camelCaseToDash(param.getName()));
+            }
+        }
+        return names;
+    }
+
+    private static boolean isTemplateParameter(String name, Set<String> 
templateNames) {
+        return templateNames.contains(name)
+                || templateNames.contains(StringHelper.dashToCamelCase(name))
+                || templateNames.contains(StringHelper.camelCaseToDash(name));
+    }
+
+    /**
+     * Preserves the user-supplied option name. When both camelCase and 
kebab-case forms are present, the kebab-case
+     * form is kept so the same option is not appended twice.
+     */
+    private static Map<String, Object> normalizeParameterNames(Map<String, 
Object> parameters) {
+        Map<String, Object> normalized = new LinkedHashMap<>();
+        Map<String, String> seenOriginal = new HashMap<>();
+        Map<String, Boolean> seenIsCanonical = new HashMap<>();
+
+        if (parameters == null) {
+            return normalized;
+        }
+
+        for (Map.Entry<String, Object> entry : parameters.entrySet()) {
+            String originalName = entry.getKey();
+            String name = StringHelper.camelCaseToDash(originalName);
+            boolean isCanonical = originalName.equals(name);
+
+            String existingOriginal = seenOriginal.get(name);
+            if (existingOriginal == null) {
+                seenOriginal.put(name, originalName);
+                seenIsCanonical.put(name, isCanonical);
+                normalized.put(originalName, entry.getValue());
+            } else {
+                boolean existingIsCanonical = seenIsCanonical.get(name);
+                if (isCanonical && !existingIsCanonical) {
+                    normalized.remove(existingOriginal);
+                    seenOriginal.put(name, originalName);
+                    seenIsCanonical.put(name, isCanonical);
+                    normalized.put(originalName, entry.getValue());
+                }
+            }
+        }
+
+        return normalized;
+    }
+
+    /**
+     * Appends query parameters without parsing or re-encoding the endpoint 
URI. This preserves property placeholders
+     * and RAW expressions that may appear in the URI.
+     */
+    private static String appendParametersToURI(String uri, Map<String, 
Object> parameters) {
+        if (parameters == null || parameters.isEmpty()) {
+            return uri;
+        }
+
+        String result = uri;
+
+        // First remove all parameters that will be overridden.
+        for (String name : parameters.keySet()) {
+            result = removeQueryParameter(result, name);
+        }
+
+        // Then append the options to the preserved URI.
+        StringBuilder sb = new StringBuilder(result);
+        char sep = result.indexOf('?') < 0 ? '?' : '&';
+
+        for (Map.Entry<String, Object> entry : parameters.entrySet()) {
+            sb.append(sep).append(entry.getKey());
+            if (entry.getValue() != null) {
+                
sb.append('=').append(wrapRawIfNeeded(String.valueOf(entry.getValue())));
+            }
+            sep = '&';
+        }
+
+        return sb.toString();
+    }
+
+    /**
+     * Re-wraps values that contain URI-sensitive characters.
+     */
+    private static String wrapRawIfNeeded(String value) {
+        if (value == null || value.isEmpty() || isRawToken(value)) {
+            return value;
+        }
+        if (value.contains("&") || value.contains("=") || value.contains("?")
+                || value.contains("+") || value.contains("%")) {
+            if (value.contains(")&") && !value.startsWith("{") && 
!value.endsWith("}")
+                    && !value.contains("}&")) {
+                return "RAW{" + value + "}";
+            }
+            if (value.contains(")&")) {
+                // fits in neither RAW(...) nor RAW{...}; keep the value out 
of the message, it may be a secret
+                throw new IllegalArgumentException(
+                        "The value of advanced options cannot contain \")&\" 
when it also starts with '{',"
+                                                   + " ends with '}' or 
contains \"}&\"");
+            }
+            return "RAW(" + value + ")";
+        }
+
+        return value;
+    }
+
+    private static boolean isRawToken(String value) {
+        return value != null
+                && ((value.startsWith("RAW(") && value.endsWith(")"))
+                        || (value.startsWith("RAW{") && value.endsWith("}")));
+    }
+
+    /**
+     * Removes a query parameter by name, treating camelCase and kebab-case 
names as aliases. Respects RAW(...) and
+     * RAW{...} boundaries so ampersands inside raw values do not split 
parameters.
+     */
+    static String removeQueryParameter(String uri, String parameterName) {
+        int queryIndex = uri.indexOf('?');
+        if (queryIndex < 0) {
+            return uri;
+        }
+
+        String query = uri.substring(queryIndex + 1);
+        String normalizedName = StringHelper.camelCaseToDash(parameterName);
+
+        List<String> parts = new ArrayList<>();
+        StringBuilder current = new StringBuilder();
+        int parenDepth = 0;
+        int braceDepth = 0;
+
+        for (int i = 0; i < query.length(); i++) {
+            char c = query.charAt(i);
+            if (c == '(') {
+                parenDepth++;
+            } else if (c == ')') {
+                parenDepth = Math.max(0, parenDepth - 1);
+            } else if (c == '{') {
+                braceDepth++;
+            } else if (c == '}') {
+                braceDepth = Math.max(0, braceDepth - 1);
+            } else if (c == '&' && parenDepth == 0 && braceDepth == 0) {
+                parts.add(current.toString());

Review Comment:
   Non-blocking. This counts every `(` and `{` in the query, while Camel's own 
parser (`URIScanner`) only treats `RAW(...)` / `RAW{...}` as a block, and ends 
a `RAW(` value at the first `)&`. The two can disagree when a value has an 
unbalanced bracket. For example, with the template URI 
`foo?password=RAW(p(ss)&other=1`, Camel reads `password` = `p(ss` and `other` = 
`1`. Here the depth is still 1 at the `&`, so the query stays in one piece. 
Overriding `other` then leaves the old `other=1` in place and appends a second 
one.
   
   `URISupport.scanRaw(query)` returns the start and end of each RAW token with 
Camel's own rules, and `URISupport.isRaw(i, pairs)` tells whether an index is 
inside one. Splitting on every `&` that is not inside a RAW token would match 
`URIScanner` exactly, and placeholders like `{{x}}` contain no `&`, so they 
need no special case.



-- 
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