The Camel splitter: one message in, many messages out
The splitter breaks one message into parts and processes each part as a message of its own: the lines of a file, the items of an order, the elements of an XML document. This page explains how Camel builds and runs the parts, then shows with Camel 4.23 how to combine the results, run the parts in parallel, stream large inputs and control what happens when one part fails.
Contents
How the splitter works
Many messages are really batches: a CSV file with ten thousand orders, a JSON array of events, an XML document with a list of invoices. Downstream systems usually want one item at a time. The splitter takes one exchange, evaluates an expression that returns the parts, and sends each part through the steps inside split()
Underneath, the splitter is a multicast whose list of messages comes from the expression instead of from a list of endpoints. In Camel's code, SplitterMulticastProcessor
- It gets the next item from the expression. A
, an array, anList or aIterator is used directly, and other bodies are converted to an iterator.Stream - It copies the original exchange and sets the item as the body. Headers and exchange properties are copied, so each part still carries the original's metadata.
- It sets the exchange properties
,CamelSplitIndex andCamelSplitSize on the copy.CamelSplitComplete - It runs the copy through the steps inside the split, and passes the result to an
if one is configured.AggregationStrategy
After the last part, the route continues with the original message, or with the aggregated result when there is a strategy.
| Expression | Splits | Best for |
|---|---|---|
split(body()) | A ListIterableIterator | Bodies that are already collections |
split(body().tokenize(",")) | Text by a delimiter | Lines and simple delimited data |
split(body().tokenize("\n", 100, false)) | Text in groups of lines | Batch inserts of large files |
split().tokenizeXML("order", "orders") | XML elements, without building a DOM | Large XML documents |
split().xpath(...) | Nodes selected by XPath | Smaller XML documents that need real queries |
split().jsonpath("$.items[*]") | JSON array elements (camel-jsonpath) | JSON bodies |
split(method(bean, "parts")) | Whatever a Java method returns | Splitting that needs logic |
The examples run with Camel 4.23 on Java 21, with camel-main and the core components; the XPath example also uses camel-xpath and camel-xml-jaxp.
Splitting a list and a string
The two most common inputs are a collection, split as it is, and a delimited string, split with tokenize
import java.util.List;
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.impl.DefaultCamelContext;
public class SplitBasics {
static class Routes extends RouteBuilder {
@Override
public void configure() {
from("direct:list")
.split(body())
.process(SplitBasics::show)
.end()
.process(e -> System.out.println(" after split, body = "
+ e.getMessage().getBody()));
from("direct:csv")
.split(body().tokenize(","))
.process(SplitBasics::show)
.end();
}
}
static void show(Exchange e) {
System.out.printf(" item %-6s index=%s size=%s complete=%s%n",
e.getMessage().getBody(),
e.getProperty(Exchange.SPLIT_INDEX),
e.getProperty(Exchange.SPLIT_SIZE),
e.getProperty(Exchange.SPLIT_COMPLETE));
}
public static void main(String[] args) throws Exception {
CamelContext camel = new DefaultCamelContext();
camel.addRoutes(new Routes());
camel.start();
ProducerTemplate template = camel.createProducerTemplate();
System.out.println("split(body()) on a List:");
Object reply = template.requestBody("direct:list", List.of("apple", "pear", "fig"));
System.out.println(" caller got " + reply);
System.out.println("split(body().tokenize(\",\")) on a String:");
template.sendBody("direct:csv", "red,green,blue");
camel.stop();
}
}
split(body()) on a List:
item apple index=0 size=3 complete=false
item pear index=1 size=3 complete=false
item fig index=2 size=3 complete=true
after split, body = [apple, pear, fig]
caller got [apple, pear, fig]
split(body().tokenize(",")) on a String:
item red index=0 size=3 complete=false
item green index=1 size=3 complete=false
item blue index=2 size=3 complete=true
- Each item ran through the inner step separately, with
counting from 0 andCamelSplitIndex at 3.CamelSplitSize was true only for the last item,CamelSplitComplete . Use it to do something once at the end of a batch, such as closing a file.fig- After
, the body was the original list again, and the caller receivedend() . Without an aggregation strategy, nothing done inside the split changes the message that continues.[apple, pear, fig] splittokenize(",") into three strings and produced the same properties.red,green,blue
The split properties are exchange properties, not headers, so they do not leak into outgoing messages. Read them in Simple as ${exchangeProperty.CamelSplitIndex}
Combining the results with an AggregationStrategy
When the parts produce results the route needs, give the splitter an AggregationStrategy
import java.util.List;
import java.util.Map;
import org.apache.camel.AggregationStrategy;
import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.AggregationStrategies;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
public class SplitAggregate {
static final Map<String, Integer> PRICES = Map.of("apple", 30, "pear", 45, "fig", 80);
static class SumPrices implements AggregationStrategy {
@Override
public Exchange aggregate(Exchange oldExchange, Exchange newExchange) {
int price = newExchange.getMessage().getBody(Integer.class);
if (oldExchange == null) {
return newExchange;
}
int total = oldExchange.getMessage().getBody(Integer.class) + price;
oldExchange.getMessage().setBody(total);
return oldExchange;
}
}
static class Routes extends RouteBuilder {
@Override
public void configure() {
from("direct:total")
.split(body(), new SumPrices())
.process(e -> e.getMessage().setBody(
PRICES.get(e.getMessage().getBody(String.class))))
.end()
.setBody(simple("total=${body}"));
from("direct:grouped")
.split(body(), AggregationStrategies.groupedBody())
.transform(simple("${body.toUpperCase()}"))
.end();
}
}
public static void main(String[] args) throws Exception {
CamelContext camel = new DefaultCamelContext();
camel.addRoutes(new Routes());
camel.start();
ProducerTemplate template = camel.createProducerTemplate();
List<String> basket = List.of("apple", "pear", "fig");
System.out.println("custom strategy : " + template.requestBody("direct:total", basket));
Object grouped = template.requestBody("direct:grouped", basket);
System.out.println("groupedBody() : " + grouped + " ("
+ grouped.getClass().getSimpleName() + ")");
camel.stop();
}
}
custom strategy : total=155
groupedBody() : [APPLE, PEAR, FIG] (GroupedExchangeList)
gotSumPrices asnull for the first part, so it returned that part's exchange, with body 30. For the next parts, it added 45 and 80 to the running total, givingoldExchange after the split.total=155 collected the result bodies into a list, hereAggregationStrategies.groupedBody() . The list's class is[APPLE, PEAR, FIG] , Camel's ownGroupedExchangeList type.List
Camel calls the strategy for one part at a time, synchronizing the calls even with parallelProcessing()parallelAggregate()newExchange.getException()
Processing the parts in parallel
By default the parts run one after another on the thread that started the split. parallelProcessing()
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.IntStream;
import org.apache.camel.CamelContext;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.AggregationStrategies;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
public class SplitParallel {
static final Set<String> THREADS = ConcurrentHashMap.newKeySet();
static class Routes extends RouteBuilder {
@Override
public void configure() {
from("direct:sequential")
.split(body(), AggregationStrategies.groupedBody())
.to("direct:work")
.end();
from("direct:parallel")
.split(body(), AggregationStrategies.groupedBody()).parallelProcessing()
.to("direct:work")
.end();
from("direct:work")
.process(e -> {
THREADS.add(Thread.currentThread().getName());
int n = e.getMessage().getBody(Integer.class);
Thread.sleep(100 + (n % 3) * 50);
e.getMessage().setBody(n * n);
});
}
}
public static void main(String[] args) throws Exception {
CamelContext camel = new DefaultCamelContext();
camel.addRoutes(new Routes());
camel.start();
ProducerTemplate template = camel.createProducerTemplate();
List<Integer> numbers = IntStream.rangeClosed(1, 20).boxed().toList();
template.requestBody("direct:parallel", numbers);
for (String mode : new String[] {"sequential", "parallel"}) {
THREADS.clear();
long start = System.nanoTime();
Object squares = template.requestBody("direct:" + mode, numbers);
long ms = (System.nanoTime() - start) / 1000000;
System.out.println(mode + ": " + squares);
System.out.println(" threads used: " + THREADS.size() + ", about "
+ Math.round(ms / 100.0) / 10.0 + " s");
}
camel.stop();
}
}
sequential: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400]
threads used: 1, about 3.1 s
parallel: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400]
threads used: 10, about 0.4 s
- Both runs returned the squares in input order. Camel aggregates parallel results in the order of the parts, not the order they finish, unless
is also set.streaming() - The sequential split used one thread, and its time was the sum of the twenty delays.
- The parallel split used 10 threads, the pool size of Camel's default thread pool profile, and finished several times faster (rough comparison, on a shared Linux container). With 20 parts and 10 threads, two rounds of work set the lower bound.
Parallel splitting helps when each part waits on I/O, such as an HTTP call or a database insert. Give it its own pool with executorService(...)
Streaming large inputs
By default the splitter builds the full list of parts before processing the first one, which for a large file means holding every line in memory. streaming()
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
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.impl.DefaultCamelContext;
public class SplitStreaming {
static class Routes extends RouteBuilder {
@Override
public void configure() {
from("direct:streaming")
.split(body().tokenize("\n")).streaming()
.process(e -> System.out.printf(" %-8s index=%s size=%s%n",
e.getMessage().getBody(), e.getProperty(Exchange.SPLIT_INDEX),
e.getProperty(Exchange.SPLIT_SIZE)))
.end();
from("direct:groups")
.split(body().tokenize("\n", 4, false)).streaming()
.process(e -> System.out.println(" chunk " + e.getProperty(
Exchange.SPLIT_INDEX) + ": " + e.getMessage().getBody(String.class)
.replace("\n", " | ")))
.end();
}
}
public static void main(String[] args) throws Exception {
Path file = Files.createTempFile("orders", ".txt");
Files.writeString(file, IntStream.rangeClosed(1, 10).mapToObj(i -> "order-" + i)
.collect(Collectors.joining("\n")));
CamelContext camel = new DefaultCamelContext();
camel.addRoutes(new Routes());
camel.start();
ProducerTemplate template = camel.createProducerTemplate();
System.out.println("streaming() over a File body, first and last lines:");
template.sendBody("direct:streaming", file.toFile());
System.out.println("tokenize(\"\\n\", 4, false): four lines per exchange");
template.sendBody("direct:groups", file.toFile());
camel.stop();
Files.delete(file);
}
}
streaming() over a File body, first and last lines:
order-1 index=0 size=null
order-2 index=1 size=null
order-3 index=2 size=null
order-4 index=3 size=null
order-5 index=4 size=null
order-6 index=5 size=null
order-7 index=6 size=null
order-8 index=7 size=null
order-9 index=8 size=null
order-10 index=9 size=10
tokenize("\n", 4, false): four lines per exchange
chunk 0: order-1 | order-2 | order-3 | order-4
chunk 1: order-5 | order-6 | order-7 | order-8
chunk 2: order-9 | order-10
- The body was a
.java.io.File read the file as it went and returned the lines one at a time.tokenize("\n") wasCamelSplitSize for the first nine lines and 10 for the last. While streaming, the splitter does not know the total until it reaches the end, so code that needs the size must wait fornull .CamelSplitComplete grouped four lines per exchange, so the ten lines became three exchanges with 4, 4 and 2 lines. The third argument istokenize("\n", 4, false) , which drops the first line, such as a CSV header.skipFirst
Groups are the usual way to load a big file into a database: one insert of 500 rows is much cheaper than 500 inserts of one row. Streaming keeps memory flat only if the body is a stream or a file. A body that is already a 2 GB StringFile
When a part fails
A batch with bad rows is normal, so it is worth deciding what one failing part should do to the rest. This program imports five rows, two of which fail, first with the default settings and then with stopOnException()
import java.util.List;
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.impl.DefaultCamelContext;
public class SplitErrors {
static class Routes extends RouteBuilder {
@Override
public void configure() {
errorHandler(defaultErrorHandler().logExhausted(false));
from("direct:default")
.split(body())
.to("direct:import")
.end();
from("direct:stopOnException")
.split(body()).stopOnException()
.to("direct:import")
.end();
from("direct:import")
.process(e -> {
String row = e.getMessage().getBody(String.class);
if (row.startsWith("bad")) {
throw new IllegalArgumentException("cannot import " + row);
}
System.out.println(" imported " + row);
});
}
}
public static void main(String[] args) throws Exception {
CamelContext camel = new DefaultCamelContext();
camel.addRoutes(new Routes());
camel.start();
ProducerTemplate template = camel.createProducerTemplate();
List<String> rows = List.of("row1", "bad2", "row3", "bad4", "row5");
for (String mode : new String[] {"default", "stopOnException"}) {
System.out.println(mode + ":");
Exchange result = template.send("direct:" + mode,
e -> e.getMessage().setBody(rows));
Exception error = result.getException();
System.out.println(" exchange failed: " + result.isFailed() + ", "
+ error.getClass().getSimpleName());
System.out.println(" message: " + error.getMessage());
}
camel.stop();
}
}
default:
imported row1
imported row3
imported row5
exchange failed: true, IllegalArgumentException
message: cannot import bad4
stopOnException:
imported row1
exchange failed: true, CamelExchangeException
message: Multicast processing failed for number 1. Exchange[]. Caused by: [java.lang.IllegalArgumentException - cannot import bad2]
- By default, the splitter carried on after
failed and importedbad2 androw3 . At the end, the whole exchange was marked failed with the last exception,row5 . The failure ofcannot import bad4 is not reported at all.bad2 - With
, the split stopped atstopOnException() , sobad2 androw3 were never imported. The exception is arow5 that names the failing part,CamelExchangeException , counting from 0, and wraps the cause.number 1
Neither default suits every batch. To import what you can and report every failure, catch the failure per part with an onException(...).handled(true)shareUnitOfWork()
Splitting XML
XML has two options with very different costs. tokenizeXML
import org.apache.camel.CamelContext;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.support.builder.Namespaces;
public class SplitXml {
static final String XML = """
<orders xmlns="urn:shop">
<order id="1"><item>book</item></order>
<order id="2"><item>lamp</item></order>
<order id="3"><item>desk</item></order>
</orders>
""";
static final Namespaces SHOP = new Namespaces("s", "urn:shop");
static class Routes extends RouteBuilder {
@Override
public void configure() {
from("direct:tokenizeXML")
.split().tokenizeXML("order", "orders").streaming()
.process(e -> System.out.println(" " + e.getMessage().getBody()))
.end();
from("direct:xpath")
.split().xpath("/s:orders/s:order[@id > 1]/s:item/text()", SHOP)
.process(e -> System.out.println(" " + e.getMessage()
.getBody(String.class)))
.end();
}
}
public static void main(String[] args) throws Exception {
CamelContext camel = new DefaultCamelContext();
camel.addRoutes(new Routes());
camel.start();
ProducerTemplate template = camel.createProducerTemplate();
System.out.println("tokenizeXML(\"order\", \"orders\"):");
template.sendBody("direct:tokenizeXML", XML);
System.out.println("xpath on items of orders with id > 1:");
template.sendBody("direct:xpath", XML);
camel.stop();
}
}
tokenizeXML("order", "orders"):
<order id="1" xmlns="urn:shop"><item>book</item></order>
<order id="2" xmlns="urn:shop"><item>lamp</item></order>
<order id="3" xmlns="urn:shop"><item>desk</item></order>
xpath on items of orders with id > 1:
lamp
desk
returned eachtokenizeXML("order", "orders") element as text. The second argument named the parent element whose namespace declarations are copied in, which is why each part carries<order> and is a valid document on its own.xmlns="urn:shop"- The XPath expression selected only the items of orders with
greater than 1, so it returnedid andlamp . It needed thedesk prefix mapped to the namespace, because the document uses a default namespace.s
Use tokenizeXMLstreaming()
Choosing splitter options
| Situation | Setting |
|---|---|
| Process the items of a collection one by one | split(body()) |
| Need the results of the parts afterwards | split(expression, strategy)AggregationStrategies.groupedBody() |
| Large file or stream | streaming()File |
| Bulk load into a database | tokenize("\n", 500, false)streaming()true |
| Parts that wait on I/O | parallelProcessing()executorService |
| One bad part should abort the batch | stopOnException() |
| Import what you can and report every failure | Per-part onException |
| Large XML | tokenizeXMLstreaming() |
The splitter's partner is the