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 653501529a6c04e46eebe9f4c3844ebfa3ab558f Author: Claus Ibsen <[email protected]> AuthorDate: Thu Nov 19 10:58:24 2026 +0100 CAMEL-27160: Bind the option values of a dynamic endpoint as literal text in every binding path Builds on the literal option binding of the previous commits: - The CamelContext opens the literal option binding scope around Component#createEndpoint(String, Map), so a component's overrides of createEndpoint and setProperties, and an endpoint's configureProperties, are called as usual. The three-argument createEndpoint and setProperties methods on DefaultComponent and DefaultEndpoint are removed again. - While the scope is active, PropertyBindingSupport binds in literal mode (also when a component calls it directly or through the setProperties(Object, Map) overloads), and PropertyBindingSupport.resolveBean and EndpointHelper.resolveReferenceParameter refuse a placeholder, #class: or #property: value. This covers the generated configurers for options that are not a String, and resolveAndRemoveReferenceParameter. #bean:, #type: and #name are still resolved. - In literal mode the option names are not resolved as placeholders, and DefaultRegistry does not resolve placeholders in a bean name while the scope is active. - Javadoc no longer says that #bean: and #type: are kept literal; the upgrade guide says which options are affected and what to use instead. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Claus Ibsen <[email protected]> --- .../camel/impl/engine/AbstractCamelContext.java | 17 +- .../org/apache/camel/processor/PollEnricher.java | 4 +- .../apache/camel/processor/ProcessorHelper.java | 4 +- .../camel/processor/SendDynamicProcessor.java | 4 +- ...DynamicEndpointMessageOptionLiteralLogTest.java | 206 +++++++++++++++++++++ .../DynamicEndpointMessageOptionLiteralTest.java | 71 ++++++- .../org/apache/camel/support/DefaultComponent.java | 67 +------ .../org/apache/camel/support/DefaultEndpoint.java | 21 --- .../org/apache/camel/support/DefaultRegistry.java | 8 +- .../org/apache/camel/support/EndpointHelper.java | 3 + .../org/apache/camel/support/NormalizedUri.java | 14 +- .../camel/support/PropertyBindingSupport.java | 128 ++++++++----- .../ROOT/pages/camel-4x-upgrade-guide-4_24.adoc | 46 +++-- 13 files changed, 419 insertions(+), 174 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 bd8d8995e994..3b1dd62d7cfc 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,7 +193,6 @@ 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; @@ -202,6 +201,7 @@ import org.apache.camel.support.NormalizedUri; import org.apache.camel.support.OrderedComparator; import org.apache.camel.support.PluginHelper; import org.apache.camel.support.ProcessorEndpoint; +import org.apache.camel.support.PropertyBindingSupport; import org.apache.camel.support.ResetableClock; import org.apache.camel.support.ResolverHelper; import org.apache.camel.support.jsse.SSLContextParameters; @@ -953,10 +953,17 @@ public abstract class AbstractCamelContext extends BaseService // Have the component create the endpoint if it can. 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); + if (literalOptionBinding) { + // the uri was computed from the current message at runtime, so its option values are bound + // as literal text while the component creates the endpoint: no property placeholders, + // #class: or #property: (registry references such as #bean: and #type: are still resolved). + // The scope covers every way a component binds its options (see PropertyBindingSupport) + boolean prev = PropertyBindingSupport.setLiteralOptionBinding(true); + try { + answer = component.createEndpoint(createUri, parameters); + } finally { + PropertyBindingSupport.setLiteralOptionBinding(prev); + } } else { answer = component.createEndpoint(createUri, parameters); } 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 f2184208c3ca..4ccf9034e33b 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,8 +539,8 @@ 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. - // 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 + // The per-message recipient comes from the message, so its option values are bound as literal text + // as well: no property placeholders, #class: or #property: (#bean: and #type: still resolve) - 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 3b8481369eee..5c00fceca0cf 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 @@ -88,8 +88,8 @@ final class ProcessorHelper { } // 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). + // message, so its option values are bound as literal text: no #class: or #property: resolution on the + // option values; registry references (#bean:, #type:) are still resolved (CAMEL-27160). try { String resolved = EndpointHelper.resolveEndpointUriPropertyPlaceholders(ecc, uri); return NormalizedUri.newNormalizedUri(resolved, false, true); 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 7a2f445372e1..aa6f05387698 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 @@ -334,8 +334,8 @@ public class SendDynamicProcessor extends BaseProcessorSupport } // optimize and normalize endpoint without re-resolving property placeholders on the // 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 + // comes from the message, so its option values are bound as literal text as well: no property + // placeholders, #class: or #property: (#bean: and #type: still resolve) - CAMEL-27160 return NormalizedUri.newNormalizedUri(uri, false, true); } return null; diff --git a/core/camel-core/src/test/java/org/apache/camel/processor/DynamicEndpointMessageOptionLiteralLogTest.java b/core/camel-core/src/test/java/org/apache/camel/processor/DynamicEndpointMessageOptionLiteralLogTest.java new file mode 100644 index 000000000000..4a4eb02b3a97 --- /dev/null +++ b/core/camel-core/src/test/java/org/apache/camel/processor/DynamicEndpointMessageOptionLiteralLogTest.java @@ -0,0 +1,206 @@ +/* + * 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.Properties; + +import org.apache.camel.CamelContext; +import org.apache.camel.ContextTestSupport; +import org.apache.camel.Exchange; +import org.apache.camel.ResolveEndpointFailedException; +import org.apache.camel.builder.RouteBuilder; +import org.apache.camel.component.log.LogEndpoint; +import org.apache.camel.component.stub.StubEndpoint; +import org.apache.camel.spi.ExchangeFormatter; +import org.apache.camel.support.processor.DefaultExchangeFormatter; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * The option values of an endpoint whose uri is computed from the message are bound as literal text, also for a real + * component that binds its options inside its own {@code createEndpoint}, with a generated configurer and typed options + * ({@code log}). A {@code #class:} value is not created for a typed option (through the configurer and through + * {@code resolveAndRemoveReferenceParameter}), a property placeholder stays literal (also for a bean that the component + * configures with {@code setProperties(Object, Map)}), while {@code #bean:} and {@code #type:} in the static text of + * the {@code toD} still resolve, and {@code #class:} in a static {@code to} still works. + */ +class DynamicEndpointMessageOptionLiteralLogTest extends ContextTestSupport { + + @Override + protected CamelContext createCamelContext() throws Exception { + CamelContext context = super.createCamelContext(); + Properties prop = new Properties(); + prop.setProperty("secretTarget", "resolved"); + context.getPropertiesComponent().setInitialProperties(prop); + context.getRegistry().bind("myFormatter", new RegisteredFormatter()); + // the log component configures this bean with the options of every log endpoint + context.getRegistry().bind("logFormatter", new PrefixFormatter()); + return context; + } + + @BeforeEach + void resetCounter() { + CountingFormatter.instances = 0; + } + + @Test + void classValueFromMessageIsNotCreatedForTypedOption() { + Exchange out = template.send("direct:tod", e -> e.getMessage().setHeader("target", + "log:m1?exchangeFormatter=#class:" + CountingFormatter.class.getName())); + + assertThat(out.getException()).isInstanceOf(ResolveEndpointFailedException.class); + assertThat(CountingFormatter.instances).isZero(); + } + + @Test + void classValueFromMessageIsNotCreatedForReferenceParameter() { + // the log component resolves the logger option with resolveAndRemoveReferenceParameter + Exchange out = template.send("direct:tod", e -> e.getMessage().setHeader("target", + "log:m2?logger=#class:" + CountingFormatter.class.getName())); + + assertThat(out.getException()).isInstanceOf(ResolveEndpointFailedException.class); + assertThat(CountingFormatter.instances).isZero(); + } + + @Test + void placeholderFromMessageStaysLiteral() { + template.sendBodyAndHeader("direct:marker", "Hello", "m", "{{secretTarget}}"); + + assertThat(logEndpoint("m3").getMarker()).isEqualTo("{{secretTarget}}"); + } + + @Test + void classValueFromMessageStaysLiteralForStringOption() { + String value = "#class:" + CountingFormatter.class.getName(); + template.sendBodyAndHeader("direct:marker", "Hello", "m", value); + + assertThat(logEndpoint("m3").getMarker()).isEqualTo(value); + assertThat(CountingFormatter.instances).isZero(); + } + + @Test + void placeholderFromMessageStaysLiteralForComponentConfiguredBean() { + // the log component binds the options to the logFormatter bean with setProperties(Object, Map) + template.sendBodyAndHeader("direct:prefix", "Hello", "p", "{{secretTarget}}"); + + PrefixFormatter formatter = context.getRegistry().lookupByNameAndType("logFormatter", PrefixFormatter.class); + assertThat(formatter.getPrefix()).isEqualTo("{{secretTarget}}"); + } + + @Test + void beanReferenceInStaticTextStillResolves() { + template.sendBodyAndHeader("direct:bean", "Hello", "m", "audit"); + + LogEndpoint endpoint = logEndpoint("b1"); + assertThat(endpoint.getExchangeFormatter()).isSameAs(context.getRegistry().lookupByName("myFormatter")); + assertThat(endpoint.getMarker()).isEqualTo("audit"); + } + + @Test + void typeReferenceInStaticTextStillResolves() { + template.sendBodyAndHeader("direct:type", "Hello", "m", "audit"); + + LogEndpoint endpoint = logEndpoint("t1"); + assertThat(endpoint.getExchangeFormatter()).isSameAs(context.getRegistry().lookupByName("myFormatter")); + } + + @Test + void classValueInStaticToStillCreated() { + LogEndpoint endpoint = context.getEndpoint("log:s1?exchangeFormatter=#class:" + StaticFormatter.class.getName(), + LogEndpoint.class); + + assertThat(endpoint.getExchangeFormatter()).isInstanceOf(StaticFormatter.class); + } + + @Test + void componentSetPropertiesOverrideIsUsed() { + // the stub component turns off the binding of the options in its setProperties(Endpoint, Map) override + template.sendBodyAndHeader("direct:tod", "Hello", "target", "stub:s2?timeout=1234"); + + StubEndpoint endpoint = context.getEndpoints().stream() + .filter(StubEndpoint.class::isInstance).map(StubEndpoint.class::cast) + .filter(e -> e.getEndpointUri().contains("s2")).findFirst().orElseThrow(); + assertThat(endpoint.getTimeout()).isEqualTo(30000L); + } + + private LogEndpoint logEndpoint(String name) { + return context.getEndpoints().stream() + .filter(LogEndpoint.class::isInstance).map(LogEndpoint.class::cast) + .filter(e -> e.getEndpointUri().startsWith("log://" + name + "?")) + .findFirst().orElseThrow(); + } + + @Override + protected RouteBuilder createRouteBuilder() { + return new RouteBuilder() { + @Override + public void configure() { + from("direct:tod").toD("${header.target}"); + from("direct:marker").toD("log:m3?marker=${header.m}"); + from("direct:prefix").toD("log:f1?prefix=${header.p}"); + from("direct:bean").toD("log:b1?exchangeFormatter=#bean:myFormatter&marker=${header.m}"); + from("direct:type").toD("log:t1?exchangeFormatter=#type:" + RegisteredFormatter.class.getName() + + "&marker=${header.m}"); + from("direct:static").to("log:s1?exchangeFormatter=#class:" + StaticFormatter.class.getName()); + } + }; + } + + /** + * Counts its instances, so a {@code #class:} value that is created can be detected. + */ + public static class CountingFormatter implements ExchangeFormatter { + static volatile int instances; + + public CountingFormatter() { + instances++; + } + + @Override + public String format(Exchange exchange) { + return "counting"; + } + } + + public static class StaticFormatter implements ExchangeFormatter { + @Override + public String format(Exchange exchange) { + return "static"; + } + } + + public static class RegisteredFormatter implements ExchangeFormatter { + @Override + public String format(Exchange exchange) { + return "registered"; + } + } + + public static class PrefixFormatter extends DefaultExchangeFormatter { + private String prefix; + + public String getPrefix() { + return prefix; + } + + public void setPrefix(String prefix) { + this.prefix = prefix; + } + } +} 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 index 93a87f920d90..2cc63837bac3 100644 --- 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 @@ -28,6 +28,7 @@ import org.apache.camel.Header; import org.apache.camel.PollingConsumer; import org.apache.camel.Processor; import org.apache.camel.Producer; +import org.apache.camel.ResolveEndpointFailedException; import org.apache.camel.builder.AggregationStrategies; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.support.DefaultComponent; @@ -41,15 +42,18 @@ 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. + * computed from the message, so its option values are bound as literal text. A property placeholder ({@code {{...}}}), + * a {@code #class:} value or a {@code #property:} value in a runtime-computed option value is kept verbatim: it is not + * resolved and no class is created. Registry references ({@code #bean:}, {@code #type:}) are still resolved. 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. + * {@code #class:} and {@code #property:} resolution of their runtime option values is brought in line, which is why + * those EIPs are exercised here with {@code #class:} values rather than placeholders. + * <p/> + * {@link DynamicEndpointMessageOptionLiteralLogTest} covers a real component with a generated configurer and typed + * options. */ class DynamicEndpointMessageOptionLiteralTest extends ContextTestSupport { @@ -61,9 +65,11 @@ class DynamicEndpointMessageOptionLiteralTest extends ContextTestSupport { CamelContext context = super.createCamelContext(); Properties prop = new Properties(); prop.setProperty("secretTarget", "resolved"); + prop.setProperty("optionName", "option"); context.getPropertiesComponent().setInitialProperties(prop); context.addComponent("sink", new SinkComponent()); context.addComponent("selfsink", new SelfBindingSinkComponent()); + context.addComponent("singletonsink", new SingletonSinkComponent()); context.getRegistry().bind("marker", new Marker()); return context; } @@ -109,6 +115,41 @@ class DynamicEndpointMessageOptionLiteralTest extends ContextTestSupport { assertThat(Marker.instances).isZero(); } + @Test + void toDOptionTypeReferenceStillResolves() throws Exception { + getMockEndpoint("mock:done").expectedMessageCount(1); + + template.sendBodyAndHeader("direct:tod", "Hello", "target", "sink:t?option=#type:" + Marker.class.getName()); + + assertMockEndpointsSatisfied(); + assertThat(SinkEndpoint.lastOption).isSameAs(context.getRegistry().lookupByName("marker")); + assertThat(Marker.instances).isZero(); + } + + @Test + void toDOptionNamePlaceholderIsNotResolved() { + // the option names of the uri were resolved when the route was built, a name computed from the message is not + Exchange out = template.send("direct:tod", + e -> e.getMessage().setHeader("target", "sink:n?{{optionName}}=hello")); + + assertThat(out.getException()).isInstanceOf(ResolveEndpointFailedException.class); + assertThat(SinkEndpoint.lastOption).isNull(); + } + + @Test + void toDSingletonEndpointClassReferenceStaysLiteral() throws Exception { + getMockEndpoint("mock:done").expectedMessageCount(2); + + // a singleton endpoint is created once and then taken from the endpoint registry + template.sendBodyAndHeader("direct:tod", "Hello", "target", "singletonsink:a?option=" + MARKER_CLASS); + template.sendBodyAndHeader("direct:tod", "Hello", "target", "singletonsink:a?option=" + MARKER_CLASS); + + assertMockEndpointsSatisfied(); + assertThat(SinkEndpoint.lastOption).isEqualTo(MARKER_CLASS); + assertThat(Marker.instances).isZero(); + assertThat(context.getEndpoints().stream().filter(e -> e.getEndpointUri().startsWith("singletonsink:"))).hasSize(1); + } + @Test void toDOptionPropertyReferenceStaysLiteral() throws Exception { getMockEndpoint("mock:done").expectedMessageCount(1); @@ -253,12 +294,28 @@ class DynamicEndpointMessageOptionLiteralTest extends ContextTestSupport { } } + /** + * Like {@link SinkComponent} but its endpoints are singletons, so they are kept in the endpoint registry. + */ + private static final class SingletonSinkComponent extends DefaultComponent { + @Override + protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) { + return new SinkEndpoint(uri, this, true); + } + } + private static final class SinkEndpoint extends DefaultEndpoint { static volatile Object lastOption; + private final boolean singleton; private Object option; SinkEndpoint(String uri, DefaultComponent component) { + this(uri, component, false); + } + + SinkEndpoint(String uri, DefaultComponent component, boolean singleton) { super(uri, component); + this.singleton = singleton; } public Object getOption() { @@ -292,7 +349,7 @@ class DynamicEndpointMessageOptionLiteralTest extends ContextTestSupport { @Override public boolean isSingleton() { - return false; + return singleton; } } 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 d6aa74a8bfd7..c3f5fd0eabfd 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,44 +88,6 @@ 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 { - if (!literalOptionBinding) { - return doCreateEndpoint(uri, properties, false); - } - // mark the whole endpoint creation as literal so that components that bind their options inside their own - // createEndpoint (through the two-argument setProperties) also bind the message-derived values literally - boolean prev = PropertyBindingSupport.setLiteralOptionBinding(true); - try { - return doCreateEndpoint(uri, properties, true); - } finally { - PropertyBindingSupport.setLiteralOptionBinding(prev); - } - } - - private Endpoint doCreateEndpoint(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); @@ -215,7 +177,7 @@ public abstract class DefaultComponent extends ServiceSupport implements Compone } // configure remainder of the parameters - setProperties(endpoint, parameters, literalOptionBinding); + setProperties(endpoint, parameters); // 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 @@ -442,33 +404,6 @@ 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 { - if (literalOptionBinding && LOG.isWarnEnabled()) { - // literal binding of message-derived option values is enforced through DefaultEndpoint; a custom - // endpoint that does not extend it falls back to the standard resolution path, which may resolve - // property placeholders or #class: / #property: references against the message-derived values - LOG.warn("Endpoint {} does not extend DefaultEndpoint; option values computed from the message cannot" - + " be bound as literal text and will use the standard property resolution", - endpoint.getEndpointUri()); - } - 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 4f1c0a795edf..904f0a40dd94 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,25 +403,6 @@ public abstract class DefaultEndpoint extends ServiceSupport implements Endpoint * @param parameters properties to set */ public void setProperties(Object bean, Map<String, Object> parameters) { - // honor a literal-option-binding scope opened while a dynamic endpoint is being created, so that options - // bound by a component inside its own createEndpoint are also kept literal (see - // PropertyBindingSupport#isLiteralOptionBinding and DefaultComponent#createEndpoint(String, Map, boolean)) - setProperties(bean, parameters, PropertyBindingSupport.isLiteralOptionBinding()); - } - - /** - * 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; } @@ -439,8 +420,6 @@ 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/DefaultRegistry.java b/core/camel-support/src/main/java/org/apache/camel/support/DefaultRegistry.java index cdcec4248bf2..12ec13efc4e5 100644 --- a/core/camel-support/src/main/java/org/apache/camel/support/DefaultRegistry.java +++ b/core/camel-support/src/main/java/org/apache/camel/support/DefaultRegistry.java @@ -276,7 +276,9 @@ public class DefaultRegistry extends ServiceSupport implements Registry, LocalBe try { // Must avoid attempting placeholder resolution when looking up // the properties component or else we end up in an infinite loop. - if (camelContext != null && !name.equals("properties")) { + // A name is not resolved either while an endpoint whose uri is computed from the message is created, + // as the name may come from an option value of that uri. + if (camelContext != null && !name.equals("properties") && !PropertyBindingSupport.isLiteralOptionBinding()) { name = camelContext.resolvePropertyPlaceholders(name); } } catch (Exception e) { @@ -317,7 +319,9 @@ public class DefaultRegistry extends ServiceSupport implements Registry, LocalBe try { // Must avoid attempting placeholder resolution when looking up // the properties component or else we end up in an infinite loop. - if (camelContext != null && !name.equals("properties")) { + // A name is not resolved either while an endpoint whose uri is computed from the message is created, + // as the name may come from an option value of that uri. + if (camelContext != null && !name.equals("properties") && !PropertyBindingSupport.isLiteralOptionBinding()) { name = camelContext.resolvePropertyPlaceholders(name); } } catch (Exception e) { diff --git a/core/camel-support/src/main/java/org/apache/camel/support/EndpointHelper.java b/core/camel-support/src/main/java/org/apache/camel/support/EndpointHelper.java index 756a54311fad..5a8bfa95f3bb 100644 --- a/core/camel-support/src/main/java/org/apache/camel/support/EndpointHelper.java +++ b/core/camel-support/src/main/java/org/apache/camel/support/EndpointHelper.java @@ -361,6 +361,9 @@ public final class EndpointHelper { * @throws NoSuchBeanException if object was not found in registry and <code>mandatory</code> is <code>true</code>. */ public static <T> T resolveReferenceParameter(CamelContext context, String value, Class<T> type, boolean mandatory) { + // while an endpoint whose uri is computed from the current message is created, its option values are bound as + // literal text: a placeholder, #class: or #property: value is not resolved (#bean: and #type: still are) + PropertyBindingSupport.checkLiteralOptionReference(value); Object answer; if (value.startsWith("#class:")) { try { 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 522fd6f5e972..7d63890ac294 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 @@ -64,9 +64,10 @@ public final class NormalizedUri extends ValueHolder<String> implements Normaliz * * @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) + * @param literalOptionBinding whether the uri was computed from the current message, so its option values are + * bound as literal text: no property placeholders, {@code #class:} or + * {@code #property:}; registry references ({@code #bean:}, {@code #type:}) are still + * resolved * @return the created normalized uri * @since 4.24 */ @@ -94,9 +95,10 @@ public final class NormalizedUri extends ValueHolder<String> implements Normaliz } /** - * 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. + * Whether this uri was computed from the current message at runtime, so the option values of the endpoint created + * from it are bound as literal text: a property placeholder ({@code {{...}}}), a {@code #class:} value or a + * {@code #property:} value is not resolved. Registry references ({@code #bean:}, {@code #type:}) are still + * resolved. * * @since 4.24 */ 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 2f281ac445d0..02ad5ba2b5fa 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 @@ -118,12 +118,13 @@ public final class PropertyBindingSupport { private PropertyBindingSupport() { } - // a thread-scoped signal that the endpoint currently being created was computed from the current message at - // runtime (a dynamic endpoint such as toD/enrich/wireTap/pollEnrich/recipientList/routingSlip/dynamicRouter), - // so its option values must be bound as literal text. It is set (in a try/finally) around the whole endpoint - // creation by DefaultComponent.createEndpoint(uri, properties, true) and read by DefaultComponent and - // DefaultEndpoint when they bind the options, so components that bind inside their own createEndpoint still honor - // literal binding. + // a thread-scoped signal that the endpoint currently being created has a uri computed from the current message at + // runtime (a dynamic endpoint such as toD/enrich/wireTap/pollEnrich/recipientList/routingSlip/dynamicRouter), so + // its option values are bound as literal text. The CamelContext sets it (in a try/finally) around + // Component#createEndpoint(String, Map) only. While it is set, the Builder binds in literal mode, and resolveBean + // and EndpointHelper#resolveReferenceParameter refuse the values that are kept literal, so every way a component + // binds its options is covered (generated configurers, setProperties overloads, resolveAndRemoveReferenceParameter + // and direct use of this class). private static final ThreadLocal<Boolean> LITERAL_OPTION_BINDING = new ThreadLocal<>(); public static Builder build() { @@ -131,8 +132,8 @@ public final class PropertyBindingSupport { } /** - * Whether the endpoint currently being created on this thread must bind its query option values as literal text, - * because its uri was computed from the current message at runtime, see {@link Builder#withLiteral(boolean)}. + * Whether the endpoint currently being created on this thread binds its option values as literal text, because its + * uri was computed from the current message at runtime, see {@link Builder#withLiteral(boolean)}. * * @return true if literal option binding is active on the current thread * @since 4.24 @@ -142,9 +143,10 @@ public final class PropertyBindingSupport { } /** - * Marks (or clears) the current thread as creating an endpoint whose query option values must be bound as literal - * text. The caller MUST restore the returned previous value in a {@code finally} block, as - * {@link DefaultComponent#createEndpoint(String, java.util.Map, boolean)} does. + * Marks (or clears) the current thread as creating an endpoint whose option values are bound as literal text. The + * caller MUST restore the returned previous value in a {@code finally} block. The CamelContext does this around + * {@link org.apache.camel.Component#createEndpoint(String, Map)} when the uri was computed from the current + * message. * * @param literalOptionBinding whether literal option binding is active * @return the previous value, to be restored by the caller @@ -160,6 +162,33 @@ public final class PropertyBindingSupport { return prev; } + /** + * Whether the value is kept as literal text when bound in literal mode: a value with a property placeholder + * ({@code {{...}}}), a {@code #class:} value or a {@code #property:} value. Plain registry references such as + * {@code #bean:}, {@code #type:} and {@code #name} are not. + */ + static boolean isLiteralOnlyValue(String value) { + if (value == null) { + return false; + } + String s = value.trim(); + return s.contains(PropertiesComponent.PREFIX_TOKEN) || s.startsWith("#class:") || s.startsWith("#property:"); + } + + /** + * Fails when literal option binding is active and the value is one that is only bound as literal text, so it is not + * resolved as a property placeholder, created as a class, or looked up as a property. + */ + static void checkLiteralOptionReference(String value) { + if (isLiteralOnlyValue(value) && isLiteralOptionBinding()) { + throw new IllegalArgumentException( + "The option value is bound as literal text because the endpoint uri is computed from the message" + + " (such as with toD, enrich, pollEnrich or recipientList): property" + + " placeholders, #class: and #property: are not resolved there." + + " Register the bean and refer to it with #bean:name instead"); + } + } + /** * Binds the properties to the target object, and removes the property that was bound from properties. * <p> @@ -290,11 +319,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 literal whether to bind in literal mode: a value with a property placeholder, a #class: value + * or a #property: value is bound as literal text, and option names are not resolved as + * property placeholders. Plain registry references (#bean:, #type:, #name) are still + * resolved. Literal mode is also on while a literal option binding scope is active, see + * {@link #isLiteralOptionBinding()}. * @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 @@ -313,6 +342,10 @@ public final class PropertyBindingSupport { return false; } + // an endpoint whose uri is computed from the current message binds its options in literal mode, however the + // component binds them + literal = literal || isLiteralOptionBinding(); + if (flattenProperties) { properties = new FlattenMap(properties); } @@ -566,38 +599,35 @@ public final class PropertyBindingSupport { String key = name; Object text = value; - // a value computed from the current message at runtime (literal mode) is kept verbatim only when resolving it - // would be unsafe: a {{...}} property placeholder (which reads env vars, system or application properties or - // vault secrets), a #class: reference (which instantiates a class and can invoke a public static or factory - // method), or a #property: lookup. Benign registry references (#bean:, #type:, ...) are still resolved, so a + // in literal mode (the endpoint uri was computed from the current message at runtime) a value with a {{...}} + // property placeholder, a #class: value (which creates a class and can call a factory method) or a #property: + // value is bound as literal text. Plain registry references (#bean:, #type:, #name) are still resolved, so a // reference a route author wrote in the dynamic uri, such as dataSource=#ds, keeps working. - boolean literalValue = literal && text instanceof String lit - && (lit.contains(PropertiesComponent.PREFIX_TOKEN) - || lit.startsWith("#class:") || lit.startsWith("#property:")); + boolean literalValue = literal && text instanceof String lit && isLiteralOnlyValue(lit); - if (placeholder && !literalValue) { - // resolve property placeholders + // the option names of the uri were already resolved when the route was built, so in literal mode they are not + // resolved again + if (placeholder && !literal) { key = camelContext.resolvePropertyPlaceholders(key); - if (text instanceof String s) { - // resolve property placeholders - text = camelContext.resolvePropertyPlaceholders(s); - if (text == null && s.startsWith(PropertiesComponent.PREFIX_TOKEN + "?")) { - // it was an optional value, so we should not try to set the property but regard it as a "hit" - return true; - } + } + if (placeholder && !literalValue && text instanceof String s) { + // resolve property placeholders + text = camelContext.resolvePropertyPlaceholders(s); + if (text == null && s.startsWith(PropertiesComponent.PREFIX_TOKEN + "?")) { + // it was an optional value, so we should not try to set the property but regard it as a "hit" + return true; } } // prepare the value before it is bound if (literalValue) { - // the message-derived value is kept verbatim: no property-placeholder, #class: or #property: resolution + // keep the value as literal text: no property-placeholder, #class: or #property: resolution value = text; } else { try { Object str = resolveValue(camelContext, target, key, text, ignoreCase, fluentBuilder, allowPrivateSetter, reflection, configurer); - // resolve property placeholders - if (str instanceof String strValue) { + if (str instanceof String strValue && !literal) { // resolve property placeholders str = camelContext.resolvePropertyPlaceholders(strValue); } @@ -612,11 +642,11 @@ public final class PropertyBindingSupport { } } - // when the value was kept literal, 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 + // a value kept as literal text is not resolved as a reference by reflection. A configurer resolves a + // reference (#...) on its own for an option that is not a String: there EndpointHelper.resolveReferenceParameter + // refuses a #class: or #property: value while the literal option binding scope is active, and an option of + // type String gets the literal text boolean effReference = reference && !literalValue; - boolean skipConfigurer = literalValue && 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 @@ -624,7 +654,7 @@ public final class PropertyBindingSupport { try { if (isCollectionKey(name)) { // collection key (list,map,array) - if (configurer != null && !skipConfigurer) { + if (configurer != null) { bound = setPropertyCollectionViaConfigurer(camelContext, target, key, value, ignoreCase, configurer); } if (!bound && reflection) { @@ -634,7 +664,7 @@ public final class PropertyBindingSupport { } } else { // regular key - if (configurer != null && !skipConfigurer) { + if (configurer != null) { bound = setSimplePropertyViaConfigurer(camelContext, target, key, value, ignoreCase, configurer); } if (!bound && reflection) { @@ -2027,6 +2057,10 @@ public final class PropertyBindingSupport { Object answer = value; + // while an endpoint whose uri is computed from the current message is created, a placeholder, #class: or + // #property: value is not resolved + checkLiteralOptionReference(strval); + // resolve placeholders strval = camelContext.resolvePropertyPlaceholders(strval); @@ -2318,10 +2352,14 @@ public final class PropertyBindingSupport { } /** - * 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. + * Whether to bind in literal mode, for values computed from message content at runtime (for example the option + * values of a dynamic endpoint). In literal mode a value with a property placeholder ({@code {{...}}}), a + * {@code #class:} value or a {@code #property:} value is bound as literal text, and option names are not + * resolved as property placeholders. Plain registry references ({@code #bean:}, {@code #type:}, {@code #name}) + * are still resolved. + * <p> + * Literal mode is also on, whatever this option says, while a literal option binding scope is active on the + * current thread, see {@link PropertyBindingSupport#isLiteralOptionBinding()}. * * @since 4.24 */ 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 7b1c4c3ef518..29b551c2c8dd 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,24 +133,38 @@ 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 +=== camel-core - option values of a dynamic endpoint 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 more strictly: a property-placeholder token (`+{{...}}+`), a `#class:` reference -(which would instantiate a class and can invoke a public static or factory method) or a `#property:` reference that -appears in a runtime-computed option value is kept verbatim, so it is neither resolved as a property nor used to -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 this subset of -their option values changes. - -Plain registry references (`#bean:`, `#type:`) are still resolved, so a reference a route author wrote in a dynamic -uri, such as `+toD("sql:${header.query}?dataSource=#ds")+`, keeps working. Property placeholders written in the static -route template are also still resolved once when the route starts, so `+toD("mock:foo?delay={{myDelay}}")+` is -unchanged. Only a value that is itself computed from the message and is a `+{{...}}+` placeholder, a `#class:` -reference or a `#property:` reference is kept literal; configure such an option on the component, or use a static -`to(...)` endpoint, if it must be resolved. +`dynamicRouter` -- compute their target endpoint from the current message at runtime. The option values of that +endpoint are now bound as literal text: a property placeholder (`+{{...}}+`), a `#class:` value or a `#property:` value +is not resolved. This extends to the options the treatment that `toD`, `enrich`, `wireTap` and `pollEnrich` already gave +the endpoint path. It applies however the component binds its options, including components that bind them in their +own `createEndpoint` or look up a reference option with `resolveAndRemoveReferenceParameter`. + +This applies to every option of that uri, not only to the parts that come from the message: a `#class:` or +`#property:` value written in the text of a `toD`, or in a uri that a bean of the route builds for `recipientList`, +`routingSlip` or `dynamicRouter`, is not resolved either. For an option of type `String` the text is bound as is. For +an option of another type, a `#class:` value fails the creation of the endpoint with a `ResolveEndpointFailedException`. +Register the bean instead and refer to it with `#bean:`, for example: + +[source,java] +---- +// before: the class was created for every new endpoint +toD("log:audit?exchangeFormatter=#class:com.foo.MyFormatter&marker=${header.customer}") + +// after: create the bean once (e.g. camel.beans.myFormatter = #class:com.foo.MyFormatter) and refer to it +toD("log:audit?exchangeFormatter=#bean:myFormatter&marker=${header.customer}") +---- + +What still works as before: + +* Registry references (`#bean:name`, `#type:`, `#name`) are still resolved, so `+toD("sql:${header.query}?dataSource=#ds")+` keeps working. +* Property placeholders written in the text of a `toD` are resolved once when the route is built, so + `+toD("mock:foo?delay={{myDelay}}")+` is unchanged. `recipientList`, `routingSlip` and `dynamicRouter` still resolve + property placeholders in the computed uri string. +* An endpoint in a static `to(...)`, or configured on the component, binds `#class:`, `#property:` and placeholders as + before. === camel-core - Rest DSL binding mode json fails at startup without a JSON data format
