Skip to end of metadata
Go to start of metadata

The Axis2 Message Formatter is an extension point provided by Apache Axis2. It can be used to modify messages by serializing them into a different message format. For example, to JSON. Users need to implement the org.apache.axis2.transport.MessageFormatter interface. The axis2.xml file (located in the <PRODUCT_HOME>/repository/conf/axis2 directory) is used to register the message formatter along with the required content type.

The process of implementing a sample message formatter is as follows: 

Implementing a message formatter

The following Axis2 message formatter is written to change the content type of the messages to “application/format-x”. Additionally, there are two debug logs printed when the message is processed by the message formatter.

package org.wso2.carbon.extensions;

import org.apache.axiom.om.OMOutputFormat;
import org.apache.axis2.AxisFault;
import org.apache.axis2.context.MessageContext;
import org.apache.axis2.transport.MessageFormatter;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.net.URL;

public class CustomMessageFormatter implements MessageFormatter {

   private static Log log = LogFactory.getLog(CustomMessageFormatter.class);

   public byte[] getBytes(MessageContext messageContext, OMOutputFormat omOutputFormat)
           throws AxisFault {
       ByteArrayOutputStream baos = new ByteArrayOutputStream();
       writeTo(messageContext, omOutputFormat, baos, true);
       return baos.toByteArray();

   public void writeTo(MessageContext messageContext, OMOutputFormat omOutputFormat, OutputStream outputStream,
                       boolean b) throws AxisFault {
       if (log.isDebugEnabled()) {
           log.debug("Start of message modification");

       // message modification logic goes here.

       if (log.isDebugEnabled()) {
           log.debug("End of message modification");
   public String getContentType(MessageContext messageContext, OMOutputFormat omOutputFormat, String s) {
       return "application/format-x";
   public URL getTargetAddress(MessageContext messageContext, OMOutputFormat omOutputFormat, URL url)
           throws AxisFault {
       return null;
   public String formatSOAPAction(MessageContext messageContext, OMOutputFormat omOutputFormat, String s) {
       return null;

Adding the JARs

The JAR containing the CustomMessageFormatter class needs to be placed in the <PRODUCT_HOME>/repository/components/lib directory of the Carbon server. 

Updating the configurations

 Update the axis2.xml file (located in the <PRODUCT_HOME>/repository/conf/axis2 directory) as shown below. This registers the message formatter against the “application/soap+xml” content type.

<messageFormatter contentType="application/soap+xml"
  • No labels