Apache Camel AWS S3 component: storing and consuming objects

The aws2-s3 component uploads messages as S3 objects, runs S3 calls such as getObject and listObjects, and polls buckets for new objects. Its consumer deletes what it reads by default, and its downloads are open streams. This page explains how the component works, then runs each case with the real AWS SDK against a small local stand-in for S3.

Contents

How the AWS S3 component works

Amazon S3 stores objects, blobs of bytes with metadata, under keys in buckets. There are no real folders: a key such as 2026/invoice-77.csv is one string, and tools only display the slashes as folders. The camel-aws2-s3 component connects routes to S3 through the AWS SDK for Java 2.x (version 2.55 with Camel 4.23). The endpoint URI names the bucket, aws2-s3://bucketName?options, and the component works in two directions:

  • Producer: to("aws2-s3://invoices") uploads the message body as an object, with the key from the CamelAwsS3Key header. With the operation option or the CamelAwsS3Operation header, it runs other S3 calls instead, such as getObject, listObjects or deleteObject.
  • Consumer: from("aws2-s3://inbox") lists the bucket every delay milliseconds (500 by default), downloads up to maxMessagesPerPoll objects (10 by default), and turns each into an exchange. By default it deletes each object after the route has processed it.

Each endpoint builds an S3Client from its options: region, credentials, and optionally an endpoint override for S3-compatible stores such as MinIO or LocalStack. When an endpoint starts, it checks that the bucket exists, and creates it only if autoCreateBucket=true.

The main options
OptionDefaultEffect
regionNoneAWS region, such as eu-west-1
useDefaultCredentialsProviderfalseFind credentials the standard AWS way: environment, profile, IAM role
accessKey, secretKeyNoneStatic credentials
operationUploadWhich S3 call the producer makes
prefixNoneOnly list or consume keys that start with it
deleteAfterReadtrueThe consumer deletes objects it has processed
moveAfterRead, destinationBucketfalseThe consumer moves processed objects to another bucket
multiPartUpload, partSizefalse, 25 MBUpload large bodies in parts
overrideEndpoint, uriEndpointOverride, forcePathStylefalseTalk to an S3-compatible server instead of AWS

No AWS account was available for this page, so nothing here ran against Amazon S3. The examples run against S3Stub, a small local imitation of S3 shown in the next section, reached through the endpoint override options. The S3 client, its request signing and Camel's component code are the real ones; the server is not. The stub accepts any credentials, invents its own ETags and implements only the calls the examples make. Multipart uploads, streaming uploads and real credentials were not run, and the stub does not check signatures; their sections show configuration checked against the component's option catalog.

A local stand-in for S3

S3's API is HTTP with XML responses, so a server that answers a handful of calls fits in one class. It keeps objects in a map under bucket/key, answers PUT, GET, HEAD and DELETE on objects and a GET listing on buckets, and records each request so the programs can print what the client sent:

Java
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.CopyOnWriteArrayList;

// A tiny stand-in for S3, for the examples only: path-style requests, no authentication
// checks, and only the calls the examples make (put, copy, get, head, delete, list).
public class S3Stub implements AutoCloseable {

    public final Map<String, byte[]> objects = new ConcurrentSkipListMap<>(); // "bucket/key"
    public final List<String> requests = new CopyOnWriteArrayList<>();
    private final HttpServer server;

    public S3Stub() throws IOException {
        server = HttpServer.create(new InetSocketAddress("localhost", 0), 0);
        server.createContext("/", this::handle);
        server.start();
    }

    public String endpoint() {
        return "http://localhost:" + server.getAddress().getPort();
    }

