Wednesday, December 14, 2011

Writing a custom class mediator in wso2esb

In this post we will look at how to write a very simple class mediator for wso2esb. All what you have to do is, just extend the AbstractMediator class (org.apache.synapse.mediators.AbstractMediator) or implement the Mediator interface (org.apache.synapse.Mediator). AbstractMediator contains the implementation for some methods , so it would be easy to use that class.
Say, in a scenario, when exception occurs  at ESB, we want to extract the error details , and need to do further processing. In the following  sample,  error details are extracted and printed as sysout..

package org.wso2.carbon.custommediator
import org.apache.synapse.MessageContext;
import org.apache.synapse.core.axis2.Axis2MessageContext;
import org.apache.synapse.mediators.AbstractMediator;

* This custom mediator extracts error detail from synapse messagecontext.
* SynapseConfiguration would be;
*   <class name="org.wso2.carbon.custommediator.CustomErrorDataMediator">
*   </class>

public class CustomErrorDataMediator extends AbstractMediator {

public boolean mediate(MessageContext synapseMsgContext) {
  String errorMesssage = (String) synapseMsgContext.getProperty("ERROR_MESSAGE");
  Exception exception = (Exception)  synapseMsgContext.              getProperty("ERROR_EXCEPTION");
  String errorCode = (String) synapseMsgContext.getProperty("ERROR_CODE");
  String errorDetail = (String) synapseMsgContext.getProperty("ERROR_DETAIL");

  System.out.println("Error Message is "+errorMesssage +"ErrorCode "+errorCode);

  return true;

To build above code (*.jar as output), use following pom.xml file..

<project xmlns="" xmlns:xsi="" xsi:schemaLocation="">

    <groupId> org.wso2.carbon.custommediator</groupId>
    <artifactId> org.wso2.carbon.custommediator</artifactId>



Keep the *.jar in ESB/repository/component/lib folder and place the class mediator in your faultsequence.Whenever fault sequence get invoke, you will see the sysout at your server console.