camel-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From "Claus Ibsen (Confluence)" <conflue...@apache.org>
Subject [CONF] Apache Camel > Aggregator2
Date Tue, 20 Aug 2013 11:27:00 GMT
<html>
<head>
    <base href="https://cwiki.apache.org/confluence">
            <link rel="stylesheet" href="/confluence/s/en/2176/1/1/_/styles/combined.css?spaceKey=CAMEL&amp;forWysiwyg=true" type="text/css">
    </head>
<body style="background: white;" bgcolor="white" class="email-body">
<div id="pageContent">
<div id="notificationFormat">
<div class="wiki-content">
<div class="email">
    <h2><a href="https://cwiki.apache.org/confluence/display/CAMEL/Aggregator2">Aggregator2</a></h2>
    <h4>Page <b>edited</b> by             <a href="https://cwiki.apache.org/confluence/display/~davsclaus">Claus Ibsen</a>
    </h4>
        <br/>
                         <h4>Changes (8)</h4>
                                 
    
<div id="page-diffs">
                    <table class="diff" cellpadding="0" cellspacing="0">
    
            <tr><td class="diff-snipped" >...<br></td></tr>
            <tr><td class="diff-unchanged" >h4. Aggregating when no data <br> <br></td></tr>
            <tr><td class="diff-deleted-lines" style="color:#999;background-color:#fdd;text-decoration:line-through;">By default when using POJOs as AggregationStrategy, then the method is *only* invoked when there is data to be aggregated. Where as without using POJOs then you may have {{null}} as {{oldExchange}} or {{newExchange}} parameters.  <br></td></tr>
            <tr><td class="diff-added-lines" style="background-color: #dfd;">By default when using POJOs as AggregationStrategy, then the method is *only* invoked when there is data to be aggregated (by default). You can use the option {{strategyMethodAllowNull}} to configure this. Where as without using POJOs then you may have {{null}} as {{oldExchange}} or {{newExchange}} parameters. For example the [Aggregate|Aggregator2] EIP will invoke the {{AggregationStrategy}} with {{oldExchange}} as null, for the first [Exchange] incoming to the aggregator. And then for subsequent [Exchange]s then {{oldExchange}} and {{newExchange}} parameters are both not null.  <br></td></tr>
            <tr><td class="diff-unchanged" > <br></td></tr>
            <tr><td class="diff-deleted-lines" style="color:#999;background-color:#fdd;text-decoration:line-through;">For example the [Aggregate|Aggregator2] EIP will invoke the {{AggregationStrategy}} with {{oldExchange}} as null, for the first [Exchange] incoming to the aggregator. And then for subsequent [Exchange]s then {{oldExchange}} and {{newExchange}} parameters are both not null.  <br> <br></td></tr>
            <tr><td class="diff-unchanged" >h5. Example with [Content Enricher] and no data <br>Though with POJOs as AggregationStrategy we made this simpler and only call the method when {{oldExchange}} and {{newExchange}} is not null, as that would be the most common use-case. If you need to allow {{oldExchange}} or {{newExchange}} to be null, then you can configure this with the POJO using the {{AggregationStrategyBeanAdapter}} as shown below. On the bean adapter we call {{setAllowNullNewExchange}} to allow the new exchange to be null. <br></td></tr>
            <tr><td class="diff-snipped" >...<br></td></tr>
            <tr><td class="diff-unchanged" >    public void configure() throws Exception { <br>        AggregationStrategyBeanAdapter myStrategy = new AggregationStrategyBeanAdapter(appender, &quot;append&quot;); <br></td></tr>
            <tr><td class="diff-added-lines" style="background-color: #dfd;">        myStrategy.setAllowNullOldExchange(true); <br></td></tr>
            <tr><td class="diff-unchanged" >        myStrategy.setAllowNullNewExchange(true); <br> <br></td></tr>
            <tr><td class="diff-snipped" >...<br></td></tr>
            <tr><td class="diff-unchanged" >{code} <br> <br></td></tr>
            <tr><td class="diff-added-lines" style="background-color: #dfd;">This can be configured a bit easier using the {{beanAllowNull}} method from {{AggregationStrategies}} as shown: <br>{code} <br>    public void configure() throws Exception { <br>        from(&quot;direct:start&quot;) <br>            .pollEnrich(&quot;seda:foo&quot;, 1000, AggregationStrategies.beanAllowNull(appender, &quot;append&quot;)) <br>                .to(&quot;mock:result&quot;); <br>    } <br>{code} <br> <br> <br></td></tr>
            <tr><td class="diff-unchanged" >Then the {{append}} method in the POJO would need to deal with the situation that {{newExchange}} can be null: <br>{code} <br></td></tr>
            <tr><td class="diff-snipped" >...<br></td></tr>
            <tr><td class="diff-unchanged" >In the example above we use the [Content Enricher] EIP using {{pollEnrich}}. The {{newExchange}} will be null in the situation we could not get any data from the &quot;seda:foo&quot; endpoint, and therefore the timeout was hit after 1 second. So if we need to do some special merge logic we would need to set {{setAllowNullNewExchange=true}}, so the {{append}} method will be invoked. If we do not do that then when the timeout was hit, then the append method would normally not be invoked, meaning the [Content Enricher] did not merge/change the message.  <br> <br></td></tr>
            <tr><td class="diff-deleted-lines" style="color:#999;background-color:#fdd;text-decoration:line-through;">There is also a method {{setAllowNullOldExchange}} to set whether the {{oldExchange}} is allowed to be null. <br></td></tr>
            <tr><td class="diff-added-lines" style="background-color: #dfd;">In XML DSL you would configure the {{strategyMethodAllowNull}} option and set it to true as shown below: <br>{code:xml} <br>    &lt;camelContext xmlns=&quot;http://camel.apache.org/schema/spring&quot;&gt; <br>        &lt;route&gt; <br>            &lt;from uri=&quot;direct:start&quot;/&gt; <br>            &lt;aggregate strategyRef=&quot;myAppender&quot; strategyMethodName=&quot;append&quot; strategyMethodAllowNull=&quot;true&quot; completionSize=&quot;3&quot;&gt; <br>                &lt;correlationExpression&gt; <br>                    &lt;constant&gt;true&lt;/constant&gt; <br>                &lt;/correlationExpression&gt; <br>                &lt;to uri=&quot;mock:result&quot;/&gt; <br>            &lt;/aggregate&gt; <br>        &lt;/route&gt; <br>    &lt;/camelContext&gt; <br>{code} <br></td></tr>
            <tr><td class="diff-unchanged" > <br></td></tr>
            <tr><td class="diff-added-lines" style="background-color: #dfd;">h5. Different body types <br> <br>When for example using {{strategyMethodAllowNull}} as true, then the parameter types of the message bodies does not have to be the same. For example suppose we want to aggregate from a {{com.foo.User}} type to a {{List&lt;String&gt;}} that contains the user name. We could code a POJO doing this as follows: <br>{code} <br>    public static final class MyUserAppender { <br> <br>        public List addUsers(List names, User user) { <br>            if (names == null) { <br>                names = new ArrayList(); <br>            } <br>            names.add(user.getName()); <br>            return names; <br>        } <br>    } <br>{code} <br> <br>Notice that the return type is a List which we want to contain the user names. The 1st parameter is the list of names, and then notice the 2nd parameter is the incoming {{com.foo.User}} type. <br> <br></td></tr>
            <tr><td class="diff-unchanged" >h3. See also <br>- The [Loan Broker Example] which uses an aggregator <br></td></tr>
            <tr><td class="diff-snipped" >...<br></td></tr>
    
            </table>
    </div>                            <h4>Full Content</h4>
                    <div class="notificationGreySide">
        <h3><a name="Aggregator2-Aggregator"></a>Aggregator</h3>

<p><b>This applies for Camel version 2.3 or newer. If you use an older version then use this <a href="/confluence/display/CAMEL/Aggregator" title="Aggregator">Aggregator</a> link instead.</b></p>

<p>The <a href="http://www.enterpriseintegrationpatterns.com/Aggregator.html" class="external-link" rel="nofollow">Aggregator</a> from the <a href="/confluence/display/CAMEL/Enterprise+Integration+Patterns" title="Enterprise Integration Patterns">EIP patterns</a> allows you to combine a number of messages together into a single message. </p>

<p><span class="image-wrap" style=""><img src="http://www.enterpriseintegrationpatterns.com/img/Aggregator.gif" style="border: 0px solid black" /></span></p>

<p>A correlation <a href="/confluence/display/CAMEL/Expression" title="Expression">Expression</a> is used to determine the messages which should be aggregated together. If you want to aggregate all messages into a single message, just use a constant expression. An AggregationStrategy is used to combine all the message exchanges for a single correlation key into a single message exchange. </p>

<h3><a name="Aggregator2-Aggregatoroptions"></a>Aggregator options</h3>
<p>The aggregator supports the following options:</p>
<div class="confluenceTableSmall"><div class='table-wrap'>
<table class='confluenceTable'><tbody>
<tr>
<th class='confluenceTh'> Option </th>
<th class='confluenceTh'> Default </th>
<th class='confluenceTh'> Description </th>
</tr>
<tr>
<td class='confluenceTd'> correlationExpression </td>
<td class='confluenceTd'>&nbsp;</td>
<td class='confluenceTd'> Mandatory <a href="/confluence/display/CAMEL/Expression" title="Expression">Expression</a> which evaluates the correlation key to use for aggregation. The <a href="/confluence/display/CAMEL/Exchange" title="Exchange">Exchange</a> which has the same correlation key is aggregated together. If the correlation key could not be evaluated an Exception is thrown. You can disable this by using the <tt>ignoreBadCorrelationKeys</tt> option. </td>
</tr>
<tr>
<td class='confluenceTd'> aggregationStrategy </td>
<td class='confluenceTd'>&nbsp;</td>
<td class='confluenceTd'> Mandatory <tt>AggregationStrategy</tt> which is used to <em>merge</em> the incoming <a href="/confluence/display/CAMEL/Exchange" title="Exchange">Exchange</a> with the existing already merged exchanges. At first call the <tt>oldExchange</tt> parameter is <tt>null</tt>. On subsequent invocations the <tt>oldExchange</tt> contains the merged exchanges and <tt>newExchange</tt> is of course the new incoming Exchange. From <b>Camel 2.9.2</b> onwards the strategy can also be a <tt>TimeoutAwareAggregationStrategy</tt> implementation, supporting the timeout callback, see further below for more details. </td>
</tr>
<tr>
<td class='confluenceTd'> strategyRef </td>
<td class='confluenceTd'>&nbsp;</td>
<td class='confluenceTd'> A reference to lookup the <tt>AggregationStrategy</tt> in the <a href="/confluence/display/CAMEL/Registry" title="Registry">Registry</a>. From <b>Camel 2.12</b> onwards you can also use a POJO as the <tt>AggregationStrategy</tt>, see further below for details. </td>
</tr>
<tr>
<td class='confluenceTd'> strategyMethodName </td>
<td class='confluenceTd'>&nbsp;</td>
<td class='confluenceTd'> <b>Camel 2.12:</b> This option can be used to explicit declare the method name to use, when using POJOs as the <tt>AggregationStrategy</tt>. See further below for more details. </td>
</tr>
<tr>
<td class='confluenceTd'> strategyMethodAllowNull </td>
<td class='confluenceTd'> <tt>false</tt> </td>
<td class='confluenceTd'> <b>Camel 2.12:</b> If this option is <tt>false</tt> then the aggregate method is not used for the very first aggregation. If this option is <tt>true</tt> then <tt>null</tt> values is used as the <tt>oldExchange</tt> (at the very first aggregation), when using POJOs as the <tt>AggregationStrategy</tt>. See further below for more details. </td>
</tr>
<tr>
<td class='confluenceTd'> completionSize </td>
<td class='confluenceTd'>&nbsp;</td>
<td class='confluenceTd'> Number of messages aggregated before the aggregation is complete. This option can be set as either a fixed value or using an <a href="/confluence/display/CAMEL/Expression" title="Expression">Expression</a> which allows you to evaluate a size dynamically - will use <tt>Integer</tt> as result. If both are set Camel will fallback to use the fixed value if the <a href="/confluence/display/CAMEL/Expression" title="Expression">Expression</a> result was <tt>null</tt> or <tt>0</tt>. </td>
</tr>
<tr>
<td class='confluenceTd'> completionTimeout </td>
<td class='confluenceTd'>&nbsp;</td>
<td class='confluenceTd'> Time in millis that an aggregated exchange should be inactive before its complete. This option can be set as either a fixed value or using an <a href="/confluence/display/CAMEL/Expression" title="Expression">Expression</a> which allows you to evaluate a timeout dynamically - will use <tt>Long</tt> as result. If both are set Camel will fallback to use the fixed value if the <a href="/confluence/display/CAMEL/Expression" title="Expression">Expression</a> result was <tt>null</tt> or <tt>0</tt>. You cannot use this option together with completionInterval, only one of the two can be used. </td>
</tr>
<tr>
<td class='confluenceTd'> completionInterval </td>
<td class='confluenceTd'>&nbsp;</td>
<td class='confluenceTd'> A repeating period in millis by which the aggregator will complete all current aggregated exchanges. Camel has a background task which is triggered every period. You cannot use this option together with completionTimeout, only one of them can be used. </td>
</tr>
<tr>
<td class='confluenceTd'> completionPredicate </td>
<td class='confluenceTd'>&nbsp;</td>
<td class='confluenceTd'> A <a href="/confluence/display/CAMEL/Predicate" title="Predicate">Predicate</a> to indicate when an aggregated exchange is complete. </td>
</tr>
<tr>
<td class='confluenceTd'> completionFromBatchConsumer </td>
<td class='confluenceTd'> <tt>false</tt> </td>
<td class='confluenceTd'> This option is if the exchanges are coming from a <a href="/confluence/display/CAMEL/Batch+Consumer" title="Batch Consumer">Batch Consumer</a>. Then when enabled the <a href="/confluence/display/CAMEL/Aggregator2" title="Aggregator2">Aggregator2</a> will use the batch size determined by the <a href="/confluence/display/CAMEL/Batch+Consumer" title="Batch Consumer">Batch Consumer</a> in the message header <tt>CamelBatchSize</tt>. See more details at <a href="/confluence/display/CAMEL/Batch+Consumer" title="Batch Consumer">Batch Consumer</a>. This can be used to aggregate all files consumed from a <a href="/confluence/display/CAMEL/File2" title="File2">File</a> endpoint in that given poll. </td>
</tr>
<tr>
<td class='confluenceTd'> forceCompletionOnStop </td>
<td class='confluenceTd'> <tt>false</tt> </td>
<td class='confluenceTd'> <b>Camel 2.9</b> Indicates to complete all current aggregated exchanges when the context is stopped </td>
</tr>
<tr>
<td class='confluenceTd'> eagerCheckCompletion </td>
<td class='confluenceTd'> <tt>false</tt> </td>
<td class='confluenceTd'> Whether or not to eager check for completion when a new incoming <a href="/confluence/display/CAMEL/Exchange" title="Exchange">Exchange</a> has been received. This option influences the behavior of the <tt>completionPredicate</tt> option as the <a href="/confluence/display/CAMEL/Exchange" title="Exchange">Exchange</a> being passed in changes accordingly. When <tt>false</tt> the <a href="/confluence/display/CAMEL/Exchange" title="Exchange">Exchange</a> passed in the <a href="/confluence/display/CAMEL/Predicate" title="Predicate">Predicate</a> is the <em>aggregated</em> Exchange which means any information you may store on the aggregated Exchange from the <tt>AggregationStrategy</tt> is available for the <a href="/confluence/display/CAMEL/Predicate" title="Predicate">Predicate</a>. When <tt>true</tt> the <a href="/confluence/display/CAMEL/Exchange" title="Exchange">Exchange</a> passed in the <a href="/confluence/display/CAMEL/Predicate" title="Predicate">Predicate</a> is the <em>incoming</em> <a href="/confluence/display/CAMEL/Exchange" title="Exchange">Exchange</a>, which means you can access data from the incoming Exchange. </td>
</tr>
<tr>
<td class='confluenceTd'> groupExchanges </td>
<td class='confluenceTd'> <tt>false</tt> </td>
<td class='confluenceTd'> If enabled then Camel will group all aggregated Exchanges into a single combined <tt>org.apache.camel.impl.GroupedExchange</tt> holder class that holds all the aggregated Exchanges. And as a result only one Exchange is being sent out from the aggregator. Can be used to combine many incoming Exchanges into a single output Exchange without coding a custom <tt>AggregationStrategy</tt> yourself. <b>Important:</b> This option does <b>not</b> support persistant repository with the aggregator. </td>
</tr>
<tr>
<td class='confluenceTd'> ignoreInvalidCorrelationKeys </td>
<td class='confluenceTd'> <tt>false</tt> </td>
<td class='confluenceTd'> Whether or not to ignore correlation keys which could not be evaluated to a value. By default Camel will throw an Exception, but you can enable this option and ignore the situation instead. </td>
</tr>
<tr>
<td class='confluenceTd'> closeCorrelationKeyOnCompletion </td>
<td class='confluenceTd'>&nbsp;</td>
<td class='confluenceTd'> Whether or not too <em>late</em> Exchanges should be accepted or not. You can enable this to indicate that if a correlation key has already been completed, then any new exchanges with the same correlation key be denied. Camel will then throw a <tt>closedCorrelationKeyException</tt> exception. When using this option you pass in a <tt>integer</tt> which is a number for a LRUCache which keeps that last X number of closed correlation keys. You can pass in 0 or a negative value to indicate a unbounded cache. By passing in a number you are ensured that cache won't grow too big if you use a log of different correlation keys. </td>
</tr>
<tr>
<td class='confluenceTd'> discardOnCompletionTimeout </td>
<td class='confluenceTd'> <tt>false</tt> </td>
<td class='confluenceTd'> <b>Camel 2.5:</b> Whether or not exchanges which complete due to a timeout should be discarded. If enabled then when a timeout occurs the aggregated message will <b>not</b> be sent out but dropped (discarded). </td>
</tr>
<tr>
<td class='confluenceTd'> aggregationRepository </td>
<td class='confluenceTd'>&nbsp;</td>
<td class='confluenceTd'> Allows you to plugin you own implementation of <tt>org.apache.camel.spi.AggregationRepository</tt> which keeps track of the current inflight aggregated exchanges. Camel uses by default a memory based implementation. </td>
</tr>
<tr>
<td class='confluenceTd'> aggregationRepositoryRef </td>
<td class='confluenceTd'>&nbsp;</td>
<td class='confluenceTd'> Reference to lookup a <tt>aggregationRepository</tt> in the <a href="/confluence/display/CAMEL/Registry" title="Registry">Registry</a>. </td>
</tr>
<tr>
<td class='confluenceTd'> parallelProcessing </td>
<td class='confluenceTd'> <tt>false</tt> </td>
<td class='confluenceTd'> When aggregated are completed they are being send out of the aggregator. This option indicates whether or not Camel should use a thread pool with multiple threads for concurrency. If no custom thread pool has been specified then Camel creates a default pool with 10 concurrent threads. </td>
</tr>
<tr>
<td class='confluenceTd'> executorService </td>
<td class='confluenceTd'>&nbsp;</td>
<td class='confluenceTd'> If using <tt>parallelProcessing</tt> you can specify a custom thread pool to be used. In fact also if you are not using <tt>parallelProcessing</tt> this custom thread pool is used to send out aggregated exchanges as well. </td>
</tr>
<tr>
<td class='confluenceTd'> executorServiceRef </td>
<td class='confluenceTd'>&nbsp;</td>
<td class='confluenceTd'> Reference to lookup a <tt>executorService</tt> in the <a href="/confluence/display/CAMEL/Registry" title="Registry">Registry</a> </td>
</tr>
<tr>
<td class='confluenceTd'> timeoutCheckerExecutorService </td>
<td class='confluenceTd'>&nbsp;</td>
<td class='confluenceTd'> <b>Camel 2.9:</b> If using either of the <tt>completionTimeout</tt>, <tt>completionTimeoutExpression</tt>, or <tt>completionInterval</tt> options a background thread is created to check for the completion for every aggregator. Set this option to provide a custom thread pool to be used rather than creating a new thread for every aggregator. </td>
</tr>
<tr>
<td class='confluenceTd'> timeoutCheckerExecutorServiceRef </td>
<td class='confluenceTd'>&nbsp;</td>
<td class='confluenceTd'> <b>Camel 2.9:</b> Reference to lookup a <tt>timeoutCheckerExecutorService</tt> in the <a href="/confluence/display/CAMEL/Registry" title="Registry">Registry</a> </td>
</tr>
<tr>
<td class='confluenceTd'> optimisticLocking </td>
<td class='confluenceTd'> <tt>false</tt> </td>
<td class='confluenceTd'> <b>Camel 2.11:</b> Turns on using optimistic locking, which requires the <tt>aggregationRepository</tt> being used, is supporting this by implementing the <tt>org.apache.camel.spi.OptimisticLockingAggregationRepository</tt> interface. </td>
</tr>
<tr>
<td class='confluenceTd'> optimisticLockRetryPolicy </td>
<td class='confluenceTd'>&nbsp;</td>
<td class='confluenceTd'> <b>Camel 2.11.1:</b> Allows to configure retry settings when using optimistic locking. </td>
</tr>
</tbody></table>
</div>
</div>

<h3><a name="Aggregator2-ExchangeProperties"></a>Exchange Properties</h3>

<p>The following properties are set on each aggregated Exchange:</p>
<div class="confluenceTableSmall"><div class='table-wrap'>
<table class='confluenceTable'><tbody>
<tr>
<th class='confluenceTh'> header </th>
<th class='confluenceTh'> type </th>
<th class='confluenceTh'> description </th>
</tr>
<tr>
<td class='confluenceTd'> <tt>CamelAggregatedSize</tt> </td>
<td class='confluenceTd'> int </td>
<td class='confluenceTd'> The total number of Exchanges aggregated into this combined Exchange. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>CamelAggregatedCompletedBy</tt> </td>
<td class='confluenceTd'> String </td>
<td class='confluenceTd'> Indicator how the aggregation was completed as a value of either: <tt>predicate</tt>, <tt>size</tt>, <tt>consumer</tt>, <tt>timeout</tt> or <tt>interval</tt>. </td>
</tr>
</tbody></table>
</div>
</div>

<h3><a name="Aggregator2-AboutAggregationStrategy"></a>About AggregationStrategy</h3>
<p>The <tt>AggregationStrategy</tt> is used for aggregating the old (lookup by its correlation id) and the new exchanges together into a single exchange. Possible implementations include performing some kind of combining or delta processing, such as adding line items together into an invoice or just using the newest exchange and removing old exchanges such as for state tracking or market data prices; where old values are of little use.</p>

<p>Notice the aggregation strategy is a mandatory option and must be provided to the aggregator.</p>

<p>Here are a few example AggregationStrategy implementations that should help you create your own custom strategy.</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Default; brush: java; gutter: false" style="font-size:12px; font-family: ConfluenceInstalledFont,monospace;">
//simply combines Exchange String body values using '+' as a delimiter
class StringAggregationStrategy implements AggregationStrategy {

    public Exchange aggregate(Exchange oldExchange, Exchange newExchange) {
        if (oldExchange == null) {
            return newExchange;
        }

        String oldBody = oldExchange.getIn().getBody(String.class);
        String newBody = newExchange.getIn().getBody(String.class);
        oldExchange.getIn().setBody(oldBody + "+" + newBody);
        return oldExchange;
    }
}

//simply combines Exchange body values into an ArrayList&lt;Object&gt;
class ArrayListAggregationStrategy implements AggregationStrategy {

    public Exchange aggregate(Exchange oldExchange, Exchange newExchange) {
	Object newBody = newExchange.getIn().getBody();
	ArrayList&lt;Object&gt; list = null;
        if (oldExchange == null) {
		list = new ArrayList&lt;Object&gt;();
		list.add(newBody);
		newExchange.getIn().setBody(list);
		return newExchange;
        } else {
	        list = oldExchange.getIn().getBody(ArrayList.class);
		list.add(newBody);
		return oldExchange;
	}
    }
}
</pre>
</div></div>

<h3><a name="Aggregator2-Aboutcompletion"></a>About completion</h3>
<p>When aggregation <a href="/confluence/display/CAMEL/Exchange" title="Exchange">Exchange</a>s at some point you need to indicate that the aggregated exchanges is complete, so they can be send out of the aggregator. Camel allows you to indicate completion in various ways as follows:</p>
<ul class="alternate" type="square">
	<li>completionTimeout - Is an inactivity timeout in which is triggered if no new exchanges have been aggregated for that particular correlation key within the period.</li>
	<li>completionInterval - Once every X period all the current aggregated exchanges are completed.</li>
	<li>completionSize - Is a number indicating that after X aggregated exchanges it's complete.</li>
	<li>completionPredicate - Runs a <a href="/confluence/display/CAMEL/Predicate" title="Predicate">Predicate</a> when a new exchange is aggregated to determine if we are complete or not</li>
	<li>completionFromBatchConsumer - Special option for <a href="/confluence/display/CAMEL/Batch+Consumer" title="Batch Consumer">Batch Consumer</a> which allows you to complete when all the messages from the batch has been aggregated.</li>
	<li>forceCompletionOnStop - <b>Camel 2.9</b> Indicates to complete all current aggregated exchanges when the context is stopped</li>
</ul>


<p>Notice that all the completion ways are per correlation key. And you can combine them in any way you like. It's basically the first which triggers that wins. So you can use a completion size together with a completion timeout. Only completionTimeout and completionInterval cannot be used at the same time.</p>

<p>Notice the completion is a mandatory option and must be provided to the aggregator. If not provided Camel will thrown an Exception on startup.</p>

<div class='panelMacro'><table class='tipMacro'><colgroup><col width='24'><col></colgroup><tr><td valign='top'><img src="/confluence/images/icons/emoticons/check.gif" width="16" height="16" align="absmiddle" alt="" border="0"></td><td><b>Callbacks</b><br />See the <tt>TimeoutAwareAggregationStrategy</tt> and <tt>CompletionAwareAggregationStrategy</tt> extensions to <tt>AggregationStrategy</tt> that has callbacks when the aggregated Exchange was completed and if a timeout occurred.</td></tr></table></div>

<h3><a name="Aggregator2-PersistentAggregationRepository"></a>Persistent AggregationRepository</h3>
<p>The aggregator provides a pluggable repository which you can implement your own <tt>org.apache.camel.spi.AggregationRepository</tt>.<br/>
If you need persistent repository then you can use either Camel <a href="/confluence/display/CAMEL/HawtDB" title="HawtDB">HawtDB</a>, <a href="/confluence/display/CAMEL/LevelDB" title="LevelDB">LevelDB</a>, or <a href="/confluence/display/CAMEL/SQL+Component" title="SQL Component">SQL Component</a> components.</p>

<h3><a name="Aggregator2-Examples"></a>Examples</h3>
<p>See some examples from the old <a href="/confluence/display/CAMEL/Aggregator" title="Aggregator">Aggregator</a> which is somewhat similar to this new aggregator.</p>

<div class='panelMacro'><table class='tipMacro'><colgroup><col width='24'><col></colgroup><tr><td valign='top'><img src="/confluence/images/icons/emoticons/check.gif" width="16" height="16" align="absmiddle" alt="" border="0"></td><td><b>Setting options in Spring XML</b><br />Many of the options are configurable as attributes on the <tt>&lt;aggregate&gt;</tt> tag when using Spring XML.</td></tr></table></div>

<h4><a name="Aggregator2-UsingcompletionTimeout"></a>Using completionTimeout</h4>
<p>In this example we want to aggregate all incoming messages and after 3 seconds of inactivity we want the aggregation to complete. This is done using the <tt>completionTimeout</tt> option as shown:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<script type="syntaxhighlighter" class="theme: Default; brush: java; gutter: false"><![CDATA[
from("direct:start")
    // aggregate all exchanges correlated by the id header.
    // Aggregate them using the BodyInAggregatingStrategy strategy which
    // and after 3 seconds of inactivity them timeout and complete the aggregation
    // and send it to mock:aggregated
    .aggregate(header("id"), new BodyInAggregatingStrategy()).completionTimeout(3000)
        .to("mock:aggregated");
]]></script>
</div></div>

<p>And the same example using Spring XML:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<script type="syntaxhighlighter" class="theme: Default; brush: xml; gutter: false"><![CDATA[
&lt;camelContext xmlns="http://camel.apache.org/schema/spring"&gt;
    &lt;route&gt;
        &lt;from uri="direct:start"/&gt;
        &lt;aggregate strategyRef="aggregatorStrategy" completionTimeout="3000"&gt;
            &lt;correlationExpression&gt;
                &lt;simple&gt;header.id&lt;/simple&gt;
            &lt;/correlationExpression&gt;
            &lt;to uri="mock:aggregated"/&gt;
        &lt;/aggregate&gt;
    &lt;/route&gt;
&lt;/camelContext&gt;

&lt;bean id="aggregatorStrategy" class="org.apache.camel.processor.BodyInAggregatingStrategy"/&gt;
]]></script>
</div></div>

<h4><a name="Aggregator2-UsingTimeoutAwareAggregationStrategy"></a>Using TimeoutAwareAggregationStrategy</h4>
<p><b>Available as of Camel 2.9.2</b></p>

<p>If your aggregation strategy implements <tt>TimeoutAwareAggregationStrategy</tt>, then Camel will invoke the <tt>timeout</tt> method when the timeout occurs. Notice that the values for index and total parameters will be -1, and the timeout parameter will be provided only if configured as a fixed value. You must <b>not</b> throw any exceptions from the <tt>timeout</tt> method.</p>

<h4><a name="Aggregator2-UsingCompletionAwareAggregationStrategy"></a>Using CompletionAwareAggregationStrategy</h4>
<p><b>Available as of Camel 2.9.3</b></p>

<p>If your aggregation strategy implements <tt>CompletionAwareAggregationStrategy</tt>, then Camel will invoke the <tt>onComplete</tt> method when the aggregated Exchange is completed.  This allows you to do any last minute custom logic such as to cleanup some resources, or additional work on the exchange as it's now completed.<br/>
You must <b>not</b> throw any exceptions from the <tt>onCompletion</tt> method.</p>

<h4><a name="Aggregator2-UsingcompletionSize"></a>Using completionSize</h4>
<p>In this example we want to aggregate all incoming messages and when we have 3 messages aggregated (in the same correlation group) we want the aggregation to complete. This is done using the <tt>completionSize</tt> option as shown:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<script type="syntaxhighlighter" class="theme: Default; brush: java; gutter: false"><![CDATA[
from("direct:start")
    // aggregate all exchanges correlated by the id header.
    // Aggregate them using the BodyInAggregatingStrategy strategy which
    // and after 3 messages has been aggregated then complete the aggregation
    // and send it to mock:aggregated
    .aggregate(header("id"), new BodyInAggregatingStrategy()).completionSize(3)
        .to("mock:aggregated");
]]></script>
</div></div>

<p>And the same example using Spring XML:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<script type="syntaxhighlighter" class="theme: Default; brush: xml; gutter: false"><![CDATA[
&lt;camelContext xmlns="http://camel.apache.org/schema/spring"&gt;
    &lt;route&gt;
        &lt;from uri="direct:start"/&gt;
        &lt;aggregate strategyRef="aggregatorStrategy" completionSize="3"&gt;
            &lt;correlationExpression&gt;
                &lt;simple&gt;header.id&lt;/simple&gt;
            &lt;/correlationExpression&gt;
            &lt;to uri="mock:aggregated"/&gt;
        &lt;/aggregate&gt;
    &lt;/route&gt;
&lt;/camelContext&gt;

&lt;bean id="aggregatorStrategy" class="org.apache.camel.processor.BodyInAggregatingStrategy"/&gt;
]]></script>
</div></div>

<h4><a name="Aggregator2-UsingcompletionPredicate"></a>Using completionPredicate</h4>
<p>In this example we want to aggregate all incoming messages and use a <a href="/confluence/display/CAMEL/Predicate" title="Predicate">Predicate</a> to determine when we are complete. The <a href="/confluence/display/CAMEL/Predicate" title="Predicate">Predicate</a> can be evaluated using either the aggregated exchange (default) or the incoming exchange. We will so both situations as examples. We start with the default situation as shown:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<script type="syntaxhighlighter" class="theme: Default; brush: java; gutter: false"><![CDATA[
from("direct:start")
    // aggregate all exchanges correlated by the id header.
    // Aggregate them using the BodyInAggregatingStrategy strategy which
    // and when the aggregated body contains A+B+C then complete the aggregation
    // and send it to mock:aggregated
    .aggregate(header("id"), new BodyInAggregatingStrategy()).completionPredicate(body().contains("A+B+C"))
        .to("mock:aggregated");
]]></script>
</div></div>

<p>And the same example using Spring XML:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<script type="syntaxhighlighter" class="theme: Default; brush: xml; gutter: false"><![CDATA[
&lt;camelContext xmlns="http://camel.apache.org/schema/spring"&gt;
    &lt;route&gt;
        &lt;from uri="direct:start"/&gt;
        &lt;aggregate strategyRef="aggregatorStrategy"&gt;
            &lt;correlationExpression&gt;
                &lt;simple&gt;header.id&lt;/simple&gt;
            &lt;/correlationExpression&gt;
            &lt;completionPredicate&gt;
                &lt;simple&gt;${body} contains 'A+B+C'&lt;/simple&gt;
            &lt;/completionPredicate&gt;
            &lt;to uri="mock:aggregated"/&gt;
        &lt;/aggregate&gt;
    &lt;/route&gt;
&lt;/camelContext&gt;

&lt;bean id="aggregatorStrategy" class="org.apache.camel.processor.BodyInAggregatingStrategy"/&gt;
]]></script>
</div></div>

<p>And the other situation where we use the <tt>eagerCheckCompletion</tt> option to tell Camel to use the incoming Exchange. Notice how we can just test in the completion predicate that the incoming message is the <em>END</em> message:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<script type="syntaxhighlighter" class="theme: Default; brush: java; gutter: false"><![CDATA[
from("direct:start")
    // aggregate all exchanges correlated by the id header.
    // Aggregate them using the BodyInAggregatingStrategy strategy
    // do eager checking which means the completion predicate will use the incoming exchange
    // which allows us to trigger completion when a certain exchange arrived which is the
    // END message
    .aggregate(header("id"), new BodyInAggregatingStrategy())
        .eagerCheckCompletion().completionPredicate(body().isEqualTo("END"))
        .to("mock:aggregated");
]]></script>
</div></div>

<p>And the same example using Spring XML:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<script type="syntaxhighlighter" class="theme: Default; brush: xml; gutter: false"><![CDATA[
&lt;camelContext xmlns="http://camel.apache.org/schema/spring"&gt;
    &lt;route&gt;
        &lt;from uri="direct:start"/&gt;
        &lt;aggregate strategyRef="aggregatorStrategy" eagerCheckCompletion="true"&gt;
            &lt;correlationExpression&gt;
                &lt;simple&gt;header.id&lt;/simple&gt;
            &lt;/correlationExpression&gt;
            &lt;completionPredicate&gt;
                &lt;simple&gt;${body} == 'END'&lt;/simple&gt;
            &lt;/completionPredicate&gt;
            &lt;to uri="mock:aggregated"/&gt;
        &lt;/aggregate&gt;
    &lt;/route&gt;
&lt;/camelContext&gt;

&lt;bean id="aggregatorStrategy" class="org.apache.camel.processor.BodyInAggregatingStrategy"/&gt;
]]></script>
</div></div>

<h4><a name="Aggregator2-UsingdynamiccompletionTimeout"></a>Using dynamic completionTimeout</h4>
<p>In this example we want to aggregate all incoming messages and after a period of inactivity we want the aggregation to complete. The period should be computed at runtime based on the <tt>timeout</tt> header in the incoming messages. This is done using the <tt>completionTimeout</tt> option as shown:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<script type="syntaxhighlighter" class="theme: Default; brush: java; gutter: false"><![CDATA[
from("direct:start")
    // aggregate all exchanges correlated by the id header.
    // Aggregate them using the BodyInAggregatingStrategy strategy which
    // and the timeout header contains the timeout in millis of inactivity them timeout and complete the aggregation
    // and send it to mock:aggregated
    .aggregate(header("id"), new BodyInAggregatingStrategy()).completionTimeout(header("timeout"))
        .to("mock:aggregated");
]]></script>
</div></div>

<p>And the same example using Spring XML:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<script type="syntaxhighlighter" class="theme: Default; brush: xml; gutter: false"><![CDATA[
&lt;camelContext xmlns="http://camel.apache.org/schema/spring"&gt;
    &lt;route&gt;
        &lt;from uri="direct:start"/&gt;
        &lt;aggregate strategyRef="aggregatorStrategy"&gt;
            &lt;correlationExpression&gt;
                &lt;simple&gt;header.id&lt;/simple&gt;
            &lt;/correlationExpression&gt;
            &lt;completionTimeout&gt;
                &lt;header&gt;timeout&lt;/header&gt;
            &lt;/completionTimeout&gt;
            &lt;to uri="mock:aggregated"/&gt;
        &lt;/aggregate&gt;
    &lt;/route&gt;
&lt;/camelContext&gt;

&lt;bean id="aggregatorStrategy" class="org.apache.camel.processor.BodyInAggregatingStrategy"/&gt;
]]></script>
</div></div>

<p><b>Note:</b> You can also add a fixed timeout value and Camel will fallback to use this value if the dynamic value was <tt>null</tt> or <tt>0</tt>.</p>

<h4><a name="Aggregator2-UsingdynamiccompletionSize"></a>Using dynamic completionSize</h4>
<p>In this example we want to aggregate all incoming messages based on a dynamic size per correlation key. The size is computed at runtime based on the <tt>mySize</tt> header in the incoming messages. This is done using the <tt>completionSize</tt> option as shown:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<script type="syntaxhighlighter" class="theme: Default; brush: java; gutter: false"><![CDATA[
from("direct:start")
    // aggregate all exchanges correlated by the id header.
    // Aggregate them using the BodyInAggregatingStrategy strategy which
    // and the header mySize determines the number of aggregated messages should trigger the completion
    // and send it to mock:aggregated
    .aggregate(header("id"), new BodyInAggregatingStrategy()).completionSize(header("mySize"))
        .to("mock:aggregated");
]]></script>
</div></div>

<p>And the same example using Spring XML:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<script type="syntaxhighlighter" class="theme: Default; brush: xml; gutter: false"><![CDATA[
&lt;camelContext xmlns="http://camel.apache.org/schema/spring"&gt;
    &lt;route&gt;
        &lt;from uri="direct:start"/&gt;
        &lt;aggregate strategyRef="aggregatorStrategy"&gt;
            &lt;correlationExpression&gt;
                &lt;simple&gt;header.id&lt;/simple&gt;
            &lt;/correlationExpression&gt;
            &lt;completionSize&gt;
                &lt;header&gt;mySize&lt;/header&gt;
            &lt;/completionSize&gt;
            &lt;to uri="mock:aggregated"/&gt;
        &lt;/aggregate&gt;
    &lt;/route&gt;
&lt;/camelContext&gt;

&lt;bean id="aggregatorStrategy" class="org.apache.camel.processor.BodyInAggregatingStrategy"/&gt;
]]></script>
</div></div>

<p><b>Note:</b> You can also add a fixed size value and Camel will fallback to use this value if the dynamic value was <tt>null</tt> or <tt>0</tt>.</p>

<h4><a name="Aggregator2-UsingThisPattern"></a>Using This Pattern</h4>

<p>If you would like to use this EIP Pattern then please read the <a href="/confluence/display/CAMEL/Getting+Started" title="Getting Started">Getting Started</a>, you may also find the <a href="/confluence/display/CAMEL/Architecture" title="Architecture">Architecture</a> useful particularly the description of <a href="/confluence/display/CAMEL/Endpoint" title="Endpoint">Endpoint</a> and <a href="/confluence/display/CAMEL/URIs" title="URIs">URIs</a>. Then you could try out some of the <a href="/confluence/display/CAMEL/Examples" title="Examples">Examples</a> first before trying this pattern out.</p>

<h4><a name="Aggregator2-ManuallyForcetheCompletionofAllAggregatedExchangesImmediately"></a>Manually Force the Completion of All Aggregated Exchanges Immediately</h4>

<p><b>Available as of Camel 2.9</b><br/>
You can manually trigger completion of all current aggregated exchanges by sending a message containing the header Exchange.AGGREGATION_COMPLETE_ALL_GROUPS set to true.  The message is considered a signal message only, the message headers/contents will not be processed otherwise.</p>

<p><b>Available as of Camel 2.11</b><br/>
You can alternatively set the header Exchange.AGGREGATION_COMPLETE_ALL_GROUPS_INCLUSIVE to true to trigger completion of all groups after processing the current message.</p>

<h4><a name="Aggregator2-UsingaList%3CV%3EinAggregationStrategy"></a>Using a List&lt;V&gt; in AggregationStrategy</h4>
<p><b>Available as of Camel 2.11</b></p>

<p>If you want to aggregate some value from the messages &lt;V&gt; into a List&lt;V&gt; then we have added a <tt>org.apache.camel.processor.aggregate.AbstractListAggregationStrategy</tt> abstract class in <b>Camel 2.11</b> that makes this easier. The completed Exchange that is sent out of the aggregator will contain the List&lt;V&gt; in the message body.</p>

<p>For example to aggregate a List&lt;Integer&gt; you can extend this class as shown below, and implement the <tt>getValue</tt> method:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<script type="syntaxhighlighter" class="theme: Default; brush: java; gutter: false"><![CDATA[
/**
 * Our strategy just group a list of integers.
 */
public final class MyListOfNumbersStrategy extends AbstractListAggregationStrategy&lt;Integer&gt; {

    @Override
    public Integer getValue(Exchange exchange) {
        // the message body contains a number, so just return that as-is
        return exchange.getIn().getBody(Integer.class);
    }
}
]]></script>
</div></div>


<h3><a name="Aggregator2-UsingPOJOsasAggregationStrategy"></a>Using POJOs as AggregationStrategy</h3>
<p><b>Available as of Camel 2.12</b></p>

<div class='panelMacro'><table class='tipMacro'><colgroup><col width='24'><col></colgroup><tr><td valign='top'><img src="/confluence/images/icons/emoticons/check.gif" width="16" height="16" align="absmiddle" alt="" border="0"></td><td>You can use POJOs as AggregationStrategy with the other <a href="/confluence/display/CAMEL/EIP" title="EIP">EIP</a>s that supports aggregation, such as <a href="/confluence/display/CAMEL/Splitter" title="Splitter">Splitter</a>, <a href="/confluence/display/CAMEL/Recipient+List" title="Recipient List">Recipient List</a>, etc.</td></tr></table></div>

<p>To use the <tt>AggregationStrategy</tt> you had to implement the <tt>org.apache.camel.processor.aggregate.AggregationStrategy</tt> interface, which means your logic would be tied to the Camel API. From <b>Camel 2.12</b> onwards you can use a POJO for the logic and let Camel adapt to your POJO. To use a POJO a convention must be followed:</p>

<ul class="alternate" type="square">
	<li>there must be a public method to use</li>
	<li>the method must not be void</li>
	<li>the method can be static or non-static</li>
	<li>the method must have 2 or more parameters</li>
	<li>the parameters is paired so the first 50% is applied to the <tt>oldExchnage</tt> and the reminder 50% is for the <tt>newExchange</tt></li>
	<li>.. meaning that there must be an equal number of parameters, eg 2, 4, 6 etc.</li>
</ul>


<p>The paired methods is expected to be ordered as follows:</p>
<ul class="alternate" type="square">
	<li>the first parameter is the message body</li>
	<li>the 2nd parameter is a Map of the headers</li>
	<li>the 3rd parameter is a Map of the Exchange properties</li>
</ul>


<p>This convention is best explained with some examples.</p>

<p>In the method below, we have only 2 parameters, so the 1st parameter is the body of the <tt>oldExchange</tt>, and the 2nd is paired to the body of the <tt>newExchange</tt>:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Default; brush: java; gutter: false" style="font-size:12px; font-family: ConfluenceInstalledFont,monospace;">
public String append(String existing, String next) {
  return existing + next;
}
</pre>
</div></div>

<p>In the method below, we have only 4 parameters, so the 1st parameter is the body of the <tt>oldExchange</tt>, and the 2nd is the Map of the <tt>oldExchange} headers, and the 3rd is paired to the body of the {{newExchange</tt>, and the 4th parameter is the Map of the <tt>newExchange</tt> headers:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Default; brush: java; gutter: false" style="font-size:12px; font-family: ConfluenceInstalledFont,monospace;">
public String append(String existing, Map existingHeaders, String next, Map nextHeaders) {
  return existing + next;
}
</pre>
</div></div>

<p>And finally if we have 6 parameters the we also have the properties of the <a href="/confluence/display/CAMEL/Exchange" title="Exchange">Exchange</a>s:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Default; brush: java; gutter: false" style="font-size:12px; font-family: ConfluenceInstalledFont,monospace;">
public String append(String existing, Map existingHeaders, Map existingProperties, String next, Map nextHeaders, Map nextProperties) {
  return existing + next;
}
</pre>
</div></div>

<p>To use this with the <a href="/confluence/display/CAMEL/Aggregator2" title="Aggregator2">Aggregate</a> EIP we can use a POJO with the aggregate logic as follows:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Default; brush: java; gutter: false" style="font-size:12px; font-family: ConfluenceInstalledFont,monospace;">
public class MyBodyAppender {

    public String append(String existing, String next) {
        return next + existing;
    }

}
</pre>
</div></div>

<p>And then in the Camel route we create an instance of our bean, and then refer to the bean in the route using <tt>bean</tt> method from <tt>org.apache.camel.util.toolbox.AggregationStrategies</tt> as shown:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Default; brush: java; gutter: false" style="font-size:12px; font-family: ConfluenceInstalledFont,monospace;">
    private MyBodyAppender appender = new MyBodyAppender();

    public void configure() throws Exception {
        from("direct:start")
            .aggregate(constant(true), AggregationStrategies.bean(appender, "append"))
                .completionSize(3)
                .to("mock:result");
    }
</pre>
</div></div>

<p>We can also provide the bean type directly:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Default; brush: java; gutter: false" style="font-size:12px; font-family: ConfluenceInstalledFont,monospace;">
    public void configure() throws Exception {
        from("direct:start")
            .aggregate(constant(true), AggregationStrategies.bean(MyBodyAppender.class, "append"))
                .completionSize(3)
                .to("mock:result");
    }
</pre>
</div></div>



<p>And if the bean has only one method we do not need to specify the name of the method:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Default; brush: java; gutter: false" style="font-size:12px; font-family: ConfluenceInstalledFont,monospace;">
    public void configure() throws Exception {
        from("direct:start")
            .aggregate(constant(true), AggregationStrategies.bean(MyBodyAppender.class))
                .completionSize(3)
                .to("mock:result");
    }
</pre>
</div></div>

<p>And the <tt>append</tt> method could be static:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Default; brush: java; gutter: false" style="font-size:12px; font-family: ConfluenceInstalledFont,monospace;">
public class MyBodyAppender {

    public static String append(String existing, String next) {
        return next + existing;
    }

}
</pre>
</div></div>

<p>If you are using XML DSL then we need to declare a &lt;bean&gt; with the POJO:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Default; brush: xml; gutter: false" style="font-size:12px; font-family: ConfluenceInstalledFont,monospace;">
    &lt;bean id="myAppender" class="com.foo.MyBodyAppender"/&gt;
</pre>
</div></div>

<p>And in the Camel route we use <tt>strategyRef</tt> to refer to the bean by its id, and the <tt>strategyMethodName</tt> can be used to define the method name to call:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Default; brush: xml; gutter: false" style="font-size:12px; font-family: ConfluenceInstalledFont,monospace;">
    &lt;camelContext xmlns="http://camel.apache.org/schema/spring"&gt;
        &lt;route&gt;
            &lt;from uri="direct:start"/&gt;
            &lt;aggregate strategyRef="myAppender" strategyMethodName="append" completionSize="3"&gt;
                &lt;correlationExpression&gt;
                    &lt;constant&gt;true&lt;/constant&gt;
                &lt;/correlationExpression&gt;
                &lt;to uri="mock:result"/&gt;
            &lt;/aggregate&gt;
        &lt;/route&gt;
    &lt;/camelContext&gt;
</pre>
</div></div>

<p>When using XML DSL you must define the POJO as a &lt;bean&gt;.</p>

<h4><a name="Aggregator2-Aggregatingwhennodata"></a>Aggregating when no data</h4>

<p>By default when using POJOs as AggregationStrategy, then the method is <b>only</b> invoked when there is data to be aggregated (by default). You can use the option <tt>strategyMethodAllowNull</tt> to configure this. Where as without using POJOs then you may have <tt>null</tt> as <tt>oldExchange</tt> or <tt>newExchange</tt> parameters. For example the <a href="/confluence/display/CAMEL/Aggregator2" title="Aggregator2">Aggregate</a> EIP will invoke the <tt>AggregationStrategy</tt> with <tt>oldExchange</tt> as null, for the first <a href="/confluence/display/CAMEL/Exchange" title="Exchange">Exchange</a> incoming to the aggregator. And then for subsequent <a href="/confluence/display/CAMEL/Exchange" title="Exchange">Exchange</a>s then <tt>oldExchange</tt> and <tt>newExchange</tt> parameters are both not null. </p>

<h5><a name="Aggregator2-ExamplewithContentEnricherandnodata"></a>Example with <a href="/confluence/display/CAMEL/Content+Enricher" title="Content Enricher">Content Enricher</a> and no data</h5>
<p>Though with POJOs as AggregationStrategy we made this simpler and only call the method when <tt>oldExchange</tt> and <tt>newExchange</tt> is not null, as that would be the most common use-case. If you need to allow <tt>oldExchange</tt> or <tt>newExchange</tt> to be null, then you can configure this with the POJO using the <tt>AggregationStrategyBeanAdapter</tt> as shown below. On the bean adapter we call <tt>setAllowNullNewExchange</tt> to allow the new exchange to be null.</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Default; brush: java; gutter: false" style="font-size:12px; font-family: ConfluenceInstalledFont,monospace;">
    public void configure() throws Exception {
        AggregationStrategyBeanAdapter myStrategy = new AggregationStrategyBeanAdapter(appender, "append");
        myStrategy.setAllowNullOldExchange(true);
        myStrategy.setAllowNullNewExchange(true);

        from("direct:start")
            .pollEnrich("seda:foo", 1000, myStrategy)
                .to("mock:result");
    }
</pre>
</div></div>

<p>This can be configured a bit easier using the <tt>beanAllowNull</tt> method from <tt>AggregationStrategies</tt> as shown:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Default; brush: java; gutter: false" style="font-size:12px; font-family: ConfluenceInstalledFont,monospace;">
    public void configure() throws Exception {
        from("direct:start")
            .pollEnrich("seda:foo", 1000, AggregationStrategies.beanAllowNull(appender, "append"))
                .to("mock:result");
    }
</pre>
</div></div>


<p>Then the <tt>append</tt> method in the POJO would need to deal with the situation that <tt>newExchange</tt> can be null:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Default; brush: java; gutter: false" style="font-size:12px; font-family: ConfluenceInstalledFont,monospace;">
    public class MyBodyAppender {

        public String append(String existing, String next) {
            if (next == null) {
                return "NewWasNull" + existing;
            } else {
                return existing + next;
            }
        }

    }
</pre>
</div></div>

<p>In the example above we use the <a href="/confluence/display/CAMEL/Content+Enricher" title="Content Enricher">Content Enricher</a> EIP using <tt>pollEnrich</tt>. The <tt>newExchange</tt> will be null in the situation we could not get any data from the "seda:foo" endpoint, and therefore the timeout was hit after 1 second. So if we need to do some special merge logic we would need to set <tt>setAllowNullNewExchange=true</tt>, so the <tt>append</tt> method will be invoked. If we do not do that then when the timeout was hit, then the append method would normally not be invoked, meaning the <a href="/confluence/display/CAMEL/Content+Enricher" title="Content Enricher">Content Enricher</a> did not merge/change the message. </p>

<p>In XML DSL you would configure the <tt>strategyMethodAllowNull</tt> option and set it to true as shown below:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Default; brush: xml; gutter: false" style="font-size:12px; font-family: ConfluenceInstalledFont,monospace;">
    &lt;camelContext xmlns="http://camel.apache.org/schema/spring"&gt;
        &lt;route&gt;
            &lt;from uri="direct:start"/&gt;
            &lt;aggregate strategyRef="myAppender" strategyMethodName="append" strategyMethodAllowNull="true" completionSize="3"&gt;
                &lt;correlationExpression&gt;
                    &lt;constant&gt;true&lt;/constant&gt;
                &lt;/correlationExpression&gt;
                &lt;to uri="mock:result"/&gt;
            &lt;/aggregate&gt;
        &lt;/route&gt;
    &lt;/camelContext&gt;
</pre>
</div></div>

<h5><a name="Aggregator2-Differentbodytypes"></a>Different body types</h5>

<p>When for example using <tt>strategyMethodAllowNull</tt> as true, then the parameter types of the message bodies does not have to be the same. For example suppose we want to aggregate from a <tt>com.foo.User</tt> type to a <tt>List&lt;String&gt;</tt> that contains the user name. We could code a POJO doing this as follows:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Default; brush: java; gutter: false" style="font-size:12px; font-family: ConfluenceInstalledFont,monospace;">
    public static final class MyUserAppender {

        public List addUsers(List names, User user) {
            if (names == null) {
                names = new ArrayList();
            }
            names.add(user.getName());
            return names;
        }
    }
</pre>
</div></div>

<p>Notice that the return type is a List which we want to contain the user names. The 1st parameter is the list of names, and then notice the 2nd parameter is the incoming <tt>com.foo.User</tt> type.</p>

<h3><a name="Aggregator2-Seealso"></a>See also</h3>
<ul class="alternate" type="square">
	<li>The <a href="/confluence/display/CAMEL/Loan+Broker+Example" title="Loan Broker Example">Loan Broker Example</a> which uses an aggregator</li>
	<li><a href="http://tmielke.blogspot.com/2009/01/using-camel-aggregator-correctly.html" class="external-link" rel="nofollow">Blog post by Torsten Mielke</a> about using the aggregator correctly.</li>
	<li>The old <a href="/confluence/display/CAMEL/Aggregator" title="Aggregator">Aggregator</a></li>
	<li><a href="/confluence/display/CAMEL/HawtDB" title="HawtDB">HawtDB</a>, <a href="/confluence/display/CAMEL/LevelDB" title="LevelDB">LevelDB</a> or <a href="/confluence/display/CAMEL/SQL+Component" title="SQL Component">SQL Component</a> for persistence support</li>
	<li><a href="/confluence/display/CAMEL/Aggregate+Example" title="Aggregate Example">Aggregate Example</a> for an example application</li>
</ul>

    </div>
        <div id="commentsSection" class="wiki-content pageSection">
        <div style="float: right;" class="grey">
                        <a href="https://cwiki.apache.org/confluence/users/removespacenotification.action?spaceKey=CAMEL">Stop watching space</a>
            <span style="padding: 0px 5px;">|</span>
                <a href="https://cwiki.apache.org/confluence/users/editmyemailsettings.action">Change email notification preferences</a>
</div>
        <a href="https://cwiki.apache.org/confluence/display/CAMEL/Aggregator2">View Online</a>
        |
        <a href="https://cwiki.apache.org/confluence/pages/diffpagesbyversion.action?pageId=14057759&revisedVersion=40&originalVersion=39">View Changes</a>
                |
        <a href="https://cwiki.apache.org/confluence/display/CAMEL/Aggregator2?showComments=true&amp;showCommentArea=true#addcomment">Add Comment</a>
            </div>
</div>
</div>
</div>
</div>
</body>
</html>

Mime
View raw message