As Mule consultants, one issue we seem to repeatedly face is the excessive amount of time spent building the input/output structure of the DataMapper. The DataMapper in Mule 3.4 helps you solve this issue if you have XML, by importing the input using an XSD. The same with JSON, you can provide a JSON sample. But when it comes to other things, like Maps and List of Maps, it becomes very time consuming.
This issue occurs most often when dealing with databases. A JDBC select statement in Mule returns either a Map, or a List of Maps. Each time you want to use the DataMapper, you have to build the input structure manually. In Mule 3.5.0, Mule uses DataSense with the new JDBC connector to help simplify this process, however if you are stuck with an older version of Mule, you will most likely face this issue at some point.
The DataMapper allows you to supply a Groovy sample, so how can we use this to make our job easier? Well you can use a Logger to display the payload after the JDBC call, but the logger displays the output in a different way to how you would write it in Groovy. The following is a List of Maps printed using the Logger. Note that one of the elements of the first Map is another Map:
If we supply this input to the DataMapper as a Groovy sample, it won’t get us anywhere. To solve the problem, we have written a simple Groovy script that displays the elements as you would write them in Groovy. The same List of Maps shown above will be printed as follows:
As you can see, the String elements are enclosed in single quotes. Both Maps and Lists are enclosed in square brackets, and Map key and value pairs are separated using colon. This is exactly what Groovy is expecting. If we copy the printed result and supply it to the DataMapper, it happily creates the input/output structure:
Here is the Groovy script:
To make this work in Mule, drop a Groovy component message processor, and paste the script inside the script text section. It prints the object without affecting the original payload.
Once done, you can copy the printed object from the logs and supply it to the DataMapper.
I hope you have enjoyed this blog post and that you find this information useful.
(This post first published; 27th May 2014 on blog.ricston.com)