This is an automated email from the ASF dual-hosted git repository.
davsclaus pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git
The following commit(s) were added to refs/heads/main by this push:
new 637bd2908b3a CAMEL-28071: Preserve stream headers when storing a
receive variable (#31297)
637bd2908b3a is described below
commit 637bd2908b3acdc25ae116ac9bb31fddd921d58d
Author: Claudio Miranda <[email protected]>
AuthorDate: Thu Dec 3 13:25:57 2026 +0000
CAMEL-28071: Preserve stream headers when storing a receive variable
(#31297)
* CAMEL-28071: Preserve stream headers when storing a receive variable
Keep live input streams and readers readable when a variable repository
requests a stream cache without an owning exchange.
Restore the original body and headers when a receive-variable write
fails in a send or enricher. Propagate the failure through the EIP's
error path so the enricher completes the resource as failed.
Co-authored-by: OpenAI Codex <[email protected]>
AI-assisted-by: OpenAI Codex on behalf of Claudio4j
---
.../java/org/apache/camel/processor/Enricher.java | 9 ++---
.../org/apache/camel/processor/PollEnricher.java | 9 ++---
.../apache/camel/processor/ProcessorHelper.java | 33 +++++++++++++++++
.../camel/processor/SendDynamicProcessor.java | 7 +---
.../org/apache/camel/processor/SendProcessor.java | 25 ++++++-------
.../processor/ToVariableReceiveHeadersTest.java | 37 +++++++++++++++++++
.../camel/processor/ToVariableReceiveTest.java | 28 +++++++++++++++
.../enricher/EnricherResourceCompletionTest.java | 41 ++++++++++++++++++++++
.../converter/stream/StreamCacheConverter.java | 7 ++++
9 files changed, 162 insertions(+), 34 deletions(-)
diff --git
a/core/camel-core-processor/src/main/java/org/apache/camel/processor/Enricher.java
b/core/camel-core-processor/src/main/java/org/apache/camel/processor/Enricher.java
index 0e95486ab992..519db459ffc5 100644
---
a/core/camel-core-processor/src/main/java/org/apache/camel/processor/Enricher.java
+++
b/core/camel-core-processor/src/main/java/org/apache/camel/processor/Enricher.java
@@ -243,13 +243,8 @@ public class Enricher extends BaseProcessorSupport
Exchange aggregatedExchange =
aggregationStrategy.aggregate(exchange, resourceExchange);
if (aggregatedExchange != null) {
- if
(ExchangeHelper.shouldSetVariableResult(aggregatedExchange, variableReceive)) {
- // result should be stored in variable instead
of message body
-
ExchangeHelper.setVariableFromMessageBodyAndHeaders(aggregatedExchange,
variableReceive,
- aggregatedExchange.getMessage());
-
aggregatedExchange.getMessage().setBody(originalBody);
-
aggregatedExchange.getMessage().setHeaders(originalHeaders);
- }
+ ProcessorHelper.storeVariableResult(exchange,
aggregatedExchange, variableReceive, originalBody,
+ originalHeaders);
// copy aggregation result onto original exchange
(preserving pattern)
copyResultsWithoutCorrelationId(exchange,
aggregatedExchange);
}
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 d12cf3260ae5..bf908e863abc 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
@@ -433,13 +433,8 @@ public class PollEnricher extends BaseProcessorSupport
implements IdAware, Route
// must catch any exception from aggregation
Exchange aggregatedExchange =
aggregationStrategy.aggregate(exchange, resourceExchange);
if (aggregatedExchange != null) {
- if
(ExchangeHelper.shouldSetVariableResult(aggregatedExchange, variableReceive)) {
- // result should be stored in variable instead of
message body
-
ExchangeHelper.setVariableFromMessageBodyAndHeaders(aggregatedExchange,
variableReceive,
- aggregatedExchange.getMessage());
- aggregatedExchange.getMessage().setBody(originalBody);
-
aggregatedExchange.getMessage().setHeaders(originalHeaders);
- }
+ ProcessorHelper.storeVariableResult(exchange,
aggregatedExchange, variableReceive, originalBody,
+ originalHeaders);
// copy aggregation result onto original exchange
(preserving pattern)
copyResultsPreservePattern(exchange, aggregatedExchange);
}
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 5c00fceca0cf..78f96a9ccd97 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
@@ -25,6 +25,7 @@ import org.apache.camel.CamelContext;
import org.apache.camel.Endpoint;
import org.apache.camel.Exchange;
import org.apache.camel.ExtendedCamelContext;
+import org.apache.camel.Message;
import org.apache.camel.NoTypeConversionAvailableException;
import org.apache.camel.ResolveEndpointFailedException;
import org.apache.camel.spi.NormalizedEndpointUri;
@@ -39,6 +40,38 @@ final class ProcessorHelper {
private ProcessorHelper() {
}
+ /**
+ * Stores the reply body and headers as variables when the result is
eligible for a receive variable. After a
+ * successful write, restores the saved body and headers on {@code result}
so the caller can copy it back to
+ * {@code original}. If the write throws, restores them on {@code
original} before propagating the failure to the
+ * caller.
+ *
+ * @param original the incoming route exchange that continues
routing or enters error handling
+ * @param result the exchange carrying the reply. A send uses
{@code original} for both parameters. An
+ * enricher uses the exchange returned by its
aggregation strategy, which may be
+ * {@code original} or a separate exchange.
+ * @param variableReceive the name of the receive variable, or {@code
null} to skip storage
+ * @param originalBody the message body saved before the send or
enrichment
+ * @param originalHeaders the message headers saved before the send or
enrichment
+ */
+ static void storeVariableResult(
+ Exchange original, Exchange result, String variableReceive, Object
originalBody,
+ Map<String, Object> originalHeaders) {
+ if (!ExchangeHelper.shouldSetVariableResult(result, variableReceive)) {
+ return;
+ }
+
+ Exchange toRestore = original;
+ try {
+ ExchangeHelper.setVariableFromMessageBodyAndHeaders(result,
variableReceive, result.getMessage());
+ toRestore = result;
+ } finally {
+ Message message = toRestore.getMessage();
+ message.setBody(originalBody);
+ message.setHeaders(originalHeaders);
+ }
+ }
+
/**
* Parses a comma-separated list of component schemes into a set, or
{@code null} when unset. Used by the
* dynamic-uri EIPs to hold an optional {@code allowedSchemes} allow-list
(see CAMEL-24298).
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 aa6f05387698..a58ad9ef0240 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
@@ -272,12 +272,7 @@ public class SendDynamicProcessor extends
BaseProcessorSupport
if (stopEndpoint) {
ServiceHelper.stopAndShutdownService(endpoint);
}
- // result should be stored in variable instead of message body
- if (ExchangeHelper.shouldSetVariableResult(target,
variableReceive)) {
-
ExchangeHelper.setVariableFromMessageBodyAndHeaders(target, variableReceive,
target.getMessage());
- target.getMessage().setBody(originalBody);
- target.getMessage().setHeaders(originalHeaders);
- }
+ SendProcessor.storeVariableResult(target, variableReceive,
originalBody, originalHeaders);
// signal we are done
c.done(doneSync);
});
diff --git
a/core/camel-core-processor/src/main/java/org/apache/camel/processor/SendProcessor.java
b/core/camel-core-processor/src/main/java/org/apache/camel/processor/SendProcessor.java
index e72802f5bac1..986e8bc1cbce 100644
---
a/core/camel-core-processor/src/main/java/org/apache/camel/processor/SendProcessor.java
+++
b/core/camel-core-processor/src/main/java/org/apache/camel/processor/SendProcessor.java
@@ -200,18 +200,21 @@ public class SendProcessor extends BaseProcessorSupport
(producer, ex, cb) -> producer.process(ex, doneSync -> {
// restore previous MEP
exchange.setPattern(existingPattern);
- // result should be stored in variable instead of message
body/headers
- if (ExchangeHelper.shouldSetVariableResult(exchange,
variableReceive)) {
-
ExchangeHelper.setVariableFromMessageBodyAndHeaders(exchange, variableReceive,
- exchange.getMessage());
- exchange.getMessage().setBody(originalBody);
- exchange.getMessage().setHeaders(originalHeaders);
- }
+ storeVariableResult(exchange, variableReceive,
originalBody, originalHeaders);
// signal we are done
cb.done(doneSync);
}));
}
+ static void storeVariableResult(
+ Exchange exchange, String variableReceive, Object originalBody,
Map<String, Object> originalHeaders) {
+ try {
+ ProcessorHelper.storeVariableResult(exchange, exchange,
variableReceive, originalBody, originalHeaders);
+ } catch (Exception e) {
+ exchange.setException(e);
+ }
+ }
+
private boolean sendUsingProducer(
Exchange exchange, AsyncCallback callback, ExchangePattern
existingPattern, Object originalBody,
Map<String, Object> originalHeaders) {
@@ -315,13 +318,7 @@ public class SendProcessor extends BaseProcessorSupport
private void complete(boolean doneSync) {
this.doneSync = doneSync;
try {
- // result should be stored in variable instead of message
body/headers
- if (ExchangeHelper.shouldSetVariableResult(target,
variableReceive)) {
-
ExchangeHelper.setVariableFromMessageBodyAndHeaders(target, variableReceive,
- target.getMessage());
- target.getMessage().setBody(originalBody);
- target.getMessage().setHeaders(originalHeaders);
- }
+ storeVariableResult(target, variableReceive, originalBody,
originalHeaders);
// restore previous MEP
target.setPattern(existingPattern);
// emit event that the exchange was sent to the endpoint
diff --git
a/core/camel-core/src/test/java/org/apache/camel/processor/ToVariableReceiveHeadersTest.java
b/core/camel-core/src/test/java/org/apache/camel/processor/ToVariableReceiveHeadersTest.java
index 3c0b90da46bb..599cdcb68a59 100644
---
a/core/camel-core/src/test/java/org/apache/camel/processor/ToVariableReceiveHeadersTest.java
+++
b/core/camel-core/src/test/java/org/apache/camel/processor/ToVariableReceiveHeadersTest.java
@@ -16,9 +16,14 @@
*/
package org.apache.camel.processor;
+import java.io.InputStream;
+import java.io.StringReader;
+import java.nio.file.Files;
+import java.nio.file.Path;
import java.util.Set;
import org.apache.camel.ContextTestSupport;
+import org.apache.camel.Exchange;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.spi.BrowsableVariableRepository;
@@ -29,6 +34,7 @@ import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
/**
* Receiving into a variable again replaces all its header variables, so a
header that the new reply does not have is
@@ -36,6 +42,35 @@ import static org.junit.jupiter.api.Assertions.assertNull;
*/
class ToVariableReceiveHeadersTest extends ContextTestSupport {
+ @Test
+ void testReceiveWithStreamHeader() throws Exception {
+ try (InputStream stream =
Files.newInputStream(Path.of("src/test/resources/org/apache/camel/util/foo.txt")))
{
+ assertReceivedWithHeader(stream);
+ assertEquals('f', stream.read());
+ }
+ }
+
+ @Test
+ void testReceiveWithReaderHeader() throws Exception {
+ try (StringReader reader = new StringReader("sample")) {
+ assertReceivedWithHeader(reader);
+ assertEquals('s', reader.read());
+ }
+ }
+
+ private void assertReceivedWithHeader(Object handle) {
+ Exchange reply = template.request("direct:stream", e -> {
+ e.getMessage().setBody("original");
+ e.getMessage().setHeader("handle", handle);
+ });
+
+ assertNull(reply.getException());
+ assertEquals("original", reply.getMessage().getBody());
+ assertEquals("Bye original", reply.getVariable("resp"));
+ assertSame(handle, reply.getMessage().getHeader("handle"));
+ assertSame(handle, reply.getVariable("header:resp.handle"));
+ }
+
@Test
void testReceiveTwice() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:local");
@@ -141,6 +176,8 @@ class ToVariableReceiveHeadersTest extends
ContextTestSupport {
return new RouteBuilder() {
@Override
public void configure() {
+ from("direct:stream").toV("direct:svc", null, "resp");
+
from("direct:local")
.setBody(constant("first")).toV("direct:svc", null,
"other")
.setBody(constant("first")).toV("direct:svc", null,
"resp")
diff --git
a/core/camel-core/src/test/java/org/apache/camel/processor/ToVariableReceiveTest.java
b/core/camel-core/src/test/java/org/apache/camel/processor/ToVariableReceiveTest.java
index 7558c937d384..0d0a6809448e 100644
---
a/core/camel-core/src/test/java/org/apache/camel/processor/ToVariableReceiveTest.java
+++
b/core/camel-core/src/test/java/org/apache/camel/processor/ToVariableReceiveTest.java
@@ -16,9 +16,18 @@
*/
package org.apache.camel.processor;
+import java.util.concurrent.TimeUnit;
+
import org.apache.camel.ContextTestSupport;
+import org.apache.camel.Exchange;
import org.apache.camel.builder.RouteBuilder;
import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertInstanceOf;
+import static org.junit.jupiter.api.Assertions.assertNull;
public class ToVariableReceiveTest extends ContextTestSupport {
@@ -35,6 +44,17 @@ public class ToVariableReceiveTest extends
ContextTestSupport {
assertMockEndpointsSatisfied();
}
+ @ParameterizedTest
+ @ValueSource(strings = { "direct:missingRepo", "direct:dynamicMissingRepo"
})
+ void testReceiveWithMissingRepository(String uri) throws Exception {
+ Exchange exchange = template.asyncSend(uri, e ->
e.getMessage().setBody("World")).get(10, TimeUnit.SECONDS);
+
+ assertInstanceOf(IllegalArgumentException.class,
exchange.getException());
+ assertEquals("World", exchange.getMessage().getBody());
+ assertNull(exchange.getMessage().getHeader("foo"));
+ assertEquals(0, getMockEndpoint("mock:after").getReceivedCounter());
+ }
+
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@@ -46,6 +66,14 @@ public class ToVariableReceiveTest extends
ContextTestSupport {
.setBody(variable("bye"))
.to("mock:result");
+ from("direct:missingRepo")
+ .toV("direct:foo", null, "missing:bye")
+ .to("mock:after");
+
+ from("direct:dynamicMissingRepo")
+ .toD("direct:foo", null, "missing:bye")
+ .to("mock:after");
+
from("direct:foo")
.setHeader("foo", constant("Foo was here"))
.transform().simple("Bye ${body}");
diff --git
a/core/camel-core/src/test/java/org/apache/camel/processor/enricher/EnricherResourceCompletionTest.java
b/core/camel-core/src/test/java/org/apache/camel/processor/enricher/EnricherResourceCompletionTest.java
index f8452b416b12..a09ad0859bc3 100644
---
a/core/camel-core/src/test/java/org/apache/camel/processor/enricher/EnricherResourceCompletionTest.java
+++
b/core/camel-core/src/test/java/org/apache/camel/processor/enricher/EnricherResourceCompletionTest.java
@@ -28,11 +28,14 @@ import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.Producer;
import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.support.DefaultComponent;
import org.apache.camel.support.DefaultEndpoint;
import org.apache.camel.support.DefaultProducer;
import org.apache.camel.support.SynchronizationAdapter;
import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
import static org.awaitility.Awaitility.await;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -61,6 +64,44 @@ public class EnricherResourceCompletionTest extends
ContextTestSupport {
assertEquals(1, failures.get(), "the resource should be completed as
failed");
}
+ @ParameterizedTest
+ @CsvSource({ "direct:enrich, false", "direct:enrich, true",
"direct:pollEnrich, false", "direct:pollEnrich, true" })
+ void testVariableWriteFailureRestoresMessageAndFailsResource(String uri,
boolean returnResource) throws Exception {
+ AggregationStrategy aggregate = (original, resource) -> {
+ addCompletion(resource);
+ original.getMessage().setBody("aggregate");
+ original.getMessage().setHeader("state", "changed");
+ return returnResource ? resource : original;
+ };
+ context.addRoutes(new RouteBuilder() {
+ @Override
+ public void configure() {
+ onException(IllegalArgumentException.class).handled(true)
+ .process(e ->
e.getMessage().setHeader("resourceFailures", failures.get()))
+ .to("mock:error");
+
+ from("direct:enrich")
+
.enrich().constant("mock:resource").aggregationStrategy(aggregate).variableReceive("missing:result");
+ from("direct:pollEnrich")
+
.pollEnrich().constant("seda:resource").timeout(0).aggregationStrategy(aggregate)
+ .variableReceive("missing:result");
+ }
+ });
+
+ if ("direct:pollEnrich".equals(uri)) {
+ template.sendBody("seda:resource", "Resource");
+ }
+ MockEndpoint error = getMockEndpoint("mock:error");
+ error.expectedBodiesReceived("Hello");
+ error.expectedHeaderReceived("state", "original");
+ error.expectedHeaderReceived("resourceFailures", 1);
+
+ template.sendBodyAndHeader(uri, "Hello", "state", "original");
+
+ error.assertIsSatisfied();
+ assertEquals(1, completions.get());
+ }
+
@Test
public void testAggregationReturnsNull() {
// the strategy discards the resource, so the original message
continues unchanged
diff --git
a/core/camel-support/src/main/java/org/apache/camel/converter/stream/StreamCacheConverter.java
b/core/camel-support/src/main/java/org/apache/camel/converter/stream/StreamCacheConverter.java
index b919a95ec7de..dace9e52d5a9 100644
---
a/core/camel-support/src/main/java/org/apache/camel/converter/stream/StreamCacheConverter.java
+++
b/core/camel-support/src/main/java/org/apache/camel/converter/stream/StreamCacheConverter.java
@@ -48,6 +48,10 @@ public final class StreamCacheConverter {
@Converter(order = 2)
public static StreamCache convertToStreamCache(InputStream stream,
Exchange exchange) throws IOException {
+ // A variable repository can request a cache without an exchange to
own its resources.
+ if (exchange == null) {
+ return null;
+ }
// transfer the input stream to a cached output stream, and then
creates a new stream cache view
// of the data, which ensures the input stream is cached and
re-readable.
CachedOutputStream cos = new CachedOutputStream(exchange);
@@ -62,6 +66,9 @@ public final class StreamCacheConverter {
@Converter(order = 4)
public static StreamCache convertToStreamCache(Reader reader, Exchange
exchange) throws IOException {
+ if (exchange == null) {
+ return null;
+ }
String data =
exchange.getContext().getTypeConverter().convertTo(String.class, exchange,
reader);
return new ReaderCache(data);
}