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.csvcamel-aws2-s3aws2-s3://bucketName?options
- Producer:
uploads the message body as an object, with the key from theto("aws2-s3://invoices") header. With theCamelAwsS3Key option or theoperation header, it runs other S3 calls instead, such asCamelAwsS3Operation ,getObject orlistObjects .deleteObject - Consumer:
lists the bucket everyfrom("aws2-s3://inbox") milliseconds (500 by default), downloads up todelay objects (10 by default), and turns each into an exchange. By default it deletes each object after the route has processed it.maxMessagesPerPoll
Each endpoint builds an S3ClientautoCreateBucket=true
| Option | Default | Effect |
|---|---|---|
region | None | AWS region, such as eu-west-1 |
useDefaultCredentialsProvider | false | Find credentials the standard AWS way: environment, profile, IAM role |
accessKeysecretKey | None | Static credentials |
operation | Upload | Which S3 call the producer makes |
prefix | None | Only list or consume keys that start with it |
deleteAfterRead | true | The consumer deletes objects it has processed |
moveAfterReaddestinationBucket | false | The consumer moves processed objects to another bucket |
multiPartUploadpartSize | false | Upload large bodies in parts |
overrideEndpointuriEndpointOverrideforcePathStyle | false | Talk 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 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/keyPUTGETHEADDELETEGET
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,
, which is whathttp://host/bucket/key does. Real S3 uses virtual-hosted URLs by default, with the bucket in the host name.forcePathStyle=true - The SDK uploads with
encoding: the body comes in chunks with a trailing checksum. Theaws-chunked method decodes it back to the original bytes.read
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:
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")));
}
}
}
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
, the bucket check made when an endpoint starts. Each distinct endpoint URI is a separate endpoint and makes its own check.HEAD /invoices - The upload was a
toPUT : the key came from the/invoices/2026/invoice-77.csv header, built by the route with a Simple expression.CamelAwsS3Key - The request was signed with AWS Signature Version 4 (
), and its body was sent as a signed stream with a trailing checksum (AWS4-HMAC-SHA256 ). The SDK adds a checksum to uploads by default.STREAMING-AWS4-HMAC-SHA256-PAYLOAD-TRAILER became the object'sCamelAwsS3ContentType , and theContent-Type map became the headerCamelAwsS3Metadata , which S3 stores with the object.x-amz-meta-customer: C-1001- The reply carried the ETag from the server in
and the key inCamelAwsS3ETag . Real S3 returns an MD5-based ETag for simple uploads; the stub'sCamelAwsS3ProducedKey is made up.etag-22
Without a CamelAwsS3KeykeyNameIllegalArgumentException: AWS S3 Key is not set, or resolved to null.
Reading, listing and deleting
A bucket of monthly reports, with keys under 2026/archive/
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());
}
}
}
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]
with thelistObjects headerCamelAwsS3Prefix returned a2026/ of the SDK'sList , with keys and sizes, and left outS3Object . The client sentarchive/2025.csv , the ListObjectsV2 call.list-type=2 returned agetObject : 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.ResponseInputStream removeddeleteObject .2026/feb.csv for a key that does not exist failed with the SDK'sgetObject , status 404. UseNoSuchKeyException first, or catch it withheadObject , when missing keys are expected.onException- The request list shows one
per endpoint URI. The lastHEAD /reports reused the earlier endpoint, so it made no new check.getObject
A listObjectscopyObjectdeleteObjectsheadObjectgetObjectRangecreateDownloadLinkcreateUploadLinkcreateBucketlistBuckets
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/deleteAfterRead=falsemoveAfterRead=true
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());
}
}
}
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:
deleted each object after its exchange completed. OnlydeleteAfterRead=true , outside the prefix, was left. A route pointed at a bucket that other systems also read deletes their data.other/readme.txt - The consumer put the object content in the body, because
by default, and the key in theincludeBody=true header.CamelAwsS3Key - With
, nothing was deleted, and the next poll read both orders again: four exchanges in a few hundred milliseconds, and it would go on.deleteAfterRead=false - With
, each order was read once, copied to the bucketmoveAfterRead=true underprocessed (fromdone/ ), and deleted from the inbox: the client sent a copy request followed by a delete.destinationBucketPrefix
The consumer has no memory of what it has read, so with deleteAfterRead=falsefrom()
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:
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());
}
}
}
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 ...
returned the URL as the body. Theoperation=createDownloadLink header (spelled that way in Camel's constants) gave 600,000 ms, which becameCamelAwsS3DowloadLinkExpirationTime seconds in the URL.X-Amz-Expires = 600- The query carries the signature algorithm,
, the access key id at the start ofAWS4-HMAC-SHA256 , the signed headers, here onlyX-Amz-Credential , and a 64-character hex signature.host - A plain
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.GET
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. createUploadLinkPUT
Large files: multipart and streaming uploads
A single PUT
// 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®ion=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®ion=eu-west-1"
+ "&streamingUploadMode=true&keyName=clicks.json"
+ "&batchSize=1000000&batchMessageNumber=10000");
applies to file bodies larger thanmultiPartUpload=true , 25 MB by default. S3 requires parts of at least 5 MB, except the last.partSize appends incoming messages to an object being uploaded in parts, and completes it whenstreamingUploadMode=true bytes orbatchSize messages are reached, or afterbatchMessageNumber . With the defaultstreamingUploadTimeout , each completed object gets a numbered key based onnamingStrategy=progressive .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:
# 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
, the application gets temporary credentials from its IAM role on EC2, ECS, EKS or Lambda, and no secret appears in configuration. Staticuse-default-credentials-provider andaccessKey work too, but they are long-lived secrets that must be stored and rotated.secretKey - Give the role only the actions the routes use, for example
on one bucket. Note that the startup check callss3:PutObject , which needsHeadBucket permission on the bucket.s3:ListBucket - For server-side encryption with KMS, set
anduseAwsKMS=true .awsKMSKeyId - For S3-compatible stores such as MinIO, or LocalStack in tests, use the same override options as this page:
,overrideEndpoint=true and usuallyuriEndpointOverride .forcePathStyle=true
In Spring Boot, these properties come with camel-aws2-s3-starterS3Clientcamel.component.*
Choosing S3 options
| Situation | Options |
|---|---|
| Upload a message as an object | The producer with a CamelAwsS3Key |
| Read one known object | operation=getObject |
| Process objects dropped into a bucket | The consumer with a prefixdeleteAfterRead=true |
| Process objects without deleting them | moveAfterReaddeleteAfterRead=false |
| Files over a few hundred MB | multiPartUpload=true |
| A stream of small messages into few objects | streamingUploadMode=true |
| Running on AWS | useDefaultCredentialsProvider=true |
| Tests and S3-compatible stores | overrideEndpointuriEndpointOverrideforcePathStyle |
The traps to remember are the consumer that deletes what it reads, the consumer that reads everything again when it does not delete, getObject