Showing posts with label wso2esb. Show all posts
Showing posts with label wso2esb. Show all posts

November 19, 2016

LDAP User Authentication

What is LDAP and LDAP Authentication ?

To get started on what and how LDAP works, take a look at [1].

Quoting from the above article, following is about how LDAP Authentication works :
To perform any of these LDAP operations, an LDAP client needs to establish a connection with an LDAP server. The LDAP protocol specifies the use of TCP/IP port number 389, although servers may run on other ports.
The LDAP protocol also defines a simple method for authentication. LDAP servers can be set up to restrict permissions to the directory. Before an LDAP client can perform an operation on an LDAP server, the client must authenticate itself to the server by supplying a distinguished name and password. If the user identified by the distinguished name does not have permission to perform the operation, the server does not execute the operation.
In order write a simple LDAP Authenticator using Java, refer to the article [2] first to get an idea.

As per the above quote and explanations, in order to perform an LDAP based user authentication, we validate the user's permission by trying to execute an operation on LDAP.

Java LDAP Authenticator

import javax.naming.Context;
import java.util.Hashtable;
 * Open a connection to the LDAP server with uid and password and authenticate the user.
public class LDAPAuthenticator {
    private static String UID_FORMAT_STRING = "uid=%1s,%2s";
    private static String VDS_SERVER = "LDAPS://localhost:389";
    private static final String PEOPLE_OU = "ou=people,dc=local,dc=com";
    public static void main(String[] args) {
        Hashtable<String, String> authEnv = new Hashtable<String, String>();
        authEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        authEnv.put(Context.PROVIDER_URL, VDS_SERVER);
        authEnv.put(Context.SECURITY_AUTHENTICATION, "simple"); //default authentication
        authEnv.put(Context.SECURITY_PRINCIPAL, String.format(UID_FORMAT_STRING, "uidName", PEOPLE_OU));
        authEnv.put(Context.SECURITY_CREDENTIALS, "password");
        try {
            DirContext ctx = new InitialDirContext(authEnv);
            System.out.println("User Authentication Successful");
        } catch (Exception e) {
            System.out.println("User Authentication Failed");

In addition if you need perform attribute matching along with authentication use the following code as an example :

Attributes matchAttrs = new BasicAttributes(true); // ignore attribute name case
matchAttrs.put(new BasicAttribute("uid", "AARSupport"));

// Search for objects with those matching attributes
NamingEnumeration answer =, matchAttrs);

WSO2 LDAP Connector

If you are using WSO2 ESB, you can use the WSO2 LDAP connector to perform LDAP authentication. You can download the connector from [6]. Documentation on using the LDAP connector for authentication can be found at [7].

Use the following configurations to call the Authenticate operation.

Create a local entry with authentication details as below.

<ldap.init xmlns="">

Or you can also create local entry as below without authentication details since they are again later provided at the authenticate operation.

<ldap.init xmlns="">

In the mediation, you can call the LDAP connector's authenticate operation to perform authentication.

<ldap.authenticate configkey="LDAPConfig">

If the authentication is successful, you would be getting a Success response back.

References : 


October 30, 2016

Mocking Endpoint Behaviours for Troubleshooting in ESB

This article explains some common timeout and latency scenarios in endpoints and information on troubleshooting these issues. Following three scenarios will be discussed.
  1. Backend responds as expected but response time is fairly low
  2. Backend timeout
  3. 101503 Error : Backend connection refused
  4. Unknown Host exception
In order to explain the different scenarios, the easiest approach is to create a mock service for troubleshooting. For this article I am creating a mock service with SOAPUI. You may use any other tool to do the same. Refer [1] on more details for creating mock services using SOAPUI.

Once we create a mock service it is accessible with http://localhost:8080/mockservice.

Case 1 : Endpoint Responds with Low Response Time

This case is fairly straightforward. First we need to create the mock service and point to the mock service url in the ESB endpoint definition. Usually the cases to verify are the behaviour at different responses. To simulate this we can create multiple responses and attach to the mock service. This allows us to validate the behaviour for different responses.

Case 2 : Endpoint Timeout

Refer below endpoint timeout duration in the endpoint definition. We have set it to be 3000ms.

<?xml version="1.0" encoding="UTF-8"?>
<endpoint name="MockServiceEndpoint" xmlns="">
    <http method="post" uri-template="http//localhost:8080/mockservice">

In this case, since endpoint timeout duration is 3000ms, we can verify four cases where;

  1. No backend latency
  2. 2000 < timeout_duration <  3000 (latency close to 3000)
  3. timeout_duration  > 4000 (latency much higher than 3000)
  4. timeout_duration = 3000

From above four cases, 3 and 4 cases should cause endpoint to timeout. Other scenarios should respond and the rest of the mediation flow should work correct. In order to add the response latency to mock service, add a sleep command on the onRequest script of the mock service window as below.

Notice the delay in response time for the request that has gone past 3000ms in the below screenshot (left bottom)

By changing the sleep duration we can test out the behaviour of response time at the above four scenarios listed above.

Case 3 : 101503 - Endpoint Connection Refused

When faced with this error, a latency of ~10000 ms will be observed from the backend. Considering the fact that the endpoint timeout was 3000ms and it seemed highly improbable to exceed this number.

In order to mock this scenario, you need to host the mock service in a different machine in the same network and point to it as the endpoint (referred to as the mock server hereafter). While requests were sent out, the ‘mock server’ was disconnected from the network and ~10000ms of latency was observed. When ‘mock server’ is reconnected to the network normal behaviour is observed again.

To explain further the latency of ~10000ms is caused by connection refused error where a hostname is valid by DNS but is no longer available. This is why the ‘mock server’ had to be disconnected from the network to mock this behaviour. This is different from Case 4 described below.

Another way to mock this behaviour is to use an IP address which timeouts when pinged as the hostname in the endpoint definition.

Explanation on the Observation from WSO2 ESB perspective

In ESB, whenever a request is made a callback is registered for the request. This callback is responsible for sending back the response and doing the required processing. When backend does not response, these callbacks have to be cleared. Clearing is done by a task (TimeoutHandler) which runs every 15000 ms (by default).  This time duration can be controlled by overriding the default time duration with “synapse.timeout_handler_interval” property in ‘’ file.

To further elaborate, what happens here is that TimeoutHandler is executed every 15s and the callbacks get cleared within a 15s timeframe. Thus the response time will be somewhere below 15s, yet above 3s (to allow initial endpoint timeout duration). Attached graph of response time at default timeout for the mock API we created further explains this fact.

Response time will go to a lower range when we reduce the timeout_handler_interval. However, this means a higher frequency of timeout handler task being executed and will in turn impact performance.

To confirm the above description please refer the following observations when timeout_handler_interval is reduced.

Timeout_handler_interval = 5000ms

Timeout_handler_interval = 1000ms

Case 4 : Unknown Host Exception

Another scenario that was verified was giving an invalid host name, which resulted in an ‘Unknown Host Exception’, but this is handled within the 3000ms timespan.

Apart from these, there are a number of scenarios related to troubleshooting issues in endpoints. Refer for possible error scenarios in endpoints in [2]



August 8, 2016

Using SAML SSO Authorize Carbon Admin Services from Jaggery App

To give a background on the above scenario, please refer the following diagram.

A Jaggery App is deployed on WSO2 Application Server (AS) and we have enabled SAML 2.0 based SSO for the Jaggery app using WSO2 Identity Server (IS) . You can find more details on enabling SSO with IS at [1]. ESB also shares the same IDP.

What we are doing here is authenticating the Jaggery App from IDP by sending a SAML request and using the same SAML response to authenticate ESB and get a session cookie. This cookie can then be used to invoke admin services of ESB.

[JAGGERY_APP]/jagg/jaggery_acs file acts as the assertion consumer service (ACS). This is the same that is configured in the IDP. Once the request comes to jaggery_acs.jag we will validate the SAML response and get the cookie from ESB.

Once we have the SAML response, use the following code to authenticate ESB.

 //authenticate ESB
var ws = require("ws");
var requestESB = new ws.WSRequest();
var options = new Array();
options.useSOAP = 1.2;
options.action = "urn:login";
var endPoint = "https://localhost:9453/services/SAML2SSOAuthenticationService";
var payload = '<sso:login xmlns:sso=""><sso:authDto><xsd:response xmlns:xsd="">' + samlResponse + '</xsd:response></sso:authDto></sso:login>';,endPoint, false);
var responseESB = requestESB.responseE4X;
var adminSession = requestESB.getResponseHeader("Set-Cookie");
session.put("esb-auth-cookie", adminSession);

Use the following code segment to invoke ESB Admin services with the above cookie

var restApiAdminUrl = site.esb.serverBaseURL + "t/" + tenantDomain + "/services/" + REST_API_ADMIN_SERVICE + "/";
var requestPayload = "<xsd:getAPIsForListing xmlns:xsd=\"http://org.apache.axis2/xsd\">"
                      +"  <xsd:pageNumber>0</xsd:pageNumber>"
                      +"  <xsd:itemsPerPage>100</xsd:itemsPerPage>"

var ws = require("ws");
var request = new ws.WSRequest();
var options = new Array();
options.useSOAP = 1.2;
options.action = "urn:getAPIsForListing";
options["HTTPHeaders"] = [{name: "cookie", value: session.get("esb-auth-cookie")}];, restApiAdminUrl, false);
var response = request.responseE4X;