    private void handle(HttpExchange http) throws IOException {
        String method = http.getRequestMethod();
        String path = http.getRequestURI().getRawPath().substring(1); // bucket or bucket/key
        String query = http.getRequestURI().getRawQuery();
        StringBuilder line = new StringBuilder(method + " /" + path
                + (query == null ? "" : "?" + query));
        if (method.equals("PUT")) {
            // show how the SDK signed and encoded the upload
            var headers = http.getRequestHeaders();
            String auth = headers.getFirst("Authorization");
            line.append("\n    Authorization: ").append(auth == null ? "none" : auth.split(" ")[0])
                    .append("\n    x-amz-content-sha256: ")
                    .append(headers.getFirst("x-amz-content-sha256"))
                    .append("\n    Content-Type: ").append(headers.getFirst("Content-Type"));
            headers.forEach((name, values) -> {
                if (name.toLowerCase().startsWith("x-amz-meta-")) {
                    line.append("\n    ").append(name.toLowerCase()).append(": ")
                            .append(values.get(0));
                }
            });
        }
        requests.add(line.toString());
        byte[] body = read(http);
        int slash = path.indexOf('/');
        if (slash < 0) { // bucket level: list objects
            if (method.equals("GET")) {
                reply(http, 200, listXml(path, query), "application/xml");
            } else {
                reply(http, 200, new byte[0], null);
            }
            return;
        }
        String id = URLDecoder.decode(path, StandardCharsets.UTF_8);
        switch (method) {
            case "PUT" -> {
                String copySource = http.getRequestHeaders().getFirst("x-amz-copy-source");
                if (copySource != null) { // copyObject: the source is "bucket/key"
                    byte[] data = objects.get(URLDecoder.decode(copySource.replaceFirst("^/", ""),
                            StandardCharsets.UTF_8));
                    objects.put(id, data);
                    reply(http, 200, ("<CopyObjectResult><ETag>\"etag-" + data.length
                            + "\"</ETag></CopyObjectResult>").getBytes(StandardCharsets.UTF_8),
                            "application/xml");
                    return;
                }
                objects.put(id, body);
                http.getResponseHeaders().add("ETag", "\"etag-" + body.length + "\"");
                reply(http, 200, new byte[0], null);
            }
            case "GET", "HEAD" -> {
                byte[] data = objects.get(id);
                if (data == null) {
                    byte[] error = ("<Error><Code>NoSuchKey</Code><Message>The specified key"
                            + " does not exist.</Message></Error>")
                            .getBytes(StandardCharsets.UTF_8);
                    reply(http, 404, error, "application/xml");
                } else {
                    http.getResponseHeaders().add("ETag", "\"etag-" + data.length + "\"");
                    http.getResponseHeaders().add("Last-Modified",
                            "Sun, 15 Nov 2026 10:00:00 GMT");
                    reply(http, 200, method.equals("HEAD") ? null : data,
                            "application/octet-stream", data.length);
                }
            }
            case "DELETE" -> {
                objects.remove(id);
                reply(http, 204, null, null);
            }
            default -> reply(http, 501, new byte[0], null);
        }
    }

    private byte[] listXml(String bucket, String query) {
        StringBuilder xml = new StringBuilder("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
                + "<ListBucketResult><Name>" + bucket + "</Name><IsTruncated>false</IsTruncated>");
        String prefix = "";
        if (query != null) {
            for (String part : query.split("&")) {
                if (part.startsWith("prefix=")) {
                    prefix = URLDecoder.decode(part.substring(7), StandardCharsets.UTF_8);
                }
            }
        }
        Map<String, byte[]> matching = new TreeMap<>();
        for (var e : objects.entrySet()) {
            if (e.getKey().startsWith(bucket + "/" + prefix)) {
                matching.put(e.getKey().substring(bucket.length() + 1), e.getValue());
            }
        }
        matching.forEach((key, data) -> xml.append("<Contents><Key>").append(key)
                .append("</Key><LastModified>2026-11-15T10:00:00.000Z</LastModified>")
                .append("<ETag>\"etag-").append(data.length).append("\"</ETag><Size>")
                .append(data.length).append("</Size><StorageClass>STANDARD</StorageClass>")
                .append("</Contents>"));
        xml.append("<KeyCount>").append(matching.size()).append("</KeyCount></ListBucketResult>");
        return xml.toString().getBytes(StandardCharsets.UTF_8);
    }

