Expressions Configuration Reference

Overview

One of the most powerful features of Mule is its expression language. A Mule expression is a dynamic expression that Mule evaluates while executing a flow, which provides information used to process the current message. Each expression uses one or more evaluators. An evaluator is a Java class that knows how to evaluate a string and return a Java object. Mule comes with a large number of evaluators, but as with almost everything in Mule, you can add your own.

Mule provides evaluators that can extract information from any of a variety of sources:

The current message’s payload

The current message’s headers

The Mule registry

The Java process

And, since you can add custom evaluators, there’s no limit to the information that expressions can provide.

Using Mule Expressions in a configuration

Mule expressions can appear at many places in a Mule configuration. In general, there are two ways to specify them:

Specify the evaluator and expression separately.

Specify a string that contains any number of evaluator/expression pairs

Depending upon the total value of the message payload, the message is written to he queue for small, medium, or large orders. Note that no special syntax is required, just the name of the evaluator and the expression (in this case, a numerical comparison) that it evaluates.

Here’s an example of 2, which illustrates how expressions are used in dynamic endpoints:

1

<jms:outbound-endpoint path="#[variable:queueName]" />

This specifies a JMS endpoint whose queue is determined by the current value of the variable queueName. This allows you to route the message dynamically by using a message-property-transformer to set the value of this flow variable to the name of the queue that should receive it. Note the syntax used when Mule expressions are specified as a single string:

The expression begins with #[ (a pound sign followed by a left square bracket)

The expression ends with ] (a right square bracket)

The evaluator name and expression are separated by : (a colon)

When multiple expressions appear in the string, each one uses this syntax separately, for instance:

If the variable queueNamePrefix has the value “new” and queueNameSuffix has the value “East”, the resulting queue name will be newOrdersEast.

In case number 2, you can combine as many expressions together with as much simple text as you like. The expressions can use the same evaluator or different evaluators.

Mule Expressions vs. Spring property placeholders

Mule expressions resemble Spring property placeholders in some ways, but they are actually quite different.

They are similar in that

Both Mule expressions and Spring property placeholders can appear in Mule configurations

Both are evaluated to produce the values that are actually used

They differ in

When they are evaluated:

Spring property placeholders are evaluated when the Mule application is initialized, and keeps the same value while the application runs.

Mule Expressions are re-evaluated each time they are used.

Where their values come from

Spring property placeholder return values specified in property files. By default, this is mule-app.propertiies, though it’s possible to configure Spring to read them from elsewhere. See Using Parameters in Your Configuration Files .

Mule Expressions can return any information their evaluator can retrieve or calculate.

The syntax they use

Spring property placeholders always use the syntax ${propertyName}

Mule properties use no special syntax when the evaluator name is specified separately. When they do use special syntax, it looks like #[evaluator:expression].

Where they can be used

Because they are automatically evaluated when processing the Mule configuration, Spring property placeholders can be used almost anywhere in the configuration. For instance, it’s entirely legal to use a property placeholder to configure either an inbound or an outbound endpoint:

Mule expressions can only be used during message processing, and where the configuration explicitly supports them. For instance, they cannot be used on an inbound endpoint as above, because no Mule message is being processed while Mule is waiting for a native message to be received.

Examples

Configuring endpoints statically

If endpoints need to be configured differently on different installations, but this configuration will not change while the Mule application si running, use Spring property placeholders. See Using Parameters in Your Configuration Files for an example of how to do this.

Dynamic outbound endpoints

If a message will be sent to different locations depending on its contents, use Mule Expressions in a dynamic outbound endpoint. SeeConfiguring Dynamic Endpoints for examples.

Routing based on message content

The when expression uses the groovy evaluator to check whether the message come from Washington DC, and if so sends it to the queue for federal orders. Otherwise, it is routed to the normal queue for orders.

There are a number of evaluators that can be used for message content. In general,

The bean evaluator is simplest for extracting possible nest properties

xpath and xpath-node are used to extract data from XML payloads

json and json-node are used to extrace data from JSON payload

OGNL and groovy are the most flexible and powerful evaluators. You can use whichever of those you are most comfortable with.

