Transforming JSON body using WSO2 class mediator
Asked Answered
E

2

5

Following is the log of my current json body. And I want to add new property to this body. "NewPropertyName": "value". Since the value is in a database I am using a class mediator to add this property.

[2015-05-18 05:47:08,730]  INFO - LogMediator To: /a/create-project, MessageID: urn:uuid:b7b6efa6-5fff-49be-a94a-320cee1d4406, Direction: request, _______BODY_______ = 
{
  "token": "abc123",
  "usertype":"ext",
  "request": "create"
}

Class mediator's mediate method,

public boolean mediate(MessageContext mc) {
        mc.setProperty("key", "vale retrived from db");
        return true;
}

but this doesn't work as I expected. I couldn't find any guide to add property to json body using class mediator, please help.

Enneastyle answered 18/5, 2015 at 6:12 Comment(4)
any update? we have same problem.Hemihydrate
@MiladKianmehr Yep, I got this solved and add a new answer to this thread please see the new answer.Enneastyle
I can't use script mediator because we have large payload and code length error.Hemihydrate
@MiladKianmehr New answer added explaining how to do this using a class mediator. I think that will help you.Enneastyle
E
10

To inject a property to the body you have to use following code snippet,

JsonUtil.newJsonPayload(
            ((Axis2MessageContext) context).getAxis2MessageContext(),
            transformedJson, true, true);

inside a class mediator. Following is an example of mediate method.

/**
 * Mediate overridden method to set the token property.
 */@Override
public boolean mediate(MessageContext context) {
try {

    // Getting the json payload to string
    String jsonPayloadToString = JsonUtil.jsonPayloadToString(((Axis2MessageContext) context)
        .getAxis2MessageContext());
    // Make a json object
    JSONObject jsonBody = new JSONObject(jsonPayloadToString);

    // Adding the name:nameParam.
    jsonBody.put("name", getNameParam());

    String transformedJson = jsonBody.toString();

    // Setting the new json payload.
    JsonUtil.newJsonPayload(
    ((Axis2MessageContext) context).getAxis2MessageContext(),
    transformedJson, true, true);

    System.out.println("Transformed JSON body:\n" + transformedJson);

} catch (Exception e) {
    System.err.println("Error occurred: " + e);
    return false;
}

return true;
}

You will need json and other libraries for this. This is fully explained in following blog post.

json-support-for-wso2-esb-class-mediator

Enneastyle answered 10/12, 2015 at 6:1 Comment(9)
Thank you Isuru. This url is not work now. Can u give which dependency I need to add for do this taskNationality
@Dev4World try here: isurugunawardana.com/2015/05/19/…Enneastyle
This url not work. Did u check it.It say isurugunawardana.com recently expired! Oh no!Nationality
@Dev4World it should be working now. If not will be available in few hours.Enneastyle
@Isuru, I added dependencies to pom.xml file. But I can't Import JSONObject inside the java class of mediator projects. Do you have idea about thisNationality
@Isuru do you have any idea about "The type org.apache.axis2.context.MessageContext cannot be resolved. It is indirectly referenced from required .class files" errorNationality
@Dev4World Now you can use wso2 dev studio for this and get this done in an easy way. You just need to create wso2 mediator project. you can download the product here. wso2.com/more-downloads/developer-studio hope this helpsEnneastyle
@Isuru I already did these all thing.I import all thing according to your blog. But Its not get "Axis2MessageContext".Nationality
itsmeisuru.wordpress.com/2015/05/19/…Enneastyle
F
0

mc.setProperty is used to create a new property as if you were using property mediator.

If you want to add a new element inside your message, in java, you can handle it as if it were a XML message (for exemple, to get the first element :
OMElement element = (OMElement) context.getEnvelope().getBody().getFirstOMChild(); )

Sample to add a new element with a javascript :

<script language="js"><![CDATA[
    var payloadXML = mc.getPayloadXML();
    payloadXML.appendChild(new XML(<NewPropertyName>value</NewPropertyName>));
    mc.setPayloadXML(payloadXML);
]]></script>

Log the message in XML with <log level="full"> and you get :

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
  <soapenv:Body>
    <jsonObject>
      <token>abc123</token>
      <usertype>ext</usertype>
      <request>create</request>
      <NewPropertyName>value</NewPropertyName>
    </jsonObject>
  </soapenv:Body>
</soapenv:Envelope>

Log the message in JSON with

<log>
  <property name="JSON-Payload" expression="json-eval($.)"/>
</log> 

and you get : JSON-Payload = {"token":"abc123","usertype":"ext","request":"create","NewPropertyName":"value"}

Flexible answered 18/5, 2015 at 6:47 Comment(3)
I added the Element inside the class mediator, (confirmed by printing the xml) but it doesn't show up in the json body when I again print it using a log mediator, the json body has not changed.Enneastyle
I've updated my answer with a sample based on javascriptFlexible
Thanks for helping but please noticed that I am using a class mediator and I want to transform this inside the class mediator as I need some complex task.Enneastyle

© 2022 - 2024 — McMap. All rights reserved.