Apache Groovy is a powerful object oriented programming language for Java platform. Its simplicity and easy to learn syntax had made it the preferred scripting language for developers. We will implement groovy script in a Mule flow to demonstrate the smooth integration of groovy script in a Mule application.
- Basic working knowledge on Mule ESB development using Anypoint Studio.
- Basic knowledge on any object-oriented programming language is an added advantage.
In this simple example, we will build a Mule application with an HTTP listener which will be inputted with the below query parameters:
The Mule application will be configured with a groovy component which will print the sum of parameter 1 and parameter 2 as the response.
HTTP Inbound Endpoint:
An HTTP inbound endpoint is created by dragging the HTTP connector component from the palette to the canvas. An HTTP connector configuration is created which will listen to the localhost on port 8081 and the path in which the resource can be accessed will be “groovy”.
We will have 3 session variable components to extract the query parameters from the input url and save it to the session variables configured in the flow.
A groovy component is placed next to the session variable components in which we sum up the values of parameters passed.
Note: We need to use the toInteger() function to convert the string into integer. When the query parameter is assigned to the session variable its data type is string. In order to convert the string to integer we use the toInterger() function.
We will use a logger to log the values of the session variables in the console.
We will place a Set Payload component to complete the Mule flow. The Set Payload component will print the message in the following format as output.
Hello “Name” !!! The sum of “Parameter1” and “Parameter2” is “Sum” !!!
Testing the Mule flow:
It’s time to test the Mule application we have built. We can use any browser or tools such as SOAP UI or the Postman Chrome plug-in which is capable of posting a HTTP request. Using the chrome browser, try to post the following: localhost:8081/groovy?name=Karthik¶meter1=4¶meter2=65