Monday, January 23, 2017

Dynamic XPath expressions in property mediator

Suppose we have following xml content stored in the registry and we need to read the entry value dynamically by passing the entry element(entry1,entry2) as a parameter.

 <myConfigFile>  
 <entry1>value1</entry1>  
 <entry2>value2</entry2>  
 </myConfigFile>  

The following sequence template reads the xml content from the registry(conf:/myConfigFile) to a property and base on the entry element parameter pass by the call template mediator, a dynamic xpath expression will be built and evaluate the value of the entry element.

 <template xmlns="http://ws.apache.org/ns/synapse" name="myTemplate">  
   <parameter name="entryValue"></parameter>  
   <sequence>  
    <property xmlns:ns2="http://org.apache.synapse/xsd" xmlns:ns="http://org.apache.synapse/xsd" name="myConfigFile" expression="get-property('registry','conf:/myConfigFile')" scope="default" type="OM"></property>  
    <log level="custom">  
      <property xmlns:ns2="http://org.apache.synapse/xsd" xmlns:ns="http://org.apache.synapse/xsd" name="+++++++Logging myConfigFile+++++++" expression="get-property('myConfigFile')"></property>  
    </log>  
    <property xmlns:ns2="http://org.apache.synapse/xsd" xmlns:ns="http://org.apache.synapse/xsd" name="entryparam" expression="$func:entryValue"></property>  
    <property xmlns:ns2="http://org.apache.synapse/xsd" xmlns:ns="http://org.apache.synapse/xsd" name="xpathExpression" expression="fn:concat('$ctx:myConfigFile//',get-property('entryparam'))"></property>  
    <log>  
      <property xmlns:ns2="http://org.apache.synapse/xsd" xmlns:ns="http://org.apache.synapse/xsd" name="****entry value****" expression="evaluate($ctx:xpathExpression)"></property>  
    </log>  
   </sequence>  
 </template>  

Following API including the call template mediator invokes the above template.


 <api xmlns="http://ws.apache.org/ns/synapse" name="TestApi" context="/sample">  
   <resource methods="GET">  
    <inSequence>  
      <call-template target="myTemplate">  
       <with-param name="entryValue" value="entry2"></with-param>  
      </call-template>  
    </inSequence>  
   </resource>  
 </api>  

Observed the following log on the ESB console.

 INFO - LogMediator +++++++Logging myConfigFile+++++++ = <myConfigFile>  
 <entry1>value1</entry1>  
 <entry2>value2</entry2>  
 </myConfigFile>  
 [2017-01-20 13:21:12,016] INFO - LogMediator To: /sample, MessageID: urn:uuid:8cc61345-3358-4b0b-bddc-c950a863416e, Direction: request, ****entry value**** = value2  


No comments:

Post a Comment