CAMEL-10837: Migrate EIP patterns to adoc (squashed)
Project: http://git-wip-us.apache.org/repos/asf/camel/repo Commit: http://git-wip-us.apache.org/repos/asf/camel/commit/f0bae85e Tree: http://git-wip-us.apache.org/repos/asf/camel/tree/f0bae85e Diff: http://git-wip-us.apache.org/repos/asf/camel/diff/f0bae85e Branch: refs/heads/master Commit: f0bae85e4c3c5bbed8b796fe7dee64da972940c7 Parents: 4b81fbb Author: Claus Ibsen <davscl...@apache.org> Authored: Sun Feb 19 19:50:37 2017 +0100 Committer: Claus Ibsen <davscl...@apache.org> Committed: Sun Feb 19 19:50:37 2017 +0100 ---------------------------------------------------------------------- camel-core/readme-eip.adoc | 3 +- .../src/main/docs/content-based-router.adoc | 79 -- .../src/main/docs/correlation-identifier.adoc | 64 - .../src/main/docs/dead-letter-channel.adoc | 507 -------- .../src/main/docs/eips/aggregate-eip.adoc | 675 ---------- .../src/main/docs/eips/aggregator-eip.adoc | 1163 ++++++++++++++++++ .../src/main/docs/eips/circuitBreaker-eip.adoc | 57 + .../main/docs/eips/content-based-router.adoc | 79 ++ .../main/docs/eips/correlation-identifier.adoc | 64 + .../main/docs/eips/customLoadBalancer-eip.adoc | 82 ++ .../src/main/docs/eips/dead-letter-channel.adoc | 507 ++++++++ camel-core/src/main/docs/eips/delay-eip.adoc | 166 +++ .../src/main/docs/eips/dynamicRouter-eip.adoc | 185 +++ camel-core/src/main/docs/eips/enrich-eip.adoc | 370 ++++++ .../src/main/docs/eips/event-message.adoc | 86 ++ .../src/main/docs/eips/guaranteed-delivery.adoc | 64 + camel-core/src/main/docs/eips/hystrix-eip.adoc | 129 ++ .../docs/eips/hystrixConfiguration-eip.adoc | 44 + .../src/main/docs/eips/loadBalance-eip.adoc | 266 ++++ camel-core/src/main/docs/eips/message-bus.adoc | 64 + .../src/main/docs/eips/message-channel.adoc | 58 + .../src/main/docs/eips/message-endpoint.adoc | 192 +++ .../src/main/docs/eips/message-filter.adoc | 130 ++ .../src/main/docs/eips/message-router.adoc | 37 + .../src/main/docs/eips/message-translator.adoc | 96 ++ camel-core/src/main/docs/eips/message.adoc | 69 ++ .../src/main/docs/eips/pipes-and-filters.adoc | 93 ++ .../main/docs/eips/point-to-point-channel.adoc | 52 + .../docs/eips/publish-subscribe-channel.adoc | 69 ++ camel-core/src/main/docs/eips/random-eip.adoc | 13 + camel-core/src/main/docs/event-message.adoc | 86 -- .../src/main/docs/guaranteed-delivery.adoc | 64 - camel-core/src/main/docs/message-bus.adoc | 64 - camel-core/src/main/docs/message-channel.adoc | 58 - camel-core/src/main/docs/message-endpoint.adoc | 192 --- camel-core/src/main/docs/message-filter.adoc | 130 -- camel-core/src/main/docs/message-router.adoc | 37 - .../src/main/docs/message-translator.adoc | 96 -- camel-core/src/main/docs/message.adoc | 69 -- camel-core/src/main/docs/pipes-and-filters.adoc | 93 -- .../src/main/docs/point-to-point-channel.adoc | 52 - .../main/docs/publish-subscribe-channel.adoc | 69 -- 42 files changed, 4137 insertions(+), 2336 deletions(-) ---------------------------------------------------------------------- http://git-wip-us.apache.org/repos/asf/camel/blob/f0bae85e/camel-core/readme-eip.adoc ---------------------------------------------------------------------- diff --git a/camel-core/readme-eip.adoc b/camel-core/readme-eip.adoc index 0d49abc..2e65a7c 100644 --- a/camel-core/readme-eip.adoc +++ b/camel-core/readme-eip.adoc @@ -1,6 +1,8 @@ Enterprise Integration Patterns ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +Camel supports most of the link:http://www.eaipatterns.com/toc.html[Enterprise Integration Patterns] from the excellent book by link:http://www.amazon.com/exec/obidos/search-handle-url/105-9796798-8100401?%5Fencoding=UTF8&search-type=ss&index=books&field-author=Gregor%20Hohpe[Gregor Hohpe] and link:http://www.amazon.com/exec/obidos/search-handle-url/105-9796798-8100401?%5Fencoding=UTF8&search-type=ss&index=books&field-author=Bobby%20Woolf[Bobby Woolf]. + // eips: START Number of EIPs: 61 @@ -193,4 +195,3 @@ Number of EIPs: 61 |======================================================================= // eips: END - http://git-wip-us.apache.org/repos/asf/camel/blob/f0bae85e/camel-core/src/main/docs/content-based-router.adoc ---------------------------------------------------------------------- diff --git a/camel-core/src/main/docs/content-based-router.adoc b/camel-core/src/main/docs/content-based-router.adoc deleted file mode 100644 index 809b332..0000000 --- a/camel-core/src/main/docs/content-based-router.adoc +++ /dev/null @@ -1,79 +0,0 @@ -[[ContentBasedRouter-ContentBasedRouter]] -Content Based Router -^^^^^^^^^^^^^^^^^^^^ - -The -http://www.enterpriseintegrationpatterns.com/ContentBasedRouter.html[Content -Based Router] from the link:enterprise-integration-patterns.html[EIP -patterns] allows you to route messages to the correct destination based -on the contents of the message exchanges. - -image:http://www.enterpriseintegrationpatterns.com/img/ContentBasedRouter.gif[image] - -The following example shows how to route a request from an input -*seda:a* endpoint to either *seda:b*, *seda:c* or *seda:d* depending on -the evaluation of various link:predicate.html[Predicate] expressions - -*Using the link:fluent-builders.html[Fluent Builders]* - -[source,java] --------------------------------------------------------- -RouteBuilder builder = new RouteBuilder() { - public void configure() { - errorHandler(deadLetterChannel("mock:error")); - - from("direct:a") - .choice() - .when(header("foo").isEqualTo("bar")) - .to("direct:b") - .when(header("foo").isEqualTo("cheese")) - .to("direct:c") - .otherwise() - .to("direct:d"); - } -}; --------------------------------------------------------- - -TIP: See link:why-can-i-not-use-when-or-otherwise-in-a-java-camel-route.html[Why -can I not use when or otherwise in a Java Camel route] if you have -problems with the Java DSL, accepting using `when` or `otherwise`. - - -*Using the link:spring-xml-extensions.html[Spring XML Extensions]* - -[source,xml] -------------------------------------------------------------------------------------------- -<camelContext errorHandlerRef="errorHandler" xmlns="http://camel.apache.org/schema/spring"> - <route> - <from uri="direct:a"/> - <choice> - <when> - <xpath>$foo = 'bar'</xpath> - <to uri="direct:b"/> - </when> - <when> - <xpath>$foo = 'cheese'</xpath> - <to uri="direct:c"/> - </when> - <otherwise> - <to uri="direct:d"/> - </otherwise> - </choice> - </route> -</camelContext> -------------------------------------------------------------------------------------------- - -For further examples of this pattern in use you could look at the -http://svn.apache.org/viewvc/camel/trunk/camel-core/src/test/java/org/apache/camel/processor/ChoiceTest.java?view=markup[junit -test case] - -[[ContentBasedRouter-UsingThisPattern]] -Using This Pattern -++++++++++++++++++ - -If you would like to use this EIP Pattern then please read the -link:getting-started.html[Getting Started], you may also find the -link:architecture.html[Architecture] useful particularly the description -of link:endpoint.html[Endpoint] and link:uris.html[URIs]. Then you could -try out some of the link:examples.html[Examples] first before trying -this pattern out. http://git-wip-us.apache.org/repos/asf/camel/blob/f0bae85e/camel-core/src/main/docs/correlation-identifier.adoc ---------------------------------------------------------------------- diff --git a/camel-core/src/main/docs/correlation-identifier.adoc b/camel-core/src/main/docs/correlation-identifier.adoc deleted file mode 100644 index d020eb8..0000000 --- a/camel-core/src/main/docs/correlation-identifier.adoc +++ /dev/null @@ -1,64 +0,0 @@ -[[CorrelationIdentifier-CorrelationIdentifier]] -Correlation Identifier -^^^^^^^^^^^^^^^^^^^^^^ - -Camel supports the -http://www.enterpriseintegrationpatterns.com/CorrelationIdentifier.html[Correlation -Identifier] from the link:enterprise-integration-patterns.html[EIP -patterns] by getting or setting a header on a -link:message.html[Message]. - -When working with the link:activemq.html[ActiveMQ] or link:jms.html[JMS] -components the correlation identifier header is called -*JMSCorrelationID*. You can add your own correlation identifier to any -message exchange to help correlate messages together to a single -conversation (or business process). - -image:http://www.enterpriseintegrationpatterns.com/img/CorrelationIdentifierSolution.gif[image] - -The use of a Correlation Identifier is key to working with the -link:bam.html[Camel Business Activity Monitoring Framework] and can also -be highly useful when testing with simulation or canned data such as -with the link:mock.html[Mock testing framework] - -Some link:eip.html[EIP] patterns will spin off a sub message, and in -those cases, Camel will add a correlation id on the -link:exchange.html[Exchange] as a property with they key -`Exchange.CORRELATION_ID`, which links back to the source -link:exchange.html[Exchange]. For example the -link:splitter.html[Splitter], link:multicast.html[Multicast], -link:recipient-list.html[Recipient List], and link:wire-tap.html[Wire -Tap] EIP does this. - -The following example demonstrates using the Camel JMSMessageID as the -Correlation Identifier within a request/reply pattern in -the link:jms.html[JMS] component - -*Using the link:fluent-builders.html[Fluent Builders]* - -[source,java] -------------------------------------------------------------------------------- -from("direct:start") - .to(ExchangePattern.InOut,"jms:queue:foo?useMessageIDAsCorrelationID=true") - .to("mock:result"); -------------------------------------------------------------------------------- - - - -**Using the link:spring-xml-extensions.html[Spring XML Extensions]** - -[source,xml] ------------------------------------------------------------------------------- -<route> - <from uri="direct:start"/> - <to uri="jms:queue:foo?useMessageIDAsCorrelationID=true" pattern="InOut"/> - <to uri="mock:result"/> -</route> ------------------------------------------------------------------------------- - -[[CorrelationIdentifier-SeeAlso]] -See Also -++++++++ - -* link:bam.html[BAM] - http://git-wip-us.apache.org/repos/asf/camel/blob/f0bae85e/camel-core/src/main/docs/dead-letter-channel.adoc ---------------------------------------------------------------------- diff --git a/camel-core/src/main/docs/dead-letter-channel.adoc b/camel-core/src/main/docs/dead-letter-channel.adoc deleted file mode 100644 index dc11f9c..0000000 --- a/camel-core/src/main/docs/dead-letter-channel.adoc +++ /dev/null @@ -1,507 +0,0 @@ -[[DeadLetterChannel-DeadLetterChannel]] -Dead Letter Channel -~~~~~~~~~~~~~~~~~~~ - -Camel supports the -http://www.enterpriseintegrationpatterns.com/DeadLetterChannel.html[Dead -Letter Channel] from the link:enterprise-integration-patterns.html[EIP -patterns] using the -http://camel.apache.org/maven/current/camel-core/apidocs/org/apache/camel/processor/DeadLetterChannel.html[DeadLetterChannel] -processor which is an link:error-handler.html[Error Handler]. - -image:http://www.enterpriseintegrationpatterns.com/img/DeadLetterChannelSolution.gif[image] - -TIP:*Difference between Dead Letter Channel and Default Error -Handler* - -The Default Error Handler does very little: it ends the Exchange -immediately and propagates the thrown Exception back to the caller. - -The Dead Letter Channel lets you control behaviors including redelivery, -whether to propagate the thrown Exception to the caller (the *handled* -option), and where the (failed) Exchange should now be routed to. - -The Dead Letter Channel is also by default configured to not be verbose -in the logs, so when a message is handled and moved to the dead letter -endpoint, then there is nothing logged. If you want some level of -logging you can use the various options on the redelivery policy / dead -letter channel to configure this. For example if you want the message -history then set logExhaustedMessageHistory=true (and logHandled=true -for Camel 2.15.x or older). - -When the DeadLetterChannel moves a message to the dead letter endpoint, -any new Exception thrown is by default handled by the dead letter -channel as well. This ensures that the DeadLetterChannel will always -succeed. From *Camel 2.15* onwards this behavior can be changed by -setting the option deadLetterHandleNewException=false. Then if a new -Exception is thrown, then the dead letter channel will fail and -propagate back that new Exception (which is the behavior of the default -error handler). When a new Exception occurs then the dead letter channel -logs this at WARN level. This can be turned off by setting -logNewException=false. - -[[DeadLetterChannel-Redelivery]] -Redelivery -^^^^^^^^^^ - -It is common for a temporary outage or database deadlock to cause a -message to fail to process; but the chances are if its tried a few more -times with some time delay then it will complete fine. So we typically -wish to use some kind of redelivery policy to decide how many times to -try redeliver a message and how long to wait before redelivery attempts. - -The -http://camel.apache.org/maven/current/camel-core/apidocs/org/apache/camel/processor/RedeliveryPolicy.html[RedeliveryPolicy] -defines how the message is to be redelivered. You can customize things -like - -* how many times a message is attempted to be redelivered before it is -considered a failure and sent to the dead letter channel -* the initial redelivery timeout -* whether or not exponential backoff is used (i.e. the time between -retries increases using a backoff multiplier) -* whether to use collision avoidance to add some randomness to the -timings -* delay pattern (see below for details) -* *Camel 2.11:* whether to allow redelivery during stopping/shutdown - -Once all attempts at redelivering the message fails then the message is -forwarded to the dead letter queue. - -[[DeadLetterChannel-AboutmovingExchangetodeadletterqueueandusinghandled]] -About moving Exchange to dead letter queue and using handled -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -*Handled* on link:dead-letter-channel.html[Dead Letter Channel] - -When all attempts of redelivery have failed the -link:exchange.html[Exchange] is moved to the dead letter queue (the dead -letter endpoint). The exchange is then complete and from the client -point of view it was processed. As such the -link:dead-letter-channel.html[Dead Letter Channel] have handled the -link:exchange.html[Exchange]. - -For instance configuring the dead letter channel as: - -*Using the link:fluent-builders.html[Fluent Builders]* - -[source,java] ---------------------------------------------------- -errorHandler(deadLetterChannel("jms:queue:dead") - .maximumRedeliveries(3).redeliveryDelay(5000)); ---------------------------------------------------- - -*Using the link:spring-xml-extensions.html[Spring XML Extensions]* - -[source,xml] ----------------------------------------------------------------------------------------------- -<route errorHandlerRef="myDeadLetterErrorHandler"> - ... -</route> - -<bean id="myDeadLetterErrorHandler" class="org.apache.camel.builder.DeadLetterChannelBuilder"> - <property name="deadLetterUri" value="jms:queue:dead"/> - <property name="redeliveryPolicy" ref="myRedeliveryPolicyConfig"/> -</bean> - -<bean id="myRedeliveryPolicyConfig" class="org.apache.camel.processor.RedeliveryPolicy"> - <property name="maximumRedeliveries" value="3"/> - <property name="redeliveryDelay" value="5000"/> -</bean> ----------------------------------------------------------------------------------------------- - -The link:dead-letter-channel.html[Dead Letter Channel] above will clear -the caused exception (`setException(null)`), by moving the caused -exception to a property on the link:exchange.html[Exchange], with the -key `Exchange.EXCEPTION_CAUGHT`. Then the link:exchange.html[Exchange] -is moved to the `"jms:queue:dead"` destination and the client will not -notice the failure. - -[[DeadLetterChannel-AboutmovingExchangetodeadletterqueueandusingtheoriginalmessage]] -About moving Exchange to dead letter queue and using the original -message -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -The option *useOriginalMessage* is used for routing the original input -message instead of the current message that potentially is modified -during routing. - -For instance if you have this route: - -[source,java] ---------------------------------- - from("jms:queue:order:input") - .to("bean:validateOrder") - .to("bean:transformOrder") - .to("bean:handleOrder"); ---------------------------------- - -The route listen for JMS messages and validates, transforms and handle -it. During this the link:exchange.html[Exchange] payload is -transformed/modified. So in case something goes wrong and we want to -move the message to another JMS destination, then we can configure our -link:dead-letter-channel.html[Dead Letter Channel] with the -*useOriginalMessage* option. But when we move the -link:exchange.html[Exchange] to this destination we do not know in which -state the message is in. Did the error happen in before the -transformOrder or after? So to be sure we want to move the original -input message we received from `jms:queue:order:input`. So we can do -this by enabling the *useOriginalMessage* option as shown below: - -[source,java] -------------------------------------------------------------------------- - // will use original body - errorHandler(deadLetterChannel("jms:queue:dead") - .useOriginalMessage().maximumRedeliveries(5).redeliverDelay(5000); -------------------------------------------------------------------------- - -Then the messages routed to the `jms:queue:dead` is the original input. -If we want to manually retry we can move the JMS message from the failed -to the input queue, with no problem as the message is the same as the -original we received. - -[[DeadLetterChannel-OnRedelivery]] -OnRedelivery -^^^^^^^^^^^^ - -When link:dead-letter-channel.html[Dead Letter Channel] is doing -redeliver its possible to configure a link:processor.html[Processor] -that is executed just *before* every redelivery attempt. This can be -used for the situations where you need to alter the message before its -redelivered. See below for sample. - -TIP:*onException and onRedeliver* -We also support for per link:exception-clause.html[*onException*] to set -a *onRedeliver*. That means you can do special on redelivery for -different exceptions, as opposed to onRedelivery set on -link:dead-letter-channel.html[Dead Letter Channel] can be viewed as a -global scope. - - -[[DeadLetterChannel-Redeliverydefaultvalues]] -Redelivery default values -^^^^^^^^^^^^^^^^^^^^^^^^^ - -Redelivery is disabled by default. - -The default redeliver policy will use the following values: - -* maximumRedeliveries=0 -* redeliverDelay=1000L (1 second) -* maximumRedeliveryDelay = 60 * 1000L (60 seconds) -* And the exponential backoff and collision avoidance is turned off. -* The retriesExhaustedLogLevel are set to LoggingLevel.ERROR -* The retryAttemptedLogLevel are set to LoggingLevel.DEBUG -* Stack traces is logged for exhausted messages from Camel 2.2 onwards. -* Handled exceptions is not logged from Camel 2.3 onwards -* logExhaustedMessageHistory is true for default error handler, and -false for dead letter channel. -* logExhaustedMessageBody *Camel 2.17:* is disabled by default to avoid -logging sensitive message body/header details. If this option is true, -then logExhaustedMessageHistory must also be true. - -The maximum redeliver delay ensures that a delay is never longer than -the value, default 1 minute. This can happen if you turn on the -exponential backoff. - -The maximum redeliveries is the number of *re* delivery attempts. By -default Camel will try to process the exchange 1 + 5 times. 1 time for -the normal attempt and then 5 attempts as redeliveries. + - Setting the maximumRedeliveries to a negative value such as -1 will -then always redelivery (unlimited). + - Setting the maximumRedeliveries to 0 will disable any re delivery -attempt. - -Camel will log delivery failures at the DEBUG logging level by default. -You can change this by specifying retriesExhaustedLogLevel and/or -retryAttemptedLogLevel. See -http://svn.apache.org/repos/asf/camel/trunk/camel-core/src/test/java/org/apache/camel/builder/ExceptionBuilderWithRetryLoggingLevelSetTest.java[ExceptionBuilderWithRetryLoggingLevelSetTest] -for an example. - -You can turn logging of stack traces on/off. If turned off Camel will -still log the redelivery attempt. Its just much less verbose. - -[[DeadLetterChannel-RedeliverDelayPattern]] -Redeliver Delay Pattern -+++++++++++++++++++++++ - -Delay pattern is used as a single option to set a range pattern for -delays. If used then the following options does not apply: (delay, -backOffMultiplier, useExponentialBackOff, useCollisionAvoidance, -maximumRedeliveryDelay). - -The idea is to set groups of ranges using the following syntax: -`limit:delay;limit 2:delay 2;limit 3:delay 3;...;limit N:delay N` - -Each group has two values separated with colon - -* limit = upper limit -* delay = delay in millis -And the groups is again separated with semi colon. -The rule of thumb is that the next groups should have a higher limit -than the previous group. - -Lets clarify this with an example: - -`delayPattern=5:1000;10:5000;20:20000` - -That gives us 3 groups: - -* 5:1000 -* 10:5000 -* 20:20000 - -Resulting in these delays for redelivery attempt: - -* Redelivery attempt number 1..4 = 0 millis (as the first group start -with 5) -* Redelivery attempt number 5..9 = 1000 millis (the first group) -* Redelivery attempt number 10..19 = 5000 millis (the second group) -* Redelivery attempt number 20.. = 20000 millis (the last group) - -Note: The first redelivery attempt is 1, so the first group should start -with 1 or higher. - -You can start a group with limit 1 to eg have a starting delay: -`delayPattern=1:1000;5:5000` - -* Redelivery attempt number 1..4 = 1000 millis (the first group) -* Redelivery attempt number 5.. = 5000 millis (the last group) - -There is no requirement that the next delay should be higher than the -previous. You can use any delay value you like. For example with -`delayPattern=1:5000;3:1000` we start with 5 sec delay and then later -reduce that to 1 second. - -[[DeadLetterChannel-Redeliveryheader]] -Redelivery header -^^^^^^^^^^^^^^^^^ - -When a message is redelivered the -http://camel.apache.org/maven/camel-core/apidocs/org/apache/camel/processor/DeadLetterChannel.html[DeadLetterChannel] -will append a customizable header to the message to indicate how many -times its been redelivered. -Before Camel 2.6: The header is *CamelRedeliveryCounter*, which is also -defined on the `Exchange.REDELIVERY_COUNTER`. -Starting with 2.6: The header *CamelRedeliveryMaxCounter*, which is -also defined on the `Exchange.REDELIVERY_MAX_COUNTER`, contains the -maximum redelivery setting. This header is absent if you use -`retryWhile` or have unlimited maximum redelivery configured. - -And a boolean flag whether it is being redelivered or not (first -attempt) -The header *CamelRedelivered* contains a boolean if the message is -redelivered or not, which is also defined on the `Exchange.REDELIVERED`. - -Dynamically calculated delay from the exchange -In Camel 2.9 and 2.8.2: The header is *CamelRedeliveryDelay*, which is -also defined on the `Exchange.REDELIVERY_DELAY`. -Is this header is absent, normal redelivery rules apply. - -[[DeadLetterChannel-Whichendpointfailed]] -Which endpoint failed -+++++++++++++++++++++ - -*Available as of Camel 2.1* - -When Camel routes messages it will decorate the -link:exchange.html[Exchange] with a property that contains the *last* -endpoint Camel send the link:exchange.html[Exchange] to: - -[source,java] ----------------------------------------------------------------------------------- -String lastEndpointUri = exchange.getProperty(Exchange.TO_ENDPOINT, String.class); ----------------------------------------------------------------------------------- - -The `Exchange.TO_ENDPOINT` have the constant value `CamelToEndpoint`. - -This information is updated when Camel sends a message to any endpoint. -So if it exists its the *last* endpoint which Camel send the Exchange -to. - -When for example processing the link:exchange.html[Exchange] at a given -link:endpoint.html[Endpoint] and the message is to be moved into the -dead letter queue, then Camel also decorates the Exchange with another -property that contains that *last* endpoint: - -[source,java] ------------------------------------------------------------------------------------------ -String failedEndpointUri = exchange.getProperty(Exchange.FAILURE_ENDPOINT, String.class); ------------------------------------------------------------------------------------------ - -The `Exchange.FAILURE_ENDPOINT` have the constant value -`CamelFailureEndpoint`. - -This allows for example you to fetch this information in your dead -letter queue and use that for error reporting. + - This is useable if the Camel route is a bit dynamic such as the dynamic -link:recipient-list.html[Recipient List] so you know which endpoints -failed. - -*Notice:* These information is kept on the Exchange even if the message -was successfully processed by a given endpoint, and then later fails for -example in a local link:bean.html[Bean] processing instead. So beware -that this is a hint that helps pinpoint errors. - -[source,java] -------------------------------------- -from("activemq:queue:foo") - .to("http://someserver/somepath") - .beanRef("foo"); -------------------------------------- - -Now suppose the route above and a failure happens in the `foo` bean. -Then the `Exchange.TO_ENDPOINT` and `Exchange.FAILURE_ENDPOINT` will -still contain the value of `http://someserver/somepath`. - -[[DeadLetterChannel-OnPrepareFailure]] -OnPrepareFailure -^^^^^^^^^^^^^^^^ - -*Available as of Camel 2.16* - -Before the exchange is sent to the dead letter queue, you can use -onPrepare to allow a custom `Processor` to prepare the exchange, such as -adding information why the Exchange failed. For example the following -processor adds a header with the exception message - -[source,java] ------------------------------------------------------------------------------------------------ - public static class MyPrepareProcessor implements Processor { - @Override - public void process(Exchange exchange) throws Exception { - Exception cause = exchange.getProperty(Exchange.EXCEPTION_CAUGHT, Exception.class); - exchange.getIn().setHeader("FailedBecause", cause.getMessage()); - } - } ------------------------------------------------------------------------------------------------ - -Then configure the error handler to use the processor as follows: - -[source,java] ---------------------------------------------------------------------------------------- -errorHandler(deadLetterChannel("jms:dead").onPrepareFailure(new MyPrepareProcessor())); ---------------------------------------------------------------------------------------- - -Configuring this from XML DSL is as shown: - -[source,java] --------------------------------------------------------------------------------------------------------------- - <bean id="myPrepare" - class="org.apache.camel.processor.DeadLetterChannelOnPrepareTest.MyPrepareProcessor"/> - - - <errorHandler id="dlc" type="DeadLetterChannel" deadLetterUri="jms:dead" onPrepareFailureRef="myPrepare"/> --------------------------------------------------------------------------------------------------------------- - -The onPrepare is also available using the default error handler. - -[[DeadLetterChannel-Whichroutefailed]] -Which route failed -^^^^^^^^^^^^^^^^^^ - -*Available as of Camel 2.10.4/2.11* - -When Camel error handler handles an error such as -link:dead-letter-channel.html[Dead Letter Channel] or using -link:exception-clause.html[Exception Clause] with handled=true, then -Camel will decorate + - the link:exchange.html[Exchange] with the route id where the error -occurred. - -[source,java] -------------------------------------------------------------------------------------- -String failedRouteId = exchange.getProperty(Exchange.FAILURE_ROUTE_ID, String.class); -------------------------------------------------------------------------------------- - -The `Exchange.FAILURE_ROUTE_ID` have the constant value -`CamelFailureRouteId`. - -This allows for example you to fetch this information in your dead -letter queue and use that for error reporting. - -[[DeadLetterChannel-Controlifredeliveryisallowedduringstoppingshutdown]] -Control if redelivery is allowed during stopping/shutdown -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -*Available as of Camel 2.11* - -Prior to Camel 2.10, Camel will perform redelivery while stopping a -route, or shutting down Camel. This has improved a bit in Camel 2.10 -onwards, as Camel will not perform redelivery attempts when shutting -down aggressively (eg during link:graceful-shutdown.html[Graceful -Shutdown] and timeout hit). From Camel 2.11 onwards there is a new -option `allowRedeliveryWhileStopping` which you can use to control if -redelivery is allowed or not; notice that any in progress redelivery -will still be executed. This option can only disallow any redelivery to -be executed *after* the stopping of a route/shutdown of Camel has been -triggered. If a redelivery is dissallowed then a -`RejectedExcutionException` is set on the link:exchange.html[Exchange] -and the processing of the link:exchange.html[Exchange] stops. This means -any consumer will see the link:exchange.html[Exchange] as failed due the -`RejectedExecutionException`. - -The default value is `true` to be backwards compatible as before. For -example the following sample shows how to do this with Java DSL and XML -DSL - -And the sample sample with XML DSL - -[[DeadLetterChannel-Samples]] -Samples -^^^^^^^ - -The following example shows how to configure the Dead Letter Channel -configuration using the link:dsl.html[DSL] - -You can also configure the -http://camel.apache.org/maven/current/camel-core/apidocs/org/apache/camel/processor/RedeliveryPolicy.html[RedeliveryPolicy] -as this example shows - -[[DeadLetterChannel-HowcanImodifytheExchangebeforeredelivery]] -How can I modify the Exchange before redelivery? -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -We support directly in link:dead-letter-channel.html[Dead Letter -Channel] to set a link:processor.html[Processor] that is executed -*before* each redelivery attempt. - -When link:dead-letter-channel.html[Dead Letter Channel] is doing -redeliver its possible to configure a link:processor.html[Processor] -that is executed just *before* every redelivery attempt. This can be -used for the situations where you need to alter the message before its -redelivered. - -Here we configure the link:dead-letter-channel.html[Dead Letter Channel] -to use our processor `MyRedeliveryProcessor` to be executed before each -redelivery. - -And this is the processor `MyRedeliveryProcessor` where we alter the -message. - -[[DeadLetterChannel-HowcanIlogwhatcausedtheDeadLetterChanneltobeinvoked]] -How can I log what caused the Dead Letter Channel to be invoked? -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -You often need to know what went wrong that caused the Dead Letter -Channel to be used and it does not offer logging for this purpose. So -the Dead Letter Channel's endpoint can be set to a endpoint of our own -(such as `direct:deadLetterChannel`). We write a route to accept this -Exchange and log the Exception, then forward on to where we want the -failed Exchange moved to (which might be a DLQ queue for instance). See -also http://stackoverflow.com/questions/13711462/logging-camel-exceptions-and-sending-to-the-dead-letter-channel[http://stackoverflow.com/questions/13711462/logging-camel-exceptions-and-sending-to-the-dead-letter-channel] - -[[DeadLetterChannel-UsingThisPattern]] -Using This Pattern -++++++++++++++++++ - -If you would like to use this EIP Pattern then please read the -link:getting-started.html[Getting Started], you may also find the -link:architecture.html[Architecture] useful particularly the description -of link:endpoint.html[Endpoint] and link:uris.html[URIs]. Then you could -try out some of the link:examples.html[Examples] first before trying -this pattern out. - -* link:error-handler.html[Error Handler] -* link:exception-clause.html[Exception Clause] - http://git-wip-us.apache.org/repos/asf/camel/blob/f0bae85e/camel-core/src/main/docs/eips/aggregate-eip.adoc ---------------------------------------------------------------------- diff --git a/camel-core/src/main/docs/eips/aggregate-eip.adoc b/camel-core/src/main/docs/eips/aggregate-eip.adoc deleted file mode 100644 index 795a3e8..0000000 --- a/camel-core/src/main/docs/eips/aggregate-eip.adoc +++ /dev/null @@ -1,675 +0,0 @@ -## Aggregate EIP - -*This applies for Camel version 2.3 or newer. If you use an older -version then use this link:aggregator.html[Aggregator] link instead.* - -The -http://www.enterpriseintegrationpatterns.com/Aggregator.html[Aggregator] -from the link:enterprise-integration-patterns.html[EIP patterns] allows -you to combine a number of messages together into a single message. - -image:http://www.enterpriseintegrationpatterns.com/img/Aggregator.gif[image] - -A correlation link:expression.html[Expression] 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. - -### Aggregator options - -// eip options: START -The Aggregate EIP supports 25 options which are listed below: - -{% raw %} -[width="100%",cols="3,1m,6",options="header"] -|======================================================================= -| Name | Java Type | Description -| correlationExpression | NamespaceAwareExpression | *Required* The expression used to calculate the correlation key to use for aggregation. The Exchange 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 ignoreBadCorrelationKeys option. -| completionPredicate | NamespaceAwareExpression | TODO: document Note: this is experimental and subject to changes in future releases. -| completionTimeout | NamespaceAwareExpression | Time in millis that an aggregated exchange should be inactive before its complete (timeout). This option can be set as either a fixed value or using an Expression which allows you to evaluate a timeout dynamically - will use Long as result. If both are set Camel will fallback to use the fixed value if the Expression result was null or 0. You cannot use this option together with completionInterval only one of the two can be used. -| completionSize | NamespaceAwareExpression | Number of messages aggregated before the aggregation is complete. This option can be set as either a fixed value or using an Expression which allows you to evaluate a size dynamically - will use Integer as result. If both are set Camel will fallback to use the fixed value if the Expression result was null or 0. -| optimisticLockRetryPolicy | OptimisticLockRetryPolicyDefinition | Allows to configure retry settings when using optimistic locking. -| parallelProcessing | Boolean | 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. -| optimisticLocking | Boolean | Turns on using optimistic locking which requires the aggregationRepository being used is supporting this by implementing org.apache.camel.spi.OptimisticLockingAggregationRepository. -| executorServiceRef | String | If using parallelProcessing you can specify a custom thread pool to be used. In fact also if you are not using parallelProcessing this custom thread pool is used to send out aggregated exchanges as well. -| timeoutCheckerExecutorServiceRef | String | If using either of the completionTimeout completionTimeoutExpression or completionInterval 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. -| aggregationRepositoryRef | String | Sets the custom aggregate repository to use Will by default use org.apache.camel.processor.aggregate.MemoryAggregationRepository -| strategyRef | String | A reference to lookup the AggregationStrategy in the Registry. Configuring an AggregationStrategy is required and is used to merge the incoming Exchange with the existing already merged exchanges. At first call the oldExchange parameter is null. On subsequent invocations the oldExchange contains the merged exchanges and newExchange is of course the new incoming Exchange. -| strategyMethodName | String | This option can be used to explicit declare the method name to use when using POJOs as the AggregationStrategy. -| strategyMethodAllowNull | Boolean | If this option is false then the aggregate method is not used for the very first aggregation. If this option is true then null values is used as the oldExchange (at the very first aggregation) when using POJOs as the AggregationStrategy. -| completionSize | Integer | Number of messages aggregated before the aggregation is complete. This option can be set as either a fixed value or using an Expression which allows you to evaluate a size dynamically - will use Integer as result. If both are set Camel will fallback to use the fixed value if the Expression result was null or 0. -| completionInterval | Long | 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. -| completionTimeout | Long | Time in millis that an aggregated exchange should be inactive before its complete (timeout). This option can be set as either a fixed value or using an Expression which allows you to evaluate a timeout dynamically - will use Long as result. If both are set Camel will fallback to use the fixed value if the Expression result was null or 0. You cannot use this option together with completionInterval only one of the two can be used. -| completionFromBatchConsumer | Boolean | Enables the batch completion mode where we aggregate from a org.apache.camel.BatchConsumer and aggregate the total number of exchanges the org.apache.camel.BatchConsumer has reported as total by checking the exchange property link org.apache.camel.ExchangeBATCH_COMPLETE when its complete. -| groupExchanges | Boolean | Enables grouped exchanges so the aggregator will group all aggregated exchanges into a single combined Exchange holding all the aggregated exchanges in a java.util.List. -| eagerCheckCompletion | Boolean | Use eager completion checking which means that the completionPredicate will use the incoming Exchange. As opposed to without eager completion checking the completionPredicate will use the aggregated Exchange. -| ignoreInvalidCorrelationKeys | Boolean | If a correlation key cannot be successfully evaluated it will be ignored by logging a DEBUG and then just ignore the incoming Exchange. -| closeCorrelationKeyOnCompletion | Integer | Closes a correlation key when its complete. Any late received exchanges which has a correlation key that has been closed it will be defined and a ClosedCorrelationKeyException is thrown. -| discardOnCompletionTimeout | Boolean | Discards the aggregated message on completion timeout. This means on timeout the aggregated message is dropped and not sent out of the aggregator. -| forceCompletionOnStop | Boolean | Indicates to complete all current aggregated exchanges when the context is stopped -| completeAllOnStop | Boolean | Indicates to wait to complete all current and partial (pending) aggregated exchanges when the context is stopped. This also means that we will wait for all pending exchanges which are stored in the aggregation repository to complete so the repository is empty before we can stop. You may want to enable this when using the memory based aggregation repository that is memory based only and do not store data on disk. When this option is enabled then the aggregator is waiting to complete all those exchanges before its stopped when stopping CamelContext or the route using it. -| aggregateControllerRef | String | To use a org.apache.camel.processor.aggregate.AggregateController to allow external sources to control this aggregator. -|======================================================================= -{% endraw %} -// eip options: END - -### About AggregationStrategy - -The `AggregationStrategy` 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. - -Notice the aggregation strategy is a mandatory option and must be -provided to the aggregator. - -Here are a few example AggregationStrategy implementations that should -help you create your own custom strategy. - -[source,java] ---------------------------------------------------------------------------- -//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<Object> -class ArrayListAggregationStrategy implements AggregationStrategy { - - public Exchange aggregate(Exchange oldExchange, Exchange newExchange) { - Object newBody = newExchange.getIn().getBody(); - ArrayList<Object> list = null; - if (oldExchange == null) { - list = new ArrayList<Object>(); - list.add(newBody); - newExchange.getIn().setBody(list); - return newExchange; - } else { - list = oldExchange.getIn().getBody(ArrayList.class); - list.add(newBody); - return oldExchange; - } - } -} ---------------------------------------------------------------------------- - -### About completion - -When aggregation link:exchange.html[Exchange]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: - -* completionTimeout - Is an inactivity timeout in which is triggered if -no new exchanges have been aggregated for that particular correlation -key within the period. -* completionInterval - Once every X period all the current aggregated -exchanges are completed. -* completionSize - Is a number indicating that after X aggregated -exchanges it's complete. -* completionPredicate - Runs a link:predicate.html[Predicate] when a new -exchange is aggregated to determine if we are complete or not. Staring -in *Camel 2.15*, the configured aggregationStrategy can implement the -Predicate interface and will be used as the completionPredicate if no -completionPredicate is configured. From *Camel 2.16*, the configured -aggregationStrategy can -implement `PreCompletionAwareAggregationStrategy` and will be used as -the completionPredicate in pre-complete check mode. See further below -for more details. -* completionFromBatchConsumer - Special option for -link:batch-consumer.html[Batch Consumer] which allows you to complete -when all the messages from the batch has been aggregated. -* forceCompletionOnStop - *Camel 2.9* Indicates to complete all current -aggregated exchanges when the context is stopped -* Using a `AggregateController` - *Camel 2.16* which allows to use an -external source to complete groups or all groups. This can be done using -Java or JMX API. - -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. - -Notice the completion is a mandatory option and must be provided to the -aggregator. If not provided Camel will thrown an Exception on startup. - -### Pre-completion mode - -*available as of Camel 2.16* - -There can be use-cases where you want the incoming -link:exchange.html[Exchange] to determine if the correlation group -should pre-complete, and then the incoming -link:exchange.html[Exchange] is starting a new group from scratch. To -determine this the `AggregationStrategy` can -implement `PreCompletionAwareAggregationStrategy` which has -a `preComplete` method: - -[source,java] ----------------------------------------------------------------------------------------------------------------------- - /** - * Determines if the aggregation should complete the current group, and start a new group, or the aggregation - * should continue using the current group. - * - * @param oldExchange the oldest exchange (is <tt>null</tt> on first aggregation as we only have the new exchange) - * @param newExchange the newest exchange (can be <tt>null</tt> if there was no data possible to acquire) - * @return <tt>true</tt> to complete current group and start a new group, or <tt>false</tt> to keep using current - */ - boolean preComplete(Exchange oldExchange, Exchange newExchange); ----------------------------------------------------------------------------------------------------------------------- - -If the preComplete method returns true, then the existing groups is -completed (without aggregating the incoming exchange (newExchange). And -then the newExchange is used to start the correlation group from scratch -so the group would contain only that new incoming exchange. This is -known as pre-completion mode. And when the aggregation is in -pre-completion mode, then only the following completions are in use - -* aggregationStrategy must -implement `PreCompletionAwareAggregationStrategy` xxx -* completionTimeout or completionInterval can also be used as fallback -completions -* any other completion are not used (such as by size, from batch -consumer etc) -* eagerCheckCompletion is implied as true, but the option has no effect - -### Persistent AggregationRepository - -The aggregator provides a pluggable repository which you can implement -your own `org.apache.camel.spi.AggregationRepository`. + - If you need persistent repository then you can use either Camel -link:hawtdb.html[HawtDB], link:leveldb.html[LevelDB], or -link:sql-component.html[SQL Component] components. - -### Using TimeoutAwareAggregationStrategy - -*Available as of Camel 2.9.2* - -If your aggregation strategy implements -`TimeoutAwareAggregationStrategy`, then Camel will invoke the `timeout` -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 *not* throw any exceptions -from the `timeout` method. - -### Using CompletionAwareAggregationStrategy - -*Available as of Camel 2.9.3* - -If your aggregation strategy implements -`CompletionAwareAggregationStrategy`, then Camel will invoke the -`onComplete` 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. + - You must *not* throw any exceptions from the `onCompletion` method. - -### Completing current group decided from the AggregationStrategy - -*Available as of Camel 2.15* - -The `AggregationStrategy` can now included a property on the -returned `Exchange` that contains a boolean to indicate if the current -group should be completed. This allows to overrule any existing -completion predicates / sizes / timeouts etc, and complete the group. - -For example the following logic (from an unit test) will complete the -group if the message body size is larger than 5. This is done by setting -the property Exchange.AGGREGATION_COMPLETE_CURRENT_GROUP to true. - -[source,java] -------------------------------------------------------------------------------------------- - public final class MyCompletionStrategy implements AggregationStrategy { - @Override - public Exchange aggregate(Exchange oldExchange, Exchange newExchange) { - if (oldExchange == null) { - return newExchange; - } - String body = oldExchange.getIn().getBody(String.class) + "+" - + newExchange.getIn().getBody(String.class); - oldExchange.getIn().setBody(body); - if (body.length() >= 5) { - oldExchange.setProperty(Exchange.AGGREGATION_COMPLETE_CURRENT_GROUP, true); - } - return oldExchange; - } - } -------------------------------------------------------------------------------------------- - - -### Manually Force the Completion of All Aggregated Exchanges Immediately - -*Available as of Camel 2.9* + - 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. - -*Available as of Camel 2.11* + - 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. - -### Using a List<V> in AggregationStrategy - -*Available as of Camel 2.11* - -If you want to aggregate some value from the messages <V> into a List<V> -then we have added a -`org.apache.camel.processor.aggregate.AbstractListAggregationStrategy` -abstract class in *Camel 2.11* that makes this easier. The completed -Exchange that is sent out of the aggregator will contain the List<V> in -the message body. - -For example to aggregate a List<Integer> you can extend this class as -shown below, and implement the `getValue` method: - -### Using AggregateController - -*Available as of Camel 2.16* - -The `org.apache.camel.processor.aggregate.AggregateController` allows -you to control the aggregate at runtime using Java or JMX API. This can -be used to force completing groups of exchanges, or query its current -runtime statistics. - -The aggregator provides a default implementation if no custom have been -configured, which can be accessed -using `getAggregateController()` method. Though it may be easier to -configure a controller in the route using aggregateController as shown -below: - -[source,java] ----------------------------------------------------------------------------------------------- -private AggregateController controller = new DefaultAggregateController(); - -from("direct:start") - .aggregate(header("id"), new MyAggregationStrategy()).completionSize(10).id("myAggregator") - .aggregateController(controller) - .to("mock:aggregated"); ----------------------------------------------------------------------------------------------- - -Then there is API on AggregateController to force completion. For -example to complete a group with key foo - -[source,java] ------------------------------------------------------- -int groups = controller.forceCompletionOfGroup("foo"); ------------------------------------------------------- - -The number return would be the number of groups completed. In this case -it would be 1 if the foo group existed and was completed. If foo does -not exists then 0 is returned. - -There is also an api to complete all groups - -[source,java] ------------------------------------------------------ -int groups = controller.forceCompletionOfAllGroups(); ------------------------------------------------------ - - - -To configure this from XML DSL - -[source,java] ----------------------------------------------------------------------------------------------------------- -<bean id="myController" class="org.apache.camel.processor.aggregate.DefaultAggregateController"/> - - <camelContext xmlns="http://camel.apache.org/schema/spring"> - <route> - <from uri="direct:start"/> - <aggregate strategyRef="myAppender" completionSize="10" aggregateControllerRef="myController"> - <correlationExpression> - <header>id</header> - </correlationExpression> - <to uri="mock:result"/> - </aggregate> - </route> - </camelContext> ----------------------------------------------------------------------------------------------------------- - - - -There is also JMX API on the aggregator which is available under the -processors node in the Camel JMX tree. - -### Using GroupedExchanges - -In the route below we group all the exchanges together using -`groupExchanges()`: - -[source,java] --------------------------------------------------------------------------------------------------- - from("direct:start") - // aggregate all using same expression - .aggregate(constant(true)) - // wait for 0.5 seconds to aggregate - .completionTimeout(500L) - // group the exchanges so we get one single exchange containing all the others - .groupExchanges() - .to("mock:result"); --------------------------------------------------------------------------------------------------- - -As a result we have one outgoing link:exchange.html[Exchange] being -routed the the "mock:result" endpoint. The exchange is a holder -containing all the incoming Exchanges. + - To get access to these exchanges you need to access them from a -property on the outgoing exchange as shown: - -[source,java] --------------------------------------------------------------------------------- -List<Exchange> grouped = out.getProperty(Exchange.GROUPED_EXCHANGE, List.class); --------------------------------------------------------------------------------- - -From *Camel 2.13* onwards this behavior has changed to store these -exchanges directly on the message body which is more intuitive: - -[source,java] --------------------------------------------------------------- -List<Exchange> grouped = exchange.getIn().getBody(List.class); --------------------------------------------------------------- - -### Using POJOs as AggregationStrategy - -*Available as of Camel 2.12* - -To use the `AggregationStrategy` you had to implement the -`org.apache.camel.processor.aggregate.AggregationStrategy` interface, -which means your logic would be tied to the Camel API. From *Camel 2.12* -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: - -* there must be a public method to use -* the method must not be void -* the method can be static or non-static -* the method must have 2 or more parameters -* the parameters is paired so the first 50% is applied to the -`oldExchange` and the reminder 50% is for the `newExchange` -* .. meaning that there must be an equal number of parameters, eg 2, 4, -6 etc. - -The paired methods is expected to be ordered as follows: - -* the first parameter is the message body -* the 2nd parameter is a Map of the headers -* the 3rd parameter is a Map of the Exchange properties - -This convention is best explained with some examples. - -In the method below, we have only 2 parameters, so the 1st parameter is -the body of the `oldExchange`, and the 2nd is paired to the body of the -`newExchange`: - -[source,java] ----------------------------------------------------- -public String append(String existing, String next) { - return existing + next; -} ----------------------------------------------------- - -In the method below, we have only 4 parameters, so the 1st parameter is -the body of the `oldExchange`, and the 2nd is the Map of the -`oldExchange} headers, and the 3rd is paired to the body of the {{newExchange`, -and the 4th parameter is the Map of the `newExchange` headers: - -[source,java] ------------------------------------------------------------------------------------------- -public String append(String existing, Map existingHeaders, String next, Map nextHeaders) { - return existing + next; -} ------------------------------------------------------------------------------------------- - -And finally if we have 6 parameters the we also have the properties of -the link:exchange.html[Exchange]s: - -[source,java] --------------------------------------------------------------------------------------------------------------------------------------- -public String append(String existing, Map existingHeaders, Map existingProperties, String next, Map nextHeaders, Map nextProperties) { - return existing + next; -} --------------------------------------------------------------------------------------------------------------------------------------- - -To use this with the link:aggregator2.html[Aggregate] EIP we can use a -POJO with the aggregate logic as follows: - -[source,java] --------------------------------------------------------- -public class MyBodyAppender { - - public String append(String existing, String next) { - return next + existing; - } - -} --------------------------------------------------------- - -And then in the Camel route we create an instance of our bean, and then -refer to the bean in the route using `bean` method from -`org.apache.camel.util.toolbox.AggregationStrategies` as shown: - -[source,java] --------------------------------------------------------------------------------------- - 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"); - } --------------------------------------------------------------------------------------- - -We can also provide the bean type directly: - -[source,java] --------------------------------------------------------------------------------------------------- - public void configure() throws Exception { - from("direct:start") - .aggregate(constant(true), AggregationStrategies.bean(MyBodyAppender.class, "append")) - .completionSize(3) - .to("mock:result"); - } --------------------------------------------------------------------------------------------------- - -And if the bean has only one method we do not need to specify the name -of the method: - -[source,java] ----------------------------------------------------------------------------------------- - public void configure() throws Exception { - from("direct:start") - .aggregate(constant(true), AggregationStrategies.bean(MyBodyAppender.class)) - .completionSize(3) - .to("mock:result"); - } ----------------------------------------------------------------------------------------- - -And the `append` method could be static: - -[source,java] ---------------------------------------------------------------- -public class MyBodyAppender { - - public static String append(String existing, String next) { - return next + existing; - } - -} ---------------------------------------------------------------- - -If you are using XML DSL then we need to declare a <bean> with the POJO: - -[source,xml] ----------------------------------------------------------- - <bean id="myAppender" class="com.foo.MyBodyAppender"/> ----------------------------------------------------------- - -And in the Camel route we use `strategyRef` to refer to the bean by its -id, and the `strategyMethodName` can be used to define the method name -to call: - -[source,xml] ------------------------------------------------------------------------------------------------ - <camelContext xmlns="http://camel.apache.org/schema/spring"> - <route> - <from uri="direct:start"/> - <aggregate strategyRef="myAppender" strategyMethodName="append" completionSize="3"> - <correlationExpression> - <constant>true</constant> - </correlationExpression> - <to uri="mock:result"/> - </aggregate> - </route> - </camelContext> ------------------------------------------------------------------------------------------------ - -When using XML DSL you must define the POJO as a <bean>. - -### Aggregating when no data - -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 -link:aggregator2.html[Aggregate] EIP will invoke the -`AggregationStrategy` with `oldExchange` as null, for the first -link:exchange.html[Exchange] incoming to the aggregator. And then for -subsequent link:exchange.html[Exchange]s then `oldExchange` and -`newExchange` parameters are both not null. - -Example with link:content-enricher.html[Content Enricher] and no data - -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. - -[source,java] ------------------------------------------------------------------------------------------------------------ - 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"); - } ------------------------------------------------------------------------------------------------------------ - -This can be configured a bit easier using the `beanAllowNull` method -from `AggregationStrategies` as shown: - -[source,java] --------------------------------------------------------------------------------------------------- - public void configure() throws Exception { - from("direct:start") - .pollEnrich("seda:foo", 1000, AggregationStrategies.beanAllowNull(appender, "append")) - .to("mock:result"); - } --------------------------------------------------------------------------------------------------- - -Then the `append` method in the POJO would need to deal with the -situation that `newExchange` can be null: - -[source,java] ------------------------------------------------------------- - public class MyBodyAppender { - - public String append(String existing, String next) { - if (next == null) { - return "NewWasNull" + existing; - } else { - return existing + next; - } - } - - } ------------------------------------------------------------- - -In the example above we use the link:content-enricher.html[Content -Enricher] EIP using `pollEnrich`. The `newExchange` 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 `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 link:content-enricher.html[Content Enricher] did -not merge/change the message. - -In XML DSL you would configure the `strategyMethodAllowNull` option and -set it to true as shown below: - -[source,xml] ------------------------------------------------------------------------------------------------------------------------------- - <camelContext xmlns="http://camel.apache.org/schema/spring"> - <route> - <from uri="direct:start"/> - <aggregate strategyRef="myAppender" strategyMethodName="append" strategyMethodAllowNull="true" completionSize="3"> - <correlationExpression> - <constant>true</constant> - </correlationExpression> - <to uri="mock:result"/> - </aggregate> - </route> - </camelContext> ------------------------------------------------------------------------------------------------------------------------------- - -### Different body types - -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<String>` that contains the user name. We could code a POJO doing -this as follows: - -[source,java] ------------------------------------------------------ - public static final class MyUserAppender { - - public List addUsers(List names, User user) { - if (names == null) { - names = new ArrayList(); - } - names.add(user.getName()); - return names; - } - } ------------------------------------------------------ - -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. - -### See also - -* The link:loan-broker-example.html[Loan Broker Example] which uses an -aggregator -* -http://tmielke.blogspot.com/2009/01/using-camel-aggregator-correctly.html[Blog -post by Torsten Mielke] about using the aggregator correctly. -* The old link:aggregator.html[Aggregator] -* link:hawtdb.html[HawtDB], link:leveldb.html[LevelDB] or -link:sql-component.html[SQL Component] for persistence support -* link:aggregate-example.html[Aggregate Example] for an example -application