    // decodes the aws-chunked body that the SDK sends with a trailing checksum
    private static byte[] read(HttpExchange http) throws IOException {
        byte[] raw = http.getRequestBody().readAllBytes();
        String encoding = http.getRequestHeaders().getFirst("Content-Encoding");
        String sha = http.getRequestHeaders().getFirst("x-amz-content-sha256");
        boolean chunked = (encoding != null && encoding.contains("aws-chunked"))
                || (sha != null && sha.startsWith("STREAMING-"));
        if (!chunked) {
            return raw;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int pos = 0;
        while (pos < raw.length) {
            int lineEnd = indexOf(raw, pos);
            String header = new String(raw, pos, lineEnd - pos, StandardCharsets.US_ASCII);
            int size = Integer.parseInt(header.split(";")[0].trim(), 16);
            pos = lineEnd + 2;
            if (size == 0) {
                break;
            }
            out.write(raw, pos, size);
            pos += size + 2;
        }
        return out.toByteArray();
    }

    private static int indexOf(byte[] data, int from) {
        for (int i = from; i < data.length - 1; i++) {
            if (data[i] == '\r' && data[i + 1] == '\n') {
                return i;
            }
        }
        return data.length;
    }

    private static void reply(HttpExchange http, int code, byte[] body, String type)
            throws IOException {
        reply(http, code, body, type, body == null ? -1 : body.length);
    }

    private static void reply(HttpExchange http, int code, byte[] body, String type,
            long length) throws IOException {
        if (type != null) {
            http.getResponseHeaders().add("Content-Type", type);
        }
        if (body == null) {
            if (length > 0) {
                http.getResponseHeaders().add("Content-Length", String.valueOf(length));
            }
            http.sendResponseHeaders(code, -1);
        } else {
            http.sendResponseHeaders(code, body.length == 0 ? -1 : body.length);
            http.getResponseBody().write(body);
        }
        http.close();
    }

    @Override
    public void close() {
        server.stop(0);
    }
}
  • The client must use path-style URLs, http://host/bucket/key, which is what forcePathStyle=true does. Real S3 uses virtual-hosted URLs by default, with the bucket in the host name.
  • The SDK uploads with aws-chunked encoding: the body comes in chunks with a trailing checksum. The read method decodes it back to the original bytes.

Uploading an object

An invoice CSV with a computed key, a content type and one item of user metadata shows what the producer sends and what it reports back:

Java
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.aws2.s3.AWS2S3Constants;
import org.apache.camel.impl.DefaultCamelContext;
import org.slf4j.LoggerFactory;

public class Upload {

