This is an automated email from the ASF dual-hosted git repository.

davsclaus pushed a commit to branch CAMEL-27299-binary-keeps-inputstream
in repository https://gitbox.apache.org/repos/asf/camel.git

commit 8a8c4ee6e727aec1f3c23d160c2b73da08abea57
Author: Claus Ibsen <[email protected]>
AuthorDate: Fri Nov 20 15:55:38 2026 +0100

    CAMEL-27299: camel-kamelet - the binary output type of a source Kamelet 
keeps a stream body
    
    Since CAMEL-27258 the output data type of a source Kamelet is applied before
    the consuming route. With stream caching turned off, a source with the 
binary
    type (aws-s3-source, google-storage-source, azure-storage-blob-source, ...)
    gives a plain InputStream, and the binary type read the whole object into
    memory, where before the consuming route got the stream.
    
    When KameletProducer applies the binary (application-octet-stream) output 
type
    of a source Kamelet, it now keeps an InputStream body as it is and only sets
    Content-Type: application/octet-stream. This is what the consuming route got
    before CAMEL-27258, when the type was applied after it.
    
    The binary data type transformer itself is unchanged: in any other place
    (transformDataType, inputType/outputType, action Kamelets) it still reads a
    stream that is not a stream cache into a byte[], as it may be read only once
    (see BinaryDataTypeOneShotStreamTest from the review of #30453).
    
    Co-Authored-By: Claude Opus 5.5 <[email protected]>
    Signed-off-by: Claus Ibsen <[email protected]>
---
 .../camel/component/kamelet/KameletProducer.java   | 30 ++++++-
 .../ROOT/pages/camel-4x-upgrade-guide-4_24.adoc    |  8 +-
 .../apache/camel/dsl/yaml/KameletLoaderTest.java   | 94 ++++++++++++++++++++++
 3 files changed, 126 insertions(+), 6 deletions(-)

diff --git 
a/components/camel-kamelet/src/main/java/org/apache/camel/component/kamelet/KameletProducer.java
 
b/components/camel-kamelet/src/main/java/org/apache/camel/component/kamelet/KameletProducer.java
index d95afc2bfef7..218d5d84964d 100644
--- 
a/components/camel-kamelet/src/main/java/org/apache/camel/component/kamelet/KameletProducer.java
+++ 
b/components/camel-kamelet/src/main/java/org/apache/camel/component/kamelet/KameletProducer.java
@@ -16,6 +16,8 @@
  */
 package org.apache.camel.component.kamelet;
 
+import java.io.InputStream;
+
 import org.apache.camel.AsyncCallback;
 import org.apache.camel.AsyncProcessor;
 import org.apache.camel.CamelContext;
@@ -23,12 +25,14 @@ import org.apache.camel.Exchange;
 import org.apache.camel.Processor;
 import org.apache.camel.Route;
 import org.apache.camel.ServiceStatus;
+import org.apache.camel.processor.transformer.ByteArrayDataTypeTransformer;
 import org.apache.camel.processor.transformer.DataTypeProcessor;
 import org.apache.camel.processor.transformer.TypeConverterTransformer;
 import org.apache.camel.spi.DataType;
 import org.apache.camel.spi.DataTypeAware;
 import org.apache.camel.spi.ManagementStrategy;
 import org.apache.camel.spi.RouteIdAware;
+import org.apache.camel.spi.TransformerKey;
 import org.apache.camel.support.DefaultAsyncProducer;
 import org.apache.camel.support.ExchangeHelper;
 import org.apache.camel.support.service.ServiceHelper;
@@ -55,6 +59,8 @@ final class KameletProducer extends DefaultAsyncProducer 
implements RouteIdAware
     private volatile Processor outputType;
     private volatile DataType outputDataType;
     private volatile boolean outputTypeResolved;
+    // whether the output data type is binary and the Kamelet is a source, 
which then keeps a stream body as it is
+    private volatile boolean outputTypeKeepsStream;
 
     public KameletProducer(KameletEndpoint endpoint, String key) {
         super(endpoint);
@@ -154,10 +160,19 @@ final class KameletProducer extends DefaultAsyncProducer 
implements RouteIdAware
         if (processor == null) {
             return true;
         }
-        try {
-            processor.process(exchange);
-        } catch (Exception e) {
-            exchange.setException(e);
+        if (outputTypeKeepsStream && exchange.getMessage().getBody() 
instanceof InputStream) {
+            // the binary type of a source keeps any stream, also one that can 
be read only once (stream caching off),
+            // and only sets the content type: this is what the consuming 
route got before the output type of a source
+            // was applied before it (it was applied when the route of the 
Kamelet completed), and a large object, such
+            // as a file of an FTP server with streamDownload, is not read 
into memory. The binary type itself reads such
+            // a stream into a byte array, so the steps after it in the same 
route can read it again.
+            exchange.getMessage().setHeader(Exchange.CONTENT_TYPE, 
"application/octet-stream");
+        } else {
+            try {
+                processor.process(exchange);
+            } catch (Exception e) {
+                exchange.setException(e);
+            }
         }
         if (exchange.getException() != null) {
             return false;
@@ -181,6 +196,12 @@ final class KameletProducer extends DefaultAsyncProducer 
implements RouteIdAware
                     if (type != null) {
                         outputDataType = new DataType(type.toString());
                         outputType = createOutputType(route, type.toString());
+                        // the route of a source Kamelet starts from a 
component; the route of an action Kamelet from
+                        // kamelet:source
+                        boolean source = !(route.getConsumer() instanceof 
KameletConsumer);
+                        outputTypeKeepsStream = source && outputType != null 
&& getEndpoint().getCamelContext()
+                                
.getTransformerRegistry().resolveTransformer(new TransformerKey(
+                                        DataType.ANY, outputDataType)) 
instanceof ByteArrayDataTypeTransformer;
                     }
                     outputTypeResolved = true;
                 }
@@ -216,6 +237,7 @@ final class KameletProducer extends DefaultAsyncProducer 
implements RouteIdAware
         outputType = null;
         outputDataType = null;
         outputTypeResolved = false;
+        outputTypeKeepsStream = false;
         super.doStop();
     }
 
diff --git 
a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc 
b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
index 6760655d13f4..a1b7b26abe91 100644
--- a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
+++ b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
@@ -237,7 +237,10 @@ when it hands it on with `kamelet:sink`. Before, the type 
was applied only when
   the type, and an exchange failed at the end when the consuming route left a 
body that could not be converted to the
   type, such as a `Map` for `binary`. Sources of the Kamelet catalog such as 
`aws-sqs-source` (`text`), `slack-source`
   (`json`) or `azure-eventhubs-source` (`binary`) now give the first step of 
the consuming route a `String`, JSON or a
-  `byte[]` with the matching `Content-Type` header, where it used to get the 
body of the component.
+  `byte[]` with the matching `Content-Type` header, where it used to get the 
body of the component. A source with the
+  `binary` type keeps a stream body as it is, also an `InputStream` that is 
not a stream cache (stream caching turned
+  off), and only sets the `Content-Type` header, so a large object or file 
(such as `aws-s3-source`, or an FTP source
+  with `streamDownload`) is not read into memory, and the consuming route gets 
the stream as before.
 * For an action or a sink Kamelet called with the Kamelet EIP (`kamelet: name: 
...` in YAML, `.kamelet("...")` in
   Java), that was after the steps that follow the EIP had run, so these steps 
got the body before the type was applied.
   They now get the body of the type, as the steps after a `to("kamelet:...")` 
already did.
@@ -254,7 +257,8 @@ The `application-octet-stream` (`binary`) data type 
transformer keeps a body tha
 header to `application/octet-stream`. Before, it read the body into a 
`byte[]`. These bodies are binary already and can
 be read again, and they may be large: a source Kamelet such as `aws-s3-source` 
or `azure-storage-blob-source` declares
 `binary` and gives the object as a stream, and a file can be uploaded without 
reading it into memory. Any other body,
-including an `InputStream` that is not a stream cache (stream caching turned 
off), is still converted to a `byte[]`.
+including an `InputStream` that is not a stream cache (stream caching turned 
off), is still converted to a `byte[]`,
+as it may be read only once; only the `binary` output type of a source Kamelet 
keeps such a stream (see above).
 
 === camel-kamelet - each Kamelet EIP has a Kamelet route of its own
 
diff --git 
a/dsl/camel-yaml-dsl/camel-yaml-dsl/src/test/java/org/apache/camel/dsl/yaml/KameletLoaderTest.java
 
b/dsl/camel-yaml-dsl/camel-yaml-dsl/src/test/java/org/apache/camel/dsl/yaml/KameletLoaderTest.java
index 5127ce381f8b..c3f0e4805f3c 100644
--- 
a/dsl/camel-yaml-dsl/camel-yaml-dsl/src/test/java/org/apache/camel/dsl/yaml/KameletLoaderTest.java
+++ 
b/dsl/camel-yaml-dsl/camel-yaml-dsl/src/test/java/org/apache/camel/dsl/yaml/KameletLoaderTest.java
@@ -16,6 +16,12 @@
  */
 package org.apache.camel.dsl.yaml;
 
+import java.io.ByteArrayInputStream;
+import java.io.InputStream;
+import java.io.SequenceInputStream;
+import java.nio.charset.StandardCharsets;
+import java.util.Collections;
+import java.util.List;
 import java.util.Map;
 import java.util.concurrent.atomic.AtomicInteger;
 
@@ -654,6 +660,94 @@ class KameletLoaderTest extends YamlTestSupport {
         MockEndpoint.assertIsSatisfied(context);
     }
 
+    @Test
+    void sourceKameletBinaryOutputTypeKeepsStream() throws Exception {
+        // CAMEL-27299: with stream caching off, the binary type of a source 
keeps a stream that can be read only once,
+        // as the consuming route got it before the output type of a source 
was applied before it
+        context.setStreamCaching(false);
+        loadKamelets("""
+                apiVersion: camel.apache.org/v1
+                kind: Kamelet
+                metadata:
+                  name: my-binary-source
+                  labels:
+                    camel.apache.org/kamelet.type: source
+                spec:
+                  definition:
+                    title: "My Source"
+                  dataTypes:
+                    out:
+                      default: binary
+                      types:
+                        binary:
+                          format: application-octet-stream
+                  template:
+                    from:
+                      uri: "direct:feed"
+                      steps:
+                        - to: "kamelet:sink"
+                """);
+        loadRoutes("""
+                - from:
+                    uri: "kamelet:my-binary-source"
+                    steps:
+                      - to: "mock:first"
+                """);
+
+        InputStream stream = oneShotStream("payload");
+        withMock("mock:first", mock -> {
+            mock.expectedMessageCount(1);
+            mock.expectedHeaderReceived("Content-Type", 
"application/octet-stream");
+            mock.message(0).body().isEqualTo(stream);
+        });
+
+        context.start();
+
+        Exchange out = context.createProducerTemplate().send("direct:feed", e 
-> e.getMessage().setBody(stream));
+        assertThat(out.getException()).isNull();
+
+        MockEndpoint.assertIsSatisfied(context);
+        // the stream was not read
+        assertThat(new String(stream.readAllBytes(), 
StandardCharsets.UTF_8)).isEqualTo("payload");
+    }
+
+    @Test
+    void actionKameletBinaryOutputTypeReadsStream() throws Exception {
+        // the steps after an action Kamelet got a byte array before, so its 
binary type still reads a stream
+        context.setStreamCaching(false);
+        loadKamelets(BINARY_ACTION);
+        loadRoutes("""
+                - from:
+                    uri: "direct:to"
+                    steps:
+                      - to: "kamelet:my-binary-action"
+                      - to: "mock:after"
+                """);
+
+        withMock("mock:after", mock -> {
+            mock.expectedMessageCount(1);
+            mock.expectedHeaderReceived("Content-Type", 
"application/octet-stream");
+            mock.message(0).body().isInstanceOf(byte[].class);
+        });
+
+        context.start();
+
+        Exchange out = context.createProducerTemplate().send("direct:to",
+                e -> e.getMessage().setBody(oneShotStream("payload")));
+        assertThat(out.getException()).isNull();
+        
assertThat(out.getMessage().getBody(String.class)).isEqualTo("payload");
+
+        MockEndpoint.assertIsSatisfied(context);
+    }
+
+    /**
+     * A stream that can be read only once (no mark/reset), as a component 
with stream caching off can give.
+     */
+    private static InputStream oneShotStream(String text) {
+        return new SequenceInputStream(
+                Collections.enumeration(List.of(new 
ByteArrayInputStream(text.getBytes(StandardCharsets.UTF_8)))));
+    }
+
     @Test
     void sourceKameletOutputTypeWithoutTransformerHandsMessagesOnUnchanged() 
throws Exception {
         // the transformer of the format is not on the classpath (camel-slack 
is not a test dependency)

Reply via email to