Monday, April 17, 2017

How to write handler class for WSO2 APIM?

In this article, I'm going to cover below areas
  1. How to write custom handler 
  2. How to get the request and response payload
Find the below sample custom handler to cover above scenarios.

package com.wso2.sample.handler;

import org.apache.axis2.context.MessageContext;
import org.apache.commons.io.IOUtils;

import org.apache.synapse.core.axis2.Axis2MessageContext;
import org.apache.synapse.rest.AbstractHandler;
import org.apache.synapse.transport.passthru.util.RelayUtils;

import java.io.InputStream;
import java.io.StringWriter;

public class CustomHandler extends AbstractHandler {

    public boolean handleRequest(org.apache.synapse.MessageContext messageContext) {
        try {
            RelayUtils.buildMessage(((Axis2MessageContext) messageContext).getAxis2MessageContext());
            InputStream jsonPaylodStream = (InputStream) ((Axis2MessageContext) messageContext)
                    .getAxis2MessageContext().getProperty(
                            "org.apache.synapse.commons.json.JsonInputStream");
            StringWriter writer = new StringWriter();
            IOUtils.copy(jsonPaylodStream, writer);
            // You can get the request message here
            String payloadMessge = writer.toString();
            System.out.println("Request payload message :" + payloadMessge);
            return true;
        } catch (Exception ex) {
            return true;
        }
    }

    public boolean handleResponse(org.apache.synapse.MessageContext messageContext) {
        try {
            RelayUtils.buildMessage(((Axis2MessageContext) messageContext).getAxis2MessageContext());

            InputStream jsonPaylodStream = (InputStream) ((Axis2MessageContext) messageContext)
                    .getAxis2MessageContext().getProperty(
                            "org.apache.synapse.commons.json.JsonInputStream");
            StringWriter writer = new StringWriter();
            IOUtils.copy(jsonPaylodStream, writer);
            // You can get the response message here
            String payloadMessge = writer.toString();
            System.out.println("Response payload message :" + payloadMessge);
            return true;
        } catch (Exception ex) {
            return true;
        }
    }
}

Before access the payload, we need to build the message, so, we can build the message as below
RelayUtils.buildMessage(((Axis2MessageContext) messageContext).getAxis2MessageContext());

After that you can access the payload with below code segment.
  InputStream jsonPaylodStream = (InputStream) ((Axis2MessageContext) messageContext)
          .getAxis2MessageContext().getProperty(
                   "org.apache.synapse.commons.json.JsonInputStream");
  StringWriter writer = new StringWriter();
  IOUtils.copy(jsonPaylodStream, writer);
  // You can get the response message here
  String payloadMessge = writer.toString();

1 comment: