How do you set message properties in Mule using Groovy?

10,736

Solution 1

In the scripting component you have available the message binding that is an instance of org.mule.api.MuleMessage, thus you can use the method org.mule.api.MuleMessage.addProperties(Map, PropertyScope) to add any property you need.

Solution 2

You can set individual properties as follows:

message.setInvocationProperty('myFlowVariable', 'value') // sets a flow variable, like <set-variable/>
message.setOutboundProperty('myProperty', 'value') // sets an outbound message property, like <set-property/>
message.setProperty('myInboundProperty', 'value', PropertyScope.INBOUND) // sets an inbound property

Solution 3

It depends on which version of Mule EE (and so then Groovy) you are using, but in recent versions of Mule (3.7.x) the easiest way is:

flowVars ['name_of_variable'] = 'value'
flowVars ['name_of_variable'] = 14

This for variables with Invocation scope, if you wan to store variable for Session scope, then:

sessionVars ['name_of_variable'] = 'value'
sessionVars ['name_of_variable'] = 14

Please use this site from Mulesoft for Scripting as reference.

https://docs.mulesoft.com/mule-user-guide/v/3.7/script-component-reference

Solution 4

Here is how I figured it out:

add schema to your flow if missing: xmlns:scripting="http://www.mulesoft.org/schema/mule/scripting" http://www.mulesoft.org/schema/mule/scripting http://www.mulesoft.org/schema/mule/scripting/current/mule-scripting.xsd

now let's set session-variable 'account' with a custom Foo object using Groovy:

   <scripting:transformer doc:name="Script">
     <scripting:script engine="groovy"><![CDATA[  
        com.test.Foo f = new com.test.Foo();
        f.setAccountId('333');
        return message.setSessionProperty('account',f);]]>
      </scripting:script>
    </scripting:transformer>

above script will turn your Payload to NullPayload, because it is a transformer. If that' a concern, try this instead:

<enricher target="#[sessionVars['account']]">
   <scripting:transformer doc:name="Script">
     <scripting:script engine="groovy"><![CDATA[  
       com.test.Foo f = new com.test.Foo();
       f.setAccountId('333');
       return f;]]>
     </scripting:script>
   </scripting:transformer>
 </enricher>

Enjoy. :)

Share:
10,736
Gary Sharpe
Author by

Gary Sharpe

LinkedIn: http://www.linkedin.com/in/garysharpe1/ Udemy: https://www.udemy.com/u/garysharpe/ GitHub: https://github.com/gmsharpe

Updated on June 17, 2022

Comments

  • Gary Sharpe
    Gary Sharpe almost 2 years

    How do you set message properties in Mule using Groovy?

    I need to set a message property from within a Groovy Scripting Component. Documentation on the subject does not appear to be easy to find.