December 11, 2015

JSON Payload as String in Mediation

Due to the underlying synapse engine based on SOAP/XML message format, when a JSON payload is to be processed with ESB, it is being built as a XML message by default. In any case if we want to use the JSON payload as a string in our mediation, we will need to follow the below steps.

First the payload needs to be set as a string property as below :
<property name="JSONPayload" expression="json-eval($.)"/>
This property can then be used for any transformations as a string literal of the JSON.

Check out the sample below, which gets the response from the <call> mediator as a JSON, saves it to a string and then uses it in an xml payload. The final response of the API is XML.
<api xmlns="" name="JSONTestAPI" context="/json">
   <resource methods="GET">
            <endpoint key="MockBackend"></endpoint>
         <property name="JSONPayload" expression="json-eval($.)"></property>
         <log level="full">
            <property name="====JSONPayload====" expression="$ctx:JSONPayload"></property>
         <payloadFactory media-type="xml">
               <xmlPayload xmlns="">
               <arg evaluator="xml" expression="$ctx:JSONPayload"></arg>
         <property name="messageType" value="application/xml" scope="axis2"></property>

Response from mock backend is as below :
  "mock":"mock service"

JSON payload will be logged as below when invoking the API. Notice that although the JSON payload is built to XML, the property preserves the payload as a string literal.

