This is an automated email from the ASF dual-hosted git repository. davsclaus pushed a commit to branch CAMEL-27160-4.22.x in repository https://gitbox.apache.org/repos/asf/camel.git
commit a7efdbde0175c20ae2246554bc919f8a732a9463 Author: Claus Ibsen <[email protected]> AuthorDate: Thu Nov 19 11:52:06 2026 +0100 CAMEL-27160: Dynamic endpoint option values computed from the message are bound as literal text (#30389) The option values of an endpoint whose uri is computed from the current message (toD, enrich, wireTap, pollEnrich, recipientList, routingSlip, dynamicRouter) are bound as literal text: a property placeholder, a #class: value or a #property: value is not resolved, and a RAW(...) value is unwrapped without evaluating $simple{...} in it. Registry references (#bean:, #type:, #name) are still resolved. The CamelContext opens a literal binding scope around Component#createEndpoint, so component and endpoint overrides are called as before; PropertyBindingSupport, EndpointHelper.resolveReferenceParameter, PropertyBindingSupport.resolveBean, RawParameterHelper and the SendDynamicAware/PollDynamicAware support classes read the scope. This completes the work of Andrea Cosentino in #30340. Co-authored-by: Andrea Cosentino <[email protected]> Co-Authored-By: Claude Opus 5.5 <[email protected]> (cherry picked from commit 13c0615acc0617104daf9a8c11d3c16f4ba8ca6b, adapted for camel-4.22.x) Signed-off-by: Claus Ibsen <[email protected]> --- .../http/HttpSendDynamicAwareRawSimpleTest.java | 100 ++++++ .../camel/impl/engine/AbstractCamelContext.java | 27 +- .../impl/engine/DefaultCamelContextExtension.java | 18 +- .../org/apache/camel/processor/PollEnricher.java | 27 +- .../apache/camel/processor/ProcessorHelper.java | 16 +- .../camel/processor/SendDynamicProcessor.java | 6 +- ...DynamicEndpointMessageOptionLiteralLogTest.java | 206 +++++++++++ .../DynamicEndpointMessageOptionLiteralTest.java | 386 +++++++++++++++++++++ .../DynamicEndpointMessagePlaceholderTest.java | 28 +- .../DynamicEndpointMessageRawOptionTest.java | 224 ++++++++++++ .../support/component/RawParameterHelperTest.java | 9 + .../org/apache/camel/support/DefaultRegistry.java | 8 +- .../org/apache/camel/support/EndpointHelper.java | 3 + .../org/apache/camel/support/NormalizedUri.java | 44 ++- .../camel/support/PropertyBindingSupport.java | 192 ++++++++-- .../support/component/PollDynamicAwareSupport.java | 10 +- .../support/component/RawParameterHelper.java | 28 +- .../support/component/SendDynamicAwareSupport.java | 10 +- docs/user-manual/modules/ROOT/pages/endpoint.adoc | 5 + 19 files changed, 1274 insertions(+), 73 deletions(-) diff --git a/components/camel-http/src/test/java/org/apache/camel/component/http/HttpSendDynamicAwareRawSimpleTest.java b/components/camel-http/src/test/java/org/apache/camel/component/http/HttpSendDynamicAwareRawSimpleTest.java new file mode 100644 index 000000000000..50a957548b48 --- /dev/null +++ b/components/camel-http/src/test/java/org/apache/camel/component/http/HttpSendDynamicAwareRawSimpleTest.java @@ -0,0 +1,100 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.component.http; + +import java.util.concurrent.atomic.AtomicReference; + +import org.apache.camel.Exchange; +import org.apache.camel.RoutesBuilder; +import org.apache.camel.builder.RouteBuilder; +import org.apache.camel.util.StringHelper; +import org.apache.hc.core5.http.impl.bootstrap.HttpServer; +import org.apache.hc.core5.http.impl.bootstrap.ServerBootstrap; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * A RAW() query value that toD computes from the message is taken as literal text on the optimised http path: a + * $simple{} in it is not evaluated. + */ +public class HttpSendDynamicAwareRawSimpleTest extends BaseHttpTest { + + private static final String PROP = "camel.test.httpRawOption." + System.nanoTime(); + private static final String PROP_VALUE = "prop-value-" + System.nanoTime(); + + private final AtomicReference<String> receivedQuery = new AtomicReference<>(); + private HttpServer localServer; + + @BeforeAll + static void setSystemProperty() { + System.setProperty(PROP, PROP_VALUE); + } + + @AfterAll + static void clearSystemProperty() { + System.clearProperty(PROP); + } + + @Override + public void setupResources() throws Exception { + localServer = ServerBootstrap.bootstrap() + .setCanonicalHostName("localhost") + .setHttpProcessor(getBasicHttpProcessor()) + .setConnectionReuseStrategy(getConnectionReuseStrategy()) + .setResponseFactory(getHttpResponseFactory()) + .setSslContext(getSSLContext()) + .register("/dynamicAware", (request, response, context) -> { + receivedQuery.set(StringHelper.after(request.getRequestUri(), "?")); + response.setCode(200); + }) + .create(); + localServer.start(); + } + + @Override + public void cleanupResources() throws Exception { + if (localServer != null) { + localServer.stop(); + } + } + + @Override + protected RoutesBuilder createRouteBuilder() { + return new RouteBuilder() { + @Override + public void configure() { + from("direct:dynamicAware") + .toD("http://localhost:" + localServer.getLocalPort() + "/dynamicAware?q=${header.q}"); + } + }; + } + + @Test + public void testRawSimpleFromMessageIsLiteral() throws Exception { + Exchange e = fluentTemplate + .to("direct:dynamicAware") + .withHeader("q", "RAW($simple{sys." + PROP + "})") + .send(); + + String expected = "q=%24simple%7Bsys." + PROP + "%7D"; + assertEquals(expected, e.getIn().getHeader(Exchange.HTTP_QUERY)); + assertEquals(expected, receivedQuery.get()); + } +} 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 452d47a5c684..5a5fd1dae789 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 @@ -199,6 +199,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; @@ -788,11 +789,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(); @@ -859,9 +866,21 @@ 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; + 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); + } 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 0be9ea6e0fb7..dfe6f176b64d 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 @@ -269,8 +269,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 @@ -280,14 +282,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 00ea62ba759a..9d42a661ff27 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 @@ -41,6 +41,7 @@ import org.apache.camel.spi.EndpointUtilizationStatistics; import org.apache.camel.spi.ExceptionHandler; import org.apache.camel.spi.HeadersMapFactory; import org.apache.camel.spi.IdAware; +import org.apache.camel.spi.NormalizedEndpointUri; import org.apache.camel.spi.OptimisedComponentResolver; import org.apache.camel.spi.PollDynamicAware; import org.apache.camel.spi.RouteIdAware; @@ -51,6 +52,7 @@ import org.apache.camel.support.DefaultMessage; import org.apache.camel.support.EndpointHelper; import org.apache.camel.support.EventDrivenPollingConsumer; import org.apache.camel.support.ExchangeHelper; +import org.apache.camel.support.NormalizedUri; import org.apache.camel.support.cache.DefaultConsumerCache; import org.apache.camel.support.cache.EmptyConsumerCache; import org.apache.camel.support.service.ServiceHelper; @@ -493,7 +495,30 @@ public class PollEnricher extends BaseProcessorSupport implements IdAware, Route } protected static Object prepareRecipient(Exchange exchange, Object recipient) throws NoTypeConversionAvailableException { - return ProcessorHelper.prepareRecipient(exchange, recipient); + if (recipient instanceof Endpoint || recipient instanceof NormalizedEndpointUri) { + return recipient; + } else if (recipient instanceof String string) { + // trim strings as end users might have added spaces between separators + recipient = string.trim(); + } + if (recipient != null) { + CamelContext ecc = exchange.getContext(); + String uri; + if (recipient instanceof String string) { + uri = string; + } else { + // convert to a string type we can work with + uri = ecc.getTypeConverter().mandatoryConvertTo(String.class, exchange, recipient); + } + // optimize and normalize endpoint without re-resolving property placeholders on the + // per-message evaluated recipient, matching toD and enrich (CAMEL-24282). A property placeholder + // written in the route is resolved when the route is created (the expression text of pollEnrich), + // so a placeholder that is still in the evaluated recipient came from the message. + // 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; } protected static Endpoint getExistingEndpoint(Exchange exchange, Object recipient) { 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..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 @@ -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 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); + } 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 b1e48e7f78c3..b2773c979990 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 @@ -328,8 +328,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 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 new file mode 100644 index 000000000000..1f780998e392 --- /dev/null +++ b/core/camel-core/src/test/java/org/apache/camel/processor/DynamicEndpointMessageOptionLiteralTest.java @@ -0,0 +1,386 @@ +/* + * 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.ResolveEndpointFailedException; +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 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 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 + * {@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 { + + 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"); + 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; + } + + @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 toDOptionBeanReferenceStillResolves() throws Exception { + getMockEndpoint("mock:done").expectedMessageCount(1); + + template.sendBodyAndHeader("direct:tod", "Hello", "target", "sink:c?option=" + MARKER_BEAN); + + assertMockEndpointsSatisfied(); + // a #bean: / #type: reference is a plain registry lookup of an already-registered bean, so it is still + // resolved: this keeps references a route author wrote in a dynamic uri (such as dataSource=#ds) working. + // Only property placeholders, #class: and #property: are kept literal. + assertThat(SinkEndpoint.lastOption).isSameAs(context.getRegistry().lookupByName("marker")); + 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); + + template.sendBodyAndHeader("direct:tod", "Hello", "target", "sink:p?option=#property:secretTarget"); + + assertMockEndpointsSatisfied(); + assertThat(SinkEndpoint.lastOption).isEqualTo("#property:secretTarget"); + } + + @Test + void toDSelfBindingComponentClassReferenceStaysLiteral() throws Exception { + getMockEndpoint("mock:done").expectedMessageCount(1); + + // selfsink binds its options inside its own createEndpoint, like log/aws2-s3/sql/jms and ~329 other + // components; literal binding must be enforced there too (CAMEL-27160), so a #class: option value from the + // message is not instantiated + template.sendBodyAndHeader("direct:tod", "Hello", "target", "selfsink:a?option=" + MARKER_CLASS); + + assertMockEndpointsSatisfied(); + assertThat(SinkEndpoint.lastOption).isEqualTo(MARKER_CLASS); + assertThat(Marker.instances).isZero(); + } + + @Test + void toDSelfBindingComponentPlaceholderStaysLiteral() throws Exception { + getMockEndpoint("mock:done").expectedMessageCount(1); + + template.sendBodyAndHeader("direct:tod", "Hello", "target", "selfsink:b?option={{secretTarget}}"); + + assertMockEndpointsSatisfied(); + assertThat(SinkEndpoint.lastOption).isEqualTo("{{secretTarget}}"); + } + + @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); + } + } + + /** + * Like {@link SinkComponent} but binds its options inside its own {@code createEndpoint} (through the two-argument + * {@code setProperties}), the pattern used by {@code log}, {@code aws2-s3}, {@code sql}, {@code jms} and ~329 other + * components. It proves that literal binding is also enforced for these components (CAMEL-27160). + */ + private static final class SelfBindingSinkComponent extends DefaultComponent { + @Override + protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) + throws Exception { + SinkEndpoint endpoint = new SinkEndpoint(uri, this); + setProperties(endpoint, parameters); + return endpoint; + } + } + + /** + * 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() { + 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 singleton; + } + } + + 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-core/src/test/java/org/apache/camel/processor/DynamicEndpointMessagePlaceholderTest.java b/core/camel-core/src/test/java/org/apache/camel/processor/DynamicEndpointMessagePlaceholderTest.java index 573d6a6afd5a..d28b7ccc4351 100644 --- a/core/camel-core/src/test/java/org/apache/camel/processor/DynamicEndpointMessagePlaceholderTest.java +++ b/core/camel-core/src/test/java/org/apache/camel/processor/DynamicEndpointMessagePlaceholderTest.java @@ -38,9 +38,8 @@ import static org.assertj.core.api.Assertions.assertThat; * {@code recipientList} / {@code routingSlip} / {@code dynamicRouter} compute their recipients entirely from a runtime * expression (no static template resolved at build time), so they continue to resolve {@code {{...}}} in those * recipients - this is relied upon e.g. by routes carrying a {@code {{port}}}-style placeholder in the recipient - * header, and must be preserved. {@code pollEnrich} does resolve its static uri at build time, but its per-message - * recipient goes through the same shared resolution path, so it too still resolves {@code {{...}}} (left unchanged in - * this PR). + * header, and must be preserved. {@code pollEnrich} resolves the placeholders of its expression text at build time, so + * its per-message recipient is not re-resolved either, like {@code toD} and {@code enrich} (CAMEL-27160). */ class DynamicEndpointMessagePlaceholderTest extends ContextTestSupport { @@ -105,15 +104,29 @@ class DynamicEndpointMessagePlaceholderTest extends ContextTestSupport { } @Test - void pollEnrichPlaceholderInHeaderStillResolved() throws Exception { - // pollEnrich's per-message recipient goes through the shared resolution path, so {{...}} is still resolved + void pollEnrichPlaceholderInHeaderNotResolved() throws Exception { template.sendBody("seda:resolved", "SEED"); getMockEndpoint("mock:done").expectedMessageCount(1); template.sendBodyAndHeader("direct:pe", "trigger", "target", "seda:{{secretTarget}}"); assertMockEndpointsSatisfied(); - // resolved -> pollEnrich drained the seed from seda:resolved (not from the literal seda:{{secretTarget}}) + // not resolved -> pollEnrich polled the literal seda:{{secretTarget}} and left the seed untouched + SedaEndpoint seda = context.getEndpoint("seda:resolved", SedaEndpoint.class); + assertThat(seda.getQueue()).hasSize(1); + } + + @Test + void pollEnrichPlaceholderInRouteTextIsResolved() throws Exception { + // control: a placeholder written in the expression text of pollEnrich is resolved when the route is created + template.sendBody("seda:resolved", "SEED"); + template.sendBody("seda:resolved", "SEED2"); + getMockEndpoint("mock:done").expectedBodiesReceived("SEED", "SEED2"); + + template.sendBodyAndHeader("direct:peStaticSimple", "trigger", "suffix", ""); + template.sendBody("direct:peStaticConstant", "trigger"); + + assertMockEndpointsSatisfied(); SedaEndpoint seda = context.getEndpoint("seda:resolved", SedaEndpoint.class); assertThat(seda.getQueue()).isEmpty(); } @@ -147,6 +160,9 @@ class DynamicEndpointMessagePlaceholderTest extends ContextTestSupport { from("direct:rs").routingSlip(header("target")).to("mock:done"); from("direct:dr").dynamicRouter(method(DynamicEndpointMessagePlaceholderTest.this, "route")); from("direct:pe").pollEnrich().simple("${header.target}").timeout(2000).end().to("mock:done"); + from("direct:peStaticSimple").pollEnrich().simple("seda:{{secretTarget}}${header.suffix}").timeout(2000).end() + .to("mock:done"); + from("direct:peStaticConstant").pollEnrich("seda:{{secretTarget}}", 2000).to("mock:done"); from("direct:staticTemplate").toD("mock:{{secretTarget}}"); } }; diff --git a/core/camel-core/src/test/java/org/apache/camel/processor/DynamicEndpointMessageRawOptionTest.java b/core/camel-core/src/test/java/org/apache/camel/processor/DynamicEndpointMessageRawOptionTest.java new file mode 100644 index 000000000000..5f08f68fd75a --- /dev/null +++ b/core/camel-core/src/test/java/org/apache/camel/processor/DynamicEndpointMessageRawOptionTest.java @@ -0,0 +1,224 @@ +/* + * 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.concurrent.atomic.AtomicInteger; + +import org.apache.camel.CamelContext; +import org.apache.camel.ContextTestSupport; +import org.apache.camel.Endpoint; +import org.apache.camel.Exchange; +import org.apache.camel.Processor; +import org.apache.camel.builder.RouteBuilder; +import org.apache.camel.component.log.LogEndpoint; +import org.apache.camel.support.DefaultExchange; +import org.apache.camel.support.component.PollDynamicAwareSupport; +import org.apache.camel.support.component.SendDynamicAwareSupport; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Companion to {@link DynamicEndpointMessageOptionLiteralTest}: a {@code RAW(...)} option value of an endpoint created + * from a uri computed from the current message is unwrapped, but taken as literal text: a {@code $simple{...}} in it is + * not evaluated. An endpoint written in the route (such as {@code to("log:x?marker=RAW($simple{...})")}) still + * evaluates it. + */ +class DynamicEndpointMessageRawOptionTest extends ContextTestSupport { + + private static final String PROP = "camel.test.rawOption." + System.nanoTime(); + private static final String PROP_VALUE = "prop-value-" + System.nanoTime(); + private static final AtomicInteger HITS = new AtomicInteger(); + + @BeforeAll + static void setSystemProperty() { + System.setProperty(PROP, PROP_VALUE); + } + + @AfterAll + static void clearSystemProperty() { + System.clearProperty(PROP); + } + + @BeforeEach + void resetHits() { + HITS.set(0); + } + + @Override + protected CamelContext createCamelContext() throws Exception { + CamelContext context = super.createCamelContext(); + context.getRegistry().bind("probe", new Probe()); + return context; + } + + @Test + void toDRawSystemPropertyFunctionIsLiteral() { + assertToDMarkerIsLiteral("sys", "$simple{sys." + PROP + "}"); + } + + @Test + void toDRawEnvFunctionIsLiteral() { + assertToDMarkerIsLiteral("env", "$simple{env.HOME}"); + } + + @Test + void toDRawBeanFunctionIsLiteral() { + assertToDMarkerIsLiteral("bean", "$simple{bean:probe?method=hit}"); + assertThat(HITS.get()).isZero(); + } + + @Test + void toDRawCamelContextFunctionIsLiteral() { + assertToDMarkerIsLiteral("ctx", "$simple{camelContext.getName()}"); + } + + @Test + void toDRawValueIsStillUnwrapped() { + assertToDMarkerIsLiteral("plain", "a+b&c=d"); + } + + @Test + void toDRawPropertyPlaceholderInRouteIsResolved() { + template.sendBodyAndHeader("direct:todph", "Hello", "id", "ph"); + + assertThat(markerOf("log://todph-ph")).isEqualTo(PROP_VALUE); + } + + @Test + void staticEndpointRawSimpleIsEvaluated() { + template.sendBody("direct:static", "Hello"); + + assertThat(markerOf("log://static")).isEqualTo(PROP_VALUE); + } + + @Test + void sendDynamicAwareRawSimpleIsLiteral() throws Exception { + LenientSendDynamicAware aware = new LenientSendDynamicAware(); + aware.setCamelContext(context); + aware.setScheme("log"); + aware.init(); + Exchange exchange = new DefaultExchange(context); + String uri = "log:aware?marker=RAW($simple{sys." + PROP + "})&custom=RAW($simple{bean:probe?method=hit})"; + + Map<String, Object> known = aware.endpointProperties(exchange, uri); + Map<String, Object> lenient = aware.endpointLenientProperties(exchange, uri); + + assertThat(known).containsEntry("marker", "$simple{sys." + PROP + "}"); + assertThat(lenient).containsEntry("custom", "$simple{bean:probe?method=hit}"); + assertThat(HITS.get()).isZero(); + } + + @Test + void pollDynamicAwareRawSimpleIsLiteral() throws Exception { + LenientPollDynamicAware aware = new LenientPollDynamicAware(); + aware.setCamelContext(context); + aware.setScheme("log"); + aware.init(); + Exchange exchange = new DefaultExchange(context); + String uri = "log:aware?marker=RAW($simple{sys." + PROP + "})&custom=RAW($simple{bean:probe?method=hit})"; + + Map<String, Object> known = aware.endpointProperties(exchange, uri); + Map<String, Object> lenient = aware.endpointLenientProperties(exchange, uri); + + assertThat(known).containsEntry("marker", "$simple{sys." + PROP + "}"); + assertThat(lenient).containsEntry("custom", "$simple{bean:probe?method=hit}"); + assertThat(HITS.get()).isZero(); + } + + private void assertToDMarkerIsLiteral(String id, String value) { + template.sendBodyAndHeaders("direct:tod", "Hello", Map.of("id", id, "m", "RAW(" + value + ")")); + + assertThat(markerOf("log://tod-" + id)).isEqualTo(value); + } + + private String markerOf(String uriPrefix) { + for (Endpoint e : context.getEndpoints()) { + if (e instanceof LogEndpoint le && e.getEndpointUri().startsWith(uriPrefix)) { + return le.getMarker(); + } + } + throw new AssertionError("No log endpoint for " + uriPrefix); + } + + @Override + protected RouteBuilder createRouteBuilder() { + return new RouteBuilder() { + @Override + public void configure() { + from("direct:tod").toD("log:tod-${header.id}?marker=${header.m}"); + from("direct:todph").toD("log:todph-${header.id}?marker=RAW({{sys:" + PROP + "}})"); + from("direct:static").to("log:static?marker=RAW($simple{sys." + PROP + "})"); + } + }; + } + + public static class Probe { + public String hit() { + HITS.incrementAndGet(); + return "probe-called"; + } + } + + private static final class LenientSendDynamicAware extends SendDynamicAwareSupport { + @Override + public boolean isLenientProperties() { + return true; + } + + @Override + public DynamicAwareEntry prepare(Exchange exchange, String uri, String originalUri) { + return null; + } + + @Override + public String resolveStaticUri(Exchange exchange, DynamicAwareEntry entry) { + return null; + } + + @Override + public Processor createPreProcessor(Exchange exchange, DynamicAwareEntry entry) { + return null; + } + + @Override + public Processor createPostProcessor(Exchange exchange, DynamicAwareEntry entry) { + return null; + } + } + + private static final class LenientPollDynamicAware extends PollDynamicAwareSupport { + @Override + public boolean isLenientProperties() { + return true; + } + + @Override + public DynamicAwareEntry prepare(Exchange exchange, String uri, String originalUri) { + return null; + } + + @Override + public String resolveStaticUri(Exchange exchange, DynamicAwareEntry entry) { + return null; + } + } +} diff --git a/core/camel-core/src/test/java/org/apache/camel/support/component/RawParameterHelperTest.java b/core/camel-core/src/test/java/org/apache/camel/support/component/RawParameterHelperTest.java index 6d8cc4c968f5..8e87ee1a9cfd 100644 --- a/core/camel-core/src/test/java/org/apache/camel/support/component/RawParameterHelperTest.java +++ b/core/camel-core/src/test/java/org/apache/camel/support/component/RawParameterHelperTest.java @@ -45,6 +45,15 @@ public class RawParameterHelperTest extends ContextTestSupport { Assertions.assertEquals("abc", map.get("username")); Assertions.assertEquals(context.getName(), map.get("password")); + // literal: the RAW token is removed, but the simple expression is not evaluated + map.put("password", "RAW($simple{camelId})"); + RawParameterHelper.resolveRawParameterValues(context, map, true); + Assertions.assertEquals("$simple{camelId}", map.get("password")); + + map.put("password", "RAW(sec*ret)"); + RawParameterHelper.resolveRawParameterValues(context, map, true); + Assertions.assertEquals("sec*ret", map.get("password")); + String usr = System.getenv("USER"); if (usr != null) { map.put("password", "RAW($simple{env:USER})"); 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 5d6d29d06be3..2635374c25b5 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 883366b8ef8e..8ba348d7aa9c 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 cbd9f543674d..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 @@ -33,9 +33,19 @@ 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 more strictly, to stop message content from being turned into routing + // configuration: a {{...}} property placeholder, a #class: reference or a #property: reference in such a value is + // kept as literal text (no placeholder resolution, no class instantiation, no property lookup), while plain + // registry references (#bean:, #type:) are still resolved. 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 +56,26 @@ 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 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 + */ + 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 +94,18 @@ public final class NormalizedUri extends ValueHolder<String> implements Normaliz return rawUri; } + /** + * 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 + */ + 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 1d7ddf67a898..de1e21ff7b70 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 @@ -111,10 +111,77 @@ public final class PropertyBindingSupport { private PropertyBindingSupport() { } + // 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() { return new Builder(); } + /** + * 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 + */ + public static boolean isLiteralOptionBinding() { + return Boolean.TRUE.equals(LITERAL_OPTION_BINDING.get()); + } + + /** + * 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 + * @since 4.24 + */ + public static boolean setLiteralOptionBinding(boolean literalOptionBinding) { + boolean prev = isLiteralOptionBinding(); + if (literalOptionBinding) { + LITERAL_OPTION_BINDING.set(Boolean.TRUE); + } else { + LITERAL_OPTION_BINDING.remove(); + } + 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/> @@ -243,6 +310,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 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 @@ -253,7 +325,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) { @@ -261,6 +333,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); } @@ -300,7 +376,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); } @@ -313,8 +390,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 @@ -420,7 +497,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( @@ -507,44 +584,61 @@ 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) { - // resolve property placeholders + // 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 && isLiteralOnlyValue(lit); + + // 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 - try { - Object str = resolveValue(camelContext, target, key, text, ignoreCase, fluentBuilder, - allowPrivateSetter, reflection, configurer); - // resolve property placeholders - 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); + if (literalValue) { + // 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); + if (str instanceof String strValue && !literal) { + // 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); } + // 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; + // 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; @@ -556,7 +650,7 @@ public final class PropertyBindingSupport { } 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 { @@ -567,7 +661,7 @@ public final class PropertyBindingSupport { if (!bound && reflection) { // fallback to reflection based bound = setSimplePropertyViaReflection(camelContext, target, key, value, fluentBuilder, allowPrivateSetter, - reflection, ignoreCase); + !literalValue && reflection, ignoreCase); } // if the target value is a map type, then we can skip reflection // and set the entry @@ -1588,6 +1682,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); @@ -1753,6 +1851,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; @@ -1866,6 +1965,23 @@ public final class PropertyBindingSupport { return this; } + /** + * 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 + */ + public Builder withLiteral(boolean literal) { + this.literal = literal; + return this; + } + /** * Whether fluent builder is allowed as a valid getter/setter */ @@ -1970,8 +2086,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); } /** @@ -1989,8 +2105,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); } /** @@ -2008,8 +2124,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/core/camel-support/src/main/java/org/apache/camel/support/component/PollDynamicAwareSupport.java b/core/camel-support/src/main/java/org/apache/camel/support/component/PollDynamicAwareSupport.java index 1e0664b136b9..d3813fa9e759 100644 --- a/core/camel-support/src/main/java/org/apache/camel/support/component/PollDynamicAwareSupport.java +++ b/core/camel-support/src/main/java/org/apache/camel/support/component/PollDynamicAwareSupport.java @@ -84,8 +84,9 @@ public abstract class PollDynamicAwareSupport extends ServiceSupport implements if (resolveRawParameterValues()) { // parameters using raw syntax: RAW(value) // should have the token removed, so its only the value we have in parameters, as we are about to create - // an endpoint and want to have the parameter values without the RAW tokens - RawParameterHelper.resolveRawParameterValues(exchange.getContext(), map); + // an endpoint and want to have the parameter values without the RAW tokens. The uri was computed from + // the current message, so the RAW values are taken as literal text (a $simple{} in them is not evaluated) + RawParameterHelper.resolveRawParameterValues(exchange.getContext(), map, true); } // okay so only add the known properties as they are the non lenient properties properties = new LinkedHashMap<>(); @@ -115,8 +116,9 @@ public abstract class PollDynamicAwareSupport extends ServiceSupport implements if (resolveRawParameterValues()) { // parameters using raw syntax: RAW(value) // should have the token removed, so its only the value we have in parameters, as we are about to create - // an endpoint and want to have the parameter values without the RAW tokens - RawParameterHelper.resolveRawParameterValues(exchange.getContext(), map); + // an endpoint and want to have the parameter values without the RAW tokens. The uri was computed from + // the current message, so the RAW values are taken as literal text (a $simple{} in them is not evaluated) + RawParameterHelper.resolveRawParameterValues(exchange.getContext(), map, true); } properties = new LinkedHashMap<>(); map.forEach((k, v) -> { diff --git a/core/camel-support/src/main/java/org/apache/camel/support/component/RawParameterHelper.java b/core/camel-support/src/main/java/org/apache/camel/support/component/RawParameterHelper.java index 524c81763a94..1ed6280bb9f9 100644 --- a/core/camel-support/src/main/java/org/apache/camel/support/component/RawParameterHelper.java +++ b/core/camel-support/src/main/java/org/apache/camel/support/component/RawParameterHelper.java @@ -21,6 +21,7 @@ import java.util.Map; import org.apache.camel.CamelContext; import org.apache.camel.Exchange; import org.apache.camel.support.ExchangeHelper; +import org.apache.camel.support.PropertyBindingSupport; import org.apache.camel.util.URISupport; public final class RawParameterHelper { @@ -36,12 +37,37 @@ public final class RawParameterHelper { * The value can refer to a simple expression using $simple{xxx} syntax which allows to refer to passwords defined * as ENV variables etc. * + * When the endpoint currently being created on this thread binds its option values as literal text (see + * {@link PropertyBindingSupport#isLiteralOptionBinding()}), the RAW tokens are removed but a $simple{xxx} in the + * value is not evaluated, see {@link #resolveRawParameterValues(CamelContext, Map, boolean)}. + * * @param camelContext the camel context * @param parameters the uri parameters */ public static void resolveRawParameterValues(CamelContext camelContext, Map<String, Object> parameters) { + resolveRawParameterValues(camelContext, parameters, PropertyBindingSupport.isLiteralOptionBinding()); + } + + /** + * Traverses the given parameters, and resolves any parameter values which use the RAW token syntax: + * <code>key=RAW(value)</code>. This method will then remove the RAW tokens, and replace the content of the value, + * with just the value. + * + * When {@code literal} is {@code false} the value can refer to a simple expression using $simple{xxx} syntax which + * allows to refer to passwords defined as ENV variables etc. When {@code literal} is {@code true} the value is + * taken as literal text and a $simple{xxx} in it is not evaluated. This is used for an endpoint whose uri was + * computed from the current message at runtime (for example the per-message recipient of {@code toD} or + * {@code pollEnrich}), as its option values come from the message and not from the route. + * + * @param camelContext the camel context + * @param parameters the uri parameters + * @param literal whether the RAW values are taken as literal text, without evaluating $simple{xxx} + * @since 4.24 + */ + public static void resolveRawParameterValues( + CamelContext camelContext, Map<String, Object> parameters, boolean literal) { URISupport.resolveRawParameterValues(parameters, s -> { - if (s != null && s.contains("$simple{")) { + if (!literal && s != null && s.contains("$simple{")) { Exchange dummy = ExchangeHelper.getDummy(camelContext); s = camelContext.resolveLanguage("simple").createExpression(s).evaluate(dummy, String.class); } diff --git a/core/camel-support/src/main/java/org/apache/camel/support/component/SendDynamicAwareSupport.java b/core/camel-support/src/main/java/org/apache/camel/support/component/SendDynamicAwareSupport.java index 117613441960..0d5ae4cab1d5 100644 --- a/core/camel-support/src/main/java/org/apache/camel/support/component/SendDynamicAwareSupport.java +++ b/core/camel-support/src/main/java/org/apache/camel/support/component/SendDynamicAwareSupport.java @@ -84,8 +84,9 @@ public abstract class SendDynamicAwareSupport extends ServiceSupport implements if (resolveRawParameterValues()) { // parameters using raw syntax: RAW(value) // should have the token removed, so its only the value we have in parameters, as we are about to create - // an endpoint and want to have the parameter values without the RAW tokens - RawParameterHelper.resolveRawParameterValues(exchange.getContext(), map); + // an endpoint and want to have the parameter values without the RAW tokens. The uri was computed from + // the current message, so the RAW values are taken as literal text (a $simple{} in them is not evaluated) + RawParameterHelper.resolveRawParameterValues(exchange.getContext(), map, true); } // okay so only add the known properties as they are the non lenient properties properties = new LinkedHashMap<>(); @@ -115,8 +116,9 @@ public abstract class SendDynamicAwareSupport extends ServiceSupport implements if (resolveRawParameterValues()) { // parameters using raw syntax: RAW(value) // should have the token removed, so its only the value we have in parameters, as we are about to create - // an endpoint and want to have the parameter values without the RAW tokens - RawParameterHelper.resolveRawParameterValues(exchange.getContext(), map); + // an endpoint and want to have the parameter values without the RAW tokens. The uri was computed from + // the current message, so the RAW values are taken as literal text (a $simple{} in them is not evaluated) + RawParameterHelper.resolveRawParameterValues(exchange.getContext(), map, true); } properties = new LinkedHashMap<>(); map.forEach((k, v) -> { diff --git a/docs/user-manual/modules/ROOT/pages/endpoint.adoc b/docs/user-manual/modules/ROOT/pages/endpoint.adoc index a6c82d05910a..2ad0a2c8c3d7 100644 --- a/docs/user-manual/modules/ROOT/pages/endpoint.adoc +++ b/docs/user-manual/modules/ROOT/pages/endpoint.adoc @@ -322,6 +322,11 @@ YAML:: ==== +NOTE: The `+++$simple{xxx}+++` in a `RAW(...)` value is evaluated only for endpoints written in the route. For an +endpoint whose uri is computed from the message at runtime, such as with `toD` or `pollEnrich`, a `RAW(...)` value is +taken as literal text. Use a property placeholder such as `+RAW({{env:MY_FTP_PASSWORD}})+` there, which is resolved +when the route is created. + === Endpoint URIs with property placeholders Camel has extensive support for using xref:using-propertyplaceholder.adoc[].
