Handling Groovy Scripts in Mule ESB

In my work project we had to make plenty of XML manipulations on some complex structures. As Mule supports Groovy (scripts) natively, we decided to make use of Groovy’s XMLSlurper. Two things I wanted to have covered, before I begin: How to easily handle those scripts in Mule Studio and how to unit test them.

1. Groovy scripts in Mule Studio

Mule, when it comes to Groovy components, can embed script code inside the Mule configuration file or use an external script file. Of course, at all times, I don’t want to clutter my Mule code with embedded scripts. The only exception I make, is when I need to do something simple and I’m unable to use Mule Expression Language to achieve that (i.e. throwing an exception directly from flow - JIRA).

First thing I did was installation of Groovy plugin for the IDE. Latest Mule Studio version is 3.5.0, which is based on Eclipse 3.8. Update site URL for the plugin is: http://dist.springsource.org/release/GRECLIPSE/e4.2/. My example project was built on Mule ESB 3.4.0. It uses Groovy 1.8.6, hence we have to add an extra Groovy compiler when installing plugin and we have to switch it on in Groovy preferences afterwards.

Next, we need to think about where to locate our scripts. There are several possibilities, but I find most convinient to put them in src/main/scripts in a subfolder named as a Mule configuration file, which uses it. Then, we need to force IDE to be as useful as possible, especially the m2e plugin built in Mule Studio. I always work on Maven-supported Mule projects and strongly recommend to do the same.

  • Enable Groovy scripts folders in Groovy preferences and add src/main/scripts and src/test/scripts patterns (note that Compiler version is already set to 1.8.6):

  • Now we need to make sure that Maven will put those scripts in proper location. Ideal for me, is to put them in classes/scripts directory. It will cause nice separation with other project resources. Achieving that appeared to be simple. In pom.xml specify resources in the <build> part:
 1<build>
 2    <resources>
 3        <resource>
 4            <directory>src/main/resources</directory>
 5        </resource>
 6        <resource>
 7            <directory>src/main/scripts</directory>
 8            <targetPath>scripts</targetPath>
 9        </resource>
10    </resources>
11    ...
12</build>

Maven’s build <resources/> element is described here. When doing research about the above I found out something interesting. With the default structure of pom.xml file generated by Mule Studio, all Mule configuration files are duplicated in the built zip file. Sample Mule application structure generated by Maven would look like:

1 \- classes
2  \- mule-config.xml
3  |- mule-deploy.properties
4  |- mule-app.properties
5 |- lib
6 |- mule-config.xml
7 |- mule-deploy.properties
8 |- mule-app.properties

Files (2,3,4) are redundant (per Mule’s application format reference). Responsible for that mess is Build Helper Maven Plugin:

 1<plugin>
 2    <groupId>org.codehaus.mojo</groupId>
 3    <artifactId>build-helper-maven-plugin</artifactId>
 4    <version>1.7</version>
 5    <executions>
 6        <execution>
 7            <id>add-resource</id>
 8            <phase>generate-resources</phase>
 9            <goals>
10                <goal>add-resource</goal>
11            </goals>
12            <configuration>
13                <resources>
14                    <resource>
15                        <directory>src/main/app/</directory>
16                    </resource>
17                </resources>
18            </configuration>
19        </execution>
20    </executions>
21</plugin>

If I remove that plugin part, everything still seems to be working perfectly fine and my project’s output structure is neat and clean:

1 \- classes
2  \- scripts
3   \- GroovyScriptTesting
4    \- CalculateSquareNumber.groovy
5  |- log4j.properties
6 |- GroovyScriptTesting.xml
7 |- mule-deploy.properties
8 |- mule-app.properties

It looks like maven-mule-plugin is doing all the necessary work for src/main/app folder. So, if you know why the build helper plugin is set up in the pom.xml in the first place or if you’re having any problem without it, please let me know. In the end, with everything in place, my project in Mule Studio should look like this:

and we are ready to go to the second part.

2. Unit testing Groovy scripts

Mule provide direct access to Mule context objects and variables in Groovy scripts the same way as it does for MEL. In terms of testing, it’s important to decide and be consequent about how we are accessing Mule variables: If I’m sure that the variable will be defined during script execution, I access them directly (as ‘number’ in the example):

1def square = number.toInteger() * number.toInteger()

If it’s possible that the variable won’t be set up (can be a part of the script logic - to check for variable presence), then I would try to get it from the message context (it’s always available):

1def number = message.getInvocationProperty('number')

and then do some null checks etc. Otherwise, I would get Groovy’s MissingPropertyException. Setting variables via scripts always needs to happen using message.setProperty method.

Let’s look at this simple Groovy script (CalculateSquareNumber.groovy):

1def square = number.toInteger() * number.toInteger()
2message.setInvocationProperty('squareNumber', square)

and it’s unit test (CalculateSquareNumberTest.java):

 1@RunWith(JUnitParamsRunner.class)
 2public class CalculateSquareNumberTest {
 3
 4    private static final String PAYLOAD = "payload";
 5
 6    @Test
 7    @Parameters(method = "numbersAndSquares")
 8    public void test(int number, int square) throws Exception {
 9
10        Binding binding = new Binding();
11        binding.setVariable("number", number);
12        binding.setVariable("message", TestMuleMessage.withPayload(PAYLOAD));
13
14        GroovyShell shell = new GroovyShell(binding);
15        shell.evaluate(getFile("/scripts/GroovyScriptTesting/CalculateSquareNumber.groovy"));
16        MuleMessage message = (MuleMessage) binding.getVariable("message");
17
18        assertThat((Integer)message.getInvocationProperty("squareNumber"), is(square));
19    }
20
21    @SuppressWarnings("unused")
22    private Object[] numbersAndSquares() {
23        return $(
24             $(3, 9),
25             $(5, 25),
26             $(10, 100),
27             $(12, 144)
28        );
29    }
30
31    private File getFile(String pathToFile) throws URISyntaxException, FileNotFoundException {
32        URL url = CalculateSquareNumberTest.class.getResource(pathToFile);
33        if (url == null) {
34            throw new FileNotFoundException("Couldn't find: " + pathToFile);
35        }
36        return new File(url.toURI());
37    }
38}

To evaluate Groovy scripts in our test we need to use GroovyShell along with Binding’s setVariable() method to make variables available. As you can see it’s pretty easy, the trickier part is how to pass proper MuleMessage instance to our test. To do that, I have prepared helper TestMuleMessage class, which is preparing message with default Mule context:

 1public class TestMuleMessage {
 2
 3    public static MuleMessage withPayload(Object payload) {
 4
 5        MuleContextFactory contextFactory = new DefaultMuleContextFactory();
 6        MuleContext muleContext = null;
 7        try {
 8            muleContext = contextFactory.createMuleContext();
 9        } catch (InitialisationException e) {
10            e.printStackTrace();
11        } catch (ConfigurationException e) {
12            e.printStackTrace();
13        }
14
15        return new DefaultMuleMessage(payload, muleContext);
16    }
17}

Another useful thing in the test is the helper getFile() method which retrieves script file not from hardcoded full path, but from classpath instead, which is always a better idea. Usually, you would put it in some test util class. Your main target for assertions is MuleMessage object, which can be retrieved using Binding getVariable() method. There you can check for variables’ values or message payload itself. As you can see, keeping few simple rules, can make work with Groovy scripts (in Mule) a pleasant, easily testable experience. Sample project, I prepared, is using Quartz endpoint and Groovy script to count and display square number of number 5 :) It is available here.

Comments