LogMediator To:, WSAction: , SOAPAction: , MessageID: urn:uuid:08b4f213-0df0-4d18-88b7-8cf3e2d1872c, Direction: request, ====JSONPayload==== = {
   "mock":"mock service"
}, Envelope: <?xml version="1.0" encoding="utf-8"?><soapenv:Envelope xmlns:soapenv=""><soapenv:Body><jsonObject><mock>mock service</mock></jsonObject></soapenv:Body></soapenv:Envelope>

Final response from the API is as below :
      <jsonPayload>{"mock":"mock service"}</jsonPayload>

Additional Reference :

November 30, 2015

Sample for Restricting Proxy with Throttle Mediator

Following is a sample of using Throttle mediator to restrict local proxy invocations. Notice that the IP has to be given as and not "localhost".

A custom fault message can be added within onreject/makefault/reason tag (line 19-23) . Custom fault messages cannot be added for service level throttling.

<proxy name="ThrottleMediatorSample" startonload="true" trace="disable" transports="https http" xmlns="">
         <throttle id="A">
               <wsp:policy wsu:id="WSO2MediatorThrottlingPolicy" xmlns:throttle="" xmlns:wsp="" xmlns:wsu="">
                        <throttle:id throttle:type="IP"></throttle:id>
               <makefault response="true" version="soap11">
                  <code value="tns:Receiver" xmlns:tns="">
                     <reason value="ERROR : Restricted IP Address"/>
                     <address uri="http://localhost:9000/services/SimpleStockQuoteService">

Reference :

September 13, 2015

ESB 4.9.0 - Enhanced RabbitMQ Support

WSO2 ESB 4.9.0 Released !!

Checkout the blog at : for details on the exciting new features of this release.

You can download latest ESB version from :
Product documentation is available at :

With this release there are a number of enhancements done in RabbitMQ transport support. Documentation for RabbitMQ transport is available at :

