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() as an exchange of its own.

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, Splitter extends MulticastProcessor, which is why error messages from a split sometimes mention multicast. The splitter does four things for each part:

  1. It gets the next item from the expression. A List, an array, an Iterator or a Stream is used directly, and other bodies are converted to an iterator.
  2. 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.
  3. It sets the exchange properties CamelSplitIndex, CamelSplitSize and CamelSplitComplete on the copy.
  4. It runs the copy through the steps inside the split, and passes the result to an AggregationStrategy if one is configured.

After the last part, the route continues with the original message, or with the aggregated result when there is a strategy.

Common split expressions
ExpressionSplitsBest for
split(body())A List, array, Iterable or Iterator bodyBodies that are already collections
split(body().tokenize(","))Text by a delimiterLines and simple delimited data
split(body().tokenize("\n", 100, false))Text in groups of linesBatch inserts of large files
split().tokenizeXML("order", "orders")XML elements, without building a DOMLarge XML documents
split().xpath(...)Nodes selected by XPathSmaller XML documents that need real queries
split().jsonpath("$.items[*]")JSON array elements (camel-jsonpath)JSON bodies
split(method(bean, "parts"))Whatever a Java method returnsSplitting 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. Three items in each make the split properties easy to follow:

Java
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();
    }
}
Output
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 CamelSplitIndex counting from 0 and CamelSplitSize at 3.
  • CamelSplitComplete was true only for the last item, fig. Use it to do something once at the end of a batch, such as closing a file.
  • After end(), the body was the original list again, and the caller received [apple, pear, fig]. Without an aggregation strategy, nothing done inside the split changes the message that continues.
  • tokenize(",") split red,green,blue into three strings and produced the same properties.

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. The first route looks up the price of each fruit and adds them up; the second uppercases each item and collects the results with a built-in strategy:

Java
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();
    }
}
Output
custom strategy : total=155
groupedBody()   : [APPLE, PEAR, FIG] (GroupedExchangeList)
  • SumPrices got null as oldExchange 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, giving total=155 after the split.
  • AggregationStrategies.groupedBody() collected the result bodies into a list, here [APPLE, PEAR, FIG]. The list's class is GroupedExchangeList, Camel's own List type.

Camel calls the strategy for one part at a time, synchronizing the calls even with parallelProcessing(), so it does not need to be thread-safe. Set parallelAggregate() only when the strategy is thread-safe and slow enough to matter. A strategy also decides what happens to failures: newExchange.getException() holds the part's exception, and a strategy that clears it and records the failure lets the split carry on with a partial result.

Processing the parts in parallel

By default the parts run one after another on the thread that started the split. parallelProcessing() hands them to a thread pool. Twenty numbers, each taking 100 to 200 ms to square, show the difference:

Java
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();
    }
}
Output
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 streaming() is also set.
  • 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(...) so that one large split does not take every thread from the rest of the application, and size the pool to what the downstream system can take. When the downstream service limits calls per second, combine the split with the throttler.

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() processes each part as it is read. A ten-line file shows what changes:

Java
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);
    }
}
Output
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. tokenize("\n") read the file as it went and returned the lines one at a time.
  • CamelSplitSize was null 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 for CamelSplitComplete.
  • tokenize("\n", 4, false) grouped four lines per exchange, so the ten lines became three exchanges with 4, 4 and 2 lines. The third argument is skipFirst, which drops the first line, such as a CSV header.

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 String is in memory before the splitter starts, so read files with the file component and pass the File on unconverted.

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():

Java
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();
    }
}
Output
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 bad2 failed and imported row3 and row5. At the end, the whole exchange was marked failed with the last exception, cannot import bad4. The failure of bad2 is not reported at all.
  • With stopOnException(), the split stopped at bad2, so row3 and row5 were never imported. The exception is a CamelExchangeException that names the failing part, number 1, counting from 0, and wraps the cause.

Neither default suits every batch. To import what you can and report every failure, catch the failure per part with an onException(...).handled(true) that records the row, or let an aggregation strategy collect the exceptions. Error handlers apply to each part separately: redelivery retries the failing part, not the whole batch. By default each part has its own unit of work; shareUnitOfWork() makes the parts share the parent's instead. The error handling page covers these options.

Splitting XML

XML has two options with very different costs. tokenizeXML scans the text for element tags and never parses the whole document. XPath parses the document into a DOM and can then select nodes with any query. The same document goes through both:

Java
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();
    }
}
Output
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
  • tokenizeXML("order", "orders") returned each <order> element as text. The second argument named the parent element whose namespace declarations are copied in, which is why each part carries xmlns="urn:shop" and is a valid document on its own.
  • The XPath expression selected only the items of orders with id greater than 1, so it returned lamp and desk. It needed the s prefix mapped to the namespace, because the document uses a default namespace.

Use tokenizeXML with streaming() for large files, where it keeps memory flat. Use XPath when you need conditions or nested paths, and the document fits comfortably in memory several times over, since a DOM takes much more memory than the text.

Choosing splitter options

Splitter settings for common situations
SituationSetting
Process the items of a collection one by onesplit(body())
Need the results of the parts afterwardssplit(expression, strategy), or AggregationStrategies.groupedBody()
Large file or streamstreaming() with a File or stream body
Bulk load into a databasetokenize("\n", 500, false) with streaming(), or true to skip a header line
Parts that wait on I/OparallelProcessing() with its own executorService
One bad part should abort the batchstopOnException()
Import what you can and report every failurePer-part onException or a strategy that collects exceptions
Large XMLtokenizeXML with streaming()

The splitter's partner is the aggregator, which collects separate messages back into one; a strategy on the splitter is the simpler choice when the parts come from a single message. For the other fan-out patterns, see multicast and the other EIPs.