    public static void main(String[] args) throws Exception {
        ((Logger) LoggerFactory.getLogger("ROOT")).setLevel(Level.OFF);
        try (S3Stub s3 = new S3Stub()) {
            // the stub in place of AWS: endpoint override, path-style URLs, dummy keys
            String bucket = "aws2-s3://invoices?region=eu-west-1&accessKey=test&secretKey=test"
                    + "&overrideEndpoint=true&forcePathStyle=true&uriEndpointOverride="
                    + s3.endpoint();
            CamelContext context = new DefaultCamelContext();
            context.addRoutes(new RouteBuilder() {
                @Override
                public void configure() {
                    from("direct:storeInvoice")
                            .setHeader(AWS2S3Constants.KEY,
                                    simple("${header.year}/invoice-${header.invoiceId}.csv"))
                            .setHeader(AWS2S3Constants.CONTENT_TYPE, constant("text/csv"))
                            .setHeader(AWS2S3Constants.METADATA,
                                    simple("${header.customerMeta}"))
                            .to(bucket);
                }
            });
            context.start();
            ProducerTemplate template = context.createProducerTemplate();
            Exchange result = template.request("direct:storeInvoice", e -> {
                e.getMessage().setBody("item,price\nbook,12.50\n");
                e.getMessage().setHeader("invoiceId", 77);
                e.getMessage().setHeader("year", 2026);
                e.getMessage().setHeader("customerMeta", Map.of("customer", "C-1001"));
            });
            context.close();

            System.out.println("Requests the S3 client sent:");
            s3.requests.forEach(r -> System.out.println("  " + r));
            System.out.println("Headers on the reply:");
            System.out.println("  CamelAwsS3ETag = "
                    + result.getMessage().getHeader(AWS2S3Constants.E_TAG));
            System.out.println("  CamelAwsS3ProducedKey = "
                    + result.getMessage().getHeader(AWS2S3Constants.PRODUCED_KEY));
            s3.objects.forEach((key, data) -> System.out.println("Stored " + key + ": "
                    + new String(data, StandardCharsets.UTF_8).replace("\n", "\\n")));
        }
    }
}
Output
Requests the S3 client sent:
  HEAD /invoices
  PUT /invoices/2026/invoice-77.csv
    Authorization: AWS4-HMAC-SHA256
    x-amz-content-sha256: STREAMING-AWS4-HMAC-SHA256-PAYLOAD-TRAILER
    Content-Type: text/csv
    x-amz-meta-customer: C-1001
Headers on the reply:
  CamelAwsS3ETag = "etag-22"
  CamelAwsS3ProducedKey = 2026/invoice-77.csv
Stored invoices/2026/invoice-77.csv: item,price\nbook,12.50\n
  • Before the upload, the endpoint sent HEAD /invoices, the bucket check made when an endpoint starts. Each distinct endpoint URI is a separate endpoint and makes its own check.
  • The upload was a PUT to /invoices/2026/invoice-77.csv: the key came from the CamelAwsS3Key header, built by the route with a Simple expression.
  • The request was signed with AWS Signature Version 4 (AWS4-HMAC-SHA256), and its body was sent as a signed stream with a trailing checksum (STREAMING-AWS4-HMAC-SHA256-PAYLOAD-TRAILER). The SDK adds a checksum to uploads by default.
  • CamelAwsS3ContentType became the object's Content-Type, and the CamelAwsS3Metadata map became the header x-amz-meta-customer: C-1001, which S3 stores with the object.
  • The reply carried the ETag from the server in CamelAwsS3ETag and the key in CamelAwsS3ProducedKey. Real S3 returns an MD5-based ETag for simple uploads; the stub's etag-22 is made up.

Without a CamelAwsS3Key header or a keyName option, the upload fails with IllegalArgumentException: AWS S3 Key is not set, or resolved to null. If two messages produce the same key, the second silently replaces the first, unless the bucket has versioning turned on.

Reading, listing and deleting

A bucket of monthly reports, with keys under 2026/ and one under archive/, is enough to run the most common producer operations:

Java
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;
import org.apache.camel.CamelContext;
import org.apache.camel.CamelExecutionException;
import org.apache.camel.Exchange;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.component.aws2.s3.AWS2S3Constants;
import org.apache.camel.impl.DefaultCamelContext;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.services.s3.model.S3Object;

public class Operations {