So what's new with RabbitMQ support ?

  • RabbitMQ transport is now inbuilt with WSO2 ESB. Earlier it had to be installed separately as a feature on ESB. But now it is just a matter of modifying the axis2.xml file as would for any other transport
  • Introducing RabbitMQ based message store
  • Automatic connection recovery for RabbitMQ transport incase of network failure, server shutdown etc. Just a few configurations in axis2.xml and you are good to go
  • Introducing RabbitMQ SSL transport support for sender and receiver
  • Synchronized request-response support for RabbitMQ sender. Configure a reply-to queue and RabbitMQ sender is now no longer "out-only"
  • Inbound endpoints is one of the major features of this release and we have introduced for RabbitMQ as well
  • All content-types are now supported by RabbitMQ transport

I will be writing more posts on these features in future posts.

ESB 4.9.0 - Introducing ForEach Mediator

WSO2 ESB 4.9.0 Released !!

Checkout the blog at : for details on the exciting new features of this release.

You can download latest ESB version from :
Product documentation is available at :

One of the new features that is released is the ForEach mediator. This post is to give an introduction to this mediator. Documentation for the ForEach mediator is available at:

What happens in ForEach mediator?

  • ForEach mediator requires and xpath/jsonpath expression and a sequence (inline or referenced)
  • The original message is split to sub messages based on xpath/jsonpath expression and each such message is mediated sequentially in the mediation flow as defined by the sequence
  • ForEach mediator works in a single thread, thus a blocked execution
  • After the mediation of the sub messages are completed, they are merged back to the original message context to the original parent

ForEach or Iterate Mediator?

  • ForEach mediator and Iterate mediator may sound similar at first. But there are significant differences
  • Iterate mediator will always have to be accompanied by an Aggregate mediator. But ForEach mediator will complete all the processing within the mediator and will have the full message context after the mediation
  • Iterate mediator will allow sending a message to an endpoint where as ForEach mediator will not allow Call, Send or CallOut mediators. ForEach mediator is mostly useful for payload transformation use cases.
  • Xpath/jsonpath expressions can be used to conditionally select elements to be iterated in both mediators
  • ForEach mediator will not split the message flow unlike Iterate mediator. ForEach will execute all iterations in a single thread
  • ForEach supports modifying the original payload. Iterate will be used for situations where split messages will be sent to a target and collected by aggregate in a different flow. ForEach is for modifying a split message. ForEach also eliminates the need for complex XSLT mediators. 

Check out ESB documentation for samples on using ForEach mediator.

August 10, 2015

Using Script Mediator to Modify a JSON Payload

Environment :  ESB 4.8.0
Assuming the following properties are defined :
Property1 : {"object1": "this is object1"}
Property2 : {"sample": [123, "ABC", "456", "A12"]}

Following is the way to use script mediator to append a json array to an existing payload.
<script language="js">
var prop1 = eval('('+mc.getProperty("Property1") +')');
var payload ={};
var prop2 =eval('('+mc.getProperty("Property2")+ ')');
Following is the final payload.
{"final":{"object1":"this is object1","object2":{"sample":[123,"ABC","456","A12"]}}}

July 26, 2015

WS-Addressing with MessageID using SOAPUI and ESB

For all requests received by WSO2 ESB, a new message context is created with a new Message ID. This message ID is useful if you need to use it as a unique identification or for a correlation identification at some point.

However, if the request uses WS-Addressing, ESB will reuse the same Message ID provided with the request. 

You can send a request with WS-Addressing as in the following in example. Enter a MessageID and use a log in the relevant proxy in ESB to view the MessageID using get-property('MessageID')

If there is any requirement to get a new MessageID, despite using WS-Addressing, then you will need to include your complete message flow within a clone mediator, which will create a new message context and thus a new MessageID.

Example :

Following file will send the request to SimpleStockQuoteService (sample backend available with ESB) and write the response to a file. Here the file name is taken from MessageID. If the MessageID was not unique it will be overwriting the same file. Please note that this is assuming MessageID does not have any importance when serving the message.

Sending the request using SOAPUI :
  • Enable WS-A addressing
  • Enable Add default wsa:action
  • Enable Add default wsa:To
  • Enter MessageID in urn:XXXXXXXX or urn:uuid:XXXXXXXX (urn:uuid is the format used in WSO2 ESB)