Logging message content

1

<loggermessage="message #payload:java.lang.String] received from #[function:hostname] (#function:ip])"/>

This logs the current message’s payload, transformed to a String, together with the host and IP address it was received from.

(Note: the following examples can be copied as is from the existing page Using Expressions)

Create a message payload with expressions

The expression transformer executes one or more expressions on the current message where the result of the expression(s) will become the payload of the current message.

For example, imagine you have a service component with a message signature that accepts three arguments:

The <expression-transformer> can be used to extract the fields from the ShippingRequestMessage to invoke the ShippingService. Note that we can only get two of the arguments from the ShippingRequestMessage: Customer and Item[]. The supporting documentation, which could be something like a Microsoft Word or Excel document, is an attachment to the ShippingRequestMessage. Attachments can be associated with any message within Mule.

Here we execute three separate expressions to obtain the three arguments required to invoke the ShippingService.makeShippingRequest() method. The first two expressions use the bean evaluator to extract objects from the message. The last argument uses the attachment evaluator to obtain a single attachment. Note that supportDocuments can be null, so we set required="false" on the return argument.

Create message headers with expressions

The <message-properties-transformer> allows you to add, remove, or rename properties dynamically or statically on the current message. For example:

The above expressions extract the <ID> element value and the ref attribute on the <body> element, setting the result as a message property named GUID.

Filtering messages using expressions

Expression filters can be used in content-based routing to assert statements on the current message and route the message accordingly. Expression filters work in the same way as other types of Mule filters and have the same expression attributes as listed above. The expression on the filter must evaluate to true or false. For example:

1

<expression-filterevaluator="header"expression="my-header!=null"/>

As usual, you can use AND, OR, and NOT filters to combine expressions.

Note that expression filters support a sub-set of all expression evaluators, because filters should only evaluate against the current message. For example, there is no point in using a function expression on a filter. The supported expression evaluators are: bean, custom, exception-type, groovy, header, jxpath, ognl, payload-type, regex, wildcard, and xpath.

When the evaluator and expression are specified as a single string

Note that there is no distinction here between built-in and custom evaluators. Both are used by specifying the evaluator’s name.

For evaluators where the expression is optional the colon that follows the evaluator is still required.

Attachment Evaluators

There are several evaluators that return the values of inbound attachments in different ways. The evaluators that return multiple attachments work in one of two ways:

If the expression contains a wildcard marker , they return all the headers whose attachments mes match the wildcard expression.

Otherwise, the expression contains a comma-separated list of header attachments . It is an error for an attachment not to be present, unless the name is followed by a question mark , which marks it as optional.

Examples:

evaluator="attachment" expression="itemPhoto"

#[attachment:itemPhoto]

return the value of the inbound attachment named “itemPhoto”

evaluator=”attachments” expression=”itemPhoto,itemVideo?”

#[itemPhoto,itemVideo?”]

return a map containing key-value pairs for the two specified attachments. Since itemPhoto is not optional, an error occurs if this attachment does not exist. The keys are the names of the headers ("itemPhoto" and :"itemVideo").

evaluator="attachments-list" expression="itemPhoto,itemVideo?"

#[itemPhoto,itemVideo?”]

Like the example above, except that it returns a list of the attachments instead of a map.

evaluator="attachments" expression="OUTBOUND:a*z"

#[headers:OUTBOUND:a*z]

return a map of all inbound attachments whose names begin with “a’ and end with “z”.

Bean Evaluator

The Bean evaluator can evaluate (possibly nested) bean properties of the current message’s payload.

Examples:

evaluator=”bean” expression=”vendor.location.city”

#[bean:vendor.location.city]

returns the city property of the location property of the vendor property of the payload. It is an error if any of these properties do not exist.

Endpoint Evaluator

The endpoint evaluator returns the address of a global endpoint.

Examples:

*evaluator="endpoint" expression="inboundOrders.address"

#[endpoint:inboundOrders.address]

returns the address of the global endpoint named inboundOrders. It is an error if the endpoint does not exist.

Exception-Type Evaluator

The exception-type evaluator can only be used with the <expression-filter> filter. It returns true if

