You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@camel.apache.org by da...@apache.org on 2026/06/23 18:30:53 UTC
(camel) branch main updated: CAMEL-23806: Split simple-language, rest-dsl, and exception-clause docs into focused sub-pages
This is an automated email from the ASF dual-hosted git repository.
davsclaus pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git
The following commit(s) were added to refs/heads/main by this push:
new 8ac5fe03333d CAMEL-23806: Split simple-language, rest-dsl, and exception-clause docs into focused sub-pages
8ac5fe03333d is described below
commit 8ac5fe03333df65002b8836abe96f9d0d530df0d
Author: Claus Ibsen <cl...@gmail.com>
AuthorDate: Tue Jun 23 20:30:34 2026 +0200
CAMEL-23806: Split simple-language, rest-dsl, and exception-clause docs into focused sub-pages
Split the three remaining long documentation pages into focused sub-pages:
- simple-language (2,836 -> 131 lines): split into simple-functions,
simple-operators, simple-ognl, and simple-advanced sub-pages
- rest-dsl (1,741 -> 599 lines): split into rest-dsl-binding and
rest-dsl-validation sub-pages (rest-dsl-openapi already existed)
- exception-clause (1,667 -> 271 lines): split into exception-redelivery,
exception-handling-patterns, and exception-advanced sub-pages
Updated nav files and PrepareDocSymlinksMojo to include language sub-pages
in the build copy process.
Co-Authored-By: Claude <no...@anthropic.com>
Signed-off-by: Claus Ibsen <cl...@gmail.com>
---
.../modules/languages/pages/simple-advanced.adoc | 1009 ++++++++
...{simple-language.adoc => simple-functions.adoc} | 1671 +-----------
.../modules/languages/pages/simple-language.adoc | 2717 +-------------------
.../docs/modules/languages/pages/simple-ognl.adoc | 183 ++
.../modules/languages/pages/simple-operators.adoc | 371 +++
docs/components/modules/languages/nav.adoc | 8 +
.../modules/languages/pages/simple-advanced.adoc | 1 +
.../modules/languages/pages/simple-functions.adoc | 1 +
.../modules/languages/pages/simple-ognl.adoc | 1 +
.../modules/languages/pages/simple-operators.adoc | 1 +
docs/languages-nav.adoc.template | 4 +
docs/user-manual/modules/ROOT/nav.adoc | 5 +
.../modules/ROOT/pages/exception-advanced.adoc | 462 ++++
.../modules/ROOT/pages/exception-clause.adoc | 1406 +---------
.../ROOT/pages/exception-handling-patterns.adoc | 768 ++++++
.../modules/ROOT/pages/exception-redelivery.adoc | 186 ++
.../modules/ROOT/pages/rest-dsl-binding.adoc | 580 +++++
.../modules/ROOT/pages/rest-dsl-validation.adoc | 380 +++
docs/user-manual/modules/ROOT/pages/rest-dsl.adoc | 1152 +--------
.../maven/packaging/PrepareDocSymlinksMojo.java | 3 +-
20 files changed, 3980 insertions(+), 6929 deletions(-)
diff --git a/core/camel-core-languages/src/main/docs/modules/languages/pages/simple-advanced.adoc b/core/camel-core-languages/src/main/docs/modules/languages/pages/simple-advanced.adoc
new file mode 100644
index 000000000000..1d9d79c4dc83
--- /dev/null
+++ b/core/camel-core-languages/src/main/docs/modules/languages/pages/simple-advanced.adoc
@@ -0,0 +1,1009 @@
+= Simple - Advanced Features
+:tabs-sync-option:
+
+xref:simple-language.adoc[Back to Simple Language]
+
+== Init Blocks
+
+Starting from *Camel 4.18* you can in the top of your Simple expressions declare an _initialization_ block that are used
+to define a set of local variables that are pre-computed, and can be used in the following Simple expression. This allows
+to reuse variables, and also avoid making the simple expression complicated when having inlined functions, and in general
+make the simple expression easier to maintain and understand.
+
+IMPORTANT: Init Blocks is not supported with xref:csimple-language.adoc[CSimple] language.
+
+NOTE: The init block declaration `$init{ ... }init$` may be changed in the future.
+
+The _init block_ is declared as follows:
+
+[source,text]
+----
+$init{
+ // init block
+ // goes here
+ // ...
+}init$
+// here is the regular simple expression
+----
+
+Notice how the block uses the `$init{` ... `}init$` markers to indicate the start and end of the block.
+
+Inside the init block, then you can assign local variables in the syntax `$key := <statement>;` where you can then use simple language to compute
+the value of the variable.
+
+IMPORTANT: Each statement must end with semicolon and new-line (`;\n`). You can only have 1 statement per line.
+This makes the init block more similar to Java programming language,
+and it was also necessary to make this work for the internal simple parser used by Camel.
+
+Here are a couple of examples:
+
+[source,text]
+----
+$init{
+ $cheese := 'Hello ${body}';
+ $minAge := 18;
+ $foo := ${uppercase('Hello ${body}')};
+ $bar := ${header.code > 999 ? 'Gold' : 'Silver'};
+}init$
+----
+
+You can have Java style code comments in the init block using `// comment here` as follows:
+
+[source,text]
+----
+$init{
+ // minimum age to drive
+ $minAge := 18;
+
+ // say hello to my friend
+ $foo := ${uppercase('Hello ${body}')};
+
+ // either gold or silver
+ $bar := ${header.code > 999 ? 'Gold' : 'Silver'};
+}init$
+----
+
+The local variables can then easily be used in the Simple language either using the `${variable.foo}` syntax
+or the shorthand syntax `$foo`.
+
+For example as below where we do a basic JSON mapping:
+
+[source,text]
+----
+$init{
+ $greeting := ${uppercase('Hello ${body}')};
+ $level := ${header.code > 999 ? 'Gold' : 'Silver'};
+}init$
+{
+ "message": "$greeting",
+ "status": "$level"
+}
+----
+
+The assigned variables from the _init block_ are stored as xref:manual::variables.adoc[Variables] on the `Exchange` which
+allows to use the variables later in the Camel routes.
+
+For example:
+
+[tabs]
+====
+Java::
++
+[source,java]
+----
+from("direct:welcome")
+ .transform().simple(
+ """
+ $init{
+ $greeting := ${uppercase('Hello ${body}')};
+ $level := ${header.code > 999 ? 'Gold' : 'Silver'};
+ }init$
+ {
+ "message": "$greeting",
+ "status": "$level"
+ }
+ """)
+ .to("kafka:welcome")
+ .log("Sending welcome email to customer with status ${variable.level}");
+----
+
+XML::
++
+[source,xml]
+----
+<route>
+ <from uri="direct:welcome"/>
+ <transform>
+ <simple>
+ $init{
+ $greeting := ${uppercase('Hello ${body}')};
+ $level := ${header.code > 999 ? 'Gold' : 'Silver'};
+ }init$
+ {
+ "message": "$greeting",
+ "status": "$level"
+ }
+ </simple>
+ </transform>
+ <to uri="kafka:welcome"/>
+ <log message="Sending welcome email to customer with status ${variable.level}"/>
+</route>
+----
+
+YAML::
++
+[source,yaml]
+----
+- from:
+ uri: direct:welcome
+ steps:
+ - transform:
+ simple:
+ expression: |-
+ $init{
+ $greeting := ${uppercase('Hello ${body}')};
+ $level := ${header.code > 999 ? 'Gold' : 'Silver'};
+ }init$
+ {
+ "message": "$greeting",
+ "status": "$level"
+ }
+ - to:
+ uri: kafka:welcome
+ - log:
+ message: "Sending welcome email to customer with status ${variable.level}"
+----
+====
+
+Notice how we can refer to the variable (`$level`) in the log statement using the standard `${variable.xxx}` syntax.
+
+TIP: Instead of inlining the simple script in the route, you can externalize this to a source file such as `mymapping.txt`
+and then refer to the file such as `resource:classpath:mymapping.txt` where the file is located in the root classpath (can also be located in sub packages).
+
+=== Init Blocks with custom functions
+
+You can also declare custom functions using
+
+Inside the init block, it is a lso possible to define custom functions in the syntax `$nane ~:= <statement>;` where you can then use simple language to declare
+the structure of the function. Then you can later use these custom functions in your simple language expressions.
+
+For example to create a function that can cleanup a `String` value:
+
+[source,text]
+----
+$init{
+ $cleanUp ~:= ${trim()} ~> ${normalizeWhitespace()} ~> ${uppercase()};
+}init$
+----
+
+The function will by default use the message body as the input, such that the following:
+
+[source,java]
+----
+simple("Incoming message: $cleanUp()");
+----
+
+Would then call the _clean_ function with the message body as the input, which will then be used for trim, normalize and upper-casing.
+
+A custom function can also use a **single** parameter, however then the syntax must use `${name(...)}` style, such as:
+
+[source,java]
+----
+simple("Incoming message: ${cleanUp(' Please clean this text for me ')}");
+----
+
+Here the parameter is a fixed `String` but you can also pass in other type of value such as a number, boolean, or even a nested function.
+
+==== Calling custom functions from custom functions
+
+It is also possible to reuse custom functions from other functions using `${function(name)}`, such shown:
+
+[source,text]
+----
+$init{
+ $cleanUp ~:= ${trim()} ~> ${normalizeWhitespace()} ~> ${uppercase()};
+ $count ~:= ${function(cleanUp)} ~> ${split(' ')} ~> ${size()};
+}init$
+----
+
+Here the `$count` is declared as a function which calls the cleanUp function and then counts the words via split and size functions.
+
+Instead of using `${function(name)}` you can also same syntax as the built-in Simple functions, as follows:
+
+[source,text]
+----
+$init{
+ $cleanUp ~:= ${trim()} ~> ${normalizeWhitespace()} ~> ${uppercase()};
+ $count ~:= ${cleanUp()} ~> ${split(' ')} ~> ${size()};
+}init$
+----
+
+Notice how `${cleanUp()}` despite being a custom function is using the same syntax as all the built-in functions that are being used, for example:
+ `${trim()}`.
+
+
+== EIP Examples
+
+Below we filter based on a header value:
+
+[tabs]
+====
+Java::
++
+[source,java]
+----
+from("seda:orders")
+ .filter().simple("${header.foo}")
+ .to("seda:fooOrders");
+----
+
+XML::
++
+[source,xml]
+----
+<route>
+ <from uri="seda:orders"/>
+ <filter>
+ <simple>${header.foo}</simple>
+ <to uri="seda:fooOrders"/>
+ </filter>
+</route>
+----
+
+YAML::
++
+[source,yaml]
+----
+- route:
+ from:
+ uri: seda:orders
+ steps:
+ - filter:
+ simple: "${header.foo}"
+ steps:
+ - to:
+ uri: seda:fooOrders
+----
+====
+
+The Simple language can be used for the predicate test above in the
+Message Filter pattern, where we test if the
+in message has a `foo` header (a header with the key `foo` exists). If
+the expression evaluates to `*true*`, then the message is routed to the
+`seda:fooOrders` endpoint, otherwise the message is dropped.
+
+You can also use the simple language for simple text concatenations such as:
+
+[tabs]
+====
+Java::
++
+[source,java]
+----
+from("direct:hello")
+ .transform().simple("Hello ${header.user} how are you?")
+ .to("mock:reply");
+----
+
+XML::
++
+[source,xml]
+----
+<route>
+ <from uri="direct:hello"/>
+ <transform>
+ <simple>Hello ${header.user} how are you?</simple>
+ </transform>
+ <to uri="mock:reply"/>
+</route>
+----
+
+YAML::
++
+[source,yaml]
+----
+- route:
+ from:
+ uri: direct:hello
+ steps:
+ - transform:
+ simple: "Hello ${header.user} how are you?"
+ - to:
+ uri: mock:reply
+----
+====
+
+Notice that we must use `${ }` placeholders in the expression now to
+allow Camel to parse it correctly.
+
+And this sample uses the date command to output current date.
+
+[tabs]
+====
+Java::
++
+[source,java]
+----
+from("direct:hello")
+ .transform().simple("The today is ${date:now:yyyyMMdd} and it is a great day.")
+ .to("mock:reply");
+----
+
+XML::
++
+[source,xml]
+----
+<route>
+ <from uri="direct:hello"/>
+ <transform>
+ <simple>The today is ${date:now:yyyyMMdd} and it is a great day.</simple>
+ </transform>
+ <to uri="mock:reply"/>
+</route>
+----
+
+YAML::
++
+[source,yaml]
+----
+- route:
+ from:
+ uri: direct:hello
+ steps:
+ - transform:
+ simple: "The today is ${date:now:yyyyMMdd} and it is a great day."
+ - to:
+ uri: mock:reply
+----
+====
+
+And in the sample below, we invoke the bean language to invoke a method
+on a bean to be included in the returned string:
+
+[tabs]
+====
+Java::
++
+[source,java]
+----
+from("direct:order")
+ .transform().simple("OrderId: ${bean:orderIdGenerator}")
+ .to("mock:reply");
+----
+
+XML::
++
+[source,xml]
+----
+<route>
+ <from uri="direct:order"/>
+ <transform>
+ <simple>OrderId: ${bean:orderIdGenerator}</simple>
+ </transform>
+ <to uri="mock:reply"/>
+</route>
+----
+
+YAML::
++
+[source,yaml]
+----
+- route:
+ from:
+ uri: direct:order
+ steps:
+ - transform:
+ simple: "OrderId: ${bean:orderIdGenerator}"
+ - to:
+ uri: mock:reply
+----
+====
+
+Where `orderIdGenerator` is the id of the bean registered in the
+Registry. If using Spring, then it is the Spring bean
+id.
+
+If we want to declare which method to invoke on the order id generator
+bean we must prepend `.method name` such as below where we invoke the
+`generateId` method.
+
+[tabs]
+====
+Java::
++
+[source,java]
+----
+from("direct:order")
+ .transform().simple("OrderId: ${bean:orderIdGenerator.generateId}")
+ .to("mock:reply");
+----
+
+XML::
++
+[source,xml]
+----
+<route>
+ <from uri="direct:order"/>
+ <transform>
+ <simple>OrderId: ${bean:orderIdGenerator.generateId}</simple>
+ </transform>
+ <to uri="mock:reply"/>
+</route>
+----
+
+YAML::
++
+[source,yaml]
+----
+- route:
+ from:
+ uri: direct:order
+ steps:
+ - transform:
+ simple: "OrderId: ${bean:orderIdGenerator.generateId}"
+ - to:
+ uri: mock:reply
+----
+====
+
+We can use the `?method=methodname` option that we are familiar with the
+xref:components::bean-component.adoc[Bean] component itself:
+
+[tabs]
+====
+Java::
++
+[source,java]
+----
+from("direct:order")
+ .transform().simple("OrderId: ${bean:orderIdGenerator?method=generateId}")
+ .to("mock:reply");
+----
+
+XML::
++
+[source,xml]
+----
+<route>
+ <from uri="direct:order"/>
+ <transform>
+ <simple>OrderId: ${bean:orderIdGenerator?method=generateId}</simple>
+ </transform>
+ <to uri="mock:reply"/>
+</route>
+----
+
+YAML::
++
+[source,yaml]
+----
+- route:
+ from:
+ uri: direct:order
+ steps:
+ - transform:
+ simple: "OrderId: ${bean:orderIdGenerator?method=generateId}"
+ - to:
+ uri: mock:reply
+----
+====
+
+You can also convert the body to a given
+type, for example, to ensure that it is a String you can do:
+
+[source,xml]
+----
+<transform>
+ <simple>Hello ${bodyAs(String)} how are you?</simple>
+</transform>
+----
+
+There are a few types which have a shorthand notation, so we can use
+`String` instead of `java.lang.String`. These are:
+`byte[], String, Integer, Long`. All other types must use their FQN
+name, e.g. `org.w3c.dom.Document`.
+
+It is also possible to look up a value from a header `Map`:
+
+[source,xml]
+----
+<transform>
+ <simple>The gold value is ${header.type[gold]}</simple>
+</transform>
+----
+
+In the code above we look up the header with name `type` and regard it as
+a `java.util.Map` and we then look up with the key `gold` and return the
+value. If the header is not convertible to Map, an exception is thrown. If the
+header with name `type` does not exist `null` is returned.
+
+You can nest functions, such as shown below:
+
+[source,xml]
+----
+<setHeader name="myHeader">
+ <simple>${properties:${header.someKey}}</simple>
+</setHeader>
+----
+
+== Using Substring Function
+
+You can use the `substring` function to more easily clip the message body.
+For example if the message body contains the following 10 letters `ABCDEFGHIJ` then:
+
+[source,xml]
+----
+<setBody>
+ <simple>${substring(3)}</simple>
+</setBody>
+----
+
+Then the message body after the substring will be `DEFGHIJ`.
+If you want to clip from the end instead, then use negative values such as `substring(-3)`.
+
+You can also clip from both ends at the same time such as `substring(1,-1)` that will clip the first and last character in the String.
+
+If the number is higher than the length of the message body, then an empty string is returned, for example `substring(99)`.
+
+Instead of the message body then a simple expression can be nested as input, for example, using a variable, as shown below:
+
+[source,xml]
+----
+<setBody>
+ <simple>${substring(1,-1,${variable.foo})}</simple>
+</setBody>
+----
+
+[#_replacing_double_and_single_quotes]
+== Replacing double and single quotes
+
+You can use the `replace` function to more easily replace all single or double quotes in the message body,
+using the XML escape syntax. This avoids to fiddle with enclosing a double quote or single quotes with outer quotes,
+that can get confusing to be correct as you may need to escape the quotes as well. So instead you can use the XML escape
+syntax where double quote is `\"` and single quote is `\'` (yeah that is the name).
+
+For example, to replace all double quotes with single quotes:
+
+[tabs]
+====
+Java::
++
+[source,java]
+----
+from("direct:order")
+ .transform().simple("${replace(" , ')}")
+ .to("mock:reply");
+----
+
+XML::
++
+[source,xml]
+----
+<route>
+ <from uri="direct:order"/>
+ <transform>
+ <simple>${replace(&quot; , &apos;)}</simple>
+ </transform>
+ <to uri="mock:reply"/>
+</route>
+----
+
+YAML::
++
+[source,yaml]
+----
+- route:
+ from:
+ uri: direct:order
+ steps:
+ - transform:
+ simple: "${replace(" , ')}"
+ - to:
+ uri: mock:reply
+----
+====
+
+And to replace all single quotes with double quotes:
+
+[source,xml]
+----
+<setBody>
+ <simple>${replace(' , ")}</simple>
+</setBody>
+----
+
+Or to remove all double quotes:
+
+[source,xml]
+----
+<setBody>
+ <simple>${replace(" , ∅)}</simple>
+</setBody>
+----
+
+== Setting the result type
+
+You can now provide a result type to the xref:simple-language.adoc[Simple]
+expression, which means the result of the evaluation will be converted
+to the desired type. This is most usable to define types such as
+booleans, integers, etc.
+
+For example, to set a header as a boolean type, you can do:
+
+._Java-only: setting result type on a simple expression_
+[source,java]
+----
+.setHeader("cool", simple("true", Boolean.class))
+----
+
+And in XML DSL
+
+[source,xml]
+----
+<setHeader name="cool">
+ <!-- use resultType to indicate that the type should be a java.lang.Boolean -->
+ <simple resultType="java.lang.Boolean">true</simple>
+</setHeader>
+----
+
+== Using new lines or tabs in XML DSLs
+
+It is easier to specify new lines or tabs in
+XML DSLs as you can escape the value now
+
+[source,xml]
+----
+<transform>
+ <simple>The following text\nis on a new line</simple>
+</transform>
+----
+
+== Leading and trailing whitespace handling
+
+The trim attribute of the expression can be
+used to control whether the leading and trailing whitespace characters
+are removed or preserved. The default value is true, which removes the
+whitespace characters.
+
+[source,xml]
+----
+<setBody>
+ <simple trim="false">You get some trailing whitespace characters. </simple>
+</setBody>
+----
+
+== Loading script from external resource
+
+You can externalize the script and have Camel load it from a resource
+such as `"classpath:"`, `"file:"`, or `"http:"`.
+This is done using the following syntax: `"resource:scheme:location"`,
+e.g., to refer to a file on the classpath you can do:
+
+._Java-only: loading a simple script from an external resource_
+[source,java]
+----
+.setHeader("myHeader").simple("resource:classpath:mysimple.txt")
+----
+
+== Pretty XML or JSON
+
+From *Camel 4.18* onwards then the Simple language can _pretty format_ the output.
+
+You turn this on via the `pretty` option set to `true`:
+
+[tabs]
+====
+Java::
++
+[source,java]
+----
+from("direct:json")
+ .setBody().simple("{ \"name\": \"Jack\", \"age\": 44 }", true)
+ .to("mock:result");
+----
+
+XML::
++
+[source,xml]
+----
+<route>
+ <from uri="direct:json"/>
+ <setBody>
+ <simple pretty="true">{ "name": "Jack", "age": 44 }</simple>
+ </setBody>
+ <to uri="mock:result"/>
+</route>
+----
+
+YAML::
++
+[source,yaml]
+----
+- route:
+ from:
+ uri: direct:json
+ steps:
+ - setBody:
+ simple:
+ expression: "{ \"name\": \"Jack\", \"age\": 44 }"
+ pretty: true
+ - to:
+ uri: mock:result
+----
+====
+
+This works with XML, JSON and text content:
+
+._Java-only: pretty formatting with different content types_
+[source,java]
+----
+from("direct:xml")
+ .setBody().simple("<person><name>Jack</name></person>", true)
+ .to("mock:result");
+
+from("direct:text")
+ .setBody().simple("Hello ${body}", true)
+ .to("mock:result");
+----
+
+== Adding custom functions to Simple language
+
+You can add custom functions to the Simple language by adding to the `org.apache.camel.spi.SimpleFunctionRegistry`.
+
+A custom function should either be an `Expression` or a `org.apache.camel.spi.SimpleFunction` implementation.
+
+You may want to use `Expression` when you build custom functions from the built-in functions in Camel.
+This can be done programmatically such as:
+
+._Java-only: registering a custom function with SimpleFunctionRegistry_
+[source,java]
+----
+SimpleFunctionRegistry reg = PluginHelper.getSimpleFunctionRegistry(getCamelContext());
+
+reg.addFunction("foo", new ExpressionAdapter() {
+ @Override
+ public Object evaluate(Exchange exchange) {
+ return "I was here " + exchange.getMessage().getBody();
+ }
+});
+----
+
+Here we add a custom function named `foo` which is implemented as a `org.apache.camel.Expression` which conveniently
+can be done by using the `org.apache.camel.support.ExpressionAdapter` class as above.
+
+The foo function can now be used in simple such as:
+
+[tabs]
+====
+Java::
++
+[source,java]
+----
+from("direct:start")
+ .setBody(simple("Hello ${foo}"))
+ .to("mock:result");
+----
+
+XML::
++
+[source,xml]
+----
+<route>
+ <from uri="direct:start"/>
+ <setBody>
+ <simple>Hello ${foo}</simple>
+ </setBody>
+ <to uri="mock:result"/>
+</route>
+----
+
+YAML::
++
+[source,yaml]
+----
+- route:
+ from:
+ uri: direct:start
+ steps:
+ - setBody:
+ simple: "Hello ${foo}"
+ - to:
+ uri: mock:result
+----
+====
+
+Notice how the foo function is used just like it was a built-in function using `$\{foo}` syntax.
+
+Since a custom function is just an `Expression` then it's possible to build custom functions from
+all the Camel languages such as Groovy, JSonPath and even Simple as well.
+
+._Java-only: building a custom function from Simple expressions_
+[source,java]
+----
+var bar = context.resolveLanguage("simple").createExpression("${trim()} ~> ${normalizeWhitespace()} ~> ${capitalize()} ~> ${quote()}");
+reg.addFunction("bar", bar);
+----
+
+The `bar` function is build using simple functions using the `~>` chain operators to perform a sequence of functions on the payload.
+
+Custom functions will by default use the message body as the payload. But they also support a single parameter as the input,
+which allows to provide the input as fixed value such as a string literal or to refer to an existing header or variable.
+
+For example the foo function uses variable with name `msg` as the input:
+
+[tabs]
+====
+Java::
++
+[source,java]
+----
+from("direct:start")
+ .setVariable("msg", constant("Moon"))
+ .setBody(simple("Bye ${foo(${variable.msg})}"))
+ .to("mock:result");
+----
+
+XML::
++
+[source,xml]
+----
+<route>
+ <from uri="direct:start"/>
+ <setVariable name="msg">
+ <constant>Moon</constant>
+ </setVariable>
+ <setBody>
+ <simple>Bye ${foo(${variable.msg})}</simple>
+ </setBody>
+ <to uri="mock:result"/>
+</route>
+----
+
+YAML::
++
+[source,yaml]
+----
+- route:
+ from:
+ uri: direct:start
+ steps:
+ - setVariable:
+ name: msg
+ constant: "Moon"
+ - setBody:
+ simple: "Bye ${foo(${variable.msg})}"
+ - to:
+ uri: mock:result
+----
+====
+
+And instead of nesting the variable inside the foo function, we can also use the `~>` chain operator:
+
+[tabs]
+====
+Java::
++
+[source,java]
+----
+from("direct:start")
+ .setVariable("msg", constant("Moon"))
+ .setBody(simple("Bye ${variable.msg} ~> ${foo}"))
+ .to("mock:result");
+----
+
+XML::
++
+[source,xml]
+----
+<route>
+ <from uri="direct:start"/>
+ <setVariable name="msg">
+ <constant>Moon</constant>
+ </setVariable>
+ <setBody>
+ <simple>Bye ${variable.msg} ~> ${foo}</simple>
+ </setBody>
+ <to uri="mock:result"/>
+</route>
+----
+
+YAML::
++
+[source,yaml]
+----
+- route:
+ from:
+ uri: direct:start
+ steps:
+ - setVariable:
+ name: msg
+ constant: "Moon"
+ - setBody:
+ simple: "Bye ${variable.msg} ~> ${foo}"
+ - to:
+ uri: mock:result
+----
+====
+
+You can also build custom functions as a Java class as below:
+
+._Java-only: implementing SimpleFunction interface_
+[source,java]
+----
+public class FooSimpleFunction implements SimpleFunction {
+
+ @Override
+ public String getName() {
+ return "foo";
+ }
+
+ @Override
+ public Object apply(Exchange exchange, Object input) throws Exception {
+ return "I was here " + input;
+ }
+}
+----
+
+This gives you the full power to implement the function logic in standard Java.
+
+This function can be added programmatically:
+
+._Java-only: adding a SimpleFunction to the registry_
+[source,java]
+----
+SimpleFunctionRegistry reg = PluginHelper.getSimpleFunctionRegistry(getCamelContext());
+
+reg.addFunction(new FooSimpleFunction());
+----
+
+TIP: The custom function can then be made discoverable by Camel by dependency injection.
+If you use standalone Camel you can add `@BindToRegistry("foo-function")` to the class.
+For Spring Boot use `@Component` or `@Service` and Quarkus you can for example use `@ApplicationScoped`.
+
+
+== JavaScript Validator
+
+The `camel-catalog` JAR includes a self-contained JavaScript validator for the Simple language.
+It can syntax-check expressions and predicates in any browser or Node.js environment — no Java backend required.
+
+The files are located in the JAR under:
+
+----
+org/apache/camel/catalog/simple/camel-simple-validator.js
+org/apache/camel/catalog/simple/camel-simple-validator.html
+----
+
+The `.js` file is auto-generated from `simple.json` during the Maven build, so its list of functions and operators
+always matches the current Camel version.
+
+=== API
+
+The validator exposes these functions:
+
+* `validate(input, mode)` — validate a Simple expression or predicate.
+ `mode` is `'expression'` (default) or `'predicate'`.
+ Returns `{ valid: boolean, diagnostics: [...] }`.
+* `complete(input, pos)` — return completion suggestions at the given cursor position.
+* `getFunctions()` — return the list of known Simple function names.
+* `getOperators()` — return the list of known Simple operators with their kind and description.
+
+=== Usage in Node.js
+
+[source,javascript]
+----
+const { validate, complete } = require('./camel-simple-validator.js');
+
+const result = validate("${body} == 'hello'", 'predicate');
+console.log(result.valid); // true
+console.log(result.diagnostics); // []
+
+const bad = validate("${bdy}", 'expression');
+console.log(bad.valid); // false
+console.log(bad.diagnostics[0].message); // "Unknown function 'bdy', did you mean 'body'?"
+----
+
+=== Usage in a browser
+
+Extract `camel-simple-validator.html` from the JAR and open it in a browser.
+It provides an interactive form where you can type Simple expressions and validate them with instant feedback.
+
diff --git a/core/camel-core-languages/src/main/docs/modules/languages/pages/simple-language.adoc b/core/camel-core-languages/src/main/docs/modules/languages/pages/simple-functions.adoc
similarity index 61%
copy from core/camel-core-languages/src/main/docs/modules/languages/pages/simple-language.adoc
copy to core/camel-core-languages/src/main/docs/modules/languages/pages/simple-functions.adoc
index 300a86f57d54..ae8ba44207ce 100644
--- a/core/camel-core-languages/src/main/docs/modules/languages/pages/simple-language.adoc
+++ b/core/camel-core-languages/src/main/docs/modules/languages/pages/simple-functions.adoc
@@ -1,121 +1,7 @@
-= Simple Language
-:doctitle: Simple
-:shortname: simple
-:artifactid: camel-core-languages
-:description: Evaluates a Camel simple expression.
-:since: 1.1
-:supportlevel: Stable
+= Simple - Built-in Functions
:tabs-sync-option:
-*Since Camel {since}*
-
-The Simple Expression Language was a really simple language when it was
-created, but has since grown more powerful. It is primarily intended for
-being a very small and Camel specific scripting language used anywhere in Camel
-such as with xref:components:eips:enterprise-integration-patterns.adoc[EIPs] and
-xref:manual::routes.adoc[Route].
-
-The simple language is designed with intent to cover almost all the common use cases
-when little need for scripting in your Camel routes.
-
-However, for much more complex use cases, then a more powerful language is recommended such as: xref:groovy-language.adoc[Groovy].
-
-The simple language uses `$\{body}` placeholders for dynamic expressions and functions.
-
-[TIP]
-====
-*Alternative syntax*
-
-You can also use the alternative syntax which
-uses `$simple{ }` as placeholders. This can be used in situations to avoid clashes when using, for example,
-Spring property placeholder together with Camel.
-====
-
-[NOTE]
-====
-See also the xref:csimple-language.adoc[CSimple] language which is *pre compiled*.
-====
-
-== A quick Simple Language example
-
-You often use Simple together with xref:components:eips:enterprise-integration-patterns.adoc[EIPs] such as xref:eips:choice-eip.adoc[Content-Based Router] EIP.
-
-In the example below we want to route the message depending on whether a message header with key `foo` is equal to different values:
-
-[tabs]
-====
-Java::
-+
-[source,java]
-----
-from("direct:a")
- .choice()
- .when(simple("${header.foo} == 'bar'"))
- .to("direct:b")
- .when(simple("${header.foo} == 'cheese'"))
- .to("direct:c")
- .otherwise()
- .to("direct:d");
-----
-
-XML::
-+
-[source,xml]
-----
-<route>
- <from uri="direct:a"/>
- <choice>
- <when>
- <simple>${header.foo} == 'bar'</simple>
- <to uri="direct:b"/>
- </when>
- <when>
- <simple>${header.foo} == 'cheese'</simple>
- <to uri="direct:c"/>
- </when>
- <otherwise>
- <to uri="direct:d"/>
- </otherwise>
- </choice>
-</route>
-----
-
-YAML::
-+
-[source,yaml]
-----
-- from:
- uri: direct:a
- steps:
- - choice:
- when:
- - expression:
- simple:
- expression: "${header.foo} == 'bar'"
- steps:
- - to:
- uri: direct:b
- - expression:
- simple:
- expression: "${header.foo} == 'cheese'"
- steps:
- - to:
- uri: direct:c
- otherwise:
- steps:
- - to:
- uri: direct:d
-----
-====
-
-
-== Simple Language options
-
-The Simple Language can be configured globally. However, its seldom needed.
-
-// language options: START
-include::partial$language-options.adoc[]
-// language options: END
+xref:simple-language.adoc[Back to Simple Language]
== Built-in Simple Functions
@@ -1281,1556 +1167,3 @@ The following special symbols can be used when escaped with `\` as below:
For example to use a new-line character in the split function `${split(\\n)}`.
-
-== Built-in Operators
-
-The simple language has limited support for operators that are used in predicates to evaluate whether a condition is either _true_ or _false_.
-
-Camel operators require the left value must be enclosed in `${ }`.
-The syntax is:
-
-[source,text]
-----
-${leftValue} OP rightValue
-----
-
-Where the `rightValue` can be a string literal enclosed in `' '`,
-`null`, a constant value or another expression enclosed in `${ }`.
-
-IMPORTANT: There *must* be spaces around the operator.
-
-Camel will automatically type convert the rightValue type to the
-leftValue type, so it is able to e.g., convert a string into a numeric, so
-you can use `>` comparison for numeric values.
-
-=== Comparison Operators
-
-The following comparison operators are supported:
-
-[width="100%",cols="50%,50%",options="header",]
-|====
-|Operator |Description
-|`==` | equals
-|`=~` | equals ignore case (will ignore case when comparing String values)
-|`>` | greater than
-|`>=` | greater than or equals
-|`<` | less than
-|`+<=+` | less than or equals
-|`!=` | not equals
-|`!=~` | not equals ignore case (will ignore case when comparing String values)
-|`~~` | For testing if contains by ignoring case sensitivity in a string-based value
-|`!~~` | For testing if it does not contain by ignoring case sensitivity in a string-based value
-|`contains` | For testing if contains in a string-based value
-|`!contains` | For testing if it does not contain in a string-based value
-|`endsWith` | For testing if the left-hand side string ends with the right-hand string.
-|`!endsWith` | For testing if the left-hand side string does not end with the right-hand string.
-|`in` | For matching if in a set of values, each element must be separated by comma. If you want to include an empty value, then it must be defined using double comma, e.g. `",,bronze,silver,gold"`, which is a set of four values with an empty value and then the three medals.
-|`!in` | For matching if not in a set of values, each element must be separated by comma. If you want to include an empty value, then it must be defined using double comma, e.g. `",,bronze,silver,gold"`, which is a set of four values with an empty value and then the three medals.
-|`is` | For matching if the left-hand side type is an instance of the value.
-|`!is` | For matching if the left-hand side type is not an instance of the value.
-|`range` | For matching if the left-hand side is within a range of values defined as numbers: `from..to`.
-|`!range` | For matching if the left-hand side is not within a range of values defined as numbers: `from..to`.
-|`regex` | For matching against a given regular expression pattern defined as a String value
-|`!regex` | For not matching against a given regular expression pattern defined as a String value
-|`startsWith` | For testing if the left-hand side string starts with the right-hand string.
-|`!startsWith` | For testing if the left-hand side string does not start with the right-hand string.
-|====
-
-=== Numeric Operators
-
-The following numeric operators can be used:
-
-[width="100%",cols="50%,50%",options="header",]
-|====
-|Operator |Description
-|`++` | To increment a number by one. The left-hand side must be a function, otherwise parsed as literal.
-|`--` | To decrement a number by one. The left-hand side must be a function, otherwise parsed as literal.
-|====
-
-These operators are unary and requires to be attached directly next to a function:
-
-[source,text]
-----
-${function}OP
-----
-
-For example to increment the result of the function:
-
-[source,java]
-----
-simple("${header.myNumber}++ > 10");
-----
-
-And the same for decrement:
-
-[source,java]
-----
-simple("${header.myNumber}-- < 10");
-----
-
-
-=== Other Operators
-
-The following other operators can be used:
-
-[width="100%",cols="50%,50%",options="header",]
-|====
-|Operator |Description
-|`? :` | The ternary operator evaluates a condition and returns a value based on the result. If the condition is true, the first value (after `?`) is returned; otherwise, the second value (after `:`) is returned. There must be spaces around both `?` and `:` operators. This is similar to the ternary operator in Java.
-|`?:` | The elvis operator returns the left-hand side if it has an effective Boolean value of true, otherwise it returns the right-hand side. This is useful for providing fallback values when an expression may evaluate to a value with an effective Boolean value of false (such as `null`, `false`, `0`, empty/blank string).
-|`~>` | The chain operator is used in the situations where multiple nested functions need to be applied to a value, while making it easy to read. The value on the left-hand-side is evaluated, and set as the new message body before evaluating the right-hand-side function. This concept is similar to the xref:eips:pipeline-eip.adoc[Pipeline EIP].
-|`?~>` | The null-safe chain operator, where the chain will not continue when a function returned `null`.
-|====
-
-==== Ternary Operator
-
-The syntax for the ternary operator is:
-
-[source,text]
-----
-${leftValue} OP rightValue ? trueValue : falseValue
-----
-
-For example the following ternary operator will return `positive` if header `foo` is greater than 0, otherwise `negative`:
-
-[source,java]
-----
-simple("${header.foo > 0 ? 'positive' : 'negative'}");
-----
-
-Ternary operators can also be nested to handle multiple conditions:
-
-[source,java]
-----
-simple("${header.score >= 90 ? 'A' : ${header.score >= 80 ? 'B' : 'C'}}");
-----
-
-==== Elvis Operator
-
-For example the following elvis operator will return the username header unless its null or empty, which
-then the default value of `Guest` is returned.
-
-[source,java]
-----
-simple("${header.username} ?: 'Guest'");
-----
-
-==== Chain Operator
-
-The syntax for the chain operator is:
-
-[source,text]
-----
-${leftValue} ~> ${rightValue}
-----
-
-And there can be as many chains:
-
-[source,text]
-----
-${leftValue} ~> ${midValue} ~> ${midValue} ~> ${rightValue}
-----
-
-For example if the message body contains `Hello World` then the follow would return `WORLD`:
-
-[source,java]
-----
-simple("${substringAfter('Hello')} ~> ${trim()} ~> ${uppercase()}");
-----
-
-The _null safe_ variant (`?~>`) can be used to avoid `NullPointerException` if it's accepted to not continue the chain when any function returned `null`:
-
-However, many of the simple functions have NPE protection built-in, so this variant is only needed in special situations.
-
-==== Using $param as input parameter value
-
-IMPORTANT: The chain operator will by default pass results via the message body. This usually works well with most functions.
-However, when you need to be in full control then use `$param` as the magic parameter which represents the passed value from the previous function in the chain.
-
-Suppose the message body contains `" Hello World from the Camel "` then the following chain works out of the box:
-
-[source,java]
-----
-simple("${trim()} ~> ${replace('Hello','Hi')} ~> ${split(' ')} ~> ${size()}");
-----
-
-And here is the same example where we explicit use `$param` in the parameters where we need the input to be:
-
-[source,java]
-----
-simple("${trim()} ~> ${replace('Hello','Hi',$param)} ~> ${split($param,' ')} ~> ${size($param)}");
-----
-
-
-=== Boolean Operators
-
-And the following boolean operators can be used to group expressions:
-
-[width="100%",cols="50%,50%",options="header",]
-|====
-|Operator |Description
-|`&&` | The `and` operator is used to group two expressions if both operands evaluates to `true`.
-|`\|\|` | The `or` operator is used to group two expressions if any operand evaluates to `true`.
-|====
-
-The syntax for AND is:
-
-[source,text]
-----
-${leftValue} OP rightValue && ${leftValue} OP rightValue
-----
-
-And the syntax for OR is:
-
-[source,text]
-----
-${leftValue} OP rightValue || ${leftValue} OP rightValue
-----
-
-Some examples:
-
-[source,java]
-----
-// exact equals match
-simple("${header.foo} == 'foo'")
-
-// ignore case when comparing, so if the header has value FOO, this will match
-simple("${header.foo} =~ 'foo'")
-
-// here Camel will type convert '100' into the type of header.bar and if it is an Integer '100' will also be converter to an Integer
-simple("${header.bar} == '100'")
-
-simple("${header.bar} == 100")
-
-// 100 will be converter to the type of header.bar, so we can do > comparison
-simple("${header.bar} > 100")
-
-// if the value of header.bar was 100, value returned will be 101. header.bar itself will not be changed.
-simple("${header.bar}++")
-----
-
-=== Using Operators with different Java Object types
-
-When you compare with different types such as String and int, then you
-have to take a bit of care. Camel will use the type from the left-hand side
-as first priority. And fallback to the right-hand side type if both values
-couldn't be compared based on that type. This means you can flip the values
-to enforce a specific type. Suppose the bar value above is a String.
-
-Then you can flip the equation:
-
-[source,java]
-----
-simple("100 < ${header.bar}")
-----
-
-which then ensures the int type is used as first priority.
-
-This may change in the future if the Camel team improves the binary
-comparison operations to prefer numeric types to String-based. It's
-most often the String type which causes problems when comparing with
-numbers.
-
-[source,java]
-----
-// testing for null
-simple("${header.baz} == null")
-
-// testing for not null
-simple("${header.baz} != null")
-----
-
-And a bit more advanced example where the right value is another
-expression
-
-[source,java]
-----
-simple("${header.date} == ${date:now:yyyyMMdd}")
-
-simple("${header.type} == ${bean:orderService?method=getOrderType}")
-----
-
-And an example with `contains`, testing if the title contains the word Camel
-
-[source,java]
-----
-simple("${header.title} contains 'Camel'")
-----
-
-And an example with regex, testing if the number header is a 4-digit value:
-
-[source,java]
-----
-simple("${header.number} regex '\\d{4}'")
-----
-
-And finally an example if the header equals any of the values in the
-list. Each element must be separated by comma, and no space around.
-This also works for numbers etc., as Camel will convert each element
-into the type of the left-hand side.
-
-[source,java]
-----
-simple("${header.type} in 'gold,silver'")
-----
-
-And for all the last 3, we also support the negate test using not:
-
-[source,java]
-----
-simple("${header.type} !in 'gold,silver'")
-----
-
-And you can test if the type is a certain instance, e.g., for instance a
-String
-
-[source,java]
-----
-simple("${header.type} is 'java.lang.String'")
-----
-
-We have added a shorthand for all `java.lang` types, so you can write it as:
-
-[source,java]
-----
-simple("${header.type} is 'String'")
-----
-
-Ranges are also supported. The range interval requires numbers and both
-from and end are inclusive. For instance, to test whether a value is
-between 100 and 199:
-
-[source,java]
-----
-simple("${header.number} range 100..199")
-----
-
-Notice we use `..` in the range without spaces. It is based on the same
-syntax as Groovy.
-
-[source,java]
-----
-simple("${header.number} range '100..199'")
-----
-
-As the XML DSL does not have all the power as the Java DSL with all
-its various builder methods, you have to resort to using some other
-languages for testing with simple operators. Now you can do this with the simple
-language. In the sample below, we want to test it if the header is a widget
-order:
-
-._XML-only:_
-[source,xml]
-----
-<from uri="seda:orders">
- <filter>
- <simple>${header.type} == 'widget'</simple>
- <to uri="bean:orderService?method=handleWidget"/>
- </filter>
-</from>
-----
-
-=== Combining multiple expression using AND / OR Operator
-
-If you have two expressions you can combine them with the `&&` (and) or `||` (or) operator.
-
-For instance:
-
-[source,java]
------
-simple("${header.title} contains 'Camel' && ${header.type} == 'gold'")
------
-
-And of course the `||` is also supported. The sample would be:
-
-[source,java]
------
-simple("${header.title} contains 'Camel' || ${header.type} == 'gold'")
------
-
-== Init Blocks
-
-Starting from *Camel 4.18* you can in the top of your Simple expressions declare an _initialization_ block that are used
-to define a set of local variables that are pre-computed, and can be used in the following Simple expression. This allows
-to reuse variables, and also avoid making the simple expression complicated when having inlined functions, and in general
-make the simple expression easier to maintain and understand.
-
-IMPORTANT: Init Blocks is not supported with xref:csimple-language.adoc[CSimple] language.
-
-NOTE: The init block declaration `$init{ ... }init$` may be changed in the future.
-
-The _init block_ is declared as follows:
-
-[source,text]
-----
-$init{
- // init block
- // goes here
- // ...
-}init$
-// here is the regular simple expression
-----
-
-Notice how the block uses the `$init{` ... `}init$` markers to indicate the start and end of the block.
-
-Inside the init block, then you can assign local variables in the syntax `$key := <statement>;` where you can then use simple language to compute
-the value of the variable.
-
-IMPORTANT: Each statement must end with semicolon and new-line (`;\n`). You can only have 1 statement per line.
-This makes the init block more similar to Java programming language,
-and it was also necessary to make this work for the internal simple parser used by Camel.
-
-Here are a couple of examples:
-
-[source,text]
-----
-$init{
- $cheese := 'Hello ${body}';
- $minAge := 18;
- $foo := ${uppercase('Hello ${body}')};
- $bar := ${header.code > 999 ? 'Gold' : 'Silver'};
-}init$
-----
-
-You can have Java style code comments in the init block using `// comment here` as follows:
-
-[source,text]
-----
-$init{
- // minimum age to drive
- $minAge := 18;
-
- // say hello to my friend
- $foo := ${uppercase('Hello ${body}')};
-
- // either gold or silver
- $bar := ${header.code > 999 ? 'Gold' : 'Silver'};
-}init$
-----
-
-The local variables can then easily be used in the Simple language either using the `${variable.foo}` syntax
-or the shorthand syntax `$foo`.
-
-For example as below where we do a basic JSON mapping:
-
-[source,text]
-----
-$init{
- $greeting := ${uppercase('Hello ${body}')};
- $level := ${header.code > 999 ? 'Gold' : 'Silver'};
-}init$
-{
- "message": "$greeting",
- "status": "$level"
-}
-----
-
-The assigned variables from the _init block_ are stored as xref:manual::variables.adoc[Variables] on the `Exchange` which
-allows to use the variables later in the Camel routes.
-
-For example:
-
-[tabs]
-====
-Java::
-+
-[source,java]
-----
-from("direct:welcome")
- .transform().simple(
- """
- $init{
- $greeting := ${uppercase('Hello ${body}')};
- $level := ${header.code > 999 ? 'Gold' : 'Silver'};
- }init$
- {
- "message": "$greeting",
- "status": "$level"
- }
- """)
- .to("kafka:welcome")
- .log("Sending welcome email to customer with status ${variable.level}");
-----
-
-XML::
-+
-[source,xml]
-----
-<route>
- <from uri="direct:welcome"/>
- <transform>
- <simple>
- $init{
- $greeting := ${uppercase('Hello ${body}')};
- $level := ${header.code > 999 ? 'Gold' : 'Silver'};
- }init$
- {
- "message": "$greeting",
- "status": "$level"
- }
- </simple>
- </transform>
- <to uri="kafka:welcome"/>
- <log message="Sending welcome email to customer with status ${variable.level}"/>
-</route>
-----
-
-YAML::
-+
-[source,yaml]
-----
-- from:
- uri: direct:welcome
- steps:
- - transform:
- simple:
- expression: |-
- $init{
- $greeting := ${uppercase('Hello ${body}')};
- $level := ${header.code > 999 ? 'Gold' : 'Silver'};
- }init$
- {
- "message": "$greeting",
- "status": "$level"
- }
- - to:
- uri: kafka:welcome
- - log:
- message: "Sending welcome email to customer with status ${variable.level}"
-----
-====
-
-Notice how we can refer to the variable (`$level`) in the log statement using the standard `${variable.xxx}` syntax.
-
-TIP: Instead of inlining the simple script in the route, you can externalize this to a source file such as `mymapping.txt`
-and then refer to the file such as `resource:classpath:mymapping.txt` where the file is located in the root classpath (can also be located in sub packages).
-
-=== Init Blocks with custom functions
-
-You can also declare custom functions using
-
-Inside the init block, it is a lso possible to define custom functions in the syntax `$nane ~:= <statement>;` where you can then use simple language to declare
-the structure of the function. Then you can later use these custom functions in your simple language expressions.
-
-For example to create a function that can cleanup a `String` value:
-
-[source,text]
-----
-$init{
- $cleanUp ~:= ${trim()} ~> ${normalizeWhitespace()} ~> ${uppercase()};
-}init$
-----
-
-The function will by default use the message body as the input, such that the following:
-
-[source,java]
-----
-simple("Incoming message: $cleanUp()");
-----
-
-Would then call the _clean_ function with the message body as the input, which will then be used for trim, normalize and upper-casing.
-
-A custom function can also use a **single** parameter, however then the syntax must use `${name(...)}` style, such as:
-
-[source,java]
-----
-simple("Incoming message: ${cleanUp(' Please clean this text for me ')}");
-----
-
-Here the parameter is a fixed `String` but you can also pass in other type of value such as a number, boolean, or even a nested function.
-
-==== Calling custom functions from custom functions
-
-It is also possible to reuse custom functions from other functions using `${function(name)}`, such shown:
-
-[source,text]
-----
-$init{
- $cleanUp ~:= ${trim()} ~> ${normalizeWhitespace()} ~> ${uppercase()};
- $count ~:= ${function(cleanUp)} ~> ${split(' ')} ~> ${size()};
-}init$
-----
-
-Here the `$count` is declared as a function which calls the cleanUp function and then counts the words via split and size functions.
-
-Instead of using `${function(name)}` you can also same syntax as the built-in Simple functions, as follows:
-
-[source,text]
-----
-$init{
- $cleanUp ~:= ${trim()} ~> ${normalizeWhitespace()} ~> ${uppercase()};
- $count ~:= ${cleanUp()} ~> ${split(' ')} ~> ${size()};
-}init$
-----
-
-Notice how `${cleanUp()}` despite being a custom function is using the same syntax as all the built-in functions that are being used, for example:
- `${trim()}`.
-
-
-== OGNL Expression Support
-
-The xref:simple-language.adoc[Simple] and xref:simple-language.adoc[Bean] languages support a _OGNL like_ notation for invoking methods (using reflection) in a fluent builder like style.
-
-https://en.wikipedia.org/wiki/OGNL[OGNL] (Object-Graph Navigation Language) is a powerful expression language used in Java. In Camel you can use OGNL dot notation to invoke methods. If you for instance have a body that contains a POJO that has a `getFamilyName` method then
-you can construct the Simple syntax as follows:
-
-[source,java]
-----
-simple("${body.familyName}")
-----
-
-Or use similar syntax as in Java:
-
-[source,java]
-----
-simple("${body.getFamilyName()}")
-----
-
-Camel's OGNL support is for invoking methods only. You cannot access fields. Camel support accessing the length field of Java arrays.
-
-[IMPORTANT]
-====
-When using *OGNL* then `camel-bean` JAR is required to be on the classpath.
-====
-
-=== Built-in Functions supporting OGNL
-
-The following functions support _OGNL syntax_:
-
-[width="100%",options="header",]
-|====
-|Variable | Response Type | Description
-|`attachment.key._OGNL_` | `Object` | Refer to the attachment with the given key on the `Exchange`. This requires having camel-attachments JAR on classpath.
-|`bodyAs(type)` | `<T>` | The message body converted to the given type
-|`body` | `Object` | The message body
-|`camelContext` | `CamelContext` | The `CamelContext`
-|`convertTo(exp,type)` | `<T>` | Converts the expression to the specified type
-|`exception` | `Throwable` | If the exchange failed due to an exception
-|`exchangeProperty.key` | `Object` | The value from the exchange property with the given key
-|`exchange` | `Exchange` | The current `Exchange`
-|`header.key` | `Object` | The value from the message header with the given key
-|`mandatoryBodyAs(type)` | `<T>` | The message body converted to the given type
-|`messageAs(type)` | `<T>` | The `org.apache.camel.Message` as a specialized instance
-|`variable.key` | `Object` | The value from the variable with the given key
-|====
-
-=== Basic OGNL examples
-
-Suppose the Message body contains a POJO which has a `getAddress()`
-method. Then you can use Camel OGNL notation to access the address object:
-
-[source,java]
-----
-simple("${body.address}")
-simple("${body.address.street}")
-simple("${body.address.zip}")
-----
-
-Camel understands the shorthand names for getters, but you can invoke
-any method or use the real name such as:
-
-[source,java]
-----
-simple("${body.address}")
-simple("${body.getAddress.getStreet}")
-simple("${body.getAddress().getStreet()}")
-simple("${body.address.getZip}")
-simple("${body.doSomething}")
-----
-
-You can also use the null safe operator (`?.`) to avoid `NullPointerException` if, for example,
-the body does NOT have an address:
-
-[source,java]
-----
-simple("${body?.address?.street}")
-----
-
-=== Advanced OGNL examples
-
-It is also possible to index in `Map` or `List` types, so you can do:
-
-[source,java]
-----
-simple("${body[foo].name}")
-----
-
-To assume the body is `Map` based and look up the value with `foo` as
-key, and invoke the `getName` method on that value.
-
-If the key has space, then you *must* enclose the key with quotes, for
-example, 'foo bar':
-
-[source,java]
-----
-simple("${body['foo bar'].name}")
-----
-
-You can access the `Map` or `List` objects directly using their key name
-(with or without dots) :
-
-[source,java]
-----
-simple("${body[foo]}")
-simple("${body[this.is.foo]}")
-----
-
-Suppose there was no value with the key `foo` then you can use the null
-safe operator to avoid the NPE as shown:
-
-[source,java]
-----
-simple("${body[foo]?.name}")
-----
-
-You can also access `List` types, for example, to get lines from the
-address you can do:
-
-[source,java]
-----
-simple("${body.address.lines[0]}")
-simple("${body.address.lines[1]}")
-simple("${body.address.lines[2]}")
-----
-
-There is a special `last` keyword which can be used to get the last
-value from a list.
-
-[source,java]
-----
-simple("${body.address.lines[last]}")
-----
-
-And to get the 2nd last you can subtract a number, so we can use
-`last-1` to indicate this:
-
-[source,java]
-----
-simple("${body.address.lines[last-1]}")
-----
-
-And the third last is, of course:
-
-[source,java]
-----
-simple("${body.address.lines[last-2]}")
-----
-
-And you can call the size method on the list with
-
-[source,java]
-----
-simple("${body.address.lines.size}")
-----
-
-Camel supports the length field for Java arrays as well, e.g.:
-
-[source,java]
-----
-String[] lines = new String[]{"foo", "bar", "cat"};
-exchange.getMessage().setBody(lines);
-
-simple("There are ${body.length} lines")
-----
-
-[TIP]
-====
-You can also use the *length* function from *Camel 4.18*: `simple("There are ${length()} lines")`
-====
-
-And yes, you can combine this with the Simple operators such as checking if a zip code is larger than 1000:
-
-[source,java]
-----
-simple("${body.address.zip} > 1000")
-----
-
-
-== EIP Examples
-
-Below we filter based on a header value:
-
-[tabs]
-====
-Java::
-+
-[source,java]
-----
-from("seda:orders")
- .filter().simple("${header.foo}")
- .to("seda:fooOrders");
-----
-
-XML::
-+
-[source,xml]
-----
-<route>
- <from uri="seda:orders"/>
- <filter>
- <simple>${header.foo}</simple>
- <to uri="seda:fooOrders"/>
- </filter>
-</route>
-----
-
-YAML::
-+
-[source,yaml]
-----
-- route:
- from:
- uri: seda:orders
- steps:
- - filter:
- simple: "${header.foo}"
- steps:
- - to:
- uri: seda:fooOrders
-----
-====
-
-The Simple language can be used for the predicate test above in the
-Message Filter pattern, where we test if the
-in message has a `foo` header (a header with the key `foo` exists). If
-the expression evaluates to `*true*`, then the message is routed to the
-`seda:fooOrders` endpoint, otherwise the message is dropped.
-
-You can also use the simple language for simple text concatenations such as:
-
-[tabs]
-====
-Java::
-+
-[source,java]
-----
-from("direct:hello")
- .transform().simple("Hello ${header.user} how are you?")
- .to("mock:reply");
-----
-
-XML::
-+
-[source,xml]
-----
-<route>
- <from uri="direct:hello"/>
- <transform>
- <simple>Hello ${header.user} how are you?</simple>
- </transform>
- <to uri="mock:reply"/>
-</route>
-----
-
-YAML::
-+
-[source,yaml]
-----
-- route:
- from:
- uri: direct:hello
- steps:
- - transform:
- simple: "Hello ${header.user} how are you?"
- - to:
- uri: mock:reply
-----
-====
-
-Notice that we must use `${ }` placeholders in the expression now to
-allow Camel to parse it correctly.
-
-And this sample uses the date command to output current date.
-
-[tabs]
-====
-Java::
-+
-[source,java]
-----
-from("direct:hello")
- .transform().simple("The today is ${date:now:yyyyMMdd} and it is a great day.")
- .to("mock:reply");
-----
-
-XML::
-+
-[source,xml]
-----
-<route>
- <from uri="direct:hello"/>
- <transform>
- <simple>The today is ${date:now:yyyyMMdd} and it is a great day.</simple>
- </transform>
- <to uri="mock:reply"/>
-</route>
-----
-
-YAML::
-+
-[source,yaml]
-----
-- route:
- from:
- uri: direct:hello
- steps:
- - transform:
- simple: "The today is ${date:now:yyyyMMdd} and it is a great day."
- - to:
- uri: mock:reply
-----
-====
-
-And in the sample below, we invoke the bean language to invoke a method
-on a bean to be included in the returned string:
-
-[tabs]
-====
-Java::
-+
-[source,java]
-----
-from("direct:order")
- .transform().simple("OrderId: ${bean:orderIdGenerator}")
- .to("mock:reply");
-----
-
-XML::
-+
-[source,xml]
-----
-<route>
- <from uri="direct:order"/>
- <transform>
- <simple>OrderId: ${bean:orderIdGenerator}</simple>
- </transform>
- <to uri="mock:reply"/>
-</route>
-----
-
-YAML::
-+
-[source,yaml]
-----
-- route:
- from:
- uri: direct:order
- steps:
- - transform:
- simple: "OrderId: ${bean:orderIdGenerator}"
- - to:
- uri: mock:reply
-----
-====
-
-Where `orderIdGenerator` is the id of the bean registered in the
-Registry. If using Spring, then it is the Spring bean
-id.
-
-If we want to declare which method to invoke on the order id generator
-bean we must prepend `.method name` such as below where we invoke the
-`generateId` method.
-
-[tabs]
-====
-Java::
-+
-[source,java]
-----
-from("direct:order")
- .transform().simple("OrderId: ${bean:orderIdGenerator.generateId}")
- .to("mock:reply");
-----
-
-XML::
-+
-[source,xml]
-----
-<route>
- <from uri="direct:order"/>
- <transform>
- <simple>OrderId: ${bean:orderIdGenerator.generateId}</simple>
- </transform>
- <to uri="mock:reply"/>
-</route>
-----
-
-YAML::
-+
-[source,yaml]
-----
-- route:
- from:
- uri: direct:order
- steps:
- - transform:
- simple: "OrderId: ${bean:orderIdGenerator.generateId}"
- - to:
- uri: mock:reply
-----
-====
-
-We can use the `?method=methodname` option that we are familiar with the
-xref:components::bean-component.adoc[Bean] component itself:
-
-[tabs]
-====
-Java::
-+
-[source,java]
-----
-from("direct:order")
- .transform().simple("OrderId: ${bean:orderIdGenerator?method=generateId}")
- .to("mock:reply");
-----
-
-XML::
-+
-[source,xml]
-----
-<route>
- <from uri="direct:order"/>
- <transform>
- <simple>OrderId: ${bean:orderIdGenerator?method=generateId}</simple>
- </transform>
- <to uri="mock:reply"/>
-</route>
-----
-
-YAML::
-+
-[source,yaml]
-----
-- route:
- from:
- uri: direct:order
- steps:
- - transform:
- simple: "OrderId: ${bean:orderIdGenerator?method=generateId}"
- - to:
- uri: mock:reply
-----
-====
-
-You can also convert the body to a given
-type, for example, to ensure that it is a String you can do:
-
-[source,xml]
-----
-<transform>
- <simple>Hello ${bodyAs(String)} how are you?</simple>
-</transform>
-----
-
-There are a few types which have a shorthand notation, so we can use
-`String` instead of `java.lang.String`. These are:
-`byte[], String, Integer, Long`. All other types must use their FQN
-name, e.g. `org.w3c.dom.Document`.
-
-It is also possible to look up a value from a header `Map`:
-
-[source,xml]
-----
-<transform>
- <simple>The gold value is ${header.type[gold]}</simple>
-</transform>
-----
-
-In the code above we look up the header with name `type` and regard it as
-a `java.util.Map` and we then look up with the key `gold` and return the
-value. If the header is not convertible to Map, an exception is thrown. If the
-header with name `type` does not exist `null` is returned.
-
-You can nest functions, such as shown below:
-
-[source,xml]
-----
-<setHeader name="myHeader">
- <simple>${properties:${header.someKey}}</simple>
-</setHeader>
-----
-
-== Using Substring Function
-
-You can use the `substring` function to more easily clip the message body.
-For example if the message body contains the following 10 letters `ABCDEFGHIJ` then:
-
-[source,xml]
-----
-<setBody>
- <simple>${substring(3)}</simple>
-</setBody>
-----
-
-Then the message body after the substring will be `DEFGHIJ`.
-If you want to clip from the end instead, then use negative values such as `substring(-3)`.
-
-You can also clip from both ends at the same time such as `substring(1,-1)` that will clip the first and last character in the String.
-
-If the number is higher than the length of the message body, then an empty string is returned, for example `substring(99)`.
-
-Instead of the message body then a simple expression can be nested as input, for example, using a variable, as shown below:
-
-[source,xml]
-----
-<setBody>
- <simple>${substring(1,-1,${variable.foo})}</simple>
-</setBody>
-----
-
-[#_replacing_double_and_single_quotes]
-== Replacing double and single quotes
-
-You can use the `replace` function to more easily replace all single or double quotes in the message body,
-using the XML escape syntax. This avoids to fiddle with enclosing a double quote or single quotes with outer quotes,
-that can get confusing to be correct as you may need to escape the quotes as well. So instead you can use the XML escape
-syntax where double quote is `\"` and single quote is `\'` (yeah that is the name).
-
-For example, to replace all double quotes with single quotes:
-
-[tabs]
-====
-Java::
-+
-[source,java]
-----
-from("direct:order")
- .transform().simple("${replace(" , ')}")
- .to("mock:reply");
-----
-
-XML::
-+
-[source,xml]
-----
-<route>
- <from uri="direct:order"/>
- <transform>
- <simple>${replace(&quot; , &apos;)}</simple>
- </transform>
- <to uri="mock:reply"/>
-</route>
-----
-
-YAML::
-+
-[source,yaml]
-----
-- route:
- from:
- uri: direct:order
- steps:
- - transform:
- simple: "${replace(" , ')}"
- - to:
- uri: mock:reply
-----
-====
-
-And to replace all single quotes with double quotes:
-
-[source,xml]
-----
-<setBody>
- <simple>${replace(' , ")}</simple>
-</setBody>
-----
-
-Or to remove all double quotes:
-
-[source,xml]
-----
-<setBody>
- <simple>${replace(" , ∅)}</simple>
-</setBody>
-----
-
-== Setting the result type
-
-You can now provide a result type to the xref:simple-language.adoc[Simple]
-expression, which means the result of the evaluation will be converted
-to the desired type. This is most usable to define types such as
-booleans, integers, etc.
-
-For example, to set a header as a boolean type, you can do:
-
-._Java-only: setting result type on a simple expression_
-[source,java]
-----
-.setHeader("cool", simple("true", Boolean.class))
-----
-
-And in XML DSL
-
-[source,xml]
-----
-<setHeader name="cool">
- <!-- use resultType to indicate that the type should be a java.lang.Boolean -->
- <simple resultType="java.lang.Boolean">true</simple>
-</setHeader>
-----
-
-== Using new lines or tabs in XML DSLs
-
-It is easier to specify new lines or tabs in
-XML DSLs as you can escape the value now
-
-[source,xml]
-----
-<transform>
- <simple>The following text\nis on a new line</simple>
-</transform>
-----
-
-== Leading and trailing whitespace handling
-
-The trim attribute of the expression can be
-used to control whether the leading and trailing whitespace characters
-are removed or preserved. The default value is true, which removes the
-whitespace characters.
-
-[source,xml]
-----
-<setBody>
- <simple trim="false">You get some trailing whitespace characters. </simple>
-</setBody>
-----
-
-== Loading script from external resource
-
-You can externalize the script and have Camel load it from a resource
-such as `"classpath:"`, `"file:"`, or `"http:"`.
-This is done using the following syntax: `"resource:scheme:location"`,
-e.g., to refer to a file on the classpath you can do:
-
-._Java-only: loading a simple script from an external resource_
-[source,java]
-----
-.setHeader("myHeader").simple("resource:classpath:mysimple.txt")
-----
-
-== Pretty XML or JSON
-
-From *Camel 4.18* onwards then the Simple language can _pretty format_ the output.
-
-You turn this on via the `pretty` option set to `true`:
-
-[tabs]
-====
-Java::
-+
-[source,java]
-----
-from("direct:json")
- .setBody().simple("{ \"name\": \"Jack\", \"age\": 44 }", true)
- .to("mock:result");
-----
-
-XML::
-+
-[source,xml]
-----
-<route>
- <from uri="direct:json"/>
- <setBody>
- <simple pretty="true">{ "name": "Jack", "age": 44 }</simple>
- </setBody>
- <to uri="mock:result"/>
-</route>
-----
-
-YAML::
-+
-[source,yaml]
-----
-- route:
- from:
- uri: direct:json
- steps:
- - setBody:
- simple:
- expression: "{ \"name\": \"Jack\", \"age\": 44 }"
- pretty: true
- - to:
- uri: mock:result
-----
-====
-
-This works with XML, JSON and text content:
-
-._Java-only: pretty formatting with different content types_
-[source,java]
-----
-from("direct:xml")
- .setBody().simple("<person><name>Jack</name></person>", true)
- .to("mock:result");
-
-from("direct:text")
- .setBody().simple("Hello ${body}", true)
- .to("mock:result");
-----
-
-== Adding custom functions to Simple language
-
-You can add custom functions to the Simple language by adding to the `org.apache.camel.spi.SimpleFunctionRegistry`.
-
-A custom function should either be an `Expression` or a `org.apache.camel.spi.SimpleFunction` implementation.
-
-You may want to use `Expression` when you build custom functions from the built-in functions in Camel.
-This can be done programmatically such as:
-
-._Java-only: registering a custom function with SimpleFunctionRegistry_
-[source,java]
-----
-SimpleFunctionRegistry reg = PluginHelper.getSimpleFunctionRegistry(getCamelContext());
-
-reg.addFunction("foo", new ExpressionAdapter() {
- @Override
- public Object evaluate(Exchange exchange) {
- return "I was here " + exchange.getMessage().getBody();
- }
-});
-----
-
-Here we add a custom function named `foo` which is implemented as a `org.apache.camel.Expression` which conveniently
-can be done by using the `org.apache.camel.support.ExpressionAdapter` class as above.
-
-The foo function can now be used in simple such as:
-
-[tabs]
-====
-Java::
-+
-[source,java]
-----
-from("direct:start")
- .setBody(simple("Hello ${foo}"))
- .to("mock:result");
-----
-
-XML::
-+
-[source,xml]
-----
-<route>
- <from uri="direct:start"/>
- <setBody>
- <simple>Hello ${foo}</simple>
- </setBody>
- <to uri="mock:result"/>
-</route>
-----
-
-YAML::
-+
-[source,yaml]
-----
-- route:
- from:
- uri: direct:start
- steps:
- - setBody:
- simple: "Hello ${foo}"
- - to:
- uri: mock:result
-----
-====
-
-Notice how the foo function is used just like it was a built-in function using `$\{foo}` syntax.
-
-Since a custom function is just an `Expression` then it's possible to build custom functions from
-all the Camel languages such as Groovy, JSonPath and even Simple as well.
-
-._Java-only: building a custom function from Simple expressions_
-[source,java]
-----
-var bar = context.resolveLanguage("simple").createExpression("${trim()} ~> ${normalizeWhitespace()} ~> ${capitalize()} ~> ${quote()}");
-reg.addFunction("bar", bar);
-----
-
-The `bar` function is build using simple functions using the `~>` chain operators to perform a sequence of functions on the payload.
-
-Custom functions will by default use the message body as the payload. But they also support a single parameter as the input,
-which allows to provide the input as fixed value such as a string literal or to refer to an existing header or variable.
-
-For example the foo function uses variable with name `msg` as the input:
-
-[tabs]
-====
-Java::
-+
-[source,java]
-----
-from("direct:start")
- .setVariable("msg", constant("Moon"))
- .setBody(simple("Bye ${foo(${variable.msg})}"))
- .to("mock:result");
-----
-
-XML::
-+
-[source,xml]
-----
-<route>
- <from uri="direct:start"/>
- <setVariable name="msg">
- <constant>Moon</constant>
- </setVariable>
- <setBody>
- <simple>Bye ${foo(${variable.msg})}</simple>
- </setBody>
- <to uri="mock:result"/>
-</route>
-----
-
-YAML::
-+
-[source,yaml]
-----
-- route:
- from:
- uri: direct:start
- steps:
- - setVariable:
- name: msg
- constant: "Moon"
- - setBody:
- simple: "Bye ${foo(${variable.msg})}"
- - to:
- uri: mock:result
-----
-====
-
-And instead of nesting the variable inside the foo function, we can also use the `~>` chain operator:
-
-[tabs]
-====
-Java::
-+
-[source,java]
-----
-from("direct:start")
- .setVariable("msg", constant("Moon"))
- .setBody(simple("Bye ${variable.msg} ~> ${foo}"))
- .to("mock:result");
-----
-
-XML::
-+
-[source,xml]
-----
-<route>
- <from uri="direct:start"/>
- <setVariable name="msg">
- <constant>Moon</constant>
- </setVariable>
- <setBody>
- <simple>Bye ${variable.msg} ~> ${foo}</simple>
- </setBody>
- <to uri="mock:result"/>
-</route>
-----
-
-YAML::
-+
-[source,yaml]
-----
-- route:
- from:
- uri: direct:start
- steps:
- - setVariable:
- name: msg
- constant: "Moon"
- - setBody:
- simple: "Bye ${variable.msg} ~> ${foo}"
- - to:
- uri: mock:result
-----
-====
-
-You can also build custom functions as a Java class as below:
-
-._Java-only: implementing SimpleFunction interface_
-[source,java]
-----
-public class FooSimpleFunction implements SimpleFunction {
-
- @Override
- public String getName() {
- return "foo";
- }
-
- @Override
- public Object apply(Exchange exchange, Object input) throws Exception {
- return "I was here " + input;
- }
-}
-----
-
-This gives you the full power to implement the function logic in standard Java.
-
-This function can be added programmatically:
-
-._Java-only: adding a SimpleFunction to the registry_
-[source,java]
-----
-SimpleFunctionRegistry reg = PluginHelper.getSimpleFunctionRegistry(getCamelContext());
-
-reg.addFunction(new FooSimpleFunction());
-----
-
-TIP: The custom function can then be made discoverable by Camel by dependency injection.
-If you use standalone Camel you can add `@BindToRegistry("foo-function")` to the class.
-For Spring Boot use `@Component` or `@Service` and Quarkus you can for example use `@ApplicationScoped`.
-
-
-== JavaScript Validator
-
-The `camel-catalog` JAR includes a self-contained JavaScript validator for the Simple language.
-It can syntax-check expressions and predicates in any browser or Node.js environment — no Java backend required.
-
-The files are located in the JAR under:
-
-----
-org/apache/camel/catalog/simple/camel-simple-validator.js
-org/apache/camel/catalog/simple/camel-simple-validator.html
-----
-
-The `.js` file is auto-generated from `simple.json` during the Maven build, so its list of functions and operators
-always matches the current Camel version.
-
-=== API
-
-The validator exposes these functions:
-
-* `validate(input, mode)` — validate a Simple expression or predicate.
- `mode` is `'expression'` (default) or `'predicate'`.
- Returns `{ valid: boolean, diagnostics: [...] }`.
-* `complete(input, pos)` — return completion suggestions at the given cursor position.
-* `getFunctions()` — return the list of known Simple function names.
-* `getOperators()` — return the list of known Simple operators with their kind and description.
-
-=== Usage in Node.js
-
-[source,javascript]
-----
-const { validate, complete } = require('./camel-simple-validator.js');
-
-const result = validate("${body} == 'hello'", 'predicate');
-console.log(result.valid); // true
-console.log(result.diagnostics); // []
-
-const bad = validate("${bdy}", 'expression');
-console.log(bad.valid); // false
-console.log(bad.diagnostics[0].message); // "Unknown function 'bdy', did you mean 'body'?"
-----
-
-=== Usage in a browser
-
-Extract `camel-simple-validator.html` from the JAR and open it in a browser.
-It provides an interactive form where you can type Simple expressions and validate them with instant feedback.
-
-== Dependencies
-
-The Simple language is part of *camel-core*.
diff --git a/core/camel-core-languages/src/main/docs/modules/languages/pages/simple-language.adoc b/core/camel-core-languages/src/main/docs/modules/languages/pages/simple-language.adoc
index 300a86f57d54..045b9393e399 100644
--- a/core/camel-core-languages/src/main/docs/modules/languages/pages/simple-language.adoc
+++ b/core/camel-core-languages/src/main/docs/modules/languages/pages/simple-language.adoc
@@ -117,2719 +117,14 @@ The Simple Language can be configured globally. However, its seldom needed.
include::partial$language-options.adoc[]
// language options: END
-== Built-in Simple Functions
+== Detailed Reference
-The Simple language has many built-in functions which allows access to various part of Camel and the current `Exchange`, the message payload such as body and headers, and much more.
+For detailed documentation on each topic, see the following sub-pages:
-NOTE: Some functions take 1 or more arguments enclosed in parentheses, and arguments separated by comma (ie `${replace('custID','customerId')}`.
-
-=== Inlined Result Type Function
-
-**Available as of Camel 4.21**
-
-The simple language, has many built-in functions, and each of them take different set of parameters, and some are more advanced than others, for example
-the functions working with JSon or XML payloads. Regards of that, you may have need for being able to easily specify that the function should return the value
-as an integer instead of _what it would otherwise do_. To make this easy we have built-in a fixed set of very common result types to make this easy.
-
-[width="100%",cols="10%,10%,80%",options="header",]
-|====
-|Prefix |Response Type |Description
-|`int:` | `Integer` | To use `Integer` as a result type.
-|`integer:` | `Integer` | To use `Integer` as a result type.
-|`long:` | `Long` | To use `Long` as a result type.
-|`boolean:` | `Boolean` | To use `Boolean` as a result type.
-|`string:` | `String` | To use `String` (text) as a result type.
-|====
-
-You do this by prefixing the function with any of the above, such as `${int:header.age}` to return the age header as an integer.
-If you use XML then the XPath function can do this as well such as `${int:xpath(//food/quantity)}`.
-
-If you need to use a type that is not in the table above, then you can combine two functions together with the `${convertTo(type)}` function, as follows:
-
-`${xpath(//food[name='food1']/price/text())} ~> ${convertTo(java.math.BigDecimal)}`
-
-=== Core Camel Functions
-
-The Camel functions are as the name implies specific to Apache Camel and these functions are primary used
-to access Camel functionality and content of the message being routed.
-
-[width="100%",cols="10%,10%,80%",options="header",]
-|====
-|Function |Response Type |Description
-|`bean(name.method)` | `Object` | Invoking a bean expression using the xref:components::bean-component.adoc[Bean] language. Specifying a method name, you must use dot as the separator. We also support the ?method=methodname syntax that is used by the xref:components::bean-component.adoc[Bean] component. Camel will by default lookup a bean by the given name. However, if you need to refer to a bean class (such as calling a static method), then you can prefix with the type, such as `bean:ty [...]
-|`body._OGNL_` | `Object` | The body invoked using a Camel _OGNL syntax_. For example to invoke the `getCountryCode` on the message body, you can use `${body.getCountryCode()}`. In the message body is a POJO then you can use a short-hand syntax `${body.countryCode}`.
-|`bodyAs(type)` | `<T>` | Converts the body to the given type determined by its classname.
-|`bodyAs(type)._OGNL_` | `Object` | Converts the body to the given type determined by its classname and then invoke methods using a Camel _OGNL syntax_.
-|`bodyOneLine` | `String` | Converts the body to a String and removes all line-breaks, so the string is in one line.
-|`bodyType` | `Class` | The message body class.
-|`body` | `Object` | The message body
-|`camelContext._OGNL_` | `Object` | The CamelContext invoked using Camel _OGNL syntax_.
-|`camelId` | `String` | The name of the Camel application (ie `CamelContext`).
-|`convertTo(type)` | `<T>` | Converts the message body to the specified type.
-|`convertTo(exp,type)` | `<T>` | Converts the expression to the specified type.
-|`convertTo(exp,type)._OGNL_` | `Object` | Converts the expression to the specified type and then invoke methods using a Camel _OGNL syntax_.
-|`exception` | `Throwable` | The `Exception` object on the exchange, is `null` if no exception is set on the `Exchange`. Will fallback and grab any caught exceptions stored as exchange property (`Exchange.EXCEPTION_CAUGHT`)
-|`exception._OGNL_` | `Object` | Same as `exception` and then invoke Camel _OGNL syntax_.
-|`exception.message` | `String` | The message from the `Exchange` object. See `exception` for more details.
-|`exception.stacktrace` | `String` | The stacktrace from the `Exchange` object. See `exception` for more details.
-|`exchange._OGNL_` | `Object` | The current `Exchange` invoked using Camel _OGNL syntax_.
-|`exchangeId` | `String` | The id of the current `Exchange`.
-|`exchangeProperty.key` | `Object` | Returns the value of the exchange property with the given key. Returns `null` if the property does not exists.
-|`exchangeProperty.key._OGNL_` | `Object` | Same as `exchangeProperty.key` and then invoke Camel _OGNL syntax_.
-|`exchange` | `Exchange` | The current `Exchange` object.
-|`fromRouteId` | `String` | Returns the original route id where this `Exchange` was created.
-|`function(name,exp)` | `Object` | Invokes a custom function with the given name using the message body (or expression) as input parameter.
-|`header.key` | `Object` | The message header with the given key.
-|`header.key._OGNL_` | `Object` | Same as `header.key` and then invoke Camel _OGNL syntax_.
-|`header[key]` | `Object` | *Deprecated* The message header with the given key.
-|`header[key]._OGNL_` | `Object` | *Deprecated* Same as `header[key]` and then invoke Camel _OGNL syntax_.
-|`headerAs(key,type)` | `<T>` | The message header with the given key, converted to the given type.
-|`headers.key` | `Object` | *Deprecated* The message header with the given key.
-|`headers.size` | `int` | The number of headers
-|`headers:key` | `Object` | *Deprecated* The message header with the given key.
-|`headers[key]` | `Object` | *Deprecated* The message header with the given key.
-|`headers` | `Map` | All the message headers as a `java.util.Map`.
-|`id` | `String` | The message id
-|`kindOfType(exp)` | `String` | What kind of type is the value (null,number,string,boolean,array,object).
-|`length()` | `int` | The payload length (number of bytes) of the message body
-|`length(exp)` | `int` | The payload length (number of bytes) of the expression.
-|`logExchange` | `String` | Dumps the exchange for logging purpose (uses `ExchangeFormatter` to format the output).
-|`mandatoryBodyAs(type)` | `<T>` | Converts the message body to the given type determined by its classname. If the body is `null` then an exception is thrown.
-|`mandatoryBodyAs(type)._OGNL_` | `Object` | Same as `mandatoryBodyAs(type)` and then invoke Camel _OGNL syntax_.
-|`messageAs(type)` | `<T>` | Converts the message to the given type determined by its classname.
-|`messageAs(type)._OGNL_` | `Object` | Same as `messageAs(type)` and then invoke Camel _OGNL syntax_.
-|`messageHistory` | `String` | The message history of the current exchange (how it has been routed). This is similar to the route stack-trace message history the error handler logs in case of an unhandled exception.
-|`messageHistory(false)` | `String` | Same as `messageHistory` but without the exchange details (only includes the route stack-trace). This can be used if you do not want to log sensitive data from the message itself.
-|`messageTimestamp` | `long` | The message timestamp (millis since epoc) that this message originates from. Some systems like JMS, Kafka, AWS have a timestamp on the event/message that Camel received. This method returns the timestamp if a timestamp exists. The message timestamp and exchange created are different. An exchange always has a created timestamp which is the local timestamp when Camel created the exchange. The message timestamp is only available in some Camel components when t [...]
-|`originalBody` | `Object` | The original incoming message body (only available if Camel has been configured with `allowUseOriginalMessage=true`).
-|`properties:key:default` | `String` | Lookup a property placeholder with the given key. If the key does not exist nor has a value, then an optional default value can be specified.
-|`propertiesExist:key` | `boolean` | Checks whether a property placeholder with the given key exists or not. The result can be negated by prefixing the key with `!`.
-|`ref:key` | `Object` | To look up a bean from the Camel xref:manual::registry.adoc[Registry] with the given key.
-|`routeGroup` | `String` | Returns the route group of the current route the `Exchange` is being routed. Not all routes have a group assigned, so this may be `null`.
-|`routeId` | `String` | Returns the route id of the current route the `Exchange` is being routed.
-|`setHeader(name,type,exp)` | `null` | Sets a message header with the given expression (optional converting to the given type).
-|`setVariable(name,type,exp)` | `null` | Sets a variable with the given expression (optional converting to the given type).
-|`stepId` | `String` | Returns the id of the current step the `Exchange` is being routed. Returns `null` if there are no steps.
-|`throwException(type,msg)` | `Exception` | Deliberately throws an error. Uses `IllegalArgumentException` by default if no type is specified (use fully qualified classname).
-|`type:name.field` | `Object` | To refer to a type or field by its fully qualified classname. For example: `type:org.apache.camel.Exchange.FILE_NAME`.
-|`val(exp)` | `Object` | Returns the expression as a constant value.
-|`variable.key` | `Object` | To look up the variable with the given key.
-|`variable.key._OGNL_` | `Object` | To look up the variable with the given key and then invoke Camel _OGNL syntax_.
-|`variable[key]` | `Object` | *Deprecated* To look up the variable with the given key.
-|`variableAs(key,type)` | `<T>` | To look up the variable with the given key, and convert the value to the given type determined by its classname
-|`variables` | `Map` | All the variables from the current `Exchange` as a `java.util.Map`.
-|`variables.size` | `int` | The number of `Exchange` variables
-|====
-
-The core functions are powerful to give easy access to the current `Exchange` / `Message` being routed so
-you can get the message body, headers, variables and exchange properties.
-
-The `body` function returns the message body as-is. If the body is a `String` with value `Hello World`, then `$\{body}` returns `Hello World`.
-
-The `bodyAs` function converts the body to the given type. For example if the body is the integer `42`, then `${bodyAs(String)}` returns `"42"` as a String.
-And `${mandatoryBodyAs(Integer)}` will throw an exception if the body is `null`, otherwise it converts and returns the value.
-
-The `bodyOneLine` function converts the body to a String and removes all line-breaks, so the string is in one line. This is useful for logging.
-
-The `bodyType` function returns the Java class of the message body. For example if the body is `"Hello"`, then the type is `java.lang.String`.
-
-The `convertTo` function converts the message body (or a given expression) to the specified type.
-For example `${convertTo(int)}` converts the body to an `Integer`, and `${convertTo(byte[])}` converts to a byte array.
-You can also convert a nested expression: `${convertTo($\{body},String)}`.
-
-The `headerAs` function returns a header value converted to the given type. For example if a header `num` contains the string `"42"`,
-then `${headerAs(num,Integer)}` returns the integer `42`.
-
-The `variableAs` function works similarly for variables. If a variable `num` contains `"99"`,
-then `${variableAs(num,Integer)}` returns the integer `99`.
-
-The `exchangeProperty` function returns an exchange property. You can use dot, colon, or bracket notation:
-`${exchangeProperty.color}`, `${exchangeProperty:color}`, or `${exchangeProperty[color]}` all return the same value.
-
-The `setHeader` function sets a message header from an expression. For example `${setHeader(foo,$\{body})}` sets the header `foo` to the current body.
-You can also specify a type: `${setHeader(bar,int,$\{body})}` converts the body to an `Integer` before setting the header.
-Setting a header to `null` removes it: `${setHeader(bar,$\{null})}`.
-
-The `setVariable` function works the same as `setHeader` but for exchange variables. For example `${setVariable(count,$\{body.length})}` stores
-the body length in a variable named `count`, which can later be used as `${variable.count}`.
-
-The `val` function returns its argument as a constant value (unchanged). For example `${val(abc)}` returns the string `abc`.
-When using a nested function `${val($\{body})}`, it captures the current body value at evaluation time.
-
-The `kindOfType` function returns a string describing the _kind_ of a value. It returns one of: `null`, `string`, `number`, `boolean`, `array`, or `object`.
-For example `${kindOfType('Hello')}` returns `string`, `${kindOfType(123)}` returns `number`,
-and if the body is a `List` then `${kindOfType()}` returns `array`.
-
-During routing, you can use the xref:eips:log-eip.adoc[LogEIP] to write to the log, for example:
-
-[tabs]
-====
-Java::
-+
-[source,java]
-----
-from("direct:email")
- .log("Sending welcome email to customer ${header.id} with status ${variable.level}");
-----
-
-XML::
-+
-[source,xml]
-----
-<route>
- <from uri="direct:email"/>
- <log message="Sending welcome email to customer ${header.id} with status ${variable.level}"/>
-</route>
-----
-
-YAML::
-+
-[source,yaml]
-----
-- from:
- uri: direct:email
- steps:
- - log:
- message: "Sending welcome email to customer ${header.id} with status ${variable.level}"
-----
-====
-
-NOTE: The Camel functions are often also used for basic data mapping to easily get the part of the message payload you desire.
-
-The `length` function calculates the payload size in bytes (if possible). This is calculated by
-(if necessary) converting the payload into String to use for determine the byte length.
-For example `${length('Hello World')}` returns `11`. For larger payloads, then when using xref:manual::stream-caching.adoc[stream caching]
-the length is pre-computed and usually does not require to load the content into memory.
-
-The `throwException` function is used for throwing an exception.
-For example `${throwException('Invalid order')}` throws an `IllegalArgumentException` with the given message.
-You can also specify the exception type: `${throwException('Not found',java.io.FileNotFoundException)}`.
-
-The `exchangeId` function returns the unique identifier of the current exchange.
-This is commonly used for correlation in log messages: `$\{exchangeId}` returns a value like `ID-myhost-1234-1234567890-0-1`.
-
-The `routeId` function returns the id of the route currently processing the exchange.
-For example `$\{routeId}` returns `myRoute` when the exchange is inside a route with `routeId("myRoute")`.
-The `fromRouteId` function returns the route id where the exchange was _originally created_, which can differ from `routeId`
-when the exchange has been forwarded to another route via `direct` or `seda`.
-
-The `exception.message` function is commonly used in error handling to get the exception message.
-For example in an `onException` block you can log: `"Failed: ${exception.message}"`.
-If an `IllegalStateException("boom")` was thrown, then `${exception.message}` returns `boom`.
-Use `${exception.stacktrace}` if you need the full stack trace.
-
-The `properties:key:default` function looks up a property placeholder value from the Camel configuration.
-For example `${properties:myApp.greeting}` returns the value of the `myApp.greeting` property.
-You can also specify a default value: `${properties:myApp.greeting:Hello}` returns `Hello` if the property is not set.
-And `${propertiesExist:myApp.greeting}` returns `true` or `false` depending on whether the property exists.
-
-The `headers` function returns all message headers as a `java.util.Map`. This is useful when you need
-to pass all headers to a bean or processor. The `${headers.size}` returns the number of headers.
-
-The `messageTimestamp` function returns the timestamp from the source system (e.g., Kafka, JMS) if available.
-This is different from the exchange created timestamp, as it reflects when the original event occurred.
-Returns `0` if no timestamp is available.
-
-
-=== Array & List Functions
-
-The array and list functions are less commonly used as they are more advanced and require to work with data that are structured
-in arrays or lists.
-
-[width="100%",cols="10%,10%,80%",options="header",]
-|====
-|Function |Response Type |Description
-|`collate(size)` | `Iterator<List>` | The collate function iterates the message body and groups the data into sub lists of specified size. This can be used with the Splitter EIP to split a message body and group/batch the split sub message into a group of N sub lists. This method works similar to the collate method in Groovy.
-|`distinct(val1,val2,...)` | `Set` | Returns a set of all the values with duplicates removed
-|`empty(kind)` | `<T>` | *Deprecated* Use `createEmpty` instead.
-|`forEach(exp,fun)` | `<List>` | Returns a List containing the values returned by the function when applied to each value from the input expression. This function is not supported when using csimple.
-|`list(val1,val2,...)` | `List` | The list function creates an `java.util.ArrayList` with the given set of values.
-|`listAdd(fun)` | `List` | Adds the result of the function to the message body as a list object.
-|`listAdd(source,fun)` | `List` | Adds the result of the function to the source expression as a list object.
-|`listRemove(fun)` | `List` | Removes the result of the function (use int to remove by position index) from the message body as a list object.
-|`listRemove(source,fun)` | `List` | Removes the result of the function (use int to remove by position index) from the source expression as a list object.
-|`map(key1,value1,...)` | `Map` | The map function creates a `java.util.LinkedHashMap` with the given set of pairs.
-|`mapAdd(key,fun)` | `List` | Adds the result of the function to the message body as a map object.
-|`mapAdd(source,key,fun)` | `List` | Adds the result of the function to the source expression as a map object.
-|`mapRemove(key)` | `List` | Removes the key from the message body as a map object.
-|`mapRemove(source,key)` | `List` | Removes the key from the source expression as a map object.
-|`createEmpty(kind)` | `<T>` | Creates a new empty object of the given kind. The `string` kind creates an empty `String` object. The `list` creates an empty `ArrayList`, and `map` creates an empty `LinkedHashMap` object. Use `set` to create an empty `java.util.LinkedHashSet`.
-|`filter(exp,fun)` | `List` | Returns a List containing only the values from the input expression for which the function evaluates to true. This function is not supported when using csimple.
-|`reverse(val1,val2,...)` | `List` | Returns a list of all the values, but in reverse order.
-|`shuffle(val1,val2,...)` | `List` | Returns a list of all the values shuffled in random order.
-|`size()` | `int` | Returns the number of elements in collection or array based message body. If the value is null then 0 is returned, otherwise 1.
-|`size(exp)` | `int` | Returns the number of elements in collection or array based value. If the value is null then 0 is returned, otherwise 1.
-|`skip(number)` | `Iterator` | The skip function iterates the message body and skips the first number of items. This can be used with the Splitter EIP to split a message body and skip the first N number of items.
-|`sort(exp,reverse)` | `List` | Sorts the message body or expression in natural order
-|`split(separator)` | `String[]` | Splits the message body as a `String` value using the separator into a `String` array. The separator is comma by default.
-|`split(exp,separator)` | `String[]` | Splits the expression as a `String` value using the separator into a `String` array. The separator is comma by default.
-|====
-
-The `collate` function is used for grouping together data into smaller subgroups. Suppose you have a message body containing a list of 9 elements.
-Then by using `${collate(2)}` will transform this into an `java.util.Iterator` that will return each sub list.
-As there are 9 elements as input then the output will be 5 sub lists with 2 2 2 2 and 1 element each.
-
-The `distinct` function takes one or more values as input and then returns a `Set` with only the unique values.
-The input values can single objects or arrays or lists as well. If no values is provided then the `${distinct()}` function will use the message body as input.
-For example `${distinct('Z','X','Z','A','B','A','C','D','B','E')}` will return a `Set` with values `[Z, X, A, B, C, D, E]`.
-
-The `forEach` function is like a for loop that loops the input values and apply the function to each item, and aggregates their responses into a `List` as result.
-
-For example suppose the message body contains a comma separated String with `Camel,World,Cheese` then
-executing `${forEach($\{body},'Hello $\{body}')}` will return a List with 3 values: `["Hello Camel", "Hello World", "Hello Cheese"]`.
-
-The `list` function is used for taking all input values and putting them into a single `List` as response.
-For example if the message body contains '4' then `${list(1,2,3,$\{body})}` will return a list with 4 elements. `[1,2,3,4]`.
-
-You can also add and remove from `java.util.List`(s). For example if the message body is a `List` then you can add
-something `${listAdd('Hello')}`. This will add to the message body. The source can also be an expression instead
-of the message body, such as a variable: `${listAdd(${variable.myVar},'Hello')}`.
-To remove from a list, you use `${listRemove('Hello')}`, or use a number to refer to the position `${listRemove(0)}`.
-Use _last_ as a special index to remove the last element: `${listRemove(last)}`.
-
-Besides adding to a `List` its also possible to add to a `java.util.Map` with the `mapAdd` function. For example if the message body is a `Map` then you can add
-something `${mapAdd('country','DK')}`. This will add to the message body. The source can also be an expression instead
-of the message body, such as a variable: `${mapAdd(${variable.myVar},'country','DK')}`.
-To remove from a list, you use `${mapRemove('country')}`.
-
-The `map` function is similar to the `list` function but for creating a `Map` instead where the values are grouped in pairs 2 by 2.
-For example `${map(1,a,2,b,3,c)}` will return a map with 3 elements `{1=a, 2=b, 3=c}`.
-
-The `createEmpty` function is for creating an empty object which can either be an empty `String` or a `List`, `Map` or `Set`.
-To create an empty `Map` use `${createEmpty(map)}`.
-
-The `reverse` function is to reverse the order of the values.
-For example `${reverse(1,2,3,4,5)}` will return a `List` with the values `5,4,3,2,1`.
-
-And the `shuffle` function will randomize the order of the values. The `sort` function will sort the order of the values (in natural order A...Z).
-
-The `size` functions is used to determine the number of elements, when using `Collection` or array based payloads.
-If not then either 0 or 1 is returned whether the body is `null` or not.
-For example if the message body contains a `List` with 7 elements then `${size()}` returns `7`.
-On the other hand if the message body contains a `InputStream` then the result is `1`, and when body is `null` then `0` is returned.
-And for String payloads such as `${size('Hello World')}` then `1` is always returned.
-
-TIP: Use the `length` function to return the payload length in bytes.
-
-The `skip` function is used for skipping the first number of elements. For example suppose you have a CSV file that contains a header line,
-and you want to skip this line, then you can use `${skip(1)}` that then returns an `Iterator` that starts at the 2nd line.
-
-The `split` function is as the name implies used for splitting the message body or the value (using a separator) into an array of sub elements.
-For example if the message body a CSV payload then using `${split(\\n)}` (you need to escape the new-line character) will split
-this into a `String[]` separated by new-line.
-If the body is `a:b:c` then `${split(:)}` returns a list `[a, b, c]`.
-You can also split a header or variable value: `${split($\{header.csv},-)}` splits the header value using `-` as separator.
-
-The `sort` function sorts values in natural order. If the body is a list `[b, a, c]` then `${sort()}` returns `[a, b, c]`.
-To sort in reverse (descending) order use `${sort(true)}` which returns `[c, b, a]`.
-
-The `createEmpty` function creates a new empty object. `${createEmpty(list)}` returns an empty `ArrayList`,
-`${createEmpty(map)}` returns an empty `LinkedHashMap`, `${createEmpty(set)}` returns an empty `LinkedHashSet`,
-and `${createEmpty(string)}` returns an empty `String`.
-
-The `filter` function filters elements from a collection based on a predicate.
-For example if the body is `Camel,Dog,Cheese` then `${filter($\{body},$\{length() > 4})}` returns a list with `[Camel, Cheese]`
-(only elements with more than 4 characters). You can also filter by content: `${filter($\{body},$\{contains(dog)})}` returns `[Dog]`.
-
-
-=== Boolean & Condition Functions
-
-The condition functions is small functions that mostly evaluates to a `boolean` value.
-
-[width="100%",cols="10%,10%,80%",options="header",]
-|====
-|Function |Response Type |Description
-|`assert(exp,msg)` | `null` | Evaluates the expression and throws an exception with the message if the condition is false. This function is not supported when using csimple.
-|`contains(text)` | `boolean` | Returns true if the message body contains part of the text (ignore case)
-|`contains(exp,text)` | `boolean` | Returns true if the expression contains part of the text (ignore case)
-|`iif(predicate,trueExp,falseExp)` | `Object` | The inlined if function evaluates the predicate expression and returns the value of _trueExp_ if the predicate is `true`, otherwise the value of `falseExp` is returned. This function is similar to the ternary operator in Java.
-|`isEmpty` | `boolean` | Whether the message body is `null` or empty (list/map types are tested if they have 0 elements).
-|`isEmpty(exp)` | `boolean` | Whether the expression is `null` or empty (list/map types are tested if they have 0 elements).
-|`isAlpha()` | `boolean` | Whether the message body is alphabetic value (A..Z). For more advanced checks use the `regex` operator.
-|`isAlpha(exp)` | `boolean` | Whether the expression is alphabetic value (A..Z). For more advanced checks use the `regex` operator.
-|`isAlphaNumeric()` | `boolean` | Whether the message body is alphanumeric value (A..Z0-9). For more advanced checks use the `regex` operator.
-|`isAlphaNumeric(exp)` | `boolean` | Whether the expression is alphanumeric value (A..Z0-9). For more advanced checks use the `regex` operator.
-|`isNumeric()` | `boolean` | Whether the message body is numeric value (0..9). For more advanced checks use the `regex` operator.
-|`isNumeric(exp)` | `boolean` | Whether the expression is numeric value (0..9). For more advanced checks use the `regex` operator.
-|`not(predicate)` | `boolean` | Evaluates the predicate and returns the opposite.
-|====
-
-The `assert` function evaluates the expression and if its false or null, then an `SimpleAssertionException` is thrown with the given message.
-
-The `contains` function is a convenient function to check if a given expression contain partly a given text (ignore case).
-For example given the message body is `Hello big World` then `${contains(world)}` returns `true`, and `${contains(camel)}` returns `false`.
-
-The `iif` (_inlined if_) function is from Camel 4.18 also available as a ternary operator (predicate `?` trueExp `:` falseExp), see further below.
-An example with `iif` could be `${iif(${header.foo} > 0,'positive','negative')}`. This example is also used further below with the ternary operator.
-Instead of returning a fixed string as response, you can also use functions such as: `${iif(${header.foo} > 0,$\{body},$\{null})}`
-
-The remainder boolean functions are basic functions to check a value and return either `true` or `false`.
-
-The `isEmpty` is primary for checking if a value is either `null` or empty string or empty list/map/array types. For any other values then `false` is returned.
-
-The `isAlpha` / `isAlphaNumeric` and `isNumeric` is for checking if a value only contains `A..Z` or `A.Z0..9`, or `0..9` characters.
-Camel will use from the JDK `Character.isLetter` / `Character.isLetterOrDigit`, or `Character.isDigit` methods internally.
-
-So `${isAlpha('Hello World')}` will actually return `false` because there is a whitespace. However `${isAlpha('HelloWorld')}` returns `true`.
-
-TIP: You can use the `regex` operator to use regular expressions for more advanced tests.
-
-The `not` function inverts a boolean value. If the body is empty then `${not()}` returns `true`.
-If the body is `"Hello"` then `${not()}` returns `false`.
-You can also negate a predicate: `${not($\{body} == 'Hello')}` returns `false` when the body is `Hello`, and `true` otherwise.
-
-The `assert` function evaluates a condition and throws an exception if it fails.
-For example `${assert($\{body} == 'Hello', 'Must be Hello')}` will pass when the body is `Hello`,
-but throws a `SimpleAssertionException` with the message `Must be Hello` when the body is anything else.
-
-
-=== Date & Time Functions
-
-The date functions is used for parsing and formatting with date and times.
-
-[width="100%",cols="10%,10%,80%",options="header",]
-|====
-|Function |Response Type |Description
-|`date:millis` | `long` | Returns the current timestamp as millis in unix epoch.
-|`date:command` | `Date` | Evaluates to a `java.util.Date` object. Supported commands are: `now` for current timestamp, `exchangeCreated` for the timestamp when the current exchange was created, `header.xxx` to use the `Long/Date` object in the header with the key xxx. `variable.xxx` to use the `Long/Date` in the variable with the key xxx. `exchangeProperty.xxx` to use the `Long/Date` object in the exchange property with the key xxx. `file` for the last modified timestamp of the file (on [...]
-|`date:command:pattern` | `String` | Date formatting using `java.text.SimpleDateFormat` patterns. See `date:command` function for additional documentation on the commands.
-|`date-with-timezone:command:timezone:pattern` | `String` | Date formatting using `java.text.SimpleDateFormat` timezones and patterns. See `date:command` function for additional documentation on the commands.
-|====
-
-For example to get the current time use `${date:now}` which is returned as a `java.util.Date` object.
-And you can use `${date:millis}` to get unix epoch timestamp as a long value.
-
-If you want to format this to a String value, you can use the pattern command, such as `${date:now:hh:mm:ss}`.
-And to get the time 8 hours in the future `${date:now+8h:hh:mm:ss}`.
-
-There is also a timezone supported function so you can say `date-with-timezone:header.birthday:GMT+8:yyyy-MM-dd'T'HH:mm:ss:SSS`.
-This will get the `Date` object from the header with key birthday, and format that using the given pattern in the timezone GMT+8.
-
-You can also use date offsets with headers or exchange properties. For example `${date:header.birthday+24h:yyyyMMdd}` returns the date
-from the header shifted forward by 24 hours. And `${date:header.birthday-10s:yyyy-MM-dd'T'HH:mm:ss:SSS}` subtracts 10 seconds.
-
-Exchange properties work the same way: `${date:exchangeProperty.birthday:yyyyMMdd}` formats the property date.
-
-The `date:exchangeCreated` command returns the timestamp when the current exchange was created:
-`${date:exchangeCreated:hh:mm:ss a}` formats it as a 12-hour time with AM/PM marker.
-
-
-=== Math & Numeric Functions
-
-Various functions to work with numbers.
-
-[width="100%",cols="10%,10%,80%",options="header",]
-|====
-|Function |Response Type |Description
-|`abs()` | `long` | Converts the message body to a long number and return the absolute value.
-|`abs(exp)` | `Long` | Converts the message body (or expression) to a long number and return the absolute value.
-|`average(val1,val2,...)` | `long` | Returns the average number from all the values (integral numbers only).
-|`ceil()` | `int` | Converts the message body to a floating number and return the ceil value (rounded up to nearest integer).
-|`ceil(exp)` | `int` | Converts the expression to a floating number and return the ceil value (rounded up to nearest integer).
-|`floor()` | `int` | Converts the message body to a floating number and return the floor value (rounded down to nearest integer).
-|`floor(exp)` | `int` | Converts the expression to a floating number and return the floor value (rounded down to nearest integer).
-|`max(val1,val2,...)` | `long` | Returns the maximum number from all the values (integral numbers only).
-|`min(val1,val2,...)` | `long` | Returns the minimum number from all the values (integral numbers only).
-|`random(max)` | `int` | Returns a random `Integer` between 0 (included) and max (excluded).
-|`random(min,max)` | `int` | Returns a random `Integer` between min (included) and max (excluded).
-|`range(max)` | `List` | Returns a list of increasing integers between 0 (included) and max (excluded).
-|`range(min,max)` | `List` | Returns a list of increasing integers between min (included) and max (excluded).
-|`sum(val1,val2,...)` | `long` | Sums together all the values as integral numbers. This function can also be used to subtract by using negative numbers.
-|====
-
-The `abs` function returns the absolute value of a numeric value. It converts the input (either the message body or the result of an expression) to a long number and computes its absolute value.
-A few examples `${abs(-5)}` returns `5`, and `${abs(5)}` also returns `5`.
-
-The `average` function calculates the average (mean) of integral numbers (not floating point).
-Assume message body is `[10, 20, 30]` (as `List<Integer>` or similar) then `${average()}` results in `20`
-
-The `ceil` functions returns the value of number rounded up to the nearest integer that is greater than or equal to number.
-For example `${ceil(5.7)}` returns `6`, and `${ceil(5.1)}` also returns `6`.
-
-The `floor` functions returns the value of number rounded down to the nearest integer that is smaller or equal to number.
-For example `${floor(5.7)}` returns `5`, and `${floor(5.1)}` also returns `5`.
-
-The `max` and `min` functions in are used to find the maximum or minimum value among a set of numeric integral values.
-For example message body contains a list `[10, 5, 30, 15]` then `${max()}` returns `30` and `${min()}` returns `5`.
-
-The `random` functions returns a random number between min and max (exclusive).
-For example `${random(10)}` returns a random number 0..9. And `${random(18,50)}` returns a random number between 18..49.
-
-The `range` functions returns a list of increasing numbers between min and max (exclusive).
-For example `${range(10)}` returns the numbers `0..9`. And `${range(1,10)}` returns `1..9`.
-
-The `sum` function adds up numeric values (not floating point) and returns the result as a long.
-Assume message body is `[10, 20, 30]` (as `List<Integer>` or similar) then `${sum()}` results in `60`
-You can also use the `sum` function to add or subtract numbers. For example if you want to add 2 to a number, you can do
-`${sum($\{body},2)}`, and likewise to subtract you use negative number, such as `${sum($\{body},-2)}`.
-
-=== Other Functions
-
-Other kind of functions.
-
-[width="100%",cols="10%,10%,80%",options="header",]
-|====
-|Function |Response Type |Description
-|`env.key` | `String` | Refers to the OS system environment variable with the given key. For example `env.HOME` to refer to the home directory.
-|`hash(exp,algorithm)` | `String` | Returns a hashed value (string in hex decimal) of the given expression. The algorithm can be `SHA-256` (default) or `SHA3-256`.
-|`hostname` | `String` | Returns the local hostname (may be `null` if not possible to resolve).
-|`load(file)` | `String` | Loads the content of the resource from classpath (cannot load from file-system to avoid dangerous situations).
-|`null` | `null` | Returns a `null` value.
-|`sys.key` | `String` | *Deprecated* To lookup the JVM system property with the given key.
-|`sysenv.key` | `String` | To lookup the OS environment variable with the given key.
-|`threadId` | `String` | Returns the id of the current thread.
-|`threadName` | `String` | Returns the name of the current thread.
-|`uuid(kind)` | `String` | Returns a UUID using the Camel `UuidGenerator`. You can choose kind between `default`, `classic`, `short`, `simple` and `random` as the kind. If no kind is given, then `default` is used. It is also possible to use a custom `UuidGenerator` and bind the bean to the xref:manual::registry.adoc[Registry] with an id. For example `${uuid(myGenerator)}` where the id is `myGenerator`.
-|====
-
-To use OS environment variables you use the `${env.key}` function, such as `${env.PATH}` or `${env.HOME}`, or `${env.JAVA_HOME}`.
-Notice how the key should be in uppercase, as required by OS environment variables.
-For example `${env.HOME}` returns the home directory path such as `/home/scott`.
-
-The `hash` function is used for calculating a hash value of the given value. The `${hash()}` would use the message body and SHA-256 as algorithm and
-return a hash value as String hex-decimal.
-For example if the body is `hello` then `${hash()}` returns the SHA-256 hash as a hex string.
-You can also specify the algorithm: `${hash($\{body},SHA3-256)}` uses SHA3-256 instead of the default SHA-256.
-To hash a specific expression: `${hash($\{header.apiKey})}` hashes the value of a header.
-
-The `hostname` function returns the OS hostname and does not require using parenthesis, so just use `$\{hostname}`.
-For example `$\{hostname}` returns the local machine hostname such as `myserver`.
-
-The `null` function returns a `null` value such as `$\{null}`. This is useful for setting a header or variable to null:
-`${setHeader(foo,$\{null})}` removes the header `foo`.
-
-To use OS environment variables you can also use the `${sysenv.key}` function (an alias for `${env.key}`), such as `${sysenv.PATH}` or `${sysenv.HOME}`.
-
-You can get the current thread id by the `$\{threadId}` function (returns a numeric id),
-and the name via `$\{threadName}` (returns the thread name such as `Camel (camel-1) thread #1 - direct://start`).
-
-And you can generate unique IDs with the xref:manual::uuidgenerator.adoc[Camel UUID Generator] by the `uuid` function.
-The generator supports different kinds `default`, `classic`, `short`, `simple` and `random`, such as `${uuid(random)}`.
-For example `$\{uuid}` returns a UUID like `ID-myhost-1234-1234567890-0-1`, and `${uuid(short)}` returns a shorter form.
-You can also bind a custom `UuidGenerator` to the registry and use it by name: `${uuid(myGenerator)}`.
-
-To load data from classpath, you can use the load function such as `$\{load(myrules.json)}`.
-If the file is not present on classpath, then an exception is thrown. However, you can mark the file as optional as follows:
-`$\{load(myrules.json?optional=true)}`, which will return `null` if the file does not exists.
-
-IMPORTANT: The load function can only load from classpath; and not the file-system in general. This is on purpose
-to avoid potential security risks by constructing dynamic simple expressions using the load function to attempt
-to load server files.
-
-
-=== String Functions
-
-The string functions is various functions to work with values that are String and text based.
-
-[width="100%",cols="10%,10%,80%",options="header",]
-|====
-|Function |Response Type |Description
-|`capitalize()` | `String` | Capitalizes the message body as a String value (upper case every words)
-|`capitalize(exp)` | `String` | Capitalizes the expression as a String value (upper case every words)
-|`concat(exp,exp,separator)` | `String` | Performs a string concat using two expressions (message body as default) with optional separator.
-|`join(separator,prefix,exp)` | `String` | The join function iterates the message body (by default) and joins the data into a `String`. The separator is by default a comma. The prefix is optional. The join uses the message body as source by default. It is possible to refer to another source (simple language) such as a header via the exp parameter. For example `join('&','id=','$\{header.ids}')`
-|`lowercase()` | `String` | Lowercases the message body
-|`lowercase(exp)` | `String` | Lowercases the expression
-|`normalizeWhitespace()` | `String` | Normalizes the whitespace in the message body by cleaning up excess whitespaces.
-|`normalizeWhitespace(exp)` | `String` | Normalizes the whitespace in the expression by cleaning up excess whitespaces.
-|`pad(exp,width,separator)` | `String` | Pads the expression with extra padding if necessary, according the total width The separator is by default a space. If the width is negative then padding to the right, otherwise to the left.
-|`replace(from,to)` | `String` | Replace all the string values in the message body. To make it easier to replace single and double quotes, then you can use XML escaped values `\"` as double quote, `\'` as single quote, and `\∅` as empty value.
-|`replace(from,to,exp)` | `String` | Replace all the string values in the given expression. To make it easier to replace single and double quotes, then you can use XML escaped values `\"` as double quote, `\'` as single quote, and `\∅` as empty value.
-|`safeQuote()` | `String` | Returns the message body safely quoted if needed
-|`safeQuote(exp)` | `String` | Returns the expression safely quoted if needed
-|`substring(num1)` | `String` | Returns a substring of the message body. If the number is positive, then the returned string is clipped from the beginning. If the number is negative, then the returned string is clipped from the ending.
-|`substring(num1,num2)` | `String` | Returns a substring of the message body. `num1` clips from the beginning, `num2` clips from the ending. Negative values clip from the opposite end.
-|`substring(num1,num2,exp)` | `String` | Returns a substring of the given expression. `num1` clips from the beginning, `num2` clips from the ending. Negative values clip from the opposite end.
-|`substringAfter(after)` | `String` | Returns a substring of the message body that comes after. Returns `null` if nothing comes after.
-|`substringAfter(exp,after)` | `String` | Returns a substring of the expression that comes after. Returns `null` if nothing comes after.
-|`substringBefore(before)` | `String` | Returns a substring of the message body that comes before. Returns `null` if nothing comes before.
-|`substringBefore(exp,before)` | `String` | Returns a substring of the expression that comes before. Returns `null` if nothing comes before.
-|`substringBetween(after,before)` | `String` | Returns a substring of the message body that are between before and after. Returns `null` if nothing comes between.
-|`substringBetween(exp,after,before)` | `String` | Returns a substring of the expression that are between before and after. Returns `null` if nothing comes between.
-|`trim()` | `String` | The trim function trims the message body by removing all leading and trailing white spaces.
-|`trim(exp)` | `String` | The trim function trims the expression by removing all leading and trailing white spaces.
-|`unquote()` | `String` | Returns the message body with any leading/ending quotes removed
-|`unquote(exp)` | `String` | Returns the expression with any leading/ending quotes removed
-|`quote()` | `String` | Returns the message body as a double-quoted string
-|`quote(exp)` | `String` | Returns the expression as a double-quoted string
-|`uppercase()` | `String` | Uppercases the message body
-|`uppercase(exp)` | `String` | Uppercases the expression
-|====
-
-The `capitalize` function is used for _capitalizing_ words, by upper-casing the first letter in every words.
-For example `${capitalize('hello world')}` returns `Hello World`.
-
-The `concat` function is used for putting together two values as a single String result.
-In Java, you would use the `+` operator such as `String s = "Hello" + " world";`.
-
-The simple function works like `${concat('Hello ',$\{body})}`. Notice how you can use nested functions so the 2nd parameter is the `$\{body}` function.
-In the example we had to add a space after `"Hello "`, but you can also use the separator parameter, such as `${concat('Hello',$\{body},' ')}`.
-
-The `join` function is a more complex function to join together a set of values, separated by comma (by default) as a single combined String.
-For example if the message body contains a list of [A, B, C] then `${join()}` would return `A,B,C`.
-To use semicolon as separator you would use `${join(;)}`. The `prefix` argument can be used to prefix each value, so for example
-`${join(&,id=)}` would return `id=A&id=B&id=C`.
-
-The `lowercase` and `uppercase` functions are as the name implies used for lower and uppercasing.
-So `${lowercase('Hello World')}` returns `hello world` and `${uppercase('Hello World')}` returns `HELLO WORLD`.
-Without arguments, they operate on the message body: if the body is `HELLO` then `${lowercase()}` returns `hello`.
-
-You can use the `normalizeWhitespace` function to _clean up_ a value by removing extra whitespaces. This is done by ensuring that
-there are exactly only 1 whitespace between words. And as well trimming the value for empty whitespace
-in the beginning and end. Suppose the message body is a String value with `" Hello big World "`, then `${normalizeWhitespace()}` will return `Hello big World`.
-
-The `pad` function returns a copy of the string with extra padding, if necessary, so that its total number of characters is at least the absolute value of the width parameter.
-If width is a positive number, then the string is padded to the right; if negative, it is padded to the left.
-The optional separator specifies the padding character(s) to use. If not specified, it defaults to the space character.
-If the message body contains `foo` then `${pad($\{body},5)}` returns `"foo "` and `${pad($\{body},-5)}` returns `" foo"`, and `${pad($\{body},-5,'@')}` returns `@@foo`.
-
-The `replace` function is used for finding a given text in a string and replacing it with another.
-For example the message body contains `Hello a how are you`, then `${replace(a,b)}` returns `Hello b how bre you`.
-The replace function has special support for xref:_replacing_double_and_single_quotes[replacing double and single quotes].
-
-The `substring`, `substringBefore`, and `substringAfter` functions are all similar functions to return a substring of a given value.
-
-Suppose the message body contains `ABCDEFGHIJK` then `${substring(3)}` returns `DEFGHIJK`, and `${substring(-3)}` returns `ABCDEFGH`.
-If you want to clip the first and last character you can use `${substring(1,-1)}` returning `BCDEFGHIJ`.
-
-Now suppose the message body contains `Hello great big World how are you`.
-
-Then `${substringBefore('World')}` return `"Hello great big "`.
-And `${substringAfter('World')}` returns `" how are you"`.
-And `${substringBetween('great','how')}` would return `" big World "`.
-
-The `trim` function trims the value by removing leading and trailing whitespaces.
-So the previous example can also be trimmed by nesting the function as follows:
-`${trim(${substringBetween('great','how')})}` which would return `"big World"`.
-
-And of course `${trim(' hello world ')}` returns `hello world`.
-Without arguments, `${trim()}` trims the message body. If the body is `" hello "` then `${trim()}` returns `hello`.
-
-The `length` function calculates the payload length in bytes. If the body is `Hello` then `${length()}` returns `5`.
-You can also pass a literal: `${length('Hello World')}` returns `11`.
-
-The `size` function returns the number of elements in a collection or array.
-If the body is a `List` with elements `[a, b, c]` then `${size()}` returns `3`.
-
-The `quote` function is making sure the returned value is enclosed in double quotes.
-If the value is currently in single quote, then this will be converted to double quotes.
-
-If the message body contains `Hello World` then `${quote()}` returns `"Hello World"`.
-And using `${quote('Hi from me')}` then `"Hi from me"` is returned.
-
-The `unquote` function removes any surrounding single or double quotes from a value.
-If the body contains `'hello'` then `${unquote()}` returns `hello` (without the quotes).
-
-The `safeQuote` function is quoting the value depending on the value type
-(uses the same logic as `kindOfType` function). In essence values that are null, boolean or numbers are not quoted,
-while everything else is. The `safeQuote` function is useful when working with JSON data.
-
-For example when doing JSON to JSON mapping you can extract values form the source document,
-to be included in the output, but the values may or may not need to be quoted. Then you can use the `~>` chain operator
-to call the `safeQuote` function as shown below:
-
-[source,text]
-----
-{
- "id": ${jsonpath($.id)} ~> ${safeQuote()}
- "total": ${jsonpath($.amount)} ~> ${safeQuote()}
-}
-----
-
-
-=== XML & JSON Functions
-
-Functions to work with XML and JSON payloads.
-
-[width="100%",cols="10%,10%,80%",options="header",]
-|====
-|Function |Response Type |Description
-|`jq(exp)` | `Object` | When working with JSON data, then this allows using the JQ language, for example, to extract data from the message body (in JSON format). This requires having camel-jq JAR on the classpath.
-|`jq(input,exp)` | `Object` | Same as `jq(exp)` but to use the _input_ expression as the source of the JSON document.
-|`jsonpath(exp)` | `Object` | When working with JSON data, then this allows using the JsonPath language, for example, to extract data from the message body (in JSON format). This requires having camel-jsonpath JAR on the classpath.
-|`jsonpath(input,exp)` | `Object` | Same as `jsonpath(exp)` but to use the _input_ expression as the source of the JSON document.
-|`pretty(exp)` | `String` | Converts the expression to a `String`, and attempts to pretty print (if JSON or XML) otherwise return the value as-is.
-|`prettyBody` | `String` | Converts the message body to a `String`, and attempts to pretty print (if JSON or XML) otherwise return the value as-is.
-|`simpleJsonpath(exp)` | `Object` | When working with JSON data, then this allows using built-in Simple JsonPath, for example, to extract data from the message body (in JSON format).
-|`simpleJsonpath(input,exp)` | `Object` | Same as `simpleJsonpath(exp)` but to use the _input_ expression as the source of the JSON document.
-|`toJson(exp)` | `String` | Converts the expression to a JSON `String` representation. String values are returned as-is, null values return null, all other types are serialized to JSON.
-|`toJsonBody` | `String` | Converts the message body to a JSON `String` representation. String values are returned as-is, null values return null, all other types are serialized to JSON.
-|`toPrettyJson(exp)` | `String` | Converts the expression to a JSON `String` representation. String values are returned as-is, null values return null, all other types are serialized to JSON in pretty mode.
-|`toPrettyJsonBody` | `String` | Converts the message body to a JSON `String` representation. String values are returned as-is, null values return null, all other types are serialized to JSON in pretty mode.
-|`xpath(exp)` | `Object` | When working with XML data, then this allows using the XPath language, for example, to extract data from the message body (in XML format). This requires having camel-xpath JAR on the classpath.
-|`xpath(input,exp)` | `Object` | When working with XML data, then this allows using the XPath language, for example, to extract data from the message body (in XML format). This requires having camel-xpath JAR on the classpath. For input you can choose `header:key`, `exchangeProperty:key` or `variable:key` to use as input for the JSON payload instead of the message body.
-|====
-
-The simple language has support for working with XML and JSON data by offering functions that leverage the
-xref:languages:jsonpath-language.adoc[JSONPath], xref:languages:jq-language.adoc[JQ], xref:languages:xpath-language.adoc[XPath] languages.
-This also mean that you must include the required JARs on the classpath.
-
-The `jq` function (JSON Query) is used for using the JQ language to obtain data from an existing JSON payload.
-For example given this payload:
-
-[source,json]
-----
-{"id": 123, "age": 42, "name": "scott"}
-----
-
-Then `${jq(.id)}` will return `123`.
-
-You can also use this for basic data mapping such as:
-
-[tabs]
-====
-Java::
-+
-[source,java]
-----
-from("direct:map")
- .transform().simple("""
- {
- "roll": ${jq(.id)},
- "country": "${jq(.country // constant(sweden))}",
- "fullname": "${jq(.name)}"
- }""")
- .to("log:data");
-----
-
-XML::
-+
-[source,xml]
-----
-<route>
- <from uri="direct:map"/>
- <transform>
- <simple>{
- "roll": ${jq(.id)},
- "country": "${jq(.country // constant(sweden))}",
- "fullname": "${jq(.name)}"
- }</simple>
- </transform>
- <to uri="log:data"/>
-</route>
-----
-
-YAML::
-+
-[source,yaml]
-----
-- route:
- from:
- uri: direct:map
- steps:
- - transform:
- simple: |-
- {
- "roll": ${jq(.id)},
- "country": "${jq(.country // constant(sweden))}",
- "fullname": "${jq(.name)}"
- }
- - to:
- uri: log:data
-----
-====
-
-The `jsonpath` function works similar to `jq` but uses JSONPath.
-When using `${jsonpath($.id)}` will also return `123`.
-
-And the data mapping can be done as follows with JSonPath instead of JQ:
-
-[tabs]
-====
-Java::
-+
-[source,java]
-----
-from("direct:map")
- .transform().simple("""
- {
- "roll": ${jsonpath($.id)},
- "years": ${jsonpath($.age)},
- "fullname": "${jsonpath($.name)}"
- }""")
- .to("log:data");
-----
-
-XML::
-+
-[source,xml]
-----
-<route>
- <from uri="direct:map"/>
- <transform>
- <simple>{
- "roll": ${jsonpath($.id)},
- "years": ${jsonpath($.age)},
- "fullname": "${jsonpath($.name)}"
- }</simple>
- </transform>
- <to uri="log:data"/>
-</route>
-----
-
-YAML::
-+
-[source,yaml]
-----
-- route:
- from:
- uri: direct:map
- steps:
- - transform:
- simple: |-
- {
- "roll": ${jsonpath($.id)},
- "years": ${jsonpath($.age)},
- "fullname": "${jsonpath($.name)}"
- }
- - to:
- uri: log:data
-----
-====
-
-The `simpleJsonpath` function is using Camel's built in JSON library from `camel-util-json` that is a basic JSON parser.
-The syntax for the path is similar to Camel's bean OGNL syntax to use a dot notation to walk down a nested structure.
-
-Because the input JSON is not nested then the mapping example is just:
-
-[tabs]
-====
-Java::
-+
-[source,java]
-----
-from("direct:map")
- .transform().simple("""
- {
- "roll": ${simpleJsonpath(id)},
- "years": ${simpleJsonpath(age)},
- "fullname": "${simpleJsonpath(name)}"
- }""")
- .to("log:data");
-----
-
-XML::
-+
-[source,xml]
-----
-<route>
- <from uri="direct:map"/>
- <transform>
- <simple>{
- "roll": ${simpleJsonpath(id)},
- "years": ${simpleJsonpath(age)},
- "fullname": "${simpleJsonpath(name)}"
- }</simple>
- </transform>
- <to uri="log:data"/>
-</route>
-----
-
-YAML::
-+
-[source,yaml]
-----
-- route:
- from:
- uri: direct:map
- steps:
- - transform:
- simple: |-
- {
- "roll": ${simpleJsonpath(id)},
- "years": ${simpleJsonpath(age)},
- "fullname": "${simpleJsonpath(name)}"
- }
- - to:
- uri: log:data
-----
-====
-
-However, if there are nested JSON such as:
-
-[source,json]
-----
-{
- "library": {
- "book": [
- {
- "title": "No Title",
- "author": "F. Scott Fitzgerald",
- "year": "1925",
- "genre": "Classic",
- "movie": false,
- "id": "bk101"
- },
- {
- "title": "1984",
- "author": "George Orwell",
- "year": "1949",
- "genre": "Dystopian",
- "movie": true,
- "id": "bk102"
- }
- ]
- }
-}
-----
-
-Then you can retrieve data from the JSON payload as follows:
-
-[source,text]
-----
-library.book[0].title
-library.book[0].author
-library.book[0].year
-
-library.book[1].title
-library.book[1].author
-library.book[1].year
-----
-
-TIP: You can use `[last]` to refer to the last element in an array.
-
-You can use `?.` to declare that the path is option, so if the node or attribute does not exist, then `null` is returned.
-Otherwise, Camel will throw an exception.
-
-For example, we attempt to refer to a non-existing attribute
-
-[source,text]
-----
-library.book[0]?.cheese
-----
-
-The optional marker can also be used sooner in the path, such as `foo?.bar.age` which will not fail if there are no nested _bar_ node in the JSON payload.
-
-The `toJson` function is to convert the payload to JSON as a `String` value. However, if the payload is already a `String` then no conversion happens.
-So suppose the payload is a `Map` object as follows:
-
-[source,java]
-----
-Map<String, Object> map = new LinkedHashMap<>();
-map.put("name", "Jack");
-map.put("id", 123);
-----
-
-Then `toJson` will output:
-
-[source,json]
-----
-{"name":"Jack","id":123}
-----
-
-
-There are also _pretty_ alternatives so when calling `toPrettyJson` will output:
-
-[source,json]
-----
-{
- "name": "Jack",
- "id": 123
-}
-----
-
-The `xpath` function is for working with XML and using XPath expressions to extract data from XML payloads.
-
-Given the following XML payload:
-
-[source,xml]
-----
-<order id="123">
- <item>Brake</item>
- <first>scott</first>
- <last>jackson</last>
- <address>
- <co>sweden</co>
- <zip>12345</zip>
- </address>
-</order>
-----
-
-Then `${xpath(/order/@id)}` will return `123`.
-
-And the data mapping can be done with XPath as follows:
-
-[tabs]
-====
-Java::
-+
-[source,java]
-----
-from("direct:map")
- .transform().simple("""
- {
- "id": ${xpath(/order/@id)},
- "item": "${xpath(/order/item)}",
- "fullname": "${xpath(/order/first)} ${xpath(/order/last)}"
- }""")
- .to("log:data");
-----
-
-XML::
-+
-[source,xml]
-----
-<route>
- <from uri="direct:map"/>
- <transform>
- <simple>{
- "id": ${xpath(/order/@id)},
- "item": "${xpath(/order/item)}",
- "fullname": "${xpath(/order/first)} ${xpath(/order/last)}"
- }</simple>
- </transform>
- <to uri="log:data"/>
-</route>
-----
-
-YAML::
-+
-[source,yaml]
-----
-- route:
- from:
- uri: direct:map
- steps:
- - transform:
- simple: |-
- {
- "id": ${xpath(/order/@id)},
- "item": "${xpath(/order/item)}",
- "fullname": "${xpath(/order/first)} ${xpath(/order/last)}"
- }
- - to:
- uri: log:data
-----
-====
-
-The `pretty` function is used for pretty printing JSON or XML data as a String value.
-For example given the following JSON payload (in a single line): `{"id": 123, "age": 42, "name": "scott"}`
-then `$\{pretty}` will output this nicely formatted:
-
-[source,json]
-----
-{
- "id": 123,
- "age": 42,
- "name": "scott"
-}
-----
-
-
-=== Attachment Functions
-
-From *Camel 4.10* onwards then Camel has built-in attachment functions making it easy to obtain
-details from attachments stored on the Camel Message such as from HTTP file uploads, email with file attachments etc.
-
-This requires having `camel-attachments` JAR on the classpath.
-
-[width="100%",cols="10%,10%,80%",options="header",]
-|====
-|Function |Response Type |Description
-|`attachment.key._OGNL_` | `Object` | Refer to the attachment with the given key on the `Exchange` and invoke its value using a Camel _OGNL syntax_.
-|`attachmentContent(key)` | `Object` | The content of the attachment.
-|`attachmentContentAs(key,type)` | `Object` | The content of the attachment, converted to the given type.
-|`attachmentContentAsText(key)` | `String` | The content of the attachment as text (ie `String`).
-|`attachmentHeader(key,name)` | `Object` | The attachment header with the given name.
-|`attachmentHeaderAs(key,name,type)` | `<T>` | The attachment header with the given name, converted to the given type.
-|`attachmentsKeys` | `Set` | All the attachment keys (filenames).
-|`attachment[key]` | `DataHandler` | The `jakarta.activation.DataHandler` for the given attachment.
-|`attachments.size` | `int` | The number of attachments. Is 0 if there are no attachments.
-|`attachments` | `Map` | All the attachments as a `Map<String,jakarta.activation.DataHandler>`.
-|`setAttachment(key,exp)` | `null` | Sets an attachment with payload from the message body/expression.
-|`clearAttachments` | `null` | Removes all existing attachments on the message.
-|====
-
-The attachment functions are only used with components that supports `javax.attachments` APIs
-such as `camel-cxf`, `camel-http`, `camel-mail`, `camel-platform-http`, `camel-spring-ws`, etc.
-
-NOTE: The _key_ is the attachment filename such as `mydata.xml` or an `int` to lookup by index (0 = first).
-
-Suppose you are using `camel-platform-http` to expose a HTTP endpoint that support file uploads via http multipart,
-then you can use `${attachments.size}` to know how many files are attached. The other functions are used
-to access attachment content, headers and metadata.
-
-The key is either the filename such as `${attachmentContent(mydata.xml)}` or by index (0 based) `${attachmentContent(0)}`.
-
-To know the names of the files you can use `$\{attachmentsKeys}` which returns a `Set` will all the keys.
-
-If the attached file is text based, you can access the payload via `${attachmentContentAsText(mydata.xml)}` or by index `${attachmentContentAsText(0)}`
-which returns the payload as a `String` value.
-
-For example if an XML file was uploaded as `mydata.xml`, then you can access metadata such as
-`${attachment[0].name` returns `mydata.xml`, and `${attachment[0].contentType` return `text/xml`, and
-`${attachment[0].content}` returns the XML payload.
-
-If the content is binary or other formats, you can use Camels xref:manual::type-converter.adoc[Type Converter] to
-convert the payload into the given Object of choice, for example as a byte array: `${attachmentContentAs(mydata.xml,byte[])}`
-
-The `setAttachment` function is used for adding,updating or removing attachments. If the expression is `null` then
-any existing attachment is removed, such as `${setAttachment(mydata.xml,null)}`.
-
-You can add an attachment such as `${setAttachment(mydata2.xml)}`, which then will use the current message body
-as the payload. You can also use an expression such as from a variable `${setAttachment(mydata2.xml,${variable.mydata})}`.
-
-TIP: Camel will automatically detect the content-type of the attachment.
-
-The payload of the attachment can also refer to resources from the file system, or classpath by prefixing with `resource:` as follows
-`${setAttachment(mydata2.xml,resource:file:/inbox/mydata2.xml)}`
-
-To make the file name dynamic you can store the name in a variable such as: `${setAttachment(mydata2.xml,resource:file:${variable.attchmentName})}`
-
-
-=== Base64 Functions
-
-From *Camel 4.18* onwards then Camel has built-in base64 functions to make it easy to encode/decode.
-
-This requires having `camel-base64` JAR on the classpath.
-
-[width="100%",cols="10%,10%,80%",options="header",]
-|====
-|Function |Response Type |Description
-|`base64Decode()` | `byte[]` |Base64 decodes the message body
-|`base64Decode(exp)` | `byte[]` |Base64 decodes the expression
-|`base64Encode()` | `String` |Base64 encodes the message body
-|`base64Encode(exp)` | `String` |Base64 encodes the expression
-|====
-
-Camel comes with functions to use `camel-base64` JAR for base64 encoding and decoding.
-
-For example `${base64Encode(Camel)}` returns `Q2FtZWw=` and you can reverse
-this by `${base64Decode(Q2FtZWw=)}` which then returns `Camel`.
-
-If you want to encode the message body then use `${base64Encode()}`, but you can also
-provide a nested function such as `${base64Encode(${header.myKey})}` to encode a header.
-
-=== HTML Functions
-
-From *Camel 4.21* onwards then Camel has built-in HTML functions to make it easy to clean/parse and decode.
-
-This requires having `camel-jsoup` JAR on the classpath.
-
-[width="100%",cols="10%,10%,80%",options="header",]
-|====
-|Function |Response Type |Description
-|`htmlClean()` | `String` |Cleans the HTML to remove unsafe links and JavaScripts from the message body
-|`htmlClean(exp)` | `String` |Cleans the HTML to remove unsafe links and JavaScripts from the expression
-|`htmlDecode()` | `String` |Decodes the HTML as plain text (removing all HTML tags) that is also suitable as input for AI and LLMs
-|`htmlDecode(exp)` | `String` |Decodes the HTML as plain text (removing all HTML tags) that is also suitable as input for AI and LLMs
-|`htmlParse()` | `org.jsoup.nodes.Document` |Parses the HTML as a JSoup object from the message body
-|`htmlParse(exp)` | `org.jsoup.nodes.Document` |Parses the HTML as a JSoup object from the expression
-|====
-
-Camel comes with functions to use `camel-jsoup` JAR for HTML cleaning and decoding.
-
-For example `${htmlDecode(${header.myHtml})}` will from the header with key `myHtml` decode
-the HTML (removing all tags) into a plain text, which can be fed into LLMs etc.
-
-The `${htmlClean()}` function can be used to remove unwanted tags from the HTML to
-https://jsoup.org/cookbook/cleaning-html/safelist-sanitizer[sanitize untrusted HTML].
-
-The `${htmlParse()`} is used to parse the HTML into a Java `org.jsoup.nodes.Document` structure which is similar to `org.w3c.Document`
-but uses the JSoup API instead.
-
-=== A2A Functions
-
-From *Camel 4.21* onwards, Camel has built-in Agent-to-Agent (A2A) functions to emit task progress and extract data
-from A2A messages, tasks, and agent cards.
-
-This requires having `camel-a2a` JAR on the classpath.
-
-[width="100%",cols="10%,10%,80%",options="header",]
-|====
-|Function |Response Type |Description
-|`a2a:emit(message)` | `String` |Emits an A2A task progress update with `WORKING` state. Requires an active A2A task context.
-|`a2a:emit(state,message)` | `String` |Emits an A2A task progress update with the given task state, such as `WORKING`, `INPUT_REQUIRED`, `COMPLETED`, `FAILED`, `CANCELED`, `REJECTED`, or `AUTH_REQUIRED`.
-|`a2a:text` | `String` |Extracts `TextPart` content from an A2A Task or Message in the message body.
-|`a2a:text(expression)` | `String` |Extracts `TextPart` content from an A2A Task or Message returned by the expression.
-|`a2a:data` | `String` |Extracts `DataPart` content as a JSON string from an A2A Task or Message in the message body.
-|`a2a:data(expression)` | `String` |Extracts `DataPart` content as a JSON string from an A2A Task or Message returned by the expression.
-|`a2a:file` | `String` |Extracts `FilePart` content from an A2A Task or Message in the message body.
-|`a2a:file(expression)` | `String` |Extracts `FilePart` content from an A2A Task or Message returned by the expression.
-|`a2a:card` | `String` |Returns the resolved A2A agent card as a JSON string.
-|`a2a:card.name` | `String` |Returns the resolved A2A agent card name.
-|`a2a:card.description` | `String` |Returns the resolved A2A agent card description.
-|`a2a:card.url` | `String` |Returns the resolved A2A agent card URL.
-|`a2a:card.version` | `String` |Returns the resolved A2A agent card version.
-|`a2a:card.skills` | `String` |Returns the resolved A2A agent card skills as human-readable text.
-|`a2a:card.skills.json` | `String` |Returns the resolved A2A agent card skills as a JSON array string.
-|`a2a:card.iconUrl` | `String` |Returns the resolved A2A agent card icon URL.
-|`a2a:card.documentationUrl` | `String` |Returns the resolved A2A agent card documentation URL.
-|`a2a:card.provider` | `String` |Returns the resolved A2A agent card provider as a JSON string.
-|`a2a:card.capabilities` | `String` |Returns the resolved A2A agent card capabilities as a JSON string.
-|`a2a:card.supportedInterfaces` | `String` |Returns the resolved A2A agent card supported interfaces as a JSON array string.
-|`a2a:card.securitySchemes` | `String` |Returns the resolved A2A agent card security schemes as a JSON object string.
-|`a2a:card.securityRequirements` | `String` |Returns the resolved A2A agent card security requirements as a JSON array string.
-|`a2a:card.security` | `String` |Returns the resolved A2A agent card legacy security field as a JSON array string.
-|====
-
-For example, `${a2a:emit('Searching documents')}` emits a `WORKING` progress event for the current A2A task.
-Use `${a2a:emit(INPUT_REQUIRED,'Please provide your address')}` to emit progress with an explicit task state.
-
-== Built-in Symbols
-
-The following special symbols can be used when escaped with `\` as below:
-
-[width="100%",cols="50%,50%",options="header",]
-|====
-|Symbol |Description
-|`\\n` | To use newline character.
-|`\\t` | To use tab character.
-|`\\r` | To use carriage return character.
-|`\\}` | To use the `}` character as text. This may be needed when building a JSON structure with the simple language.
-|====
-
-For example to use a new-line character in the split function `${split(\\n)}`.
-
-
-== Built-in Operators
-
-The simple language has limited support for operators that are used in predicates to evaluate whether a condition is either _true_ or _false_.
-
-Camel operators require the left value must be enclosed in `${ }`.
-The syntax is:
-
-[source,text]
-----
-${leftValue} OP rightValue
-----
-
-Where the `rightValue` can be a string literal enclosed in `' '`,
-`null`, a constant value or another expression enclosed in `${ }`.
-
-IMPORTANT: There *must* be spaces around the operator.
-
-Camel will automatically type convert the rightValue type to the
-leftValue type, so it is able to e.g., convert a string into a numeric, so
-you can use `>` comparison for numeric values.
-
-=== Comparison Operators
-
-The following comparison operators are supported:
-
-[width="100%",cols="50%,50%",options="header",]
-|====
-|Operator |Description
-|`==` | equals
-|`=~` | equals ignore case (will ignore case when comparing String values)
-|`>` | greater than
-|`>=` | greater than or equals
-|`<` | less than
-|`+<=+` | less than or equals
-|`!=` | not equals
-|`!=~` | not equals ignore case (will ignore case when comparing String values)
-|`~~` | For testing if contains by ignoring case sensitivity in a string-based value
-|`!~~` | For testing if it does not contain by ignoring case sensitivity in a string-based value
-|`contains` | For testing if contains in a string-based value
-|`!contains` | For testing if it does not contain in a string-based value
-|`endsWith` | For testing if the left-hand side string ends with the right-hand string.
-|`!endsWith` | For testing if the left-hand side string does not end with the right-hand string.
-|`in` | For matching if in a set of values, each element must be separated by comma. If you want to include an empty value, then it must be defined using double comma, e.g. `",,bronze,silver,gold"`, which is a set of four values with an empty value and then the three medals.
-|`!in` | For matching if not in a set of values, each element must be separated by comma. If you want to include an empty value, then it must be defined using double comma, e.g. `",,bronze,silver,gold"`, which is a set of four values with an empty value and then the three medals.
-|`is` | For matching if the left-hand side type is an instance of the value.
-|`!is` | For matching if the left-hand side type is not an instance of the value.
-|`range` | For matching if the left-hand side is within a range of values defined as numbers: `from..to`.
-|`!range` | For matching if the left-hand side is not within a range of values defined as numbers: `from..to`.
-|`regex` | For matching against a given regular expression pattern defined as a String value
-|`!regex` | For not matching against a given regular expression pattern defined as a String value
-|`startsWith` | For testing if the left-hand side string starts with the right-hand string.
-|`!startsWith` | For testing if the left-hand side string does not start with the right-hand string.
-|====
-
-=== Numeric Operators
-
-The following numeric operators can be used:
-
-[width="100%",cols="50%,50%",options="header",]
-|====
-|Operator |Description
-|`++` | To increment a number by one. The left-hand side must be a function, otherwise parsed as literal.
-|`--` | To decrement a number by one. The left-hand side must be a function, otherwise parsed as literal.
-|====
-
-These operators are unary and requires to be attached directly next to a function:
-
-[source,text]
-----
-${function}OP
-----
-
-For example to increment the result of the function:
-
-[source,java]
-----
-simple("${header.myNumber}++ > 10");
-----
-
-And the same for decrement:
-
-[source,java]
-----
-simple("${header.myNumber}-- < 10");
-----
-
-
-=== Other Operators
-
-The following other operators can be used:
-
-[width="100%",cols="50%,50%",options="header",]
-|====
-|Operator |Description
-|`? :` | The ternary operator evaluates a condition and returns a value based on the result. If the condition is true, the first value (after `?`) is returned; otherwise, the second value (after `:`) is returned. There must be spaces around both `?` and `:` operators. This is similar to the ternary operator in Java.
-|`?:` | The elvis operator returns the left-hand side if it has an effective Boolean value of true, otherwise it returns the right-hand side. This is useful for providing fallback values when an expression may evaluate to a value with an effective Boolean value of false (such as `null`, `false`, `0`, empty/blank string).
-|`~>` | The chain operator is used in the situations where multiple nested functions need to be applied to a value, while making it easy to read. The value on the left-hand-side is evaluated, and set as the new message body before evaluating the right-hand-side function. This concept is similar to the xref:eips:pipeline-eip.adoc[Pipeline EIP].
-|`?~>` | The null-safe chain operator, where the chain will not continue when a function returned `null`.
-|====
-
-==== Ternary Operator
-
-The syntax for the ternary operator is:
-
-[source,text]
-----
-${leftValue} OP rightValue ? trueValue : falseValue
-----
-
-For example the following ternary operator will return `positive` if header `foo` is greater than 0, otherwise `negative`:
-
-[source,java]
-----
-simple("${header.foo > 0 ? 'positive' : 'negative'}");
-----
-
-Ternary operators can also be nested to handle multiple conditions:
-
-[source,java]
-----
-simple("${header.score >= 90 ? 'A' : ${header.score >= 80 ? 'B' : 'C'}}");
-----
-
-==== Elvis Operator
-
-For example the following elvis operator will return the username header unless its null or empty, which
-then the default value of `Guest` is returned.
-
-[source,java]
-----
-simple("${header.username} ?: 'Guest'");
-----
-
-==== Chain Operator
-
-The syntax for the chain operator is:
-
-[source,text]
-----
-${leftValue} ~> ${rightValue}
-----
-
-And there can be as many chains:
-
-[source,text]
-----
-${leftValue} ~> ${midValue} ~> ${midValue} ~> ${rightValue}
-----
-
-For example if the message body contains `Hello World` then the follow would return `WORLD`:
-
-[source,java]
-----
-simple("${substringAfter('Hello')} ~> ${trim()} ~> ${uppercase()}");
-----
-
-The _null safe_ variant (`?~>`) can be used to avoid `NullPointerException` if it's accepted to not continue the chain when any function returned `null`:
-
-However, many of the simple functions have NPE protection built-in, so this variant is only needed in special situations.
-
-==== Using $param as input parameter value
-
-IMPORTANT: The chain operator will by default pass results via the message body. This usually works well with most functions.
-However, when you need to be in full control then use `$param` as the magic parameter which represents the passed value from the previous function in the chain.
-
-Suppose the message body contains `" Hello World from the Camel "` then the following chain works out of the box:
-
-[source,java]
-----
-simple("${trim()} ~> ${replace('Hello','Hi')} ~> ${split(' ')} ~> ${size()}");
-----
-
-And here is the same example where we explicit use `$param` in the parameters where we need the input to be:
-
-[source,java]
-----
-simple("${trim()} ~> ${replace('Hello','Hi',$param)} ~> ${split($param,' ')} ~> ${size($param)}");
-----
-
-
-=== Boolean Operators
-
-And the following boolean operators can be used to group expressions:
-
-[width="100%",cols="50%,50%",options="header",]
-|====
-|Operator |Description
-|`&&` | The `and` operator is used to group two expressions if both operands evaluates to `true`.
-|`\|\|` | The `or` operator is used to group two expressions if any operand evaluates to `true`.
-|====
-
-The syntax for AND is:
-
-[source,text]
-----
-${leftValue} OP rightValue && ${leftValue} OP rightValue
-----
-
-And the syntax for OR is:
-
-[source,text]
-----
-${leftValue} OP rightValue || ${leftValue} OP rightValue
-----
-
-Some examples:
-
-[source,java]
-----
-// exact equals match
-simple("${header.foo} == 'foo'")
-
-// ignore case when comparing, so if the header has value FOO, this will match
-simple("${header.foo} =~ 'foo'")
-
-// here Camel will type convert '100' into the type of header.bar and if it is an Integer '100' will also be converter to an Integer
-simple("${header.bar} == '100'")
-
-simple("${header.bar} == 100")
-
-// 100 will be converter to the type of header.bar, so we can do > comparison
-simple("${header.bar} > 100")
-
-// if the value of header.bar was 100, value returned will be 101. header.bar itself will not be changed.
-simple("${header.bar}++")
-----
-
-=== Using Operators with different Java Object types
-
-When you compare with different types such as String and int, then you
-have to take a bit of care. Camel will use the type from the left-hand side
-as first priority. And fallback to the right-hand side type if both values
-couldn't be compared based on that type. This means you can flip the values
-to enforce a specific type. Suppose the bar value above is a String.
-
-Then you can flip the equation:
-
-[source,java]
-----
-simple("100 < ${header.bar}")
-----
-
-which then ensures the int type is used as first priority.
-
-This may change in the future if the Camel team improves the binary
-comparison operations to prefer numeric types to String-based. It's
-most often the String type which causes problems when comparing with
-numbers.
-
-[source,java]
-----
-// testing for null
-simple("${header.baz} == null")
-
-// testing for not null
-simple("${header.baz} != null")
-----
-
-And a bit more advanced example where the right value is another
-expression
-
-[source,java]
-----
-simple("${header.date} == ${date:now:yyyyMMdd}")
-
-simple("${header.type} == ${bean:orderService?method=getOrderType}")
-----
-
-And an example with `contains`, testing if the title contains the word Camel
-
-[source,java]
-----
-simple("${header.title} contains 'Camel'")
-----
-
-And an example with regex, testing if the number header is a 4-digit value:
-
-[source,java]
-----
-simple("${header.number} regex '\\d{4}'")
-----
-
-And finally an example if the header equals any of the values in the
-list. Each element must be separated by comma, and no space around.
-This also works for numbers etc., as Camel will convert each element
-into the type of the left-hand side.
-
-[source,java]
-----
-simple("${header.type} in 'gold,silver'")
-----
-
-And for all the last 3, we also support the negate test using not:
-
-[source,java]
-----
-simple("${header.type} !in 'gold,silver'")
-----
-
-And you can test if the type is a certain instance, e.g., for instance a
-String
-
-[source,java]
-----
-simple("${header.type} is 'java.lang.String'")
-----
-
-We have added a shorthand for all `java.lang` types, so you can write it as:
-
-[source,java]
-----
-simple("${header.type} is 'String'")
-----
-
-Ranges are also supported. The range interval requires numbers and both
-from and end are inclusive. For instance, to test whether a value is
-between 100 and 199:
-
-[source,java]
-----
-simple("${header.number} range 100..199")
-----
-
-Notice we use `..` in the range without spaces. It is based on the same
-syntax as Groovy.
-
-[source,java]
-----
-simple("${header.number} range '100..199'")
-----
-
-As the XML DSL does not have all the power as the Java DSL with all
-its various builder methods, you have to resort to using some other
-languages for testing with simple operators. Now you can do this with the simple
-language. In the sample below, we want to test it if the header is a widget
-order:
-
-._XML-only:_
-[source,xml]
-----
-<from uri="seda:orders">
- <filter>
- <simple>${header.type} == 'widget'</simple>
- <to uri="bean:orderService?method=handleWidget"/>
- </filter>
-</from>
-----
-
-=== Combining multiple expression using AND / OR Operator
-
-If you have two expressions you can combine them with the `&&` (and) or `||` (or) operator.
-
-For instance:
-
-[source,java]
------
-simple("${header.title} contains 'Camel' && ${header.type} == 'gold'")
------
-
-And of course the `||` is also supported. The sample would be:
-
-[source,java]
------
-simple("${header.title} contains 'Camel' || ${header.type} == 'gold'")
------
-
-== Init Blocks
-
-Starting from *Camel 4.18* you can in the top of your Simple expressions declare an _initialization_ block that are used
-to define a set of local variables that are pre-computed, and can be used in the following Simple expression. This allows
-to reuse variables, and also avoid making the simple expression complicated when having inlined functions, and in general
-make the simple expression easier to maintain and understand.
-
-IMPORTANT: Init Blocks is not supported with xref:csimple-language.adoc[CSimple] language.
-
-NOTE: The init block declaration `$init{ ... }init$` may be changed in the future.
-
-The _init block_ is declared as follows:
-
-[source,text]
-----
-$init{
- // init block
- // goes here
- // ...
-}init$
-// here is the regular simple expression
-----
-
-Notice how the block uses the `$init{` ... `}init$` markers to indicate the start and end of the block.
-
-Inside the init block, then you can assign local variables in the syntax `$key := <statement>;` where you can then use simple language to compute
-the value of the variable.
-
-IMPORTANT: Each statement must end with semicolon and new-line (`;\n`). You can only have 1 statement per line.
-This makes the init block more similar to Java programming language,
-and it was also necessary to make this work for the internal simple parser used by Camel.
-
-Here are a couple of examples:
-
-[source,text]
-----
-$init{
- $cheese := 'Hello ${body}';
- $minAge := 18;
- $foo := ${uppercase('Hello ${body}')};
- $bar := ${header.code > 999 ? 'Gold' : 'Silver'};
-}init$
-----
-
-You can have Java style code comments in the init block using `// comment here` as follows:
-
-[source,text]
-----
-$init{
- // minimum age to drive
- $minAge := 18;
-
- // say hello to my friend
- $foo := ${uppercase('Hello ${body}')};
-
- // either gold or silver
- $bar := ${header.code > 999 ? 'Gold' : 'Silver'};
-}init$
-----
-
-The local variables can then easily be used in the Simple language either using the `${variable.foo}` syntax
-or the shorthand syntax `$foo`.
-
-For example as below where we do a basic JSON mapping:
-
-[source,text]
-----
-$init{
- $greeting := ${uppercase('Hello ${body}')};
- $level := ${header.code > 999 ? 'Gold' : 'Silver'};
-}init$
-{
- "message": "$greeting",
- "status": "$level"
-}
-----
-
-The assigned variables from the _init block_ are stored as xref:manual::variables.adoc[Variables] on the `Exchange` which
-allows to use the variables later in the Camel routes.
-
-For example:
-
-[tabs]
-====
-Java::
-+
-[source,java]
-----
-from("direct:welcome")
- .transform().simple(
- """
- $init{
- $greeting := ${uppercase('Hello ${body}')};
- $level := ${header.code > 999 ? 'Gold' : 'Silver'};
- }init$
- {
- "message": "$greeting",
- "status": "$level"
- }
- """)
- .to("kafka:welcome")
- .log("Sending welcome email to customer with status ${variable.level}");
-----
-
-XML::
-+
-[source,xml]
-----
-<route>
- <from uri="direct:welcome"/>
- <transform>
- <simple>
- $init{
- $greeting := ${uppercase('Hello ${body}')};
- $level := ${header.code > 999 ? 'Gold' : 'Silver'};
- }init$
- {
- "message": "$greeting",
- "status": "$level"
- }
- </simple>
- </transform>
- <to uri="kafka:welcome"/>
- <log message="Sending welcome email to customer with status ${variable.level}"/>
-</route>
-----
-
-YAML::
-+
-[source,yaml]
-----
-- from:
- uri: direct:welcome
- steps:
- - transform:
- simple:
- expression: |-
- $init{
- $greeting := ${uppercase('Hello ${body}')};
- $level := ${header.code > 999 ? 'Gold' : 'Silver'};
- }init$
- {
- "message": "$greeting",
- "status": "$level"
- }
- - to:
- uri: kafka:welcome
- - log:
- message: "Sending welcome email to customer with status ${variable.level}"
-----
-====
-
-Notice how we can refer to the variable (`$level`) in the log statement using the standard `${variable.xxx}` syntax.
-
-TIP: Instead of inlining the simple script in the route, you can externalize this to a source file such as `mymapping.txt`
-and then refer to the file such as `resource:classpath:mymapping.txt` where the file is located in the root classpath (can also be located in sub packages).
-
-=== Init Blocks with custom functions
-
-You can also declare custom functions using
-
-Inside the init block, it is a lso possible to define custom functions in the syntax `$nane ~:= <statement>;` where you can then use simple language to declare
-the structure of the function. Then you can later use these custom functions in your simple language expressions.
-
-For example to create a function that can cleanup a `String` value:
-
-[source,text]
-----
-$init{
- $cleanUp ~:= ${trim()} ~> ${normalizeWhitespace()} ~> ${uppercase()};
-}init$
-----
-
-The function will by default use the message body as the input, such that the following:
-
-[source,java]
-----
-simple("Incoming message: $cleanUp()");
-----
-
-Would then call the _clean_ function with the message body as the input, which will then be used for trim, normalize and upper-casing.
-
-A custom function can also use a **single** parameter, however then the syntax must use `${name(...)}` style, such as:
-
-[source,java]
-----
-simple("Incoming message: ${cleanUp(' Please clean this text for me ')}");
-----
-
-Here the parameter is a fixed `String` but you can also pass in other type of value such as a number, boolean, or even a nested function.
-
-==== Calling custom functions from custom functions
-
-It is also possible to reuse custom functions from other functions using `${function(name)}`, such shown:
-
-[source,text]
-----
-$init{
- $cleanUp ~:= ${trim()} ~> ${normalizeWhitespace()} ~> ${uppercase()};
- $count ~:= ${function(cleanUp)} ~> ${split(' ')} ~> ${size()};
-}init$
-----
-
-Here the `$count` is declared as a function which calls the cleanUp function and then counts the words via split and size functions.
-
-Instead of using `${function(name)}` you can also same syntax as the built-in Simple functions, as follows:
-
-[source,text]
-----
-$init{
- $cleanUp ~:= ${trim()} ~> ${normalizeWhitespace()} ~> ${uppercase()};
- $count ~:= ${cleanUp()} ~> ${split(' ')} ~> ${size()};
-}init$
-----
-
-Notice how `${cleanUp()}` despite being a custom function is using the same syntax as all the built-in functions that are being used, for example:
- `${trim()}`.
-
-
-== OGNL Expression Support
-
-The xref:simple-language.adoc[Simple] and xref:simple-language.adoc[Bean] languages support a _OGNL like_ notation for invoking methods (using reflection) in a fluent builder like style.
-
-https://en.wikipedia.org/wiki/OGNL[OGNL] (Object-Graph Navigation Language) is a powerful expression language used in Java. In Camel you can use OGNL dot notation to invoke methods. If you for instance have a body that contains a POJO that has a `getFamilyName` method then
-you can construct the Simple syntax as follows:
-
-[source,java]
-----
-simple("${body.familyName}")
-----
-
-Or use similar syntax as in Java:
-
-[source,java]
-----
-simple("${body.getFamilyName()}")
-----
-
-Camel's OGNL support is for invoking methods only. You cannot access fields. Camel support accessing the length field of Java arrays.
-
-[IMPORTANT]
-====
-When using *OGNL* then `camel-bean` JAR is required to be on the classpath.
-====
-
-=== Built-in Functions supporting OGNL
-
-The following functions support _OGNL syntax_:
-
-[width="100%",options="header",]
-|====
-|Variable | Response Type | Description
-|`attachment.key._OGNL_` | `Object` | Refer to the attachment with the given key on the `Exchange`. This requires having camel-attachments JAR on classpath.
-|`bodyAs(type)` | `<T>` | The message body converted to the given type
-|`body` | `Object` | The message body
-|`camelContext` | `CamelContext` | The `CamelContext`
-|`convertTo(exp,type)` | `<T>` | Converts the expression to the specified type
-|`exception` | `Throwable` | If the exchange failed due to an exception
-|`exchangeProperty.key` | `Object` | The value from the exchange property with the given key
-|`exchange` | `Exchange` | The current `Exchange`
-|`header.key` | `Object` | The value from the message header with the given key
-|`mandatoryBodyAs(type)` | `<T>` | The message body converted to the given type
-|`messageAs(type)` | `<T>` | The `org.apache.camel.Message` as a specialized instance
-|`variable.key` | `Object` | The value from the variable with the given key
-|====
-
-=== Basic OGNL examples
-
-Suppose the Message body contains a POJO which has a `getAddress()`
-method. Then you can use Camel OGNL notation to access the address object:
-
-[source,java]
-----
-simple("${body.address}")
-simple("${body.address.street}")
-simple("${body.address.zip}")
-----
-
-Camel understands the shorthand names for getters, but you can invoke
-any method or use the real name such as:
-
-[source,java]
-----
-simple("${body.address}")
-simple("${body.getAddress.getStreet}")
-simple("${body.getAddress().getStreet()}")
-simple("${body.address.getZip}")
-simple("${body.doSomething}")
-----
-
-You can also use the null safe operator (`?.`) to avoid `NullPointerException` if, for example,
-the body does NOT have an address:
-
-[source,java]
-----
-simple("${body?.address?.street}")
-----
-
-=== Advanced OGNL examples
-
-It is also possible to index in `Map` or `List` types, so you can do:
-
-[source,java]
-----
-simple("${body[foo].name}")
-----
-
-To assume the body is `Map` based and look up the value with `foo` as
-key, and invoke the `getName` method on that value.
-
-If the key has space, then you *must* enclose the key with quotes, for
-example, 'foo bar':
-
-[source,java]
-----
-simple("${body['foo bar'].name}")
-----
-
-You can access the `Map` or `List` objects directly using their key name
-(with or without dots) :
-
-[source,java]
-----
-simple("${body[foo]}")
-simple("${body[this.is.foo]}")
-----
-
-Suppose there was no value with the key `foo` then you can use the null
-safe operator to avoid the NPE as shown:
-
-[source,java]
-----
-simple("${body[foo]?.name}")
-----
-
-You can also access `List` types, for example, to get lines from the
-address you can do:
-
-[source,java]
-----
-simple("${body.address.lines[0]}")
-simple("${body.address.lines[1]}")
-simple("${body.address.lines[2]}")
-----
-
-There is a special `last` keyword which can be used to get the last
-value from a list.
-
-[source,java]
-----
-simple("${body.address.lines[last]}")
-----
-
-And to get the 2nd last you can subtract a number, so we can use
-`last-1` to indicate this:
-
-[source,java]
-----
-simple("${body.address.lines[last-1]}")
-----
-
-And the third last is, of course:
-
-[source,java]
-----
-simple("${body.address.lines[last-2]}")
-----
-
-And you can call the size method on the list with
-
-[source,java]
-----
-simple("${body.address.lines.size}")
-----
-
-Camel supports the length field for Java arrays as well, e.g.:
-
-[source,java]
-----
-String[] lines = new String[]{"foo", "bar", "cat"};
-exchange.getMessage().setBody(lines);
-
-simple("There are ${body.length} lines")
-----
-
-[TIP]
-====
-You can also use the *length* function from *Camel 4.18*: `simple("There are ${length()} lines")`
-====
-
-And yes, you can combine this with the Simple operators such as checking if a zip code is larger than 1000:
-
-[source,java]
-----
-simple("${body.address.zip} > 1000")
-----
-
-
-== EIP Examples
-
-Below we filter based on a header value:
-
-[tabs]
-====
-Java::
-+
-[source,java]
-----
-from("seda:orders")
- .filter().simple("${header.foo}")
- .to("seda:fooOrders");
-----
-
-XML::
-+
-[source,xml]
-----
-<route>
- <from uri="seda:orders"/>
- <filter>
- <simple>${header.foo}</simple>
- <to uri="seda:fooOrders"/>
- </filter>
-</route>
-----
-
-YAML::
-+
-[source,yaml]
-----
-- route:
- from:
- uri: seda:orders
- steps:
- - filter:
- simple: "${header.foo}"
- steps:
- - to:
- uri: seda:fooOrders
-----
-====
-
-The Simple language can be used for the predicate test above in the
-Message Filter pattern, where we test if the
-in message has a `foo` header (a header with the key `foo` exists). If
-the expression evaluates to `*true*`, then the message is routed to the
-`seda:fooOrders` endpoint, otherwise the message is dropped.
-
-You can also use the simple language for simple text concatenations such as:
-
-[tabs]
-====
-Java::
-+
-[source,java]
-----
-from("direct:hello")
- .transform().simple("Hello ${header.user} how are you?")
- .to("mock:reply");
-----
-
-XML::
-+
-[source,xml]
-----
-<route>
- <from uri="direct:hello"/>
- <transform>
- <simple>Hello ${header.user} how are you?</simple>
- </transform>
- <to uri="mock:reply"/>
-</route>
-----
-
-YAML::
-+
-[source,yaml]
-----
-- route:
- from:
- uri: direct:hello
- steps:
- - transform:
- simple: "Hello ${header.user} how are you?"
- - to:
- uri: mock:reply
-----
-====
-
-Notice that we must use `${ }` placeholders in the expression now to
-allow Camel to parse it correctly.
-
-And this sample uses the date command to output current date.
-
-[tabs]
-====
-Java::
-+
-[source,java]
-----
-from("direct:hello")
- .transform().simple("The today is ${date:now:yyyyMMdd} and it is a great day.")
- .to("mock:reply");
-----
-
-XML::
-+
-[source,xml]
-----
-<route>
- <from uri="direct:hello"/>
- <transform>
- <simple>The today is ${date:now:yyyyMMdd} and it is a great day.</simple>
- </transform>
- <to uri="mock:reply"/>
-</route>
-----
-
-YAML::
-+
-[source,yaml]
-----
-- route:
- from:
- uri: direct:hello
- steps:
- - transform:
- simple: "The today is ${date:now:yyyyMMdd} and it is a great day."
- - to:
- uri: mock:reply
-----
-====
-
-And in the sample below, we invoke the bean language to invoke a method
-on a bean to be included in the returned string:
-
-[tabs]
-====
-Java::
-+
-[source,java]
-----
-from("direct:order")
- .transform().simple("OrderId: ${bean:orderIdGenerator}")
- .to("mock:reply");
-----
-
-XML::
-+
-[source,xml]
-----
-<route>
- <from uri="direct:order"/>
- <transform>
- <simple>OrderId: ${bean:orderIdGenerator}</simple>
- </transform>
- <to uri="mock:reply"/>
-</route>
-----
-
-YAML::
-+
-[source,yaml]
-----
-- route:
- from:
- uri: direct:order
- steps:
- - transform:
- simple: "OrderId: ${bean:orderIdGenerator}"
- - to:
- uri: mock:reply
-----
-====
-
-Where `orderIdGenerator` is the id of the bean registered in the
-Registry. If using Spring, then it is the Spring bean
-id.
-
-If we want to declare which method to invoke on the order id generator
-bean we must prepend `.method name` such as below where we invoke the
-`generateId` method.
-
-[tabs]
-====
-Java::
-+
-[source,java]
-----
-from("direct:order")
- .transform().simple("OrderId: ${bean:orderIdGenerator.generateId}")
- .to("mock:reply");
-----
-
-XML::
-+
-[source,xml]
-----
-<route>
- <from uri="direct:order"/>
- <transform>
- <simple>OrderId: ${bean:orderIdGenerator.generateId}</simple>
- </transform>
- <to uri="mock:reply"/>
-</route>
-----
-
-YAML::
-+
-[source,yaml]
-----
-- route:
- from:
- uri: direct:order
- steps:
- - transform:
- simple: "OrderId: ${bean:orderIdGenerator.generateId}"
- - to:
- uri: mock:reply
-----
-====
-
-We can use the `?method=methodname` option that we are familiar with the
-xref:components::bean-component.adoc[Bean] component itself:
-
-[tabs]
-====
-Java::
-+
-[source,java]
-----
-from("direct:order")
- .transform().simple("OrderId: ${bean:orderIdGenerator?method=generateId}")
- .to("mock:reply");
-----
-
-XML::
-+
-[source,xml]
-----
-<route>
- <from uri="direct:order"/>
- <transform>
- <simple>OrderId: ${bean:orderIdGenerator?method=generateId}</simple>
- </transform>
- <to uri="mock:reply"/>
-</route>
-----
-
-YAML::
-+
-[source,yaml]
-----
-- route:
- from:
- uri: direct:order
- steps:
- - transform:
- simple: "OrderId: ${bean:orderIdGenerator?method=generateId}"
- - to:
- uri: mock:reply
-----
-====
-
-You can also convert the body to a given
-type, for example, to ensure that it is a String you can do:
-
-[source,xml]
-----
-<transform>
- <simple>Hello ${bodyAs(String)} how are you?</simple>
-</transform>
-----
-
-There are a few types which have a shorthand notation, so we can use
-`String` instead of `java.lang.String`. These are:
-`byte[], String, Integer, Long`. All other types must use their FQN
-name, e.g. `org.w3c.dom.Document`.
-
-It is also possible to look up a value from a header `Map`:
-
-[source,xml]
-----
-<transform>
- <simple>The gold value is ${header.type[gold]}</simple>
-</transform>
-----
-
-In the code above we look up the header with name `type` and regard it as
-a `java.util.Map` and we then look up with the key `gold` and return the
-value. If the header is not convertible to Map, an exception is thrown. If the
-header with name `type` does not exist `null` is returned.
-
-You can nest functions, such as shown below:
-
-[source,xml]
-----
-<setHeader name="myHeader">
- <simple>${properties:${header.someKey}}</simple>
-</setHeader>
-----
-
-== Using Substring Function
-
-You can use the `substring` function to more easily clip the message body.
-For example if the message body contains the following 10 letters `ABCDEFGHIJ` then:
-
-[source,xml]
-----
-<setBody>
- <simple>${substring(3)}</simple>
-</setBody>
-----
-
-Then the message body after the substring will be `DEFGHIJ`.
-If you want to clip from the end instead, then use negative values such as `substring(-3)`.
-
-You can also clip from both ends at the same time such as `substring(1,-1)` that will clip the first and last character in the String.
-
-If the number is higher than the length of the message body, then an empty string is returned, for example `substring(99)`.
-
-Instead of the message body then a simple expression can be nested as input, for example, using a variable, as shown below:
-
-[source,xml]
-----
-<setBody>
- <simple>${substring(1,-1,${variable.foo})}</simple>
-</setBody>
-----
-
-[#_replacing_double_and_single_quotes]
-== Replacing double and single quotes
-
-You can use the `replace` function to more easily replace all single or double quotes in the message body,
-using the XML escape syntax. This avoids to fiddle with enclosing a double quote or single quotes with outer quotes,
-that can get confusing to be correct as you may need to escape the quotes as well. So instead you can use the XML escape
-syntax where double quote is `\"` and single quote is `\'` (yeah that is the name).
-
-For example, to replace all double quotes with single quotes:
-
-[tabs]
-====
-Java::
-+
-[source,java]
-----
-from("direct:order")
- .transform().simple("${replace(" , ')}")
- .to("mock:reply");
-----
-
-XML::
-+
-[source,xml]
-----
-<route>
- <from uri="direct:order"/>
- <transform>
- <simple>${replace(&quot; , &apos;)}</simple>
- </transform>
- <to uri="mock:reply"/>
-</route>
-----
-
-YAML::
-+
-[source,yaml]
-----
-- route:
- from:
- uri: direct:order
- steps:
- - transform:
- simple: "${replace(" , ')}"
- - to:
- uri: mock:reply
-----
-====
-
-And to replace all single quotes with double quotes:
-
-[source,xml]
-----
-<setBody>
- <simple>${replace(' , ")}</simple>
-</setBody>
-----
-
-Or to remove all double quotes:
-
-[source,xml]
-----
-<setBody>
- <simple>${replace(" , ∅)}</simple>
-</setBody>
-----
-
-== Setting the result type
-
-You can now provide a result type to the xref:simple-language.adoc[Simple]
-expression, which means the result of the evaluation will be converted
-to the desired type. This is most usable to define types such as
-booleans, integers, etc.
-
-For example, to set a header as a boolean type, you can do:
-
-._Java-only: setting result type on a simple expression_
-[source,java]
-----
-.setHeader("cool", simple("true", Boolean.class))
-----
-
-And in XML DSL
-
-[source,xml]
-----
-<setHeader name="cool">
- <!-- use resultType to indicate that the type should be a java.lang.Boolean -->
- <simple resultType="java.lang.Boolean">true</simple>
-</setHeader>
-----
-
-== Using new lines or tabs in XML DSLs
-
-It is easier to specify new lines or tabs in
-XML DSLs as you can escape the value now
-
-[source,xml]
-----
-<transform>
- <simple>The following text\nis on a new line</simple>
-</transform>
-----
-
-== Leading and trailing whitespace handling
-
-The trim attribute of the expression can be
-used to control whether the leading and trailing whitespace characters
-are removed or preserved. The default value is true, which removes the
-whitespace characters.
-
-[source,xml]
-----
-<setBody>
- <simple trim="false">You get some trailing whitespace characters. </simple>
-</setBody>
-----
-
-== Loading script from external resource
-
-You can externalize the script and have Camel load it from a resource
-such as `"classpath:"`, `"file:"`, or `"http:"`.
-This is done using the following syntax: `"resource:scheme:location"`,
-e.g., to refer to a file on the classpath you can do:
-
-._Java-only: loading a simple script from an external resource_
-[source,java]
-----
-.setHeader("myHeader").simple("resource:classpath:mysimple.txt")
-----
-
-== Pretty XML or JSON
-
-From *Camel 4.18* onwards then the Simple language can _pretty format_ the output.
-
-You turn this on via the `pretty` option set to `true`:
-
-[tabs]
-====
-Java::
-+
-[source,java]
-----
-from("direct:json")
- .setBody().simple("{ \"name\": \"Jack\", \"age\": 44 }", true)
- .to("mock:result");
-----
-
-XML::
-+
-[source,xml]
-----
-<route>
- <from uri="direct:json"/>
- <setBody>
- <simple pretty="true">{ "name": "Jack", "age": 44 }</simple>
- </setBody>
- <to uri="mock:result"/>
-</route>
-----
-
-YAML::
-+
-[source,yaml]
-----
-- route:
- from:
- uri: direct:json
- steps:
- - setBody:
- simple:
- expression: "{ \"name\": \"Jack\", \"age\": 44 }"
- pretty: true
- - to:
- uri: mock:result
-----
-====
-
-This works with XML, JSON and text content:
-
-._Java-only: pretty formatting with different content types_
-[source,java]
-----
-from("direct:xml")
- .setBody().simple("<person><name>Jack</name></person>", true)
- .to("mock:result");
-
-from("direct:text")
- .setBody().simple("Hello ${body}", true)
- .to("mock:result");
-----
-
-== Adding custom functions to Simple language
-
-You can add custom functions to the Simple language by adding to the `org.apache.camel.spi.SimpleFunctionRegistry`.
-
-A custom function should either be an `Expression` or a `org.apache.camel.spi.SimpleFunction` implementation.
-
-You may want to use `Expression` when you build custom functions from the built-in functions in Camel.
-This can be done programmatically such as:
-
-._Java-only: registering a custom function with SimpleFunctionRegistry_
-[source,java]
-----
-SimpleFunctionRegistry reg = PluginHelper.getSimpleFunctionRegistry(getCamelContext());
-
-reg.addFunction("foo", new ExpressionAdapter() {
- @Override
- public Object evaluate(Exchange exchange) {
- return "I was here " + exchange.getMessage().getBody();
- }
-});
-----
-
-Here we add a custom function named `foo` which is implemented as a `org.apache.camel.Expression` which conveniently
-can be done by using the `org.apache.camel.support.ExpressionAdapter` class as above.
-
-The foo function can now be used in simple such as:
-
-[tabs]
-====
-Java::
-+
-[source,java]
-----
-from("direct:start")
- .setBody(simple("Hello ${foo}"))
- .to("mock:result");
-----
-
-XML::
-+
-[source,xml]
-----
-<route>
- <from uri="direct:start"/>
- <setBody>
- <simple>Hello ${foo}</simple>
- </setBody>
- <to uri="mock:result"/>
-</route>
-----
-
-YAML::
-+
-[source,yaml]
-----
-- route:
- from:
- uri: direct:start
- steps:
- - setBody:
- simple: "Hello ${foo}"
- - to:
- uri: mock:result
-----
-====
-
-Notice how the foo function is used just like it was a built-in function using `$\{foo}` syntax.
-
-Since a custom function is just an `Expression` then it's possible to build custom functions from
-all the Camel languages such as Groovy, JSonPath and even Simple as well.
-
-._Java-only: building a custom function from Simple expressions_
-[source,java]
-----
-var bar = context.resolveLanguage("simple").createExpression("${trim()} ~> ${normalizeWhitespace()} ~> ${capitalize()} ~> ${quote()}");
-reg.addFunction("bar", bar);
-----
-
-The `bar` function is build using simple functions using the `~>` chain operators to perform a sequence of functions on the payload.
-
-Custom functions will by default use the message body as the payload. But they also support a single parameter as the input,
-which allows to provide the input as fixed value such as a string literal or to refer to an existing header or variable.
-
-For example the foo function uses variable with name `msg` as the input:
-
-[tabs]
-====
-Java::
-+
-[source,java]
-----
-from("direct:start")
- .setVariable("msg", constant("Moon"))
- .setBody(simple("Bye ${foo(${variable.msg})}"))
- .to("mock:result");
-----
-
-XML::
-+
-[source,xml]
-----
-<route>
- <from uri="direct:start"/>
- <setVariable name="msg">
- <constant>Moon</constant>
- </setVariable>
- <setBody>
- <simple>Bye ${foo(${variable.msg})}</simple>
- </setBody>
- <to uri="mock:result"/>
-</route>
-----
-
-YAML::
-+
-[source,yaml]
-----
-- route:
- from:
- uri: direct:start
- steps:
- - setVariable:
- name: msg
- constant: "Moon"
- - setBody:
- simple: "Bye ${foo(${variable.msg})}"
- - to:
- uri: mock:result
-----
-====
-
-And instead of nesting the variable inside the foo function, we can also use the `~>` chain operator:
-
-[tabs]
-====
-Java::
-+
-[source,java]
-----
-from("direct:start")
- .setVariable("msg", constant("Moon"))
- .setBody(simple("Bye ${variable.msg} ~> ${foo}"))
- .to("mock:result");
-----
-
-XML::
-+
-[source,xml]
-----
-<route>
- <from uri="direct:start"/>
- <setVariable name="msg">
- <constant>Moon</constant>
- </setVariable>
- <setBody>
- <simple>Bye ${variable.msg} ~> ${foo}</simple>
- </setBody>
- <to uri="mock:result"/>
-</route>
-----
-
-YAML::
-+
-[source,yaml]
-----
-- route:
- from:
- uri: direct:start
- steps:
- - setVariable:
- name: msg
- constant: "Moon"
- - setBody:
- simple: "Bye ${variable.msg} ~> ${foo}"
- - to:
- uri: mock:result
-----
-====
-
-You can also build custom functions as a Java class as below:
-
-._Java-only: implementing SimpleFunction interface_
-[source,java]
-----
-public class FooSimpleFunction implements SimpleFunction {
-
- @Override
- public String getName() {
- return "foo";
- }
-
- @Override
- public Object apply(Exchange exchange, Object input) throws Exception {
- return "I was here " + input;
- }
-}
-----
-
-This gives you the full power to implement the function logic in standard Java.
-
-This function can be added programmatically:
-
-._Java-only: adding a SimpleFunction to the registry_
-[source,java]
-----
-SimpleFunctionRegistry reg = PluginHelper.getSimpleFunctionRegistry(getCamelContext());
-
-reg.addFunction(new FooSimpleFunction());
-----
-
-TIP: The custom function can then be made discoverable by Camel by dependency injection.
-If you use standalone Camel you can add `@BindToRegistry("foo-function")` to the class.
-For Spring Boot use `@Component` or `@Service` and Quarkus you can for example use `@ApplicationScoped`.
-
-
-== JavaScript Validator
-
-The `camel-catalog` JAR includes a self-contained JavaScript validator for the Simple language.
-It can syntax-check expressions and predicates in any browser or Node.js environment — no Java backend required.
-
-The files are located in the JAR under:
-
-----
-org/apache/camel/catalog/simple/camel-simple-validator.js
-org/apache/camel/catalog/simple/camel-simple-validator.html
-----
-
-The `.js` file is auto-generated from `simple.json` during the Maven build, so its list of functions and operators
-always matches the current Camel version.
-
-=== API
-
-The validator exposes these functions:
-
-* `validate(input, mode)` — validate a Simple expression or predicate.
- `mode` is `'expression'` (default) or `'predicate'`.
- Returns `{ valid: boolean, diagnostics: [...] }`.
-* `complete(input, pos)` — return completion suggestions at the given cursor position.
-* `getFunctions()` — return the list of known Simple function names.
-* `getOperators()` — return the list of known Simple operators with their kind and description.
-
-=== Usage in Node.js
-
-[source,javascript]
-----
-const { validate, complete } = require('./camel-simple-validator.js');
-
-const result = validate("${body} == 'hello'", 'predicate');
-console.log(result.valid); // true
-console.log(result.diagnostics); // []
-
-const bad = validate("${bdy}", 'expression');
-console.log(bad.valid); // false
-console.log(bad.diagnostics[0].message); // "Unknown function 'bdy', did you mean 'body'?"
-----
-
-=== Usage in a browser
-
-Extract `camel-simple-validator.html` from the JAR and open it in a browser.
-It provides an interactive form where you can type Simple expressions and validate them with instant feedback.
+* xref:simple-functions.adoc[Built-in Functions] — All function categories (Core, Array/List, Boolean, Date/Time, Math, String, XML/JSON, and more)
+* xref:simple-operators.adoc[Built-in Operators] — Comparison, numeric, ternary, elvis, chain, and boolean operators
+* xref:simple-ognl.adoc[OGNL Expressions] — OGNL dot-notation for invoking methods on POJOs
+* xref:simple-advanced.adoc[Advanced Features] — Init blocks, EIP examples, custom functions, and JavaScript validator
== Dependencies
diff --git a/core/camel-core-languages/src/main/docs/modules/languages/pages/simple-ognl.adoc b/core/camel-core-languages/src/main/docs/modules/languages/pages/simple-ognl.adoc
new file mode 100644
index 000000000000..56a429400d4f
--- /dev/null
+++ b/core/camel-core-languages/src/main/docs/modules/languages/pages/simple-ognl.adoc
@@ -0,0 +1,183 @@
+= Simple - OGNL Expressions
+:tabs-sync-option:
+
+xref:simple-language.adoc[Back to Simple Language]
+
+== OGNL Expression Support
+
+The xref:simple-language.adoc[Simple] and xref:simple-language.adoc[Bean] languages support a _OGNL like_ notation for invoking methods (using reflection) in a fluent builder like style.
+
+https://en.wikipedia.org/wiki/OGNL[OGNL] (Object-Graph Navigation Language) is a powerful expression language used in Java. In Camel you can use OGNL dot notation to invoke methods. If you for instance have a body that contains a POJO that has a `getFamilyName` method then
+you can construct the Simple syntax as follows:
+
+[source,java]
+----
+simple("${body.familyName}")
+----
+
+Or use similar syntax as in Java:
+
+[source,java]
+----
+simple("${body.getFamilyName()}")
+----
+
+Camel's OGNL support is for invoking methods only. You cannot access fields. Camel support accessing the length field of Java arrays.
+
+[IMPORTANT]
+====
+When using *OGNL* then `camel-bean` JAR is required to be on the classpath.
+====
+
+=== Built-in Functions supporting OGNL
+
+The following functions support _OGNL syntax_:
+
+[width="100%",options="header",]
+|====
+|Variable | Response Type | Description
+|`attachment.key._OGNL_` | `Object` | Refer to the attachment with the given key on the `Exchange`. This requires having camel-attachments JAR on classpath.
+|`bodyAs(type)` | `<T>` | The message body converted to the given type
+|`body` | `Object` | The message body
+|`camelContext` | `CamelContext` | The `CamelContext`
+|`convertTo(exp,type)` | `<T>` | Converts the expression to the specified type
+|`exception` | `Throwable` | If the exchange failed due to an exception
+|`exchangeProperty.key` | `Object` | The value from the exchange property with the given key
+|`exchange` | `Exchange` | The current `Exchange`
+|`header.key` | `Object` | The value from the message header with the given key
+|`mandatoryBodyAs(type)` | `<T>` | The message body converted to the given type
+|`messageAs(type)` | `<T>` | The `org.apache.camel.Message` as a specialized instance
+|`variable.key` | `Object` | The value from the variable with the given key
+|====
+
+=== Basic OGNL examples
+
+Suppose the Message body contains a POJO which has a `getAddress()`
+method. Then you can use Camel OGNL notation to access the address object:
+
+[source,java]
+----
+simple("${body.address}")
+simple("${body.address.street}")
+simple("${body.address.zip}")
+----
+
+Camel understands the shorthand names for getters, but you can invoke
+any method or use the real name such as:
+
+[source,java]
+----
+simple("${body.address}")
+simple("${body.getAddress.getStreet}")
+simple("${body.getAddress().getStreet()}")
+simple("${body.address.getZip}")
+simple("${body.doSomething}")
+----
+
+You can also use the null safe operator (`?.`) to avoid `NullPointerException` if, for example,
+the body does NOT have an address:
+
+[source,java]
+----
+simple("${body?.address?.street}")
+----
+
+=== Advanced OGNL examples
+
+It is also possible to index in `Map` or `List` types, so you can do:
+
+[source,java]
+----
+simple("${body[foo].name}")
+----
+
+To assume the body is `Map` based and look up the value with `foo` as
+key, and invoke the `getName` method on that value.
+
+If the key has space, then you *must* enclose the key with quotes, for
+example, 'foo bar':
+
+[source,java]
+----
+simple("${body['foo bar'].name}")
+----
+
+You can access the `Map` or `List` objects directly using their key name
+(with or without dots) :
+
+[source,java]
+----
+simple("${body[foo]}")
+simple("${body[this.is.foo]}")
+----
+
+Suppose there was no value with the key `foo` then you can use the null
+safe operator to avoid the NPE as shown:
+
+[source,java]
+----
+simple("${body[foo]?.name}")
+----
+
+You can also access `List` types, for example, to get lines from the
+address you can do:
+
+[source,java]
+----
+simple("${body.address.lines[0]}")
+simple("${body.address.lines[1]}")
+simple("${body.address.lines[2]}")
+----
+
+There is a special `last` keyword which can be used to get the last
+value from a list.
+
+[source,java]
+----
+simple("${body.address.lines[last]}")
+----
+
+And to get the 2nd last you can subtract a number, so we can use
+`last-1` to indicate this:
+
+[source,java]
+----
+simple("${body.address.lines[last-1]}")
+----
+
+And the third last is, of course:
+
+[source,java]
+----
+simple("${body.address.lines[last-2]}")
+----
+
+And you can call the size method on the list with
+
+[source,java]
+----
+simple("${body.address.lines.size}")
+----
+
+Camel supports the length field for Java arrays as well, e.g.:
+
+[source,java]
+----
+String[] lines = new String[]{"foo", "bar", "cat"};
+exchange.getMessage().setBody(lines);
+
+simple("There are ${body.length} lines")
+----
+
+[TIP]
+====
+You can also use the *length* function from *Camel 4.18*: `simple("There are ${length()} lines")`
+====
+
+And yes, you can combine this with the Simple operators such as checking if a zip code is larger than 1000:
+
+[source,java]
+----
+simple("${body.address.zip} > 1000")
+----
+
diff --git a/core/camel-core-languages/src/main/docs/modules/languages/pages/simple-operators.adoc b/core/camel-core-languages/src/main/docs/modules/languages/pages/simple-operators.adoc
new file mode 100644
index 000000000000..d1b48abe47d9
--- /dev/null
+++ b/core/camel-core-languages/src/main/docs/modules/languages/pages/simple-operators.adoc
@@ -0,0 +1,371 @@
+= Simple - Built-in Operators
+:tabs-sync-option:
+
+xref:simple-language.adoc[Back to Simple Language]
+
+== Built-in Operators
+
+The simple language has limited support for operators that are used in predicates to evaluate whether a condition is either _true_ or _false_.
+
+Camel operators require the left value must be enclosed in `${ }`.
+The syntax is:
+
+[source,text]
+----
+${leftValue} OP rightValue
+----
+
+Where the `rightValue` can be a string literal enclosed in `' '`,
+`null`, a constant value or another expression enclosed in `${ }`.
+
+IMPORTANT: There *must* be spaces around the operator.
+
+Camel will automatically type convert the rightValue type to the
+leftValue type, so it is able to e.g., convert a string into a numeric, so
+you can use `>` comparison for numeric values.
+
+=== Comparison Operators
+
+The following comparison operators are supported:
+
+[width="100%",cols="50%,50%",options="header",]
+|====
+|Operator |Description
+|`==` | equals
+|`=~` | equals ignore case (will ignore case when comparing String values)
+|`>` | greater than
+|`>=` | greater than or equals
+|`<` | less than
+|`+<=+` | less than or equals
+|`!=` | not equals
+|`!=~` | not equals ignore case (will ignore case when comparing String values)
+|`~~` | For testing if contains by ignoring case sensitivity in a string-based value
+|`!~~` | For testing if it does not contain by ignoring case sensitivity in a string-based value
+|`contains` | For testing if contains in a string-based value
+|`!contains` | For testing if it does not contain in a string-based value
+|`endsWith` | For testing if the left-hand side string ends with the right-hand string.
+|`!endsWith` | For testing if the left-hand side string does not end with the right-hand string.
+|`in` | For matching if in a set of values, each element must be separated by comma. If you want to include an empty value, then it must be defined using double comma, e.g. `",,bronze,silver,gold"`, which is a set of four values with an empty value and then the three medals.
+|`!in` | For matching if not in a set of values, each element must be separated by comma. If you want to include an empty value, then it must be defined using double comma, e.g. `",,bronze,silver,gold"`, which is a set of four values with an empty value and then the three medals.
+|`is` | For matching if the left-hand side type is an instance of the value.
+|`!is` | For matching if the left-hand side type is not an instance of the value.
+|`range` | For matching if the left-hand side is within a range of values defined as numbers: `from..to`.
+|`!range` | For matching if the left-hand side is not within a range of values defined as numbers: `from..to`.
+|`regex` | For matching against a given regular expression pattern defined as a String value
+|`!regex` | For not matching against a given regular expression pattern defined as a String value
+|`startsWith` | For testing if the left-hand side string starts with the right-hand string.
+|`!startsWith` | For testing if the left-hand side string does not start with the right-hand string.
+|====
+
+=== Numeric Operators
+
+The following numeric operators can be used:
+
+[width="100%",cols="50%,50%",options="header",]
+|====
+|Operator |Description
+|`++` | To increment a number by one. The left-hand side must be a function, otherwise parsed as literal.
+|`--` | To decrement a number by one. The left-hand side must be a function, otherwise parsed as literal.
+|====
+
+These operators are unary and requires to be attached directly next to a function:
+
+[source,text]
+----
+${function}OP
+----
+
+For example to increment the result of the function:
+
+[source,java]
+----
+simple("${header.myNumber}++ > 10");
+----
+
+And the same for decrement:
+
+[source,java]
+----
+simple("${header.myNumber}-- < 10");
+----
+
+
+=== Other Operators
+
+The following other operators can be used:
+
+[width="100%",cols="50%,50%",options="header",]
+|====
+|Operator |Description
+|`? :` | The ternary operator evaluates a condition and returns a value based on the result. If the condition is true, the first value (after `?`) is returned; otherwise, the second value (after `:`) is returned. There must be spaces around both `?` and `:` operators. This is similar to the ternary operator in Java.
+|`?:` | The elvis operator returns the left-hand side if it has an effective Boolean value of true, otherwise it returns the right-hand side. This is useful for providing fallback values when an expression may evaluate to a value with an effective Boolean value of false (such as `null`, `false`, `0`, empty/blank string).
+|`~>` | The chain operator is used in the situations where multiple nested functions need to be applied to a value, while making it easy to read. The value on the left-hand-side is evaluated, and set as the new message body before evaluating the right-hand-side function. This concept is similar to the xref:eips:pipeline-eip.adoc[Pipeline EIP].
+|`?~>` | The null-safe chain operator, where the chain will not continue when a function returned `null`.
+|====
+
+==== Ternary Operator
+
+The syntax for the ternary operator is:
+
+[source,text]
+----
+${leftValue} OP rightValue ? trueValue : falseValue
+----
+
+For example the following ternary operator will return `positive` if header `foo` is greater than 0, otherwise `negative`:
+
+[source,java]
+----
+simple("${header.foo > 0 ? 'positive' : 'negative'}");
+----
+
+Ternary operators can also be nested to handle multiple conditions:
+
+[source,java]
+----
+simple("${header.score >= 90 ? 'A' : ${header.score >= 80 ? 'B' : 'C'}}");
+----
+
+==== Elvis Operator
+
+For example the following elvis operator will return the username header unless its null or empty, which
+then the default value of `Guest` is returned.
+
+[source,java]
+----
+simple("${header.username} ?: 'Guest'");
+----
+
+==== Chain Operator
+
+The syntax for the chain operator is:
+
+[source,text]
+----
+${leftValue} ~> ${rightValue}
+----
+
+And there can be as many chains:
+
+[source,text]
+----
+${leftValue} ~> ${midValue} ~> ${midValue} ~> ${rightValue}
+----
+
+For example if the message body contains `Hello World` then the follow would return `WORLD`:
+
+[source,java]
+----
+simple("${substringAfter('Hello')} ~> ${trim()} ~> ${uppercase()}");
+----
+
+The _null safe_ variant (`?~>`) can be used to avoid `NullPointerException` if it's accepted to not continue the chain when any function returned `null`:
+
+However, many of the simple functions have NPE protection built-in, so this variant is only needed in special situations.
+
+==== Using $param as input parameter value
+
+IMPORTANT: The chain operator will by default pass results via the message body. This usually works well with most functions.
+However, when you need to be in full control then use `$param` as the magic parameter which represents the passed value from the previous function in the chain.
+
+Suppose the message body contains `" Hello World from the Camel "` then the following chain works out of the box:
+
+[source,java]
+----
+simple("${trim()} ~> ${replace('Hello','Hi')} ~> ${split(' ')} ~> ${size()}");
+----
+
+And here is the same example where we explicit use `$param` in the parameters where we need the input to be:
+
+[source,java]
+----
+simple("${trim()} ~> ${replace('Hello','Hi',$param)} ~> ${split($param,' ')} ~> ${size($param)}");
+----
+
+
+=== Boolean Operators
+
+And the following boolean operators can be used to group expressions:
+
+[width="100%",cols="50%,50%",options="header",]
+|====
+|Operator |Description
+|`&&` | The `and` operator is used to group two expressions if both operands evaluates to `true`.
+|`\|\|` | The `or` operator is used to group two expressions if any operand evaluates to `true`.
+|====
+
+The syntax for AND is:
+
+[source,text]
+----
+${leftValue} OP rightValue && ${leftValue} OP rightValue
+----
+
+And the syntax for OR is:
+
+[source,text]
+----
+${leftValue} OP rightValue || ${leftValue} OP rightValue
+----
+
+Some examples:
+
+[source,java]
+----
+// exact equals match
+simple("${header.foo} == 'foo'")
+
+// ignore case when comparing, so if the header has value FOO, this will match
+simple("${header.foo} =~ 'foo'")
+
+// here Camel will type convert '100' into the type of header.bar and if it is an Integer '100' will also be converter to an Integer
+simple("${header.bar} == '100'")
+
+simple("${header.bar} == 100")
+
+// 100 will be converter to the type of header.bar, so we can do > comparison
+simple("${header.bar} > 100")
+
+// if the value of header.bar was 100, value returned will be 101. header.bar itself will not be changed.
+simple("${header.bar}++")
+----
+
+=== Using Operators with different Java Object types
+
+When you compare with different types such as String and int, then you
+have to take a bit of care. Camel will use the type from the left-hand side
+as first priority. And fallback to the right-hand side type if both values
+couldn't be compared based on that type. This means you can flip the values
+to enforce a specific type. Suppose the bar value above is a String.
+
+Then you can flip the equation:
+
+[source,java]
+----
+simple("100 < ${header.bar}")
+----
+
+which then ensures the int type is used as first priority.
+
+This may change in the future if the Camel team improves the binary
+comparison operations to prefer numeric types to String-based. It's
+most often the String type which causes problems when comparing with
+numbers.
+
+[source,java]
+----
+// testing for null
+simple("${header.baz} == null")
+
+// testing for not null
+simple("${header.baz} != null")
+----
+
+And a bit more advanced example where the right value is another
+expression
+
+[source,java]
+----
+simple("${header.date} == ${date:now:yyyyMMdd}")
+
+simple("${header.type} == ${bean:orderService?method=getOrderType}")
+----
+
+And an example with `contains`, testing if the title contains the word Camel
+
+[source,java]
+----
+simple("${header.title} contains 'Camel'")
+----
+
+And an example with regex, testing if the number header is a 4-digit value:
+
+[source,java]
+----
+simple("${header.number} regex '\\d{4}'")
+----
+
+And finally an example if the header equals any of the values in the
+list. Each element must be separated by comma, and no space around.
+This also works for numbers etc., as Camel will convert each element
+into the type of the left-hand side.
+
+[source,java]
+----
+simple("${header.type} in 'gold,silver'")
+----
+
+And for all the last 3, we also support the negate test using not:
+
+[source,java]
+----
+simple("${header.type} !in 'gold,silver'")
+----
+
+And you can test if the type is a certain instance, e.g., for instance a
+String
+
+[source,java]
+----
+simple("${header.type} is 'java.lang.String'")
+----
+
+We have added a shorthand for all `java.lang` types, so you can write it as:
+
+[source,java]
+----
+simple("${header.type} is 'String'")
+----
+
+Ranges are also supported. The range interval requires numbers and both
+from and end are inclusive. For instance, to test whether a value is
+between 100 and 199:
+
+[source,java]
+----
+simple("${header.number} range 100..199")
+----
+
+Notice we use `..` in the range without spaces. It is based on the same
+syntax as Groovy.
+
+[source,java]
+----
+simple("${header.number} range '100..199'")
+----
+
+As the XML DSL does not have all the power as the Java DSL with all
+its various builder methods, you have to resort to using some other
+languages for testing with simple operators. Now you can do this with the simple
+language. In the sample below, we want to test it if the header is a widget
+order:
+
+._XML-only:_
+[source,xml]
+----
+<from uri="seda:orders">
+ <filter>
+ <simple>${header.type} == 'widget'</simple>
+ <to uri="bean:orderService?method=handleWidget"/>
+ </filter>
+</from>
+----
+
+=== Combining multiple expression using AND / OR Operator
+
+If you have two expressions you can combine them with the `&&` (and) or `||` (or) operator.
+
+For instance:
+
+[source,java]
+-----
+simple("${header.title} contains 'Camel' && ${header.type} == 'gold'")
+-----
+
+And of course the `||` is also supported. The sample would be:
+
+[source,java]
+-----
+simple("${header.title} contains 'Camel' || ${header.type} == 'gold'")
+-----
+
diff --git a/docs/components/modules/languages/nav.adoc b/docs/components/modules/languages/nav.adoc
index 13511c826ec4..a2f641962a2f 100644
--- a/docs/components/modules/languages/nav.adoc
+++ b/docs/components/modules/languages/nav.adoc
@@ -21,6 +21,10 @@
** xref:python-language.adoc[Python]
** xref:ref-language.adoc[Ref]
** xref:simple-language.adoc[Simple]
+** xref:simple-advanced.adoc[Simple - Advanced Features]
+** xref:simple-functions.adoc[Simple - Built-in Functions]
+** xref:simple-operators.adoc[Simple - Built-in Operators]
+** xref:simple-ognl.adoc[Simple - OGNL Expressions]
** xref:spel-language.adoc[SpEL]
** xref:tokenize-language.adoc[Tokenize]
** xref:variable-language.adoc[Variable]
@@ -28,3 +32,7 @@
** xref:xtokenize-language.adoc[XML Tokenize]
** xref:xpath-language.adoc[XPath]
** xref:xquery-language.adoc[XQuery]
+** xref:simple-advanced.adoc[Simple - Advanced Features]
+** xref:simple-functions.adoc[Simple - Built-in Functions]
+** xref:simple-ognl.adoc[Simple - OGNL Expressions]
+** xref:simple-operators.adoc[Simple - Built-in Operators]
diff --git a/docs/components/modules/languages/pages/simple-advanced.adoc b/docs/components/modules/languages/pages/simple-advanced.adoc
new file mode 120000
index 000000000000..01b231aeab66
--- /dev/null
+++ b/docs/components/modules/languages/pages/simple-advanced.adoc
@@ -0,0 +1 @@
+../../../../../core/camel-core-languages/src/main/docs/modules/languages/pages/simple-advanced.adoc
\ No newline at end of file
diff --git a/docs/components/modules/languages/pages/simple-functions.adoc b/docs/components/modules/languages/pages/simple-functions.adoc
new file mode 120000
index 000000000000..da4b54cb5388
--- /dev/null
+++ b/docs/components/modules/languages/pages/simple-functions.adoc
@@ -0,0 +1 @@
+../../../../../core/camel-core-languages/src/main/docs/modules/languages/pages/simple-functions.adoc
\ No newline at end of file
diff --git a/docs/components/modules/languages/pages/simple-ognl.adoc b/docs/components/modules/languages/pages/simple-ognl.adoc
new file mode 120000
index 000000000000..67724264a274
--- /dev/null
+++ b/docs/components/modules/languages/pages/simple-ognl.adoc
@@ -0,0 +1 @@
+../../../../../core/camel-core-languages/src/main/docs/modules/languages/pages/simple-ognl.adoc
\ No newline at end of file
diff --git a/docs/components/modules/languages/pages/simple-operators.adoc b/docs/components/modules/languages/pages/simple-operators.adoc
new file mode 120000
index 000000000000..39ef32ad4e98
--- /dev/null
+++ b/docs/components/modules/languages/pages/simple-operators.adoc
@@ -0,0 +1 @@
+../../../../../core/camel-core-languages/src/main/docs/modules/languages/pages/simple-operators.adoc
\ No newline at end of file
diff --git a/docs/languages-nav.adoc.template b/docs/languages-nav.adoc.template
index df56b61c87d8..449b3dd80adf 100644
--- a/docs/languages-nav.adoc.template
+++ b/docs/languages-nav.adoc.template
@@ -3,3 +3,7 @@
* xref:languages:index.adoc[Languages]
<!-- inject:adoc -->
<!-- endinject -->
+** xref:simple-advanced.adoc[Simple - Advanced Features]
+** xref:simple-functions.adoc[Simple - Built-in Functions]
+** xref:simple-ognl.adoc[Simple - OGNL Expressions]
+** xref:simple-operators.adoc[Simple - Built-in Operators]
diff --git a/docs/user-manual/modules/ROOT/nav.adoc b/docs/user-manual/modules/ROOT/nav.adoc
index 6ce6a33d4dfd..1b8a556c336f 100644
--- a/docs/user-manual/modules/ROOT/nav.adoc
+++ b/docs/user-manual/modules/ROOT/nav.adoc
@@ -35,7 +35,9 @@
*** xref:advice-with.adoc[AdviceWith]
*** xref:integration-test.adoc[Integration Test]
** xref:rest-dsl.adoc[Working with REST and Rest DSL]
+*** xref:rest-dsl-binding.adoc[Rest DSL binding and configuration]
*** xref:rest-dsl-openapi.adoc[Rest DSL contract first]
+*** xref:rest-dsl-validation.adoc[Rest DSL error handling and validation]
** xref:writing-components.adoc[Writing Components]
** xref:sbom.adoc[Generating SBOMs]
** xref:release-guide.adoc[Release guide]
@@ -67,6 +69,9 @@
** xref:endpoint.adoc[Endpoints]
** xref:endpoint-annotations.adoc[Endpoint Annotations]
** xref:exception-clause.adoc[Exception Clause]
+*** xref:exception-redelivery.adoc[Exception Clause redelivery]
+*** xref:exception-handling-patterns.adoc[Exception Clause handling patterns]
+*** xref:exception-advanced.adoc[Exception Clause advanced usage]
** xref:exchange-pooling.adoc[Exchange Pooling]
** xref:http-session-handling.adoc[HTTP-Session Handling]
** xref:parameter-binding-annotations.adoc[Parameter Binding Annotations]
diff --git a/docs/user-manual/modules/ROOT/pages/exception-advanced.adoc b/docs/user-manual/modules/ROOT/pages/exception-advanced.adoc
new file mode 100644
index 000000000000..44d3e09e18c5
--- /dev/null
+++ b/docs/user-manual/modules/ROOT/pages/exception-advanced.adoc
@@ -0,0 +1,462 @@
+= Exception Clause - Advanced Usage
+:tabs-sync-option:
+
+xref:exception-clause.adoc[Back to Exception Clause]
+
+== Advanced Usage of Exception Clause
+
+Camel supports advanced configuration of exception clauses.
+
+=== Using Global and Per Route Exception Clauses
+
+You can define exception clauses either as:
+
+* global
+* or route specific
+
+We start off with the sample that we change over time. First off
+we use only global exception clauses:
+
+._Java-only: global exception policies_
+[source,java]
+----
+// default should errors go to mock:error
+errorHandler(deadLetterChannel("mock:error").redeliveryDelay(0));
+
+// if a MyTechnicalException is thrown we will not try to
+// redeliver and we mark it as handled
+// so the caller does not get a failure
+// since we have no to then the exchange will continue to be
+// routed to the normal error handler
+// destination that is mock:error as defined above
+onException(MyTechnicalException.class).maximumRedeliveries(0).handled(true);
+
+// if a MyFunctionalException is thrown we do not want Camel to
+// redelivery but handle it our self using
+// our bean myOwnHandler, then the exchange is not routed to the
+// default error (mock:error)
+onException(MyFunctionalException.class).maximumRedeliveries(0).handled(true).to("bean:myOwnHandler");
+
+// here we route message to our service bean
+from("direct:start").choice().when().xpath("//type = 'myType'").to("bean:myServiceBean").end().to("mock:result");
+----
+
+In the next sample we change the global exception policies to be pure route
+specific.
+
+=== Must use `.end()` for route specific exception policies
+
+[IMPORTANT] This requires to end the *`onException`* route with
+*`.end()`* to indicate where it stops and when the regular route
+continues.
+
+._Java-only: route-specific exception policies with .end()_
+[source,java]
+----
+// default should errors go to mock:error
+errorHandler(deadLetterChannel("mock:error"));
+
+// here we start the routing with the consumer
+from("direct:start")
+
+ // if a MyTechnicalException is thrown we will not try to
+ // redeliver and we mark it as handled
+ // so the caller does not get a failure
+ // since we have no to then the exchange will continue to be
+ // routed to the normal error handler
+ // destination that is mock:error as defined above
+ // we MUST use .end() to indicate that this sub block is
+ // ended
+ .onException(MyTechnicalException.class).maximumRedeliveries(0).handled(true).end()
+
+ // if a MyFunctionalException is thrown we do not want Camel
+ // to redelivery but handle it our self using
+ // our bean myOwnHandler, then the exchange is not routed to
+ // the default error (mock:error)
+ // we MUST use .end() to indicate that this sub block is
+ // ended
+ .onException(MyFunctionalException.class).maximumRedeliveries(0).handled(true).to("bean:myOwnHandler").end()
+
+ // here we have the regular routing
+ .choice().when().xpath("//type = 'myType'").to("bean:myServiceBean").end().to("mock:result");
+----
+
+And now it gets complex as we combine global and route specific exception
+policies as we introduce a second route in the sample:
+
+._Java-only: combining global and route-specific exception policies_
+[source,java]
+----
+// global error handler
+// as its based on a unit test we do not have any delays between
+// and do not log the stack trace
+errorHandler(deadLetterChannel("mock:error").redeliveryDelay(0).logStackTrace(false));
+
+// shared for both routes
+onException(MyTechnicalException.class).handled(true).maximumRedeliveries(2).to("mock:tech.error");
+
+from("direct:start")
+ // route specific on exception for MyFunctionalException
+ // we MUST use .end() to indicate that this sub block is
+ // ended
+ .onException(MyFunctionalException.class).maximumRedeliveries(0).end().to("bean:myServiceBean").to("mock:result");
+
+from("direct:start2")
+ // route specific on exception for MyFunctionalException
+ // that is different than the previous route
+ // here we marked it as handled and send it to a different
+ // destination mock:handled
+ // we MUST use .end() to indicate that this sub block is
+ // ended
+ .onException(MyFunctionalException.class).handled(true).maximumRedeliveries(0).to("mock:handled").end().to("bean:myServiceBean").to("mock:result");
+----
+
+Notice that we can define the same exception *`MyFunctionalException`* in both
+routes, but they are configured differently and thus is handled
+different depending on the route. You can of course also add a
+new *`onException`* to one of the routes so it has an additional
+exception policy.
+
+And finally we top this by throwing in a nested error handler as well,
+as we add the 3rd route shown below:
+
+._Java-only: nested error handler with route-specific exceptions_
+[source,java]
+----
+from("direct:start3")
+ // route specific error handler that is different than the
+ // global error handler
+ // here we do not redeliver and send errors to mock:error3
+ // instead of the global endpoint
+ .errorHandler(deadLetterChannel("mock:error3").maximumRedeliveries(0))
+
+ // route specific on exception to mark MyFunctionalException
+ // as being handled
+ .onException(MyFunctionalException.class).handled(true).end()
+ // however we want the IO exceptions to redeliver at most 3
+ // times
+ .onException(IOException.class).maximumRedeliveries(3).end().to("bean:myServiceBean").to("mock:result");
+----
+
+=== Global exception policies and nested error handlers
+
+The sample above with both nested error handlers and both global and per
+route exception clauses is a bit advanced. It's important to get the
+fact straight that the *global* exception clauses is really global so
+they also applies for nested error handlers. So if a
+*`MyTechnicalException`* is thrown then it's the global exception policy
+that is selected.
+
+=== Using Fine Grained Selection Using `onWhen` Predicate
+
+You can attach an xref:expression.adoc[Expression] to the exception
+clause to have fine-grained control when a clause should be selected or
+not. As it's an xref:expression.adoc[Expression] you can use any kind of
+code to perform the test. Here is a sample:
+
+[tabs]
+====
+
+Java::
++
+[source,java]
+----
+errorHandler(deadLetterChannel("mock:error").redeliveryDelay(0).maximumRedeliveries(3));
+
+// here we define our onException to catch MyUserException when
+// there is a header[user] on the exchange that is not null
+onException(MyUserException.class).onWhen(header("user").isNotNull()).maximumRedeliveries(1)
+ // setting delay to zero is just to make unit testing faster
+ .redeliveryDelay(0).to(ERROR_USER_QUEUE);
+
+// here we define onException to catch MyUserException as a kind
+// of fallback when the above did not match.
+// Notice: The order how we have defined these onException is
+// important as Camel will resolve in the same order as they
+// have been defined
+onException(MyUserException.class).maximumRedeliveries(2)
+ // setting delay to zero is just to make unit testing faster
+ .redeliveryDelay(0).to(ERROR_QUEUE);
+----
+
+XML::
++
+[source,xml]
+----
+<onException>
+ <exception>com.foo.MyUserException</exception>
+ <redeliveryPolicy maximumRedeliveries="1" redeliveryDelay="0"/>
+ <onWhen>
+ <simple>${header.user} != null</simple>
+ </onWhen>
+ <to uri="mock:error"/>
+</onException>
+
+<onException>
+ <exception>com.foo.MyUserException</exception>
+ <redeliveryPolicy maximumRedeliveries="2" redeliveryDelay="0"/>
+ <to uri="mock:error"/>
+</onException>
+----
+
+YAML::
++
+[source,yaml]
+----
+- onException:
+ exception:
+ - com.foo.MyUserException
+ steps:
+ - redeliveryPolicy:
+ maximumRedeliveries: 1
+ redeliveryDelay: 0
+ - onWhen:
+ expression:
+ simple:
+ expression: "${header.user} != null"
+ - to:
+ uri: mock:error
+- onException:
+ exception:
+ - com.foo.MyUserException
+ redeliveryPolicy:
+ maximumRedeliveries: 2
+ redeliveryDelay: 0
+ steps:
+ - to:
+ uri: mock:error
+----
+====
+
+In the sample above we have two *`onException`*'s defined. The first has
+an *`onWhen`* expression attached to only trigger if the message has a
+header with the key user that is not null. If so this clause is selected
+and is handling the thrown exception. The second clause is a for coarse
+gained selection to select the same exception being thrown but when the
+expression is evaluated to false.
+
+[NOTE]
+====
+This is not required, if the second clause is omitted, then the
+default error handler will kick in.
+====
+
+=== Using onRedelivery Processor
+
+xref:components:eips:dead-letter-channel.adoc[Dead Letter Channel] has support
+for *`onRedelivery`* to allow custom processing of a Message before its
+being redelivered. It can be used to add some customer header or
+whatnot. In Camel 2.0 we have added this feature to
+xref:exception-clause.adoc[Exception Clause] as well, so you can use per
+exception scoped on redelivery. Camel will fallback to use the one
+defined on xref:components:eips:dead-letter-channel.adoc[Dead Letter Channel] if any, if
+none exists on the xref:exception-clause.adoc[Exception Clause]. See
+xref:components:eips:dead-letter-channel.adoc[Dead Letter Channel] for more details on
+*`onRedelivery`*.
+
+In the code below we want to do some custom code before redelivering any
+*`IOException`*. So we configure an *`onException`* for
+the *`IOException`* and set the *`onRedelivery`* to use our custom
+processor:
+
+[tabs]
+====
+
+Java::
++
+[source,java]
+----
+// when we redeliver caused by an IOException we want to do some
+// special code before the redelivery attempt
+onException(IOException.class)
+ // try to redeliver at most 3 times
+ .maximumRedeliveries(3)
+ // setting delay to zero is just to make unit testing faster
+ .redeliveryDelay(0).onRedelivery(new MyIORedeliverProcessor());
+----
+
+XML::
++
+In XML then you refer to the redelivery process using `onRedeliveryRef` which is configured on `onException`.
++
+[source,xml]
+----
+<onException onRedeliveryRef="myIORedeliverProcessor">
+ <redeliveryPolicy maximumRedeliveries="3" redeliveryDelay="0"/>
+ <exception>java.io.IOException</exception>
+</onException>
+----
+
+YAML::
++
+In YAML then you refer to the redelivery process using `onRedeliveryRef` which is configured on `onException`.
++
+[source,yaml]
+----
+- onException:
+ exception:
+ - java.io.IOException
+ onRedeliveryRef: myIORedeliverProcessor
+ redeliveryPolicy:
+ maximumRedeliveries: 3
+ redeliveryDelay: 0
+----
+====
+
+And in our custom processor we set a special timeout header to the message.
+You can of course do anything what you like in your code.
+
+._Java-only: custom redelivery processor_
+[source,java]
+----
+// This is our processor that is executed before every redelivery attempt
+// here we can do what we want in the java code, such as altering the
+// message
+public static class MyRedeliverProcessor implements Processor {
+
+ @Override
+ public void process(Exchange exchange) throws Exception {
+ // the message is being redelivered so we can alter it
+
+ // we just append the redelivery counter to the body
+ // you can of course do all kind of stuff instead
+ String body = exchange.getIn().getBody(String.class);
+ int count = exchange.getIn().getHeader("CamelRedeliveryCounter", Integer.class);
+
+ exchange.getIn().setBody(body + count);
+ }
+}
+----
+
+=== Using onExceptionOccurred Processor
+
+xref:components:eips:dead-letter-channel.adoc[Dead Letter Channel] has support
+for *`onExceptionOccurred`* to allow custom processing of a Message just
+after the exception was thrown. It can be used to do some custom logging
+or whatnot. The difference between *`onRedelivery`* processor
+and *`onExceptionOccurred`* processor, is that the former is processed
+just before a redelivery attempt is being performed, that means it will
+not happen right after an exception was thrown. For example if the error
+handler has been configured to perform 5 seconds delay between
+redelivery attempts, then the redelivery processor is invoked 5 seconds
+after the exception was thrown. On the other hand
+the *`onExceptionOccurred`* processor is always invoked right after the
+exception was thrown, and also if redelivery has been disabled.
+
+[NOTE]
+====
+Any new exceptions thrown from the *`onExceptionOccurred`*
+processor is logged as *`WARN`* and ignored, to not override the
+existing exception.
+====
+
+In the code below we want to do some custom logging when an exception
+happened. Therefore, we configure an *`onExceptionOccurred`* to use our
+custom processor:
+
+[tabs]
+====
+
+Java::
++
+[source.java]
+----
+errorHandler(defaultErrorHandler()
+ .maximumRedeliveries(3)
+ .redeliveryDelay(5000)
+ .onExceptionOccurred(myProcessor));
+----
+
+XML::
++
+[source,xml]
+----
+<errorHandler>
+ <defaultErrorHandler onExceptionOccurredRef="myProcessor">
+ <redeliveryPolicy maximumRedeliveries="3" redeliveryDelay="5000"/>
+ </defaultErrorHandler>
+</errorHandler>
+----
+
+YAML::
++
+[source,yaml]
+----
+- errorHandler:
+ defaultErrorHandler:
+ onExceptionOccurredRef: myProcessor
+ redeliveryPolicy:
+ maximumRedeliveries: 3
+ redeliveryDelay: 5000
+----
+====
+
+
+=== Using Fine Grained Retry Using retryWhile Predicate
+
+When you need fine-grained control for determining if an exchange should
+be retried or not you can use the *`retryWhile`* predicate. Camel will
+redeliver until the predicate returns false.
+
+Example:
+
+._Java-only: using retryWhile predicate for fine-grained retry_
+[source,java]
+----
+// we want to use a predicate for retries so we can determine in
+// our bean when retry should stop, notice it will overrule the global
+// error handler where we defined at most 1 redelivery attempt. Here we will
+// continue until the predicate returns false
+onException(MyFunctionalException.class).retryWhile(method("myRetryHandler")).handled(true).transform().constant("Sorry");
+----
+
+Where the bean *`myRetryHandler`* is computing if we should retry or not:
+
+._Java-only: retry handler bean with Bean Binding_
+[source,java]
+----
+public class MyRetryBean {
+
+ // using bean binding we can bind the information from the exchange to
+ // the types we have in our method signature
+ public boolean retry(@Header(Exchange.REDELIVERY_COUNTER) Integer counter) {
+ // NOTE: counter is the redelivery attempt, will start from 1
+ // we can of course do what ever we want to determine the result but
+ // this is a unit test so we end after 3 attempts
+ return counter < 3;
+ }
+}
+----
+
+=== Using Custom ExceptionPolicyStrategy
+
+The default `org.apache.camel.processor.errorhandler.ExceptionPolicyStrategy` in Camel should be sufficient in nearly all use-cases.
+However, if you need to use your own (use only for rare and advanced use-cases) this can be configured as the
+sample below illustrates:
+
+._Java-only: configuring a custom ExceptionPolicyStrategy_
+[source,java]
+----
+// configure the error handler to use my policy instead of the default from Camel
+errorHandler(deadLetterChannel("mock:error").exceptionPolicyStrategy(new MyPolicy()));
+----
+
+Using our own strategy *`MyPolicy`* we can change the default behavior of
+Camel with our own code to resolve which exception type
+from above should be handling the given thrown exception.
+
+._Java-only: custom ExceptionPolicyStrategy implementation_
+[source,java]
+----
+public static class MyPolicy implements ExceptionPolicyStrategy {
+
+ @Override
+ public ExceptionPolicyKey getExceptionPolicy(Set<ExceptionPolicyKey> exceptionPolicies, Exchange exchange, Throwable exception) {
+ // This is just an example that always forces the exception type configured
+ // with MyPolicyException to win.
+ return new ExceptionPolicyKey(null, MyPolicyException.class, null);
+ }
+}
+----
+
+
diff --git a/docs/user-manual/modules/ROOT/pages/exception-clause.adoc b/docs/user-manual/modules/ROOT/pages/exception-clause.adoc
index 41c979e8ba26..31ad69e29351 100644
--- a/docs/user-manual/modules/ROOT/pages/exception-clause.adoc
+++ b/docs/user-manual/modules/ROOT/pages/exception-clause.adoc
@@ -262,1406 +262,10 @@ exception in the *`onException`* clause. Illustrated as:
Since *`SocketException`* is an *`instanceof IOException`*, Camel will
select the *`onException(IOException.class)`* clause.
-== Configuring RedeliveryPolicy (redeliver options)
-
-https://www.javadoc.io/doc/org.apache.camel/camel-base/current/org/apache/camel/processor/errorhandler/RedeliveryPolicy.html[RedeliveryPolicy]
-requires to use the xref:components:eips:dead-letter-channel.adoc[Dead Letter Channel]
-as the xref:error-handler.adoc[Error Handler]. Dead Letter Channel
-supports attempting to redeliver the message exchange a number of times
-before sending it to a dead letter endpoint. See
-xref:components:eips:dead-letter-channel.adoc[Dead Letter Channel] for further
-information about redeliver and which redeliver options exists.
-
-=== No redelivery is default for onException
-
-By default, any xref:exception-clause.adoc[Exception Clause] will *not*
-redeliver! (as it sets the `maximumRedeliveries` option to 0).
-
-Sometimes you want to configure the redelivery policy on a per exception
-type basis. By default in the top examples, if an
-*`org.apache.camel.ValidationException`* occurs then the message will
-not be redelivered; however if some other exception occurs, e.g.,
-*`IOException`* or whatever, the route will be retried according to the
-settings from the xref:components:eips:dead-letter-channel.adoc[Dead Letter Channel].
-
-However if you want to customize any methods on the
-https://www.javadoc.io/doc/org.apache.camel/camel-base/current/org/apache/camel/processor/errorhandler/RedeliveryPolicy.html[RedeliveryPolicy]
-object, you can do this via the fluent API. So lets retry in case
-of *`org.apache.camel.ValidationException`* up till two times.
-
-
-[tabs]
-====
-
-Java::
-+
-[source,java]
-----
-onException(ValidationException.class)
- .maximumRedeliveries(2);
-----
-
-XML::
-+
-[source,xml]
-----
-<onException>
- <exception>com.mycompany.ValidationException</exception>
- <redeliveryPolicy maximumRedeliveries="2"/>
-</onException>
-----
-
-YAML::
-+
-[source,yaml]
-----
-- onException:
- exception:
- - org.apache.camel.ValidationException
- redeliveryPolicy:
- maximumRedeliveries: 2
-----
-====
-
-You can customize any of the `RedeliveryPolicy` options, for instance set a different delay of *`5000`* millis:
-
-[tabs]
-====
-
-Java::
-+
-[source,java]
-----
-onException(ValidationException.class)
- .maximumRedeliveries(2).redeliveryDelay(5000);
-----
-
-XML::
-+
-[source,xml]
-----
-<onException>
- <exception>com.mycompany.ValidationException</exception>
- <redeliveryPolicy maximumRedeliveries="2" redeliveryDelay="5000"/>
-</onException>
-----
-
-YAML::
-+
-[source,yaml]
-----
-- onException:
- exception:
- - org.apache.camel.ValidationException
- redeliveryPolicy:
- maximumRedeliveries: 2
- redeliveryDelay: 5000
-----
-====
-
-
-== Point of Entry for Redelivery Attempts
-
-All redelivery attempts start at the point of the failure. So the route:
-
-._Java-only: redelivery starts at the point of failure_
-[source,java]
-----
-onException(ConnectException.class)
- .from("direct:start")
- .process("processor1")
- .process("processor2") // <--- throws a ConnectException
- .to("mock:theEnd")
-----
-
-Will retry from *`processor2`* - not the complete route.
-
-
-== Asynchronous Delayed Redelivery
-
-Camel has a feature to _not block_ while waiting for a
-delayed redelivery to occur. However, if you use transacted routes then
-Camel will block as it's mandated by the transaction manager to execute
-all the work in the same thread context. You can enable the non-blocking
-asynchronous behavior by the *`asyncDelayedRedelivery`* option. This
-option can be set on the *`errorHandler`*, *`onException`* or the
-redelivery policies.
-
-By default, the error handler will create and use a scheduled thread pool
-to trigger redelivery in the future. You can also configure
-the *`executorServiceRef`* on the xref:error-handler.adoc[Error Handler]
-to indicate a reference to either a shared thread pool you can enlist in
-the registry, or a thread pool profile in case you want to be able to
-control pool settings.
-
-== Catching Multiple Exceptions
-
-Multiple exception can be caught as shown:
-
-[tabs]
-====
-
-Java::
-+
-In Java DSL you can add multiple exceptions separated by comma.
-+
-[source,java]
-----
-onException(MyBusinessException.class, MyOtherBusinessException.class)
- .maximumRedeliveries(2)
- .to("activemq:businessFailed");
-----
-
-XML::
-+
-And in XML DSL you just add another exception element:
-+
-[source,xml]
-----
-<onException>
- <exception>com.mycompany.MyBusinessException</exception>
- <exception>com.mycompany.MyOtherBusinessException</exception>
- <redeliveryPolicy maximumRedeliveries="2"/>
- <to uri="activemq:businessFailed"/>
-</onException>
-----
-
-YAML::
-+
-And in YAML DSL you just add another exception in the array:
-+
-[source,yaml]
-----
-- onException:
- exception:
- - com.mycompany.MyBusinessException
- - com.mycompany.MyOtherBusinessException
- redeliveryPolicy:
- maximumRedeliveries: 2
- steps:
- - to:
- uri: activemq:businessFailed
-----
-====
-
-== Using a Processor as a Failure Handler
-
-We want to handle certain exceptions in a specific way, so we add
-a *`onException`* clause for the particular exception.
-
-._Java-only: using a processor as failure handler_
-[source,java]
-----
-// here we register exception cause for MyFunctionException
-// when this exception occurs we want it to be processed by our
-// processor
-onException(MyFunctionalException.class)
- .process(new MyFunctionFailureHandler())
- .stop();
-----
-
-
-So what happens is that whenever a *`MyFunctionalException`* is thrown it
-is being routed to our processor *`MyFunctionFailureHandler`*. So you
-can say that the exchange is diverted when a *`MyFunctionalException`*
-is thrown during processing. It's important to distinct this as perfectly
-valid. The default redelivery policy from the
-xref:components:eips:dead-letter-channel.adoc[Dead Letter Channel] will not kick in, so
-our processor receives the Exchange directly, without any redeliver
-attempted. In our processor we need to determine what to do. Camel
-regards the Exchange as *failure handled*. So our processor is the end
-of the route. So lets look the code for our processor.
-
-._Java-only: custom failure handler processor_
-[source,java]
-----
-public static class MyFunctionFailureHandler implements Processor {
-
- @Override
- public void process(Exchange exchange) throws Exception {
- // the caused by exception is stored in a property on the exchange
- Throwable caused = exchange.getProperty(Exchange.EXCEPTION_CAUGHT, Throwable.class);
- assertNotNull(caused);
- // here you can do what you want, but Camel regards this exception as
- // handled, and this processor as a failure handler, so it won't do redeliveries.
- // So this is the end of this route.
- }
-}
-----
-
-Notice how we get the *caused by* exception using a property on the Exchange.
-This is where Camel stores any caught exception during processing. So
-you can fetch this property and check what the exception message and do
-what you want.
-
-== Marking Exceptions as Handled
-
-See also the section <<Handle and Continue Exceptions>> below.
-
-`handled(true)` tells Camel: _don't send the exception back to the caller — I'll provide the
-response myself in this `onException` block, and then we're done._
-
-Three things to keep in mind:
-
-* *The original route stops* — the exchange does not continue from where it failed in the main route.
-Only the steps in the `onException` block execute.
-* *The response is whatever the `onException` block produces* — use `transform`, `bean`, or `to` to
-build the response you want the caller to receive. If you don't set a response, the caller gets an
-empty body, not the exception.
-* *`exchange.getException()` is null* inside the `onException` block — use
-`exchange.getProperty(Exchange.EXCEPTION_CAUGHT, Exception.class)` to access the original exception.
-
-This is different from `continued(true)`, which also suppresses the exception but then *resumes the
-original route* from the point of failure as if the exception never happened.
-
-Using *`onException`* to handle known exceptions is a very powerful
-feature in Camel. You can mark the exception as being handled with the *handle* DSL,
-so the caller will not receive the caused exception as a response. The handle is a
-xref:predicate.adoc[Predicate] that is overloaded to accept three types
-of parameters:
-
-* Boolean
-* xref:predicate.adoc[Predicate]
-* xref:expression.adoc[Expression] that will be evaluated as a
-xref:predicate.adoc[Predicate] using this rule set: If the expression
-returns a Boolean, it is used directly. For any other response, it is regarded
-as `true` if the response is `not null`.
-
-For instance to mark all *`ValidationException`* as being handled we can
-do this:
-
-[tabs]
-====
-
-Java::
-+
-[source,java]
-----
-onException(ValidationException)
- .handled(true);
-----
-
-XML::
-+
-[source,xml]
-----
-<onException>
- <exception>org.apache.camel.ValidationException</exception>
- <handled>
- <constant>true</constant>
- </handled>
-</onException>
-----
-
-YAML::
-+
-[source,yaml]
-----
-- onException:
- exception:
- - org.apache.camel.ValidationException
- handled:
- constant: "true"
-----
-====
-
-=== Example Using Handled in Java DSL
-
-In this route below we want to do special handling of
-all *`OrderFailedException`* as we want to return a customized response
-to the caller. First we set up our routing as:
-
-._Java-only: handling OrderFailedException with custom response_
-[source,java]
-----
- // we do special error handling for when OrderFailedException is
- // thrown
- onException(OrderFailedException.class)
- // we mark the exchange as handled so the caller doesn't
- // receive the
- // OrderFailedException but whatever we want to return
- // instead
- .handled(true)
- // this bean handles the error handling where we can
- // customize the error
- // response using java code
- .bean(OrderService.class, "orderFailed")
- // and since this is an unit test we use mocks for testing
- .to("mock:error");
-
- // this is just the generic error handler where we set the
- // destination
- // and the number of redeliveries we want to try
- errorHandler(deadLetterChannel("mock:error").maximumRedeliveries(1));
-
- // this is our route where we handle orders
- from("direct:start")
- // this bean is our order service
- .bean(OrderService.class, "handleOrder")
- // this is the destination if the order is OK
- .to("mock:result");
-----
-
-Then we have our service bean that is just a plain POJO demonstrating how you
-can use xref:bean-integration.adoc[Bean Integration] in Camel to avoid
-being tied to the Camel API:
-
-._Java-only: OrderService POJO using Bean Integration_
-[source,java]
-----
- /**
- * Order service as a plain POJO class
- */
- public static class OrderService {
-
- /**
- * This method handle our order input and return the order
- */
- public Object handleOrder(@Headers Map headers, @Body String payload) throws OrderFailedException {
- headers.put("customerid", headers.get("customerid"));
- if ("Order: kaboom".equals(payload)) {
- throw new OrderFailedException("Cannot order: kaboom");
- } else {
- headers.put("orderid", "123");
- return "Order OK";
- }
- }
-
- /**
- * This method creates the response to the caller if the order could not
- * be processed
- */
- public Object orderFailed(@Headers Map headers, @Body String payload) {
- headers.put("customerid", headers.get("customerid"));
- headers.put("orderid", "failed");
- return "Order ERROR";
- }
- }
-----
-
-And finally the exception that is being thrown is just a regular exception:
-
-._Java-only: custom exception class_
-[source,java]
-----
- public static class OrderFailedException extends Exception {
-
- public OrderFailedException(String message) {
- super(message);
- }
-
- }
-----
-
-So what happens?
-
-If we sent an order that is being processed OK then the caller will
-receive an Exchange as reply containing *`Order OK`* as the payload and
-*`orderid=123`* in a header.
-
-If the order could *not* be processed and thus
-an *`OrderFailedException`* was thrown the caller will *not* receive
-this exception but our customized response that we have
-fabricated in the *`orderFailed`* method in our *`OrderService`*. So the
-caller receives an Exchange with the payload *`Order ERROR`* and a
-*`orderid=failed`* in a header.
-
-=== Using Handled with Spring XML DSL
-
-The same route as above in Spring XML DSL:
-
-._XML-only: handling OrderFailedException with custom response_
-[source,xml]
-----
- <!-- setup our error handler as the deal letter channel -->
-<bean id="errorHandler" class="org.apache.camel.builder.DeadLetterChannelBuilder">
- <property name="deadLetterUri" value="mock:error"/>
-</bean>
-
-<!-- this is our POJO bean with our business logic defined as a plain spring bean -->
-<bean id="orderService" class="org.apache.camel.spring.processor.onexception.OrderService" />
-
-<!-- this is the camel context where we define the routes -->
-<!-- define our error handler as a global error handler -->
-<camelContext errorHandlerRef="errorHandler" xmlns="http://camel.apache.org/schema/spring">
-
- <onException>
- <!-- the exception is full qualified names as plain strings -->
- <!-- there can be more just add a 2nd, 3rd exception element (unbounded) -->
- <exception>org.apache.camel.spring.processor.onexception.OrderFailedException</exception>
- <!-- we can set the redelivery policy here as well -->
- <redeliveryPolicy maximumRedeliveries="1" />
- <!-- mark this as handled -->
- <handled>
- <constant>true</constant>
- </handled>
- <!-- let our order service handle this exception, call the orderFailed method -->
- <bean ref="orderService" method="orderFailed" />
- <!-- and since this is a unit test we use mock for assertions -->
- <to uri="mock:error" />
- </onException>
-
- <route>
- <!-- the route -->
- <from uri="direct:start" />
- <!-- in the normal route then route to our order service and call handleOrder method -->
- <bean ref="orderService" method="handleOrder" />
- <!-- and since this is a unit test we use mock for assertions -->
- <to uri="mock:result" />
- </route>
-
-</camelContext>
-----
-
-=== Using Handled with YAML DSL
-
-And the same example in YAML DSL
-
-._YAML-only: handling OrderFailedException with custom response_
-[source,yaml]
-----
-- beans:
- - name: "orderService"
- beanType: "org.apache.camel.spring.processor.onexception.OrderService"
-- errorHandler:
- deadLetterChannel:
- deadLetterUri: mock:error
-- onException:
- exception:
- - org.apache.camel.spring.processor.onexception.OrderFailedException
- handled:
- constant:
- expression: "true"
- steps:
- - redeliveryPolicy:
- maximumRedeliveries: 1
- - bean:
- ref: orderService
- method: orderFailed
- - to:
- uri: mock:error
-- route:
- from:
- uri: direct:start
- steps:
- - bean:
- ref: orderService
- method: handleOrder
- - to:
- uri: mock:result
-----
-
-== Why is the exception null when I use onException ?
-
-If you use `onException` to handle exceptions, and want to get the caused
-`Exception` from a `Processor` in Java code, such as shown below:
-
-._Java-only: exception is null in onException processor_
-[source,java]
-----
-.onException(Exception.class)
- .handled(true)
- .process(new Processor() {
- @Override
- public void process(Exchange exchange) throws Exception {
- Exception cause = exchange.getException();
- // why cause exception is null ???
- }
- })
-.end()
-----
-
-Then beware the caused exception is no longer available from `exchange.getException()`, because
-the message is processed by the `onException` block.
-
-Instead, you can access the caused exception from exchange property on the
-exchange with the key `Exchange.EXCEPTION_CAUGHT`, as follows:
-
-._Java-only: accessing the caught exception from a property_
-[source,java]
-----
-Exception cause = exchange.getProperty(Exchange.EXCEPTION_CAUGHT, Exception.class);
-----
-
-The correct code to use in the example is there:
-
-._Java-only: correct way to get exception in onException_
-[source,java]
-----
-.onException(Exception.class).handled(true)
- .process(new Processor() {
- @Override
- public void process(Exchange exchange) throws Exception {
- Exception cause = exchange.getProperty(Exchange.EXCEPTION_CAUGHT, Exception.class);
- // we now have the caused exception
- }
- })
-.end()
-----
-
-== Handling and Sending a Fixed Response Back to the Client
-
-In the route above we handled the exception but routed it to a different
-endpoint. What if you need to alter the response and send a fixed
-response back to the original caller (the client). No secret here just
-do as you do in normal Camel routing, use
-xref:components:eips:message-translator.adoc[transform] to set the response, as shown in
-the sample below:
-
-._Java-only: returning a fixed response with transform_
-[source,java]
-----
-// we catch MyFunctionalException and want to mark it as handled
-// (= no failure returned to client)
-// but we want to return a fixed text response, so we transform
-// OUT body as Sorry.
-onException(MyFunctionalException.class)
- .handled(true)
- .transform().constant("Sorry");
-----
-
-We modify the sample slightly to return the original caused exception
-message instead of the fixed text `Sorry`:
-
-._Java-only: returning the exception message_
-[source,java]
-----
-// we catch MyFunctionalException and want to mark it as handled
-// (= no failure returned to client)
-// but we want to return a fixed text response, so we transform
-// OUT body and return the exception message
-onException(MyFunctionalException.class)
- .handled(true)
- .transform(exceptionMessage());
-----
-
-And we can use the xref:components:languages:simple-language.adoc[Simple] language to set a readable error
-message with the caused exception message:
-
-._Java-only: using Simple language in error response_
-[source,java]
-----
-// we catch MyFunctionalException and want to mark it as handled
-// (= no failure returned to client)
-// but we want to return a fixed text response, so we transform
-// OUT body and return a nice message
-// using the simple language where we want insert the exception
-// message
-onException(MyFunctionalException.class)
- .handled(true)
- .transform().simple("Error reported: ${exception.message} - cannot process this message.");
-----
-
-== Handle and Continue Exceptions
-
-The option `continued` allows you to
-both *`handle`* and *`continue`* routing in the original route as if the
-exception did not occur.
-
-For example: to ignore and continue when the *`IDontCareException`* was
-thrown we can do this:
-
-[tabs]
-====
-
-Java::
-+
-[source,java]
-----
-onException(IDontCareException.class)
- .continued(true);
-----
-
-XML::
-+
-[source,xml]
-----
-<onException>
- <exception>com.foo.IDontCareException</exception>
- <continued>
- <constant>true</constant>
- </continued>
-</onException>
-----
-
-YAML::
-+
-[source,yaml]
-----
-- onException:
- exception:
- - com.foo.IDontCareException
- continued:
- constant: "true"
-----
-====
-
-You can maybe compare continued with a having a *`try ... catch`* block
-around each step and then just ignore the exception. Using continued
-makes it easier in Camel as you otherwise had to use
-xref:try-catch-finally.adoc[Try Catch Finally] style for this kind of
-use case.
-
-=== Example Using continued
-
-In this route below we want to do special handling of
-all *`IllegalArgumentException`* as we just want to continue routing.
-
-[tabs]
-====
-
-Java::
-+
-[source,java]
-----
-onException(IllegalArgumentException.class).continued(true);
-
-from("direct:start")
- .to("mock:start")
- .throwException(new IllegalArgumentException("Forced"))
- .to("mock:result");
-----
-
-XML::
-+
-[source,xml]
-----
-<onException>
- <exception>java.lang.IllegalArgumentException</exception>
- <!-- tell Camel to handle and continue when this exception was thrown -->
- <continued><constant>true</constant></continued>
-</onException>
-
-<route>
- <from uri="direct:start"/>
- <to uri="mock:start"/>
- <throwException message="Forced" exceptionType="java.lang.IllegalArgumentException"/>
- <to uri="mock:result"/>
-</route>
-----
-
-YAML::
-+
-[source,yaml]
-----
-- onException:
- exception:
- - java.lang.IllegalArgumentException
- continued:
- constant:
- expression: "true"
-- route:
- from:
- uri: direct:start
- steps:
- - to:
- uri: mock:start
- - throwException:
- message: Forced
- exceptionType: java.lang.IllegalArgumentException
- - to:
- uri: mock:result
-----
-====
-
-
-=== What is the Difference Between Handled and Continued?
-
-If handled is true, then the thrown exception will be _handled_ and
-Camel will *not* continue routing in the original route, but break out.
-However you can configure a route in the *`onException`* which will be
-used instead. You use this route if you need to create some custom
-response message back to the caller, or do any other processing because
-that exception was thrown.
-
-If continued is true, then Camel will catch the exception and in fact
-just ignore it and continue routing in the original route. However if
-you have a route configured in the *`onException`* it will route that
-route first, before it will continue routing in the original route.
-
-
-== Using the original message with onException
-
-The option *`useOriginalMessage`* is used for routing the original input
-message instead of the current message that potential is modified during routing.
-
-For example: if you have this route:
-
-[tabs]
-====
-
-Java::
-+
-[source,java]
-----
-from("jms:queue:order:input")
- .to("bean:validateOrder")
- .to("bean:transformOrder")
- .to("bean:handleOrder");
-----
-
-XML::
-+
-[source,xml]
-----
-<route>
- <from uri="jms:queue:order:input"/>
- <to uri="bean:validateOrder"/>
- <to uri="bean:transformOrder"/>
- <to uri="bean:handleOrder"/>
-</route>
-----
-
-YAML::
-+
-[source,yaml]
-----
-- route:
- from:
- uri: jms:queue:order:input
- steps:
- - to:
- uri: bean:validateOrder
- - to:
- uri: bean:transformOrder
- - to:
- uri: bean:handleOrder
-----
-====
-
-The route listen for JMS messages and validates, transforms and handle
-it. During this the xref:exchange.adoc[Exchange] payload is
-transformed/modified. So in case something goes wrong and we want to
-move the message to another JMS destination, then we can add an
-*`onException`*. But when we move the xref:exchange.adoc[Exchange] to
-this destination we do not know in which state the message is in. Did
-the error happen in before the *`transformOrder`* or after? So to be
-sure we want to move the original input message we received from
-`jms:queue:order:input`. So we can do this by enabling the
-*`useOriginalMessage`* option as shown below:
-
-[tabs]
-====
-
-Java::
-+
-[source,java]
-----
-// will use original input message (body and headers)
-onException(MyOrderException.class)
- .useOriginalMessage()
- .handled(true)
- .to("jms:queue:order:failed");
-
-from("jms:queue:order:input")
- .to("bean:validateOrder")
- .to("bean:transformOrder")
- .to("bean:handleOrder");
-----
-
-XML::
-+
-[source,xml]
-----
-<onException useOriginalMessage="true">
- <exception>com.foo.MyOrderException</exception>
- <handled>
- <constant>true</constant>
- </handled>
- <to uri="jms:queue:order:failed"/>
-</onException>
-
-<route>
- <from uri="jms:queue:order:input"/>
- <to uri="bean:validateOrder"/>
- <to uri="bean:transformOrder"/>
- <to uri="bean:handleOrder"/>
-</route>
-----
-
-YAML::
-+
-[source,yaml]
-----
-- onException:
- useOriginalMessage: "true"
- exception:
- - com.foo.MyOrderException
- handled:
- constant:
- expression: "true"
- steps:
- - to:
- uri: jms:queue:order:failed
-- route:
- from:
- uri: jms:queue:order:input
- steps:
- - to:
- uri: bean:validateOrder
- - to:
- uri: bean:transformOrder
- - to:
- uri: bean:handleOrder
-----
-====
-
-Then the messages routed to the *`jms:queue:order:failed`* is the
-original input. If we want to manually retry we can move the JMS message
-from the failed to the input queue, with no problem as the message is
-the same as the original we received.
-
-=== Boundary of original message
-
-The original input means the input message that are bounded by the current unit of work. An unit of work typically spans one route, or multiple routes if they are connected
-using internal endpoints such as direct or seda. When messages are passed via external
-endpoints such as JMS or HTTP then the consumer will create a new unit of work, with the
-message it received as input as the original input. Also, some EIP patterns such as splitter,
-multicast, will create a new unit of work boundary for the messages in their sub-route
-(i.e. the split message); however these EIPs have an option named shareUnitOfWork which
-allows combining with the parent unit of work in regard to error handling and therefore use
-the parent original message.
-
-=== Using the original body with onException
-
-The `useOriginalBody` is similar to `useOriginalMessage` as documented above.
-You may want to use `useOriginalBody` when you want to be able to enrich the message with custom headers and preserve the original message body before sending to an error handler or dead letter channel.
-
-For example: if you have this route:
-
-[tabs]
-====
-
-Java::
-+
-[source,java]
-----
-// will use original input body
-onException(MyOrderException.class)
- .useOriginalBody()
- .handled(true)
- .to("jms:queue:order:failed");
-
-from("jms:queue:order:input")
- .setHeader("application", constant("OrderApp"))
- .to("bean:validateOrder")
- .to("bean:transformOrder")
- .to("bean:handleOrder");
-----
-
-XML::
-+
-[source,xml]
-----
-<onException useOriginalBody="true">
- <exception>com.foo.MyOrderException</exception>
- <handled>
- <constant>true</constant>
- </handled>
- <to uri="jms:queue:order:failed"/>
-</onException>
-
-<route>
- <from uri="jms:queue:order:input"/>
- <setHeader name="application">
- <constant>OrderApp</constant>
- </setHeader>
- <to uri="bean:validateOrder"/>
- <to uri="bean:transformOrder"/>
- <to uri="bean:handleOrder"/>
-</route>
-----
-
-YAML::
-+
-[source,yaml]
-----
-- onException:
- useOriginalBody: "true"
- exception:
- - com.foo.MyOrderException
- handled:
- constant:
- expression: "true"
- steps:
- - to:
- uri: jms:queue:order:failed
-- route:
- from:
- uri: jms:queue:order:input
- steps:
- - setHeader:
- name: application
- expression:
- constant:
- expression: OrderApp
- - to:
- uri: bean:validateOrder
- - to:
- uri: bean:transformOrder
- - to:
- uri: bean:handleOrder
-----
-====
-
-Then the message has been enriched with a header named application after the original message was received by the JMS endpoint. And in case of an error `onException`
-will handle the exception and use the original message body and the headers from the current message as-is, which means the headers will include the application header.
-
-
-== Advanced Usage of Exception Clause
-
-Camel supports advanced configuration of exception clauses.
-
-=== Using Global and Per Route Exception Clauses
-
-You can define exception clauses either as:
-
-* global
-* or route specific
-
-We start off with the sample that we change over time. First off
-we use only global exception clauses:
-
-._Java-only: global exception policies_
-[source,java]
-----
-// default should errors go to mock:error
-errorHandler(deadLetterChannel("mock:error").redeliveryDelay(0));
-
-// if a MyTechnicalException is thrown we will not try to
-// redeliver and we mark it as handled
-// so the caller does not get a failure
-// since we have no to then the exchange will continue to be
-// routed to the normal error handler
-// destination that is mock:error as defined above
-onException(MyTechnicalException.class).maximumRedeliveries(0).handled(true);
-
-// if a MyFunctionalException is thrown we do not want Camel to
-// redelivery but handle it our self using
-// our bean myOwnHandler, then the exchange is not routed to the
-// default error (mock:error)
-onException(MyFunctionalException.class).maximumRedeliveries(0).handled(true).to("bean:myOwnHandler");
-
-// here we route message to our service bean
-from("direct:start").choice().when().xpath("//type = 'myType'").to("bean:myServiceBean").end().to("mock:result");
-----
-
-In the next sample we change the global exception policies to be pure route
-specific.
-
-=== Must use `.end()` for route specific exception policies
-
-[IMPORTANT] This requires to end the *`onException`* route with
-*`.end()`* to indicate where it stops and when the regular route
-continues.
-
-._Java-only: route-specific exception policies with .end()_
-[source,java]
-----
-// default should errors go to mock:error
-errorHandler(deadLetterChannel("mock:error"));
-
-// here we start the routing with the consumer
-from("direct:start")
-
- // if a MyTechnicalException is thrown we will not try to
- // redeliver and we mark it as handled
- // so the caller does not get a failure
- // since we have no to then the exchange will continue to be
- // routed to the normal error handler
- // destination that is mock:error as defined above
- // we MUST use .end() to indicate that this sub block is
- // ended
- .onException(MyTechnicalException.class).maximumRedeliveries(0).handled(true).end()
-
- // if a MyFunctionalException is thrown we do not want Camel
- // to redelivery but handle it our self using
- // our bean myOwnHandler, then the exchange is not routed to
- // the default error (mock:error)
- // we MUST use .end() to indicate that this sub block is
- // ended
- .onException(MyFunctionalException.class).maximumRedeliveries(0).handled(true).to("bean:myOwnHandler").end()
-
- // here we have the regular routing
- .choice().when().xpath("//type = 'myType'").to("bean:myServiceBean").end().to("mock:result");
-----
-
-And now it gets complex as we combine global and route specific exception
-policies as we introduce a second route in the sample:
-
-._Java-only: combining global and route-specific exception policies_
-[source,java]
-----
-// global error handler
-// as its based on a unit test we do not have any delays between
-// and do not log the stack trace
-errorHandler(deadLetterChannel("mock:error").redeliveryDelay(0).logStackTrace(false));
-
-// shared for both routes
-onException(MyTechnicalException.class).handled(true).maximumRedeliveries(2).to("mock:tech.error");
-
-from("direct:start")
- // route specific on exception for MyFunctionalException
- // we MUST use .end() to indicate that this sub block is
- // ended
- .onException(MyFunctionalException.class).maximumRedeliveries(0).end().to("bean:myServiceBean").to("mock:result");
-
-from("direct:start2")
- // route specific on exception for MyFunctionalException
- // that is different than the previous route
- // here we marked it as handled and send it to a different
- // destination mock:handled
- // we MUST use .end() to indicate that this sub block is
- // ended
- .onException(MyFunctionalException.class).handled(true).maximumRedeliveries(0).to("mock:handled").end().to("bean:myServiceBean").to("mock:result");
-----
-
-Notice that we can define the same exception *`MyFunctionalException`* in both
-routes, but they are configured differently and thus is handled
-different depending on the route. You can of course also add a
-new *`onException`* to one of the routes so it has an additional
-exception policy.
-
-And finally we top this by throwing in a nested error handler as well,
-as we add the 3rd route shown below:
-
-._Java-only: nested error handler with route-specific exceptions_
-[source,java]
-----
-from("direct:start3")
- // route specific error handler that is different than the
- // global error handler
- // here we do not redeliver and send errors to mock:error3
- // instead of the global endpoint
- .errorHandler(deadLetterChannel("mock:error3").maximumRedeliveries(0))
-
- // route specific on exception to mark MyFunctionalException
- // as being handled
- .onException(MyFunctionalException.class).handled(true).end()
- // however we want the IO exceptions to redeliver at most 3
- // times
- .onException(IOException.class).maximumRedeliveries(3).end().to("bean:myServiceBean").to("mock:result");
-----
-
-=== Global exception policies and nested error handlers
-
-The sample above with both nested error handlers and both global and per
-route exception clauses is a bit advanced. It's important to get the
-fact straight that the *global* exception clauses is really global so
-they also applies for nested error handlers. So if a
-*`MyTechnicalException`* is thrown then it's the global exception policy
-that is selected.
-
-=== Using Fine Grained Selection Using `onWhen` Predicate
-
-You can attach an xref:expression.adoc[Expression] to the exception
-clause to have fine-grained control when a clause should be selected or
-not. As it's an xref:expression.adoc[Expression] you can use any kind of
-code to perform the test. Here is a sample:
-
-[tabs]
-====
-
-Java::
-+
-[source,java]
-----
-errorHandler(deadLetterChannel("mock:error").redeliveryDelay(0).maximumRedeliveries(3));
-
-// here we define our onException to catch MyUserException when
-// there is a header[user] on the exchange that is not null
-onException(MyUserException.class).onWhen(header("user").isNotNull()).maximumRedeliveries(1)
- // setting delay to zero is just to make unit testing faster
- .redeliveryDelay(0).to(ERROR_USER_QUEUE);
-
-// here we define onException to catch MyUserException as a kind
-// of fallback when the above did not match.
-// Notice: The order how we have defined these onException is
-// important as Camel will resolve in the same order as they
-// have been defined
-onException(MyUserException.class).maximumRedeliveries(2)
- // setting delay to zero is just to make unit testing faster
- .redeliveryDelay(0).to(ERROR_QUEUE);
-----
-
-XML::
-+
-[source,xml]
-----
-<onException>
- <exception>com.foo.MyUserException</exception>
- <redeliveryPolicy maximumRedeliveries="1" redeliveryDelay="0"/>
- <onWhen>
- <simple>${header.user} != null</simple>
- </onWhen>
- <to uri="mock:error"/>
-</onException>
-
-<onException>
- <exception>com.foo.MyUserException</exception>
- <redeliveryPolicy maximumRedeliveries="2" redeliveryDelay="0"/>
- <to uri="mock:error"/>
-</onException>
-----
-
-YAML::
-+
-[source,yaml]
-----
-- onException:
- exception:
- - com.foo.MyUserException
- steps:
- - redeliveryPolicy:
- maximumRedeliveries: 1
- redeliveryDelay: 0
- - onWhen:
- expression:
- simple:
- expression: "${header.user} != null"
- - to:
- uri: mock:error
-- onException:
- exception:
- - com.foo.MyUserException
- redeliveryPolicy:
- maximumRedeliveries: 2
- redeliveryDelay: 0
- steps:
- - to:
- uri: mock:error
-----
-====
-
-In the sample above we have two *`onException`*'s defined. The first has
-an *`onWhen`* expression attached to only trigger if the message has a
-header with the key user that is not null. If so this clause is selected
-and is handling the thrown exception. The second clause is a for coarse
-gained selection to select the same exception being thrown but when the
-expression is evaluated to false.
-
-[NOTE]
-====
-This is not required, if the second clause is omitted, then the
-default error handler will kick in.
-====
-
-=== Using onRedelivery Processor
-
-xref:components:eips:dead-letter-channel.adoc[Dead Letter Channel] has support
-for *`onRedelivery`* to allow custom processing of a Message before its
-being redelivered. It can be used to add some customer header or
-whatnot. In Camel 2.0 we have added this feature to
-xref:exception-clause.adoc[Exception Clause] as well, so you can use per
-exception scoped on redelivery. Camel will fallback to use the one
-defined on xref:components:eips:dead-letter-channel.adoc[Dead Letter Channel] if any, if
-none exists on the xref:exception-clause.adoc[Exception Clause]. See
-xref:components:eips:dead-letter-channel.adoc[Dead Letter Channel] for more details on
-*`onRedelivery`*.
-
-In the code below we want to do some custom code before redelivering any
-*`IOException`*. So we configure an *`onException`* for
-the *`IOException`* and set the *`onRedelivery`* to use our custom
-processor:
-
-[tabs]
-====
-
-Java::
-+
-[source,java]
-----
-// when we redeliver caused by an IOException we want to do some
-// special code before the redelivery attempt
-onException(IOException.class)
- // try to redeliver at most 3 times
- .maximumRedeliveries(3)
- // setting delay to zero is just to make unit testing faster
- .redeliveryDelay(0).onRedelivery(new MyIORedeliverProcessor());
-----
-
-XML::
-+
-In XML then you refer to the redelivery process using `onRedeliveryRef` which is configured on `onException`.
-+
-[source,xml]
-----
-<onException onRedeliveryRef="myIORedeliverProcessor">
- <redeliveryPolicy maximumRedeliveries="3" redeliveryDelay="0"/>
- <exception>java.io.IOException</exception>
-</onException>
-----
-
-YAML::
-+
-In YAML then you refer to the redelivery process using `onRedeliveryRef` which is configured on `onException`.
-+
-[source,yaml]
-----
-- onException:
- exception:
- - java.io.IOException
- onRedeliveryRef: myIORedeliverProcessor
- redeliveryPolicy:
- maximumRedeliveries: 3
- redeliveryDelay: 0
-----
-====
-
-And in our custom processor we set a special timeout header to the message.
-You can of course do anything what you like in your code.
-
-._Java-only: custom redelivery processor_
-[source,java]
-----
-// This is our processor that is executed before every redelivery attempt
-// here we can do what we want in the java code, such as altering the
-// message
-public static class MyRedeliverProcessor implements Processor {
-
- @Override
- public void process(Exchange exchange) throws Exception {
- // the message is being redelivered so we can alter it
-
- // we just append the redelivery counter to the body
- // you can of course do all kind of stuff instead
- String body = exchange.getIn().getBody(String.class);
- int count = exchange.getIn().getHeader("CamelRedeliveryCounter", Integer.class);
-
- exchange.getIn().setBody(body + count);
- }
-}
-----
-
-=== Using onExceptionOccurred Processor
-
-xref:components:eips:dead-letter-channel.adoc[Dead Letter Channel] has support
-for *`onExceptionOccurred`* to allow custom processing of a Message just
-after the exception was thrown. It can be used to do some custom logging
-or whatnot. The difference between *`onRedelivery`* processor
-and *`onExceptionOccurred`* processor, is that the former is processed
-just before a redelivery attempt is being performed, that means it will
-not happen right after an exception was thrown. For example if the error
-handler has been configured to perform 5 seconds delay between
-redelivery attempts, then the redelivery processor is invoked 5 seconds
-after the exception was thrown. On the other hand
-the *`onExceptionOccurred`* processor is always invoked right after the
-exception was thrown, and also if redelivery has been disabled.
-
-[NOTE]
-====
-Any new exceptions thrown from the *`onExceptionOccurred`*
-processor is logged as *`WARN`* and ignored, to not override the
-existing exception.
-====
-
-In the code below we want to do some custom logging when an exception
-happened. Therefore, we configure an *`onExceptionOccurred`* to use our
-custom processor:
-
-[tabs]
-====
-
-Java::
-+
-[source.java]
-----
-errorHandler(defaultErrorHandler()
- .maximumRedeliveries(3)
- .redeliveryDelay(5000)
- .onExceptionOccurred(myProcessor));
-----
-
-XML::
-+
-[source,xml]
-----
-<errorHandler>
- <defaultErrorHandler onExceptionOccurredRef="myProcessor">
- <redeliveryPolicy maximumRedeliveries="3" redeliveryDelay="5000"/>
- </defaultErrorHandler>
-</errorHandler>
-----
-
-YAML::
-+
-[source,yaml]
-----
-- errorHandler:
- defaultErrorHandler:
- onExceptionOccurredRef: myProcessor
- redeliveryPolicy:
- maximumRedeliveries: 3
- redeliveryDelay: 5000
-----
-====
-
-
-=== Using Fine Grained Retry Using retryWhile Predicate
-
-When you need fine-grained control for determining if an exchange should
-be retried or not you can use the *`retryWhile`* predicate. Camel will
-redeliver until the predicate returns false.
-
-Example:
-
-._Java-only: using retryWhile predicate for fine-grained retry_
-[source,java]
-----
-// we want to use a predicate for retries so we can determine in
-// our bean when retry should stop, notice it will overrule the global
-// error handler where we defined at most 1 redelivery attempt. Here we will
-// continue until the predicate returns false
-onException(MyFunctionalException.class).retryWhile(method("myRetryHandler")).handled(true).transform().constant("Sorry");
-----
-
-Where the bean *`myRetryHandler`* is computing if we should retry or not:
-
-._Java-only: retry handler bean with Bean Binding_
-[source,java]
-----
-public class MyRetryBean {
-
- // using bean binding we can bind the information from the exchange to
- // the types we have in our method signature
- public boolean retry(@Header(Exchange.REDELIVERY_COUNTER) Integer counter) {
- // NOTE: counter is the redelivery attempt, will start from 1
- // we can of course do what ever we want to determine the result but
- // this is a unit test so we end after 3 attempts
- return counter < 3;
- }
-}
-----
-
-=== Using Custom ExceptionPolicyStrategy
-
-The default `org.apache.camel.processor.errorhandler.ExceptionPolicyStrategy` in Camel should be sufficient in nearly all use-cases.
-However, if you need to use your own (use only for rare and advanced use-cases) this can be configured as the
-sample below illustrates:
-
-._Java-only: configuring a custom ExceptionPolicyStrategy_
-[source,java]
-----
-// configure the error handler to use my policy instead of the default from Camel
-errorHandler(deadLetterChannel("mock:error").exceptionPolicyStrategy(new MyPolicy()));
-----
-
-Using our own strategy *`MyPolicy`* we can change the default behavior of
-Camel with our own code to resolve which exception type
-from above should be handling the given thrown exception.
-
-._Java-only: custom ExceptionPolicyStrategy implementation_
-[source,java]
-----
-public static class MyPolicy implements ExceptionPolicyStrategy {
-
- @Override
- public ExceptionPolicyKey getExceptionPolicy(Set<ExceptionPolicyKey> exceptionPolicies, Exchange exchange, Throwable exception) {
- // This is just an example that always forces the exception type configured
- // with MyPolicyException to win.
- return new ExceptionPolicyKey(null, MyPolicyException.class, null);
- }
-}
-----
+== More Information
+For detailed documentation on specific topics, see the following sub-pages:
+* xref:exception-redelivery.adoc[Redelivery] — Configuring redelivery policy, async delayed redelivery, catching multiple exceptions
+* xref:exception-handling-patterns.adoc[Handling Patterns] — Handled vs continued, using original message, custom failure handlers
+* xref:exception-advanced.adoc[Advanced Usage] — Global vs route-specific, onWhen predicate, onRedelivery processor, custom strategies
diff --git a/docs/user-manual/modules/ROOT/pages/exception-handling-patterns.adoc b/docs/user-manual/modules/ROOT/pages/exception-handling-patterns.adoc
new file mode 100644
index 000000000000..27d86ae6c4d0
--- /dev/null
+++ b/docs/user-manual/modules/ROOT/pages/exception-handling-patterns.adoc
@@ -0,0 +1,768 @@
+= Exception Clause - Handling Patterns
+:tabs-sync-option:
+
+xref:exception-clause.adoc[Back to Exception Clause]
+
+== Using a Processor as a Failure Handler
+
+We want to handle certain exceptions in a specific way, so we add
+a *`onException`* clause for the particular exception.
+
+._Java-only: using a processor as failure handler_
+[source,java]
+----
+// here we register exception cause for MyFunctionException
+// when this exception occurs we want it to be processed by our
+// processor
+onException(MyFunctionalException.class)
+ .process(new MyFunctionFailureHandler())
+ .stop();
+----
+
+
+So what happens is that whenever a *`MyFunctionalException`* is thrown it
+is being routed to our processor *`MyFunctionFailureHandler`*. So you
+can say that the exchange is diverted when a *`MyFunctionalException`*
+is thrown during processing. It's important to distinct this as perfectly
+valid. The default redelivery policy from the
+xref:components:eips:dead-letter-channel.adoc[Dead Letter Channel] will not kick in, so
+our processor receives the Exchange directly, without any redeliver
+attempted. In our processor we need to determine what to do. Camel
+regards the Exchange as *failure handled*. So our processor is the end
+of the route. So lets look the code for our processor.
+
+._Java-only: custom failure handler processor_
+[source,java]
+----
+public static class MyFunctionFailureHandler implements Processor {
+
+ @Override
+ public void process(Exchange exchange) throws Exception {
+ // the caused by exception is stored in a property on the exchange
+ Throwable caused = exchange.getProperty(Exchange.EXCEPTION_CAUGHT, Throwable.class);
+ assertNotNull(caused);
+ // here you can do what you want, but Camel regards this exception as
+ // handled, and this processor as a failure handler, so it won't do redeliveries.
+ // So this is the end of this route.
+ }
+}
+----
+
+Notice how we get the *caused by* exception using a property on the Exchange.
+This is where Camel stores any caught exception during processing. So
+you can fetch this property and check what the exception message and do
+what you want.
+
+== Marking Exceptions as Handled
+
+See also the section <<Handle and Continue Exceptions>> below.
+
+`handled(true)` tells Camel: _don't send the exception back to the caller — I'll provide the
+response myself in this `onException` block, and then we're done._
+
+Three things to keep in mind:
+
+* *The original route stops* — the exchange does not continue from where it failed in the main route.
+Only the steps in the `onException` block execute.
+* *The response is whatever the `onException` block produces* — use `transform`, `bean`, or `to` to
+build the response you want the caller to receive. If you don't set a response, the caller gets an
+empty body, not the exception.
+* *`exchange.getException()` is null* inside the `onException` block — use
+`exchange.getProperty(Exchange.EXCEPTION_CAUGHT, Exception.class)` to access the original exception.
+
+This is different from `continued(true)`, which also suppresses the exception but then *resumes the
+original route* from the point of failure as if the exception never happened.
+
+Using *`onException`* to handle known exceptions is a very powerful
+feature in Camel. You can mark the exception as being handled with the *handle* DSL,
+so the caller will not receive the caused exception as a response. The handle is a
+xref:predicate.adoc[Predicate] that is overloaded to accept three types
+of parameters:
+
+* Boolean
+* xref:predicate.adoc[Predicate]
+* xref:expression.adoc[Expression] that will be evaluated as a
+xref:predicate.adoc[Predicate] using this rule set: If the expression
+returns a Boolean, it is used directly. For any other response, it is regarded
+as `true` if the response is `not null`.
+
+For instance to mark all *`ValidationException`* as being handled we can
+do this:
+
+[tabs]
+====
+
+Java::
++
+[source,java]
+----
+onException(ValidationException)
+ .handled(true);
+----
+
+XML::
++
+[source,xml]
+----
+<onException>
+ <exception>org.apache.camel.ValidationException</exception>
+ <handled>
+ <constant>true</constant>
+ </handled>
+</onException>
+----
+
+YAML::
++
+[source,yaml]
+----
+- onException:
+ exception:
+ - org.apache.camel.ValidationException
+ handled:
+ constant: "true"
+----
+====
+
+=== Example Using Handled in Java DSL
+
+In this route below we want to do special handling of
+all *`OrderFailedException`* as we want to return a customized response
+to the caller. First we set up our routing as:
+
+._Java-only: handling OrderFailedException with custom response_
+[source,java]
+----
+ // we do special error handling for when OrderFailedException is
+ // thrown
+ onException(OrderFailedException.class)
+ // we mark the exchange as handled so the caller doesn't
+ // receive the
+ // OrderFailedException but whatever we want to return
+ // instead
+ .handled(true)
+ // this bean handles the error handling where we can
+ // customize the error
+ // response using java code
+ .bean(OrderService.class, "orderFailed")
+ // and since this is an unit test we use mocks for testing
+ .to("mock:error");
+
+ // this is just the generic error handler where we set the
+ // destination
+ // and the number of redeliveries we want to try
+ errorHandler(deadLetterChannel("mock:error").maximumRedeliveries(1));
+
+ // this is our route where we handle orders
+ from("direct:start")
+ // this bean is our order service
+ .bean(OrderService.class, "handleOrder")
+ // this is the destination if the order is OK
+ .to("mock:result");
+----
+
+Then we have our service bean that is just a plain POJO demonstrating how you
+can use xref:bean-integration.adoc[Bean Integration] in Camel to avoid
+being tied to the Camel API:
+
+._Java-only: OrderService POJO using Bean Integration_
+[source,java]
+----
+ /**
+ * Order service as a plain POJO class
+ */
+ public static class OrderService {
+
+ /**
+ * This method handle our order input and return the order
+ */
+ public Object handleOrder(@Headers Map headers, @Body String payload) throws OrderFailedException {
+ headers.put("customerid", headers.get("customerid"));
+ if ("Order: kaboom".equals(payload)) {
+ throw new OrderFailedException("Cannot order: kaboom");
+ } else {
+ headers.put("orderid", "123");
+ return "Order OK";
+ }
+ }
+
+ /**
+ * This method creates the response to the caller if the order could not
+ * be processed
+ */
+ public Object orderFailed(@Headers Map headers, @Body String payload) {
+ headers.put("customerid", headers.get("customerid"));
+ headers.put("orderid", "failed");
+ return "Order ERROR";
+ }
+ }
+----
+
+And finally the exception that is being thrown is just a regular exception:
+
+._Java-only: custom exception class_
+[source,java]
+----
+ public static class OrderFailedException extends Exception {
+
+ public OrderFailedException(String message) {
+ super(message);
+ }
+
+ }
+----
+
+So what happens?
+
+If we sent an order that is being processed OK then the caller will
+receive an Exchange as reply containing *`Order OK`* as the payload and
+*`orderid=123`* in a header.
+
+If the order could *not* be processed and thus
+an *`OrderFailedException`* was thrown the caller will *not* receive
+this exception but our customized response that we have
+fabricated in the *`orderFailed`* method in our *`OrderService`*. So the
+caller receives an Exchange with the payload *`Order ERROR`* and a
+*`orderid=failed`* in a header.
+
+=== Using Handled with Spring XML DSL
+
+The same route as above in Spring XML DSL:
+
+._XML-only: handling OrderFailedException with custom response_
+[source,xml]
+----
+ <!-- setup our error handler as the deal letter channel -->
+<bean id="errorHandler" class="org.apache.camel.builder.DeadLetterChannelBuilder">
+ <property name="deadLetterUri" value="mock:error"/>
+</bean>
+
+<!-- this is our POJO bean with our business logic defined as a plain spring bean -->
+<bean id="orderService" class="org.apache.camel.spring.processor.onexception.OrderService" />
+
+<!-- this is the camel context where we define the routes -->
+<!-- define our error handler as a global error handler -->
+<camelContext errorHandlerRef="errorHandler" xmlns="http://camel.apache.org/schema/spring">
+
+ <onException>
+ <!-- the exception is full qualified names as plain strings -->
+ <!-- there can be more just add a 2nd, 3rd exception element (unbounded) -->
+ <exception>org.apache.camel.spring.processor.onexception.OrderFailedException</exception>
+ <!-- we can set the redelivery policy here as well -->
+ <redeliveryPolicy maximumRedeliveries="1" />
+ <!-- mark this as handled -->
+ <handled>
+ <constant>true</constant>
+ </handled>
+ <!-- let our order service handle this exception, call the orderFailed method -->
+ <bean ref="orderService" method="orderFailed" />
+ <!-- and since this is a unit test we use mock for assertions -->
+ <to uri="mock:error" />
+ </onException>
+
+ <route>
+ <!-- the route -->
+ <from uri="direct:start" />
+ <!-- in the normal route then route to our order service and call handleOrder method -->
+ <bean ref="orderService" method="handleOrder" />
+ <!-- and since this is a unit test we use mock for assertions -->
+ <to uri="mock:result" />
+ </route>
+
+</camelContext>
+----
+
+=== Using Handled with YAML DSL
+
+And the same example in YAML DSL
+
+._YAML-only: handling OrderFailedException with custom response_
+[source,yaml]
+----
+- beans:
+ - name: "orderService"
+ beanType: "org.apache.camel.spring.processor.onexception.OrderService"
+- errorHandler:
+ deadLetterChannel:
+ deadLetterUri: mock:error
+- onException:
+ exception:
+ - org.apache.camel.spring.processor.onexception.OrderFailedException
+ handled:
+ constant:
+ expression: "true"
+ steps:
+ - redeliveryPolicy:
+ maximumRedeliveries: 1
+ - bean:
+ ref: orderService
+ method: orderFailed
+ - to:
+ uri: mock:error
+- route:
+ from:
+ uri: direct:start
+ steps:
+ - bean:
+ ref: orderService
+ method: handleOrder
+ - to:
+ uri: mock:result
+----
+
+== Why is the exception null when I use onException ?
+
+If you use `onException` to handle exceptions, and want to get the caused
+`Exception` from a `Processor` in Java code, such as shown below:
+
+._Java-only: exception is null in onException processor_
+[source,java]
+----
+.onException(Exception.class)
+ .handled(true)
+ .process(new Processor() {
+ @Override
+ public void process(Exchange exchange) throws Exception {
+ Exception cause = exchange.getException();
+ // why cause exception is null ???
+ }
+ })
+.end()
+----
+
+Then beware the caused exception is no longer available from `exchange.getException()`, because
+the message is processed by the `onException` block.
+
+Instead, you can access the caused exception from exchange property on the
+exchange with the key `Exchange.EXCEPTION_CAUGHT`, as follows:
+
+._Java-only: accessing the caught exception from a property_
+[source,java]
+----
+Exception cause = exchange.getProperty(Exchange.EXCEPTION_CAUGHT, Exception.class);
+----
+
+The correct code to use in the example is there:
+
+._Java-only: correct way to get exception in onException_
+[source,java]
+----
+.onException(Exception.class).handled(true)
+ .process(new Processor() {
+ @Override
+ public void process(Exchange exchange) throws Exception {
+ Exception cause = exchange.getProperty(Exchange.EXCEPTION_CAUGHT, Exception.class);
+ // we now have the caused exception
+ }
+ })
+.end()
+----
+
+== Handling and Sending a Fixed Response Back to the Client
+
+In the route above we handled the exception but routed it to a different
+endpoint. What if you need to alter the response and send a fixed
+response back to the original caller (the client). No secret here just
+do as you do in normal Camel routing, use
+xref:components:eips:message-translator.adoc[transform] to set the response, as shown in
+the sample below:
+
+._Java-only: returning a fixed response with transform_
+[source,java]
+----
+// we catch MyFunctionalException and want to mark it as handled
+// (= no failure returned to client)
+// but we want to return a fixed text response, so we transform
+// OUT body as Sorry.
+onException(MyFunctionalException.class)
+ .handled(true)
+ .transform().constant("Sorry");
+----
+
+We modify the sample slightly to return the original caused exception
+message instead of the fixed text `Sorry`:
+
+._Java-only: returning the exception message_
+[source,java]
+----
+// we catch MyFunctionalException and want to mark it as handled
+// (= no failure returned to client)
+// but we want to return a fixed text response, so we transform
+// OUT body and return the exception message
+onException(MyFunctionalException.class)
+ .handled(true)
+ .transform(exceptionMessage());
+----
+
+And we can use the xref:components:languages:simple-language.adoc[Simple] language to set a readable error
+message with the caused exception message:
+
+._Java-only: using Simple language in error response_
+[source,java]
+----
+// we catch MyFunctionalException and want to mark it as handled
+// (= no failure returned to client)
+// but we want to return a fixed text response, so we transform
+// OUT body and return a nice message
+// using the simple language where we want insert the exception
+// message
+onException(MyFunctionalException.class)
+ .handled(true)
+ .transform().simple("Error reported: ${exception.message} - cannot process this message.");
+----
+
+== Handle and Continue Exceptions
+
+The option `continued` allows you to
+both *`handle`* and *`continue`* routing in the original route as if the
+exception did not occur.
+
+For example: to ignore and continue when the *`IDontCareException`* was
+thrown we can do this:
+
+[tabs]
+====
+
+Java::
++
+[source,java]
+----
+onException(IDontCareException.class)
+ .continued(true);
+----
+
+XML::
++
+[source,xml]
+----
+<onException>
+ <exception>com.foo.IDontCareException</exception>
+ <continued>
+ <constant>true</constant>
+ </continued>
+</onException>
+----
+
+YAML::
++
+[source,yaml]
+----
+- onException:
+ exception:
+ - com.foo.IDontCareException
+ continued:
+ constant: "true"
+----
+====
+
+You can maybe compare continued with a having a *`try ... catch`* block
+around each step and then just ignore the exception. Using continued
+makes it easier in Camel as you otherwise had to use
+xref:try-catch-finally.adoc[Try Catch Finally] style for this kind of
+use case.
+
+=== Example Using continued
+
+In this route below we want to do special handling of
+all *`IllegalArgumentException`* as we just want to continue routing.
+
+[tabs]
+====
+
+Java::
++
+[source,java]
+----
+onException(IllegalArgumentException.class).continued(true);
+
+from("direct:start")
+ .to("mock:start")
+ .throwException(new IllegalArgumentException("Forced"))
+ .to("mock:result");
+----
+
+XML::
++
+[source,xml]
+----
+<onException>
+ <exception>java.lang.IllegalArgumentException</exception>
+ <!-- tell Camel to handle and continue when this exception was thrown -->
+ <continued><constant>true</constant></continued>
+</onException>
+
+<route>
+ <from uri="direct:start"/>
+ <to uri="mock:start"/>
+ <throwException message="Forced" exceptionType="java.lang.IllegalArgumentException"/>
+ <to uri="mock:result"/>
+</route>
+----
+
+YAML::
++
+[source,yaml]
+----
+- onException:
+ exception:
+ - java.lang.IllegalArgumentException
+ continued:
+ constant:
+ expression: "true"
+- route:
+ from:
+ uri: direct:start
+ steps:
+ - to:
+ uri: mock:start
+ - throwException:
+ message: Forced
+ exceptionType: java.lang.IllegalArgumentException
+ - to:
+ uri: mock:result
+----
+====
+
+
+=== What is the Difference Between Handled and Continued?
+
+If handled is true, then the thrown exception will be _handled_ and
+Camel will *not* continue routing in the original route, but break out.
+However you can configure a route in the *`onException`* which will be
+used instead. You use this route if you need to create some custom
+response message back to the caller, or do any other processing because
+that exception was thrown.
+
+If continued is true, then Camel will catch the exception and in fact
+just ignore it and continue routing in the original route. However if
+you have a route configured in the *`onException`* it will route that
+route first, before it will continue routing in the original route.
+
+
+== Using the original message with onException
+
+The option *`useOriginalMessage`* is used for routing the original input
+message instead of the current message that potential is modified during routing.
+
+For example: if you have this route:
+
+[tabs]
+====
+
+Java::
++
+[source,java]
+----
+from("jms:queue:order:input")
+ .to("bean:validateOrder")
+ .to("bean:transformOrder")
+ .to("bean:handleOrder");
+----
+
+XML::
++
+[source,xml]
+----
+<route>
+ <from uri="jms:queue:order:input"/>
+ <to uri="bean:validateOrder"/>
+ <to uri="bean:transformOrder"/>
+ <to uri="bean:handleOrder"/>
+</route>
+----
+
+YAML::
++
+[source,yaml]
+----
+- route:
+ from:
+ uri: jms:queue:order:input
+ steps:
+ - to:
+ uri: bean:validateOrder
+ - to:
+ uri: bean:transformOrder
+ - to:
+ uri: bean:handleOrder
+----
+====
+
+The route listen for JMS messages and validates, transforms and handle
+it. During this the xref:exchange.adoc[Exchange] payload is
+transformed/modified. So in case something goes wrong and we want to
+move the message to another JMS destination, then we can add an
+*`onException`*. But when we move the xref:exchange.adoc[Exchange] to
+this destination we do not know in which state the message is in. Did
+the error happen in before the *`transformOrder`* or after? So to be
+sure we want to move the original input message we received from
+`jms:queue:order:input`. So we can do this by enabling the
+*`useOriginalMessage`* option as shown below:
+
+[tabs]
+====
+
+Java::
++
+[source,java]
+----
+// will use original input message (body and headers)
+onException(MyOrderException.class)
+ .useOriginalMessage()
+ .handled(true)
+ .to("jms:queue:order:failed");
+
+from("jms:queue:order:input")
+ .to("bean:validateOrder")
+ .to("bean:transformOrder")
+ .to("bean:handleOrder");
+----
+
+XML::
++
+[source,xml]
+----
+<onException useOriginalMessage="true">
+ <exception>com.foo.MyOrderException</exception>
+ <handled>
+ <constant>true</constant>
+ </handled>
+ <to uri="jms:queue:order:failed"/>
+</onException>
+
+<route>
+ <from uri="jms:queue:order:input"/>
+ <to uri="bean:validateOrder"/>
+ <to uri="bean:transformOrder"/>
+ <to uri="bean:handleOrder"/>
+</route>
+----
+
+YAML::
++
+[source,yaml]
+----
+- onException:
+ useOriginalMessage: "true"
+ exception:
+ - com.foo.MyOrderException
+ handled:
+ constant:
+ expression: "true"
+ steps:
+ - to:
+ uri: jms:queue:order:failed
+- route:
+ from:
+ uri: jms:queue:order:input
+ steps:
+ - to:
+ uri: bean:validateOrder
+ - to:
+ uri: bean:transformOrder
+ - to:
+ uri: bean:handleOrder
+----
+====
+
+Then the messages routed to the *`jms:queue:order:failed`* is the
+original input. If we want to manually retry we can move the JMS message
+from the failed to the input queue, with no problem as the message is
+the same as the original we received.
+
+=== Boundary of original message
+
+The original input means the input message that are bounded by the current unit of work. An unit of work typically spans one route, or multiple routes if they are connected
+using internal endpoints such as direct or seda. When messages are passed via external
+endpoints such as JMS or HTTP then the consumer will create a new unit of work, with the
+message it received as input as the original input. Also, some EIP patterns such as splitter,
+multicast, will create a new unit of work boundary for the messages in their sub-route
+(i.e. the split message); however these EIPs have an option named shareUnitOfWork which
+allows combining with the parent unit of work in regard to error handling and therefore use
+the parent original message.
+
+=== Using the original body with onException
+
+The `useOriginalBody` is similar to `useOriginalMessage` as documented above.
+You may want to use `useOriginalBody` when you want to be able to enrich the message with custom headers and preserve the original message body before sending to an error handler or dead letter channel.
+
+For example: if you have this route:
+
+[tabs]
+====
+
+Java::
++
+[source,java]
+----
+// will use original input body
+onException(MyOrderException.class)
+ .useOriginalBody()
+ .handled(true)
+ .to("jms:queue:order:failed");
+
+from("jms:queue:order:input")
+ .setHeader("application", constant("OrderApp"))
+ .to("bean:validateOrder")
+ .to("bean:transformOrder")
+ .to("bean:handleOrder");
+----
+
+XML::
++
+[source,xml]
+----
+<onException useOriginalBody="true">
+ <exception>com.foo.MyOrderException</exception>
+ <handled>
+ <constant>true</constant>
+ </handled>
+ <to uri="jms:queue:order:failed"/>
+</onException>
+
+<route>
+ <from uri="jms:queue:order:input"/>
+ <setHeader name="application">
+ <constant>OrderApp</constant>
+ </setHeader>
+ <to uri="bean:validateOrder"/>
+ <to uri="bean:transformOrder"/>
+ <to uri="bean:handleOrder"/>
+</route>
+----
+
+YAML::
++
+[source,yaml]
+----
+- onException:
+ useOriginalBody: "true"
+ exception:
+ - com.foo.MyOrderException
+ handled:
+ constant:
+ expression: "true"
+ steps:
+ - to:
+ uri: jms:queue:order:failed
+- route:
+ from:
+ uri: jms:queue:order:input
+ steps:
+ - setHeader:
+ name: application
+ expression:
+ constant:
+ expression: OrderApp
+ - to:
+ uri: bean:validateOrder
+ - to:
+ uri: bean:transformOrder
+ - to:
+ uri: bean:handleOrder
+----
+====
+
+Then the message has been enriched with a header named application after the original message was received by the JMS endpoint. And in case of an error `onException`
+will handle the exception and use the original message body and the headers from the current message as-is, which means the headers will include the application header.
+
diff --git a/docs/user-manual/modules/ROOT/pages/exception-redelivery.adoc b/docs/user-manual/modules/ROOT/pages/exception-redelivery.adoc
new file mode 100644
index 000000000000..703e9eacb1b0
--- /dev/null
+++ b/docs/user-manual/modules/ROOT/pages/exception-redelivery.adoc
@@ -0,0 +1,186 @@
+= Exception Clause - Redelivery
+:tabs-sync-option:
+
+xref:exception-clause.adoc[Back to Exception Clause]
+
+== Configuring RedeliveryPolicy (redeliver options)
+
+https://www.javadoc.io/doc/org.apache.camel/camel-base/current/org/apache/camel/processor/errorhandler/RedeliveryPolicy.html[RedeliveryPolicy]
+requires to use the xref:components:eips:dead-letter-channel.adoc[Dead Letter Channel]
+as the xref:error-handler.adoc[Error Handler]. Dead Letter Channel
+supports attempting to redeliver the message exchange a number of times
+before sending it to a dead letter endpoint. See
+xref:components:eips:dead-letter-channel.adoc[Dead Letter Channel] for further
+information about redeliver and which redeliver options exists.
+
+=== No redelivery is default for onException
+
+By default, any xref:exception-clause.adoc[Exception Clause] will *not*
+redeliver! (as it sets the `maximumRedeliveries` option to 0).
+
+Sometimes you want to configure the redelivery policy on a per exception
+type basis. By default in the top examples, if an
+*`org.apache.camel.ValidationException`* occurs then the message will
+not be redelivered; however if some other exception occurs, e.g.,
+*`IOException`* or whatever, the route will be retried according to the
+settings from the xref:components:eips:dead-letter-channel.adoc[Dead Letter Channel].
+
+However if you want to customize any methods on the
+https://www.javadoc.io/doc/org.apache.camel/camel-base/current/org/apache/camel/processor/errorhandler/RedeliveryPolicy.html[RedeliveryPolicy]
+object, you can do this via the fluent API. So lets retry in case
+of *`org.apache.camel.ValidationException`* up till two times.
+
+
+[tabs]
+====
+
+Java::
++
+[source,java]
+----
+onException(ValidationException.class)
+ .maximumRedeliveries(2);
+----
+
+XML::
++
+[source,xml]
+----
+<onException>
+ <exception>com.mycompany.ValidationException</exception>
+ <redeliveryPolicy maximumRedeliveries="2"/>
+</onException>
+----
+
+YAML::
++
+[source,yaml]
+----
+- onException:
+ exception:
+ - org.apache.camel.ValidationException
+ redeliveryPolicy:
+ maximumRedeliveries: 2
+----
+====
+
+You can customize any of the `RedeliveryPolicy` options, for instance set a different delay of *`5000`* millis:
+
+[tabs]
+====
+
+Java::
++
+[source,java]
+----
+onException(ValidationException.class)
+ .maximumRedeliveries(2).redeliveryDelay(5000);
+----
+
+XML::
++
+[source,xml]
+----
+<onException>
+ <exception>com.mycompany.ValidationException</exception>
+ <redeliveryPolicy maximumRedeliveries="2" redeliveryDelay="5000"/>
+</onException>
+----
+
+YAML::
++
+[source,yaml]
+----
+- onException:
+ exception:
+ - org.apache.camel.ValidationException
+ redeliveryPolicy:
+ maximumRedeliveries: 2
+ redeliveryDelay: 5000
+----
+====
+
+
+== Point of Entry for Redelivery Attempts
+
+All redelivery attempts start at the point of the failure. So the route:
+
+._Java-only: redelivery starts at the point of failure_
+[source,java]
+----
+onException(ConnectException.class)
+ .from("direct:start")
+ .process("processor1")
+ .process("processor2") // <--- throws a ConnectException
+ .to("mock:theEnd")
+----
+
+Will retry from *`processor2`* - not the complete route.
+
+
+== Asynchronous Delayed Redelivery
+
+Camel has a feature to _not block_ while waiting for a
+delayed redelivery to occur. However, if you use transacted routes then
+Camel will block as it's mandated by the transaction manager to execute
+all the work in the same thread context. You can enable the non-blocking
+asynchronous behavior by the *`asyncDelayedRedelivery`* option. This
+option can be set on the *`errorHandler`*, *`onException`* or the
+redelivery policies.
+
+By default, the error handler will create and use a scheduled thread pool
+to trigger redelivery in the future. You can also configure
+the *`executorServiceRef`* on the xref:error-handler.adoc[Error Handler]
+to indicate a reference to either a shared thread pool you can enlist in
+the registry, or a thread pool profile in case you want to be able to
+control pool settings.
+
+== Catching Multiple Exceptions
+
+Multiple exception can be caught as shown:
+
+[tabs]
+====
+
+Java::
++
+In Java DSL you can add multiple exceptions separated by comma.
++
+[source,java]
+----
+onException(MyBusinessException.class, MyOtherBusinessException.class)
+ .maximumRedeliveries(2)
+ .to("activemq:businessFailed");
+----
+
+XML::
++
+And in XML DSL you just add another exception element:
++
+[source,xml]
+----
+<onException>
+ <exception>com.mycompany.MyBusinessException</exception>
+ <exception>com.mycompany.MyOtherBusinessException</exception>
+ <redeliveryPolicy maximumRedeliveries="2"/>
+ <to uri="activemq:businessFailed"/>
+</onException>
+----
+
+YAML::
++
+And in YAML DSL you just add another exception in the array:
++
+[source,yaml]
+----
+- onException:
+ exception:
+ - com.mycompany.MyBusinessException
+ - com.mycompany.MyOtherBusinessException
+ redeliveryPolicy:
+ maximumRedeliveries: 2
+ steps:
+ - to:
+ uri: activemq:businessFailed
+----
+====
diff --git a/docs/user-manual/modules/ROOT/pages/rest-dsl-binding.adoc b/docs/user-manual/modules/ROOT/pages/rest-dsl-binding.adoc
new file mode 100644
index 000000000000..68e336f8f619
--- /dev/null
+++ b/docs/user-manual/modules/ROOT/pages/rest-dsl-binding.adoc
@@ -0,0 +1,580 @@
+= Rest DSL - Binding and Configuration
+:tabs-sync-option:
+
+xref:rest-dsl.adoc[Back to Rest DSL]
+
+== Binding to POJOs using
+
+The Rest DSL supports automatic binding json/xml contents to/from POJOs using data formats.
+By default, the binding mode is off, meaning there is no automatic binding happening for
+incoming and outgoing messages.
+
+You may want to use binding if you develop POJOs that maps to your REST
+services request and response types. This allows you as a developer to
+work with the POJOs in Java code.
+
+The binding modes are:
+
+[width="100%",cols="10%,90%",options="header",]
+|===
+|Binding Mode |Description
+
+|`off` |Binding is turned off. This is the default option.
+|`auto` |Binding is enabled, and Camel is relaxed and supports JSON, XML or both if
+the necessary data formats are included in the classpath. Notice that if
+for example `camel-jaxb` is not on the classpath, then XML binding is
+not enabled. Notice that for XML then `jaxb` is default, and you must be explicit to set `xmlDataFormat=jacksonXml`
+if you want to use jackson XML instead.
+|`json` |Binding to/from JSON is enabled, and requires a JSON capable data
+format on the classpath. By default, Camel will use `jackson` as the data format.
+|`xm` |Binding to/from XML is enabled, and requires `camel-jaxb` or `camel-jacksonxml` on the classpath.
+|`json_xml` |Binding to/from JSON and XML is enabled and requires both data formats to be on the classpath.
+|===
+
+IMPORTANT: In `auto` binding mode, the `consumes` option is used as a *fallback* for format detection when the incoming request has no `Content-Type` header (or the header does not indicate JSON or XML). It does *not* reject requests whose `Content-Type` does not match `consumes`. For example, an endpoint configured with `.consumes("application/json").bindingMode(auto)` will still accept and deserialize an XML request if the client sends `Content-Type: application/xml` and an XML-capable [...]
+
+When using `camel-jaxb` for XML bindings, then
+you can use the option `mustBeJAXBElement` to relax the output message
+body must be a class with JAXB annotations. You can use this in
+situations where the message body is already in XML format, and you want
+to use the message body as-is as the output type. If that is the case,
+then set the dataFormatProperty option `mustBeJAXBElement` to `false`
+value.
+
+The binding from POJO to JSon/JAXB will only happen if the `content-type`
+header includes the word `json` or `xml` representatively. This allows you
+to specify a custom content-type if the message body should not attempt to be
+marshalled using the binding. For example, if the message body is a
+custom binary payload, etc.
+
+When automatic binding from POJO to JSON/JAXB takes place the existing `content-type` header will by default be replaced with either `application/json` or `application/xml`.
+To disable the default behavior and be able to produce JSON/JAXB responses with custom `content-type` headers (e.g. `application/user.v2+json`) you configure this as shown below:
+
+[tabs]
+====
+
+Java::
++
+[source,java]
+----
+restConfiguration().dataFormatProperty("contentTypeHeader", "false");
+----
+
+XML::
++
+[source,xml]
+----
+<restConfiguration>
+ <dataFormatProperty key="contentTypeHeader" value="false"/>
+</restConfiguration>
+----
+
+YAML::
++
+The `value` in `dataFormatProperty` must be defined as a string value, so we use `"false"` in string quotes.
++
+[source,yaml]
+----
+- restConfiguration:
+ dataFormatProperty:
+ - key: "contentTypeHeader"
+ value: "false"
+----
+====
+
+To use binding you must include the necessary data formats on the
+classpath, such as `camel-jaxb` / `camel-jacksonxml` and/or `camel-jackson`. And then enable
+the binding mode. You can configure the binding mode globally on the
+rest configuration, and then override per rest service as well.
+
+[NOTE]
+====
+To use Jackson XML for XML binding, then you must configure `xmlDataformat=jacksonXml` and include `camel-jacksonxml` on the classpath.
+====
+
+To enable binding, you configure this in Java DSL as shown below:
+
+[tabs]
+====
+
+Java::
++
+[source,java]
+----
+restConfiguration().component("netty-http").host("localhost").port(portNum).bindingMode(RestBindingMode.auto);
+----
+
+XML::
++
+[source,xml]
+----
+<restConfiguration bindingMode="auto" component="netty-http" port="8080"/>
+----
+
+YAML::
++
+[source,yaml]
+----
+- restConfiguration:
+ bindingMode: "auto"
+ component: "netty-http"
+ port: "8080"
+----
+====
+
+When binding is enabled, Camel will bind the incoming and outgoing
+messages automatic, accordingly to the content type of the message. If
+the message is JSON, then JSON binding happens; and so if the message is
+ XML, then XML binding happens. The binding happens for incoming and reply
+messages. The table below summaries what binding occurs for incoming and
+reply messages.
+
+[width="100%",cols="25%,25%,25%,25%",options="header",]
+|===
+|Message Body |Direction |Binding Mode |Message Body
+|XML |Incoming |auto,xml,json_xml |POJO
+|POJO |Outgoing |auto,xml, json_xml |XML
+|JSON |Incoming |auto,json,json_xml |POJO
+|POJO |Outgoing |auto,json,json_xml |JSON
+|===
+
+When using binding, you must also configure what POJO type to map to.
+This is mandatory for incoming messages, and optional for outgoing.
+
+NOTE: When using binding mode `json`, `xml` or `json_xml` then Camel will automatically set `consumers` and `produces`
+on the rest endpoint (according to the mode), if not already explicit configured. For example, with binding mode `json`
+and setting the outType as `UserPojo` then Camel will define this rest endpoint as producing `application/json`.
+
+For example, to map from xml/json to a pojo class `UserPojo` you do this as shown below:
+
+[tabs]
+====
+
+Java::
++
+[source,java]
+----
+// configure to use netty-http on localhost with the given port
+// and enable auto binding mode
+restConfiguration().component("netty-http").host("localhost").port(portNum).bindingMode(RestBindingMode.auto);
+
+// use the rest DSL to define the rest services
+rest("/users/")
+ .post().type(UserPojo.class)
+ .to("direct:newUser");
+----
+
+XML::
++
+[source,xml]
+----
+<restConfiguration component="netty-http" host="localhost" port="{{portNum}}" bindingMode="auto"/>
+
+<rest>
+ <post path="/users" type="com.foo.UserPojo">
+ <to uri="direct:newUser"/>
+ </post>
+</rest>
+----
+
+YAML::
++
+[source,yaml]
+----
+- restConfiguration:
+ component: "netty-http"
+ host: "localhost"
+ port: "{{portNum}}"
+ bindingMode: "auto"
+- rest:
+ post:
+ - path: "/users"
+ to: "direct:newUser"
+ type: "com.foo.UserPojo"
+----
+====
+
+Notice we use `type` to define the incoming type. We can optionally
+define an outgoing type (which can be a good idea, to make it known from
+the DSL and also for tooling and JMX APIs to know both the incoming and
+outgoing types of the REST services). To define the outgoing type, we
+use `outType` as shown below:
+
+[tabs]
+====
+Java::
++
+[source,java]
+----
+// configure to use netty-http on localhost with the given port
+// and enable auto binding mode
+restConfiguration().component("netty-http").host("localhost").port(portNum).bindingMode(RestBindingMode.auto);
+
+// use the rest DSL to define the rest services
+rest("/users/")
+ .post().type(UserPojo.class).outType(CountryPojo.class)
+ .to("direct:newUser");
+----
+
+XML::
++
+[source,xml]
+----
+<restConfiguration component="netty-http" host="localhost" port="{{portNum}}" bindingMode="auto"/>
+
+<rest>
+ <post path="/users" type="com.foo.UserPojo" outType="com.foo.CountryPojo">
+ <to uri="direct:newUser"/>
+ </post>
+</rest>
+----
+
+YAML::
++
+[source,yaml]
+----
+- restConfiguration:
+ component: "netty-http"
+ host: "localhost"
+ port: "{{portNum}}"
+ bindingMode: "auto"
+- rest:
+ post:
+ - path: "/users"
+ to: "direct:newUser"
+ type: "com.foo.UserPojo"
+ outType: "com.foo.CountryPojo"
+----
+====
+
+To specify input and/or output using an array, append `[]` to the end
+of the canonical class name as shown in the following:
+
+[tabs]
+====
+Java::
++
+Notice how we in Java declare this as an array class
++
+[source,java]
+----
+// configure to use netty-http on localhost with the given port
+// and enable auto binding mode
+restConfiguration().component("netty-http").host("localhost").port(portNum).bindingMode(RestBindingMode.auto);
+
+// use the rest DSL to define the rest services
+rest("/users/")
+ .post().type(UserPojo[].class).outType(CountryPojo[].class)
+ .to("direct:newUser");
+----
+
+XML::
++
+[source,xml]
+----
+<restConfiguration component="netty-http" host="localhost" port="{{portNum}}" bindingMode="auto"/>
+
+<rest>
+ <post path="/users" type="com.foo.UserPojo[]" outType="com.foo.CountryPojo[]">
+ <to uri="direct:newUser"/>
+ </post>
+</rest>
+----
+
+YAML::
++
+[source,yaml]
+----
+- restConfiguration:
+ component: "netty-http"
+ host: "localhost"
+ port: "{{portNum}}"
+ bindingMode: "auto"
+- rest:
+ post:
+ - path: "/users"
+ to: "direct:newUser"
+ type: "com.foo.UserPojo[]"
+ outType: "com.foo.CountryPojo[]"
+----
+====
+
+
+The `UserPojo` is just a plain pojo with getter/setter as shown:
+
+[source,java]
+----
+public class UserPojo {
+ private int id;
+ private String name;
+ public int getId() {
+ return id;
+ }
+ public void setId(int id) {
+ this.id = id;
+ }
+ public String getName() {
+ return name;
+ }
+ public void setName(String name) {
+ this.name = name;
+ }
+}
+----
+
+The `UserPojo` only supports JSON, as XML requires using JAXB
+annotations, so we can add those annotations if we want to support XML also
+
+[source,java]
+----
+@XmlRootElement(name = "user")
+@XmlAccessorType(XmlAccessType.FIELD)
+public class UserPojo {
+ @XmlAttribute
+ private int id;
+ @XmlAttribute
+ private String name;
+ public int getId() {
+ return id;
+ }
+ public void setId(int id) {
+ this.id = id;
+ }
+ public String getName() {
+ return name;
+ }
+ public void setName(String name) {
+ this.name = name;
+ }
+}
+----
+
+By having the JAXB annotations, the POJO supports both JSON and XML bindings.
+
+=== Camel Rest-DSL configurations
+
+The Rest DSL supports the following options:
+
+[width="100%",cols="2,1,1,4",options="header"]
+|===
+| Name | Default | Type | Description
+| *apiComponent*|| String| Sets the name of the Camel component to use as the REST API (such as swagger or openapi)
+| *apiContextPath*|| String| Sets a leading API context-path the REST API services will be using. This can be used when using components such as camel-servlet where the deployed web application is deployed using a context-path.
+| *apiHost*|| String| To use a specific hostname for the API documentation (such as swagger or openapi) This can be used to override the generated host with this configured hostname
+| *apiProperties*|| Map| Sets additional options on api level
+| *apiVendorExtension*| false| boolean| Whether a vendor extension is enabled in the Rest APIs. If enabled, then Camel will include additional information as a vendor extension (e.g., keys starting with `_x-_`) such as route ids, class names etc. Not all third party API gateways and tools support vendor-extensions when importing your API docs.
+| *bindingMode*| off| RestBindingMode| Sets the binding mode to be used by the REST consumer
+| *clientRequestValidation*| false| boolean| Whether to enable validation of the client request to check: 1) Content-Type header matches what the Rest DSL consumes; returns HTTP Status 415 if validation error. 2) Accept header matches what the Rest DSL produces; returns HTTP Status 406 if validation error. 3) Missing required data (query parameters, HTTP headers, body); returns HTTP Status 400 if validation error. 4) Parsing error of the message body (JSON, XML or Auto binding mode must [...]
+| *clientResponseValidation*| false| boolean| Whether to check what Camel is returning as response to the client: 1) Status-code and Content-Type matches Rest DSL response messages. 2) Check whether expected headers is included according to the Rest DSL repose message headers. 3) If the response body is JSon then check whether its valid JSon. Returns 500 if validation error detected.
+| *component*|| String| Sets the name of the Camel component to use as the REST consumer
+| *componentProperties*|| Map| Sets additional options on component level
+| *consumerProperties*|| Map| Sets additional options on consumer level
+| *contextPath*|| String| Sets a leading context-path the REST services will be using. This can be used when using components such as camel-servlet where the deployed web application is deployed using a context-path. Or for components such as camel-jetty or camel-netty-http that includes a HTTP server.
+| *corsHeaders*|| Map| Sets the CORS headers to use if CORS has been enabled.
+| *dataFormatProperties*|| Map| Sets additional options on data format level
+| *enableCORS*| false| boolean| To specify whether to enable CORS, which means Camel will automatically include CORS in the HTTP headers in the response. This option is default false
+| *enableNoContentResponse*| false| boolean| To specify whether to return HTTP 204 with an empty body when a response contains an empty JSON object or XML root object.
+| *endpointProperties*|| Map| Sets additional options on endpoint level
+| *host*|| String| Sets the hostname to use by the REST consumer
+| *hostNameResolver*| allLocalIp | RestHostNameResolver| Sets the resolver to use for resolving hostname
+| *inlineRoutes*| true| boolean| Inline routes in rest-dsl which are linked using direct endpoints. If disabling then each service in Rest DSL is an individual route, meaning that you would have at least two routes per service (rest-dsl, and the route linked from rest-dsl). By default, this allows Camel to optimize and inline this as a single route. However, this requires using direct endpoints, which must be unique per service.
+| *jsonDataFormat*|| String| Sets a custom JSON data format to be used Important: This option is only for setting a custom name of the data format, not to refer to an existing data format instance.
+| *port*|| int| Sets the port to use by the REST consumer
+| *producerApiDoc*|| String| Sets the location of the api document (swagger api) the REST producer will use to validate the REST uri and query parameters are valid accordingly to the api document...
+| *producerComponent*|| String| Sets the name of the Camel component to use as the REST producer
+| *scheme*|| String| Sets the scheme to use by the REST consumer
+| *skipBindingOnErrorCode*| true| boolean| Whether to skip binding output if there is a custom HTTP error code, and instead use the response body as-is. This option is default true.
+| *useXForwardHeaders*| true| boolean| Whether to use X-Forward headers to set host etc. for Swagger. This option is default true.
+| *xmlDataFormat*|| String| Sets a custom XML data format to be used. Important: This option is only for setting a custom name of the data format, not to refer to an existing data format instance.
+|===
+
+For example, to configure the requst buffer on the jetty component on port 9091, then we can do as follows:
+
+[tabs]
+====
+
+Java::
++
+[source,java]
+----
+restConfiguration().component("jetty").port(9091).componentProperty("requestBufferSize", "50000");
+----
+
+XML::
++
+[source,xml]
+----
+<restConfiguration component="jetty" port="9091">
+ <componentProperty key="requestBufferSize" value="50000"/>
+</restConfiguration>
+----
+
+YAML::
++
+[source,yaml]
+----
+- restConfiguration:
+ component: "jetty"
+ port: "9091"
+ componentProperty:
+ - key: "requestBufferSize"
+ value: "50000"
+----
+====
+
+
+If no component has been explicitly configured,
+then Camel will look up if there is a Camel component that integrates with the Rest DSL,
+or if a `org.apache.camel.spi.RestConsumerFactory` is registered in the registry.
+If either one is found, then that is being used.
+
+You can configure properties on these levels.
+
+* component - Is used to set any options on the Component class. You can
+also configure these directly on the component.
+* endpoint - Is used set any option on the endpoint level. Many of the
+Camel components has many options you can set on endpoint level.
+* consumer - Is used to set any option on the consumer level.
+* data format - Is used to set any option on the data formats. For
+example, to enable pretty print in the JSON data format.
+* cors headers - If cors is enabled, then custom CORS headers can be
+set. See below for the default values which are in used. If a custom
+header is set then that value takes precedence over the default value.
+
+You can set multiple options of the same level, so you can, for
+example, configure two component options, and three endpoint options, etc.
+
+=== OAuth Bearer token validation
+
+For HTTP consumer components that support OAuth Bearer token validation, such as
+`platform-http`, `servlet`, `jetty`, `netty-http`, and `undertow`, set the `oauthProfile` endpoint
+option with `endpointProperty`:
+
+[tabs]
+====
+Java::
++
+[source,java]
+----
+restConfiguration()
+ .component("netty-http")
+ .endpointProperty("oauthProfile", "myprofile");
+----
+XML::
++
+[source,xml]
+----
+<restConfiguration component="netty-http">
+ <endpointProperty key="oauthProfile" value="myprofile"/>
+</restConfiguration>
+----
+YAML::
++
+[source,yaml]
+----
+- restConfiguration:
+ component: netty-http
+ endpointProperty:
+ - key: oauthProfile
+ value: myprofile
+----
+====
+
+When using the default validator implementation, add the xref:components:others:oauth.adoc[camel-oauth]
+component to the application classpath and configure the named profile with `camel.oauth.<profile>.*`
+properties. The OAuth check runs before route processors. Depending on the selected HTTP consumer,
+the transport may already have accepted, decoded, or bound parts of the inbound request.
+
+For valid tokens, route code can read the validation result from the exchange property:
+
+[source,java]
+----
+OAuthTokenValidationResult result = exchange.getProperty(
+ "CamelOAuthTokenValidationResult",
+ OAuthTokenValidationResult.class);
+----
+
+
+== Enabling or disabling Jackson JSON features
+
+When using JSON binding, you may want to turn specific Jackson features on or off.
+For example, to disable failing on unknown properties (e.g., JSON
+input has a property which cannot be mapped to a POJO) then configure
+this using the `dataFormatProperty` as shown below:
+
+[tabs]
+====
+
+Java::
++
+[source,java]
+----
+restConfiguration().component("jetty").host("localhost").port(getPort()).bindingMode(RestBindingMode.json)
+ .dataFormatProperty("json.in.disableFeatures", "FAIL_ON_UNKNOWN_PROPERTIES");
+----
++
+You can disable more features by separating the values using comma, such as:
++
+[source,java]
+----
+.dataFormatProperty("json.in.disableFeatures", "FAIL_ON_UNKNOWN_PROPERTIES,ADJUST_DATES_TO_CONTEXT_TIME_ZONE");
+----
++
+Likewise, you can enable features using the enableFeatures such as:
++
+[source,java]
+----
+restConfiguration().component("jetty").host("localhost").port(getPort()).bindingMode(RestBindingMode.json)
+ .dataFormatProperty("json.in.disableFeatures", "FAIL_ON_UNKNOWN_PROPERTIES,ADJUST_DATES_TO_CONTEXT_TIME_ZONE")
+ .dataFormatProperty("json.in.enableFeatures", "FAIL_ON_NUMBERS_FOR_ENUMS,USE_BIG_DECIMAL_FOR_FLOATS");
+----
+
+XML::
++
+[source,xml]
+----
+<restConfiguration component="jetty" host="localhost" port="9090" bindingMode="json">
+ <dataFormatProperty key="json.in.disableFeatures" value="FAIL_ON_UNKNOWN_PROPERTIES,ADJUST_DATES_TO_CONTEXT_TIME_ZONE"/>
+ <dataFormatProperty key="json.in.enableFeatures" value="FAIL_ON_NUMBERS_FOR_ENUMS,USE_BIG_DECIMAL_FOR_FLOATS"/>
+</restConfiguration>
+----
+
+YAML::
++
+[source,yaml]
+----
+- restConfiguration:
+ component: "jetty"
+ host: "localhost"
+ port: "9090"
+ bindingMode: "json"
+ dataFormatProperty:
+ - key: "json.in.disableFeatures"
+ value: "FAIL_ON_UNKNOWN_PROPERTIES,ADJUST_DATES_TO_CONTEXT_TIME_ZONE"
+ - key: json.in.enableFeatures
+ value: "FAIL_ON_NUMBERS_FOR_ENUMS,USE_BIG_DECIMAL_FOR_FLOATS"
+----
+====
+
+The values that can be used for enabling and disabling features on
+Jackson are the names of the enums from the following three Jackson 2.x classes
+
+* `com.fasterxml.jackson.databind.SerializationFeature`
+* `com.fasterxml.jackson.databind.DeserializationFeature`
+* `com.fasterxml.jackson.databind.MapperFeature`
+
+
+== Default CORS headers
+
+If CORS is enabled, then the _"follow headers"_ is in use by default.
+You can configure custom CORS headers that take precedence over the default
+value.
+
+[width="100%",cols="1,2",options="header",]
+|===
+|Key |Value
+|`Access-Control-Allow-Origin` |*
+|`Access-Control-Allow-Methods` |GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, CONNECT, PATCH
+|`Access-Control-Allow-Headers` |Origin, Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers
+|`Access-Control-Max-Age` |3600
+|===
diff --git a/docs/user-manual/modules/ROOT/pages/rest-dsl-validation.adoc b/docs/user-manual/modules/ROOT/pages/rest-dsl-validation.adoc
new file mode 100644
index 000000000000..99369be67331
--- /dev/null
+++ b/docs/user-manual/modules/ROOT/pages/rest-dsl-validation.adoc
@@ -0,0 +1,380 @@
+= Rest DSL - Error Handling and Validation
+:tabs-sync-option:
+
+xref:rest-dsl.adoc[Back to Rest DSL]
+
+== Defining a custom error message as-is
+
+If you want to define custom error messages to be sent back to the
+client with an HTTP error code (e.g., such as 400, 404 etc.)
+then you set a header with the key `Exchange.HTTP_RESPONSE_CODE`
+to the error code (must be 300+) such as 404.
+And then the message body with any reply message, and optionally
+set the content-type header as well. There is a little example shown
+below:
+
+[tabs]
+====
+
+Java::
++
+[source,java]
+----
+restConfiguration().component("netty-http").host("localhost").port(9091).bindingMode(RestBindingMode.json);
+// use the rest DSL to define the rest services
+rest("/users/")
+ .post("lives").type(UserPojo.class).outType(CountryPojo.class)
+ .to("direct:users-lives");
+
+from("direct:users-lives")
+ .choice()
+ .when().simple("${body.id} < 100")
+ .bean("userErrorService", "idToLowError")
+ .otherwise()
+ .bean("userService", "livesWhere");
+----
+
+XML::
++
+[source,xml]
+----
+<restConfiguration component="netty-http" host="localhost" port="9091" bindingMode="json"/>
+
+<rest path="/users/">
+ <post path="lives" type="com.foo.UserPojo" outType="com.foo.CountryPojo">
+ <to uri="direct:users-lives"/>
+ </post>
+</rest>
+
+<route>
+ <from uri="direct:users-lives"/>
+ <choice>
+ <when>
+ <simple>${body.id} < 100</simple>
+ <bean ref="userErrorService" method="idToLowError"/>
+ </when>
+ <otherwise>
+ <bean ref="userService" method="livesWhere"/>
+ </otherwise>
+ </choice>
+</route>
+----
+
+YAML::
++
+[source,yaml]
+----
+- restConfiguration:
+ component: "netty-http"
+ host: "localhost"
+ port: "9091"
+ bindingMode: "json"
+- rest:
+ path: "/users"
+ post:
+ - path: "/lives"
+ to: "direct:users-lives"
+ type: "com.foo.UserPojo"
+ outType: "com.foo.CountryPojo"
+- route:
+ from:
+ uri: direct:users-lives
+ steps:
+ - choice:
+ when:
+ - expression:
+ simple:
+ expression: "${body.id} < 100"
+ steps:
+ - bean:
+ ref: userErrorService
+ method: idToLowError
+ otherwise:
+ steps:
+ - bean:
+ ref: userService
+ method: livesWhere
+----
+====
+
+In this example, if the input id is a number that is below 100, we want
+to send back a custom error message, using the `UserErrorService` bean,
+which is implemented as shown:
+
+[source,java]
+----
+public class UserErrorService {
+ public void idToLowError(Exchange exchange) {
+ exchange.getIn().setBody("id value is too low");
+ exchange.getIn().setHeader(Exchange.CONTENT_TYPE, "text/plain");
+ exchange.getIn().setHeader(Exchange.HTTP_RESPONSE_CODE, 400);
+ }
+}
+----
+
+In the `_UserErrorService_` bean, we build our custom error message, and set
+the HTTP error code to 400. This is important, as that tells rest-dsl
+that this is a custom error message, and the message should not use the
+output pojo binding (e.g., would otherwise bind to `_CountryPojo_`).
+
+=== Catching JsonParserException and returning a custom error message
+
+You can return a custom message as-is (see previous section).
+So we can leverage this with Camel error handler to
+catch `JsonParserException`, handle that exception and build our custom
+response message.
+For example, to return an HTTP error code 400 with a
+hardcoded message, we can do as shown below:
+
+[tabs]
+====
+
+Java::
++
+[source,java]
+----
+onException(JsonParseException.class)
+ .handled(true)
+ .setHeader(Exchange.HTTP_RESPONSE_CODE, constant(400))
+ .setHeader(Exchange.CONTENT_TYPE, constant("text/plain"))
+ .setBody().constant("Invalid json data");
+----
+
+XML::
++
+[source,xml]
+----
+<onException>
+ <exception>com.fasterxml.jackson.core.JsonParseException</exception>
+ <handled>
+ <constant>true</constant>
+ </handled>
+ <setHeader name="CamelHttpResponseCode">
+ <constant>400</constant>
+ </setHeader>
+ <setHeader name="Content-Type">
+ <constant>text/plain</constant>
+ </setHeader>
+ <setBody>
+ <constant>Invalid json data</constant>
+ </setBody>
+</onException>
+----
+
+YAML::
++
+[source,yaml]
+----
+- onException:
+ exception:
+ - com.fasterxml.jackson.core.JsonParseException
+ handled:
+ constant:
+ expression: "true"
+ steps:
+ - setHeader:
+ name: CamelHttpResponseCode
+ expression:
+ constant:
+ expression: 400
+ - setHeader:
+ name: Content-Type
+ expression:
+ constant:
+ expression: text/plain
+ - setBody:
+ expression:
+ constant:
+ expression: Invalid json data
+----
+====
+
+== Query/Header Parameter default Values
+
+You can specify default values for parameters in the rest-dsl, such as
+the verbose parameter below:
+
+[tabs]
+====
+
+Java::
++
+[source,java]
+----
+rest("/customers/")
+ .get("/{id}").to("direct:customerDetail")
+ .get("/{id}/orders")
+ .param().name("verbose").type(RestParamType.query).defaultValue("false").description("Verbose order details").endParam()
+ .to("direct:customerOrders")
+ .post("/neworder").to("direct:customerNewOrder");
+----
+
+XML::
++
+[source,xml]
+----
+<rest path="/customers/">
+ <get path="/{id}">
+ <to uri="direct:customerDetail"/>
+ </get>
+ <get path="/{id}/orders">
+ <param description="Verbose order details" name="verbose" type="query" defaultValue="false"/>
+ <to uri="direct:customerOrders"/>
+ </get>
+ <post path="/neworder">
+ <to uri="direct:customerNewOrder"/>
+ </post>
+</rest>
+----
+
+
+YAML::
++
+[source,yaml]
+----
+- rest:
+ path: "/customers/"
+ get:
+ - path: "/{id}"
+ to: "direct:customerDetail"
+ - path: "/{id}/orders"
+ to: "direct:customerOrders"
+ param:
+ - name: "verbose"
+ type: "query"
+ defaultValue: "false"
+ description: "Verbose order details"
+ post:
+ - path: "/neworder"
+ to: "direct:customerNewOrder"
+----
+====
+
+The default value is automatic set as
+header on the incoming Camel `Message`. So if the call
+to `/customers/id/orders` do not include a query parameter with
+key `verbose` then Camel will now include a header with key `verbose`
+and the value `false` because it was declared as the default value. This
+functionality is only applicable for query parameters.
+Request headers may also be defaulted in the same way.
+
+[tabs]
+====
+
+Java::
++
+[source,java]
+----
+rest("/customers/")
+ .get("/{id}").to("direct:customerDetail")
+ .get("/{id}/orders")
+ .param().name("indicator").type(RestParamType.header).defaultValue("disabled").description("Feature Enabled Indicator").endParam()
+ .to("direct:customerOrders")
+ .post("/neworder").to("direct:customerNewOrder");
+----
+
+XML::
++
+[source,xml]
+----
+<rest path="/customers/">
+ <get path="/{id}">
+ <param name="id"/>
+ <to uri="direct:customerDetail"/>
+ </get>
+ <get path="/{id}/orders">
+ <param description="Feature Enabled Indicator" name="indicator" type="header" defaultValue="disabled"/>
+ <to uri="direct:customerOrders"/>
+ </get>
+ <post path="/neworder">
+ <to uri="direct:customerNewOrder"/>
+ </post>
+</rest>
+----
+
+YAML::
++
+[source,yaml]
+----
+- rest:
+ path: "/customers/"
+ get:
+ - path: "/{id}"
+ to: "direct:customerDetail"
+ - path: "/{id}/orders"
+ to: "direct:customerOrders"
+ param:
+ - name: "indicator"
+ type: "header"
+ defaultValue: "disabled"
+ description: "Feature Enabled Indicator"
+ post:
+ - path: "/neworder"
+ to: "direct:customerNewOrder"
+----
+====
+
+== Client Request and Response Validation
+
+It is possible to enable validation of the incoming client request.
+The validation checks for the following:
+
+- Content-Type header matches what the Rest DSL consumes. (Returns HTTP Status 415)
+- Accept header matches what the Rest DSL produces. (Returns HTTP Status 406)
+- Missing required data (query parameters, HTTP headers, body). (Returns HTTP Status 400)
+- Checking if query parameters or HTTP headers has not-allowed values. (Returns HTTP Status 400)
+- Parsing error of the message body (JSON, XML or Auto binding mode must be enabled). (Returns HTTP Status 400)
+
+If the validation fails, then Rest DSL will return a response with an HTTP error code.
+
+The validation is by default turned off (to be backwards compatible).
+It can be turned on via `clientRequestValidation` as shown below:
+
+[tabs]
+====
+
+Java::
++
+[source,java]
+----
+restConfiguration().component("jetty").host("localhost")
+ .clientRequestValidation(true);
+----
+
+XML::
++
+[source,xml]
+----
+<restConfiguration component="jetty" host="localhost" clientRequestValidation="true"/>
+----
+
+YAML::
++
+[source,yaml]
+----
+- restConfiguration:
+ component: "jetty"
+ host: "localhost"
+ clientRequestValidation: "true"
+----
+====
+
+The validator is pluggable and Camel provides a default implementation out of the box.
+
+However, the `camel-openapi-validator` uses the third party https://bitbucket.org/atlassian/swagger-request-validator/src/master/[Atlassian Swagger Request Validator]
+library instead for client request validator. This library is a more extensive validator than
+the default validator from `camel-core`, such as being able to validate the payload
+is structured according to the OpenAPI specification.
+
+In **Camel 4.13** we added a _response validator_ as well which is intended more as development assistance
+that you can enable while building your Camel integrations, and help ensure what Camel is sending back
+to the HTTP client is valid. The response validator checks for the following:
+
+- Status-code and Content-Type matches Rest DSL response messages.
+- Check whether expected headers is included according to the Rest DSL repose message headers.
+- If the response body is JSon then check whether its valid JSon.
+
+If any error is detected the HTTP Status 500 is returned.
+
+Also, the `camel-openapi-validator` can be added to the classpath to have a more powerful response validator,
+that can be used to validate the response payload is structured according to the OpenAPI specification.
diff --git a/docs/user-manual/modules/ROOT/pages/rest-dsl.adoc b/docs/user-manual/modules/ROOT/pages/rest-dsl.adoc
index 7caa6562670c..c2ee39f773d2 100644
--- a/docs/user-manual/modules/ROOT/pages/rest-dsl.adoc
+++ b/docs/user-manual/modules/ROOT/pages/rest-dsl.adoc
@@ -590,1152 +590,10 @@ let an external configuration determine if the REST endpoint is disabled or not.
In this example the `/customers/\{id}/orders` endpoint is disabled via a placeholder.
The last REST endpoint is hardcoded to be disabled.
-== Binding to POJOs using
+== More Information
-The Rest DSL supports automatic binding json/xml contents to/from POJOs using data formats.
-By default, the binding mode is off, meaning there is no automatic binding happening for
-incoming and outgoing messages.
+For detailed documentation on specific topics, see the following sub-pages:
-You may want to use binding if you develop POJOs that maps to your REST
-services request and response types. This allows you as a developer to
-work with the POJOs in Java code.
-
-The binding modes are:
-
-[width="100%",cols="10%,90%",options="header",]
-|===
-|Binding Mode |Description
-
-|`off` |Binding is turned off. This is the default option.
-|`auto` |Binding is enabled, and Camel is relaxed and supports JSON, XML or both if
-the necessary data formats are included in the classpath. Notice that if
-for example `camel-jaxb` is not on the classpath, then XML binding is
-not enabled. Notice that for XML then `jaxb` is default, and you must be explicit to set `xmlDataFormat=jacksonXml`
-if you want to use jackson XML instead.
-|`json` |Binding to/from JSON is enabled, and requires a JSON capable data
-format on the classpath. By default, Camel will use `jackson` as the data format.
-|`xm` |Binding to/from XML is enabled, and requires `camel-jaxb` or `camel-jacksonxml` on the classpath.
-|`json_xml` |Binding to/from JSON and XML is enabled and requires both data formats to be on the classpath.
-|===
-
-IMPORTANT: In `auto` binding mode, the `consumes` option is used as a *fallback* for format detection when the incoming request has no `Content-Type` header (or the header does not indicate JSON or XML). It does *not* reject requests whose `Content-Type` does not match `consumes`. For example, an endpoint configured with `.consumes("application/json").bindingMode(auto)` will still accept and deserialize an XML request if the client sends `Content-Type: application/xml` and an XML-capable [...]
-
-When using `camel-jaxb` for XML bindings, then
... 1135 lines suppressed ...