<proxy xmlns=""
         <property name="messageid"
                   expression="fn:concat(fn:substring-after(get-property('MessageID'), 'urn:uuid:'), '.xml')"/>
               <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
         <property name="OUT_ONLY" value="true"/>
         <property name="transport.vfs.ReplyFileName"
         <property name="transport.vfs.ContentType" value="text/xml" scope="transport"/>
         <property name="ClientApiNonBlocking" scope="axis2" action="remove"/>
               <address uri="vfs:file:///Users/maheeka/test/out"/>
Solution : 
To generate a new MessageID, we are using a clone mediator in between.

<proxy name="StockProxy" startOnLoad="true" statistics="disable" trace="disable" transports="http,https" xmlns="">
      <property expression="fn:concat(fn:substring-after(get-property('MessageID'), 'urn:uuid:'), '.xml')" name="messageid"/>
          <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
            <property name="OUT_ONLY" value="true"/>
            <property expression="get-property('messageid')" name="transport.vfs.ReplyFileName" scope="transport"/>
            <property name="transport.vfs.ContentType" scope="transport" value="text/xml"/>
            <property action="remove" name="ClientApiNonBlocking" scope="axis2"/>
                <address uri="vfs:file:///Users/maheeka/test/out"/>

ClientApiNonBlocking property needs to be removed so that the primary thread will do the send to the VFS endpoint. For more details on this property refer :

Reference :

July 25, 2015

Optional Query Parameters in APIM and ESB APIs

When adding an API resource, url-template or url-mapping specifies the url pattern for to accept requests. In case of optional parameters, this needs to be handled too in the url pattern. However, this is not directly possible in APIs for both WSO2 ESB and APIM with a single resource.

Therefore, need to define two separate resources, one to accept additional(optional) parameters and the other to accept mandatory parameters. In /access_tokens/{entityRef}* , * denotes the parameters that may follow.

<api xmlns="" name="UserAPI" context="/users">
   <resource methods="GET" uri-template="/user/{userid}*">
         <property name="userid" expression="$ctx:uri.var.userid" scope="default" type="STRING"></property>
         <property name="name" expression="$"></property>
            <property name="STATUS" value="Request received for /users/{userid}*"></property>
   <resource methods="GET" uri-template="/user/{userid}">
         <property name="userid" expression="$ctx:uri.var.userid" scope="default" type="STRING"></property>
            <property name="STATUS" value="Request received for /user/{userid}"></property>

The following type of requests can be served with above API definition.

July 13, 2015

WSO2 ESB with SAP in OSX

Configure WSO2 ESB for SAP

Refer below steps while following the official documentation [1] to do the configurations in OSX.

1. Download SAP JCO for OSX from

2. Copy the sapjco3.jar and sapidoc3.jar files to [ESB_HOME]/repository/components/lib folder

3. Setup classpath to SAP as follows : 
export LD_LIBRARY_PATH=/Users/maheeka/sapjco3/
export CLASSPATH=/Users/maheeka/sapjco3/sapjco3.jar
For additional details on configuring classpath refer [2]

4. Enable SAP transport receiver/sender and create *.dest and *.server files as mentioned in documentation [1] (will be referred to as SAP.dest and SAP.server below)

5. Start ESB with the following command
sh [ESB_HOME]bin/ -Djava.library.path=<path_sapjco3>
Give path to sapjco3 folder downloaded in step 1.


Configure SAP with SAPGUI

SAPGUI is the client used for configuring SAP.

1. Download SAP GUI for OSX : PlatinGUI740_0-20012037.JAR and  (documentation) files from :
(SAP GUI 7.3.0 requires jdk 7 and SAP GUI 7.4.0 requires jdk 8 minimum)

2. Issue command : java -jar PlatinGUI740_0-20012037.JAR install
(Download PlatinManual_0-20008876.ZIP from the above location for the manual containing installation instructions)

3. Go through the installation wizard to install SAP GUI

4. Configure the following in SAP to connect to ESB via SAP GUI. First configure a connection and do the following steps.

  1. Create a TCP/IP connection and test the connection (RFC Destinations > TCP/IP Connections)
  2. Create a port (Port definition)
  3. Create a logical system (Maintaining Logical Systems)
  4. Create a partner agreement for the logical system (Partner Profiles)
  5. Create outbound and inbound parameters for partner agreement
