[WSO2 ESB] Change the response payload using class mediator
1 min readJun 20, 2018
Wso2 ESB allows you to change the backend response payload as the way you want. You can achive this by writing a class mediator as mentioned below.
Let’s assume your back end has responded with some JSON payload as follows,
{
"name": "Identifier",
"type": "string",
"size": 255
}
Now you need to change this to the following error message,
<jsonObject>
<status>403</status>
<errorMessage>
<error>Authoraization Missing</error>
<detail>Authoraization Credentials invalid</detail>
<title>Authoraization Error</title>
</errorMessage>
</jsonObject>
You can achieve this by writing a class mediator as follows,
import org.apache.synapse.MessageContext;
import org.apache.synapse.mediators.AbstractMediator;
import org.apache.synapse.core.axis2.Axis2MessageContext;
import org.apache.synapse.commons.json.JsonUtil;
import org.json.JSONObject;
public class addSignature extends AbstractMediator {
@Override
public boolean mediate(MessageContext messageContext) {
try {
org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext)messageContext).getAxis2MessageContext();
JSONObject jsonBody = new JSONObject();
JSONObject jsonError = new JSONObject(); jsonError.put("error","Authoraization Missing");
jsonError.put("detail","Authoraization Credentials invalid");
jsonError.put("title","Authoraization Error");
jsonBody.put("status", "403");
jsonBody.put("errorMessage", jsonError);
String transformedJson = jsonBody.toString();
JsonUtil.newJsonPayload(axis2MessageContext,transformedJson, true, true);// change the response type to XML
axis2MessageContext.setProperty("messageType", "application/xml");
axis2MessageContext.setProperty("ContentType", "application/xml");
} catch (Exception e) {
System.err.println("Error: " + e);
return false;
}
return true;
}
}