    public static void main(String[] args) throws Exception {
        ((Logger) LoggerFactory.getLogger("ROOT")).setLevel(Level.OFF);
        try (S3Stub s3 = new S3Stub()) {
            s3.objects.put("reports/2026/jan.csv", "month,total\njan,100\n".getBytes(
                    StandardCharsets.UTF_8));
            s3.objects.put("reports/2026/feb.csv", "month,total\nfeb,90\n".getBytes(
                    StandardCharsets.UTF_8));
            s3.objects.put("reports/archive/2025.csv", "old".getBytes(StandardCharsets.UTF_8));
            String bucket = "aws2-s3://reports?region=eu-west-1&accessKey=test&secretKey=test"
                    + "&overrideEndpoint=true&forcePathStyle=true&uriEndpointOverride="
                    + s3.endpoint();
            CamelContext context = new DefaultCamelContext();
            context.start();
            ProducerTemplate template = context.createProducerTemplate();

            Exchange list = template.request(bucket + "&operation=listObjects",
                    e -> e.getMessage().setHeader(AWS2S3Constants.PREFIX, "2026/"));
            @SuppressWarnings("unchecked")
            List<S3Object> objects = list.getMessage().getBody(List.class);
            System.out.println("listObjects with prefix 2026/:");
            objects.forEach(o -> System.out.println("  " + o.key() + ", " + o.size() + " bytes"));

            Exchange get = template.request(bucket + "&operation=getObject",
                    e -> e.getMessage().setHeader(AWS2S3Constants.KEY, "2026/jan.csv"));
            Object body = get.getMessage().getBody();
            System.out.println("getObject body type: " + body.getClass().getSimpleName()
                    + ", is an InputStream: " + (body instanceof InputStream));
            try (InputStream in = (InputStream) body) {
                System.out.println("  content: " + new String(in.readAllBytes(),
                        StandardCharsets.UTF_8).replace("\n", "\\n"));
            }
            System.out.println("  CamelAwsS3ContentLength = "
                    + get.getMessage().getHeader(AWS2S3Constants.CONTENT_LENGTH));

            template.sendBodyAndHeader(bucket + "&operation=deleteObject", null,
                    AWS2S3Constants.KEY, "2026/feb.csv");
            System.out.println("after deleteObject: " + s3.objects.keySet());

            try {
                template.requestBodyAndHeader(bucket + "&operation=getObject", null,
                        AWS2S3Constants.KEY, "2026/mar.csv");
            } catch (CamelExecutionException e) {
                System.out.println("getObject of a missing key: "
                        + e.getCause().getClass().getSimpleName() + ", status "
                        + e.getCause().getMessage().replaceAll(".*Status Code: (\\d+).*", "$1"));
            }
            context.close();
            System.out.println("requests: " + s3.requests.stream()
                    .map(r -> r.lines().findFirst().orElse("")).toList());
        }
    }
}
Output
listObjects with prefix 2026/:
  2026/feb.csv, 19 bytes
  2026/jan.csv, 20 bytes
getObject body type: ResponseInputStream, is an InputStream: true
  content: month,total\njan,100\n
  CamelAwsS3ContentLength = 20
after deleteObject: [reports/2026/jan.csv, reports/archive/2025.csv]
getObject of a missing key: NoSuchKeyException, status 404
requests: [HEAD /reports, GET /reports?list-type=2&prefix=2026%2F, HEAD /reports, GET /reports/2026/jan.csv, HEAD /reports, DELETE /reports/2026/feb.csv, GET /reports/2026/mar.csv]
  • listObjects with the CamelAwsS3Prefix header 2026/ returned a List of the SDK's S3Object, with keys and sizes, and left out archive/2025.csv. The client sent list-type=2, the ListObjectsV2 call.
  • getObject returned a ResponseInputStream: the body is a stream from the open HTTP connection, not the bytes. The program read it inside try-with-resources; a stream that is never read or closed holds a pooled connection, and enough of them stop all further S3 calls.
  • deleteObject removed 2026/feb.csv.
  • getObject for a key that does not exist failed with the SDK's NoSuchKeyException, status 404. Use headObject first, or catch it with onException, when missing keys are expected.
  • The request list shows one HEAD /reports per endpoint URI. The last getObject reused the earlier endpoint, so it made no new check.

A listObjects call returns at most 1000 keys per request. For bigger listings, follow the continuation token, or let the consumer page through the bucket. The S3 operations that the producer supports in Camel 4.23 also include copyObject, deleteObjects, headObject, getObjectRange, createDownloadLink and createUploadLink (presigned URLs), and bucket calls such as createBucket and listBuckets.

Polling a bucket, and the default that deletes

The consumer suits buckets that act as an inbox: another system drops objects, a route processes them. Two orders and one unrelated file sit in the bucket, and the route consumes the orders/ prefix three times: with the defaults, with deleteAfterRead=false, and with moveAfterRead=true:

Java
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;
import org.apache.camel.CamelContext;
import org.apache.camel.builder.NotifyBuilder;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.aws2.s3.AWS2S3Constants;
import org.apache.camel.impl.DefaultCamelContext;
import org.slf4j.LoggerFactory;

public class PollBucket {

