Modified: websites/production/camel/content/transactional-client.html
==============================================================================
--- websites/production/camel/content/transactional-client.html (original)
+++ websites/production/camel/content/transactional-client.html Fri Aug 25
08:22:01 2017
@@ -36,17 +36,6 @@
<![endif]-->
- <link href='//camel.apache.org/styles/highlighter/styles/shCoreCamel.css'
rel='stylesheet' type='text/css' />
- <link href='//camel.apache.org/styles/highlighter/styles/shThemeCamel.css'
rel='stylesheet' type='text/css' />
- <script src='//camel.apache.org/styles/highlighter/scripts/shCore.js'
type='text/javascript'></script>
- <script src='//camel.apache.org/styles/highlighter/scripts/shBrushJava.js'
type='text/javascript'></script>
- <script src='//camel.apache.org/styles/highlighter/scripts/shBrushXml.js'
type='text/javascript'></script>
- <script src='//camel.apache.org/styles/highlighter/scripts/shBrushPlain.js'
type='text/javascript'></script>
-
- <script type="text/javascript">
- SyntaxHighlighter.defaults['toolbar'] = false;
- SyntaxHighlighter.all();
- </script>
<title>
Apache Camel: Transactional Client
@@ -86,199 +75,48 @@
<tbody>
<tr>
<td valign="top" width="100%">
-<div class="wiki-content maincontent"><h3
id="TransactionalClient-TransactionalClient">Transactional Client</h3><p>Camel
recommends supporting the <a shape="rect" class="external-link"
href="http://www.enterpriseintegrationpatterns.com/TransactionalClient.html"
rel="nofollow">Transactional Client</a> from the <a shape="rect"
href="enterprise-integration-patterns.html">EIP patterns</a> using spring
transactions.</p><p><span class="confluence-embedded-file-wrapper"><img
class="confluence-embedded-image confluence-external-resource"
src="http://www.enterpriseintegrationpatterns.com/img/TransactionalClientSolution.gif"
data-image-src="http://www.enterpriseintegrationpatterns.com/img/TransactionalClientSolution.gif"></span></p><p>Transaction
Oriented Endpoints like <a shape="rect" href="jms.html">JMS</a> support using
a transaction for both inbound and outbound message exchanges. Endpoints that
support transactions will participate in the current transaction context that
they are called
from.</p><div class="confluence-information-macro
confluence-information-macro-tip"><p class="title">Configuration of
Redelivery</p><span class="aui-icon aui-icon-small aui-iconfont-approve
confluence-information-macro-icon"></span><div
class="confluence-information-macro-body"><p>The redelivery in transacted mode
is <strong>not</strong> handled by Camel but by the backing system (the
transaction manager). In such cases you should resort to the backing system how
to configure the redelivery.</p></div></div><p>You should use the <a
shape="rect" class="external-link"
href="http://camel.apache.org/maven/current/camel-spring/apidocs/org/apache/camel/spring/SpringRouteBuilder.html">SpringRouteBuilder</a>
to setup the routes since you will need to setup the spring context with the
TransactionTemplates that will define the transaction manager configuration and
policies.</p><p>For inbound endpoint to be transacted, they normally need to be
configured to use a Spring PlatformTransactionManag
er. In the case of the JMS component, this can be done by looking it up in the
spring context.</p><p>You first define needed object in the spring
configuration.</p><div class="code panel pdl" style="border-width: 1px;"><div
class="codeContent panelContent pdl">
-<script class="brush: xml; gutter: false; theme: Default"
type="syntaxhighlighter"><![CDATA[ <bean
id="jmsTransactionManager"
class="org.springframework.jms.connection.JmsTransactionManager">
- <property name="connectionFactory"
ref="jmsConnectionFactory" />
+<div class="wiki-content maincontent"><h3
id="TransactionalClient-TransactionalClient">Transactional Client</h3><p>Camel
recommends supporting the <a shape="rect" class="external-link"
href="http://www.enterpriseintegrationpatterns.com/TransactionalClient.html"
rel="nofollow">Transactional Client</a> from the <a shape="rect"
href="enterprise-integration-patterns.html">EIP patterns</a> using spring
transactions.</p><p><span class="confluence-embedded-file-wrapper"><img
class="confluence-embedded-image confluence-external-resource"
src="http://www.enterpriseintegrationpatterns.com/img/TransactionalClientSolution.gif"
data-image-src="http://www.enterpriseintegrationpatterns.com/img/TransactionalClientSolution.gif"></span></p><p>Transaction
Oriented Endpoints like <a shape="rect" href="jms.html">JMS</a> support using
a transaction for both inbound and outbound message exchanges. Endpoints that
support transactions will participate in the current transaction context that
they are called
from.</p><parameter ac:name="title">Configuration of
Redelivery</parameter><rich-text-body><p>The redelivery in transacted mode is
<strong>not</strong> handled by Camel but by the backing system (the
transaction manager). In such cases you should resort to the backing system how
to configure the redelivery.</p></rich-text-body><p>You should use the <a
shape="rect" class="external-link"
href="http://camel.apache.org/maven/current/camel-spring/apidocs/org/apache/camel/spring/SpringRouteBuilder.html">SpringRouteBuilder</a>
to setup the routes since you will need to setup the spring context with the
TransactionTemplates that will define the transaction manager configuration and
policies.</p><p>For inbound endpoint to be transacted, they normally need to be
configured to use a Spring PlatformTransactionManager. In the case of the JMS
component, this can be done by looking it up in the spring context.</p><p>You
first define needed object in the spring configuration.</p><parameter ac:name=
"">xml</parameter><plain-text-body> <bean id="jmsTransactionManager"
class="org.springframework.jms.connection.JmsTransactionManager">
+ <property name="connectionFactory" ref="jmsConnectionFactory" />
</bean>
- <bean id="jmsConnectionFactory"
class="org.apache.activemq.ActiveMQConnectionFactory">
- <property name="brokerURL"
value="tcp://localhost:61616"/>
+ <bean id="jmsConnectionFactory"
class="org.apache.activemq.ActiveMQConnectionFactory">
+ <property name="brokerURL" value="tcp://localhost:61616"/>
</bean>
-]]></script>
-</div></div><p>Then you look them up and use them to create the
JmsComponent.</p><div class="code panel pdl" style="border-width: 1px;"><div
class="codeContent panelContent pdl">
-<script class="brush: java; gutter: false; theme: Default"
type="syntaxhighlighter"><![CDATA[ PlatformTransactionManager
transactionManager = (PlatformTransactionManager)
spring.getBean("jmsTransactionManager");
- ConnectionFactory connectionFactory = (ConnectionFactory)
spring.getBean("jmsConnectionFactory");
+</plain-text-body><p>Then you look them up and use them to create the
JmsComponent.</p><parameter
ac:name="language">java</parameter><plain-text-body>
PlatformTransactionManager transactionManager = (PlatformTransactionManager)
spring.getBean("jmsTransactionManager");
+ ConnectionFactory connectionFactory = (ConnectionFactory)
spring.getBean("jmsConnectionFactory");
JmsComponent component =
JmsComponent.jmsComponentTransacted(connectionFactory, transactionManager);
component.getConfiguration().setConcurrentConsumers(1);
- ctx.addComponent("activemq", component);
-]]></script>
-</div></div><h4 id="TransactionalClient-TransactionPolicies">Transaction
Policies</h4><p>Outbound endpoints will automatically enlist in the current
transaction context. But what if you do not want your outbound endpoint to
enlist in the same transaction as your inbound endpoint? The solution is to add
a Transaction Policy to the processing route. You first have to define
transaction policies that you will be using. The policies use a spring
TransactionTemplate under the covers for declaring the transaction demarcation
to use. So you will need to add something like the following to your spring
xml:</p><div class="code panel pdl" style="border-width: 1px;"><div
class="codeContent panelContent pdl">
-<script class="brush: xml; gutter: false; theme: Default"
type="syntaxhighlighter"><![CDATA[ <bean
id="PROPAGATION_REQUIRED"
class="org.apache.camel.spring.spi.SpringTransactionPolicy">
- <property name="transactionManager"
ref="jmsTransactionManager"/>
+ ctx.addComponent("activemq", component);
+</plain-text-body><h4 id="TransactionalClient-TransactionPolicies">Transaction
Policies</h4><p>Outbound endpoints will automatically enlist in the current
transaction context. But what if you do not want your outbound endpoint to
enlist in the same transaction as your inbound endpoint? The solution is to add
a Transaction Policy to the processing route. You first have to define
transaction policies that you will be using. The policies use a spring
TransactionTemplate under the covers for declaring the transaction demarcation
to use. So you will need to add something like the following to your spring
xml:</p><parameter ac:name="">xml</parameter><plain-text-body> <bean
id="PROPAGATION_REQUIRED"
class="org.apache.camel.spring.spi.SpringTransactionPolicy">
+ <property name="transactionManager" ref="jmsTransactionManager"/>
</bean>
- <bean id="PROPAGATION_REQUIRES_NEW"
class="org.apache.camel.spring.spi.SpringTransactionPolicy">
- <property name="transactionManager"
ref="jmsTransactionManager"/>
- <property name="propagationBehaviorName"
value="PROPAGATION_REQUIRES_NEW"/>
+ <bean id="PROPAGATION_REQUIRES_NEW"
class="org.apache.camel.spring.spi.SpringTransactionPolicy">
+ <property name="transactionManager" ref="jmsTransactionManager"/>
+ <property name="propagationBehaviorName"
value="PROPAGATION_REQUIRES_NEW"/>
</bean>
-]]></script>
-</div></div><p>Then in your <a shape="rect" class="external-link"
href="http://camel.apache.org/maven/current/camel-spring/apidocs/org/apache/camel/spring/SpringRouteBuilder.html">SpringRouteBuilder</a>,
you just need to create new SpringTransactionPolicy objects for each of the
templates.</p><div class="code panel pdl" style="border-width: 1px;"><div
class="codeContent panelContent pdl">
-<script class="brush: java; gutter: false; theme: Default"
type="syntaxhighlighter"><![CDATA[public void configure() {
+</plain-text-body><p>Then in your <a shape="rect" class="external-link"
href="http://camel.apache.org/maven/current/camel-spring/apidocs/org/apache/camel/spring/SpringRouteBuilder.html">SpringRouteBuilder</a>,
you just need to create new SpringTransactionPolicy objects for each of the
templates.</p><parameter ac:name="">java</parameter><plain-text-body>public
void configure() {
...
- Policy requried = bean(SpringTransactionPolicy.class,
"PROPAGATION_REQUIRED"));
- Policy requirenew = bean(SpringTransactionPolicy.class,
"PROPAGATION_REQUIRES_NEW"));
+ Policy requried = bean(SpringTransactionPolicy.class,
"PROPAGATION_REQUIRED"));
+ Policy requirenew = bean(SpringTransactionPolicy.class,
"PROPAGATION_REQUIRES_NEW"));
...
}
-]]></script>
-</div></div><p>Once created, you can use the Policy objects in your processing
routes:</p><div class="code panel pdl" style="border-width: 1px;"><div
class="codeContent panelContent pdl">
-<script class="brush: java; gutter: false; theme: Default"
type="syntaxhighlighter"><![CDATA[ // Send to bar in a new transaction
-
from("activemq:queue:foo").policy(requirenew).to("activemq:queue:bar");
+</plain-text-body><p>Once created, you can use the Policy objects in your
processing routes:</p><parameter ac:name="">java</parameter><plain-text-body>
// Send to bar in a new transaction
+ from("activemq:queue:foo").policy(requirenew).to("activemq:queue:bar");
// Send to bar without a transaction.
- from("activemq:queue:foo").policy(notsupported
).to("activemq:queue:bar");
+ from("activemq:queue:foo").policy(notsupported ).to("activemq:queue:bar");
-]]></script>
-</div></div><h4 id="TransactionalClient-OSGiBlueprint">OSGi
Blueprint</h4><p>If you are using <a shape="rect"
href="using-osgi-blueprint-with-camel.html">OSGi Blueprint</a> then you most
likely have to explicit declare a policy and refer to the policy from the
transacted in the route.</p><div class="code panel pdl" style="border-width:
1px;"><div class="codeContent panelContent pdl">
-<script class="brush: xml; gutter: false; theme: Default"
type="syntaxhighlighter"><![CDATA[ <bean id="required"
class="org.apache.camel.spring.spi.SpringTransactionPolicy">
- <property name="transactionManager"
ref="jmsTransactionManager"/>
- <property name="propagationBehaviorName"
value="PROPAGATION_REQUIRED"/>
+</plain-text-body><h4 id="TransactionalClient-OSGiBlueprint">OSGi
Blueprint</h4><p>If you are using <a shape="rect"
href="using-osgi-blueprint-with-camel.html">OSGi Blueprint</a> then you most
likely have to explicit declare a policy and refer to the policy from the
transacted in the route.</p><parameter
ac:name="">xml</parameter><plain-text-body> <bean id="required"
class="org.apache.camel.spring.spi.SpringTransactionPolicy">
+ <property name="transactionManager" ref="jmsTransactionManager"/>
+ <property name="propagationBehaviorName"
value="PROPAGATION_REQUIRED"/>
</bean>
-]]></script>
-</div></div><p>And then refer to "required" from the route:</p><div
class="code panel pdl" style="border-width: 1px;"><div class="codeContent
panelContent pdl">
-<script class="brush: xml; gutter: false; theme: Default"
type="syntaxhighlighter"><![CDATA[<route>
- <from uri="activemq:queue:foo"/>
- <transacted ref="required"/>
- <to uri="activemq:queue:bar"/>
+</plain-text-body><p>And then refer to "required" from the
route:</p><parameter ac:name="">xml</parameter><plain-text-body><route>
+ <from uri="activemq:queue:foo"/>
+ <transacted ref="required"/>
+ <to uri="activemq:queue:bar"/>
</route>
-]]></script>
-</div></div><h3 id="TransactionalClient-DatabaseSample">Database
Sample</h3><p>In this sample we want to ensure that two endpoints is under
transaction control. These two endpoints inserts data into a database.<br
clear="none"> The sample is in its full as a <a shape="rect"
class="external-link"
href="http://svn.apache.org/viewvc/camel/trunk/components/camel-spring/src/test/java/org/apache/camel/spring/interceptor/TransactionalClientDataSourceMinimalConfigurationTest.java?view=log">unit
test</a>.</p><p>First of all we setup the usual spring stuff in its
configuration file. Here we have defined a DataSource to the HSQLDB and a most
importantly the Spring DataSource TransactionManager that is doing the
heavy lifting of ensuring our transactional policies. You are of course free to
use any of the Spring based TransactionManager, eg. if you are in a full
blown J2EE container you could use JTA or the WebLogic or WebSphere specific
managers.</p><p>As we use the new convention ov
er configuration we do <strong>not</strong> need to configure a transaction
policy bean, so we do not have any <code>PROPAGATION_REQUIRED</code>
beans. All the beans needed to be configured is <strong>standard</strong>
Spring beans only, eg. there are no Camel specific configuration at
all.</p><div class="code panel pdl" style="border-width: 1px;"><div
class="codeContent panelContent pdl">
-<script class="brush: xml; gutter: false; theme: Default"
type="syntaxhighlighter"><![CDATA[
-<!-- this example uses JDBC so we define a data source -->
-<jdbc:embedded-database id="dataSource" type="DERBY">
- <jdbc:script location="classpath:sql/init.sql" />
-</jdbc:embedded-database>
-
-<!-- spring transaction manager -->
-<!-- this is the transaction manager Camel will use for transacted routes
-->
-<bean id="txManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
- <property name="dataSource" ref="dataSource"/>
-</bean>
-
-<!-- bean for book business logic -->
-<bean id="bookService"
class="org.apache.camel.spring.interceptor.BookService">
- <property name="dataSource" ref="dataSource"/>
-</bean>
-]]></script>
-</div></div>Then we are ready to define our Camel routes. We have two routes:
1 for success conditions, and 1 for a forced rollback condition.<br
clear="none"> This is after all based on a unit test. Notice that we mark each
route as transacted using the <strong>transacted</strong> tag.<div class="code
panel pdl" style="border-width: 1px;"><div class="codeContent panelContent pdl">
-<script class="brush: xml; gutter: false; theme: Default"
type="syntaxhighlighter"><![CDATA[
-<camelContext xmlns="http://camel.apache.org/schema/spring">
- <route>
- <from uri="direct:okay"/>
- <!-- we mark this route as transacted. Camel will lookup the spring
transaction manager
- and use it by default. We can optimally pass in arguments to
specify a policy to use
- that is configured with a spring transaction manager of choice.
However Camel supports
- convention over configuration as we can just use the defaults out
of the box and Camel
- that suites in most situations -->
- <transacted/>
- <setBody>
- <constant>Tiger in Action</constant>
- </setBody>
- <bean ref="bookService"/>
- <setBody>
- <constant>Elephant in Action</constant>
- </setBody>
- <bean ref="bookService"/>
- </route>
-
- <route>
- <from uri="direct:fail"/>
- <!-- we mark this route as transacted. See comments above. -->
- <transacted/>
- <setBody>
- <constant>Tiger in Action</constant>
- </setBody>
- <bean ref="bookService"/>
- <setBody>
- <constant>Donkey in Action</constant>
- </setBody>
- <bean ref="bookService"/>
- </route>
-</camelContext>
-]]></script>
-</div></div>That is all that is needed to configure a Camel route as being
transacted. Just remember to use the <strong>transacted</strong> DSL. The rest
is standard Spring XML to setup the transaction manager.<h3
id="TransactionalClient-JMSSample">JMS Sample</h3><p>In this sample we want to
listen for messages on a queue and process the messages with our business logic
java code and send them along. Since its based on a <a shape="rect"
class="external-link"
href="http://svn.apache.org/viewvc/camel/trunk/components/camel-jms/src/test/java/org/apache/camel/component/jms/tx/TransactionMinimalConfigurationTest.java?view=log">unit
test</a> the destination is a mock endpoint.</p><p>First we configure the
standard Spring XML to declare a JMS connection factory, a JMS transaction
manager and our ActiveMQ component that we use in our routing.</p><div
class="code panel pdl" style="border-width: 1px;"><div class="codeContent
panelContent pdl">
-<script class="brush: xml; gutter: false; theme: Default"
type="syntaxhighlighter"><![CDATA[
-<!-- setup JMS connection factory -->
-<bean id="poolConnectionFactory"
class="org.apache.activemq.pool.PooledConnectionFactory"
init-method="start" destroy-method="stop">
- <property name="maxConnections" value="8"/>
- <property name="connectionFactory"
ref="jmsConnectionFactory"/>
-</bean>
-
-<bean id="jmsConnectionFactory"
class="org.apache.activemq.ActiveMQConnectionFactory">
- <property name="brokerURL"
value="vm://localhost?broker.persistent=false&amp;broker.useJmx=false"/>
-</bean>
-
-<!-- setup spring jms TX manager -->
-<bean id="jmsTransactionManager"
class="org.springframework.jms.connection.JmsTransactionManager">
- <property name="connectionFactory"
ref="poolConnectionFactory"/>
-</bean>
-
-<!-- define our activemq component -->
-<bean id="activemq"
class="org.apache.activemq.camel.component.ActiveMQComponent">
- <property name="connectionFactory"
ref="poolConnectionFactory"/>
- <!-- define the jms consumer/producer as transacted -->
- <property name="transacted" value="true"/>
- <!-- setup the transaction manager to use -->
- <!-- if not provided then Camel will automatic use a
JmsTransactionManager, however if you
- for instance use a JTA transaction manager then you must configure it
-->
- <property name="transactionManager"
ref="jmsTransactionManager"/>
-</bean>
-]]></script>
-</div></div>And then we configure our routes. Notice that all we have to do is
mark the route as transacted using the <strong>transacted</strong> tag.<div
class="code panel pdl" style="border-width: 1px;"><div class="codeContent
panelContent pdl">
-<script class="brush: xml; gutter: false; theme: Default"
type="syntaxhighlighter"><![CDATA[
-<camelContext xmlns="http://camel.apache.org/schema/spring">
- <!-- disable JMX during testing -->
- <jmxAgent id="agent" disabled="true"/>
- <route>
- <!-- 1: from the jms queue -->
- <from uri="activemq:queue:okay"/>
- <!-- 2: mark this route as transacted -->
- <transacted/>
- <!-- 3: call our business logic that is myProcessor -->
- <process ref="myProcessor"/>
- <!-- 4: if success then send it to the mock -->
- <to uri="mock:result"/>
- </route>
-</camelContext>
-
-<bean id="myProcessor"
class="org.apache.camel.component.jms.tx.JMSTransactionalClientTest$MyProcessor"/>
-]]></script>
-</div></div><div class="confluence-information-macro
confluence-information-macro-tip"><p class="title">Transaction error
handler</p><span class="aui-icon aui-icon-small aui-iconfont-approve
confluence-information-macro-icon"></span><div
class="confluence-information-macro-body"><p>When a route is marked as
transacted using <strong>transacted</strong> Camel will automatic use the <a
shape="rect" href="transactionerrorhandler.html">TransactionErrorHandler</a> as
<a shape="rect" href="error-handler.html">Error Handler</a>. It supports
basically the same feature set as the <a shape="rect"
href="defaulterrorhandler.html">DefaultErrorHandler</a>, so you can for
instance use <a shape="rect" href="exception-clause.html">Exception Clause</a>
as well.</p></div></div><h3
id="TransactionalClient-IntegrationTestingwithSpring">Integration Testing with
Spring</h3><div class="confluence-information-macro
confluence-information-macro-note"><span class="aui-icon aui-icon-small
aui-iconfont-warning c
onfluence-information-macro-icon"></span><div
class="confluence-information-macro-body"><p>An Integration Test here means a
test runner class annotated
<code>@RunWith(SpringJUnit4ClassRunner.class).</code></p></div></div><p><span
style="line-height: 1.4285715;">When following the Spring Transactions
documentation it is tempting to annotate your integration test
with </span><code style="line-height:
1.4285715;">@Transactional</code><span style="line-height: 1.4285715;"> then
seed your database before firing up the route to be tested and sending a
message in. This is incorrect as Spring will have an in-progress transaction,
and Camel will wait on this before proceeding, leading to the route timing
out.</span></p><p>Instead, remove the <code>@Transactional</code> annotation
from the test method and seed the test data within
a <code>TransactionTemplate</code> execution which will ensure the data is
committed to the database before Camel attempts to pick up and use the transact
ion manager. A simple example <a shape="rect" class="external-link"
href="https://github.com/rajivj2/example2/blob/master/src/test/java/com/example/NotificationRouterIT.java"
rel="nofollow">can be found on GitHub</a>.</p><p>Spring's transactional model
ensures each transaction is bound to one thread. A Camel route may invoke
additional threads which is where the blockage may occur. This is not a fault
of Camel but as the programmer you must be aware of the consequences of
beginning a transaction in a test thread and expecting a separate thread
created by your Camel route to be participate, which it cannot. You can, in
your test, mock the parts that cause separate threads to avoid this
issue.</p><h2
id="TransactionalClient-Usingmultiplerouteswithdifferentpropagationbehaviors">Using
multiple routes with different propagation behaviors</h2><p><strong>Available
as of Camel 2.2</strong><br clear="none"> Suppose you want to route a message
through two routes and by which the 2nd rout
e should run in its own transaction. How do you do that? You use propagation
behaviors for that where you configure it as follows:</p><ul
class="alternate"><li>The first route use
<code>PROPAGATION_REQUIRED</code></li><li>The second route use
<code>PROPAGATION_REQUIRES_NEW</code></li></ul><p>This is configured in the
Spring XML file:</p><div class="code panel pdl" style="border-width: 1px;"><div
class="codeContent panelContent pdl">
-<script class="brush: xml; gutter: false; theme: Default"
type="syntaxhighlighter"><![CDATA[
-<bean id="PROPAGATION_REQUIRED"
class="org.apache.camel.spring.spi.SpringTransactionPolicy">
- <property name="transactionManager"
ref="txManager"/>
- <property name="propagationBehaviorName"
value="PROPAGATION_REQUIRED"/>
-</bean>
-
-<bean id="PROPAGATION_REQUIRES_NEW"
class="org.apache.camel.spring.spi.SpringTransactionPolicy">
- <property name="transactionManager"
ref="txManager"/>
- <property name="propagationBehaviorName"
value="PROPAGATION_REQUIRES_NEW"/>
-</bean>
-]]></script>
-</div></div>Then in the routes you use transacted DSL to indicate which of
these two propagations it uses.<div class="code panel pdl" style="border-width:
1px;"><div class="codeContent panelContent pdl">
-<script class="brush: java; gutter: false; theme: Default"
type="syntaxhighlighter"><![CDATA[
-from("direct:mixed")
- // using required
- .transacted("PROPAGATION_REQUIRED")
- // all these steps will be okay
- .setBody(constant("Tiger in
Action")).bean("bookService")
- .setBody(constant("Elephant in
Action")).bean("bookService")
- // continue on route 2
- .to("direct:mixed2");
-
-from("direct:mixed2")
- // tell Camel that if this route fails then only rollback this last route
- // by using (rollback only *last*)
- .onException(Exception.class).markRollbackOnlyLast().end()
- // using a different propagation which is requires new
- .transacted("PROPAGATION_REQUIRES_NEW")
- // this step will be okay
- .setBody(constant("Lion in
Action")).bean("bookService")
- // this step will fail with donkey
- .setBody(constant("Donkey in
Action")).bean("bookService");
-]]></script>
-</div></div>Notice how we have configured the <code>onException</code> in the
2nd route to indicate in case of any exceptions we should handle it and just
rollback this transaction. This is done using the
<code>markRollbackOnlyLast</code> which tells Camel to only do it for the
current transaction and not globally.<h4 id="TransactionalClient-SeeAlso">See
Also</h4><ul><li><a shape="rect" href="error-handling-in-camel.html">Error
handling in Camel</a></li><li><a shape="rect"
href="transactionerrorhandler.html">TransactionErrorHandler</a></li><li><a
shape="rect" href="error-handler.html">Error Handler</a></li><li><a
shape="rect" href="jms.html">JMS</a></li></ul><p></p><h4
id="TransactionalClient-UsingThisPattern">Using This Pattern</h4>
-
-<p>If you would like to use this EIP Pattern then please read the <a
shape="rect" href="getting-started.html">Getting Started</a>, you may also find
the <a shape="rect" href="architecture.html">Architecture</a> useful
particularly the description of <a shape="rect"
href="endpoint.html">Endpoint</a> and <a shape="rect"
href="uris.html">URIs</a>. Then you could try out some of the <a shape="rect"
href="examples.html">Examples</a> first before trying this pattern
out.</p></div>
+</plain-text-body><h3 id="TransactionalClient-DatabaseSample">Database
Sample</h3><p>In this sample we want to ensure that two endpoints is under
transaction control. These two endpoints inserts data into a database.<br
clear="none"> The sample is in its full as a <a shape="rect"
class="external-link"
href="http://svn.apache.org/viewvc/camel/trunk/components/camel-spring/src/test/java/org/apache/camel/spring/interceptor/TransactionalClientDataSourceMinimalConfigurationTest.java?view=log">unit
test</a>.</p><p>First of all we setup the usual spring stuff in its
configuration file. Here we have defined a DataSource to the HSQLDB and a most
importantly the Spring DataSource TransactionManager that is doing the
heavy lifting of ensuring our transactional policies. You are of course free to
use any of the Spring based TransactionManager, eg. if you are in a full
blown J2EE container you could use JTA or the WebLogic or WebSphere specific
managers.</p><p>As we use the new convent
ion over configuration we do <strong>not</strong> need to configure a
transaction policy bean, so we do not have any
<code>PROPAGATION_REQUIRED</code> beans. All the beans needed to be
configured is <strong>standard</strong> Spring beans only, eg. there are no
Camel specific configuration at
all.<plain-text-body>{snippet:id=e1|lang=xml|url=camel/trunk/components/camel-spring/src/test/resources/org/apache/camel/spring/interceptor/springTransactionalClientDataSourceMinimalConfiguration.xml}</plain-text-body>Then
we are ready to define our Camel routes. We have two routes: 1 for success
conditions, and 1 for a forced rollback condition.<br clear="none"> This is
after all based on a unit test. Notice that we mark each route as transacted
using the <strong>transacted</strong>
tag.<plain-text-body>{snippet:id=e2|lang=xml|url=camel/trunk/components/camel-spring/src/test/resources/org/apache/camel/spring/interceptor/springTransactionalClientDataSourceMinimalConfiguration.xml}</plain-te
xt-body>That is all that is needed to configure a Camel route as being
transacted. Just remember to use the <strong>transacted</strong> DSL. The rest
is standard Spring XML to setup the transaction manager.</p><h3
id="TransactionalClient-JMSSample">JMS Sample</h3><p>In this sample we want to
listen for messages on a queue and process the messages with our business logic
java code and send them along. Since its based on a <a shape="rect"
class="external-link"
href="http://svn.apache.org/viewvc/camel/trunk/components/camel-jms/src/test/java/org/apache/camel/component/jms/tx/TransactionMinimalConfigurationTest.java?view=log">unit
test</a> the destination is a mock endpoint.</p><p>First we configure the
standard Spring XML to declare a JMS connection factory, a JMS transaction
manager and our ActiveMQ component that we use in our
routing.<plain-text-body>{snippet:id=e1|lang=xml|url=camel/trunk/components/camel-jms/src/test/resources/org/apache/camel/component/jms/tx/TransactionMinimalCo
nfigurationTest.xml}</plain-text-body>And then we configure our routes. Notice
that all we have to do is mark the route as transacted using the
<strong>transacted</strong>
tag.<plain-text-body>{snippet:id=e2|lang=xml|url=camel/trunk/components/camel-jms/src/test/resources/org/apache/camel/component/jms/tx/TransactionMinimalConfigurationTest.xml}</plain-text-body></p><parameter
ac:name="title">Transaction error handler</parameter><rich-text-body><p>When a
route is marked as transacted using <strong>transacted</strong> Camel will
automatic use the <a shape="rect"
href="transactionerrorhandler.html">TransactionErrorHandler</a> as <a
shape="rect" href="error-handler.html">Error Handler</a>. It supports basically
the same feature set as the <a shape="rect"
href="defaulterrorhandler.html">DefaultErrorHandler</a>, so you can for
instance use <a shape="rect" href="exception-clause.html">Exception Clause</a>
as well.</p></rich-text-body><h3
id="TransactionalClient-IntegrationTestingwithSprin
g">Integration Testing with Spring</h3><rich-text-body><p>An Integration Test
here means a test runner class annotated
<code>@RunWith(SpringJUnit4ClassRunner.class).</code></p></rich-text-body><p><span
style="line-height: 1.4285715;">When following the Spring Transactions
documentation it is tempting to annotate your integration test
with </span><code style="line-height:
1.4285715;">@Transactional</code><span style="line-height: 1.4285715;"> then
seed your database before firing up the route to be tested and sending a
message in. This is incorrect as Spring will have an in-progress transaction,
and Camel will wait on this before proceeding, leading to the route timing
out.</span></p><p>Instead, remove the <code>@Transactional</code> annotation
from the test method and seed the test data within
a <code>TransactionTemplate</code> execution which will ensure the data is
committed to the database before Camel attempts to pick up and use the
transaction manager. A simple exampl
e <a shape="rect" class="external-link"
href="https://github.com/rajivj2/example2/blob/master/src/test/java/com/example/NotificationRouterIT.java"
rel="nofollow">can be found on GitHub</a>.</p><p>Spring's transactional model
ensures each transaction is bound to one thread. A Camel route may invoke
additional threads which is where the blockage may occur. This is not a fault
of Camel but as the programmer you must be aware of the consequences of
beginning a transaction in a test thread and expecting a separate thread
created by your Camel route to be participate, which it cannot. You can, in
your test, mock the parts that cause separate threads to avoid this
issue.</p><h2
id="TransactionalClient-Usingmultiplerouteswithdifferentpropagationbehaviors">Using
multiple routes with different propagation behaviors</h2><p><strong>Available
as of Camel 2.2</strong><br clear="none"> Suppose you want to route a message
through two routes and by which the 2nd route should run in its own tran
saction. How do you do that? You use propagation behaviors for that where you
configure it as follows:</p><ul class="alternate"><li>The first route use
<code>PROPAGATION_REQUIRED</code></li><li>The second route use
<code>PROPAGATION_REQUIRES_NEW</code></li></ul><p>This is configured in the
Spring XML
file:<plain-text-body>{snippet:id=e1|lang=xml|url=camel/trunk/components/camel-spring/src/test/resources/org/apache/camel/spring/interceptor/MixedTransactionPropagationTest.xml}</plain-text-body>Then
in the routes you use transacted DSL to indicate which of these two
propagations it
uses.<plain-text-body>{snippet:id=e1|lang=java|url=camel/trunk/components/camel-spring/src/test/java/org/apache/camel/spring/interceptor/MixedTransactionPropagationTest.java}</plain-text-body>Notice
how we have configured the <code>onException</code> in the 2nd route to
indicate in case of any exceptions we should handle it and just rollback this
transaction. This is done using the <code>markRollbackOnlyLast
</code> which tells Camel to only do it for the current transaction and not
globally.</p><h4 id="TransactionalClient-SeeAlso">See Also</h4><ul><li><a
shape="rect" href="error-handling-in-camel.html">Error handling in
Camel</a></li><li><a shape="rect"
href="transactionerrorhandler.html">TransactionErrorHandler</a></li><li><a
shape="rect" href="error-handler.html">Error Handler</a></li><li><a
shape="rect" href="jms.html">JMS</a></li></ul><p><parameter ac:name=""><a
shape="rect" href="using-this-pattern.html">Using This
Pattern</a></parameter></p></div>
</td>
<td valign="top">
<div class="navigation">
Modified: websites/production/camel/content/try-catch-finally.html
==============================================================================
--- websites/production/camel/content/try-catch-finally.html (original)
+++ websites/production/camel/content/try-catch-finally.html Fri Aug 25
08:22:01 2017
@@ -36,17 +36,6 @@
<![endif]-->
- <link href='//camel.apache.org/styles/highlighter/styles/shCoreCamel.css'
rel='stylesheet' type='text/css' />
- <link href='//camel.apache.org/styles/highlighter/styles/shThemeCamel.css'
rel='stylesheet' type='text/css' />
- <script src='//camel.apache.org/styles/highlighter/scripts/shCore.js'
type='text/javascript'></script>
- <script src='//camel.apache.org/styles/highlighter/scripts/shBrushJava.js'
type='text/javascript'></script>
- <script src='//camel.apache.org/styles/highlighter/scripts/shBrushXml.js'
type='text/javascript'></script>
- <script src='//camel.apache.org/styles/highlighter/scripts/shBrushPlain.js'
type='text/javascript'></script>
-
- <script type="text/javascript">
- SyntaxHighlighter.defaults['toolbar'] = false;
- SyntaxHighlighter.all();
- </script>
<title>
Apache Camel: Try Catch Finally
@@ -96,8 +85,8 @@ It aims to work like its Java sisters bu
<p>Notice this document is based on how it works in Camel 2.0. In Camel 1.x
this feature isn't as powerful and it uses a slight different keyword names.</p>
-<div class="confluence-information-macro
confluence-information-macro-information"><p class="title">Camel error handling
is disabled</p><span class="aui-icon aui-icon-small aui-iconfont-info
confluence-information-macro-icon"></span><div
class="confluence-information-macro-body">
-<p>When using <code>doTry .. doCatch .. doFinally</code> then the regular
Camel <a shape="rect" href="error-handler.html">Error Handler</a> does not
apply. That means any <code>onException</code> or the likes does not trigger.
The reason is that <code>doTry .. doCatch .. doFinally</code> is in fact its
own error handler and that it aims to mimic and work like how try/catch/finally
works in Java.</p></div></div>
+<parameter ac:name="title">Camel error handling is
disabled</parameter><rich-text-body>
+<p>When using <code>doTry .. doCatch .. doFinally</code> then the regular
Camel <a shape="rect" href="error-handler.html">Error Handler</a> does not
apply. That means any <code>onException</code> or the likes does not trigger.
The reason is that <code>doTry .. doCatch .. doFinally</code> is in fact its
own error handler and that it aims to mimic and work like how try/catch/finally
works in Java.</p></rich-text-body>
<h3 id="TryCatchFinally-AboutdoCatchanditspoweroverJava">About
<code>doCatch</code> and its power over Java</h3>
<p>The <code>doCatch</code> in Camel is empowered over its Java sister.</p>
@@ -113,162 +102,32 @@ Camel for instance does this by wrapped
<h3 id="TryCatchFinally-Usingtry..catch..finallyinJavaDSL">Using try .. catch
.. finally in Java DSL</h3>
<p>In the route below we have all keywords in action. As the code is based on
a unit test we route using <a shape="rect" href="mock.html">Mock</a>.</p>
-<div class="code panel pdl" style="border-width: 1px;"><div class="codeContent
panelContent pdl">
-<script class="brush: java; gutter: false; theme: Default"
type="syntaxhighlighter"><![CDATA[
-from("direct:start")
- .doTry()
- .process(new ProcessorFail())
- .to("mock:result")
- .doCatch(IOException.class, IllegalStateException.class)
- .to("mock:catch")
- .doFinally()
- .to("mock:finally")
- .end();
-]]></script>
-</div></div>
+<plain-text-body>{snippet:id=e1|lang=java|url=camel/trunk/camel-core/src/test/java/org/apache/camel/processor/TryProcessorMultipleExceptionTest.java}</plain-text-body>
<p>And in the route below we want to indicate if an IOException occured we
want to route it elsewhere and at the same time keep the exception so the
original caller is notified about this exception. To do this we need to not
<em>rethrow</em> the exception and this is why we use <strong>handled</strong>
and set it to false to indicate, no we did not handle it so please keep the
exception.<br clear="none">
The 2nd exception block can be omitted but as the code is based on an unit
test we want to test the behavior non <code>IOException</code> as well.</p>
-<div class="code panel pdl" style="border-width: 1px;"><div class="codeContent
panelContent pdl">
-<script class="brush: java; gutter: false; theme: Default"
type="syntaxhighlighter"><![CDATA[
-from("direct:start")
- // here is our try where we try processing the exchange in the route below
if it fails
- // we can catch it below, just like regular try .. catch .. finally in Java
- .doTry()
- .process(new ProcessorFail())
- .to("mock:result")
- // catch IOExcption that we do not want to handle, eg the caller should
get the error back
- .doCatch(IOException.class)
- // mark this as NOT handled, eg the caller will also get the exception
- .handled(false)
- .to("mock:io")
- .doCatch(Exception.class)
- // and catch all other exceptions
- // they are handled by default (ie handled = true)
- .to("mock:error")
- // here the try block ends
- .end();
-]]></script>
-</div></div>
+<plain-text-body>{snippet:id=e1|lang=java|url=camel/trunk/camel-core/src/test/java/org/apache/camel/processor/TryProcessorHandledTest.java}</plain-text-body>
<p>And finally we have an example of the <code>onWhen</code> predicate in
action. We can attach it to a <code>doCatch</code> block and at runtime
determine if the block should be triggered or not.<br clear="none">
In our case we only want to trigger if the caused exception message contains
the <strong>damn</strong> word.</p>
-<div class="code panel pdl" style="border-width: 1px;"><div class="codeContent
panelContent pdl">
-<script class="brush: java; gutter: false; theme: Default"
type="syntaxhighlighter"><![CDATA[
-from("direct:start")
- // here is our try where we try processing the exchange in the route below
if it fails
- // we can catch it below, just like regular try .. catch .. finally in Java
- .doTry()
- .process(new ProcessorFail())
- .to("mock:result")
- // here we catch the following 2 exceptions but only if
- // the onWhen predicate matches, eg if the exception messsage
- // conatins the string word Damn
- .doCatch(IOException.class, IllegalStateException.class)
- .onWhen(exceptionMessage().contains("Damn"))
- .to("mock:catch")
- // another catch for CamelExchangeException that does not have any onWhen
predicate
- .doCatch(CamelExchangeException.class)
- .to("mock:catchCamel")
- // and the finally that is always processed
- .doFinally()
- .to("mock:finally")
- // here the try block ends
- .end();
-]]></script>
-</div></div>
+<plain-text-body>{snippet:id=e1|lang=java|url=camel/trunk/camel-core/src/test/java/org/apache/camel/processor/TryProcessorOnWhenTest.java}</plain-text-body>
-<div class="confluence-information-macro confluence-information-macro-tip"><p
class="title">Use end() to end the block</p><span class="aui-icon
aui-icon-small aui-iconfont-approve
confluence-information-macro-icon"></span><div
class="confluence-information-macro-body">
-<p>Notice when using Java DSL we must use <code>end()</code> to indicate where
the try .. catch .. finally block ends. As the example above has a finally,
then the <code>end()</code> should be at the end of the finally block. If we
are not using a finally, then the <code>end()</code> should be at the end of
the <code>doCatch</code> to indicate the end there.</p></div></div>
+<parameter ac:name="title">Use end() to end the
block</parameter><rich-text-body>
+<p>Notice when using Java DSL we must use <code>end()</code> to indicate where
the try .. catch .. finally block ends. As the example above has a finally,
then the <code>end()</code> should be at the end of the finally block. If we
are not using a finally, then the <code>end()</code> should be at the end of
the <code>doCatch</code> to indicate the end there.</p></rich-text-body>
<h3 id="TryCatchFinally-Usingtry..catch..finallyinSpringDSL">Using try ..
catch .. finally in Spring DSL</h3>
<p>We show the three sample samples using Spring DSL instead.</p>
<p>In the route below we have all keywords in action. As the code is based on
a unit test we route using <a shape="rect" href="mock.html">Mock</a>.</p>
-<div class="code panel pdl" style="border-width: 1px;"><div class="codeContent
panelContent pdl">
-<script class="brush: xml; gutter: false; theme: Default"
type="syntaxhighlighter"><![CDATA[
-<route>
- <from uri="direct:start"/>
- <!-- here the try starts. its a try .. catch .. finally just as regular
java code -->
- <doTry>
- <process ref="processorFail"/>
- <to uri="mock:result"/>
- <doCatch>
- <!-- catch multiple exceptions -->
- <exception>java.io.IOException</exception>
- <exception>java.lang.IllegalStateException</exception>
- <to uri="mock:catch"/>
- </doCatch>
- <doFinally>
- <to uri="mock:finally"/>
- </doFinally>
- </doTry>
-</route>
-]]></script>
-</div></div>
+<plain-text-body>{snippet:id=e1|lang=xml|url=camel/trunk/components/camel-spring/src/test/resources/org/apache/camel/spring/processor/SpringTryProcessorMultipleExceptionTest.xml}</plain-text-body>
<p>And in the route below we want to indicate if an IOException occured we
want to route it elsewhere and at the same time keep the exception so the
original caller is notified about this exception. To do this we need to not
<em>rethrow</em> the exception and this is why we use <strong>handled</strong>
and set it to false to indicate, no we did not handle it so please keep the
exception.<br clear="none">
The 2nd exception block can be omitted but as the code is based on an unit
test we want to test the behavior non <code>IOException</code> as well.</p>
-<div class="code panel pdl" style="border-width: 1px;"><div class="codeContent
panelContent pdl">
-<script class="brush: xml; gutter: false; theme: Default"
type="syntaxhighlighter"><![CDATA[
-<route>
- <from uri="direct:start"/>
- <!-- here the try starts. its a try .. catch .. finally just as regular
java code -->
- <doTry>
- <process ref="processorFail"/>
- <to uri="mock:result"/>
- <doCatch>
- <!-- catch IOExcption that we do not want to handle, eg the
caller should get the error back -->
- <exception>java.io.IOException</exception>
- <!-- mark this as NOT handled, eg the caller will also get the
exception -->
- <handled>
- <constant>false</constant>
- </handled>
- <to uri="mock:io"/>
- </doCatch>
- <doCatch>
- <!-- and catch all other exceptions they are handled by default
(ie handled = true) -->
- <exception>java.lang.Exception</exception>
- <to uri="mock:error"/>
- </doCatch>
- </doTry>
-</route>
-]]></script>
-</div></div>
+<plain-text-body>{snippet:id=e1|lang=xml|url=camel/trunk/components/camel-spring/src/test/resources/org/apache/camel/spring/processor/SpringTryProcessorHandledTest.xml}</plain-text-body>
<p>And finally we have an example of the <code>onWhen</code> predicate in
action. We can attach it to a <code>doCatch</code> block and at runtime
determine if the block should be triggered or not.<br clear="none">
In our case we only want to trigger if the caused exception message contains
the <strong>damn</strong> word.</p>
-<div class="code panel pdl" style="border-width: 1px;"><div class="codeContent
panelContent pdl">
-<script class="brush: xml; gutter: false; theme: Default"
type="syntaxhighlighter"><![CDATA[
-<route>
- <from uri="direct:start"/>
- <!-- here the try starts. its a try .. catch .. finally just as regular
java code -->
- <doTry>
- <process ref="processorFail"/>
- <to uri="mock:result"/>
- <!-- here we catch the below 2 kind of exceptions but ONLY if the
onWhen predicate matches
- that means that the exception message should contain the string
word 'Damn' -->
- <doCatch>
- <exception>java.io.IOException</exception>
- <exception>java.lang.IllegalStateException</exception>
- <onWhen>
- <simple>${exception.message} contains
'Damn'</simple>
- </onWhen>
- <to uri="mock:catch"/>
- </doCatch>
- <!-- we can have multiple catch blocks for different exception and
with their own onWhen -->
- <doCatch>
-
<exception>org.apache.camel.CamelExchangeException</exception>
- <to uri="mock:catchCamel"/>
- </doCatch>
- <!-- the finally is always processed -->
- <doFinally>
- <to uri="mock:finally"/>
- </doFinally>
- </doTry>
-</route>
-]]></script>
-</div></div>
+<plain-text-body>{snippet:id=e1|lang=xml|url=camel/trunk/components/camel-spring/src/test/resources/org/apache/camel/spring/processor/SpringTryProcessorOnWhenTest.xml}</plain-text-body>
<h3 id="TryCatchFinally-SeeAlso">See Also</h3>
<ul class="alternate"><li><a shape="rect"
href="error-handling-in-camel.html">Error handling in Camel</a></li><li><a
shape="rect" href="error-handler.html">Error Handler</a></li><li><a
shape="rect" href="exception-clause.html">Exception Clause</a></li></ul>