You can also use transaction codes instead of using the user menu for this step. Transaction codes are available at :

Sample IDoc Sender

Use the following proxy as a sample IDOC sender.

<?xml version="1.0" encoding="UTF-8"?>
<proxy xmlns=""
         <xslt key="idoc.xslt"/>
         <property name="FORCE_SC_ACCEPT" value="true"/>
         <property name="OUT_ONLY" value="true"/>
               <address uri="idoc:/SAP"/>

"idoc.xslt" will create a IDOC payload and the proxy will send the request to SAP.

Invoke the proxy with : curl -v -X POST "http://localhost:8280/services/IDOCProxy"
If the invoke is successful, you can view the response in IDOC List menu.


1. Enable tracing for SAP by setting the trace property in *.dest file as : jco.client.trace=1
2. When step (3) and (5) in "Configure SAP with WSO2 ESB" is not done correctly : 
FATAL - CarbonServerManager WSO2 Carbon initialization Failed
java.lang.ExceptionInInitializerError: JCo initialization failed with java.lang.UnsatisfiedLinkError: no sapjco3 in java.library.path
   at java.lang.Class.forName0(Native Method)
   at java.lang.Class.forName(
   at java.lang.Class.forName0(Native Method)
   at java.lang.Class.forName(
   at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
   at sun.reflect.NativeConstructorAccessorImpl.newInstance(
   at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(
   at java.lang.reflect.Constructor.newInstance(
   at java.lang.Class.newInstance0(
   at java.lang.Class.newInstance(
   at org.apache.axis2.deployment.AxisConfigBuilder.processTransportSenders(
   at org.apache.axis2.deployment.AxisConfigBuilder.populateConfig(
   at org.wso2.carbon.core.CarbonAxisConfigurator.populateAxisConfiguration(
   at org.wso2.carbon.core.CarbonAxisConfigurator.getAxisConfiguration(
   at org.apache.axis2.context.ConfigurationContextFactory.createConfigurationContext(
   at org.wso2.carbon.core.CarbonConfigurationContextFactory.createNewConfigurationContext(
   at org.wso2.carbon.core.init.CarbonServerManager.initializeCarbon(
   at org.wso2.carbon.core.init.CarbonServerManager.start(
   at org.wso2.carbon.core.internal.CarbonCoreServiceComponent.activate(
   at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
   at sun.reflect.NativeMethodAccessorImpl.invoke(
   at sun.reflect.DelegatingMethodAccessorImpl.invoke(
   at java.lang.reflect.Method.invoke(
   at org.eclipse.equinox.internal.ds.model.ServiceComponent.activate(
   at org.eclipse.equinox.internal.ds.model.ServiceComponentProp.activate(
   at org.eclipse.equinox.internal.ds.InstanceProcess.buildComponent(
   at org.eclipse.equinox.internal.ds.InstanceProcess.buildComponents(
   at org.eclipse.equinox.internal.ds.Resolver.getEligible(
   at org.eclipse.equinox.internal.ds.SCRManager.serviceChanged(
   at org.eclipse.osgi.internal.serviceregistry.FilteredServiceListener.serviceChanged(
   at org.eclipse.osgi.framework.internal.core.BundleContextImpl.dispatchEvent(
   at org.eclipse.osgi.framework.eventmgr.EventManager.dispatchEvent(
   at org.eclipse.osgi.framework.eventmgr.ListenerQueue.dispatchEventSynchronous(
   at org.eclipse.osgi.internal.serviceregistry.ServiceRegistry.publishServiceEventPrivileged(
   at org.eclipse.osgi.internal.serviceregistry.ServiceRegistry.publishServiceEvent(
   at org.eclipse.osgi.internal.serviceregistry.ServiceRegistrationImpl.register(
   at org.eclipse.osgi.internal.serviceregistry.ServiceRegistry.registerService(
   at org.eclipse.osgi.framework.internal.core.BundleContextImpl.registerService(
   at org.eclipse.equinox.http.servlet.internal.Activator.registerHttpService(
   at org.eclipse.equinox.http.servlet.internal.Activator.addProxyServlet(
   at org.eclipse.equinox.http.servlet.internal.ProxyServlet.init(
   at org.wso2.carbon.tomcat.ext.servlet.DelegationServlet.init(
   at org.apache.catalina.core.StandardWrapper.initServlet(
   at org.apache.catalina.core.StandardWrapper.loadServlet(
   at org.apache.catalina.core.StandardWrapper.load(
   at org.apache.catalina.core.StandardContext.loadOnStartup(
   at org.apache.catalina.core.StandardContext.startInternal(
   at org.apache.catalina.util.LifecycleBase.start(

March 2, 2015

WSO2 ESB - Running Integration Tests

Integration tests for WSO2 ESB is available in product-esb repository at

You can clone this module and build ESB product with mvn clean install. The product will be created in [PRODUCT_ESB]/modules/distribution/target folder as wso2esb-[version].zip file.

This will also run all the integration tests for the product and you can find the surefire reports for the product at [PRODUCT_ESB]/modules/integration/tests-integration/[relevant_module_folder]/target/surefire-reports folder.

If you are executing tests by module, you can navigate to the relevant module and issue mvn clean install. However, before doing so, issue a mvn clean install -Dmaven.test.skip=true at product-esb level, to create the distribution pack. At test execution time, the test framework extracts this pack and starts the ESB server to deploy the required artifacts or make the required configuration changes for executing the tests.

Make sure you shutdown any running instances of a WSO2 product or a Axis2 Server instance or any other before running the tests, as it might interrupt with the servers that will be started and stopped during test execution.

Debugging Integration Tests

In order to debug integration tests, do the following :
  1. Navigate to required module or product-esb folder and issue mvn clean install -Dmaven.surefire.debug
  2. Notice the following in console :
    Listening for transport dt_socket at address: 5005
  3. Now click on debug button or Run>Debug in IntellijIDEA or Eclipse (Notice that you need to do a remote debugging here. Refer )
  4. You can apply breakpoints, watch expressions as you would in any normal debug scenario

Useful TestNG Tips

These integration tests use TestNG as the test engine.

Test suites and test cases to be run is included in the testng.xml. This testng.xml file can be found at [PRODUCT_ESB]/modules/integration/tests-integration/[relevant_module_folder]/src/tests/resources/testng.xml.

The tests can be included in package level or classes or even method level. Tests can also be excluded in debug Refer [1] to read up on TestNG. Following are some useful tips on TestNG.

1. To define a new test suite, add the following within <suite> tag of testng.xml :
   <test name="[TestSuite name]" preserve-order="true" verbose="2">
            <package name="[package containing tests]"/>

set preserver-order to true, if you want to run the tests in the order specified in package or classes.

2. Instead of package, if you want to add classes :
   <test name="[TestSuite name]" preserve-order="true" verbose="2">
            <class name="[fully qualified class name]"/>
            <class name="[fully qualified class name]"/>
            <class name="[fully qualified class name]"/>

3. If you want to add specific test methods of a class :
  <test name="[TestSuite name]" preserve-order="true" verbose="2">
            <class name="[fully qualified class name]"/>
                    <include name="[test method name]" />
                    <include name="[test method name]" />

4. If you want to exclude specific methods of a class :
  <test name="[TestSuite name]" preserve-order="true" verbose="2">
            <class name="[fully qualified class name]"/>
                    <exclude name="[test method name]" />
                    <exclude name="[test method name]" />

4. You can exclude or include all test methods by using ".*" as regex value for name :
    <exclude name=".*" />
    <include name=".*" />

5. To disable a test suite, use enabled property (true/false) :
    <test name="[TestSuite name]" preserve-order="true" verbose="2" enabled="false">

6. The test suites run in the order specified in the testng.xml. However, the order of the surefire report is different to this

7. Test methods can be identified by @Test annotation in the Java class

8. You can also disable test methods in Java class
    @Test(groups = {"wso2.esb"}, description = "...", enabled = false)
    public void testMethod() {
Refer next post for notes on writing ESB integration tests.

Reference : 

November 13, 2014

Remote Debugging WSO2 ESB with IntellijIdea and Eclipse

This post assumes you are familiar with debugging concepts. The remote debugging will be explained using WSO2 ESB product.

What happens in remote debugging is that the debugging information of a running application is communicated with an IDE that has the source of the application. The application is not running from the source, and thus the term "remote" debugging. Similar to any normal debug scenario, where you would be running the application in debug mode from the IDE, you can have breakpoints, watch expressions, etc.

Read more about how remote debugging works in JVM at [1].

Let's proceed on how to debug WSO2 ESB.

Setup the Source for Debugging WSO2 ESB

There are a number of components in WSO2 stack that contribute to the complete WSO2-ESB product. Some of these components are : wso2-synapse, carbon-mediation, wso2-axis2-transport, carbon4-kernel, etc. You can download source of all these components at

Decide on the component(s) you need to debug, and import them to your preferred IDE (Eclipse or IntellijIdea). To do this :
  1. Clone the required component from the git repository : git clone <repository_url>
  2. Build the component : mvn clean install or mvn clean install -Dmaven.test.skip=true (to skip tests)
  3. To setup as an IDE project : mvn idea:idea (for IntellijIdea) or mvn eclipse:eclipse (for Eclipse)
  4. Add breakpoints as needed
  5. If debugging multiple components, 
    • Eclipse : Import as project to the same workspace and add breakpoints
    • Idea : Import as module to the same window and add breakpoints
    • Optionally, at the time of debug, when debugging takes you to the .class files, you can attach the relevant components as sources with "attach source" option and continue.
Note : 
If you want to debug message flow on ESB, add a breakpoint to receive(org.apache.axis2.context.MessageContext mc) method in org.apache.synapse.core.axis2.ProxyServiceMessageReceiver class in wso2-synapse. This is the start point to the message flow on ESB.

Remote Debugging WSO2-ESB

Step 1 : Start WSO2-ESB in debug mode

$ sh bin/ debug 5005
Please start the remote debugging client to continue...
JAVA_HOME environment variable is set to /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home
CARBON_HOME environment variable is set to /Users/maheeka/wso2esb-4.8.1
Listening for transport dt_socket at address: 5005

We have started the ESB in debug mode, and it listens now on port 5005 for a remote debugging client. 

Step 2 : Start Remote Debugging Client (IDE)

  1. Run > Edit Configurations
  2. On the left panel, click on "+" and add a new Remote Configurations. Notice the port to be same as you give when starting ESB.
  3. Then Run > Debug 'wso2-synapse' to start the listener
  4. The application will now run as normal and stop at the breakpoints you have added

  1. Run > Debug Configurations
  2. Add a new Remote Java Application Configuration. Notice the port number to be same as you give when starting ESB.
  3. Click on Debug to start debugging 

November 10, 2014

Building WSO2 ESB 4.8.1 from source in OSX

WSO2 products are all built on top of WSO2 Carbon Kernel. This is the common ground for all products. Turing is the platform release name for WSO2 Carbon 4.2.0 and WSO2 ESB 4.8.1 is based on turing. Not all products of the WSO2 platform does not get released at the same time. Therefore, these products are released in chunks. ESB 4.8.1 comes under chunk 7 of the turing platform. Refer the release matrix to get more info on this [2].
Prerequisites : 
1. Install Java 1.6 and Maven 3
       If you have only 1.7 installed, you will have to install 1.6 on OSX. Unfortunately, there is no direct installation for 1.6. But this sorted out for me  since jdk 1.6 was automatically installed when I installed IntellijIdea
       At the moment, all WSO2 products are compiled on Java 1.6 and is supported up to 1.7. This is why we need to build the source on 1.6.
2. Checkout Source (Orbit, Kernel, Platform)

Building the Source : 

Start building in order Orbit > Kernel > Platform (chunk 07) repos respectively.

To build ESB 4.8.1, you need to build wso2carbon-platform/product-releases/chunk-07 as Platform in above.

The distribution will be created in :


When building, since it will take a lot of time, and to avoid unit test failures from building the product, skip unit tests when building.

mvn clean install -Dmaven.test.skip=true

Build ESB only :

If you need to build only ESB, build at wso2carbon-platform/products/esb with mvn clean install -Dmaven.test.skip=true

Another option is to comment out other product modules in platform/trunk/pom.xml and rebuilding in Orbit > Kernel > Platform in order.

Encountered Errors : 
  1. WSS4 maven install fails > You need to compile in Java 1.6
  2. [WARNING] Error injecting: org.apache.maven.reporting.exec.DefaultMavenReportExecutor > Set maven-site plugin version to 3.3 in all places [4]
Environment :