Back to Home or Mule Components

Expression Types (Evaluators)

  • attachment, attachments, attachments-list
  • bean - Spring bean values can be extracted and changed
    With Mule 3.3, use MEL:
    <when expression="#[app.registry.myBean.myMethod()]">
    With older Mules, use Groovy:
    
    <when expression="muleContext.registry.lookupObject('myBean').myMethod()" evaluator="groovy">
  • endpoint - Get or check, display attributes on one of the projects enpoints
    #[endpoint:myEP.address]
  • exception-type check for an exception, this is largely replaced by the Mule Error Handling component
     #[exception-type:java.lang.RuntimeException] 
  • function - Performs a function: now, date, datestamp, systime, uuid, hostname, ip, or count.
    E2E_[function:datestamp:dd-MMM-yyyy].html

    will create a filename: E2E_14-Jan-2013.html

* groovy - Evaluates the expression using the Groovy language. (see below)

  • header, headers, headers-list (see below)
  • json, json-node
    // extract the command 
    //{ command : '/etc/init.d/activemq restart'}
    #[json-node://command]
  • jxpath - JXPath expression that works on both XML/DOM and Beans.
  • map-payload - Returns a value from within a java.util.Map payload.
    map-payload is deprecated: if the payload is a map you can get its values directly with MEL.
    So assuming you have a text column named destination, the following should work:
    <when expression="#[message.payload.destination == 'SFO']" >
    or 
    <when expression="#[payload.destination == 'SFO']" >
    depending on whether the message is coming off a jms or not 
  • message - Is an object passed to each element of a message flow for example the Get parameters ?db=myDb1 are extracted from the inbound properties of the messag:
    #[message.inboundProperties['db']]

    The message itself has the properties id, correlationId, correlationSequence, correlationGroupSize, replyTo, payload, encoding, and exception

  • ognl The open source expression syntax often used by Apache e.g. #[ognl:[MULE:0].equals(42)]
  • payload - this can be the main data load e.g. html body posted or xml body in a jms message.
  • payload-type Payload can be of variety of types, String for html, objects or Maps for jdbc queries. We can query the type #[payload:java.lang.String] and this matches the type of the payload.
  • process - Invokes a message processor within an expression. This processor can be any component, transformer, custom processor, processor chain or flow.
     (MessageProcessor) muleContext.getRegistry().lookupFlowConstruct(name);
      MuleEvent result = flow.process(testEvent);     
      assertNotNull(result.getMessage());

* regex perform regex comparison on the payload value

 <when expression="#[regex:.*berry]"> 

* string Evaluates the expressions in the string.

  • variable - Used for retrieving values of flow variables. e.g #[variable:variableName]
  • wildcard -
    #[wildcard:*.txt]	
  • xpath - The expression is an XPath expression.
#[xpath://fruit]
#[xpath('//title').text]
#[xpath('//title/@id').value]
  • xpath-node - Returns the node object from the XPath expression as is
    #[xpath-node://fruit]	 
     
    <expression-transformer name="xpathTransformer">
           <return-argument expression="#[xpath-node:/root/table/name"/>
    </expression-transformer>

* exception .when processing an exception in an exception flow #[exception]. Groovy is passed a muleException

