Modified: websites/production/camel/content/book-cookbook.html
==============================================================================
--- websites/production/camel/content/book-cookbook.html (original)
+++ websites/production/camel/content/book-cookbook.html Fri Aug 25 08:22:01
2017
@@ -216,148 +216,47 @@ public class MySimpleIdGenerator {
</div></div>
<p>Groovy supports GStrings that is like a template where we can insert $
placeholders that will be evaluated by Groovy.</p>
-<h2 id="Bookcookbook-BeanBinding">Bean Binding</h2><p>Bean Binding in Camel
defines both which methods are invoked and also how the <a shape="rect"
href="message.html">Message</a> is converted into the parameters of the method
when it is invoked.</p><h3 id="Bookcookbook-Choosingthemethodtoinvoke">Choosing
the method to invoke</h3><p>The binding of a Camel <a shape="rect"
href="message.html">Message</a> to a bean method call can occur in different
ways, in the following order of importance:</p><ul><li>if the message contains
the header <strong>CamelBeanMethodName</strong> then that method is invoked,
converting the body to the type of the method's argument.<ul><li>From
<strong>Camel 2.8</strong> onwards you can qualify parameter types to select
exactly which method to use among overloads with the same name (see below for
more details).</li><li>From <strong>Camel 2.9</strong> onwards you can specify
parameter values directly in the method option (see below for more
details).</li></ul>
</li><li>you can explicitly specify the method name in the <a shape="rect"
href="dsl.html">DSL</a> or when using <a shape="rect"
href="pojo-consuming.html">POJO Consuming</a> or <a shape="rect"
href="pojo-producing.html">POJO Producing</a></li><li>if the bean has a method
marked with the <code>@Handler</code> annotation, then that method is
selected</li><li>if the bean can be converted to a <a shape="rect"
href="processor.html">Processor</a> using the <a shape="rect"
href="type-converter.html">Type Converter</a> mechanism, then this is used to
process the message. The <a shape="rect" href="activemq.html">ActiveMQ</a>
component uses this mechanism to allow any JMS MessageListener to be invoked
directly by Camel without having to write any integration glue code. You can
use the same mechanism to integrate Camel into any other messaging/remoting
frameworks.</li><li>if the body of the message can be converted to a <a
shape="rect" class="external-link" href="http://camel.apache.org/maven
/current/camel-core/apidocs/org/apache/camel/component/bean/BeanInvocation.html">BeanInvocation</a>
(the default payload used by the <a shape="rect" class="external-link"
href="http://camel.apache.org/maven/current/camel-core/apidocs/org/apache/camel/component/bean/ProxyHelper.html">ProxyHelper</a>)
component - then that is used to invoke the method and pass its
arguments</li><li>otherwise the type of the body is used to find a matching
method; an error is thrown if a single method cannot be chosen
unambiguously.</li><li>you can also use Exchange as the parameter itself, but
then the return type must be void.</li><li>if the bean class is private (or
package-private), interface methods will be preferred (from <strong>Camel
2.9</strong> onwards) since Camel can't invoke class methods on such
beans</li></ul><p>In cases where Camel cannot choose a method to invoke, an
<code>AmbiguousMethodCallException</code> is thrown.</p><p>By default the
return value is set on the outbound message bo
dy. </p><h3 id="Bookcookbook-Asynchronousprocessing">Asynchronous
processing</h3><p>From <strong>Camel 2.18</strong> onwards you can
return a CompletionStage implementation (e.g. a CompletableFuture) to implement
asynchronous processing.</p><p>Please be sure to properly complete the
CompletionStage with the result or exception, including any timeout handling.
Exchange processing would wait for completion and would not impose any timeouts
automatically. It's extremely useful to monitor <a shape="rect"
class="external-link"
href="https://camel.apache.org/maven/current/camel-core/apidocs/org/apache/camel/spi/InflightRepository.html">Inflight
repository</a> for any hanging messages.</p><p>Note that completing with
"null" won't set outbody message body to null, but would keep message intact.
This is useful to support methods that don't modify exchange and return
CompletableFuture<Void>. To set body to null, just add Exchange method
parameter and directly modify
exchange messages.</p><p>Examples:</p><p>Simple asynchronous processor,
modifying message body.</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 CompletableFuture<String>
doSomethingAsync(String body)]]></script>
-</div></div><p>Composite processor that do not modify exchange</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 CompletableFuture<Void>
doSomethingAsync(String body) {
+<h2 id="Bookcookbook-BeanBinding">Bean Binding</h2><p>Bean Binding in Camel
defines both which methods are invoked and also how the <a shape="rect"
href="message.html">Message</a> is converted into the parameters of the method
when it is invoked.</p><h3 id="Bookcookbook-Choosingthemethodtoinvoke">Choosing
the method to invoke</h3><p>The binding of a Camel <a shape="rect"
href="message.html">Message</a> to a bean method call can occur in different
ways, in the following order of importance:</p><ul><li>if the message contains
the header <strong>CamelBeanMethodName</strong> then that method is invoked,
converting the body to the type of the method's argument.<ul><li>From
<strong>Camel 2.8</strong> onwards you can qualify parameter types to select
exactly which method to use among overloads with the same name (see below for
more details).</li><li>From <strong>Camel 2.9</strong> onwards you can specify
parameter values directly in the method option (see below for more
details).</li></ul>
</li><li>you can explicitly specify the method name in the <a shape="rect"
href="dsl.html">DSL</a> or when using <a shape="rect"
href="pojo-consuming.html">POJO Consuming</a> or <a shape="rect"
href="pojo-producing.html">POJO Producing</a></li><li>if the bean has a method
marked with the <code>@Handler</code> annotation, then that method is
selected</li><li>if the bean can be converted to a <a shape="rect"
href="processor.html">Processor</a> using the <a shape="rect"
href="type-converter.html">Type Converter</a> mechanism, then this is used to
process the message. The <a shape="rect" href="activemq.html">ActiveMQ</a>
component uses this mechanism to allow any JMS MessageListener to be invoked
directly by Camel without having to write any integration glue code. You can
use the same mechanism to integrate Camel into any other messaging/remoting
frameworks.</li><li>if the body of the message can be converted to a <a
shape="rect" class="external-link" href="http://camel.apache.org/maven
/current/camel-core/apidocs/org/apache/camel/component/bean/BeanInvocation.html">BeanInvocation</a>
(the default payload used by the <a shape="rect" class="external-link"
href="http://camel.apache.org/maven/current/camel-core/apidocs/org/apache/camel/component/bean/ProxyHelper.html">ProxyHelper</a>)
component - then that is used to invoke the method and pass its
arguments</li><li>otherwise the type of the body is used to find a matching
method; an error is thrown if a single method cannot be chosen
unambiguously.</li><li>you can also use Exchange as the parameter itself, but
then the return type must be void.</li><li>if the bean class is private (or
package-private), interface methods will be preferred (from <strong>Camel
2.9</strong> onwards) since Camel can't invoke class methods on such
beans</li></ul><p>In cases where Camel cannot choose a method to invoke, an
<code>AmbiguousMethodCallException</code> is thrown.</p><p>By default the
return value is set on the outbound message bo
dy. </p><h3 id="Bookcookbook-Asynchronousprocessing">Asynchronous
processing</h3><p>From <strong>Camel 2.18</strong> onwards you can
return a CompletionStage implementation (e.g. a CompletableFuture) to implement
asynchronous processing.</p><p>Please be sure to properly complete the
CompletionStage with the result or exception, including any timeout handling.
Exchange processing would wait for completion and would not impose any timeouts
automatically. It's extremely useful to monitor <a shape="rect"
class="external-link"
href="https://camel.apache.org/maven/current/camel-core/apidocs/org/apache/camel/spi/InflightRepository.html">Inflight
repository</a> for any hanging messages.</p><p>Note that completing with
"null" won't set outbody message body to null, but would keep message intact.
This is useful to support methods that don't modify exchange and return
CompletableFuture<Void>. To set body to null, just add Exchange method
parameter and directly modify
exchange messages.</p><p>Examples:</p><p>Simple asynchronous processor,
modifying message body.</p><parameter
ac:name="language">java</parameter><plain-text-body>public
CompletableFuture<String> doSomethingAsync(String
body)</plain-text-body><p>Composite processor that do not modify
exchange</p><parameter
ac:name="language">java</parameter><plain-text-body>public
CompletableFuture<Void> doSomethingAsync(String body) {
return CompletableFuture.allOf(doA(body), doB(body), doC());
-}]]></script>
-</div></div><h3 id="Bookcookbook-Parameterbinding">Parameter
binding</h3><p>When a method has been chosen for invocation, Camel will bind to
the parameters of the method.</p><p>The following Camel-specific types are
automatically bound:</p><ul
class="alternate"><li><code>org.apache.camel.Exchange</code></li><li><code>org.apache.camel.Message</code></li><li><code>org.apache.camel.CamelContext</code></li><li><code>org.apache.camel.TypeConverter</code></li><li><code>org.apache.camel.spi.Registry</code></li><li><code>java.lang.Exception</code></li></ul><p>So,
if you declare any of these types, they will be provided by Camel.
<strong>Note that <code>Exception</code> will bind to the caught exception of
the <a shape="rect" href="exchange.html">Exchange</a></strong> - so it's often
usable if you employ a <a shape="rect" href="pojo.html">Pojo</a> to handle,
e.g., an <code>onException</code> route.</p><p>What is most interesting is that
Camel will also try to bind the body of the <a shape="r
ect" href="exchange.html">Exchange</a> to the first parameter of the method
signature (albeit not of any of the types above). So if, for instance, we
declare a parameter as <code>String body</code>, then Camel will bind the IN
body to this type. Camel will also automatically convert to the type declared
in the method signature.</p><p>Let's review some examples:</p><p>Below is a
simple method with a body binding. Camel will bind the IN body to the
<code>body</code> parameter and convert it to a <code>String</code>.</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 String doSomething(String body)
-]]></script>
-</div></div><p>In the following sample we got one of the automatically-bound
types as well - for instance, a <code>Registry</code> that we can use to lookup
beans.</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 String doSomething(String body,
Registry registry)
-]]></script>
-</div></div><p>We can use <a shape="rect" href="exchange.html">Exchange</a> 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[public String doSomething(String body,
Exchange exchange)
-]]></script>
-</div></div><p>You can also have multiple types:</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 String doSomething(String body,
Exchange exchange, TypeConverter converter)
-]]></script>
-</div></div><p>And imagine you use a <a shape="rect" href="pojo.html">Pojo</a>
to handle a given custom exception <code>InvalidOrderException</code> - we can
then bind that 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[public String badOrder(String body,
InvalidOrderException invalid)
-]]></script>
-</div></div><p>Notice that we can bind to it even if we use a sub type of
<code>java.lang.Exception</code> as Camel still knows it's an exception and can
bind the cause (if any exists).</p><p>So what about headers and other stuff?
Well now it gets a bit tricky - so we can use annotations to help us, or
specify the binding in the method name option.<br clear="none"> See the
following sections for more detail.</p><h3
id="Bookcookbook-BindingAnnotations">Binding Annotations</h3><p>You can use the
<a shape="rect" href="parameter-binding-annotations.html">Parameter Binding
Annotations</a> to customize how parameter values are created from the <a
shape="rect" href="message.html">Message</a></p><h4
id="Bookcookbook-Examples">Examples</h4><p>For example, a <a shape="rect"
href="bean.html">Bean</a> such as:</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 class Bar {
+}</plain-text-body><h3 id="Bookcookbook-Parameterbinding">Parameter
binding</h3><p>When a method has been chosen for invocation, Camel will bind to
the parameters of the method.</p><p>The following Camel-specific types are
automatically bound:</p><ul
class="alternate"><li><code>org.apache.camel.Exchange</code></li><li><code>org.apache.camel.Message</code></li><li><code>org.apache.camel.CamelContext</code></li><li><code>org.apache.camel.TypeConverter</code></li><li><code>org.apache.camel.spi.Registry</code></li><li><code>java.lang.Exception</code></li></ul><p>So,
if you declare any of these types, they will be provided by Camel.
<strong>Note that <code>Exception</code> will bind to the caught exception of
the <a shape="rect" href="exchange.html">Exchange</a></strong> - so it's often
usable if you employ a <a shape="rect" href="pojo.html">Pojo</a> to handle,
e.g., an <code>onException</code> route.</p><p>What is most interesting is that
Camel will also try to bind the body of the <a s
hape="rect" href="exchange.html">Exchange</a> to the first parameter of the
method signature (albeit not of any of the types above). So if, for instance,
we declare a parameter as <code>String body</code>, then Camel will bind the IN
body to this type. Camel will also automatically convert to the type declared
in the method signature.</p><p>Let's review some examples:</p><p>Below is a
simple method with a body binding. Camel will bind the IN body to the
<code>body</code> parameter and convert it to a
<code>String</code>.</p><plain-text-body>public String doSomething(String body)
+</plain-text-body><p>In the following sample we got one of the
automatically-bound types as well - for instance, a <code>Registry</code> that
we can use to lookup beans.</p><plain-text-body>public String
doSomething(String body, Registry registry)
+</plain-text-body><p>We can use <a shape="rect"
href="exchange.html">Exchange</a> as well:</p><plain-text-body>public String
doSomething(String body, Exchange exchange)
+</plain-text-body><p>You can also have multiple
types:</p><plain-text-body>public String doSomething(String body, Exchange
exchange, TypeConverter converter)
+</plain-text-body><p>And imagine you use a <a shape="rect"
href="pojo.html">Pojo</a> to handle a given custom exception
<code>InvalidOrderException</code> - we can then bind that as
well:</p><plain-text-body>public String badOrder(String body,
InvalidOrderException invalid)
+</plain-text-body><p>Notice that we can bind to it even if we use a sub type
of <code>java.lang.Exception</code> as Camel still knows it's an exception and
can bind the cause (if any exists).</p><p>So what about headers and other
stuff? Well now it gets a bit tricky - so we can use annotations to help us, or
specify the binding in the method name option.<br clear="none"> See the
following sections for more detail.</p><h3
id="Bookcookbook-BindingAnnotations">Binding Annotations</h3><p>You can use the
<a shape="rect" href="parameter-binding-annotations.html">Parameter Binding
Annotations</a> to customize how parameter values are created from the <a
shape="rect" href="message.html">Message</a></p><h4
id="Bookcookbook-Examples">Examples</h4><p>For example, a <a shape="rect"
href="bean.html">Bean</a> such as:</p><plain-text-body>public class Bar {
public String doSomething(String body) {
// process the in body and return whatever you want
- return "Bye World";
+ return "Bye World";
}
-]]></script>
-</div></div><p>Or the Exchange example. Notice that the return type must be
<strong>void</strong> when there is only a single parameter of the type
<code>org.apache.camel.Exchange</code>:</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 class Bar {
+</plain-text-body><p>Or the Exchange example. Notice that the return type must
be <strong>void</strong> when there is only a single parameter of the type
<code>org.apache.camel.Exchange</code>:</p><plain-text-body>public class Bar {
public void doSomething(Exchange exchange) {
// process the exchange
- exchange.getIn().setBody("Bye World");
+ exchange.getIn().setBody("Bye World");
}
-]]></script>
-</div></div><h4 id="Bookcookbook-@Handler">@Handler</h4><p>You can mark a
method in your bean with the @Handler annotation to indicate that this method
should be used for <a shape="rect" href="bean-binding.html">Bean
Binding</a>.<br clear="none"> This has an advantage as you need not specify a
method name in the Camel route, and therefore do not run into problems after
renaming the method in an IDE that can't find all its references.</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 class Bar {
+</plain-text-body><h4 id="Bookcookbook-@Handler">@Handler</h4><p>You can mark
a method in your bean with the @Handler annotation to indicate that this method
should be used for <a shape="rect" href="bean-binding.html">Bean
Binding</a>.<br clear="none"> This has an advantage as you need not specify a
method name in the Camel route, and therefore do not run into problems after
renaming the method in an IDE that can't find all its references.</p><parameter
ac:name="">java</parameter><plain-text-body>public class Bar {
@Handler
public String doSomething(String body) {
// process the in body and return whatever you want
- return "Bye World";
+ return "Bye World";
}
-]]></script>
-</div></div><h3 id="Bookcookbook-Parameterbindingusingmethodoption">Parameter
binding using method option</h3><p><strong>Available as of Camel
2.9</strong></p><p>Camel uses the following rules to determine if it's a
parameter value in the method option</p><ul class="alternate"><li>The value is
either <code>true</code> or <code>false</code> which denotes a boolean
value</li><li>The value is a numeric value such as <code>123</code> or
<code>7</code></li><li>The value is a String enclosed with either single or
double quotes</li><li>The value is null which denotes a <code>null</code>
value</li><li>It can be evaluated using the <a shape="rect"
href="simple.html">Simple</a> language, which means you can use, e.g., body,
header.foo and other <a shape="rect" href="simple.html">Simple</a> tokens.
Notice the tokens must be enclosed with ${ }.</li></ul><p>Any other value is
consider to be a type declaration instead - see the next section about
specifying types for overloaded methods.</p><p>Whe
n invoking a <a shape="rect" href="bean.html">Bean</a> you can instruct Camel
to invoke a specific method by providing the method name:</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[ .bean(OrderService.class,
"doSomething")
-]]></script>
-</div></div><p>Here we tell Camel to invoke the doSomething method - Camel
handles the parameters' binding. Now suppose the method has 2 parameters, and
the 2nd parameter is a boolean where we want to pass in a true value:</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 doSomething(String payload,
boolean highPriority) {
+</plain-text-body><h3
id="Bookcookbook-Parameterbindingusingmethodoption">Parameter binding using
method option</h3><p><strong>Available as of Camel 2.9</strong></p><p>Camel
uses the following rules to determine if it's a parameter value in the method
option</p><ul class="alternate"><li>The value is either <code>true</code> or
<code>false</code> which denotes a boolean value</li><li>The value is a numeric
value such as <code>123</code> or <code>7</code></li><li>The value is a String
enclosed with either single or double quotes</li><li>The value is null which
denotes a <code>null</code> value</li><li>It can be evaluated using the <a
shape="rect" href="simple.html">Simple</a> language, which means you can use,
e.g., body, header.foo and other <a shape="rect" href="simple.html">Simple</a>
tokens. Notice the tokens must be enclosed with ${ }.</li></ul><p>Any other
value is consider to be a type declaration instead - see the next section about
specifying types for overloaded methods.</p>
<p>When invoking a <a shape="rect" href="bean.html">Bean</a> you can instruct
Camel to invoke a specific method by providing the method
name:</p><plain-text-body> .bean(OrderService.class, "doSomething")
+</plain-text-body><p>Here we tell Camel to invoke the doSomething method -
Camel handles the parameters' binding. Now suppose the method has 2 parameters,
and the 2nd parameter is a boolean where we want to pass in a true
value:</p><plain-text-body>public void doSomething(String payload, boolean
highPriority) {
...
}
-]]></script>
-</div></div><p>This is now possible in <strong>Camel 2.9</strong>
onwards:</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[ .bean(OrderService.class,
"doSomething(*, true)")
-]]></script>
-</div></div><p>In the example above, we defined the first parameter using the
wild card symbol *, which tells Camel to bind this parameter to any type, and
let Camel figure this out. The 2nd parameter has a fixed value of
<code>true</code>. Instead of the wildcard symbol we can instruct Camel to use
the message body as shown:</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[ .bean(OrderService.class,
"doSomething(${body}, true)")
-]]></script>
-</div></div><p>The syntax of the parameters is using the <a shape="rect"
href="simple.html">Simple</a> expression language so we have to use ${ }
placeholders in the body to refer to the message body.</p><p>If you want to
pass in a <code>null</code> value, then you can explicit define this in the
method option as shown below:</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[
.to("bean:orderService?method=doSomething(null, true)")
-]]></script>
-</div></div><p>Specifying <code>null</code> as a parameter value instructs
Camel to force passing a <code>null</code> value.</p><p>Besides the message
body, you can pass in the message headers as a
<code>java.util.Map</code>:</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[ .bean(OrderService.class,
"doSomethingWithHeaders(${body}, ${headers})")
-]]></script>
-</div></div><p>You can also pass in other fixed values besides booleans. For
example, you can pass in a String and an integer:</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[ .bean(MyBean.class,
"echo('World', 5)")
-]]></script>
-</div></div><p>In the example above, we invoke the echo method with two
parameters. The first has the content 'World' (without quotes), and the 2nd has
the value of 5.<br clear="none"> Camel will automatically convert these values
to the parameters' types.</p><p>Having the power of the <a shape="rect"
href="simple.html">Simple</a> language allows us to bind to message headers and
other values such as:</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[ .bean(OrderService.class,
"doSomething(${body}, ${header.high})")
-]]></script>
-</div></div><p>You can also use the OGNL support of the <a shape="rect"
href="simple.html">Simple</a> expression language. Now suppose the message body
is an object which has a method named <code>asXml</code>. To invoke the
<code>asXml</code> method we can do as follows:</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[ .bean(OrderService.class,
"doSomething(${body.asXml}, ${header.high})")
-]]></script>
-</div></div><p>Instead of using <code>.bean</code> as shown in the examples
above, you may want to use <code>.to</code> instead as shown:</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[
.to("bean:orderService?method=doSomething(${body.asXml},
${header.high})")
-]]></script>
-</div></div><h3
id="Bookcookbook-Usingtypequalifierstoselectamongoverloadedmethods">Using type
qualifiers to select among overloaded methods</h3><p><strong>Available as of
Camel 2.8</strong></p><p>If you have a <a shape="rect"
href="bean.html">Bean</a> with overloaded methods, you can now specify
parameter types in the method name so Camel can match the method you intend to
use.<br clear="none"> Given the following bean:</p><div class="code panel pdl"
style="border-width: 1px;"><div class="codeHeader panelHeader pdl"
style="border-bottom-width: 1px;"><b>MyBean</b></div><div class="codeContent
panelContent pdl">
-<script class="brush: java; gutter: false; theme: Default"
type="syntaxhighlighter"><![CDATA[
-public static final class MyBean {
-
- public String hello(String name) {
- return "Hello " + name;
- }
-
- public String hello(String name, @Header("country") String
country) {
- return "Hello " + name + " you are from " +
country;
- }
-
- public String times(String name, @Header("times") int times) {
- StringBuilder sb = new StringBuilder();
- for (int i = 0; i < times; i++) {
- sb.append(name);
- }
- return sb.toString();
- }
-
- public String times(byte[] data, @Header("times") int times) {
- String s = new String(data);
- StringBuilder sb = new StringBuilder();
- for (int i = 0; i < times; i++) {
- sb.append(s);
- if (i < times - 1) {
- sb.append(",");
- }
- }
- return sb.toString();
- }
-
- public String times(String name, int times, char separator) {
- StringBuilder sb = new StringBuilder();
- for (int i = 0; i < times; i++) {
- sb.append(name);
- if (i < times - 1) {
- sb.append(separator);
- }
- }
- return sb.toString();
- }
-
-}
-]]></script>
-</div></div>Then the <code>MyBean</code> has 2 overloaded methods with the
names <code>hello</code> and <code>times</code>. So if we want to use the
method which has 2 parameters we can do as follows in the Camel route:<div
class="code panel pdl" style="border-width: 1px;"><div class="codeHeader
panelHeader pdl" style="border-bottom-width: 1px;"><b>Invoke 2 parameter
method</b></div><div class="codeContent panelContent pdl">
-<script class="brush: java; gutter: false; theme: Default"
type="syntaxhighlighter"><![CDATA[
-from("direct:start")
- .bean(MyBean.class, "hello(String,String)")
- .to("mock:result");
-]]></script>
-</div></div>We can also use a <code>*</code> as wildcard so we can just say we
want to execute the method with 2 parameters we do<div class="code panel pdl"
style="border-width: 1px;"><div class="codeHeader panelHeader pdl"
style="border-bottom-width: 1px;"><b>Invoke 2 parameter method using
wildcard</b></div><div class="codeContent panelContent pdl">
-<script class="brush: java; gutter: false; theme: Default"
type="syntaxhighlighter"><![CDATA[
-from("direct:start")
- .bean(MyBean.class, "hello(*,*)")
- .to("mock:result");
-]]></script>
-</div></div>By default Camel will match the type name using the simple name,
e.g. any leading package name will be disregarded. However if you want to match
using the FQN, then specify the FQN type and Camel will leverage that. So if
you have a <code>com.foo.MyOrder</code> and you want to match against the FQN,
and <strong>not</strong> the simple name "MyOrder", then follow this
example:<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[ .bean(OrderService.class,
"doSomething(com.foo.MyOrder)")
-]]></script>
-</div></div><div class="confluence-information-macro
confluence-information-macro-information"><span class="aui-icon aui-icon-small
aui-iconfont-info confluence-information-macro-icon"></span><div
class="confluence-information-macro-body"><p>Camel currently only supports
either specifying parameter binding or type per parameter in the method name
option. You <strong>cannot</strong> specify both at the same time, such
as</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[doSomething(com.foo.MyOrder ${body}, boolean
${header.high})
-]]></script>
-</div></div><p>This may change in the future.</p></div></div>
+</plain-text-body><p>This is now possible in <strong>Camel 2.9</strong>
onwards:</p><plain-text-body> .bean(OrderService.class, "doSomething(*,
true)")
+</plain-text-body><p>In the example above, we defined the first parameter
using the wild card symbol *, which tells Camel to bind this parameter to any
type, and let Camel figure this out. The 2nd parameter has a fixed value of
<code>true</code>. Instead of the wildcard symbol we can instruct Camel to use
the message body as shown:</p><plain-text-body> .bean(OrderService.class,
"doSomething(${body}, true)")
+</plain-text-body><p>The syntax of the parameters is using the <a shape="rect"
href="simple.html">Simple</a> expression language so we have to use ${ }
placeholders in the body to refer to the message body.</p><p>If you want to
pass in a <code>null</code> value, then you can explicit define this in the
method option as shown below:</p><plain-text-body>
.to("bean:orderService?method=doSomething(null, true)")
+</plain-text-body><p>Specifying <code>null</code> as a parameter value
instructs Camel to force passing a <code>null</code> value.</p><p>Besides the
message body, you can pass in the message headers as a
<code>java.util.Map</code>:</p><plain-text-body> .bean(OrderService.class,
"doSomethingWithHeaders(${body}, ${headers})")
+</plain-text-body><p>You can also pass in other fixed values besides booleans.
For example, you can pass in a String and an integer:</p><plain-text-body>
.bean(MyBean.class, "echo('World', 5)")
+</plain-text-body><p>In the example above, we invoke the echo method with two
parameters. The first has the content 'World' (without quotes), and the 2nd has
the value of 5.<br clear="none"> Camel will automatically convert these values
to the parameters' types.</p><p>Having the power of the <a shape="rect"
href="simple.html">Simple</a> language allows us to bind to message headers and
other values such as:</p><plain-text-body> .bean(OrderService.class,
"doSomething(${body}, ${header.high})")
+</plain-text-body><p>You can also use the OGNL support of the <a shape="rect"
href="simple.html">Simple</a> expression language. Now suppose the message body
is an object which has a method named <code>asXml</code>. To invoke the
<code>asXml</code> method we can do as follows:</p><plain-text-body>
.bean(OrderService.class, "doSomething(${body.asXml}, ${header.high})")
+</plain-text-body><p>Instead of using <code>.bean</code> as shown in the
examples above, you may want to use <code>.to</code> instead as
shown:</p><plain-text-body>
.to("bean:orderService?method=doSomething(${body.asXml}, ${header.high})")
+</plain-text-body><h3
id="Bookcookbook-Usingtypequalifierstoselectamongoverloadedmethods">Using type
qualifiers to select among overloaded methods</h3><p><strong>Available as of
Camel 2.8</strong></p><p>If you have a <a shape="rect"
href="bean.html">Bean</a> with overloaded methods, you can now specify
parameter types in the method name so Camel can match the method you intend to
use.<br clear="none"> Given the following
bean:<plain-text-body>{snippet:id=e1|lang=java|title=MyBean|url=camel/trunk/camel-core/src/test/java/org/apache/camel/component/bean/BeanOverloadedMethodTest.java}</plain-text-body>Then
the <code>MyBean</code> has 2 overloaded methods with the names
<code>hello</code> and <code>times</code>. So if we want to use the method
which has 2 parameters we can do as follows in the Camel
route:<plain-text-body>{snippet:id=e2|lang=java|title=Invoke 2 parameter
method|url=camel/trunk/camel-core/src/test/java/org/apache/camel/component/bean/BeanOverloadedMethodTest.java}</plain
-text-body>We can also use a <code>*</code> as wildcard so we can just say we
want to execute the method with 2 parameters we
do<plain-text-body>{snippet:id=e3|lang=java|title=Invoke 2 parameter method
using
wildcard|url=camel/trunk/camel-core/src/test/java/org/apache/camel/component/bean/BeanOverloadedMethodTest.java}</plain-text-body>By
default Camel will match the type name using the simple name, e.g. any leading
package name will be disregarded. However if you want to match using the FQN,
then specify the FQN type and Camel will leverage that. So if you have a
<code>com.foo.MyOrder</code> and you want to match against the FQN, and
<strong>not</strong> the simple name "MyOrder", then follow this
example:</p><plain-text-body> .bean(OrderService.class,
"doSomething(com.foo.MyOrder)")
+</plain-text-body><rich-text-body><p>Camel currently only supports either
specifying parameter binding or type per parameter in the method name option.
You <strong>cannot</strong> specify both at the same time, such
as</p><plain-text-body>doSomething(com.foo.MyOrder ${body}, boolean
${header.high})
+</plain-text-body><p>This may change in the future.</p></rich-text-body>
<h3 id="Bookcookbook-BeanInjection">Bean Injection</h3>
<p>We support the injection of various resources using @EndpointInject or
@BeanInject. This can be used to inject</p>
@@ -994,26 +893,7 @@ When writing software these days, its im
<p>The following example shows how to perform some time based rules on a
simple business process of 2 activities - A and B - which correspond with
Purchase Orders and Invoices in the example above. If you would like to
experiment with this scenario, you may edit this <a shape="rect"
class="external-link"
href="http://svn.apache.org/repos/asf/camel/trunk/components/camel-bam/src/test/java/org/apache/camel/bam/BamRouteTest.java">Test
Case</a>, which defines the activities and rules, and then tests that they
work.</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[
-return new ProcessBuilder(entityManagerFactory, transactionTemplate) {
- public void configure() throws Exception {
-
- // let's define some activities, correlating on an XPath on the
message bodies
- ActivityBuilder a = activity("seda:a").name("a")
- .correlate(xpath("/hello/@id"));
-
- ActivityBuilder b = activity("seda:b").name("b")
- .correlate(xpath("/hello/@id"));
-
- // now let's add some rules
- b.starts().after(a.completes())
- .expectWithin(seconds(1))
-
.errorIfOver(seconds(errorTimeout)).to("mock:overdue");
- }
-};
-]]></script>
-</div></div>
+<plain-text-body>{snippet:id=example|lang=java|url=camel/trunk/components/camel-bam/src/test/java/org/apache/camel/bam/BamRouteTest.java}</plain-text-body>
<p>As you can see in the above example, we first define two activities, and
then rules to specify when we expect them to complete for a process instance
and when an error condition should be raised.p. The ProcessBuilder is a <a
shape="rect" href="routebuilder.html">RouteBuilder</a> and can be added to any
<a shape="rect" href="camelcontext.html">CamelContext</a>. </p>
@@ -1031,14 +911,8 @@ return new ProcessBuilder(entityManagerF
<p>So you could query data from various Camel <a shape="rect"
href="components.html">Components</a> such as <a shape="rect"
href="file2.html">File</a>, <a shape="rect" href="http.html">HTTP</a> or <a
shape="rect" href="jpa.html">JPA</a>, perform multiple patterns such as <a
shape="rect" href="splitter.html">Splitter</a> or <a shape="rect"
href="message-translator.html">Message Translator</a> then send the messages to
some other <a shape="rect" href="component.html">Component</a>.</p>
<p>To show how this all fits together, try the <a shape="rect"
href="etl-example.html">ETL Example</a> </p>
-<h2 id="Bookcookbook-MockComponent">Mock Component</h2><p><a shape="rect"
href="testing.html">Testing</a> of distributed and asynchronous processing is
notoriously difficult. The <a shape="rect" href="mock.html">Mock</a>, <a
shape="rect" href="test.html">Test</a> and <a shape="rect"
href="dataset.html">DataSet</a> endpoints work great with the <a shape="rect"
href="testing.html">Camel Testing Framework</a> to simplify your unit and
integration testing using <a shape="rect"
href="enterprise-integration-patterns.html">Enterprise Integration Patterns</a>
and Camel's large range of <a shape="rect"
href="components.html">Components</a> together with the powerful <a
shape="rect" href="bean-integration.html">Bean Integration</a>.</p><p>The Mock
component provides a powerful declarative testing mechanism, which is similar
to <a shape="rect" class="external-link" href="http://www.jmock.org"
rel="nofollow">jMock</a><a shape="rect" class="external-link"
href="http://jmock.org" rel="nofollow"><
/a> in that it allows declarative expectations to be created on any Mock
endpoint before a test begins. Then the test is run, which typically fires
messages to one or more endpoints, and finally the expectations can be asserted
in a test case to ensure the system worked as expected.</p><p>This allows you
to test various things like:</p><ul><li>The correct number of messages are
received on each endpoint,</li><li>The correct payloads are received, in the
right order,</li><li>Messages arrive on an endpoint in order, using some <a
shape="rect" href="expression.html">Expression</a> to create an order testing
function,</li><li>Messages arrive match some kind of <a shape="rect"
href="predicate.html">Predicate</a> such as that specific headers have certain
values, or that parts of the messages match some predicate, such as by
evaluating an <a shape="rect" href="xpath.html">XPath</a> or <a shape="rect"
href="xquery.html">XQuery</a> <a shape="rect"
href="expression.html">Expression</a>.</li>
</ul><p><strong>Note</strong> that there is also the <a shape="rect"
href="test.html">Test endpoint</a> which is a Mock endpoint, but which uses a
second endpoint to provide the list of expected message bodies and
automatically sets up the Mock endpoint assertions. In other words, it's a Mock
endpoint that automatically sets up its assertions from some sample messages in
a <a shape="rect" href="file2.html">File</a> or <a shape="rect"
href="jpa.html">database</a>, for example.</p><div
class="confluence-information-macro confluence-information-macro-warning"><p
class="title">Mock endpoints keep received Exchanges in memory
indefinitely</p><span class="aui-icon aui-icon-small aui-iconfont-error
confluence-information-macro-icon"></span><div
class="confluence-information-macro-body"><p>Remember that Mock is designed for
testing. When you add Mock endpoints to a route, each <a shape="rect"
href="exchange.html">Exchange</a> sent to the endpoint will be stored (to allow
for later validatio
n) in memory until explicitly reset or the JVM is restarted. If you are
sending high volume and/or large messages, this may cause excessive memory use.
If your goal is to test deployable routes inline, consider using <a
shape="rect" href="notifybuilder.html">NotifyBuilder</a> or <a shape="rect"
href="advicewith.html">AdviceWith</a> in your tests instead of adding Mock
endpoints to routes directly.</p><p>From Camel 2.10 onwards there are two new
options <code>retainFirst</code>, and <code>retainLast</code> that can be used
to limit the number of messages the Mock endpoints keep in
memory.</p></div></div><h3 id="Bookcookbook-URIformat">URI format</h3><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[mock:someName[?options]
-]]></script>
-</div></div><p>Where <strong>someName</strong> can be any string that uniquely
identifies the endpoint.</p><p>You can append query options to the URI in the
following format, <code>?option=value&option=value&...</code></p><h3
id="Bookcookbook-Options">Options</h3><div class="confluenceTableSmall"><div
class="table-wrap"><table class="confluenceTable"><tbody><tr><th colspan="1"
rowspan="1" class="confluenceTh"><p>Option</p></th><th colspan="1" rowspan="1"
class="confluenceTh"><p>Default</p></th><th colspan="1" rowspan="1"
class="confluenceTh"><p>Description</p></th></tr><tr><td colspan="1"
rowspan="1" class="confluenceTd"><p><code>reportGroup</code></p></td><td
colspan="1" rowspan="1" class="confluenceTd"><p><code>null</code></p></td><td
colspan="1" rowspan="1" class="confluenceTd"><p>A size to use a <a shape="rect"
href="log.html">throughput logger</a> for reporting</p></td></tr><tr><td
colspan="1" rowspan="1"
class="confluenceTd"><p><code>retainFirst</code></p></td><td cols
pan="1" rowspan="1" class="confluenceTd"><p> </p></td><td colspan="1"
rowspan="1" class="confluenceTd"><p><strong>Camel 2.10:</strong> To only keep
first X number of messages in memory.</p></td></tr><tr><td colspan="1"
rowspan="1" class="confluenceTd"><p><code>retainLast</code></p></td><td
colspan="1" rowspan="1" class="confluenceTd"><p> </p></td><td colspan="1"
rowspan="1" class="confluenceTd"><p><strong>Camel 2.10:</strong> To only keep
last X number of messages in memory.</p></td></tr></tbody></table></div></div>
-
-
-<h3 id="Bookcookbook-SimpleExample.1">Simple Example</h3><p>Here's a simple
example of Mock endpoint in use. First, the endpoint is resolved on the
context. Then we set an expectation, and then, after the test has run, we
assert that our expectations have been met.</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[MockEndpoint resultEndpoint =
context.resolveEndpoint("mock:foo", MockEndpoint.class);
+<h2 id="Bookcookbook-MockComponent">Mock Component</h2><p><parameter
ac:name=""><a shape="rect" href="testing-summary-include.html">Testing Summary
Include</a></parameter></p><p>The Mock component provides a powerful
declarative testing mechanism, which is similar to <a shape="rect"
class="external-link" href="http://www.jmock.org" rel="nofollow">jMock</a><a
shape="rect" class="external-link" href="http://jmock.org" rel="nofollow"></a>
in that it allows declarative expectations to be created on any Mock endpoint
before a test begins. Then the test is run, which typically fires messages to
one or more endpoints, and finally the expectations can be asserted in a test
case to ensure the system worked as expected.</p><p>This allows you to test
various things like:</p><ul><li>The correct number of messages are received on
each endpoint,</li><li>The correct payloads are received, in the right
order,</li><li>Messages arrive on an endpoint in order, using some <a
shape="rect" href="expressi
on.html">Expression</a> to create an order testing function,</li><li>Messages
arrive match some kind of <a shape="rect" href="predicate.html">Predicate</a>
such as that specific headers have certain values, or that parts of the
messages match some predicate, such as by evaluating an <a shape="rect"
href="xpath.html">XPath</a> or <a shape="rect" href="xquery.html">XQuery</a> <a
shape="rect"
href="expression.html">Expression</a>.</li></ul><p><strong>Note</strong> that
there is also the <a shape="rect" href="test.html">Test endpoint</a> which is a
Mock endpoint, but which uses a second endpoint to provide the list of expected
message bodies and automatically sets up the Mock endpoint assertions. In other
words, it's a Mock endpoint that automatically sets up its assertions from some
sample messages in a <a shape="rect" href="file2.html">File</a> or <a
shape="rect" href="jpa.html">database</a>, for example.</p><parameter
ac:name="title">Mock endpoints keep received Exchanges in memory i
ndefinitely</parameter><rich-text-body><p>Remember that Mock is designed for
testing. When you add Mock endpoints to a route, each <a shape="rect"
href="exchange.html">Exchange</a> sent to the endpoint will be stored (to allow
for later validation) in memory until explicitly reset or the JVM is restarted.
If you are sending high volume and/or large messages, this may cause excessive
memory use. If your goal is to test deployable routes inline, consider using <a
shape="rect" href="notifybuilder.html">NotifyBuilder</a> or <a shape="rect"
href="advicewith.html">AdviceWith</a> in your tests instead of adding Mock
endpoints to routes directly.</p><p>From Camel 2.10 onwards there are two new
options <code>retainFirst</code>, and <code>retainLast</code> that can be used
to limit the number of messages the Mock endpoints keep in
memory.</p></rich-text-body><h3 id="Bookcookbook-URIformat">URI
format</h3><plain-text-body>mock:someName[?options]
+</plain-text-body><p>Where <strong>someName</strong> can be any string that
uniquely identifies the endpoint.</p><p>You can append query options to the URI
in the following format,
<code>?option=value&option=value&...</code></p><h3
id="Bookcookbook-Options">Options</h3><parameter
ac:name="class">confluenceTableSmall</parameter><rich-text-body><div
class="table-wrap"><table class="confluenceTable"><tbody><tr><th colspan="1"
rowspan="1" class="confluenceTh"><p>Option</p></th><th colspan="1" rowspan="1"
class="confluenceTh"><p>Default</p></th><th colspan="1" rowspan="1"
class="confluenceTh"><p>Description</p></th></tr><tr><td colspan="1"
rowspan="1" class="confluenceTd"><p><code>reportGroup</code></p></td><td
colspan="1" rowspan="1" class="confluenceTd"><p><code>null</code></p></td><td
colspan="1" rowspan="1" class="confluenceTd"><p>A size to use a <a shape="rect"
href="log.html">throughput logger</a> for reporting</p></td></tr><tr><td
colspan="1" rowspan="1" class="confluenceT
d"><p><code>retainFirst</code></p></td><td colspan="1" rowspan="1"
class="confluenceTd"><p> </p></td><td colspan="1" rowspan="1"
class="confluenceTd"><p><strong>Camel 2.10:</strong> To only keep first X
number of messages in memory.</p></td></tr><tr><td colspan="1" rowspan="1"
class="confluenceTd"><p><code>retainLast</code></p></td><td colspan="1"
rowspan="1" class="confluenceTd"><p> </p></td><td colspan="1" rowspan="1"
class="confluenceTd"><p><strong>Camel 2.10:</strong> To only keep last X number
of messages in memory.</p></td></tr></tbody></table></div></rich-text-body><h3
id="Bookcookbook-SimpleExample.1">Simple Example</h3><p>Here's a simple example
of Mock endpoint in use. First, the endpoint is resolved on the context. Then
we set an expectation, and then, after the test has run, we assert that our
expectations have been met.</p><plain-text-body>MockEndpoint resultEndpoint =
context.resolveEndpoint("mock:foo", MockEndpoint.class);
resultEndpoint.expectedMessageCount(2);
@@ -1047,9 +921,7 @@ resultEndpoint.expectedMessageCount(2);
// now lets assert that the mock:foo endpoint received 2 messages
resultEndpoint.assertIsSatisfied();
-]]></script>
-</div></div><p>You typically always call the <a shape="rect"
class="external-link"
href="http://camel.apache.org/maven/current/camel-core/apidocs/org/apache/camel/component/mock/MockEndpoint.html#assertIsSatisfied()">assertIsSatisfied()
method</a> to test that the expectations were met after running a
test.</p><p>Camel will by default wait 10 seconds when the
<code>assertIsSatisfied()</code> is invoked. This can be configured by setting
the <code>setResultWaitTime(millis)</code> method.</p><h4
id="Bookcookbook-UsingassertPeriod">Using assertPeriod</h4><p><strong>Available
as of Camel 2.7</strong><br clear="none"> When the assertion is satisfied then
Camel will stop waiting and continue from the <code>assertIsSatisfied</code>
method. That means if a new message arrives on the mock endpoint, just a bit
later, that arrival will not affect the outcome of the assertion. Suppose you
do want to test that no new messages arrives after a period thereafter, then
you can do that by setting the
<code>setAssertPeriod</code> method, for example:</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[MockEndpoint resultEndpoint =
context.resolveEndpoint("mock:foo", MockEndpoint.class);
+</plain-text-body><p>You typically always call the <a shape="rect"
class="external-link"
href="http://camel.apache.org/maven/current/camel-core/apidocs/org/apache/camel/component/mock/MockEndpoint.html#assertIsSatisfied()">assertIsSatisfied()
method</a> to test that the expectations were met after running a
test.</p><p>Camel will by default wait 10 seconds when the
<code>assertIsSatisfied()</code> is invoked. This can be configured by setting
the <code>setResultWaitTime(millis)</code> method.</p><h4
id="Bookcookbook-UsingassertPeriod">Using assertPeriod</h4><p><strong>Available
as of Camel 2.7</strong><br clear="none"> When the assertion is satisfied then
Camel will stop waiting and continue from the <code>assertIsSatisfied</code>
method. That means if a new message arrives on the mock endpoint, just a bit
later, that arrival will not affect the outcome of the assertion. Suppose you
do want to test that no new messages arrives after a period thereafter, then
you can do that by setti
ng the <code>setAssertPeriod</code> method, for
example:</p><plain-text-body>MockEndpoint resultEndpoint =
context.resolveEndpoint("mock:foo", MockEndpoint.class);
resultEndpoint.setAssertPeriod(5000);
resultEndpoint.expectedMessageCount(2);
@@ -1058,263 +930,13 @@ resultEndpoint.expectedMessageCount(2);
// now lets assert that the mock:foo endpoint received 2 messages
resultEndpoint.assertIsSatisfied();
-]]></script>
-</div></div><h3 id="Bookcookbook-Settingexpectations">Setting
expectations</h3><p>You can see from the javadoc of <a shape="rect"
href="httphttp://camel.apache.org/maven/current/camel-core/apidocs/org/apache/camel/component/mock/MockEndpoint.html"
rel="nofollow">MockEndpoint</a> the various helper methods you can use to set
expectations. The main methods are as follows:</p><div
class="confluenceTableSmall"><div class="table-wrap"><table
class="confluenceTable"><tbody><tr><th colspan="1" rowspan="1"
class="confluenceTh"><p>Method</p></th><th colspan="1" rowspan="1"
class="confluenceTh"><p>Description</p></th></tr><tr><td colspan="1"
rowspan="1" class="confluenceTd"><p><a shape="rect" class="external-link"
href="http://camel.apache.org/maven/current/camel-core/apidocs/org/apache/camel/component/mock/MockEndpoint.html#expectedMessageCount(int)">expectedMessageCount(int)</a></p></td><td
colspan="1" rowspan="1" class="confluenceTd"><p>To define the expected message
count on the endpoint.
</p></td></tr><tr><td colspan="1" rowspan="1" class="confluenceTd"><p><a
shape="rect" class="external-link"
href="http://camel.apache.org/maven/current/camel-core/apidocs/org/apache/camel/component/mock/MockEndpoint.html#expectedMinimumMessageCount(int)">expectedMinimumMessageCount(int)</a></p></td><td
colspan="1" rowspan="1" class="confluenceTd"><p>To define the minimum number
of expected messages on the endpoint.</p></td></tr><tr><td colspan="1"
rowspan="1" class="confluenceTd"><p><a shape="rect" class="external-link"
href="http://camel.apache.org/maven/current/camel-core/apidocs/org/apache/camel/component/mock/MockEndpoint.html#expectedBodiesReceived(java.lang.Object...)">expectedBodiesReceived(...)</a></p></td><td
colspan="1" rowspan="1" class="confluenceTd"><p>To define the expected bodies
that should be received (in order).</p></td></tr><tr><td colspan="1"
rowspan="1" class="confluenceTd"><p><a shape="rect" class="external-link"
href="http://camel.apache.org/maven/current/came
l-core/apidocs/org/apache/camel/component/mock/MockEndpoint.html#expectedHeaderReceived(java.lang.String,%20java.lang.String)">expectedHeaderReceived(...)</a></p></td><td
colspan="1" rowspan="1" class="confluenceTd"><p>To define the expected header
that should be received</p></td></tr><tr><td colspan="1" rowspan="1"
class="confluenceTd"><p><a shape="rect" class="external-link"
href="http://camel.apache.org/maven/current/camel-core/apidocs/org/apache/camel/component/mock/MockEndpoint.html#expectsAscending(org.apache.camel.Expression)">expectsAscending(Expression)</a></p></td><td
colspan="1" rowspan="1" class="confluenceTd"><p>To add an expectation that
messages are received in order, using the given <a shape="rect"
href="expression.html">Expression</a> to compare messages.</p></td></tr><tr><td
colspan="1" rowspan="1" class="confluenceTd"><p><a shape="rect"
class="external-link"
href="http://camel.apache.org/maven/current/camel-core/apidocs/org/apache/camel/component/mock/MockEndpoint
.html#expectsDescending(org.apache.camel.Expression)">expectsDescending(Expression)</a></p></td><td
colspan="1" rowspan="1" class="confluenceTd"><p>To add an expectation that
messages are received in order, using the given <a shape="rect"
href="expression.html">Expression</a> to compare messages.</p></td></tr><tr><td
colspan="1" rowspan="1" class="confluenceTd"><p><a shape="rect"
class="external-link"
href="http://camel.apache.org/maven/current/camel-core/apidocs/org/apache/camel/component/mock/MockEndpoint.html#expectsNoDuplicates(org.apache.camel.Expression)">expectsNoDuplicates(Expression)</a></p></td><td
colspan="1" rowspan="1" class="confluenceTd"><p>To add an expectation that no
duplicate messages are received; using an <a shape="rect"
href="expression.html">Expression</a> to calculate a unique identifier for each
message. This could be something like the <code>JMSMessageID</code> if using
JMS, or some unique reference number within the
message.</p></td></tr></tbody></table></
div></div>
-
-
-<p>Here's another example:</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[resultEndpoint.expectedBodiesReceived("firstMessageBody",
"secondMessageBody", "thirdMessageBody");
-]]></script>
-</div></div><h4 id="Bookcookbook-Addingexpectationstospecificmessages">Adding
expectations to specific messages</h4><p>In addition, you can use the <a
shape="rect" class="external-link"
href="http://camel.apache.org/maven/current/camel-core/apidocs/org/apache/camel/component/mock/MockEndpoint.html#message(int)">message(int
messageIndex)</a> method to add assertions about a specific message that is
received.</p><p>For example, to add expectations of the headers or body of the
first message (using zero-based indexing like <code>java.util.List</code>), you
can use the following code:</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[resultEndpoint.message(0).header("foo").isEqualTo("bar");
-]]></script>
-</div></div><p>There are some examples of the Mock endpoint in use in the <a
shape="rect" class="external-link"
href="http://svn.apache.org/viewvc/camel/trunk/camel-core/src/test/java/org/apache/camel/processor/">camel-core
processor tests</a>.</p><h3 id="Bookcookbook-Mockingexistingendpoints">Mocking
existing endpoints</h3><p><strong>Available as of Camel
2.7</strong></p><p>Camel now allows you to automatically mock existing
endpoints in your Camel routes.</p><div class="confluence-information-macro
confluence-information-macro-information"><p class="title">How it
works</p><span class="aui-icon aui-icon-small aui-iconfont-info
confluence-information-macro-icon"></span><div
class="confluence-information-macro-body"><p><strong>Important:</strong> The
endpoints are still in action. What happens differently is that a <a
shape="rect" href="mock.html">Mock</a> endpoint is injected and receives the
message first and then delegates the message to the target endpoint. You can
view this as a
kind of intercept and delegate or endpoint
listener.</p></div></div><p>Suppose you have the given route below:</p><div
class="code panel pdl" style="border-width: 1px;"><div class="codeHeader
panelHeader pdl" style="border-bottom-width: 1px;"><b>Route</b></div><div
class="codeContent panelContent pdl">
-<script class="brush: java; gutter: false; theme: Default"
type="syntaxhighlighter"><![CDATA[
-// tag::route[]
-@Override
-protected RouteBuilder createRouteBuilder() throws Exception {
- return new RouteBuilder() {
- @Override
- public void configure() throws Exception {
-
from("direct:start").to("direct:foo").to("log:foo").to("mock:result");
-
- from("direct:foo").transform(constant("Bye
World"));
- }
- };
-}
-// end::route[]
-]]></script>
-</div></div><p>You can then use the <code>adviceWith</code> feature in Camel
to mock all the endpoints in a given route from your unit test, as shown
below:</p><div class="code panel pdl" style="border-width: 1px;"><div
class="codeHeader panelHeader pdl" style="border-bottom-width:
1px;"><b>adviceWith mocking all endpoints</b></div><div class="codeContent
panelContent pdl">
-<script class="brush: java; gutter: false; theme: Default"
type="syntaxhighlighter"><![CDATA[
-// tag::e1[]
-public void testAdvisedMockEndpoints() throws Exception {
- // advice the first route using the inlined AdviceWith route builder
- // which has extended capabilities than the regular route builder
- context.getRouteDefinitions().get(0).adviceWith(context, new
AdviceWithRouteBuilder() {
- @Override
- public void configure() throws Exception {
- // mock all endpoints
- mockEndpoints();
- }
- });
-
-
getMockEndpoint("mock:direct:start").expectedBodiesReceived("Hello
World");
-
getMockEndpoint("mock:direct:foo").expectedBodiesReceived("Hello
World");
- getMockEndpoint("mock:log:foo").expectedBodiesReceived("Bye
World");
- getMockEndpoint("mock:result").expectedBodiesReceived("Bye
World");
-
- template.sendBody("direct:start", "Hello World");
-
- assertMockEndpointsSatisfied();
-
- // additional test to ensure correct endpoints in registry
- assertNotNull(context.hasEndpoint("direct:start"));
- assertNotNull(context.hasEndpoint("direct:foo"));
- assertNotNull(context.hasEndpoint("log:foo"));
- assertNotNull(context.hasEndpoint("mock:result"));
- // all the endpoints was mocked
- assertNotNull(context.hasEndpoint("mock:direct:start"));
- assertNotNull(context.hasEndpoint("mock:direct:foo"));
- assertNotNull(context.hasEndpoint("mock:log:foo"));
-}
-// end::e1[]
-]]></script>
-</div></div><p>Notice that the mock endpoints is given the uri
<code>mock:<endpoint></code>, for example <code>mock:direct:foo</code>.
Camel logs at <code>INFO</code> level the endpoints being mocked:</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[INFO Adviced endpoint [direct://foo] with
mock endpoint [mock:direct:foo]
-]]></script>
-</div></div><div class="confluence-information-macro
confluence-information-macro-information"><p class="title">Mocked endpoints are
without parameters</p><span class="aui-icon aui-icon-small aui-iconfont-info
confluence-information-macro-icon"></span><div
class="confluence-information-macro-body"><p>Endpoints which are mocked will
have their parameters stripped off. For example the endpoint
"log:foo?showAll=true" will be mocked to the following endpoint "mock:log:foo".
Notice the parameters have been removed.</p></div></div><p>Its also possible to
only mock certain endpoints using a pattern. For example to mock all
<code>log</code> endpoints you do as shown:</p><div class="code panel pdl"
style="border-width: 1px;"><div class="codeHeader panelHeader pdl"
style="border-bottom-width: 1px;"><b>adviceWith mocking only log endpoints
using a pattern</b></div><div class="codeContent panelContent pdl">
-<script class="brush: java; gutter: false; theme: Default"
type="syntaxhighlighter"><![CDATA[
-// tag::e2[]
-public void testAdvisedMockEndpointsWithPattern() throws Exception {
- // advice the first route using the inlined AdviceWith route builder
- // which has extended capabilities than the regular route builder
- context.getRouteDefinitions().get(0).adviceWith(context, new
AdviceWithRouteBuilder() {
- @Override
- public void configure() throws Exception {
- // mock only log endpoints
- mockEndpoints("log*");
- }
- });
-
- // now we can refer to log:foo as a mock and set our expectations
- getMockEndpoint("mock:log:foo").expectedBodiesReceived("Bye
World");
-
- getMockEndpoint("mock:result").expectedBodiesReceived("Bye
World");
-
- template.sendBody("direct:start", "Hello World");
-
- assertMockEndpointsSatisfied();
-
- // additional test to ensure correct endpoints in registry
- assertNotNull(context.hasEndpoint("direct:start"));
- assertNotNull(context.hasEndpoint("direct:foo"));
- assertNotNull(context.hasEndpoint("log:foo"));
- assertNotNull(context.hasEndpoint("mock:result"));
- // only the log:foo endpoint was mocked
- assertNotNull(context.hasEndpoint("mock:log:foo"));
- assertNull(context.hasEndpoint("mock:direct:start"));
- assertNull(context.hasEndpoint("mock:direct:foo"));
-}
-// end::e2[]
-]]></script>
-</div></div><p>The pattern supported can be a wildcard or a regular
expression. See more details about this at <a shape="rect"
href="intercept.html">Intercept</a> as its the same matching function used by
Camel.</p><div class="confluence-information-macro
confluence-information-macro-information"><span class="aui-icon aui-icon-small
aui-iconfont-info confluence-information-macro-icon"></span><div
class="confluence-information-macro-body"><p>Mind that mocking endpoints causes
the messages to be copied when they arrive on the mock.<br clear="none"> That
means Camel will use more memory. This may not be suitable when you send in a
lot of messages.</p></div></div><h4
id="Bookcookbook-Mockingexistingendpointsusingthecamel-testcomponent">Mocking
existing endpoints using the <code>camel-test</code> component</h4><p>Instead
of using the <code>adviceWith</code> to instruct Camel to mock endpoints, you
can easily enable this behavior when using the <code>camel-test</code> Test
Kit.<br clear="
none"> The same route can be tested as follows. Notice that we return
<code>"*"</code> from the <code>isMockEndpoints</code> method, which tells
Camel to mock all endpoints.<br clear="none"> If you only want to mock all
<code>log</code> endpoints you can return <code>"log*"</code> instead.</p><div
class="code panel pdl" style="border-width: 1px;"><div class="codeHeader
panelHeader pdl" style="border-bottom-width: 1px;"><b>isMockEndpoints using
camel-test kit</b></div><div class="codeContent panelContent pdl">
-<script class="brush: java; gutter: false; theme: Default"
type="syntaxhighlighter"><![CDATA[
-// tag::e1[]
-public class IsMockEndpointsJUnit4Test extends CamelTestSupport {
-
- @Override
- public String isMockEndpoints() {
- // override this method and return the pattern for which endpoints to
mock.
- // use * to indicate all
- return "*";
- }
-
- @Test
- public void testMockAllEndpoints() throws Exception {
- // notice we have automatic mocked all endpoints and the name of the
endpoints is "mock:uri"
-
getMockEndpoint("mock:direct:start").expectedBodiesReceived("Hello
World");
-
getMockEndpoint("mock:direct:foo").expectedBodiesReceived("Hello
World");
-
getMockEndpoint("mock:log:foo").expectedBodiesReceived("Bye
World");
-
getMockEndpoint("mock:result").expectedBodiesReceived("Bye
World");
-
- template.sendBody("direct:start", "Hello World");
-
- assertMockEndpointsSatisfied();
-
- // additional test to ensure correct endpoints in registry
- assertNotNull(context.hasEndpoint("direct:start"));
- assertNotNull(context.hasEndpoint("direct:foo"));
- assertNotNull(context.hasEndpoint("log:foo"));
- assertNotNull(context.hasEndpoint("mock:result"));
- // all the endpoints was mocked
- assertNotNull(context.hasEndpoint("mock:direct:start"));
- assertNotNull(context.hasEndpoint("mock:direct:foo"));
- assertNotNull(context.hasEndpoint("mock:log:foo"));
- }
-
- @Override
- protected RouteBuilder createRouteBuilder() throws Exception {
- return new RouteBuilder() {
- @Override
- public void configure() throws Exception {
-
from("direct:start").to("direct:foo").to("log:foo").to("mock:result");
-
- from("direct:foo").transform(constant("Bye
World"));
- }
- };
- }
-}
-// end::e1[]
-]]></script>
-</div></div><h4 id="Bookcookbook-MockingexistingendpointswithXMLDSL">Mocking
existing endpoints with XML DSL</h4><p>If you do not use the
<code>camel-test</code> component for unit testing (as shown above) you can use
a different approach when using XML files for routes.<br clear="none"> The
solution is to create a new XML file used by the unit test and then include the
intended XML file which has the route you want to test.</p><p>Suppose we have
the route in the <code>camel-route.xml</code> file:</p><div class="code panel
pdl" style="border-width: 1px;"><div class="codeHeader panelHeader pdl"
style="border-bottom-width: 1px;"><b>camel-route.xml</b></div><div
class="codeContent panelContent pdl">
-<script class="brush: xml; gutter: false; theme: Default"
type="syntaxhighlighter"><![CDATA[
-<!-- tag::e1[] -->
-<!-- this camel route is in the camel-route.xml file -->
-<camelContext xmlns="http://camel.apache.org/schema/spring">
-
- <route>
- <from uri="direct:start"/>
- <to uri="direct:foo"/>
- <to uri="log:foo"/>
- <to uri="mock:result"/>
- </route>
-
- <route>
- <from uri="direct:foo"/>
- <transform>
- <constant>Bye World</constant>
- </transform>
- </route>
-
-</camelContext>
-<!-- end::e1[] -->
-]]></script>
-</div></div><p>Then we create a new XML file as follows, where we include the
<code>camel-route.xml</code> file and define a spring bean with the class
<code>org.apache.camel.impl.InterceptSendToMockEndpointStrategy</code> which
tells Camel to mock all endpoints:</p><div class="code panel pdl"
style="border-width: 1px;"><div class="codeHeader panelHeader pdl"
style="border-bottom-width: 1px;"><b>test-camel-route.xml</b></div><div
class="codeContent panelContent pdl">
-<script class="brush: xml; gutter: false; theme: Default"
type="syntaxhighlighter"><![CDATA[
-<!-- tag::e1[] -->
-<!-- the Camel route is defined in another XML file -->
-<import resource="camel-route.xml"/>
-
-<!-- bean which enables mocking all endpoints -->
-<bean id="mockAllEndpoints"
class="org.apache.camel.impl.InterceptSendToMockEndpointStrategy"/>
-<!-- end::e1[] -->
-]]></script>
-</div></div><p>Then in your unit test you load the new XML file
(<code>test-camel-route.xml</code>) instead of
<code>camel-route.xml</code>.</p><p>To only mock all <a shape="rect"
href="log.html">Log</a> endpoints you can define the pattern in the constructor
for the bean:</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="mockAllEndpoints"
class="org.apache.camel.impl.InterceptSendToMockEndpointStrategy">
- <constructor-arg index="0" value="log*"/>
+</plain-text-body><h3 id="Bookcookbook-Settingexpectations">Setting
expectations</h3><p>You can see from the javadoc of <a shape="rect"
href="httphttp://camel.apache.org/maven/current/camel-core/apidocs/org/apache/camel/component/mock/MockEndpoint.html"
rel="nofollow">MockEndpoint</a> the various helper methods you can use to set
expectations. The main methods are as follows:</p><parameter
ac:name="class">confluenceTableSmall</parameter><rich-text-body><div
class="table-wrap"><table class="confluenceTable"><tbody><tr><th colspan="1"
rowspan="1" class="confluenceTh"><p>Method</p></th><th colspan="1" rowspan="1"
class="confluenceTh"><p>Description</p></th></tr><tr><td colspan="1"
rowspan="1" class="confluenceTd"><p><a shape="rect" class="external-link"
href="http://camel.apache.org/maven/current/camel-core/apidocs/org/apache/camel/component/mock/MockEndpoint.html#expectedMessageCount(int)">expectedMessageCount(int)</a></p></td><td
colspan="1" rowspan="1" class="confluenceTd"><p>To def
ine the expected message count on the endpoint.</p></td></tr><tr><td
colspan="1" rowspan="1" class="confluenceTd"><p><a shape="rect"
class="external-link"
href="http://camel.apache.org/maven/current/camel-core/apidocs/org/apache/camel/component/mock/MockEndpoint.html#expectedMinimumMessageCount(int)">expectedMinimumMessageCount(int)</a></p></td><td
colspan="1" rowspan="1" class="confluenceTd"><p>To define the minimum number
of expected messages on the endpoint.</p></td></tr><tr><td colspan="1"
rowspan="1" class="confluenceTd"><p><a shape="rect" class="external-link"
href="http://camel.apache.org/maven/current/camel-core/apidocs/org/apache/camel/component/mock/MockEndpoint.html#expectedBodiesReceived(java.lang.Object...)">expectedBodiesReceived(...)</a></p></td><td
colspan="1" rowspan="1" class="confluenceTd"><p>To define the expected bodies
that should be received (in order).</p></td></tr><tr><td colspan="1"
rowspan="1" class="confluenceTd"><p><a shape="rect" class="external-link" h
ref="http://camel.apache.org/maven/current/camel-core/apidocs/org/apache/camel/component/mock/MockEndpoint.html#expectedHeaderReceived(java.lang.String,%20java.lang.String)">expectedHeaderReceived(...)</a></p></td><td
colspan="1" rowspan="1" class="confluenceTd"><p>To define the expected header
that should be received</p></td></tr><tr><td colspan="1" rowspan="1"
class="confluenceTd"><p><a shape="rect" class="external-link"
href="http://camel.apache.org/maven/current/camel-core/apidocs/org/apache/camel/component/mock/MockEndpoint.html#expectsAscending(org.apache.camel.Expression)">expectsAscending(Expression)</a></p></td><td
colspan="1" rowspan="1" class="confluenceTd"><p>To add an expectation that
messages are received in order, using the given <a shape="rect"
href="expression.html">Expression</a> to compare messages.</p></td></tr><tr><td
colspan="1" rowspan="1" class="confluenceTd"><p><a shape="rect"
class="external-link"
href="http://camel.apache.org/maven/current/camel-core/apido
cs/org/apache/camel/component/mock/MockEndpoint.html#expectsDescending(org.apache.camel.Expression)">expectsDescending(Expression)</a></p></td><td
colspan="1" rowspan="1" class="confluenceTd"><p>To add an expectation that
messages are received in order, using the given <a shape="rect"
href="expression.html">Expression</a> to compare messages.</p></td></tr><tr><td
colspan="1" rowspan="1" class="confluenceTd"><p><a shape="rect"
class="external-link"
href="http://camel.apache.org/maven/current/camel-core/apidocs/org/apache/camel/component/mock/MockEndpoint.html#expectsNoDuplicates(org.apache.camel.Expression)">expectsNoDuplicates(Expression)</a></p></td><td
colspan="1" rowspan="1" class="confluenceTd"><p>To add an expectation that no
duplicate messages are received; using an <a shape="rect"
href="expression.html">Expression</a> to calculate a unique identifier for each
message. This could be something like the <code>JMSMessageID</code> if using
JMS, or some unique reference number with
in the message.</p></td></tr></tbody></table></div></rich-text-body><p>Here's
another
example:</p><plain-text-body>resultEndpoint.expectedBodiesReceived("firstMessageBody",
"secondMessageBody", "thirdMessageBody");
+</plain-text-body><h4
id="Bookcookbook-Addingexpectationstospecificmessages">Adding expectations to
specific messages</h4><p>In addition, you can use the <a shape="rect"
class="external-link"
href="http://camel.apache.org/maven/current/camel-core/apidocs/org/apache/camel/component/mock/MockEndpoint.html#message(int)">message(int
messageIndex)</a> method to add assertions about a specific message that is
received.</p><p>For example, to add expectations of the headers or body of the
first message (using zero-based indexing like <code>java.util.List</code>), you
can use the following
code:</p><plain-text-body>resultEndpoint.message(0).header("foo").isEqualTo("bar");
+</plain-text-body><p>There are some examples of the Mock endpoint in use in
the <a shape="rect" class="external-link"
href="http://svn.apache.org/viewvc/camel/trunk/camel-core/src/test/java/org/apache/camel/processor/">camel-core
processor tests</a>.</p><h3 id="Bookcookbook-Mockingexistingendpoints">Mocking
existing endpoints</h3><p><strong>Available as of Camel
2.7</strong></p><p>Camel now allows you to automatically mock existing
endpoints in your Camel routes.</p><parameter ac:name="title">How it
works</parameter><rich-text-body><p><strong>Important:</strong> The endpoints
are still in action. What happens differently is that a <a shape="rect"
href="mock.html">Mock</a> endpoint is injected and receives the message first
and then delegates the message to the target endpoint. You can view this as a
kind of intercept and delegate or endpoint
listener.</p></rich-text-body><p>Suppose you have the given route
below:</p><plain-text-body>{snippet:id=route|title=Route|lang=java|url=camel/
trunk/camel-core/src/test/java/org/apache/camel/processor/interceptor/AdviceWithMockEndpointsTest.java}</plain-text-body><p>You
can then use the <code>adviceWith</code> feature in Camel to mock all the
endpoints in a given route from your unit test, as shown
below:</p><plain-text-body>{snippet:id=e1|title=adviceWith mocking all
endpoints|lang=java|url=camel/trunk/camel-core/src/test/java/org/apache/camel/processor/interceptor/AdviceWithMockEndpointsTest.java}</plain-text-body><p>Notice
that the mock endpoints is given the uri <code>mock:<endpoint></code>,
for example <code>mock:direct:foo</code>. Camel logs at <code>INFO</code> level
the endpoints being mocked:</p><plain-text-body>INFO Adviced endpoint
[direct://foo] with mock endpoint [mock:direct:foo]
+</plain-text-body><parameter ac:name="title">Mocked endpoints are without
parameters</parameter><rich-text-body><p>Endpoints which are mocked will have
their parameters stripped off. For example the endpoint "log:foo?showAll=true"
will be mocked to the following endpoint "mock:log:foo". Notice the parameters
have been removed.</p></rich-text-body><p>Its also possible to only mock
certain endpoints using a pattern. For example to mock all <code>log</code>
endpoints you do as
shown:</p><plain-text-body>{snippet:id=e2|lang=java|title=adviceWith mocking
only log endpoints using a
pattern|url=camel/trunk/camel-core/src/test/java/org/apache/camel/processor/interceptor/AdviceWithMockEndpointsTest.java}</plain-text-body><p>The
pattern supported can be a wildcard or a regular expression. See more details
about this at <a shape="rect" href="intercept.html">Intercept</a> as its the
same matching function used by Camel.</p><rich-text-body><p>Mind that mocking
endpoints causes the messages to be
copied when they arrive on the mock.<br clear="none"> That means Camel will
use more memory. This may not be suitable when you send in a lot of
messages.</p></rich-text-body><h4
id="Bookcookbook-Mockingexistingendpointsusingthecamel-testcomponent">Mocking
existing endpoints using the <code>camel-test</code> component</h4><p>Instead
of using the <code>adviceWith</code> to instruct Camel to mock endpoints, you
can easily enable this behavior when using the <code>camel-test</code> Test
Kit.<br clear="none"> The same route can be tested as follows. Notice that we
return <code>"*"</code> from the <code>isMockEndpoints</code> method, which
tells Camel to mock all endpoints.<br clear="none"> If you only want to mock
all <code>log</code> endpoints you can return <code>"log*"</code>
instead.</p><plain-text-body>{snippet:id=e1|lang=java|title=isMockEndpoints
using camel-test
kit|url=camel/trunk/components/camel-test/src/test/java/org/apache/camel/test/patterns/IsMockEndpointsJUnit4Test.java}
</plain-text-body><h4
id="Bookcookbook-MockingexistingendpointswithXMLDSL">Mocking existing endpoints
with XML DSL</h4><p>If you do not use the <code>camel-test</code> component for
unit testing (as shown above) you can use a different approach when using XML
files for routes.<br clear="none"> The solution is to create a new XML file
used by the unit test and then include the intended XML file which has the
route you want to test.</p><p>Suppose we have the route in the
<code>camel-route.xml</code>
file:</p><plain-text-body>{snippet:id=e1|lang=xml|title=camel-route.xml|url=camel/trunk/components/camel-spring/src/test/resources/org/apache/camel/spring/mock/camel-route.xml}</plain-text-body><p>Then
we create a new XML file as follows, where we include the
<code>camel-route.xml</code> file and define a spring bean with the class
<code>org.apache.camel.impl.InterceptSendToMockEndpointStrategy</code> which
tells Camel to mock all
endpoints:</p><plain-text-body>{snippet:id=e1|lang=xml|titl
e=test-camel-route.xml|url=camel/trunk/components/camel-spring/src/test/resources/org/apache/camel/spring/mock/InterceptSendToMockEndpointStrategyTest.xml}</plain-text-body><p>Then
in your unit test you load the new XML file
(<code>test-camel-route.xml</code>) instead of
<code>camel-route.xml</code>.</p><p>To only mock all <a shape="rect"
href="log.html">Log</a> endpoints you can define the pattern in the constructor
for the bean:</p><parameter ac:name="">xml</parameter><plain-text-body><bean
id="mockAllEndpoints"
class="org.apache.camel.impl.InterceptSendToMockEndpointStrategy">
+ <constructor-arg index="0" value="log*"/>
</bean>
-]]></script>
-</div></div><h4
id="Bookcookbook-Mockingendpointsandskipsendingtooriginalendpoint">Mocking
endpoints and skip sending to original endpoint</h4><p><strong>Available as of
Camel 2.10</strong></p><p>Sometimes you want to easily mock and skip sending to
a certain endpoints. So the message is detoured and send to the mock endpoint
only. From Camel 2.10 onwards you can now use the
<code>mockEndpointsAndSkip</code> method using <a shape="rect"
href="advicewith.html">AdviceWith</a> or the <a shape="rect" class="unresolved"
href="#">Test Kit</a>. The example below will skip sending to the two endpoints
<code>"direct:foo"</code>, and <code>"direct:bar"</code>.</p><div class="code
panel pdl" style="border-width: 1px;"><div class="codeHeader panelHeader pdl"
style="border-bottom-width: 1px;"><b>adviceWith mock and skip sending to
endpoints</b></div><div class="codeContent panelContent pdl">
-<script class="brush: java; gutter: false; theme: Default"
type="syntaxhighlighter"><![CDATA[
-// tag::e1[]
-public void testAdvisedMockEndpointsWithSkip() throws Exception {
- // advice the first route using the inlined AdviceWith route builder
- // which has extended capabilities than the regular route builder
- context.getRouteDefinitions().get(0).adviceWith(context, new
AdviceWithRouteBuilder() {
- @Override
- public void configure() throws Exception {
- // mock sending to direct:foo and direct:bar and skip send to it
- mockEndpointsAndSkip("direct:foo",
"direct:bar");
- }
- });
-
-
getMockEndpoint("mock:result").expectedBodiesReceived("Hello
World");
- getMockEndpoint("mock:direct:foo").expectedMessageCount(1);
- getMockEndpoint("mock:direct:bar").expectedMessageCount(1);
-
- template.sendBody("direct:start", "Hello World");
-
- assertMockEndpointsSatisfied();
-
- // the message was not send to the direct:foo route and thus not sent to
the seda endpoint
- SedaEndpoint seda = context.getEndpoint("seda:foo",
SedaEndpoint.class);
- assertEquals(0, seda.getCurrentQueueSize());
-}
-// end::e1[]
-]]></script>
-</div></div><p>The same example using the <a shape="rect"
href="testing.html">Test Kit</a></p><div class="code panel pdl"
style="border-width: 1px;"><div class="codeHeader panelHeader pdl"
style="border-bottom-width: 1px;"><b>isMockEndpointsAndSkip using camel-test
kit</b></div><div class="codeContent panelContent pdl">
-<script class="brush: java; gutter: false; theme: Default"
type="syntaxhighlighter"><![CDATA[
-// tag::e1[]
-public class IsMockEndpointsAndSkipJUnit4Test extends CamelTestSupport {
-
- @Override
- public String isMockEndpointsAndSkip() {
- // override this method and return the pattern for which endpoints to
mock,
- // and skip sending to the original endpoint.
- return "direct:foo";
- }
-
- @Test
- public void testMockEndpointAndSkip() throws Exception {
- // notice we have automatic mocked the direct:foo endpoints and the
name of the endpoints is "mock:uri"
-
getMockEndpoint("mock:result").expectedBodiesReceived("Hello
World");
- getMockEndpoint("mock:direct:foo").expectedMessageCount(1);
-
- template.sendBody("direct:start", "Hello World");
-
- assertMockEndpointsSatisfied();
-
- // the message was not send to the direct:foo route and thus not sent
to the seda endpoint
- SedaEndpoint seda = context.getEndpoint("seda:foo",
SedaEndpoint.class);
- assertEquals(0, seda.getCurrentQueueSize());
- }
-
- @Override
- protected RouteBuilder createRouteBuilder() throws Exception {
- return new RouteBuilder() {
- @Override
- public void configure() throws Exception {
-
from("direct:start").to("direct:foo").to("mock:result");
-
- from("direct:foo").transform(constant("Bye
World")).to("seda:foo");
- }
- };
- }
-}
-// end::e1[]
-]]></script>
-</div></div><h3 id="Bookcookbook-Limitingthenumberofmessagestokeep">Limiting
the number of messages to keep</h3><p><strong>Available as of Camel
2.10</strong></p><p>The <a shape="rect" href="mock.html">Mock</a> endpoints
will by default keep a copy of every <a shape="rect"
href="exchange.html">Exchange</a> that it received. So if you test with a lot
of messages, then it will consume memory.<br clear="none"> From Camel 2.10
onwards we have introduced two options <code>retainFirst</code> and
<code>retainLast</code> that can be used to specify to only keep N'th of the
first and/or last <a shape="rect" href="exchange.html">Exchange</a>s.</p><p>For
example in the code below, we only want to retain a copy of the first 5 and
last 5 <a shape="rect" href="exchange.html">Exchange</a>s the mock
receives.</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[ MockEndpoint mock =
getMockEndpoint("mock:data");
[... 968 lines stripped ...]