Friday, January 13, 2017

Decode base64encoded JSON by wso2 ESB

Wso2 ESB support for message encoding and decoding using following custom XPath functions.

base64Encode() function


The base64Encode function returns the base64-encoded value of the specified string.

  • base64Encode(string value)
  • base64Encode(string value, string charset) 

base64Decode() function


The base64Decode function returns the original value of the specified base64-encoded value.

  • base64Decode(string encodedValue)
  • base64Decode(string encodedValue, string charset)
The following sample illustrates, how to decode the incoming base64 encoded message by ESB.

Suppose that the backend(http://www.mocky.io/v2/5878a8c626000052011c3503) is returning the base64encoded string "eyJuYW1lIjoiUmFuZGlrYSJ9" for the json "{"name": "Randika"}".

The following proxy service can be used to decode the incoming encoded message.

 <?xml version="1.0" encoding="UTF-8"?>  
 <api xmlns="http://ws.apache.org/ns/synapse" name="SampleDecoder" context="/test">  
   <resource methods="GET">  
    <inSequence>  
      <send>  
       <endpoint>  
         <http method="GET" uri-template="http://www.mocky.io/v2/5878a8c626000052011c3503" />  
       </endpoint>  
      </send>  
    </inSequence>  
    <outSequence>  
      <property name="messageBody" expression="$body/*" scope="default" />  
      <log level="custom">  
       <property name="************Incoming Encoded Payload*************" expression="get-property('messageBody')" />  
      </log>  
      <property name="DecodeBody" expression="base64Decode(get-property('messageBody'))" scope="default" />  
      <log level="custom">  
       <property name="************Decoded Payload************" expression="get-property('DecodeBody')" />  
      </log>  
      <log level="full" />  
      <payloadFactory media-type="json">  
       <format>$1</format>  
       <args>  
         <arg evaluator="xml" expression="get-property('DecodeBody')" />  
       </args>  
      </payloadFactory>  
      <log level="full" />  
      <property name="messageType" value="application/json" scope="axis2" />  
      <send />  
    </outSequence>  
   </resource>  
 </api>  

The incoming encoded message can be stored in the property after decoding with the following configuration.

<property name="DecodeBody" expression="base64Decode(get-property('messageBody'))" scope="default" />

The output message will be seen an follows.

{"name": "Randika"}

1 comment:

  1. Thanks a lot!!
    I was struggling to decode a binary message and log it, in WSO2 since long.
    This helped. Simple solution.

    ReplyDelete