Wednesday, June 15, 2016

Creating a synapse handler with WSO2 ESB 4.9.0

There might be scenarios where you need to access data of a request/response at different points. For example you might want to perform some operation to the incoming request to ESB or you might want to access the payload that is sent from the Back End to ESB. So the perfect solution for this in ESB 4.9.0 is to write a synapse handler. [1] gives a very good explanation on how to implement and deploy this.


Following is a sample implementation of a synapse handler. Suppose your client is invoking an API artifact that is deployed in ESB, through API Manager. And suppose you need to get this client's IP address. Since we need to access the IP address of the client request that is coming into ESB, the method to access this property is 'handleRequestInFlow'. Now when you invoke an API artifact deployed in ESB, following logs will appear.

public class TestHandler extends AbstractSynapseHandler {


    static Logger log = Logger.getLogger(TestHandler.class.getName());


    protected void activate(ComponentContext ctxt) {
        try {
            log.debug("API test Handler");
        } catch (Throwable e) {
            log.error("Failed to activate API basic test Handler", e);
        }
    }

    @Override
    public boolean handleRequestInFlow(MessageContext synCtx) {
        log.info("Request In Flow");

        Axis2MessageContext axis2smc = (Axis2MessageContext) synCtx;
        org.apache.axis2.context.MessageContext axis2MessageCtx =
                axis2smc.getAxis2MessageContext();
        log.info("Client IP is " + axis2MessageCtx.getProperty("REMOTE_ADDR"));

        return true;
    }

    @Override
    public boolean handleRequestOutFlow(MessageContext synCtx) {
 log.info("Request Out Flow");
return true;
}

    @Override
    public boolean handleResponseInFlow(MessageContext synCtx) {
 log.info("Response In Flow");
  return true;
}


    @Override
    public boolean handleResponseOutFlow(MessageContext synCtx) {
  log.info("Response Out Flow");
   return true;
}


}

No comments:

Post a Comment