This documentation is for WSO2 ESB version 4.5.1. View documentation for the latest release.

Sample 353: Using Ruby Scripts for Mediation

Objective: Script mediators using Ruby

<definitions xmlns="http://ws.apache.org/ns/synapse">

    <localEntry key="stockquoteScript" src="file:repository/samples/resources/script/stockquoteTransform.rb"/>
    <in>
        <!-- transform the custom quote request into a standard quote request expected by the service -->
        <script language="rb" key="stockquoteScript" function="transformRequest"/>

        <!-- send message to real endpoint referenced by name "stockquote" and stop -->
        <send>
            <endpoint name="stockquote">
                <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
            </endpoint>
        </send>
    </in>
    <out>
        <!-- transform the standard response back into the custom format the client expects -->
        <script language="rb" key="stockquoteScript" function="transformResponse"/>
        <send/>
    </out>
</definitions> 
<x><![CDATA[
require 'rexml/document'
include REXML

def transformRequest(mc)
   newRequest= Document.new '<m:getQuote xmlns:m="http://services.samples/xsd">'<<
      '<m:request><m:symbol></m:symbol></m:request></m:getQuote>'
   newRequest.root.elements[1].elements[1].text = mc.getPayloadXML().root.elements[1].get_text
   mc.setPayloadXML(newRequest)
end

def transformResponse(mc)
   newResponse = Document.new '<m:CheckPriceResponse xmlns:m="http://services.samples/xsd"><m:Code>' <<
      '</m:Code><m:Price></m:Price></m:CheckPriceResponse>'
   newResponse.root.elements[1].text = mc.getPayloadXML().root.elements[1].elements[1].get_text
   newResponse.root.elements[2].text = mc.getPayloadXML().root.elements[1].elements[2].get_text
   mc.setPayloadXML(newResponse)
end
]]></x>

Prerequisites:

This sample uses Ruby so first setup support for this in ESB as described at Configuring JRuby .

  • Start the Synapse configuration numbered 353: i.e. wso2esb-samples -sn 353
  • Start the Axis2 server and deploy the SimpleStockQuoteService if not already done

This sample is functionally equivalent to sample # 350 (#351 and #8) but instead uses a Ruby script using the JRuby interpreter. The script has two functions, 'transformRequest' and 'transformResponse', and the Synapse configuration specifies to be invoked when used. Execute the stock quote client to send a custom stock quote as per  Sample 350 and check the received stock quote response.