简体   繁体   中英

WSO2 ESB Message context cannot be changed through custom class mediator

I'm trying to alter a message using a custom class mediator in wso2 esb. What I'm trying to achieve is to add/set the value of an element in the message sent. The message is sent using a REST API, and it goes through the mentioned class (where the transformation happens). However, when I do a full log of the message after the class, I see that the message keeps the same values that had at first (basically the class only alters the message while it's in the class mediator, so when it comes out of the mediator, it goes back to its original input form).

Input:
Body : <soapenv:Body ...><jsonObject><ts>2020-01-13</ts><temp></temp></jsonObject></soapenv:Body>

Desired output:
Body : <soapenv:Body ...><jsonObject><ts>2020-01-13</ts><temp>Hello</temp></jsonObject></soapenv:Body>

Things that I've tried so far and that didn't work:

  1. Get message context, get the desired element and set the text
  2. Use a OMFactory to create an OMElement and put that new element in the message context
  3. Get the new altered envelope and set it as the new message context envelope
  4. Create a new json payload

Any idea of how to get it working ?

You can refer to the following logic which changes the payload

@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;
}

If this doesn't help, kindly share your code to have an idea.

I already tried that tutorial @Nirothipan, but didn't work.

My code:

@Override
public boolean mediate(MessageContext mc){

    String measure = mc.getEnvelope().getBody().getFirstElement().getFirstChildWithName(new QName("measure")).getText();
    mc.getEnvelope().getBody().getFirstElement().getFirstChildWithName(new QName("temp")).setText(measure);

    return true;
}

Should be more than enough to modify that element value imo.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM