Thanks to visit codestin.com
Credit goes to camel.apache.org

Simple

Since Camel 1.1

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 EIPs and 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: Groovy.

The simple language uses ${body} placeholders for dynamic expressions and functions.

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.

See also the CSimple language which is pre compiled.

A quick Simple Language example

You often use Simple together with EIPs such as 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:

  • Java

  • XML

  • YAML

from("direct:a")
    .choice()
        .when(simple("${header.foo} == 'bar'"))
            .to("direct:b")
        .when(simple("${header.foo} == 'cheese'"))
            .to("direct:c")
        .otherwise()
            .to("direct:d");
<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>
- from:
    uri: direct:a
    steps:
      - choice:
          when:
            - simple: "${header.foo} == 'bar'"
              steps:
                - to:
                    uri: direct:b
            - simple: "${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.

The Simple language supports 4 options, which are listed below.

Name Default Java Type Description

trimResult (common)

false

Boolean

Whether to trim the returned values when this language are in use. For example the output result may contain unwanted line breaks at the beginning and end such as when using Java DSL with multi-line blocks. Is default false to be backwards compatible with existing behavior.

pretty (common)

false

Boolean

To pretty format the output (only JSon or XML supported).

resultType (common)

String

Sets the class of the result type (type from output).

trim (advanced)

true

Boolean

Whether to trim the source code to remove leading and trailing whitespaces and line breaks. For example when using DSLs where the source will span across multiple lines and there may be additional line breaks at both the beginning and end.

Built-in Simple Functions

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.

Some functions take 1 or more arguments enclosed in parentheses, and arguments separated by comma (ie ${replace('custID','customerId')}.

Camel Functions

Function Response Type Description

bean(name.method)

Object

Invoking a bean expression using the 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 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:type:fqnClassName.

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.

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).

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 the consumer is able to extract the timestamp from the source event. If the message has no timestamp, then 0 is returned.

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 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.

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.

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 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.

These 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.

During routing, you can use the LogEIP to write to the log, for example:

  • Java

  • XML

  • YAML

from("direct:email")
  .log("Sending welcome email to customer ${header.id} with status ${variable.level}");
<route>
    <from uri="direct:email"/>
    <log message="Sending welcome email to customer ${header.id} with status ${variable.level}"/>
</route>
- from:
    uri: direct:email
    steps:
      - log:
          message: "Sending welcome email to customer ${header.id} with status ${variable.level}"
The Camel functions are often also used for basic data mapping to easily get the part of the message payload you desire.

Array & List Functions

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.

map(key1,value1,…​)

Map

The map function creates a java.util.LinkedHashMap with the given set of pairs.

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.

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.

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.

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 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.

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].

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 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.

Boolean & Condition Functions

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.

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 numeric value (A..Z). For more advanced checks use the regex operator.

isAlpha(exp)

boolean

Whether the expression is numeric 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.

throwException(type,msg)

Exception

Deliberately throws an error. Uses IllegalArgumentException by default if no type is specified (use fully qualified classname).

The assert function evaluates the expression and if its false or null, then an SimpleAssertionException is thrown with the given message.

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.

You can use the regex operator to use regular expressions for more advanced tests.

And the not function is function to inverse the boolean value.

The throwException function is used for throwing an exception.

Date & Time Functions

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 (only available with a File consumer). Command accepts offsets such as: now-24h or header.xxx+1h or now+1h30m-100.

date:command:pattern

String

Date formatting using java.text.SimpleDateFormat patterns. See data: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 data:command function for additional documentation on the commands.

The date functions is used for parsing and formatting with date and times.

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.

Math & Numeric Functions

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).

length()

int

The payload length (number of bytes) of the message body

length(exp)

int

The payload length (number of bytes) of the expression.

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),

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.

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 ${avg()} 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 ${ceil(5.7)} returns 5, and ${ceil(5.1)} also returns 5.

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 stream caching the length is pre-computed and usually does not require to load the content into memory.

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 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.

Use the length function to return the payload length in bytes.

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

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).

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 JVM system property 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 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.

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.

The hostname function returns the OS hostname and does not require using parenthesis, so just use ${hostname}.

The null function returns a null value such as ${null}.

To use JVM system properties you use the ${sysenv.key} function, such as ${sysenv.java.version} or ${sysenv.java.io.tmpdir}.

You can get the current thread id by the ${threadId} function, and the name via ${threadName}.

And you can generate unique IDs with the Camel UUID Generator by the uuid function. The generator supports different kinds default, classic, short, simple and random, such as ${uuid(random)}.