    public static void main(String[] args) throws Exception {
        ((Logger) LoggerFactory.getLogger("ROOT")).setLevel(Level.OFF);
        poll("defaults (deleteAfterRead=true)", "");
        poll("deleteAfterRead=false", "&deleteAfterRead=false");
        poll("moveAfterRead=true", "&moveAfterRead=true&destinationBucket=processed"
                + "&destinationBucketPrefix=done/");
    }

    static void poll(String label, String options) throws Exception {
        try (S3Stub s3 = new S3Stub()) {
            s3.objects.put("inbox/orders/o-1.json", "{\"id\":1}".getBytes(StandardCharsets.UTF_8));
            s3.objects.put("inbox/orders/o-2.json", "{\"id\":2}".getBytes(StandardCharsets.UTF_8));
            s3.objects.put("inbox/other/readme.txt", "x".getBytes(StandardCharsets.UTF_8));
            CamelContext context = new DefaultCamelContext();
            context.addRoutes(new RouteBuilder() {
                @Override
                public void configure() {
                    from("aws2-s3://inbox?region=eu-west-1&accessKey=test&secretKey=test"
                            + "&overrideEndpoint=true&forcePathStyle=true&uriEndpointOverride="
                            + s3.endpoint() + "&prefix=orders/&delay=300" + options)
                            .routeId("poller")
                            .process(e -> System.out.println("  read "
                                    + e.getMessage().getHeader(AWS2S3Constants.KEY) + ": "
                                    + e.getMessage().getBody(String.class)));
                }
            });
            System.out.println(label + ":");
            NotifyBuilder four = new NotifyBuilder(context).fromRoute("poller").whenDone(4)
                    .create();
            context.start();
            System.out.println("  four exchanges within 3 s: " + four.matches(3, TimeUnit.SECONDS));
            context.close();
            System.out.println("  left in the bucket: " + s3.objects.keySet());
        }
    }
}
Output
defaults (deleteAfterRead=true):
  read orders/o-1.json: {"id":1}
  read orders/o-2.json: {"id":2}
  four exchanges within 3 s: false
  left in the bucket: [inbox/other/readme.txt]
deleteAfterRead=false:
  read orders/o-1.json: {"id":1}
  read orders/o-2.json: {"id":2}
  read orders/o-1.json: {"id":1}
  read orders/o-2.json: {"id":2}
  four exchanges within 3 s: true
  left in the bucket: [inbox/orders/o-1.json, inbox/orders/o-2.json, inbox/other/readme.txt]
moveAfterRead=true:
  read orders/o-1.json: {"id":1}
  read orders/o-2.json: {"id":2}
  four exchanges within 3 s: false
  left in the bucket: [inbox/other/readme.txt, processed/done/orders/o-1.json, processed/done/orders/o-2.json]
  • With the defaults, the route read both orders once, and then they were gone from the bucket: deleteAfterRead=true deleted each object after its exchange completed. Only other/readme.txt, outside the prefix, was left. A route pointed at a bucket that other systems also read deletes their data.
  • The consumer put the object content in the body, because includeBody=true by default, and the key in the CamelAwsS3Key header.
  • With deleteAfterRead=false, nothing was deleted, and the next poll read both orders again: four exchanges in a few hundred milliseconds, and it would go on.
  • With moveAfterRead=true, each order was read once, copied to the bucket processed under done/ (from destinationBucketPrefix), and deleted from the inbox: the client sent a copy request followed by a delete.

The consumer has no memory of what it has read, so with deleteAfterRead=false it needs help. Either move processed objects away, as the third run did, or put an idempotent consumer with a persistent repository after the from(), keyed on the object key and ETag, as the Camel JDBC page shows. For event-driven processing instead of polling, S3 can send event notifications to SQS, which a route can consume. The same polling ideas, for local directories, are on the Camel File component page.

Presigned download links

To let a browser or a partner download one object without giving it AWS credentials, the producer can create a presigned URL: the request, signed in advance with the route's credentials, valid for a limited time. Signing happens in the client, so the program can show the link's parts and then fetch it with a plain HTTP client:

Java
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.TreeMap;
import org.apache.camel.CamelContext;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.component.aws2.s3.AWS2S3Constants;
import org.apache.camel.impl.DefaultCamelContext;
import org.slf4j.LoggerFactory;

public class DownloadLink {

