Saturday, June 10, 2017

Setting a modified JSON String payload back to the MessageContext inside a class mediator WSO2 ESB 4.8.1

This article explains how we can set a modified JSON string payload back to the message context inside a class mediator. We achieve this inside a class mediator using the below segment of code. Here payLoad.toString() is the transformed JSON string.
 // Setting the latest JSON String to the Message Context  
      JsonUtil.newJsonPayload(  
                ((Axis2MessageContext) context).getAxis2MessageContext(),  
                payLoad.toString(), true, true);  

The usage of this code segment as below:

1) Create custom class mediator as below:
 package com.custom.json.payload;  
 import org.apache.commons.lang.StringUtils;  
 import org.apache.commons.logging.Log;  
 import org.apache.commons.logging.LogFactory;  
 import org.apache.synapse.MessageContext;  
 import org.apache.synapse.commons.json.JsonUtil;  
 import org.apache.synapse.core.axis2.Axis2MessageContext;  
 import org.apache.synapse.mediators.AbstractMediator;  
 import org.codehaus.jettison.json.JSONException;  
 import org.codehaus.jettison.json.JSONObject;  
 /*  
  * This is a sample class mediator to get the JSON message from the message context property and   
  * do some modifications to payload and set the new JSON payload to message context for further  
  * processing.   
  */  
 public class CustomJsonPayloadSetter extends AbstractMediator {  
      private static final Log log = LogFactory  
                .getLog(CustomJsonPayloadSetter.class);  
      public boolean mediate(MessageContext context) {  
           if (log.isDebugEnabled()) {  
                log.debug("[CustomJsonPayloadSetter] mediate method Invoked.");  
           }  
           // Get the JSON payload from the property.  
           String jsonPayLoad = StringUtils.stripToEmpty((String) context  
                     .getProperty("JsonPayload"));  
           if (log.isDebugEnabled()) {  
                log.debug("[CustomJsonPayloadSetter] Json Payload from Context."  
                          + jsonPayLoad);  
           }  
           try {  
                // Adding additional data to the Payload.  
                JSONObject payLoad = new JSONObject(jsonPayLoad);  
                payLoad.put("TestValueAdded1", "TEST1VAL");  
                payLoad.put("TestValueAdded2", "TEST2VAL");  
                // Setting the latest JSON String to the Message Context  
                JsonUtil.newJsonPayload(  
                          ((Axis2MessageContext) context).getAxis2MessageContext(),  
                          payLoad.toString(), true, true);  
           } catch (JSONException e) {  
                e.printStackTrace();  
           }  
           return true;  
      }  
 }  