Expression Operators

  • The usual +, -, /, * and %.
  • == allegedly the comparison operator .. but see the choice examples below a single equals appears to work when double equals doesn't
  • !=, >, < , >=, ⇐,
  • contains . True if the string on the right is a substring of the string on the left e.g 'fubar' contains 'bar' returns true
  • strsim - Degree of similarity. The value of the expression is a number between 0 and 1 representing the degree of similarity between the two string arguments. e.g 'foo' strsim 'foo' 1.0
  • soundslike - Sounds like. True iff the two string arguments sound alike according to a Soundex comparison. e.g 'Robert' soundslike 'Rupert' true
  • and logical AND. True iff both operands are true. (Don’t use &&) e.g ((a == b) and (c != d)
  • || Logical OR.
  • or Chained OR. Scans left to right and returns the value of the first non-empty item
  • endsWith string ends with value
   <when expression="#[message.inboundProperties['filename'].endsWith('.jpg']">
      <file:outbound-endpoint path="/home/me/photos" />
    </when>

Get/Set Variables

Setting and Modifying variables can be done via the “Message Properties” transformer

<message-properties-transformer doc:name="Message Properties" scope="invocation">        	
            <add-message-property key="dealId" value="#[xpath://RMSDealID]"/>
        </message-properties-transformer>

Note: the scope explicit set to invocation

Accessing the set variables. One can

        
   <logger  message="#[variable:dealId]"  level="ERROR"/>

This risks throwing a null pointer if the variable is null, one can check for empty values on variables using the following

#[org.mule.util.StringUtils.isNotEmpty(sessionVars['exceptionStatus'])]

or use groovy

   #[groovy:message.getInvocationProperty('dealId')]

This will return “{NullPayload}” if null however we can return empty (or any predefined value with)

#[groovy:message.getInvocationProperty('dealId2') ?: '']

Http Headers

Header Values Notes
http.request=/favicon.ico
Host=localhost:8081
http.method=GET
http.headers={Accept-Language=en-US,en;q=0.8, Host=localhost:8081, Accept-Charset=ISO-8859-1,utf-8;q=0.7,*;q=0.3, Accept-Encoding=gzip,deflate,sdch, User-Agent=Mozilla/5.0 (X11; Linux i686) AppleWebKit/535.8 (KHTML, like Gecko) Chrome/17.0.922.0 Safari/535.8 SUSE/17.0.922.0, Keep-Alive=true, Connection=true, Accept=*/*}
http.relative.path=favicon.ico
User-Agent=Mozilla/5.0 (X11; Linux i686) AppleWebKit/535.8 (KHTML, like Gecko) Chrome/17.0.922.0 Safari/535.8 SUSE/17.0.922.0
http.request.path=/favicon.ico
MULE_ORIGINATING_ENDPOINT=endpoint.http.localhost.8081
Connection=true
http.query.string=
http.context.path=/
Accept-Language=en-US,en;q=0.8
http.context.uri=http://localhost:8081
http.version=HTTP/1.1
http.query.params={}
Accept-Charset=ISO-8859-1,utf-8;q=0.7,*;q=0.3
MULE_REMOTE_CLIENT_ADDRESS=/127.0.0.1:40358
Accept-Encoding=gzip,deflate,sdch
Keep-Alive=true
Accept=*/*
http.request=/test/hello
Host=localhost:8081
http.method=GET
http.headers={Accept-Language=en-US,en;q=0.8, Host=localhost:8081, Accept-Charset=ISO-8859-1,utf-8;q=0.7,*;q=0.3, Accept-Encoding=gzip,deflate,sdch, User-Agent=Mozilla/5.0 (X11; Linux i686) AppleWebKit/535.8 (KHTML, like Gecko) Chrome/17.0.922.0 Safari/535.8 SUSE/17.0.922.0, Keep-Alive=true, Connection=true, Accept=text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8}
http.relative.path=test/hello
User-Agent=Mozilla/5.0 (X11; Linux i686) AppleWebKit/535.8 (KHTML, like Gecko) Chrome/17.0.922.0 Safari/535.8 SUSE/17.0.922.0
http.request.path=/test/hello
MULE_ORIGINATING_ENDPOINT=endpoint.http.localhost.8081
Connection=true
http.query.string=
http.context.path=/
Accept-Language=en-US,en;q=0.8
http.context.uri=http://localhost:8081
http.version=HTTP/1.1
http.query.params={}
Accept-Charset=ISO-8859-1,utf-8;q=0.7,*;q=0.3
MULE_REMOTE_CLIENT_ADDRESS=/127.0.0.1:40359
Accept-Encoding=gzip,deflate,sdch
Keep-Alive=true
Accept=text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8

Common http header choice block operation:

URL expression mapping like: http://localhost:8080/status

     <when expression="INBOUND:http.request.path=/status" evaluator="header">             
                <processor-chain>
                    <component class="CheckStatus" doc:name="CheckStatus"/>
                </processor-chain>
            </when>
             <when expression="message.getInboundProperty('http.request').equals('/groovy')" evaluator="groovy">
                <processor-chain>
                    <scripting:component doc:name="Groovy">
                        <scripting:script engine="Groovy">
                            <scripting:text><![CDATA[return "ok from groovy"]]></scripting:text>
                        </scripting:script>
                    </scripting:component>
                </processor-chain>
            </when>
            <!-- handle favicon.ico requests -->
            <when expression="INBOUND:http.request.path=/favicon.ico" evaluator="header">  
               <set-property value="200" propertyName="http.status" doc:name="Property" />            
            </when>

Note: the following two types of expression are equivalent:

  <when expression="INBOUND:http.request.path=/status" evaluator="header">  
  <when expression="#[header:INBOUND:http.request.path = /create]">

Outbound Properties

Outbound properties have a number of additional properites that can be set ie. MimeType. This can be set in script or property settings

<set-property propertyName="Content-Type" value="text/xml" />

Express Flow Control

MEL provides a full range of Java control flow statements. The most useful for typical MEL expressions are conditional operands (often called ternary statements).

A conditional operand has the form condition ? true value, false value.

For example, x = (name == 'Smith' ? 'Smith', 'Unknown') sets the variable x to the string “Smith” if the value of name is “Smith” and to the string “Unknown” if the value of name is not “Smith”.

Expression Filters

Some filters used with flow control like the Choice block:

  • or, and, not filters

Or Filter

 <when>
  <or-filter>
       <expression-filter condition#1/>
       <expression-filter condition#2/>
  </or-filter>
  </when>

And Filter

<and-filter>
  <message-property-filter pattern="JMSCorrelationID=1234567890"/>
  <message-property-filter pattern="JMSReplyTo=null"/>
</and-filter>

Not Filter

<not-filter>
  <payload-type-filter expectedType="java.lang.String"/>
</not-filter>

Groovy Expression

Default Classes passed to Groovy scripts are

Class Notes
log Makes sense for script component but not in an expression
result Makes sense for script component but not in an expression
muleContext
registry No need to expose this if muleContext is exposed.
message
payload
exception Used in the Exception Catch Strategy, passed if an exception has occured
src same as 'payload', can cause confusion, suggest not even documenting.
  message.setOutboundProperty('foo','bar')
  return payload

Using the following groovy code:

The following groovy script will print the passed message headers, message and session variables and values:

def data = ""
if ( message != null ){
    message.getInboundPropertyNames().each{
      data += "|" + it + " |" + message.getInboundProperty(it) + " | \n"
	}
    // print the message variables 
	message.getInvocationPropertyNames().each{
 	  data += "|Variable: " + it + " |" + message.getInvocationProperty(it) + " | \n"
	}
   // print the session variables
	message.getSessionPropertyNames().each{
     data += "|Session Var: " + message.getSessionProperty(it) + " | \n"
   }
}
 
System.err.println data
return data

The following are the Inbound Properties for http requests, for the request url:

http://localhost:8081/groovy?test=value
Property Example Value
http.version HTTP/1.1
Accept-Encoding gzip,deflate,sdch
Connection true
http.context.uri http://localhost:8081
Accept-Charset ISO-8859-1,utf-8;q=0.7,*;q=0.3
http.request /groovy?test=value
http.headers [Accept-Language:en-US,en;q=0.8, Host:localhost:8081, Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3, Accept-Encoding:gzip,deflate,sdch, User-Agent:Mozilla/5.0 (X11; Linux i686) AppleWebKit/535.8 (KHTML, like Gecko) Chrome/17.0.922.0 Safari/535.8 SUSE/17.0.922.0, Keep-Alive:true, Connection:true, Accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8, Cache-Control:max-age=0]
http.relative.path groovy
Keep-Alive true
http.method GET
MULE_ORIGINATING_ENDPOINT endpoint.http.localhost.8081
http.query.params [test:value] Note Get requests can be extracted with
#[message.inboundProperties['test']]
Cache-Control max-age=0
Accept-Language en-US,en;q=0.8
Host localhost:8081
http.context.path /
User-Agent Mozilla/5.0 (X11; Linux i686) AppleWebKit/535.8 (KHTML, like Gecko) Chrome/17.0.922.0 Safari/535.8 SUSE/17.0.922.0
MULE_REMOTE_CLIENT_ADDRESS /127.0.0.1:40613
Accept text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
http.request.path /groovy
test value
http.query.string test=value

If you put the same request on Mule Vm you get the additional headers:

MULE_ORIGINATING_ENDPOINT endpoint.http.localhost.8081
MULE_REMOTE_CLIENT_ADDRESS /127.0.0.1:40618

Exception Strategy in Groovy

The Exception handling strategy can be used to catch and processes exceptions that occur a flow:

The MuleException class will be passed to the groovy by default, with methods like:

exception.getCause()
exception.getDetailedMessage()

the full method and api for Mule Exceptions

Groovy: Accessing Spring Bean Data

Groovy is passed a registry with the spring beans. We can get and modify the values e.g modify an sqlite spring bean url

def bean = registry.get("jdbcDataSource3")  // get the spring bean
def dbName = message.getInboundProperty('http.query.params')['db'] // get the query param 
bean.url = "jdbc:sqlite:/Users/Owner/MuleStudio/workspace/datamappertesttwo/db/" + dbName +"-esb.db" // set the new bean url parameter

Groovy and File Type Choice Block

<when evaluator="groovy" 
				expression="message.getOutboundProperty('originalFilename') ==~ /.*\.csv$/">

Regex

 <when expression="#[regex:.*berry]">
 <when expression=".*berry" evaluator="regex">     
 // also used for flexible evaluation in flow exception handling 
   <until-successful objectStore-ref="objectStore"
                          ackExpression="#[string:ACK]"
                          failureExpression="#[regex('(?i).*error')]"
                          maxRetries="2"
                          secondsBetweenRetries="1"
                          deadLetterQueue-ref="dlqChannel">       

Misc

  • Mule Test Case examples are available here
     http://grepcode.com/project/repo1.maven.org/maven2/org.mule.tests/mule-tests-integration/

Java

Mule Api

 
mule_expressions.txt · Last modified: 2014/04/11 03:27 by root
 
RSS - 200 © CrosswireDigitialMedia Ltd