DataWeave language is the primary expression language in Mule 4, and is encourage to use DataWeave whenever possible. However for practicality or for whatever reason, there is always some scenario that one wish to use other general purpose programming language, such as Groovy,Python to build some logic to achieve the same result, probably in elegant/faster/easier/better understandable way. So, it is always good that we have options.

In this example will explore Groovy Scripting in Mule 4.

Firstly, drag Scripting/Execute step into flow:


In Execute step, Code section put “${file::MyScript.groovy}”.
This is reference to groovy file named ‘MyScript.groovy’ in mule project. Reference to file instead of coding direct inside Execute step, enable us to develop, debug the groovy script externally using your choice of favorite editor (e.g. IntelliJ IDEA). This save time and improve productivity, because to test in mule project, will need deploy the whole mule flow every time some code change.


Script file should put at path ‘src/main/resources’. Note that should not physical go to file system to place the script, in stead should use import method.


To import groovy file, right click, Import..

Choose General,File System.


Browse to directory that contain script, here example put at folder ‘C:\AnyScript’. Tick to select scripts want to import, then Finish.


If the script required import statement reference to other external jars. Go to Java Build Path, Libraries, Add External JARs, then choose external jars required. Example:


Besides, need edit file “mule-artifact.json” to add resource want to export.
Reference: https://docs.mulesoft.com/mule-runtime/4.1/how-to-export-resources


Also need to add dependency in file “pom.xml” under dependencies. Example: added “common-io” version 2.6.


Next we can deal with the development of groovy script.
In groovy script, if want to directly use mule payload as string, will hit error, due to payload is of type inputStream. Need to convert inputStream to string first.

Below are 2 ways tested able to convert inputStream to string:

option 1: Using plain Java:

option 2: Using IOUtils.copy() function. Need import org.apache.commons.io.IOUtils in groovy script.


Full groovy script:
BuildOutput() function contain necessary code required.
TestRun() is for local development and test run to see the output.
In below groovy script is to transform nested json to flat json.


Input nested json:

Output flat json:

🙂

Import External Jars File and Run Groovy Script in Mule 4
Tagged on:             

Leave a Reply

Your email address will not be published. Required fields are marked *