When we use WSO2 ESB, we might find some difficulties to achieve small things which we can easily do using regular programming languages. Yes, ESB is not a platform that we use to do programing… Simply we configure a message flow using XML to achieve some task. But ESB is powerful enough to do most of the things that we do using programing language. I’m going to explain few tricks that we can use with WSO2 ESB
Evaluate multiple conditions in single Filter mediator
For an example, we might need to check whether the given age is within the allowed range or not. In this case obviously we have two conditions.
- givenAge > minAge
- givenAge < maxAge
So normally we can use two filters (one filter within another) to test this. Instead we can use xPath to achieve this. Following code snippet is sample filter with xPath
<filter source="get-property('minAge') > get-property('givenAge') and get-property('givenAge') < get-property('maxAge')" regex="true"> <then><!—your success path --> </then> <else><!—your failure path --> </else> </filter>
Please note that minAge, maxAge and givenAge is defined as properties. The regex value is what we expect from the xpath evaluation, probably true or false.
Dynamic xpath within xslt mediator
Let’s say you have a payload like follows
<school xmlns ="http://sample.dineshjweerakkody.com/xslt/xpath"> <students> <student> <name>Dinesh</name> <age>27</age> <class>c1</class> </student> <student> <name>Amila</name> <age>29</age> <class>c2</class> </student> </students> <classes> <class> <code>c1</code> <name>WSO2 ESB</name> </class> <class> <code>c2</code> <name>WSO2 API Manager</name> </class> </classes> </school>
And you need to generate the output as follows
<school xmlns ="http://sample.dineshjweerakkody.com/xslt/xpath"> <students> <student> <name>Dinesh</name> <age>27</age> <class>WSO2 ESB</class> </student> <student> <name>Amila</name> <age>29</age> <class>WSO2 API Manager</class> </student> </students> </school>
I’ll show you how to do it. Simply we can do this using XSLT Mediator. It’s just a matter of generating a xpath dynamically to match the correct class name.
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:ns1="http://sample.dineshjweerakkody.com/xslt/xpath"> <xsl:template match="/"> <school xmlns ="http://sample.dineshjweerakkody.com/xslt/xpath"> <students> <xsl:for-each select=" ns1: school /ns1: student "> <student> <name><xsl:value-of select="ns1:name" /></name> <age><xsl:value-of select="ns1:age" /></age> <xsl:variable name="classCode" select="ns1:class"></xsl:variable> <class><xsl:value-of select="//ns1:classes/ns1:class[ns1:code=$classCode]/ns1:name" /></class> </student> </xsl:for-each> </students> </school> </xsl:template> </xsl:stylesheet>
So we generate a filter dynamically based on a value of current iteration to find an element which is in the same document but different path.
That’s it… I’ll add few more in time to come…