This is an automated email from the ASF dual-hosted git repository. davsclaus pushed a commit to branch CAMEL-27160 in repository https://gitbox.apache.org/repos/asf/camel.git
commit b211a75c49b5221ad691f52f127db1b85fb693e5 Author: Andrea Cosentino <[email protected]> AuthorDate: Wed Nov 18 11:05:24 2026 +0100 CAMEL-27160: Dynamic endpoint option values computed from the message are bound as literal text The per-message recipient option values of toD, enrich, wireTap, pollEnrich, recipientList, routingSlip and dynamicRouter are now bound without property-placeholder resolution and without bean/class reference resolution, extending the CAMEL-24282 / CAMEL-24414 uri-path treatment to the option binding. Property placeholders written in the static route template are still resolved at build time. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Andrea Cosentino <[email protected]> --- .../camel/impl/engine/AbstractCamelContext.java | 20 +- .../impl/engine/DefaultCamelContextExtension.java | 18 +- .../org/apache/camel/processor/PollEnricher.java | 4 +- .../apache/camel/processor/ProcessorHelper.java | 16 +- .../camel/processor/SendDynamicProcessor.java | 6 +- .../DynamicEndpointMessageOptionLiteralTest.java | 275 +++++++++++++++++++++ .../org/apache/camel/support/DefaultComponent.java | 44 +++- .../org/apache/camel/support/DefaultEndpoint.java | 18 ++ .../org/apache/camel/support/NormalizedUri.java | 40 ++- .../camel/support/PropertyBindingSupport.java | 96 ++++--- .../ROOT/pages/camel-4x-upgrade-guide-4_24.adoc | 16 ++ 11 files changed, 502 insertions(+), 51 deletions(-) diff --git a/core/camel-base-engine/src/main/java/org/apache/camel/impl/engine/AbstractCamelContext.java b/core/camel-base-engine/src/main/java/org/apache/camel/impl/engine/AbstractCamelContext.java index 4df82abb5d11..bd8d8995e994 100644 --- a/core/camel-base-engine/src/main/java/org/apache/camel/impl/engine/AbstractCamelContext.java +++ b/core/camel-base-engine/src/main/java/org/apache/camel/impl/engine/AbstractCamelContext.java @@ -193,6 +193,7 @@ import org.apache.camel.spi.ValidatorRegistry; import org.apache.camel.spi.VariableRepository; import org.apache.camel.spi.VariableRepositoryFactory; import org.apache.camel.support.CamelContextHelper; +import org.apache.camel.support.DefaultComponent; import org.apache.camel.support.DefaultThreadPoolFactory; import org.apache.camel.support.EndpointHelper; import org.apache.camel.support.EventHelper; @@ -874,11 +875,17 @@ public abstract class AbstractCamelContext extends BaseService } protected Endpoint doGetEndpoint(String uri, Map<String, Object> parameters, boolean normalized, boolean prototype) { - return doGetEndpoint(uri, null, parameters, normalized, prototype); + return doGetEndpoint(uri, null, parameters, normalized, prototype, false); } protected Endpoint doGetEndpoint( String uri, String explicitRawUri, Map<String, Object> parameters, boolean normalized, boolean prototype) { + return doGetEndpoint(uri, explicitRawUri, parameters, normalized, prototype, false); + } + + protected Endpoint doGetEndpoint( + String uri, String explicitRawUri, Map<String, Object> parameters, boolean normalized, boolean prototype, + boolean literalOptionBinding) { // ensure CamelContext are initialized before we can get an endpoint build(); @@ -945,9 +952,14 @@ public abstract class AbstractCamelContext extends BaseService LOG.trace("Creating endpoint from uri: {} using component: {}", uri, component); // Have the component create the endpoint if it can. - answer = component.createEndpoint( - component.useRawUri() ? rawUri : uri, - parameters); + String createUri = component.useRawUri() ? rawUri : uri; + // when the uri was computed from the current message at runtime its query option values must be + // bound as literal text (no property-placeholder and no bean/class reference resolution) + if (literalOptionBinding && component instanceof DefaultComponent dc) { + answer = dc.createEndpoint(createUri, parameters, true); + } else { + answer = component.createEndpoint(createUri, parameters); + } if (answer != null && LOG.isDebugEnabled()) { LOG.debug("{} converted to endpoint: {} by component: {}", URISupport.sanitizeUri(uri), answer, diff --git a/core/camel-base-engine/src/main/java/org/apache/camel/impl/engine/DefaultCamelContextExtension.java b/core/camel-base-engine/src/main/java/org/apache/camel/impl/engine/DefaultCamelContextExtension.java index 0bc46298872e..5d8c6d9a4c73 100644 --- a/core/camel-base-engine/src/main/java/org/apache/camel/impl/engine/DefaultCamelContextExtension.java +++ b/core/camel-base-engine/src/main/java/org/apache/camel/impl/engine/DefaultCamelContextExtension.java @@ -292,8 +292,10 @@ class DefaultCamelContextExtension implements ExtendedCamelContext { @Override public Endpoint getEndpoint(NormalizedEndpointUri uri) { - String rawUri = uri instanceof NormalizedUri nu ? nu.getRawUri() : null; - return camelContext.doGetEndpoint(uri.getUri(), rawUri, null, true, false); + NormalizedUri nu = uri instanceof NormalizedUri n ? n : null; + String rawUri = nu != null ? nu.getRawUri() : null; + boolean literal = nu != null && nu.isLiteralOptionBinding(); + return camelContext.doGetEndpoint(uri.getUri(), rawUri, null, true, false, literal); } @Override @@ -303,14 +305,18 @@ class DefaultCamelContextExtension implements ExtendedCamelContext { @Override public Endpoint getPrototypeEndpoint(NormalizedEndpointUri uri) { - String rawUri = uri instanceof NormalizedUri nu ? nu.getRawUri() : null; - return camelContext.doGetEndpoint(uri.getUri(), rawUri, null, true, true); + NormalizedUri nu = uri instanceof NormalizedUri n ? n : null; + String rawUri = nu != null ? nu.getRawUri() : null; + boolean literal = nu != null && nu.isLiteralOptionBinding(); + return camelContext.doGetEndpoint(uri.getUri(), rawUri, null, true, true, literal); } @Override public Endpoint getEndpoint(NormalizedEndpointUri uri, Map<String, Object> parameters) { - String rawUri = uri instanceof NormalizedUri nu ? nu.getRawUri() : null; - return camelContext.doGetEndpoint(uri.getUri(), rawUri, parameters, true, false); + NormalizedUri nu = uri instanceof NormalizedUri n ? n : null; + String rawUri = nu != null ? nu.getRawUri() : null; + boolean literal = nu != null && nu.isLiteralOptionBinding(); + return camelContext.doGetEndpoint(uri.getUri(), rawUri, parameters, true, false, literal); } @Override diff --git a/core/camel-core-processor/src/main/java/org/apache/camel/processor/PollEnricher.java b/core/camel-core-processor/src/main/java/org/apache/camel/processor/PollEnricher.java index 6c9b59f7ac78..f2184208c3ca 100644 --- a/core/camel-core-processor/src/main/java/org/apache/camel/processor/PollEnricher.java +++ b/core/camel-core-processor/src/main/java/org/apache/camel/processor/PollEnricher.java @@ -539,7 +539,9 @@ public class PollEnricher extends BaseProcessorSupport implements IdAware, Route // optimize and normalize endpoint without re-resolving property placeholders on the // per-message evaluated recipient, matching toD and enrich (CAMEL-24282 / CAMEL-24414). // pollEnrich resolves its static uri at build time, so the placeholder belongs there. - return NormalizedUri.newNormalizedUri(uri, false); + // The per-message recipient comes from the message, so its query option values are bound as + // literal text as well (no property-placeholder and no bean/class reference resolution) - CAMEL-27160 + return NormalizedUri.newNormalizedUri(uri, false, true); } return null; } diff --git a/core/camel-core-processor/src/main/java/org/apache/camel/processor/ProcessorHelper.java b/core/camel-core-processor/src/main/java/org/apache/camel/processor/ProcessorHelper.java index 8d865ade6755..3b8481369eee 100644 --- a/core/camel-core-processor/src/main/java/org/apache/camel/processor/ProcessorHelper.java +++ b/core/camel-core-processor/src/main/java/org/apache/camel/processor/ProcessorHelper.java @@ -28,7 +28,9 @@ import org.apache.camel.ExtendedCamelContext; import org.apache.camel.NoTypeConversionAvailableException; import org.apache.camel.ResolveEndpointFailedException; import org.apache.camel.spi.NormalizedEndpointUri; +import org.apache.camel.support.EndpointHelper; import org.apache.camel.support.ExchangeHelper; +import org.apache.camel.support.NormalizedUri; import org.apache.camel.support.PatternHelper; import org.slf4j.MDC; @@ -84,8 +86,18 @@ final class ProcessorHelper { // convert to a string type we can work with uri = ecc.getTypeConverter().mandatoryConvertTo(String.class, exchange, recipient); } - // optimize and normalize endpoint - return ecc.getCamelContextExtension().normalizeUri(uri); + // optimize and normalize endpoint. Property placeholders in the computed uri string are still resolved + // here (documented recipientList/routingSlip/dynamicRouter behaviour), but the uri was computed from the + // message, so its query option values are bound as literal text: no property-placeholder and no + // bean/class reference (#class:, #bean:, #type:, ...) resolution on the option values (CAMEL-27160). + try { + String resolved = EndpointHelper.resolveEndpointUriPropertyPlaceholders(ecc, uri); + return NormalizedUri.newNormalizedUri(resolved, false, true); + } catch (ResolveEndpointFailedException e) { + throw e; + } catch (Exception e) { + throw new ResolveEndpointFailedException(uri, e); + } } return null; } diff --git a/core/camel-core-processor/src/main/java/org/apache/camel/processor/SendDynamicProcessor.java b/core/camel-core-processor/src/main/java/org/apache/camel/processor/SendDynamicProcessor.java index bf6dcdd23a12..7a2f445372e1 100644 --- a/core/camel-core-processor/src/main/java/org/apache/camel/processor/SendDynamicProcessor.java +++ b/core/camel-core-processor/src/main/java/org/apache/camel/processor/SendDynamicProcessor.java @@ -333,8 +333,10 @@ public class SendDynamicProcessor extends BaseProcessorSupport throw new ResolveEndpointFailedException(uri, "Endpoint should include scheme:path"); } // optimize and normalize endpoint without re-resolving property placeholders on the - // per-message evaluated recipient (see resolveUri and CAMEL-24282) - return NormalizedUri.newNormalizedUri(uri, false); + // per-message evaluated recipient (see resolveUri and CAMEL-24282). The per-message recipient + // comes from the message, so its query option values are bound as literal text as well (no + // property-placeholder and no bean/class reference resolution) - CAMEL-27160 + return NormalizedUri.newNormalizedUri(uri, false, true); } return null; } diff --git a/core/camel-core/src/test/java/org/apache/camel/processor/DynamicEndpointMessageOptionLiteralTest.java b/core/camel-core/src/test/java/org/apache/camel/processor/DynamicEndpointMessageOptionLiteralTest.java new file mode 100644 index 000000000000..46aa5e5686e4 --- /dev/null +++ b/core/camel-core/src/test/java/org/apache/camel/processor/DynamicEndpointMessageOptionLiteralTest.java @@ -0,0 +1,275 @@ +/* + * 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.processor; + +import java.util.Map; +import java.util.Properties; + +import org.apache.camel.CamelContext; +import org.apache.camel.Consumer; +import org.apache.camel.ContextTestSupport; +import org.apache.camel.Endpoint; +import org.apache.camel.Exchange; +import org.apache.camel.Header; +import org.apache.camel.PollingConsumer; +import org.apache.camel.Processor; +import org.apache.camel.Producer; +import org.apache.camel.builder.AggregationStrategies; +import org.apache.camel.builder.RouteBuilder; +import org.apache.camel.support.DefaultComponent; +import org.apache.camel.support.DefaultEndpoint; +import org.apache.camel.support.DefaultProducer; +import org.apache.camel.support.PollingConsumerSupport; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Companion to {@link DynamicEndpointMessagePlaceholderTest}: the per-message recipient of the dynamic-uri EIPs is + * computed from the message, so its query option values are also treated as literal text. A property-placeholder token + * ({@code {{...}}}) or a bean/class reference token ({@code #class:}, {@code #bean:}, {@code #type:}) that appears in a + * runtime-computed option value is kept verbatim: it is neither resolved, nor is any class instantiated or bean looked + * up. See CAMEL-27160, which extends the CAMEL-24282 / CAMEL-24414 treatment from the uri path to the option binding. + * <p/> + * For {@code recipientList}, {@code routingSlip} and {@code dynamicRouter} the documented resolution of property + * placeholders in the computed uri string is preserved (see {@link DynamicEndpointMessagePlaceholderTest}); only the + * bean/class reference resolution of their runtime option values is brought in line, which is why those EIPs are + * exercised here with reference tokens rather than placeholder tokens. + */ +class DynamicEndpointMessageOptionLiteralTest extends ContextTestSupport { + + private static final String MARKER_CLASS = "#class:" + Marker.class.getName(); + private static final String MARKER_BEAN = "#bean:marker"; + + @Override + protected CamelContext createCamelContext() throws Exception { + CamelContext context = super.createCamelContext(); + Properties prop = new Properties(); + prop.setProperty("secretTarget", "resolved"); + context.getPropertiesComponent().setInitialProperties(prop); + context.addComponent("sink", new SinkComponent()); + context.getRegistry().bind("marker", new Marker()); + return context; + } + + @BeforeEach + void resetSink() { + SinkEndpoint.lastOption = null; + Marker.instances = 0; + } + + @Test + void toDOptionPlaceholderTokenStaysLiteral() throws Exception { + getMockEndpoint("mock:done").expectedMessageCount(1); + + template.sendBodyAndHeader("direct:tod", "Hello", "target", "sink:a?option={{secretTarget}}"); + + assertMockEndpointsSatisfied(); + assertThat(SinkEndpoint.lastOption).isEqualTo("{{secretTarget}}"); + } + + @Test + void toDOptionClassReferenceTokenStaysLiteral() throws Exception { + getMockEndpoint("mock:done").expectedMessageCount(1); + + template.sendBodyAndHeader("direct:tod", "Hello", "target", "sink:b?option=" + MARKER_CLASS); + + assertMockEndpointsSatisfied(); + assertThat(SinkEndpoint.lastOption).isEqualTo(MARKER_CLASS); + assertThat(Marker.instances).isZero(); + } + + @Test + void toDOptionBeanReferenceTokenStaysLiteral() throws Exception { + getMockEndpoint("mock:done").expectedMessageCount(1); + + template.sendBodyAndHeader("direct:tod", "Hello", "target", "sink:c?option=" + MARKER_BEAN); + + assertMockEndpointsSatisfied(); + assertThat(SinkEndpoint.lastOption).isEqualTo(MARKER_BEAN); + } + + @Test + void enrichOptionClassReferenceTokenStaysLiteral() throws Exception { + getMockEndpoint("mock:done").expectedMessageCount(1); + + template.sendBodyAndHeader("direct:en", "Hello", "target", "sink:d?option=" + MARKER_CLASS); + + assertMockEndpointsSatisfied(); + assertThat(SinkEndpoint.lastOption).isEqualTo(MARKER_CLASS); + assertThat(Marker.instances).isZero(); + } + + @Test + void pollEnrichOptionClassReferenceTokenStaysLiteral() throws Exception { + getMockEndpoint("mock:done").expectedMessageCount(1); + + template.sendBodyAndHeader("direct:pe", "Hello", "target", "sink:e?option=" + MARKER_CLASS); + + assertMockEndpointsSatisfied(); + assertThat(SinkEndpoint.lastOption).isEqualTo(MARKER_CLASS); + assertThat(Marker.instances).isZero(); + } + + @Test + void recipientListOptionClassReferenceTokenStaysLiteral() throws Exception { + getMockEndpoint("mock:done").expectedMessageCount(1); + + template.sendBodyAndHeader("direct:rl", "Hello", "target", "sink:f?option=" + MARKER_CLASS); + + assertMockEndpointsSatisfied(); + assertThat(SinkEndpoint.lastOption).isEqualTo(MARKER_CLASS); + assertThat(Marker.instances).isZero(); + } + + @Test + void routingSlipOptionClassReferenceTokenStaysLiteral() throws Exception { + template.sendBodyAndHeader("direct:rs", "Hello", "target", "sink:g?option=" + MARKER_CLASS); + + assertThat(SinkEndpoint.lastOption).isEqualTo(MARKER_CLASS); + assertThat(Marker.instances).isZero(); + } + + @Test + void dynamicRouterOptionClassReferenceTokenStaysLiteral() throws Exception { + template.sendBodyAndHeader("direct:dr", "Hello", "target", "sink:h?option=" + MARKER_CLASS); + + assertThat(SinkEndpoint.lastOption).isEqualTo(MARKER_CLASS); + assertThat(Marker.instances).isZero(); + } + + /** + * Dynamic router bean: routes to the header-supplied recipient on the first hop, then stops. + */ + public String route(@Header("target") String target, @Header(Exchange.SLIP_ENDPOINT) String previous) { + return previous == null ? target : null; + } + + @Override + protected RouteBuilder createRouteBuilder() { + return new RouteBuilder() { + @Override + public void configure() { + from("direct:tod").toD("${header.target}").to("mock:done"); + from("direct:en").enrich().simple("${header.target}") + .aggregationStrategy(AggregationStrategies.useOriginal()).to("mock:done"); + from("direct:pe").pollEnrich().simple("${header.target}").timeout(100).end().to("mock:done"); + from("direct:rl").recipientList(header("target")).to("mock:done"); + from("direct:rs").routingSlip(header("target")); + from("direct:dr").dynamicRouter(method(DynamicEndpointMessageOptionLiteralTest.this, "route")); + } + }; + } + + /** + * Marker whose public no-arg constructor counts instantiations, so a {@code #class:} reference that is wrongly + * resolved can be detected. + */ + public static class Marker { + static volatile int instances; + + public Marker() { + instances++; + } + } + + /** + * A local in-JVM sink that records the value bound to its {@code option} property, so the test can assert that a + * runtime-computed option value is kept literal. + */ + private static final class SinkComponent extends DefaultComponent { + @Override + protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) { + return new SinkEndpoint(uri, this); + } + } + + private static final class SinkEndpoint extends DefaultEndpoint { + static volatile Object lastOption; + private Object option; + + SinkEndpoint(String uri, SinkComponent component) { + super(uri, component); + } + + public Object getOption() { + return option; + } + + public void setOption(Object option) { + this.option = option; + lastOption = option; + } + + @Override + public Producer createProducer() { + return new DefaultProducer(this) { + @Override + public void process(Exchange exchange) { + // no-op sink + } + }; + } + + @Override + public Consumer createConsumer(Processor processor) { + throw new UnsupportedOperationException(); + } + + @Override + public PollingConsumer createPollingConsumer() { + return new NoopPollingConsumer(this); + } + + @Override + public boolean isSingleton() { + return false; + } + } + + private static final class NoopPollingConsumer extends PollingConsumerSupport { + NoopPollingConsumer(Endpoint endpoint) { + super(endpoint); + } + + @Override + public Exchange receive() { + return null; + } + + @Override + public Exchange receive(long timeout) { + return null; + } + + @Override + public Exchange receiveNoWait() { + return null; + } + + @Override + protected void doStart() { + // noop + } + + @Override + protected void doStop() { + // noop + } + } +} diff --git a/core/camel-support/src/main/java/org/apache/camel/support/DefaultComponent.java b/core/camel-support/src/main/java/org/apache/camel/support/DefaultComponent.java index c3f5fd0eabfd..019dc85185e8 100644 --- a/core/camel-support/src/main/java/org/apache/camel/support/DefaultComponent.java +++ b/core/camel-support/src/main/java/org/apache/camel/support/DefaultComponent.java @@ -88,6 +88,29 @@ public abstract class DefaultComponent extends ServiceSupport implements Compone @Override public Endpoint createEndpoint(String uri, Map<String, Object> properties) throws Exception { + return createEndpoint(uri, properties, false); + } + + /** + * Creates an endpoint, binding the query option values as literal text when {@code literalOptionBinding} is + * {@code true}. + * <p> + * Literal binding is used when the uri was computed from the current message at runtime (for example the + * per-message recipient of a dynamic endpoint such as {@code toD}, {@code enrich}, {@code wireTap}, + * {@code pollEnrich}, {@code recipientList}, {@code routingSlip} or {@code dynamicRouter}): the option values then + * come from the message and not from the route, so they are bound without property-placeholder resolution and + * without bean/class reference ({@code #class:}, {@code #bean:}, {@code #type:}, ...) resolution. + * + * @param uri the full URI of the endpoint + * @param properties the optional parameters passed in + * @param literalOptionBinding whether the query option values must be bound as literal text + * @return a newly created endpoint or null if the endpoint cannot be created based on the + * inputs + * @throws Exception is thrown if error creating the endpoint + * @since 4.24 + */ + public Endpoint createEndpoint(String uri, Map<String, Object> properties, boolean literalOptionBinding) + throws Exception { // need to encode before its safe to parse with java.net.Uri String encodedUri = UnsafeUriCharactersEncoder.encode(uri); URI u = new URI(encodedUri); @@ -177,7 +200,7 @@ public abstract class DefaultComponent extends ServiceSupport implements Compone } // configure remainder of the parameters - setProperties(endpoint, parameters); + setProperties(endpoint, parameters, literalOptionBinding); // if endpoint is strict (not lenient) and we have unknown parameters configured then // fail if there are parameters that could not be set, then they are probably misspell or not supported at all @@ -404,6 +427,25 @@ public abstract class DefaultComponent extends ServiceSupport implements Compone endpoint.configureProperties(parameters); } + /** + * Configure an endpoint using the given parameters, binding the option values as literal text when + * {@code literalOptionBinding} is {@code true} (for a uri computed from the current message at runtime), see + * {@link #createEndpoint(String, Map, boolean)}. + * + * @param endpoint the endpoint + * @param parameters properties to set + * @param literalOptionBinding whether the option values must be bound as literal text + * @since 4.24 + */ + protected void setProperties(Endpoint endpoint, Map<String, Object> parameters, boolean literalOptionBinding) + throws Exception { + if (literalOptionBinding && endpoint instanceof DefaultEndpoint de) { + de.setProperties(endpoint, parameters, true); + } else { + endpoint.configureProperties(parameters); + } + } + /** * Sets the bean properties on the given bean * diff --git a/core/camel-support/src/main/java/org/apache/camel/support/DefaultEndpoint.java b/core/camel-support/src/main/java/org/apache/camel/support/DefaultEndpoint.java index 904f0a40dd94..a3737c8116e7 100644 --- a/core/camel-support/src/main/java/org/apache/camel/support/DefaultEndpoint.java +++ b/core/camel-support/src/main/java/org/apache/camel/support/DefaultEndpoint.java @@ -403,6 +403,22 @@ public abstract class DefaultEndpoint extends ServiceSupport implements Endpoint * @param parameters properties to set */ public void setProperties(Object bean, Map<String, Object> parameters) { + setProperties(bean, parameters, false); + } + + /** + * Sets the bean properties on the given bean. + * <p> + * This is the same logical implementation as {@link DefaultComponent#setProperties(Object, java.util.Map)} + * + * @param bean the bean + * @param parameters properties to set + * @param literalOptionBinding whether the values were computed from the current message at runtime and so must be + * bound as literal text (without property-placeholder and without bean/class reference + * resolution), see {@link PropertyBindingSupport.Builder#withLiteral(boolean)} + * @since 4.24 + */ + public void setProperties(Object bean, Map<String, Object> parameters, boolean literalOptionBinding) { if (parameters == null || parameters.isEmpty()) { return; } @@ -420,6 +436,8 @@ public abstract class DefaultEndpoint extends ServiceSupport implements Endpoint PropertyBindingSupport.build().withConfigurer(configurer).withIgnoreCase(true) // if the endpoint is lenient then use optional .withOptional(isLenientProperties()) + // bind message-derived values as literal text + .withLiteral(literalOptionBinding) .bind(camelContext, bean, parameters); } diff --git a/core/camel-support/src/main/java/org/apache/camel/support/NormalizedUri.java b/core/camel-support/src/main/java/org/apache/camel/support/NormalizedUri.java index cbd9f543674d..9a19849b879e 100644 --- a/core/camel-support/src/main/java/org/apache/camel/support/NormalizedUri.java +++ b/core/camel-support/src/main/java/org/apache/camel/support/NormalizedUri.java @@ -33,9 +33,17 @@ public final class NormalizedUri extends ValueHolder<String> implements Normaliz // NormalizedEndpointUri (e.g. from SendDynamicProcessor / toD). private final String rawUri; - private NormalizedUri(String normalizedValue, String rawUri) { + // Whether the endpoint uri was computed from the current message at runtime (for example the per-message + // recipient of toD, enrich, wireTap, pollEnrich, recipientList, routingSlip or dynamicRouter). When true the + // query option values are bound as literal text, i.e. without property-placeholder resolution and without + // bean/class reference (#class:, #bean:, #type:, ...) resolution, because those segments come from the message + // and not from the route. Not part of equals/hashCode: the endpoint registry key stays the uri alone. + private final boolean literalOptionBinding; + + private NormalizedUri(String normalizedValue, String rawUri, boolean literalOptionBinding) { super(normalizedValue); this.rawUri = rawUri; + this.literalOptionBinding = literalOptionBinding; } /** @@ -46,10 +54,25 @@ public final class NormalizedUri extends ValueHolder<String> implements Normaliz * @return the created normalized uri */ public static NormalizedUri newNormalizedUri(String uri, boolean normalized) { + return newNormalizedUri(uri, normalized, false); + } + + /** + * Creates a new {@link NormalizedUri} instance. + * + * @param uri the uri + * @param normalized whether its already normalized + * @param literalOptionBinding whether the query option values were computed from the current message and must be + * bound as literal text (no property-placeholder and no bean/class reference + * resolution) + * @return the created normalized uri + * @since 4.24 + */ + public static NormalizedUri newNormalizedUri(String uri, boolean normalized, boolean literalOptionBinding) { if (normalized) { - return new NormalizedUri(uri, null); + return new NormalizedUri(uri, null, literalOptionBinding); } else { - return new NormalizedUri(EndpointHelper.normalizeEndpointUri(uri), uri); + return new NormalizedUri(EndpointHelper.normalizeEndpointUri(uri), uri, literalOptionBinding); } } @@ -68,6 +91,17 @@ public final class NormalizedUri extends ValueHolder<String> implements Normaliz return rawUri; } + /** + * Whether the query option values of this uri were computed from the current message at runtime and must therefore + * be bound as literal text, that is without property-placeholder resolution and without bean/class reference + * ({@code #class:}, {@code #bean:}, {@code #type:}, ...) resolution. + * + * @since 4.24 + */ + public boolean isLiteralOptionBinding() { + return literalOptionBinding; + } + @Override public String getUri() { return get(); diff --git a/core/camel-support/src/main/java/org/apache/camel/support/PropertyBindingSupport.java b/core/camel-support/src/main/java/org/apache/camel/support/PropertyBindingSupport.java index 6eda0f45eb70..be660c596d37 100644 --- a/core/camel-support/src/main/java/org/apache/camel/support/PropertyBindingSupport.java +++ b/core/camel-support/src/main/java/org/apache/camel/support/PropertyBindingSupport.java @@ -252,6 +252,11 @@ public final class PropertyBindingSupport { * value * @param reference whether reference parameter (syntax starts with #) is in use * @param placeholder whether to use Camels property placeholder to resolve placeholders on keys and values + * @param literal whether values must be bound as literal text, that is without property-placeholder + * resolution and without bean/class reference (#class:, #bean:, #type:, ...) resolution. + * Used when the values were computed from message content at runtime (for example the + * per-message option values of a dynamic endpoint) and so must not be resolved as if + * they came from the route. * @param reflection whether to allow using reflection (when there is no configurer available). * @param configurer to use an optional {@link PropertyConfigurer} to configure the properties * @param listener optional listener @@ -262,7 +267,7 @@ public final class PropertyBindingSupport { String optionPrefix, boolean ignoreCase, boolean removeParameter, boolean flattenProperties, boolean mandatory, boolean optional, boolean nesting, boolean deepNesting, boolean fluentBuilder, boolean allowPrivateSetter, - boolean reference, boolean placeholder, + boolean reference, boolean placeholder, boolean literal, boolean reflection, PropertyConfigurer configurer, PropertyBindingListener listener) { @@ -309,7 +314,8 @@ public final class PropertyBindingSupport { listener.bindProperty(target, key, value); } boolean hit = doBuildPropertyOgnlPath(camelContext, target, key, value, deepNesting, fluentBuilder, - allowPrivateSetter, ignoreCase, reference, placeholder, mandatory, optional, reflection, configurer); + allowPrivateSetter, ignoreCase, reference, placeholder, literal, mandatory, optional, reflection, + configurer); if (hit && removeParameter) { properties.remove(key); } @@ -322,8 +328,8 @@ public final class PropertyBindingSupport { private static boolean doBuildPropertyOgnlPath( final CamelContext camelContext, final Object originalTarget, String name, final Object value, boolean deepNesting, boolean fluentBuilder, boolean allowPrivateSetter, - boolean ignoreCase, boolean reference, boolean placeholder, boolean mandatory, boolean optional, - boolean reflection, PropertyConfigurer configurer) { + boolean ignoreCase, boolean reference, boolean placeholder, boolean literal, boolean mandatory, + boolean optional, boolean reflection, PropertyConfigurer configurer) { if (name.startsWith("?")) { // the name marks the option as optional @@ -429,7 +435,7 @@ public final class PropertyBindingSupport { // we have walked down to the last part of the ognl path and are ready to set the last piece with the value // now this is actually also a bit complex so lets use another method for that return doSetPropertyValue(camelContext, newTarget, newName, value, ignoreCase, mandatory, - fluentBuilder, allowPrivateSetter, reference, placeholder, optional, reflection, configurer); + fluentBuilder, allowPrivateSetter, reference, placeholder, literal, optional, reflection, configurer); } private static Object attemptCreateNewInstanceViaReflection( @@ -516,13 +522,13 @@ public final class PropertyBindingSupport { CamelContext camelContext, Object target, String name, Object value, boolean ignoreCase, boolean mandatory, boolean fluentBuilder, boolean allowPrivateSetter, - boolean reference, boolean placeholder, boolean optional, + boolean reference, boolean placeholder, boolean literal, boolean optional, boolean reflection, PropertyConfigurer configurer) { String key = name; Object text = value; - if (placeholder) { + if (placeholder && !literal) { // resolve property placeholders key = camelContext.resolvePropertyPlaceholders(key); if (text instanceof String s) { @@ -535,48 +541,60 @@ public final class PropertyBindingSupport { } } - // prepare the value before it is bound - try { - Object str = resolveValue(camelContext, target, key, text, ignoreCase, fluentBuilder, - allowPrivateSetter, reflection, configurer); - // resolve property placeholders - if (str instanceof String strValue) { + // prepare the value before it is bound. In literal mode the value was computed from message content at + // runtime, so it is kept verbatim: neither property placeholders nor bean/class references (#class:, #bean:, + // #type:, ...) are resolved, because that resolution is reserved for values authored in the route. + if (literal) { + value = text; + } else { + try { + Object str = resolveValue(camelContext, target, key, text, ignoreCase, fluentBuilder, + allowPrivateSetter, reflection, configurer); // resolve property placeholders - str = camelContext.resolvePropertyPlaceholders(strValue); - } - if (str == null && reference && mandatory && !optional) { - // we could not resolve the reference and this is mandatory - throw new PropertyBindingException(target, key, value); + if (str instanceof String strValue) { + // resolve property placeholders + str = camelContext.resolvePropertyPlaceholders(strValue); + } + if (str == null && reference && mandatory && !optional) { + // we could not resolve the reference and this is mandatory + throw new PropertyBindingException(target, key, value); + } + value = str; + } catch (Exception e) { + // report the exception using the long key and parent target + throw new PropertyBindingException(target, key, text, e); } - value = str; - } catch (Exception e) { - // report the exception using the long key and parent target - throw new PropertyBindingException(target, key, text, e); } + // in literal mode reference resolution must be disabled on every binding path, and a value that still looks + // like a reference (#...) must not be handed to the configurer either (the configurer resolves references for + // non-String options on its own), so it is bound via reflection as plain text instead + boolean effReference = reference && !literal; + boolean skipConfigurer = literal && value instanceof String refStr && isReferenceParameter(refStr); + // okay we are ready to set the value, but the property key // can still be complex such as a map/list/array so we need to handle them specially than a regular key boolean bound = false; try { if (isCollectionKey(name)) { // collection key (list,map,array) - if (configurer != null) { + if (configurer != null && !skipConfigurer) { bound = setPropertyCollectionViaConfigurer(camelContext, target, key, value, ignoreCase, configurer); } if (!bound && reflection) { // fallback to reflection based - bound = setPropertyCollectionViaReflection(camelContext, target, key, value, ignoreCase, reference, + bound = setPropertyCollectionViaReflection(camelContext, target, key, value, ignoreCase, effReference, optional); } } else { // regular key - if (configurer != null) { + if (configurer != null && !skipConfigurer) { bound = setSimplePropertyViaConfigurer(camelContext, target, key, value, ignoreCase, configurer); } if (!bound && reflection) { // fallback to reflection based bound = setSimplePropertyViaReflection(camelContext, target, key, value, fluentBuilder, allowPrivateSetter, - reflection, ignoreCase); + !literal && reflection, ignoreCase); } // if the target value is a map type, then we can skip reflection // and set the entry @@ -2139,6 +2157,7 @@ public final class PropertyBindingSupport { private boolean deepNesting = true; private boolean reference = true; private boolean placeholder = true; + private boolean literal; private boolean fluentBuilder = true; private boolean allowPrivateSetter = true; private boolean ignoreCase; @@ -2252,6 +2271,19 @@ public final class PropertyBindingSupport { return this; } + /** + * Whether values must be bound as literal text, that is without property-placeholder resolution and without + * bean/class reference ({@code #class:}, {@code #bean:}, {@code #type:}, ...) resolution. Use this when the + * values were computed from message content at runtime (for example the per-message option values of a dynamic + * endpoint) so that message content is never resolved as if it had been authored in the route. + * + * @since 4.24 + */ + public Builder withLiteral(boolean literal) { + this.literal = literal; + return this; + } + /** * Whether fluent builder is allowed as a valid getter/setter */ @@ -2356,8 +2388,8 @@ public final class PropertyBindingSupport { return doBindProperties(camelContext, target, removeParameters ? properties : new HashMap<>(properties), optionPrefix, ignoreCase, removeParameters, flattenProperties, mandatory, optional, - nesting, deepNesting, fluentBuilder, allowPrivateSetter, reference, placeholder, reflection, configurer, - listener); + nesting, deepNesting, fluentBuilder, allowPrivateSetter, reference, placeholder, literal, reflection, + configurer, listener); } /** @@ -2375,8 +2407,8 @@ public final class PropertyBindingSupport { return doBindProperties(context, obj, removeParameters ? prop : new HashMap<>(prop), optionPrefix, ignoreCase, removeParameters, flattenProperties, mandatory, optional, - nesting, deepNesting, fluentBuilder, allowPrivateSetter, reference, placeholder, reflection, configurer, - listener); + nesting, deepNesting, fluentBuilder, allowPrivateSetter, reference, placeholder, literal, reflection, + configurer, listener); } /** @@ -2394,8 +2426,8 @@ public final class PropertyBindingSupport { return doBindProperties(camelContext, target, properties, optionPrefix, ignoreCase, true, false, mandatory, optional, - nesting, deepNesting, fluentBuilder, allowPrivateSetter, reference, placeholder, reflection, configurer, - listener); + nesting, deepNesting, fluentBuilder, allowPrivateSetter, reference, placeholder, literal, reflection, + configurer, listener); } } diff --git a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc index 4dbf2897885b..ae09883c037b 100644 --- a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc +++ b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc @@ -133,6 +133,22 @@ the WARN says to use `toD`. The route works as before. Only the endpoint path is of `sql`, and the components whose path option is marked `supportSimpleExpression` in their metadata, which now includes the template of `sql-stored` and the bucket name of `aws2-s3`. +=== camel-core - option values of a dynamic endpoint computed from the message are bound as literal text + +The dynamic-endpoint EIPs -- `toD`, `enrich`, `wireTap`, `pollEnrich`, `recipientList`, `routingSlip` and +`dynamicRouter` -- compute their target endpoint from the current message at runtime. The query option values of that +per-message endpoint are now bound as literal text: a property-placeholder token (`{{...}}`) or a bean or class +reference token (`#class:`, `#bean:`, `#type:`) that appears in a runtime-computed option value is kept verbatim, so it +is neither resolved as a property nor used to look up a bean or instantiate a class. This extends to the option binding +the treatment that `toD`, `enrich`, `wireTap` and `pollEnrich` already gave the endpoint path, where property +placeholders in the computed path are not resolved. `recipientList`, `routingSlip` and `dynamicRouter` still resolve +property placeholders in the computed uri string, only their option values change. + +Property placeholders written in the static route template are still resolved once when the route starts, so +`toD("mock:foo?delay={{myDelay}}")` is unchanged. A `#bean:`, `#class:` or `#type:` reference, however, was resolved +when the endpoint was created, so such a reference in the option of a dynamic endpoint is now kept literal as well: +configure that option on the component, or use a static `to(...)` endpoint, if it must be resolved. + === camel-core - Rest DSL binding mode json fails at startup without a JSON data format A Rest DSL service with `bindingMode` `json` or `json_xml` whose JSON data format (`jackson` unless `jsonDataFormat`
