Sample 353: Using Ruby Scripts for Mediation
<definitions xmlns="http://ws.apache.org/ns/synapse">
<localEntry key="stockquoteScript"
src="file:repository/conf/sample/resources/script/stockquoteTransform.rb"/>
<sequence name="main">
<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>
</sequence>
</definitions>
The external script referenced by the configuration contains the following Ruby
scriplet.
<x><![CDATA[
require 'rexml/document'
include REXML
def transformRequest(mc)
newRequest= Document.new '<m:getQuote xmlns:m="http://services.samples">'<<
'<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://www.apache-synapse.org/test"><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>
Objective
The script mediator of Synapse can be programmed using any BSF compatible
programming language. Sample 250 shows how to
configure it using JavaScript. This sample shows how to configure the script
mediator with Ruby.
Executing the Client
This sample is identical to sample 350 with the
only difference being the use of Ruby instead of JavaScript. Use the stock
quote client to send a custom quote request as follows.
ant stockquote -Daddurl=http://localhost:9000/services/SimpleStockQuoteService -Dtrpurl=http://localhost:8280/ -Dmode=customquote
The Ruby scriplets will transform the requests and responses as they flow through
the service bus.
Back to Catalog