It is pretty common that Mule messages contain XML as a payload and that those messages need to be validated/transformed. XML documents can be automatically validated using XSD, though those validations are structural and sometimes we need to manually code some validation in plain Java (especially in complex scenarios like validating references, existence conditions and value dependencies).
As an example, let’s consider consider an application that needs to validate your bank statement. The structure of transactions is defined in an XSD file; however we need to validate the following conditions:
- Check the ‘type’ in Transaction. If it is STANDINGORDER or FEE then the amount must be negative
- Make sure that the start balance and the sum of transaction amounts is equal to the end balance
- All transactions must be dated before the statement date
Instead of coding these validation rules we will use Absolute Rule. Absolute Rule provides a powerful new way to create validation and transformation rules based on the Natural Rules Language (NRL). This helps when business knowledge is in the heads of business analyst who are not programmers. They can write the rules in NRL and then automatically derive a set of Java classes that developers can plug into Mule. As an example of the use of Absolute Rule, check the following video:
Going back to our example, a very intuitive version of the previous rule written in NRL is as follows:
The Absolute Rule Eclipse plugin transforms these rules to code on every edit; the following Java class used to validate the XML document is shown next:
Now the Mule part: we would like to validate messages that we receive over an VM connection. To do so we need to add the absoluterule:validation tag into our flows, invoking the Java code generated by the AbsoluteRule Eclipse plugin. Check the following flow:
Notice that we enrich the message with the result of validating the XML document and in case that any error exists (using a choice with a groovy expression) we move the message to an error queue.
Want to check the full example? check our Git repository.