Groovy Component in Mule

Groovy Component in Mule

In spite of the rich selection of elements available in Mule, you may find yourself in need to put together some custom code to carry out part of a complex task, if you’re comfortable coding in Groovy, then the Groovy Component is the ideal versatile tool to fall back on for these cases. Mule also includes also equivalent scripting components for other languages. The Groovy Component is also handy for when you’re modernizing legacy systems, as you can simply throw the old lines of code into a component instead of having to reengineer the code’s behavior through a series of different Mule components (this is not ideal from a debugging and maintenance perspective, though).

Groovy also allows the developer to configure interceptors and alter the values or references of particular properties in a script. Interceptors are configured to provide additional services to a message as it flows through a component. For example, a developer can configure an interceptor to execute scheduling or logging of a particular event while a message is being processed. The Groovy component also includes a custom interceptor which allows you to configure settings for Spring elements. Use the Advanced tab to access Script Properties, then define the value and reference for a particular property in the script.

Here we are using Message Enricher in mule 3 in Anypoint studio 6.2

Groovy component supports groovy code.We can write groovy script in it to modify the payload.

Mule flow of groovy component :

Here i have written a simple groovy code where input payload concatenate with String Hello.
You can write any groovy script in the script text.

URL :  http://localhost:8085/api/groovy

Method : POST

Input :

Output :

XML Project Code :

<?xml version="1.0" encoding="UTF-8"?>

<mule xmlns:json="" xmlns:http="" xmlns:scripting="" xmlns="" xmlns:doc=""
    <http:listener-config name="HTTP_Listener_Configuration" host="" port="8085" basePath="/api" doc:name="HTTP Listener Configuration"/>
    <flow name="testgroovyFlow">
        <http:listener config-ref="HTTP_Listener_Configuration" path="/groovy" doc:name="HTTP"/>
        <byte-array-to-string-transformer doc:name="Byte Array to String"/>
        <scripting:component doc:name="Groovy">
            <scripting:script engine="Groovy"><![CDATA[String str = "Hello";
String str1 = str + ' ' + payload;
        <logger message="#[payload]" level="INFO" doc:name="Logger"/>
        <set-payload value="#[payload]" doc:name="Set Payload"/>