String Functions

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 &quot; as double quote, &apos; as single quote, and &empty; 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 &quot; as double quote, &apos; as single quote, and &empty; as empty value.

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. 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,exp)

String

Returns a substring of the given expression. 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.

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.

uppercase()

String

Uppercases the message body

uppercase(exp)

String

Uppercases the expression

The string functions is various functions to work with values that are String and text based.

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.

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(5)} return "foo " and ${pad(-5)} returns " foo", and ${pad(-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 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.

XML & JSon Functions

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.

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 JSonPath, JQ, 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:

{"id": 123, "age": 42, "name": "scott"}

Then ${jq(.id)} will return 123.

You can also use this for basic data mapping such as:

from("direct:map")
        .transform().simple("""
            {
              "roll": ${jq(.id)},
              "country": "${jq(.country // constant(sweden))}",
              "fullname": "${jq(.name)}"
            }""")
        .to("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:

from("direct:map")
        .transform().simple("""
            {
              "roll": ${jsonpath($.id)},
              "years": ${jsonpath($.age)},
              "fullname": "${jsonpath($.name)}"
            }""")
        .to("log:data");

The xpath function is for working with XML and using XPath expressions to extract data from XML payloads.

Given the following XML payload:

<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:

from("direct:map")
    .transform().simple("""
        {
          "roll": ${jsonpath($.id)},
          "years": ${jsonpath($.age)},
          "fullname": "${jsonpath($.name)}"
        }""")
    .to("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:

{
  "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.

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.

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>.

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.

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.

For example if a 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[2].content} returns the XML payload. You can also use by filename ${attachmentContent(mydata.xml)} or by index ${attachmentContent(0)}.

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.

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.

Built-in Symbols

The following special symbols can be used when escaped with \ as below:

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:

${leftValue} OP rightValue

Where the rightValue can be a string literal enclosed in ' ', null, a constant value or another expression enclosed in ${ }.

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:

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:

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:

${function}OP

For example to increment the result of the function:

simple("${header.myNumber}++ > 10");

And the same for decrement:

simple("${header.myNumber}-- < 10");

Other Operators

The following other operators can be used:

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 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:

${leftValue} OP rightValue ? trueValue : falseValue

For example the following ternary operator will return positive if header foo is greater than 0, otherwise negative:

simple("${header.foo > 0 ? 'positive' : 'negative'}");

Ternary operators can also be nested to handle multiple conditions:

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.

simple("${header.username} ?: 'Guest'");

Chain Operator

The chain operator only supports passing results via the message body. This may change in the future to allow more flexible syntax to specify which parameter to use as input in the next fuction.

The syntax for the chain operator is:

${leftValue} ~> ${rightValue}

And there can be as many chains:

${leftValue} ~> ${midValue} ~> ${midValue} -> ${rightValue}

For example if the message body contains Hello World then the follow would return WORLD:

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.

Boolean Operators

And the following boolean operators can be used to group expressions:

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:

${leftValue} OP rightValue && ${leftValue} OP rightValue

And the syntax for OR is:

${leftValue} OP rightValue || ${leftValue} OP rightValue

Some examples:

// 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:

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.

// 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

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

simple("${header.title} contains 'Camel'")

And an example with regex, testing if the number header is a 4-digit value:

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.

simple("${header.type} in 'gold,silver'")

And for all the last 3, we also support the negate test using not:

simple("${header.type} !in 'gold,silver'")

And you can test if the type is a certain instance, e.g., for instance a String

simple("${header.type} is 'java.lang.String'")

We have added a shorthand for all java.lang types, so you can write it as:

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:

simple("${header.number} range 100..199")

Notice we use .. in the range without spaces. It is based on the same syntax as Groovy.

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:

<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:

simple("${header.title} contains 'Camel' && ${header.type'} == 'gold'")

And of course the || is also supported. The sample would be:

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.

Init Blocks is not supported with CSimple language.
The init block declaration $init{ …​ }init$ may be changed in the future.

The init block is declared as follows:

$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 := …​ where you can then use simple language to declare the value of the variable.

In the example below the foo variable is assigned a constant value of Hello foo, while bar variable is a string value with the dynamic value of the message body.

$init{
  $foo := 'Hello foo'
  $bar := 'Hi from ${body}'
}init$

You can have Java style code comments in the init block using // comment here as follows:

$init{
  // foo is a beginner phrase
  $foo := 'Hello foo'

  // here we can inline functions to get the name of the user from the message body
  $bar := 'Hi from ${body}'
}init$

Yes you can use the full power of the simple language and all its functions, such as:

$init{
  $foo := ${upper('Hello $body}'}
  $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:

$init{
  $greeting := ${upper('Hello $body}'}
  $level := ${header.code > 999 ? 'Gold' : 'Silver'}
}init$
{
  "message": "$greeting",
  "status": "$level"
}

The assigned variables from the init block are stored as Variables on the Exchange which allows to use the variables later in the Camel routes.

For example:

  • Java

  • XML

  • YAML

from("direct:welcome")
  .transform().simple(
          """
            $init{
              $greeting := ${upper('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}");
<route>
    <from uri="direct:welcome"/>
    <transform>
        <simple>
            $init{
              $greeting := ${upper('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>
- from:
    uri: direct:welcome
    steps:
      - transform:
          simple:
            expression: |-
                $init{
                  $greeting := ${upper('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.

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).

OGNL Expression Support

The Simple and Bean languages support a OGNL like notation for invoking methods (using reflection) in a fluent builder like style.

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:

simple("${body.familyName}")

Or use similar syntax as in 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.

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:

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:

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:

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:

simple("${body?.address?.street}")

Advanced OGNL examples

It is also possible to index in Map or List types, so you can do:

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':

simple("${body['foo bar'].name}")

You can access the Map or List objects directly using their key name (with or without dots) :

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:

simple("${body[foo]?.name}")

You can also access List types, for example, to get lines from the address you can do:

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.

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:

simple("${body.address.lines[last-1]}")

And the third last is, of course:

simple("${body.address.lines[last-2]}")

And you can call the size method on the list with

simple("${body.address.lines.size}")

Camel supports the length field for Java arrays as well, e.g.:

String[] lines = new String[]{"foo", "bar", "cat"};
exchange.getMessage().setBody(lines);

simple("There are ${body.length} lines")

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:

simple("${body.address.zip} > 1000")

EIP Examples

In the XML DSL sample below, we filter based on a header value:

<from uri="seda:orders">
   <filter>
       <simple>${header.foo}</simple>
       <to uri="mock:fooOrders"/>
   </filter>
</from>

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 mock:fooOrders endpoint, otherwise the message is dropped.

The same example in Java DSL:

from("seda:orders")
    .filter().simple("${header.foo}")
        .to("seda:fooOrders");

You can also use the simple language for simple text concatenations such as:

from("direct:hello")
    .transform().simple("Hello ${header.user} how are you?")
    .to("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.

from("direct:hello")
    .transform().simple("The today is ${date:now:yyyyMMdd} and it is a great day.")
    .to("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:

from("direct:order")
    .transform().simple("OrderId: ${bean:orderIdGenerator}")
    .to("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.

from("direct:order")
    .transform().simple("OrderId: ${bean:orderIdGenerator.generateId}")
    .to("mock:reply");

We can use the ?method=methodname option that we are familiar with the Bean component itself:

from("direct:order")
    .transform().simple("OrderId: ${bean:orderIdGenerator?method=generateId}")
    .to("mock:reply");

You can also convert the body to a given type, for example, to ensure that it is a String you can do:

<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:

<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:

<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:

<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:

<setBody>
  <simple>${substring(1,-1,${variable.foo})}</simple>
</setBody>

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 &quot; and single quote is &apos; (yeah that is the name).

For example, to replace all double quotes with single quotes:

from("direct:order")
  .transform().simple("${replace(&quot; , &apos;)}")
  .to("mock:reply");

And to replace all single quotes with double quotes:

<setBody>
  <simple>${replace(&apos; , &quot;)}</simple>
</setBody>

Or to remove all double quotes:

<setBody>
  <simple>${replace(&quot; , &empty;)}</simple>
</setBody>

Setting the result type

You can now provide a result type to the 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:

.setHeader("cool", simple("true", Boolean.class))

And in XML DSL

<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

<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.

<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:

.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.

In Java DSL you turn this on via the boolean parameter that is set as true below:

from("direct:xml")
    .setBody().simple("<person><name>Jack</name></person>", true)
    .to("mock:result");

from("direct:json")
    .setBody().simple("{ \"name\": \"Jack\", \"age\": 44 }", true)
    .to("mock:result");

from("direct:text")
    .setBody().simple("Hello ${body}", true)
    .to("mock:result");

In YAML DSL you specific pretty: true as follows:

route:
  from:
    uri: direct:xml
    steps:
      - setBody:
          simple:
            expression: "<person><name>Jack</name></person>"
            pretty: true
      - to:
          uri: mock:result

And in XML DSL you use the pretty attribute to true as show below:

<route>
  <from uri="direct:json"/>
  <setBody>
    <simple pretty="true">{ "name": "Jack", "age": 44 }</simple>
  </setBody>
  <to uri="mock:result"/>
</route>

Dependencies

The Simple language is part of camel-core.