2) Below is the pom.xml used to build the code.
 <?xml version="1.0" encoding="UTF-8"?>  
 <project  
      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"  
      xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">  
      <modelVersion>4.0.0</modelVersion>  
      <groupId>com.custom.json.payload.CustomJsonPayloadSetter</groupId>  
      <artifactId>CustomJsonPayloadSetter</artifactId>  
      <version>1.0.0</version>  
      <packaging>bundle</packaging>  
      <name>CustomJsonPayloadSetter</name>  
      <description>CustomJsonPayloadSetter</description>  
      <properties>  
           <CApp.type>lib/synapse/mediator</CApp.type>  
      </properties>  
      <dependencies>  
           <dependency>  
                <groupId>org.apache.axis2.wso2</groupId>  
                <artifactId>axis2</artifactId>  
                <version>1.6.1.wso2v10</version>  
           </dependency>  
           <dependency>  
                <groupId>org.apache.synapse</groupId>  
                <artifactId>synapse-core</artifactId>  
                <version>2.1.2-wso2v4</version>  
           </dependency>  
           <dependency>  
                <groupId>commons-logging</groupId>  
                <artifactId>commons-logging</artifactId>  
                <version>1.1.1</version>  
           </dependency>  
           <dependency>  
                <groupId>commons-lang.wso2</groupId>  
                <artifactId>commons-lang</artifactId>  
                <version>2.6.0.wso2v1</version>  
           </dependency>  
      </dependencies>  
      <repositories>  
           <repository>  
                <releases>  
                     <enabled>true</enabled>  
                     <updatePolicy>daily</updatePolicy>  
                     <checksumPolicy>ignore</checksumPolicy>  
                </releases>  
                <id>wso2-nexus</id>  
                <url>http://maven.wso2.org/nexus/content/groups/wso2-public/</url>  
           </repository>  
      </repositories>  
      <pluginRepositories>  
           <pluginRepository>  
                <releases>  
                     <enabled>true</enabled>  
                     <updatePolicy>daily</updatePolicy>  
                     <checksumPolicy>ignore</checksumPolicy>  
                </releases>  
                <id>wso2-nexus</id>  
                <url>http://maven.wso2.org/nexus/content/groups/wso2-public/</url>  
           </pluginRepository>  
      </pluginRepositories>  
      <build>  
           <plugins>  
                <plugin>  
                     <groupId>org.apache.felix</groupId>  
                     <artifactId>maven-bundle-plugin</artifactId>  
                     <version>2.3.4</version>  
                     <extensions>true</extensions>  
                     <configuration>  
                          <instructions>  
                               <Bundle-SymbolicName>CustomJsonPayloadSetter</Bundle-SymbolicName>  
                               <Bundle-Name>CustomJsonPayloadSetter</Bundle-Name>  
                               <Export-Package>com.custom.json.payload</Export-Package>  
                               <DynamicImport-Package>*</DynamicImport-Package>  
                          </instructions>  
                     </configuration>  
                </plugin>  
                <plugin>  
                     <artifactId>maven-eclipse-plugin</artifactId>  
                     <version>2.9</version>  
                     <configuration>  
                          <buildcommands>  
                               <buildcommand>org.eclipse.jdt.core.javabuilder</buildcommand>  
                          </buildcommands>  
                          <projectnatures>  
                               <projectnature>org.wso2.developerstudio.eclipse.artifact.mediator.project.nature</projectnature>  
                               <projectnature>org.eclipse.jdt.core.javanature</projectnature>  
                          </projectnatures>  
                     </configuration>  
                </plugin>  
           </plugins>  
      </build>  
 </project>  

3) Create a API as below:
 <api xmlns="http://ws.apache.org/ns/synapse" name="TestSetJsonPayload" context="/test">  
   <resource methods="POST" uri-template="/json">  
    <inSequence>  
      <log level="custom">  
       <property name="STATUS" value="------------------TestSetJsonPayload IN Invoked-------------------"></property>  
      </log>  
      <send>  
       <endpoint>  
         <http method="post" uri-template="http://www.mocky.io/v2/593a60f6110000010ba95699"></http>  
       </endpoint>  
      </send>  
    </inSequence>  
    <outSequence>  
      <log level="custom">  
       <property name="STATUS" value="------------------TestSetJsonPayload OUT Invoked-------------------"></property>  
      </log>  
      <property name="JsonPayload" expression="json-eval($.)"></property>  
      <class name="com.custom.json.payload.CustomJsonPayloadSetter"></class>  
      <log level="full"></log>  
      <send></send>  
    </outSequence>  
   </resource>  
 </api>   

4) When we send a request, the backend http://www.mocky.io/v2/593a60f6110000010ba95699 will return the below.
 {"test":"Form Mock Back end"}  

and after going through the class mediator, the requested client will receive the below modified JSON payload.
 {  
  "test": "Form Mock Back end",  
  "TestValueAdded1": "TEST1VAL",  
  "TestValueAdded2": "TEST2VAL"  
 }  


Hope this helps someone try to set the modified JSON payload back to MessageContext...


4 comments:

  1. Not Able to find jar for import org.apache.synapse.commons.json.JsonUtil; Can you help how to get it?

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete
  4. Hi @Ajanthan Eliyathamby,

    Thanks for the nice post. But i am getting ERROR like "JsonUtil cannot be resolved" in WSO2 Developer Studio. Please help me to resolve this.

    ReplyDelete