Accessing URL Query Parameters in WSO2 ESB
[Article moved from ajanthane.blogspot.com]
This article shows how to access the url parameters in synapse engine level and in axis2 level. The axis2 level retrieving help us to filter or do the needed operations to the message based on the url parameters before the message reaches the synapse engine level.
Synapse Engine Level
Use $url Synapse XPath Variable [1] to retrieve the query-parameters from the URL. Refer the below Proxy Service sample code. Here used endpoint url: http://cmdaeliyathamby:8280/services/QueryParameterProxyService?username=ajan&password=123
<proxy name="QueryParameterProxyService" startonload="true" statistics="disable" trace="disable" transports="https,http" xmlns="http://ws.apache.org/ns/synapse">
<target>
<insequence>
<log level="custom"></log>
<property expression="$url:username" name="RET_URL2"/>
<property expression="$url:password" name="RET_URL3"/>
<log level="full"/>
</insequence>
</target>
<description/>
</proxy>
[1] https://docs.wso2.com/display/ESB481/Synapse+XPath+Variables#SynapseXPathVariables-$url
Axis2 Level
The URL query parameters can be accessed at axis level also. This can be done using custom axis2 handler class.
The below maven dependencies needed while building the class:
<dependency>
<groupid>org.apache.axis2</groupid>
<artifactid>axis2</artifactid>
<version>1.5.2</version>
</dependency>
<dependency>
<groupid>org.apache.httpcomponents</groupid>
<artifactid>httpclient</artifactid>
<version>4.5.1</version>
</dependency>
Use the below class and after building the jar, copy that to the ESB_HOME/repository/components/lib and start the ESB.
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import org.apache.axis2.AxisFault;
import org.apache.axis2.context.MessageContext;
import org.apache.axis2.handlers.AbstractHandler;
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
public class CustomQueryValuesAxisLevel extends AbstractHandler {
@Override
public InvocationResponse invoke(MessageContext msgCtx) throws AxisFault {
String _consumer = null;
List & lt;
namevaluepair & gt;
queryParameter;
try {
queryParameter = URLEncodedUtils.parse(
new URI((String) msgCtx.getProperty("TransportInURL")),
"UTF-8");
for (NameValuePair nvPair: queryParameter) {
if (nvPair.getName().equals("username")) {
_consumer = nvPair.getValue();
}
}
} catch (URISyntaxException e) {
e.printStackTrace();
}
System.out.println("Username: " + _consumer);
return InvocationResponse.CONTINUE;
}
}
References
[1] https://docs.wso2.com/display/ESB460/Writing+an+Axis2+Module
[2] https://docs.wso2.com/display/ESB481/XPath+Extension+Functions
[3] https://docs.wso2.com/display/ESB481/Synapse+XPath+Variables