Check for existence of element/property with Filter Mediator in WSO2 ESB

In day to day development , sometimes you will need to check for the existence of an element or property or some thing. In other words, you will need to check something if it is null. It can be easily done in WSO2 ESB using filter mediator.

Learning by example is the best way ,

Let’s take a simple example. Suppose there is a payload incoming like below

<user>
 <name>asanka</name>
 <role>admin</role>
</user>

Suppose you need to read this field into a property. and suppose <role/> is an optional element. In that case what are you going to do?

The expected behavior is , if role is not coming with the payload, it is considered as the default role “generic_user”.

So the following code segment of filter mediator will do it for you.

<filter xpath="//role">
   <then>
      <log level="custom">
         <property name="propStatus" value="role is available" />
      </log>
      <property name="userRole" expression="//role" />
   </then>
   <else>
      <log level="custom">
         <property name="propStatus" value="!!!!role is not available!!!!" />
      </log>
      <property name="userRole" value="generic_user" />
   </else>
</filter>

“xpath” attribute in filter element provides the xpath expression to be evaluated.
If the xpath expression is evaluated to “true”, synapse code in the “then” block will be executed.
Otherwise code in the else block will be executed.

If the evaluation of the xpath returns something not null. It will be considered as true. If it is null it will be considered as false.

If you want to play with this, create filter.xml with following content and copy it to

$CARBON_HOME/repository/deployment/server/synapse-configs/default/api

https://github.com/asanka88/BlogSamples/blob/master/ESB/nullcheck.xml

and make an HTTP POST to http://localhost:8280/user/rolecheck with following payloads.

<user>
 <name>asanka</name>
 <role>admin</role>
</user>

Check the log file and you will see following output.


[2016-04-11 22:49:38,041] INFO - LogMediator propStatus = role is available
[2016-04-11 22:49:38,042] INFO - LogMediator status = ====Final user Role====, USER_ROLE = admin

<user>
 <name>asanka</name>
</user>

Check the log file and you will see following output.


[2016-04-11 22:49:43,083] INFO - LogMediator propStatus = !!!!role is not available!!!!
[2016-04-11 22:49:43,084] INFO - LogMediator status = ====Final user Role====, USER_ROLE = generic_user


Hope this helps someone 🙂 happy coding ….

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s