    public static void main(String[] args) throws Exception {
        ((Logger) LoggerFactory.getLogger("ROOT")).setLevel(Level.OFF);
        try (S3Stub s3 = new S3Stub()) {
            s3.objects.put("reports/2026/jan.pdf", "%PDF-1.7 ...".getBytes(StandardCharsets.UTF_8));
            String bucket = "aws2-s3://reports?region=eu-west-1&accessKey=AKIAEXAMPLE"
                    + "&secretKey=test&overrideEndpoint=true&forcePathStyle=true"
                    + "&uriEndpointOverride=" + s3.endpoint();
            CamelContext context = new DefaultCamelContext();
            context.start();
            ProducerTemplate template = context.createProducerTemplate();

            // a presigned URL: anyone holding it may GET this one object until it expires
            String link = template.requestBodyAndHeaders(bucket + "&operation=createDownloadLink",
                    null, Map.of(AWS2S3Constants.KEY, "2026/jan.pdf",
                            AWS2S3Constants.DOWNLOAD_LINK_EXPIRATION_TIME, 600000L),
                    String.class);
            URI uri = URI.create(link);
            System.out.println("path: " + uri.getPath());
            Map<String, String> query = new TreeMap<>();
            for (String part : uri.getRawQuery().split("&")) {
                String[] kv = part.split("=", 2);
                query.put(kv[0], kv[1]);
            }
            for (String name : new String[] {"X-Amz-Algorithm", "X-Amz-Expires",
                "X-Amz-SignedHeaders"}) {
                System.out.println(name + " = " + query.get(name));
            }
            System.out.println("X-Amz-Credential starts with "
                    + query.get("X-Amz-Credential").split("%2F")[0]);
            System.out.println("X-Amz-Signature: " + query.get("X-Amz-Signature").length()
                    + " hex characters");
            context.close();

            // the link works with a plain HTTP client, without any AWS credentials
            HttpResponse<String> response = HttpClient.newHttpClient().send(
                    HttpRequest.newBuilder(uri).build(), HttpResponse.BodyHandlers.ofString());
            System.out.println("plain GET of the link -> " + response.statusCode() + ": "
                    + response.body());
        }
    }
}
Output
path: /reports/2026/jan.pdf
X-Amz-Algorithm = AWS4-HMAC-SHA256
X-Amz-Expires = 600
X-Amz-SignedHeaders = host
X-Amz-Credential starts with AKIAEXAMPLE
X-Amz-Signature: 64 hex characters
plain GET of the link -> 200: %PDF-1.7 ...
  • operation=createDownloadLink returned the URL as the body. The CamelAwsS3DowloadLinkExpirationTime header (spelled that way in Camel's constants) gave 600,000 ms, which became X-Amz-Expires = 600 seconds in the URL.
  • The query carries the signature algorithm, AWS4-HMAC-SHA256, the access key id at the start of X-Amz-Credential, the signed headers, here only host, and a 64-character hex signature.
  • A plain GET of the link, with no AWS SDK and no credentials, returned the object. The stub does not check signatures, so this run shows the shape of the link; real S3 checks the signature and the expiry, and refuses the link with 403 once it has expired.

The access key id appears in the link in clear text, which is normal for presigned URLs, but the link itself grants access to the object for its whole lifetime: keep the expiry short and treat the URL like a password. createUploadLink creates the matching presigned PUT.

Large files: multipart and streaming uploads

A single PUT can upload at most 5 GB, and a large body sent in one request must be retried from the start if the connection drops. Multipart upload splits the body into parts that are uploaded separately and joined by S3. Camel offers two modes; neither was run here, since the stub does not implement the multipart calls:

Java
// one large file, uploaded in 50 MB parts
from("file:/data/exports?noop=true")
        .setHeader(AWS2S3Constants.KEY, simple("exports/${header.CamelFileName}"))
        .to("aws2-s3://archive?useDefaultCredentialsProvider=true&region=eu-west-1"
                + "&multiPartUpload=true&partSize=52428800");

// many small messages, collected into objects of about 1 MB each
from("kafka:clicks")
        .to("aws2-s3://click-archive?useDefaultCredentialsProvider=true&region=eu-west-1"
                + "&streamingUploadMode=true&keyName=clicks.json"
                + "&batchSize=1000000&batchMessageNumber=10000");
  • multiPartUpload=true applies to file bodies larger than partSize, 25 MB by default. S3 requires parts of at least 5 MB, except the last.
  • streamingUploadMode=true appends incoming messages to an object being uploaded in parts, and completes it when batchSize bytes or batchMessageNumber messages are reached, or after streamingUploadTimeout. With the default namingStrategy=progressive, each completed object gets a numbered key based on keyName.
  • An upload that fails halfway leaves its parts in the bucket, and S3 charges for them until they are removed. A lifecycle rule that aborts incomplete multipart uploads after a few days cleans them up.

Credentials and real buckets

Against real AWS, the endpoint needs a region and credentials. These settings were not run here. The option names come from the component's catalog in Camel 4.23:

Properties
# the usual choice: the SDK's default chain (environment, profile, container or EC2 role)
camel.component.aws2-s3.use-default-credentials-provider=true
camel.component.aws2-s3.region=eu-west-1

# a named profile from ~/.aws/credentials, for local development
camel.component.aws2-s3.use-profile-credentials-provider=true
camel.component.aws2-s3.profile-credentials-name=dev
  • With use-default-credentials-provider, the application gets temporary credentials from its IAM role on EC2, ECS, EKS or Lambda, and no secret appears in configuration. Static accessKey and secretKey work too, but they are long-lived secrets that must be stored and rotated.
  • Give the role only the actions the routes use, for example s3:PutObject on one bucket. Note that the startup check calls HeadBucket, which needs s3:ListBucket permission on the bucket.
  • For server-side encryption with KMS, set useAwsKMS=true and awsKMSKeyId.
  • For S3-compatible stores such as MinIO, or LocalStack in tests, use the same override options as this page: overrideEndpoint=true, uriEndpointOverride and usually forcePathStyle=true.

In Spring Boot, these properties come with camel-aws2-s3-starter, and the component can also use an S3Client bean defined by the application. The Camel with Spring Boot page shows how camel.component.* properties are bound, including the trap that misspelt ones are ignored.

Choosing S3 options

Common situations and the options that fit them
SituationOptions
Upload a message as an objectThe producer with a CamelAwsS3Key header
Read one known objectoperation=getObject, and close the stream
Process objects dropped into a bucketThe consumer with a prefix, accepting deleteAfterRead=true
Process objects without deleting themmoveAfterRead, or deleteAfterRead=false with an idempotent consumer
Files over a few hundred MBmultiPartUpload=true
A stream of small messages into few objectsstreamingUploadMode=true
Running on AWSuseDefaultCredentialsProvider=true and an IAM role
Tests and S3-compatible storesoverrideEndpoint, uriEndpointOverride, forcePathStyle

The traps to remember are the consumer that deletes what it reads, the consumer that reads everything again when it does not delete, getObject streams that hold connections until closed, and keys that silently overwrite each other.