Tuesday, April 11, 2017

How to access transport headers in WSO2 custom formatter?

You can access the transport header using messageContext.getProperty as below. (Transport header stored under TRANSPORT_HEADERS property.)

Map<String, Object> headerMap = 
      (Map<String, Object>) messageContext.getProperty(MessageContext.TRANSPORT_HEADERS);

Find the below sample formatter

package com.wso2.sample.formatter;

import org.apache.axiom.om.OMOutputFormat;
import org.apache.axis2.AxisFault;
import org.apache.axis2.context.MessageContext;
import org.apache.axis2.transport.MessageFormatter;

import java.io.OutputStream;
import java.net.URL;
import java.util.Map;
import java.util.Set;

public class SampleFormatter implements MessageFormatter {

    public void writeTo(MessageContext messageContext, OMOutputFormat omOutputFormat, OutputStream outputStream, boolean b) throws AxisFault {
        Map<String, Object> headerMap = (Map<String, Object>) messageContext.getProperty(MessageContext.TRANSPORT_HEADERS);
        Set<String> keySet = headerMap.keySet();
        for (String key : keySet) {
            System.out.println(key + " >> " + headerMap.get(key));
        }
    }

    public String getContentType(MessageContext messageContext, OMOutputFormat omOutputFormat, String s) {
        return null;
    }

    public URL getTargetAddress(MessageContext messageContext, OMOutputFormat omOutputFormat, URL url) throws AxisFault {
        return null;
    }

    public String formatSOAPAction(MessageContext messageContext, OMOutputFormat omOutputFormat, String s) {
        return null;
    }

    public byte[] getBytes(MessageContext messageContext, OMOutputFormat omOutputFormat) throws AxisFault {
        return new byte[0];
    }
}

Now you can see the transport headers in as below. (According to the above sample it displayed in the carbon log file)

Accept >> */*
Accept-Encoding >> gzip, deflate
Accept-Language >> en-US,en;q=0.8
Cache-Control >> no-cache
Content-Type >> application/xml
Host >> tharanga:8280
Origin >> chrome-extension://fhbjgbiflinjbdggehcddcbncdddomop
Postman-Token >> 8e78f643-842c-175a-69c0-3a94e1ba1950


No comments:

Post a Comment