Fuse 6 is no longer supported
As of February 2025, Red Hat Fuse 6 is no longer supported. If you are using Fuse 6, please upgrade to Red Hat build of Apache Camel.Routing Expression and Predicate Languages
Writing evaluative statements
Copyright © 2013 Red Hat, Inc. and/or its affiliates.
Abstract
Chapter 1. Introduction Copy linkLink copied to clipboard!
Abstract
1.1. Overview of the Languages Copy linkLink copied to clipboard!
Table of expression and predicate languages Copy linkLink copied to clipboard!
| Language | Static Method | Fluent DSL Method | XML Element | Annotation | Artifact |
|---|---|---|---|---|---|
| section "Bean Integration" in "Implementing Enterprise Integration Patterns" | bean() | EIP().method() | method | @Bean | Camel core |
| Constant | constant() | EIP().constant() | constant | @Constant | Camel core |
| EL | el() | EIP().el() | el | @EL | camel-juel |
| Groovy | groovy() | EIP().groovy() | groovy | @Groovy | camel-groovy |
| Header | header() | EIP().header() | header | @Header | Camel core |
| JavaScript | javaScript() | EIP().javaScript() | javaScript | @JavaScript | camel-script |
| JoSQL | sql() | EIP().sql() | sql | @SQL | camel-josql |
| JXPath | None | EIP().jxpath() | jxpath | @JXPath | camel-jxpath |
| MVEL | mvel() | EIP().mvel() | mvel | @MVEL | camel-mvel |
| OGNL | ognl() | EIP().ognl() | ognl | @OGNL | camel-ognl |
| PHP | php() | EIP().php() | php | @PHP | camel-script |
| Property | property() | EIP().property() | property | @Property | Camel core |
| Python | python() | EIP().python() | python | @Python | camel-script |
| Ref | ref() | EIP().ref() | ref | N/A | Camel core |
| Ruby | ruby() | EIP().ruby() | ruby | @Ruby | camel-script |
| Simple/File | simple() | EIP().simple() | simple | @Simple | Camel core |
| SpEL | spel() | EIP().spel() | spel | @SpEL | camel-spring |
| XPath | xpath() | EIP().xpath() | xpath | @XPath | Camel core |
| XQuery | xquery() | EIP().xquery() | xquery | @XQuery | camel-saxon |
1.2. How to Invoke an Expression Language Copy linkLink copied to clipboard!
Prerequisites Copy linkLink copied to clipboard!
camel-groovy feature by entering the following OSGi console command:
karaf@root> features:install camel-groovy
karaf@root> features:install camel-groovy
Approaches to invoking Copy linkLink copied to clipboard!
As a static method Copy linkLink copied to clipboard!
org.apache.camel.Expression type or an org.apache.camel.Predicate type is expected. The static method takes a string expression (or predicate) as its argument and returns an Expression object (which is usually also a Predicate object).
/order/address/countryCode element, as follows:
As a fluent DSL method Copy linkLink copied to clipboard!
filter(xpath("Expression")), you can invoke the expression as, filter().xpath("Expression").
As an XML element Copy linkLink copied to clipboard!
xpath (which belongs to the standard Apache Camel namespace). You can use XPath expressions in a XML DSL content-based router, as follows:
language element, where you specify the name of the language in the language attribute. For example, you can define an XPath expression using the language element as follows:
<language language="xpath">/order/address/countryCode = 'us'</language>
<language language="xpath">/order/address/countryCode = 'us'</language>
As an annotation Copy linkLink copied to clipboard!
myBeanProc, which is invoked as a predicate of the filter() EIP. If the bean's checkCredentials method returns true, the message is allowed to proceed; but if the method returns false, the message is blocked by the filter. The filter pattern is implemented as follows:
MyBeanProcessor class exploits the @XPath annotation to extract the username and password from the underlying XML message, as follows:
@XPath annotation is placed just before the parameter into which it gets injected. Notice how the XPath expression explicitly selects the text node, by appending /text() to the path, which ensures that just the content of the element is selected, not the enclosing tags.
Chapter 2. Constant Copy linkLink copied to clipboard!
Overview Copy linkLink copied to clipboard!
XML example Copy linkLink copied to clipboard!
username header to the value, Jane Doe as follows:
Java example Copy linkLink copied to clipboard!
username header to the value, Jane Doe as follows:
from("SourceURL")
.setHeader("username", constant("Jane Doe"))
.to("TargetURL");
from("SourceURL")
.setHeader("username", constant("Jane Doe"))
.to("TargetURL");
Chapter 3. EL Copy linkLink copied to clipboard!
Overview Copy linkLink copied to clipboard!
Adding JUEL package Copy linkLink copied to clipboard!
camel-juel to your project as shown in Example 3.1, “Adding the camel-juel dependency”.
Example 3.1. Adding the camel-juel dependency
Static import Copy linkLink copied to clipboard!
el() static method in your application code, include the following import statement in your Java source files:
import static org.apache.camel.language.juel.JuelExpression.el;
import static org.apache.camel.language.juel.JuelExpression.el;
Variables Copy linkLink copied to clipboard!
| Variable | Type | Value |
|---|---|---|
exchange | org.apache.camel.Exchange | The current Exchange |
in | org.apache.camel.Message | The IN message |
out | org.apache.camel.Message | The OUT message |
Example Copy linkLink copied to clipboard!
Example 3.2. Routes using EL
Chapter 4. The File Language Copy linkLink copied to clipboard!
Abstract
4.1. When to Use the File Language Copy linkLink copied to clipboard!
Overview Copy linkLink copied to clipboard!
\, is not available in the file language.
In a File or FTP consumer endpoint Copy linkLink copied to clipboard!
fileName, move, preMove, moveFailed, and sortBy options using a file expression.
fileName option acts as a filter, determining which file will actually be read from the starting directory. If a plain text string is specified (for example, fileName=report.txt), the File consumer reads the same file each time it is updated. You can make this option more dynamic, however, by specifying a simple expression. For example, you could use a counter bean to select a different file each time the File consumer polls the starting directory, as follows:
file://target/filelanguage/bean/?fileName=${bean:counter.next}.txt&delete=true
file://target/filelanguage/bean/?fileName=${bean:counter.next}.txt&delete=true
${bean:counter.next} expression invokes the next() method on the bean registered under the ID, counter.
move option is used to move files to a backup location after then have been read by a File consumer endpoint. For example, the following endpoint moves files to a backup directory, after they have been processed:
file://target/filelanguage/?move=backup/${date:now:yyyyMMdd}/${file:name.noext}.bak&recursive=false
file://target/filelanguage/?move=backup/${date:now:yyyyMMdd}/${file:name.noext}.bak&recursive=false
${file:name.noext}.bak expression modifies the original file name, replacing the file extension with .bak.
sortBy option to specify the order in which file should be processed. For example, to process files according to the alphabetical order of their file name, you could use the following File consumer endpoint:
file://target/filelanguage/?sortBy=file:name
file://target/filelanguage/?sortBy=file:name
file://target/filelanguage/?sortBy=file:modified
file://target/filelanguage/?sortBy=file:modified
reverse: prefix—for example:
file://target/filelanguage/?sortBy=reverse:file:modified
file://target/filelanguage/?sortBy=reverse:file:modified
On exchanges created by a File or FTP consumer Copy linkLink copied to clipboard!
4.2. File Variables Copy linkLink copied to clipboard!
Overview Copy linkLink copied to clipboard!
java.io.File type. The file variables enable you to access various parts of the file pathname, almost as if you were invoking the methods of the java.io.File class (in fact, the file language extracts the information it needs from message headers that have been set by the File or FTP endpoint).
Starting directory Copy linkLink copied to clipboard!
./filetransfer (a relative path):
file:filetransfer
file:filetransfer
./ftptransfer (a relative path):
ftp://myhost:2100/ftptransfer
ftp://myhost:2100/ftptransfer
Naming convention of file variables Copy linkLink copied to clipboard!
java.io.File class. For example, the file:absolute variable gives the value that would be returned by the java.io.File.getAbsolute() method.
java.io.File.getSize().
Table of variables Copy linkLink copied to clipboard!
| Variable | Type | Description |
|---|---|---|
file:name | String | The pathname relative to the starting directory. |
file:name.ext | String | The file extension (characters following the last . character in the pathname). |
file:name.noext | String | The pathname relative to the starting directory, omitting the file extension. |
file:onlyname | String | The final segment of the pathname. That is, the file name without the parent directory path. |
file:onlyname.noext | String | The final segment of the pathname, omitting the file extension. |
file:ext | String | The file extension (same as file:name.ext). |
file:parent | String | The pathname of the parent directory, including the starting directory in the path. |
file:path | String | The file pathname, including the starting directory in the path. |
file:absolute | Boolean | true, if the starting directory was specified as an absolute path; false, otherwise. |
file:absolute.path | String | The absolute pathname of the file. |
file:length | Long | The size of the referenced file. |
file:size | Long | Same as file:length. |
file:modified | java.util.Date | Date last modified. |
4.3. Examples Copy linkLink copied to clipboard!
Relative pathname Copy linkLink copied to clipboard!
./filelanguage:
file://filelanguage
file://filelanguage
filelanguage directory, suppose that the endpoint has just consumed the following file:
./filelanguage/test/hello.txt
./filelanguage/test/hello.txt
filelanguage directory itself has the following absolute location:
/workspace/camel/camel-core/target/filelanguage
/workspace/camel/camel-core/target/filelanguage
| Expression | Result |
|---|---|
file:name | test/hello.txt |
file:name.ext | txt |
file:name.noext | test/hello |
file:onlyname | hello.txt |
file:onlyname.noext | hello |
file:ext | txt |
file:parent | filelanguage/test |
file:path | filelanguage/test/hello.txt |
file:absolute | false |
file:absolute.path | /workspace/camel/camel-core/target/filelanguage/test/hello.txt |
Absolute pathname Copy linkLink copied to clipboard!
/workspace/camel/camel-core/target/filelanguage:
file:///workspace/camel/camel-core/target/filelanguage
file:///workspace/camel/camel-core/target/filelanguage
filelanguage directory, suppose that the endpoint has just consumed the following file:
./filelanguage/test/hello.txt
./filelanguage/test/hello.txt
| Expression | Result |
|---|---|
file:name | test/hello.txt |
file:name.ext | txt |
file:name.noext | test/hello |
file:onlyname | hello.txt |
file:onlyname.noext | hello |
file:ext | txt |
file:parent | /workspace/camel/camel-core/target/filelanguage/test |
file:path | /workspace/camel/camel-core/target/filelanguage/test/hello.txt |
file:absolute | true |
file:absolute.path | /workspace/camel/camel-core/target/filelanguage/test/hello.txt |
Chapter 5. Groovy Copy linkLink copied to clipboard!
Overview Copy linkLink copied to clipboard!
camel-script module.
Adding the script module Copy linkLink copied to clipboard!
camel-script to your project as shown in Example 5.1, “Adding the camel-script dependency”.
Example 5.1. Adding the camel-script dependency
Static import Copy linkLink copied to clipboard!
groovy() static method in your application code, include the following import statement in your Java source files:
import static org.apache.camel.builder.camel.script.ScriptBuilder.*;
import static org.apache.camel.builder.camel.script.ScriptBuilder.*;
Built-in attributes Copy linkLink copied to clipboard!
| Attribute | Type | Value |
|---|---|---|
context | org.apache.camel.CamelContext | The Camel Context |
exchange | org.apache.camel.Exchange | The current Exchange |
request | org.apache.camel.Message | The IN message |
response | org.apache.camel.Message | The OUT message |
properties | org.apache.camel.builder.script.PropertiesFunction | Function with a resolve method to make it easier to use the properties component inside scripts. |
ENGINE_SCOPE.
Example Copy linkLink copied to clipboard!
Example 5.2. Routes using Groovy
Using the properties component Copy linkLink copied to clipboard!
resolve method on the built-in properties attribute, as follows:
.setHeader("myHeader").groovy("properties.resolve(PropKey)")
.setHeader("myHeader").groovy("properties.resolve(PropKey)")
String type.
Chapter 6. Header Copy linkLink copied to clipboard!
Overview Copy linkLink copied to clipboard!
camel-core.
XML example Copy linkLink copied to clipboard!
SequenceNumber header (where the sequence number must be a positive integer), you can define a route as follows:
Java example Copy linkLink copied to clipboard!
from("SourceURL")
.resequence(header("SequenceNumber"))
.to("TargetURL");
from("SourceURL")
.resequence(header("SequenceNumber"))
.to("TargetURL");
Chapter 7. JavaScript Copy linkLink copied to clipboard!
Overview Copy linkLink copied to clipboard!
camel-script module.
Adding the script module Copy linkLink copied to clipboard!
camel-script to your project as shown in Example 7.1, “Adding the camel-script dependency”.
Example 7.1. Adding the camel-script dependency
Static import Copy linkLink copied to clipboard!
javaScript() static method in your application code, include the following import statement in your Java source files:
import static org.apache.camel.builder.camel.script.ScriptBuilder.*;
import static org.apache.camel.builder.camel.script.ScriptBuilder.*;
Built-in attributes Copy linkLink copied to clipboard!
| Attribute | Type | Value |
|---|---|---|
context | org.apache.camel.CamelContext | The Camel Context |
exchange | org.apache.camel.Exchange | The current Exchange |
request | org.apache.camel.Message | The IN message |
response | org.apache.camel.Message | The OUT message |
properties | org.apache.camel.builder.script.PropertiesFunction | Function with a resolve method to make it easier to use the properties component inside scripts. |
ENGINE_SCOPE.
Example Copy linkLink copied to clipboard!
Example 7.2. Route using JavaScript
Using the properties component Copy linkLink copied to clipboard!
resolve method on the built-in properties attribute, as follows:
.setHeader("myHeader").javaScript("properties.resolve(PropKey)")
.setHeader("myHeader").javaScript("properties.resolve(PropKey)")
String type.
Chapter 8. JoSQL Copy linkLink copied to clipboard!
Overview Copy linkLink copied to clipboard!
Adding the JoSQL module Copy linkLink copied to clipboard!
camel-josql to your project as shown in Example 8.1, “Adding the camel-josql dependency”.
Example 8.1. Adding the camel-josql dependency
Static import Copy linkLink copied to clipboard!
sql() static method in your application code, include the following import statement in your Java source files:
import static org.apache.camel.builder.sql.SqlBuilder.sql;
import static org.apache.camel.builder.sql.SqlBuilder.sql;
Variables Copy linkLink copied to clipboard!
| Name | Type | Description |
|---|---|---|
exchange | org.apache.camel.Exchange | The current Exchange |
in | org.apache.camel.Message | The IN message |
out | org.apache.camel.Message | The OUT message |
| property | Object | the Exchange property whose key is property |
| header | Object | the IN message header whose key is header |
| variable | Object | the variable whose key is variable |
Example Copy linkLink copied to clipboard!
Example 8.2. Route using JoSQL
Chapter 9. JXPath Copy linkLink copied to clipboard!
Overview Copy linkLink copied to clipboard!
Adding JXPath package Copy linkLink copied to clipboard!
camel-jxpath to your project as shown in Example 9.1, “Adding the camel-jxpath dependency”.
Example 9.1. Adding the camel-jxpath dependency
Variables Copy linkLink copied to clipboard!
| Variable | Type | Value |
|---|---|---|
this | org.apache.camel.Exchange | The current Exchange |
in | org.apache.camel.Message | The IN message |
out | org.apache.camel.Message | The OUT message |
Example Copy linkLink copied to clipboard!
Example 9.2. Routes using JXPath
Chapter 10. MVEL Copy linkLink copied to clipboard!
Overview Copy linkLink copied to clipboard!
camel-mvel module.
Syntax Copy linkLink copied to clipboard!
getRequest().getBody().getFamilyName()
getRequest().getBody().getFamilyName()
Object type) before invoking the getFamilyName() method. You can also use an abbreviated syntax for invoking bean attributes, for example:
request.body.familyName
request.body.familyName
Adding the MVEL module Copy linkLink copied to clipboard!
camel-mvel to your project as shown in Example 10.1, “Adding the camel-mvel dependency”.
Example 10.1. Adding the camel-mvel dependency
Built-in variables Copy linkLink copied to clipboard!
| Name | Type | Description |
|---|---|---|
this | org.apache.camel.Exchange | The current Exchange |
exchange | org.apache.camel.Exchange | The current Exchange |
exception | Throwable | the Exchange exception (if any) |
exchangeID | String | the Exchange ID |
fault | org.apache.camel.Message | The Fault message(if any) |
request | org.apache.camel.Message | The IN message |
response | org.apache.camel.Message | The OUT message |
properties | Map | The Exchange properties |
property(name) | Object | The value of the named Exchange property |
property(name, type) | Type | The typed value of the named Exchange property |
Example Copy linkLink copied to clipboard!
Example 10.2. Route using MVEL
Chapter 11. The Object-Graph Navigation Language(OGNL) Copy linkLink copied to clipboard!
Overview Copy linkLink copied to clipboard!
camel-ognl module.
Adding the OGNL module Copy linkLink copied to clipboard!
camel-ognl to your project as shown in Example 11.1, “Adding the camel-ognl dependency”.
Example 11.1. Adding the camel-ognl dependency
Static import Copy linkLink copied to clipboard!
ognl() static method in your application code, include the following import statement in your Java source files:
import static org.apache.camel.language.ognl.OgnlExpression.ognl;
import static org.apache.camel.language.ognl.OgnlExpression.ognl;
Built-in variables Copy linkLink copied to clipboard!
| Name | Type | Description |
|---|---|---|
this | org.apache.camel.Exchange | The current Exchange |
exchange | org.apache.camel.Exchange | The current Exchange |
exception | Throwable | the Exchange exception (if any) |
exchangeID | String | the Exchange ID |
fault | org.apache.camel.Message | The Fault message(if any) |
request | org.apache.camel.Message | The IN message |
response | org.apache.camel.Message | The OUT message |
properties | Map | The Exchange properties |
property(name) | Object | The value of the named Exchange property |
property(name, type) | Type | The typed value of the named Exchange property |
Example Copy linkLink copied to clipboard!
Example 11.2. Route using OGNL
Chapter 12. PHP Copy linkLink copied to clipboard!
Overview Copy linkLink copied to clipboard!
camel-script module.
Adding the script module Copy linkLink copied to clipboard!
camel-script to your project as shown in Example 12.1, “Adding the camel-script dependency”.
Example 12.1. Adding the camel-script dependency
Static import Copy linkLink copied to clipboard!
php() static method in your application code, include the following import statement in your Java source files:
import static org.apache.camel.builder.camel.script.ScriptBuilder.*;
import static org.apache.camel.builder.camel.script.ScriptBuilder.*;
Built-in attributes Copy linkLink copied to clipboard!
| Attribute | Type | Value |
|---|---|---|
context | org.apache.camel.CamelContext | The Camel Context |
exchange | org.apache.camel.Exchange | The current Exchange |
request | org.apache.camel.Message | The IN message |
response | org.apache.camel.Message | The OUT message |
properties | org.apache.camel.builder.script.PropertiesFunction | Function with a resolve method to make it easier to use the properties component inside scripts. |
ENGINE_SCOPE.
Example Copy linkLink copied to clipboard!
Example 12.2. Route using PHP
Using the properties component Copy linkLink copied to clipboard!
resolve method on the built-in properties attribute, as follows:
.setHeader("myHeader").php("properties.resolve(PropKey)")
.setHeader("myHeader").php("properties.resolve(PropKey)")
String type.
Chapter 13. Property Copy linkLink copied to clipboard!
Overview Copy linkLink copied to clipboard!
camel-core.
XML example Copy linkLink copied to clipboard!
listOfEndpoints exchange property contains the recipient list, you could define a route as follows:
Java example Copy linkLink copied to clipboard!
from("direct:a").recipientList(property("listOfEndpoints"));
from("direct:a").recipientList(property("listOfEndpoints"));
Chapter 14. Python Copy linkLink copied to clipboard!
Overview Copy linkLink copied to clipboard!
camel-script module.
Adding the script module Copy linkLink copied to clipboard!
camel-script to your project as shown in Example 14.1, “Adding the camel-script dependency”.
Example 14.1. Adding the camel-script dependency
Static import Copy linkLink copied to clipboard!
python() static method in your application code, include the following import statement in your Java source files:
import static org.apache.camel.builder.camel.script.ScriptBuilder.*;
import static org.apache.camel.builder.camel.script.ScriptBuilder.*;
Built-in attributes Copy linkLink copied to clipboard!
| Attribute | Type | Value |
|---|---|---|
context | org.apache.camel.CamelContext | The Camel Context |
exchange | org.apache.camel.Exchange | The current Exchange |
request | org.apache.camel.Message | The IN message |
response | org.apache.camel.Message | The OUT message |
properties | org.apache.camel.builder.script.PropertiesFunction | Function with a resolve method to make it easier to use the properties component inside scripts. |
ENGINE_SCOPE.
Example Copy linkLink copied to clipboard!
Example 14.2. Route using Python
Using the properties component Copy linkLink copied to clipboard!
resolve method on the built-in properties attribute, as follows:
.setHeader("myHeader").python("properties.resolve(PropKey)")
.setHeader("myHeader").python("properties.resolve(PropKey)")
String type.
Chapter 15. Ref Copy linkLink copied to clipboard!
Overview Copy linkLink copied to clipboard!
camel-core.
Static import Copy linkLink copied to clipboard!
import static org.apache.camel.language.simple.RefLanguage.ref;
import static org.apache.camel.language.simple.RefLanguage.ref;
XML example Copy linkLink copied to clipboard!
Java example Copy linkLink copied to clipboard!
from("seda:a")
.split().ref("myExpression")
.to("seda:b");
from("seda:a")
.split().ref("myExpression")
.to("seda:b");
Chapter 16. Ruby Copy linkLink copied to clipboard!
Overview Copy linkLink copied to clipboard!
camel-script module.
Adding the script module Copy linkLink copied to clipboard!
camel-script to your project as shown in Example 16.1, “Adding the camel-script dependency”.
Example 16.1. Adding the camel-script dependency
Static import Copy linkLink copied to clipboard!
ruby() static method in your application code, include the following import statement in your Java source files:
import static org.apache.camel.builder.camel.script.ScriptBuilder.*;
import static org.apache.camel.builder.camel.script.ScriptBuilder.*;
Built-in attributes Copy linkLink copied to clipboard!
| Attribute | Type | Value |
|---|---|---|
context | org.apache.camel.CamelContext | The Camel Context |
exchange | org.apache.camel.Exchange | The current Exchange |
request | org.apache.camel.Message | The IN message |
response | org.apache.camel.Message | The OUT message |
properties | org.apache.camel.builder.script.PropertiesFunction | Function with a resolve method to make it easier to use the properties component inside scripts. |
ENGINE_SCOPE.
Example Copy linkLink copied to clipboard!
Example 16.2. Route using Ruby
Using the properties component Copy linkLink copied to clipboard!
resolve method on the built-in properties attribute, as follows:
.setHeader("myHeader").ruby("properties.resolve(PropKey)")
.setHeader("myHeader").ruby("properties.resolve(PropKey)")
String type.
Chapter 17. The Simple Language Copy linkLink copied to clipboard!
Abstract
17.1. Java DSL Copy linkLink copied to clipboard!
Simple expressions in Java DSL Copy linkLink copied to clipboard!
simple() command in a route. You can either pass the simple() command as an argument to a processor, as follows:
from("seda:order")
.filter(simple("${in.header.foo}"))
.to("mock:fooOrders");
from("seda:order")
.filter(simple("${in.header.foo}"))
.to("mock:fooOrders");
simple() command as a sub-clause on the processor, for example:
from("seda:order")
.filter()
.simple("${in.header.foo}")
.to("mock:fooOrders");
from("seda:order")
.filter()
.simple("${in.header.foo}")
.to("mock:fooOrders");
Embedding in a string Copy linkLink copied to clipboard!
${Expression}. For example, to embed the in.header.name expression in a string:
simple("Hello ${in.header.name}, how are you?")
simple("Hello ${in.header.name}, how are you?")
Customizing the start and end tokens Copy linkLink copied to clipboard!
{ and }, by default) by calling the changeFunctionStartToken static method and the changeFunctionEndToken static method on the SimpleLanguage object.
[ and ] in Java, as follows:
// Java
import org.apache.camel.language.simple.SimpleLanguage;
...
SimpleLanguage.changeFunctionStartToken("[");
SimpleLanguage.changeFunctionEndToken("]");
// Java
import org.apache.camel.language.simple.SimpleLanguage;
...
SimpleLanguage.changeFunctionStartToken("[");
SimpleLanguage.changeFunctionEndToken("]");
camel-core library on their classpath. For example, in an OSGi server this might affect many applications; whereas in a Web application (WAR file) it would affect only the Web application itself.
17.2. XML DSL Copy linkLink copied to clipboard!
Simple expressions in XML DSL Copy linkLink copied to clipboard!
simple element. For example, to define a route that performs filtering based on the contents of the foo header:
Alternative placeholder syntax Copy linkLink copied to clipboard!
${Expression} syntax clashes with another property placeholder syntax. In this case, you can disambiguate the placeholder using the alternative syntax, $simple{Expression}, for the simple expression. For example:
<simple>Hello $simple{in.header.name}, how are you?</simple>
<simple>Hello $simple{in.header.name}, how are you?</simple>
Customizing the start and end tokens Copy linkLink copied to clipboard!
{ and }, by default) by overriding the SimpleLanguage instance. For example, to change the start and end tokens to [ and ], define a new SimpleLanguage bean in your XML configuration file, as follows:
<bean id="simple" class="org.apache.camel.language.simple.SimpleLanguage"> <constructor-arg name="functionStartToken" value="["/> <constructor-arg name="functionEndToken" value="]"/> </bean>
<bean id="simple" class="org.apache.camel.language.simple.SimpleLanguage">
<constructor-arg name="functionStartToken" value="["/>
<constructor-arg name="functionEndToken" value="]"/>
</bean>
camel-core library on their classpath. For example, in an OSGi server this might affect many applications; whereas in a Web application (WAR file) it would affect only the Web application itself.
Whitespace and auto-trim in XML DSL Copy linkLink copied to clipboard!
<transform>
<simple>
data=${body}
</simple>
</transform>
<transform>
<simple>
data=${body}
</simple>
</transform>
<transform>
<simple>data=${body}</simple>
</transform>
<transform>
<simple>data=${body}</simple>
</transform>
<transform>
<simple>data=${body}\n</simple>
</transform>
<transform>
<simple>data=${body}\n</simple>
</transform>
trim attribute to false, as follows:
<transform trim="false">
<simple>data=${body}
</simple>
</transform>
<transform trim="false">
<simple>data=${body}
</simple>
</transform>
17.3. Expressions Copy linkLink copied to clipboard!
Overview Copy linkLink copied to clipboard!
simple("${header.timeOfDay}"), would return the contents of a header called timeOfDay from the incoming message.
${Expression}, to return a variable value. It is never permissible to omit the enclosing tokens (${ and }).
Contents of a single variable Copy linkLink copied to clipboard!
in.header.HeaderName, to obtain the value of the HeaderName header, as follows:
simple("${in.header.foo}")
simple("${in.header.foo}")
Variables embedded in a string Copy linkLink copied to clipboard!
simple("Received a message from ${in.header.user} on $(date:in.header.date:yyyyMMdd}.")
simple("Received a message from ${in.header.user} on $(date:in.header.date:yyyyMMdd}.")
date and bean variables Copy linkLink copied to clipboard!
date:command:pattern, and for calling bean methods, bean:beanRef. For example, you can use the date and the bean variables as follows:
simple("Todays date is ${date:now:yyyyMMdd}")
simple("The order type is ${bean:orderService?method=getOrderType}")
simple("Todays date is ${date:now:yyyyMMdd}")
simple("The order type is ${bean:orderService?method=getOrderType}")
Specifying the result type Copy linkLink copied to clipboard!
simple(). For example, to return a boolean result, you could evaluate a simple expression as follows:
...
.setHeader("cool", simple("true", Boolean.class))
...
.setHeader("cool", simple("true", Boolean.class))
resultType attribute. For example:
<setHeader headerName="cool"> <!-- use resultType to indicate that the type should be a java.lang.Boolean --> <simple resultType="java.lang.Boolean">true</simple> </setHeader>
<setHeader headerName="cool">
<!-- use resultType to indicate that the type should be a java.lang.Boolean -->
<simple resultType="java.lang.Boolean">true</simple>
</setHeader>
Nested expressions Copy linkLink copied to clipboard!
simple("${header.${bean:headerChooser?method=whichHeader}}")
simple("${header.${bean:headerChooser?method=whichHeader}}")
OGNL expressions Copy linkLink copied to clipboard!
getAddress() accessor, you can access the Address object and the Address object's properties as follows:
simple("${body.address}")
simple("${body.address.street}")
simple("${body.address.zip}")
simple("${body.address.city}")
simple("${body.address}")
simple("${body.address.street}")
simple("${body.address.zip}")
simple("${body.address.city}")
${body.address.street}, is shorthand for ${body.getAddress.getStreet}.
OGNL null-safe operator Copy linkLink copied to clipboard!
?., to avoid encountering null-pointer exceptions, in case the body does not have an address. For example:
simple("${body?.address?.street}")
simple("${body?.address?.street}")
java.util.Map type, you can look up a value in the map with the key, foo, using the following notation:
simple("${body[foo]?.name}")
simple("${body[foo]?.name}")
OGNL list element access Copy linkLink copied to clipboard!
[k], to access the elements of a list. For example:
simple("${body.address.lines[0]}")
simple("${body.address.lines[1]}")
simple("${body.address.lines[2]}")
simple("${body.address.lines[0]}")
simple("${body.address.lines[1]}")
simple("${body.address.lines[2]}")
last keyword returns the index of the last element of a list. For example, you can access the second last element of a list, as follows:
simple("${body.address.lines[last-1]}")
simple("${body.address.lines[last-1]}")
17.4. Predicates Copy linkLink copied to clipboard!
Overview Copy linkLink copied to clipboard!
simple("${header.timeOfDay} == '14:30'"), tests whether the timeOfDay header in the incoming message is equal to 14:30.
Syntax Copy linkLink copied to clipboard!
${LHSVariable} Op RHSValue
${LHSVariable} Op RHSValue
- Another variable,
${RHSVariable}. - A string literal, enclosed in single quotes,
' '. - A numeric constant, enclosed in single quotes,
' '. - The null object,
null.
Examples Copy linkLink copied to clipboard!
simple("${in.header.user} == 'john'")
simple("${in.header.number} > '100'") // String literal can be converted to integer
simple("${in.header.user} == 'john'")
simple("${in.header.number} > '100'") // String literal can be converted to integer
simple("${in.header.type} in 'gold,silver'")
simple("${in.header.type} in 'gold,silver'")
simple("${in.header.number} regex '\d{4}'")
simple("${in.header.number} regex '\d{4}'")
is operator, as follows:
simple("${in.header.type} is 'java.lang.String'")
simple("${in.header.type} is 'String'") // You can abbreviate java.lang. types
simple("${in.header.type} is 'java.lang.String'")
simple("${in.header.type} is 'String'") // You can abbreviate java.lang. types
simple("${in.header.number} range '100..199'")
simple("${in.header.number} range '100..199'")
Conjunctions Copy linkLink copied to clipboard!
&& and ||.
&& conjunction (logical and):
simple("${in.header.title} contains 'Camel' && ${in.header.type} == 'gold'")
simple("${in.header.title} contains 'Camel' && ${in.header.type} == 'gold'")
|| conjunction (logical inclusive or):
simple("${in.header.title} contains 'Camel' || ${in.header.type} == 'gold'")
simple("${in.header.title} contains 'Camel' || ${in.header.type} == 'gold'")
17.5. Variable Reference Copy linkLink copied to clipboard!
Table of variables Copy linkLink copied to clipboard!
| Variable | Type | Description |
|---|---|---|
exchangeId | String | The exchange's ID value. |
id | String | The In message ID value. |
body | Object |
The In message body. Supports OGNL expressions.
|
in.body | Object | The In message body. Supports OGNL expressions. |
out.body | Object |
The Out message body.
|
bodyAs(Type) | Type | The In message body, converted to the specified type. All types, Type, must be specified using their fully-qualified Java name, except for the types: byte[], String, Integer, and Long. The converted body can be null. |
mandatoryBodyAs(Type) | Type | The In message body, converted to the specified type. All types, Type, must be specified using their fully-qualified Java name, except for the types: byte[], String, Integer, and Long. The converted body is expected to be non-null. |
header.HeaderName | Object |
The In message's HeaderName header. Supports OGNL expressions.
|
header[HeaderName] | Object |
The In message's HeaderName header (alternative syntax).
|
headers.HeaderName | Object | The In message's HeaderName header. |
headers[HeaderName] | Object | The In message's HeaderName header (alternative syntax). |
in.header.HeaderName | Object | The In message's HeaderName header. Supports OGNL expressions. |
in.header[HeaderName] | Object | The In message's HeaderName header (alternative syntax). |
in.headers.HeaderName | Object | The In message's HeaderName header. Supports OGNL expressions. |
in.headers[HeaderName] | Object | The In message's HeaderName header (alternative syntax). |
out.header.HeaderName | Object |
The Out message's HeaderName header.
|
out.header[HeaderName] | Object |
The Out message's HeaderName header (alternative syntax).
|
out.headers.HeaderName | Object | The Out message's HeaderName header. |
out.headers[HeaderName] | Object | The Out message's HeaderName header (alternative syntax). |
headerAs(Key,Type) | Type | The Key header, converted to the specified type. All types, Type, must be specified using their fully-qualified Java name, except for the types: byte[], String, Integer, and Long. The converted value can be null. |
headers | Map | All of the In headers (as a java.util.Map type). |
in.headers | Map | All of the In headers (as a java.util.Map type). |
property.PropertyName | Object |
The PropertyName property on the exchange.
|
property[PropertyName] | Object |
The PropertyName property on the exchange (alternative syntax).
|
sys.SysPropertyName | String | The SysPropertyName Java system property. |
sysenv.SysEnvVar | String | The SysEnvVar system environment variable. |
exception | String | Either the exception object from Exchange.getException() or, if this value is null, the caught exception from the Exchange.EXCEPTION_CAUGHT property; otherwise null. Supports OGNL expressions. |
exception.message | String | If an exception is set on the exchange, returns the value of Exception.getMessage(); otherwise, returns null. |
exception.stacktrace | String | If an exception is set on the exchange, returns the value of Exception.getStackTrace(); otherwise, returns null. Note: The simple language first tries to retrieve an exception from Exchange.getException(). If that property is not set, it checks for a caught exception, by calling Exchange.getProperty(Exchange.CAUGHT_EXCEPTION). |
date:command:pattern | String | A date formatted using a java.text.SimpleDateFormat pattern. The following commands are supported: now, for the current date and time; header.HeaderName, or in.header.HeaderName to use a java.util.Date object in the HeaderName header from the In message; out.header.HeaderName to use a java.util.Date object in the HeaderName header from the Out message; |
bean:beanID.Method | Object | Invokes a method on the referenced bean and returns the result of the method invocation. To specify a method name, you can either use the beanID.Method syntax; or you can use the beanID?method=methodName syntax. |
ref:beanID | Object | Looks up the bean with the ID, beanID, in the registry and returns a reference to the bean itself. For example, if you are using the splitter EIP, you could use this variable to reference the bean that implements the splitting algorithm. |
properties:Key | String | The value of the Key property placeholder (see section "Property Placeholders" in "Implementing Enterprise Integration Patterns"). |
properties:Location:Key | String | The value of the Key property placeholder, where the location of the properties file is given by Location (see section "Property Placeholders" in "Implementing Enterprise Integration Patterns"). |
threadName | String | The name of the current thread. |
17.6. Operator Reference Copy linkLink copied to clipboard!
Binary operators Copy linkLink copied to clipboard!
| Operator | Description |
|---|---|
== | Equals. |
> | Greater than. |
>= | Greater than or equals. |
< | Less than. |
<= | Less than or equals. |
!= | Not equal to. |
contains | Test if LHS string contains RHS string. |
not contains | Test if LHS string does not contain RHS string. |
regex | Test if LHS string matches RHS regular expression. |
not regex | Test if LHS string does not match RHS regular expression. |
in | Test if LHS string appears in the RHS comma-separated list. |
not in | Test if LHS string does not appear in the RHS comma-separated list. |
is | Test if LHS is an instance of RHS Java type (using Java instanceof operator). |
not is | Test if LHS is not an instance of RHS Java type (using Java instanceof operator). |
range | Test if LHS number lies in the RHS range (where range has the format, 'min...max'). |
not range | Test if LHS number does not lie in the RHS range (where range has the format, 'min...max'). |
Unary operators Copy linkLink copied to clipboard!
| Operator | Description |
|---|---|
++ | Increment a number by 1. |
-- | Decrement a number by 1. |
\ | Escape the following character. Note the following special cases: \n for new line, \t for tab, and \r for carriage return. |
Combining predicates Copy linkLink copied to clipboard!
| Operator | Description |
|---|---|
&& | Combine two predicates with logical and. |
|| | Combine two predicates with logical inclusive or. |
and | Deprecated. Use && instead. |
or | Deprecated. Use || instead. |
Chapter 18. SpEL Copy linkLink copied to clipboard!
Overview Copy linkLink copied to clipboard!
Syntax Copy linkLink copied to clipboard!
#{SpelExpression}, so that they can be embedded in a plain text string (in other words, SpEL has expression templating enabled).
@BeanID syntax. For example, given a bean with the ID, headerUtils, and the method, count() (which counts the number of headers on the current message), you could use the headerUtils bean in an SpEL predicate, as follows:
#{@headerUtils.count > 4}
#{@headerUtils.count > 4}
Adding SpEL package Copy linkLink copied to clipboard!
camel-spring to your project as shown in Example 18.1, “Adding the camel-spring dependency”.
Example 18.1. Adding the camel-spring dependency
Variables Copy linkLink copied to clipboard!
| Variable | Type | Description |
|---|---|---|
this | Exchange | The current exchange is the root object. |
exchange | Exchange | The current exchange. |
exchangeId | String | The current exchange's ID. |
exception | Throwable | The exchange exception (if any). |
fault | Message | The fault message (if any). |
request | Message | The exchange's In message. |
response | Message | The exchange's Out message (if any). |
properties | Map | The exchange properties. |
property(Name) | Object | The exchange property keyed by Name. |
property(Name, Type) | Type | The exchange property keyed by Name, converted to the type, Type. |
XML example Copy linkLink copied to clipboard!
Country header has the value USA, you can use the following SpEL expression:
Java example Copy linkLink copied to clipboard!
from("SourceURL")
.filter().spel("#{request.headers['Country'] == 'USA'}")
.to("TargetURL");
from("SourceURL")
.filter().spel("#{request.headers['Country'] == 'USA'}")
.to("TargetURL");
from("SourceURL")
.setBody(spel("Hello #{request.body}! What a beautiful #{request.headers['dayOrNight']}"))
.to("TargetURL");
from("SourceURL")
.setBody(spel("Hello #{request.body}! What a beautiful #{request.headers['dayOrNight']}"))
.to("TargetURL");
Chapter 19. The XPath Language Copy linkLink copied to clipboard!
Abstract
19.1. Java DSL Copy linkLink copied to clipboard!
Basic expressions Copy linkLink copied to clipboard!
xpath("Expression") to evaluate an XPath expression on the current exchange (where the XPath expression is applied to the body of the current In message). The result of the xpath() expression is an XML node (or node set, if more than one node matches).
/person/name element from the current In message body and use it to set a header named user, you could define a route like the following:
from("queue:foo")
.setHeader("user", xpath("/person/name/text()"))
.to("direct:tie");
from("queue:foo")
.setHeader("user", xpath("/person/name/text()"))
.to("direct:tie");
xpath() as an argument to setHeader(), you can use the fluent builder xpath() command—for example:
from("queue:foo")
.setHeader("user").xpath("/person/name/text()")
.to("direct:tie");
from("queue:foo")
.setHeader("user").xpath("/person/name/text()")
.to("direct:tie");
xpath(). For example, to specify explicitly that the result type is String:
xpath("/person/name/text()", String.class)
xpath("/person/name/text()", String.class)
Namespaces Copy linkLink copied to clipboard!
org.apache.camel.builder.xml.Namespaces, which enables you to define associations between namespaces and prefixes.
cust, with the namespace, http://acme.com/customer/record, and then extract the contents of the element, /cust:person/cust:name, you could define a route like the following:
xpath() expression builder by passing the Namespaces object, ns, as an additional argument. If you need to define multiple namespaces, use the Namespace.add() method, as follows:
import org.apache.camel.builder.xml.Namespaces;
...
Namespaces ns = new Namespaces("cust", "http://acme.com/customer/record");
ns.add("inv", "http://acme.com/invoice");
ns.add("xsi", "http://www.w3.org/2001/XMLSchema-instance");
import org.apache.camel.builder.xml.Namespaces;
...
Namespaces ns = new Namespaces("cust", "http://acme.com/customer/record");
ns.add("inv", "http://acme.com/invoice");
ns.add("xsi", "http://www.w3.org/2001/XMLSchema-instance");
xpath(), as follows:
xpath("/person/name/text()", String.class, ns)
xpath("/person/name/text()", String.class, ns)
Auditing namespaces Copy linkLink copied to clipboard!
INFO log level, enable the logNamespaces option in the Java DSL, as follows:
xpath("/foo:person/@id", String.class).logNamespaces()
xpath("/foo:person/@id", String.class).logNamespaces()
TRACE level logging on the org.apache.camel.builder.xml.XPathBuilder logger.
2012-01-16 13:23:45,878 [stSaxonWithFlag] INFO XPathBuilder -
Namespaces discovered in message: {xmlns:a=[http://apache.org/camel],
DEFAULT=[http://apache.org/default],
xmlns:b=[http://apache.org/camelA, http://apache.org/camelB]}
2012-01-16 13:23:45,878 [stSaxonWithFlag] INFO XPathBuilder -
Namespaces discovered in message: {xmlns:a=[http://apache.org/camel],
DEFAULT=[http://apache.org/default],
xmlns:b=[http://apache.org/camelA, http://apache.org/camelB]}
19.2. XML DSL Copy linkLink copied to clipboard!
Basic expressions Copy linkLink copied to clipboard!
xpath element. The XPath expression is applied to the body of the current In message and returns an XML node (or node set). Typically, the returned XML node is automatically converted to a string.
/person/name element from the current In message body and use it to set a header named user, you could define a route like the following:
resultType attribute to a Java type name (where you must specify the fully-qualified type name). For example, to specify explicitly that the result type is java.lang.String (you can omit the java.lang. prefix here):
<xpath resultType="String">/person/name/text()</xpath>
<xpath resultType="String">/person/name/text()</xpath>
Namespaces Copy linkLink copied to clipboard!
xmlns:Prefix="NamespaceURI".
cust, with the namespace, http://acme.com/customer/record, and then extract the contents of the element, /cust:person/cust:name, you could define a route like the following:
Auditing namespaces Copy linkLink copied to clipboard!
INFO log level, enable the logNamespaces option in the XML DSL, as follows:
<xpath logNamespaces="true" resultType="String">/foo:person/@id</xpath>
<xpath logNamespaces="true" resultType="String">/foo:person/@id</xpath>
TRACE level logging on the org.apache.camel.builder.xml.XPathBuilder logger.
2012-01-16 13:23:45,878 [stSaxonWithFlag] INFO XPathBuilder -
Namespaces discovered in message: {xmlns:a=[http://apache.org/camel],
DEFAULT=[http://apache.org/default],
xmlns:b=[http://apache.org/camelA, http://apache.org/camelB]}
2012-01-16 13:23:45,878 [stSaxonWithFlag] INFO XPathBuilder -
Namespaces discovered in message: {xmlns:a=[http://apache.org/camel],
DEFAULT=[http://apache.org/default],
xmlns:b=[http://apache.org/camelA, http://apache.org/camelB]}
19.3. XPath Injection Copy linkLink copied to clipboard!
Parameter binding annotation Copy linkLink copied to clipboard!
@XPath annotation to extract a value from the exchange and bind it to a method parameter.
credit method on an AccountService object:
from("queue:payments")
.beanRef("accountService","credit")
...
from("queue:payments")
.beanRef("accountService","credit")
...
credit method uses parameter binding annotations to extract relevant data from the message body and inject it into its parameters, as follows:
Namespaces Copy linkLink copied to clipboard!
XPath expression that appears in the @XPath annotation.
| Namespace URI | Prefix |
|---|---|
http://www.w3.org/2001/XMLSchema | xsd |
http://www.w3.org/2003/05/soap-envelope | soap |
Custom namespaces Copy linkLink copied to clipboard!
@NamespacePrefix annotation to define custom XML namespaces. Invoke the @NamespacePrefix annotation to initialize the namespaces argument of the @XPath annotation. The namespaces defined by @NamespacePrefix can then be used in the @XPath annotation's expression value.
ex, with the custom namespace, http://fusesource.com/examples, invoke the @XPath annotation as follows:
19.4. XPath Builder Copy linkLink copied to clipboard!
Overview Copy linkLink copied to clipboard!
org.apache.camel.builder.xml.XPathBuilder class enables you to evaluate XPath expressions independently of an exchange. That is, if you have an XML fragment from any source, you can use XPathBuilder to evaluate an XPath expression on the XML fragment.
Matching expressions Copy linkLink copied to clipboard!
matches() method to check whether one or more XML nodes can be found that match the given XPath expression. The basic syntax for matching an XPath expression using XPathBuilder is as follows:
boolean matches = XPathBuilder
.xpath("Expression")
.matches(CamelContext, "XMLString");
boolean matches = XPathBuilder
.xpath("Expression")
.matches(CamelContext, "XMLString");
true, because the XPath expression finds a match in the xyz attribute.
boolean matches = XPathBuilder
.xpath("/foo/bar/@xyz")
.matches(getContext(), "<foo><bar xyz='cheese'/></foo>"));
boolean matches = XPathBuilder
.xpath("/foo/bar/@xyz")
.matches(getContext(), "<foo><bar xyz='cheese'/></foo>"));
Evaluating expressions Copy linkLink copied to clipboard!
evaluate() method to return the contents of the first node that matches the given XPath expression. The basic syntax for evaluating an XPath expression using XPathBuilder is as follows:
String nodeValue = XPathBuilder
.xpath("Expression")
.evaluate(CamelContext, "XMLString");
String nodeValue = XPathBuilder
.xpath("Expression")
.evaluate(CamelContext, "XMLString");
evaluate()—for example:
19.5. Enabling Saxon Copy linkLink copied to clipboard!
Prerequisites Copy linkLink copied to clipboard!
camel-saxon artifact (either adding this dependency to your Maven POM, if you use Maven, or adding the camel-saxon-6.0.0.redhat-024.jar file to your classpath, otherwise).
Using the Saxon parser in Java DSL Copy linkLink copied to clipboard!
saxon() fluent builder method. For example, you could invoke the Saxon parser as shown in the following example:
Using the Saxon parser in XML DSL Copy linkLink copied to clipboard!
saxon attribute to true in the xpath element. For example, you could invoke the Saxon parser as shown in the following example:
<xpath saxon="true" resultType="java.lang.String">current-dateTime()</xpath>
<xpath saxon="true" resultType="java.lang.String">current-dateTime()</xpath>
Programming with Saxon Copy linkLink copied to clipboard!
// Java import javax.xml.transform.TransformerFactory; import net.sf.saxon.TransformerFactoryImpl; ... TransformerFactory saxonFactory = new net.sf.saxon.TransformerFactoryImpl();
// Java
import javax.xml.transform.TransformerFactory;
import net.sf.saxon.TransformerFactoryImpl;
...
TransformerFactory saxonFactory = new net.sf.saxon.TransformerFactoryImpl();
javax.xml.transform.TransformerFactory property in the ESBInstall/etc/system.properties file, as follows:
javax.xml.transform.TransformerFactory=net.sf.saxon.TransformerFactoryImpl
javax.xml.transform.TransformerFactory=net.sf.saxon.TransformerFactoryImpl
// Java import javax.xml.transform.TransformerFactory; ... TransformerFactory factory = TransformerFactory.newInstance();
// Java
import javax.xml.transform.TransformerFactory;
...
TransformerFactory factory = TransformerFactory.newInstance();
net.sf.saxon/saxon9he (normally installed by default). In versions of Fuse ESB prior to 7.1, it is not possible to load Saxon using the generic JAXP API.
19.6. Expressions Copy linkLink copied to clipboard!
Result type Copy linkLink copied to clipboard!
org.w3c.dom.NodeList type. You can use the type converter mechanism to convert the result to a different type, however. In the Java DSL, you can specify the result type in the second argument of the xpath() command. For example, to return the result of an XPath expression as a String:
xpath("/person/name/text()", String.class)
xpath("/person/name/text()", String.class)
resultType attribute, as follows:
<xpath resultType="java.lang.String">/person/name/text()</xpath>
<xpath resultType="java.lang.String">/person/name/text()</xpath>
Patterns in location paths Copy linkLink copied to clipboard!
/people/person- The basic location path specifies the nested location of a particular element. That is, the preceding location path would match the person element in the following XML fragment:
<people> <person>...</person> </people>
<people> <person>...</person> </people>Copy to Clipboard Copied! Toggle word wrap Toggle overflow Note that this basic pattern can match multiple nodes—for example, if there is more than onepersonelement inside thepeopleelement. /name/text()- If you just want to access the text inside by the element, append
/text()to the location path, otherwise the node includes the element's start and end tags (and these tags would be included when you convert the node to a string). /person/telephone/@isDayTime- To select the value of an attribute, AttributeName, use the syntax
@AttributeName. For example, the preceding location path returnstruewhen applied to the following XML fragment:<person> <telephone isDayTime="true">1234567890</telephone> </person>
<person> <telephone isDayTime="true">1234567890</telephone> </person>Copy to Clipboard Copied! Toggle word wrap Toggle overflow *- A wildcard that matches all elements in the specified scope. For example,
/people/person/*matches all the child elements ofperson. @*- A wildcard that matches all attributes of the matched elements. For example,
/person/name/@*matches all attributes of every matchednameelement. //- Match the location path at every nesting level. For example, the
//namepattern matches everynameelement highlighted in the following XML fragment:Copy to Clipboard Copied! Toggle word wrap Toggle overflow ..- Selects the parent of the current context node. Not normally useful in the Apache Camel XPath language, because the current context node is the document root, which has no parent.
node()- Match any kind of node.
text()- Match a text node.
comment()- Match a comment node.
processing-instruction()- Match a processing-instruction node.
Predicate filters Copy linkLink copied to clipboard!
[Predicate]. For example, you can select the Nth node from the list of matches by appending [N] to a location path. The following expression selects the first matching person element:
/people/person[1]
/people/person[1]
person element:
/people/person[last()-1]
/people/person[last()-1]
name elements, whose surname attribute is either Strachan or Davies:
/person/name[@surname="Strachan" or @surname="Davies"]
/person/name[@surname="Strachan" or @surname="Davies"]
and, or, not(), and you can compare expressions using the comparators, =, !=, >, >=, <, <= (in practice, the less-than symbol must be replaced by the < entity). You can also use XPath functions in the predicate filter.
Axes Copy linkLink copied to clipboard!
AxisType::MatchingNode. For example, you can use the child:: axis to search the children of the current context node, as follows:
/invoice/items/child::item
/invoice/items/child::item
child::item is the items element that is selected by the path, /invoice/items. The child:: axis restricts the search to the children of the context node, items, so that child::item matches the children of items that are named item. As a matter of fact, the child:: axis is the default axis, so the preceding example can be written equivalently as:
/invoice/items/item
/invoice/items/item
@ is an abbreviation of attribute::, and // is an abbreviation of descendant-or-self::. The full list of axes is as follows (for details consult the reference below):
ancestorancestor-or-selfattributechilddescendantdescendant-or-selffollowingfollowing-siblingnamespaceparentprecedingpreceding-siblingself
Functions Copy linkLink copied to clipboard!
/people/person[last()]
/people/person[last()]
person element in a sequence (in document order).
Reference Copy linkLink copied to clipboard!
19.7. Predicates Copy linkLink copied to clipboard!
Basic predicates Copy linkLink copied to clipboard!
xpath in the Java DSL or the XML DSL in a context where a predicate is expected—for example, as the argument to a filter() processor or as the argument to a when() clause.
/person/city element contains the value, London:
from("direct:tie")
.filter().xpath("/person/city = 'London'").to("file:target/messages/uk");
from("direct:tie")
.filter().xpath("/person/city = 'London'").to("file:target/messages/uk");
when() clause:
from("direct:tie")
.choice()
.when(xpath("/person/city = 'London'")).to("file:target/messages/uk")
.otherwise().to("file:target/messages/others");
from("direct:tie")
.choice()
.when(xpath("/person/city = 'London'")).to("file:target/messages/uk")
.otherwise().to("file:target/messages/others");
XPath predicate operators Copy linkLink copied to clipboard!
| Operator | Description |
|---|---|
= | Equals. |
!= | Not equal to. |
> | Greater than. |
>= | Greater than or equals. |
< | Less than. |
<= | Less than or equals. |
or | Combine two predicates with logical and. |
and | Combine two predicates with logical inclusive or. |
not() | Negate predicate argument. |
19.8. Using Variables and Functions Copy linkLink copied to clipboard!
Evaluating variables in a route Copy linkLink copied to clipboard!
$VarName or $Prefix:VarName, if the variable is accessed through an XML namespace.
$in:body and the In message's header value as $in:HeaderName. O/S environment variables can be accessed as $env:EnvVar and Java system properties can be accessed as $system:SysVar.
/person/city element and inserts it into the city header. The second route filters exchanges using the XPath expression, $in:city = 'London', where the $in:city variable is replaced by the value of the city header.
Evaluating functions in a route Copy linkLink copied to clipboard!
in:header() function and the in:body() function to access a head and the body from the underlying exchange:
from("direct:start").choice()
.when().xpath("in:header('foo') = 'bar'").to("mock:x")
.when().xpath("in:body() = '<two/>'").to("mock:y")
.otherwise().to("mock:z");
from("direct:start").choice()
.when().xpath("in:header('foo') = 'bar'").to("mock:x")
.when().xpath("in:body() = '<two/>'").to("mock:y")
.otherwise().to("mock:z");
in:HeaderName or in:body variables. The functions have a slightly different syntax however: in:header('HeaderName') instead of in:HeaderName; and in:body() instead of in:body.
Evaluating variables in XPathBuilder Copy linkLink copied to clipboard!
XPathBuilder class. In this case, you cannot use variables such as $in:body or $in:HeaderName, because there is no exchange object to evaluate against. But you can use variables that are defined inline using the variable(Name, Value) fluent builder method.
$test variable, which is defined to have the value, London:
String var = XPathBuilder.xpath("$test")
.variable("test", "London")
.evaluate(getContext(), "<name>foo</name>");
String var = XPathBuilder.xpath("$test")
.variable("test", "London")
.evaluate(getContext(), "<name>foo</name>");
$test, uses no prefix).
19.9. Variable Namespaces Copy linkLink copied to clipboard!
Table of namespaces Copy linkLink copied to clipboard!
| Namespace URI | Prefix | Description |
|---|---|---|
http://camel.apache.org/schema/spring | None | Default namespace (associated with variables that have no namespace prefix). |
http://camel.apache.org/xml/in/ | in | Used to reference header or body of the current exchange's In message. |
http://camel.apache.org/xml/out/ | out | Used to reference header or body of the current exchange's Out message. |
http://camel.apache.org/xml/functions/ | functions | Used to reference some custom functions. |
http://camel.apache.org/xml/variables/environment-variables | env | Used to reference O/S environment variables. |
http://camel.apache.org/xml/variables/system-properties | system | Used to reference Java system properties. |
http://camel.apache.org/xml/variables/exchange-property | Undefined | Used to reference exchange properties. You must define your own prefix for this namespace. |
19.10. Function Reference Copy linkLink copied to clipboard!
Table of custom functions Copy linkLink copied to clipboard!
| Function | Description |
|---|---|
in:body() | Returns the In message body. |
in:header(HeaderName) | Returns the In message header with name, HeaderName. |
out:body() | Returns the Out message body. |
out:header(HeaderName) | Returns the Out message header with name, HeaderName. |
function:properties(PropKey) | Looks up a property with the key, PropKey (see section "Property Placeholders" in "Implementing Enterprise Integration Patterns"). |
function:simple(SimpleExp) | Evaluates the specified simple expression, SimpleExp. |
Chapter 20. XQuery Copy linkLink copied to clipboard!
Overview Copy linkLink copied to clipboard!
Java syntax Copy linkLink copied to clipboard!
xquery() in several ways. For simple expressions, you can pass the XQuery expressions as a string (java.lang.String). For longer XQuery expressions, you might prefer to store the expression in a file, which you can then reference by passing a java.io.File argument or a java.net.URL argument to the overloaded xquery() method. The XQuery expression implicitly acts on the message content and returns a node set as the result. Depending on the context, the return value is interpreted either as a predicate (where an empty node set is interpreted as false) or as an expression.
Adding the Saxon module Copy linkLink copied to clipboard!
camel-saxon to your project as shown in Example 20.1, “Adding the camel-saxon dependency”.
Example 20.1. Adding the camel-saxon dependency
Static import Copy linkLink copied to clipboard!
xquery() static method in your application code, include the following import statement in your Java source files:
import static org.apache.camel.builder.saxon.XQueryBuilder.xquery;
import static org.apache.camel.builder.saxon.XQueryBuilder.xquery;
Variables Copy linkLink copied to clipboard!
| Variable | Type | Description |
|---|---|---|
exchange | Exchange | The current Exchange |
in.body | Object | The body of the IN message |
out.body | Object | The body of the OUT message |
in.headers.key | Object | The IN message header whose key is key |
out.headers.key | Object | The OUT message header whose key is key |
| key | Object | The Exchange property whose key is key |
Example Copy linkLink copied to clipboard!
Example 20.2. Route using XQuery
Legal Notice Copy linkLink copied to clipboard!
Trademark Disclaimer
Legal Notice Copy linkLink copied to clipboard!
Third Party Acknowledgements
- JLine (http://jline.sourceforge.net) jline:jline:jar:1.0License: BSD (LICENSE.txt) - Copyright (c) 2002-2006, Marc Prud'hommeaux
mwp1@cornell.eduAll rights reserved.Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:- Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
- Neither the name of JLine nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - Stax2 API (http://woodstox.codehaus.org/StAX2) org.codehaus.woodstox:stax2-api:jar:3.1.1License: The BSD License (http://www.opensource.org/licenses/bsd-license.php)Copyright (c) <YEAR>, <OWNER> All rights reserved.Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - jibx-run - JiBX runtime (http://www.jibx.org/main-reactor/jibx-run) org.jibx:jibx-run:bundle:1.2.3License: BSD (http://jibx.sourceforge.net/jibx-license.html) Copyright (c) 2003-2010, Dennis M. Sosnoski.All rights reserved.Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
- Neither the name of JiBX nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - JavaAssist (http://www.jboss.org/javassist) org.jboss.javassist:com.springsource.javassist:jar:3.9.0.GA:compileLicense: MPL (http://www.mozilla.org/MPL/MPL-1.1.html)
- HAPI-OSGI-Base Module (http://hl7api.sourceforge.net/hapi-osgi-base/) ca.uhn.hapi:hapi-osgi-base:bundle:1.2License: Mozilla Public License 1.1 (http://www.mozilla.org/MPL/MPL-1.1.txt)