Accepts the message if the exception in its exception payload is a MessagingException.

Function Evaluator

This returns various pieces of information about the running Mule instance, depending on the expression supplied:

"count"

Returns an application-wide count which begins at 0 and is incremented each time this expression is evaluated

"date"

Returns a java.util.Date object with the current time and date

"datestamp"

Returns an string with the current time and date. Optionally, “datestamp.format” can be specified, where “format” is a SimpleDataFormat used to format the string.

"hostname"

Returns the name of the machine Mule is running on.

"ip"

Returns the IP address of the machine Mule is running on."count"

"payloadClass"

Returns the full class name of the current message’s payload

"shortPayloadClass"

Returns the simple class name of the current message’s payload

“systime”

Returns the value from System.currentTimeMillis()

“uuid”

Returns a newly generated UUID

Groovy Evaluator

Returns the value of running the groovy expression supplied.

Example:

evaluator="groovy" expression="payload.items[0].value"

#[groovy:payload.items.value]

returns the value of the first item in the current message’s payload’s item array.

Header Evaluators

There are several evaluators that return the values of message header in different ways. They all have the same basic format for the expression, which is the name(s) of the header(s), optionally preceded by the name of the message scope followed by a colon. (If no scope is provided, the scope defaults to OUTBOUND.) Both the scope name and header names are case-insensitive, but the convention is to put the scope name in capitals and the header names in lowercase. The evaluators that return multiple headers work in one of two ways:

If the expression contains a wildcard marker, they return all the headers whose names match the wildcard expression.

Otherwise, the expression contains a camma-separated list of header names. Iit is an error for a header not to be present, unless the name is followed by a question mark , which marks it as optional.

Examples:

evaluator="header" expression="OUTBOUND:encoding"

#[header:OUTBOUND:encoding]

returns the value of the outbound header “encoding”. If this header is not set, an error occurs.

evaluator="headers" expression="OUTBOUND:encoding,INVOCATION:userId?"

#[headers:OUTBOUND:encoding,INVOCATION:userId?]

returns a map containing key-value pairs for the two specified headers. Since OUTBOUND:encoding is not optional, an error occurs if this header does not exist. The keys are the simple names of the headers "encoding" and :"userId".

Like the example above, except that it returns a list of the header values instead of a map.

evaluator="headers" expression="OUTBOUND:a*z"

#[headers:OUTBOUND:a*z]

Return a map of all outbound headers whose names begin with “a’ and end with “z”

JSON Evaluators

There are two evaluators that evaluate expressions on the JSON value of the current payload. It can optionally compare two expressions for equality to return a boolean value. The json evaluator always returns simple Java objects, while the json-node evaluator will, when appropriate, return JsonNode objects:

Returns “Tom”. The same would be true if the evaluator were json-node.

evaluator="json" expression="/user/registered = true"

#[json:/user/registered = true]

Returns false. The same would be true if the evaluator were json-node.

evaluator="json" expression="/user"

#[json:/user]

Returns the string “user” : \{“name” : “Tom”, registered : false} . If the evaluator were json-node, it would return a JsonNode object that corresponds to this information.

Map-payload Evaluator

This evaluator assumes that the current message’s payload is a map, and returns a subset of the entries in that map. The expression is a comma-separated list of strings, which are used as keys into the payload, and the return value is a map containing the entries corresponding to those keys. it is an error if any of those keys does not exist in the payload, unless that key is marked as option by ending with a question mark .

Example

evaluator=”map-payload” expression=”customer,discount?”

#[map-payload:customer,discount?”]

Return a map containing entries for the two specified keys. Since customer is not marked optional, an error occurs if this key does not exist.

Message Evaluator

The returns various information about the current message, depending on the expression supplied:

These apply if a message has been split into smaller messages, called a “correlation group”

correlationGroupSize

The number of messages resulting from the split

correlationId

The unique ID that identifies all of the messages resulting from the split

correlationSequence

The index of the message within the correlation group

These apply in general

encoding

The encoding used by the message (e.g. “UTF-8”)

exception

If the current message has an exception payload, its exception. Otherwise, null.

payload

The message’s payload

replyTo

The address (if any) to which a reply to this message should be sent.

OGNL evaluator

This uses OGNL (Object Graph Generation Language) to extract information from the current message’s payload. OGNL is a very powerful language, which is described here. Only a small subset of its capabilities will be given as examples.

Examples

evaluator =”ognl” expression=”item” #[ognl:item]

Returns the “item” property of the payload.

evaluator =”ognl” expression=”item[0].color”

#[ognl:item.color]

Returns the “color” property of the first item in the payload.

evaluator ="ognl" expression=’item[0].color == "red"’

#[ognl:item.color == "red"]

Returns true if the color of the first item in the payload is red.

Payload Evaluator

This returns the current message’s payload, optionally converted to a different type.

Process Evaluator

This runs a global, named message processor and returns the result. By default, the input to the message processor is the current message, but it’s possible to specify an alternate message to be processed instead.

Examples

evaluator=”process” expression=”myTransformer”

#[process:myTransformer]

Returns the result of running the global message processor named “myTransformer” on the current message

evaluator=”process” expression=”myTransformer:ognl:items]

#[process:myTransformer]

Returns the result of running the global message processor named “myTransformer” on the items property of the current message’s payload

Regex Evaluator

This returns true or false depending on whether the current message’s payload matches the specified regular expression. This can only be used with the ExpressionFilter.

Example:

1

<exception-filter evaluator="regex" expression="a.*z"/>

Accepts the message if its payload begins with “a” and end with “z”.

Registry Evaluator

This evaluator can only be used with the expression filter. It returns the boolean value of an object from the Mule registry or, optionally, one of its properties. A few options apply:

By default, an error occurs if the object is not present in the registry, but if the name is followed by a star , the object is considered optional, so instead a null is returned.

If the name is followed by a period (.), a (possibly nested) property of the object is returned, as if by the Bean evaluator.

Accepts the message if the repeat property of the registry object allowRequests has the boolean value true.

String Evaluator

The String Evaluator allows you to use multiple other evaluators and paste their results together, possibly together with some plain text. In effect, the String evaluator gives you the same freedom to use multiple evaluators that you get when using expressions in constructs that don’t require a specific evaluator (for example, dynamic endpoints). For this reason, it is never necessary to use the String Evaluator in those contexts.

Examples

evaluator=”string” expression=”There are #[ognl:items.size()] items in the order, which was received at #[function:date]”

Formats a string describing the current message.

Variable Evaluator

The variable evaluator returns the value of a flow variable. Examples:

evaluator=”variable” expression=”userId”

#[variable:userId”]

Return the value of the flow variable “userId”. If this variable is not set, an error occurs.

Wildcard Evaluator

This returns true or false depending on whether the current message’s payload matches the specified wildcard expression. This can only be used with the ExpressionFilter.

Example:

1

<exception-filterevaluator="wildcard"expression="a*z">

Accepts the message if its payload begins with “a” and end with “z”.

XPath Evaluators

There are two evaluators that execute XPath expressions against the current message. The xpath evaluator, which always returns simple Java types (Double, Boolean, String) and the xpath-node evaluator, which can also return Node objects.

Examples:

evaluator=”xpath” expression=”count(//items/item/)”

#[xpath:count(//items/item/)]

Returns the total number of items in the current message

<evaluator=”xpath-node” expression=”//items/item”>

#[xpath://items/item]

Returns the second “item” node from the current message

Creating a Custom Evaluator

A custom evaluator is simply a Java class that implements the org.mule.api.expression.ExpressionEvaluator interface. This contains three methods:

getName(), which returns the evaluator’s name

setName(), which can be used to rename the evaluator. This is generally a no-op.

Enrichers

Where evaluators are objects used to retrieve data (generally from messages), enrichers are objects used to set data in messages. They are used as targets in the message enricher (see Message Enricher. Currently, Mule supports two of them.

The variable enricher sets the value of flow variables.

The header enricher sets the value of message headers

Both have syntax very similar to that of the corresponding evaluators, but have the opposite effect (setting a value rather than retrieving it.)