Apache Synapse ESB - Running the Samples

This guide will walk you through the built-in samples shipped with the product, which will cover most of the basic functional sceanrios and capabilities of Apache Synapse as an ESB. If you are unable to solve your problem by reading through and running these samples, feel free to raise your problem on the mailing lists .

Message Mediation Samples

<definitions xmlns="http://ws.apache.org/ns/synapse"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">

    <sequence name="main">
        <!-- log all attributes of messages passing through -->
        <log level="full"/>

        <!-- Send the message to implicit destination -->
        <send/>
    </sequence>

</definitions>

Objective: Introduction to Synapse. Shows how a message could be made to pass through Synapse and logged before it is delivered to its ultimate receiver.

The Stock quote client can operate in the following modes for this example.

  1. Smart Client mode
  2. ant stockquote -Daddurl=http://localhost:9000/services/SimpleStockQuoteService -Dtrpurl=http://localhost:8280/ 
  3. Using Synapse as a HTTP Proxy
  4. ant stockquote -Daddurl=http://localhost:9000/services/SimpleStockQuoteService -Dprxurl=http://localhost:8280/
  5. Gateway Mode / Dumb Client
  6. See sample # 1

Prerequisites:
Start the Synapse configuration numbered 0: e.g. synapse -sample 0
Start the Axis2 server and deploy the SimpleStockQuoteService if not already deployed

Execute the Smart Client

By tracing the execution of Synapse with the log output level set to DEBUG, you will see the client request arriving at Synapse with a WS-Addressing 'To' set to EPR http://localhost:9000/services/SimpleStockQuoteService. The Synapse engine logs the message at the "full" log level (i.e. all the message headers and the body) then sends the message to its implicit 'To' address which is http://localhost:9000/services/SimpleStockQuoteService. You will see a message in the Axis2 server console confirming that the message got routed to the sample server and the sample service hosted at the sample server generating a stock quote for the requested symbol.

Sat Nov 18 21:01:23 IST 2006 SimpleStockQuoteService :: Generating quote for : IBM

The response message generated by the service is again received by Synapse, and flows through the same mediation rules, which logs the response message and then sends it back. This time to the client. On the client console you should see an output similar to the following based on the message received by the client.

Standard :: Stock price = $95.26454380258552

Execute the Proxy Client

You will see the exact same behaviour as per the previous example when you run this scenario. However this time the difference is at the client, as it sends the message to the WS-Addressing 'To' address http://localhost:9000/services/SimpleStockQuoteService, but the transport specifies Synapse as the HTTP proxy.

<definitions xmlns="http://ws.apache.org/ns/synapse"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">

    <sequence name="main">
        <!-- filtering of messages with XPath and regex matches -->
        <filter source="get-property('To')" regex=".*/StockQuote.*">
            <then>
                <send>
                    <endpoint>
                        <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
                    </endpoint>
                </send>
                <drop/>
            </then>
        </filter>
        <send/>
    </sequence>

</definitions> 

Objective: Introduction to simple content based routing. Shows how a message could be made to pass through Synapse using the Dumb Client mode, where Synapse acts as a gateway to accept all messages and then perform mediation and routing based on message properties or content.

Prerequisites:
Start the Synapse configuration numbered 1: i.e. synapse -sample 1
Start the Axis2 server and deploy the SimpleStockQuoteService if not already deployed

Execute the Dumb Client as:

ant stockquote -Dtrpurl=http://localhost:8280/services/StockQuote

This time you will see Synapse receiving a message for which Synapse was set as the ultimate receiver of the message. Based on the 'To' EPR of http://localhost:8280/services/StockQuote, Synapse performs a match to the path '/StockQuote' and as the request matches the XPath expression of the filter mediator, the filter mediator's child mediators execute. This sends the message to a different endpoint as specified by the endpoint definition. The 'drop' mediator terminates further processing of the current message in a configuration. During response processing, the filter condition fails, and thus the 'send' mediator forwards the response back to the client using the implicit 'To' address.

<definitions xmlns="http://ws.apache.org/ns/synapse"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">

    <sequence name="main">
        <switch source="//m0:getQuote/m0:request/m0:symbol" xmlns:m0="http://services.samples">
            <case regex="IBM">
                <!-- the property mediator sets a local property on the *current* message -->
                <property name="symbol" value="Great stock - IBM"/>
            </case>
            <case regex="MSFT">
                <property name="symbol" value="Are you sure? - MSFT"/>
            </case>
            <default>
                <!-- it is possible to assign the result of an XPath expression as well -->
                <property name="symbol" expression="fn:concat('Normal Stock - ', //m0:getQuote/m0:request/m0:symbol)"/>
            </default>
        </switch>
        <log level="custom">
            <!-- the get-property() XPath extension function allows the lookup of local message properties
                        as well as properties from the Axis2 or Transport contexts (i.e. transport headers) -->
            <property name="symbol" expression="get-property('symbol')"/>
            <!-- the get-property() function supports the implicit message headers To/From/Action/FaultTo/ReplyTo -->
            <property name="epr" expression="get-property('To')"/>
        </log>
        <!-- Send the messages where they are destined to (i.e. the 'To' EPR of the message) -->
        <send/>
    </sequence>

</definitions>

Objective: Introduce switch-case mediator and writing and reading of local properties set on a message instance

Prerequisites:
Start the Synapse configuration numbered 2: i.e. synapse -sample 2
Start the Axis2 server and deploy the SimpleStockQuoteService if not already done.

Execute the 'ant stockquote ..' request again in the smart client mode, specifying 'IBM', 'MSFT' and 'SUN' as the stock symbols. When the symbol IBM is requested, viewing the mediation logs you will see that the case statements' first case for 'IBM' is executed and a local property named 'symbol' was set to 'Great stock - IBM'. Subsequently this local property value is looked up by the log mediator and logged using the 'get-property()' XPath extension function.

ant stockquote -Daddurl=http://localhost:9000/services/SimpleStockQuoteService -Dtrpurl=http://localhost:8280/ -Dsymbol=IBM
      INFO LogMediator - symbol = Great stock - IBM, epr = http://localhost:9000/axis2/services/SimpleStockQuoteService 
ant stockquote -Daddurl=http://localhost:9000/services/SimpleStockQuoteService -Dtrpurl=http://localhost:8280/ -Dsymbol=MSFT
      INFO LogMediator - symbol = Are you sure? - MSFT, epr = http://localhost:9000/axis2/services/SimpleStockQuoteService
<definitions xmlns="http://ws.apache.org/ns/synapse"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">
    <!-- define a string resource entry to the local registry -->
    <localEntry key="version">0.1</localEntry>
    <!-- define a reuseable endpoint definition -->
    <endpoint name="simple">
        <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
    </endpoint>

    <!-- define a reusable sequence -->
    <sequence name="stockquote">
        <!-- log the message using the custom log level. illustrates custom properties for log -->
        <log level="custom">
            <property name="Text" value="Sending quote request"/>
            <property name="version" expression="get-property('version')"/>
            <property name="direction" expression="get-property('direction')"/>
        </log>
        <!-- send message to real endpoint referenced by key "simple" endpoint definition -->
        <send>
            <endpoint key="simple"/>
        </send>
    </sequence>

    <sequence name="main">
        <in>
            <property name="direction" value="incoming"/>
            <sequence key="stockquote"/>
        </in>
        <out>
            <send/>
        </out>
    </sequence>
</definitions>

Objective: Illustrates local registry entry definitions, reusable endpoints and sequences

Prerequisites:
Start the Synapse configuration numbered 3: i.e. synapse -sample 3
Start the Axis2 server and deploy the SimpleStockQuoteService if not already done

This example uses a sequence named as "main" that specifies the main mediation rules to be executed. This is equivalent to directly specifying the mediators of the main sequence within the <definitions> tags. This is the recommended and also a better approach for non-trivial configurations. Execute the 'ant stockquote ..' request again, and following through the mediation logs you will now notice that the sequence named "main" is executed. Then for the incoming message flow the <in> mediator executes, and it calls the sequence named "stockquote".

ant stockquote -Daddurl=http://localhost:9000/services/SimpleStockQuoteService -Dtrpurl=http://localhost:8280/
DEBUG SequenceMediator - Sequence mediator <main> :: mediate()

DEBUG InMediator - In mediator mediate()
DEBUG SequenceMediator - Sequence mediator <stockquote> :: mediate()

As the "stockquote" sequence executes, the log mediator dumps a simple text/string property, result of an XPath evaluation, that picks up the key named "version", and a second result of an XPath evaluation that picks up a local message property set previously by the <property> mediator. The get-property() XPath extension function is able to read message properties local to the current message, local or remote registry entries, Axis2 message context properties as well as transport headers. The local entry definition for "version" defines a simple text/string registry entry for that which is visible to all messages that pass through Synapse.

[HttpServerWorker-1] INFO  LogMediator - Text = Sending quote request, version = 0.1, direction = incoming
[HttpServerWorker-1] DEBUG SendMediator - Send mediator :: mediate()
[HttpServerWorker-1] DEBUG AddressEndpoint - Sending To: http://localhost:9000/services/SimpleStockQuoteService 
<definitions xmlns="http://ws.apache.org/ns/synapse"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">

    <!-- the default fault handling sequence used by Synapse - named 'fault' -->
    <sequence name="fault">
        <log level="custom">
            <property name="text" value="An unexpected error occured"/>
            <property name="message" expression="get-property('ERROR_MESSAGE')"/>
        </log>
        <drop/>
    </sequence>

    <sequence name="sunErrorHandler">
        <log level="custom">
            <property name="text" value="An unexpected error occured for stock SUN"/>
            <property name="message" expression="get-property('ERROR_MESSAGE')"/>
            <!--<property name="detail" expression="get-property('ERROR_DETAIL')"/>-->
        </log>
        <drop/>
    </sequence>

    <sequence name="main">
        <in>
            <switch xmlns:m0="http://services.samples" source="//m0:getQuote/m0:request/m0:symbol">
                <case regex="IBM">
                    <send>
                        <endpoint>
                            <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
                        </endpoint>
                    </send>
                </case>
                <case regex="MSFT">
                    <send>
                        <endpoint key="bogus"/>
                    </send>
                </case>
                <case regex="SUN">
                    <sequence key="sunSequence"/>
                </case>
            </switch>
            <drop/>
        </in>

        <out>
            <send/>
        </out>
    </sequence>

    <sequence name="sunSequence" onError="sunErrorHandler">
        <send>
            <endpoint key="sunPort"/>
        </send>
    </sequence>

</definitions>

Objective: Introduction to error handling with the 'fault' sequence

Prerequisites:
Start the Synapse configuration numbered 4: i.e. synapse -sample 4
Start the Axis2 server and deploy the SimpleStockQuoteService if not already done

When the IBM stock quote is requested, the configuration routes it to the defined in-line endpoint, which routes the message to the SimpleStockQuoteService on the local Axis2 instance. Hence a valid response message is shown at the client.

If you lookup a stock quote for 'MSFT', Synapse is instructed to route the message to the endpoint defined as the 'bogus' endpoint, which does not exist. Synapse executes the specified error handler sequence closest to the point where the error was encountered. In this case, the currently executing sequence is 'main' and it does not specify an 'onError' attribute. Whenever Synapse cannot find an error handler, it looks for a sequence named 'fault'. Thus the 'fault' sequence can be seen executing, and writing the generic error message to the logs.

ant stockquote -Daddurl=http://localhost:9000/services/SimpleStockQuoteService -Dtrpurl=http://localhost:8280/ -Dsymbol=MSFT
[HttpServerWorker-1] DEBUG SendMediator - Send mediator :: mediate()
[HttpServerWorker-1] ERROR IndirectEndpoint - Reference to non-existent endpoint for key : bogus
[HttpServerWorker-1] DEBUG MediatorFaultHandler - MediatorFaultHandler :: handleFault
[HttpServerWorker-1] DEBUG SequenceMediator - Sequence mediator <fault> :: mediate()
[HttpServerWorker-1] DEBUG LogMediator - Log mediator :: mediate()
[HttpServerWorker-1] INFO LogMediator text = An unexpected error occured, message = Couldn't find the endpoint with the key : bogus

When the 'SUN' quote is requested, a custom sequence 'sunSequence' is invoked, and it specifies 'sunErrorHandler' as its error handler. Hence when the send fails, you could see the proper error handler invocation and the custom error message printed as follows.

ant stockquote -Daddurl=http://localhost:9000/services/SimpleStockQuoteService -Dtrpurl=http://localhost:8280/ -Dsymbol=SUN
[HttpServerWorker-1] DEBUG SequenceMediator - Sequence mediator <sunSequence> :: mediate()
[HttpServerWorker-1] DEBUG SequenceMediator - Setting the onError handler for the sequence
[HttpServerWorker-1] DEBUG AbstractListMediator - Implicit Sequence <SequenceMediator> :: mediate()
[HttpServerWorker-1] DEBUG SendMediator - Send mediator :: mediate()
[HttpServerWorker-1] ERROR IndirectEndpoint - Reference to non-existent endpoint for key : sunPort
[HttpServerWorker-1] DEBUG MediatorFaultHandler - MediatorFaultHandler :: handleFault
[HttpServerWorker-1] DEBUG SequenceMediator - Sequence mediator <sunErrorHandler> :: mediate()
[HttpServerWorker-1] DEBUG AbstractListMediator - Implicit Sequence <SequenceMediator> :: mediate()
[HttpServerWorker-1] DEBUG LogMediator - Log mediator :: mediate()
[HttpServerWorker-1] INFO LogMediator text = An unexpected error occured for stock SUN, message = Couldn't find the endpoint with the key : sunPort
<definitions xmlns="http://ws.apache.org/ns/synapse"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">

    <sequence name="myFaultHandler">
        <makefault response="true">
			<code xmlns:tns="http://www.w3.org/2003/05/soap-envelope" value="tns:Receiver"/>
            <reason expression="get-property('ERROR_MESSAGE')"/>
        </makefault>
        <send/>
    </sequence>

    <sequence name="main" onError="myFaultHandler">
        <in>
            <switch xmlns:m0="http://services.samples" source="//m0:getQuote/m0:request/m0:symbol">
                <case regex="MSFT">
                    <send>
                        <endpoint>
                            <address uri="http://bogus:9000/services/NonExistentStockQuoteService"/>
                        </endpoint>
                    </send>
                </case>
                <case regex="SUN">
                    <send>
                        <endpoint>
                            <address uri="http://localhost:9009/services/NonExistentStockQuoteService"/>
                        </endpoint>
                    </send>
                </case>
            </switch>
            <drop/>
        </in>

        <out>
            <send/>
        </out>
    </sequence>

</definitions>

Objective: Makefault mediator and sending back error responses

Prerequisites:
Start the Synapse configuration numbered 5: i.e. synapse -sample 5
Start the Axis2 server and deploy the SimpleStockQuoteService if not already done

When the MSFT stock quote is requested, an unknown host exception would be generated. A connection refused exception would be generated for the SUN stock request. This error message is captured and returned to the original client as a SOAP fault in this example.

ant stockquote -Daddurl=http://localhost:9000/services/SimpleStockQuoteService -Dtrpurl=http://localhost:8280/ -Dsymbol=MSFT

returns,

<soapenv:Fault xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"><faultcode>soapenv:Client</faultcode>
    <faultstring>java.net.UnknownHostException: bogus</faultstring><detail /></soapenv:Fault>

And

ant stockquote -Daddurl=http://localhost:9000/services/SimpleStockQuoteService -Dtrpurl=http://localhost:8280/ -Dsymbol=SUN

returns,

<soapenv:Fault xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"><faultcode>soapenv:Client</faultcode>
    <faultstring>java.net.ConnectException: Connection refused</faultstring><detail /></soapenv:Fault>
<definitions xmlns="http://ws.apache.org/ns/synapse"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">

    <sequence name="main">
        <in>
            <header name="To" value="http://localhost:9000/services/SimpleStockQuoteService"/>
        </in>
        <send/>
    </sequence>

</definitions>

Objective: Introduction to header, in (out) mediators

Prerequisites:
Start the Synapse configuration numbered 6: i.e. synapse -sample 6
Start the Axis2 server and deploy the SimpleStockQuoteService if not already done

In this example we use the stockquote client in the dumb client mode, setting the 'To' EPR of the message to Synapse. Then the 'in' mediator processes the incoming messages, and manipulates the 'To' header to refer to the stock quote service on the sample Axis2 server. Thus it is now possible to request for a stock quote as follows.

ant stockquote -Dtrpurl=http://localhost:8280/
<definitions xmlns="http://ws.apache.org/ns/synapse"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">

    <sequence name="main">
        <in>
            <validate>
                <schema key="validate_schema"/>
                <on-fail>
                    <!-- if the request does not validate againt schema throw a fault -->
                    <makefault response="true">
                        <code xmlns:tns="http://www.w3.org/2003/05/soap-envelope" value="tns:Receiver"/>
                        <reason value="Invalid custom quote request"/>
                    </makefault>
                </on-fail>
            </validate>
        </in>
        <send/>
    </sequence>

    <localEntry key="validate_schema">
        <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
                   xmlns="http://services.samples" elementFormDefault="qualified"
                   attributeFormDefault="unqualified" targetNamespace="http://services.samples">
            <xs:element name="getQuote">
                <xs:complexType>
                    <xs:sequence>
                        <xs:element name="request">
                            <xs:complexType>
                                <xs:sequence>
                                    <xs:element name="stocksymbol" type="xs:string"/>
                                </xs:sequence>
                            </xs:complexType>
                        </xs:element>
                    </xs:sequence>
                </xs:complexType>
            </xs:element>
        </xs:schema>
    </localEntry>

</definitions>

Objective: Introduction to local (static) registry entries and the validate mediator

Prerequisites:
Start the Synapse configuration numbered 7: i.e. synapse -sample 7
Start the Axis2 server and deploy the SimpleStockQuoteService if not already done

This example shows how a static XML fragment could be made available to the Synapse local registry. Resources defined in the local registry are static (i.e. never changes over the lifetime of the configuration) and may be specified as a source URL, in-line text or in-line xml. In this example the schema is made available under the key 'validate_schema'.

The validate mediator by default operates on the first child element of the SOAP body. You may specify an XPath expression using the 'source' attribute to override this behaviour. The validate mediator now uses the 'validate_schema' resource to validate the incoming message, and if the message validation fails it invokes the 'on-fail' sequence of mediators.

If you send a stockquote request using 'ant stockquote ...' you will get a fault back with the message 'Invalid custom quote request' as the schema validation failed. This is because the schema used in the example expects a slightly different message than what is created by the stock quote client. (i.e. expects a 'stocksymbol' element instead of 'symbol' to specify the stock symbol)

ant stockquote -Daddurl=http://localhost:9000/services/SimpleStockQuoteService -Dtrpurl=http://localhost:8280/
<definitions xmlns="http://ws.apache.org/ns/synapse"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">

    <!-- the SimpleURLRegistry allows access to a URL based registry (e.g. file:/// or http://) -->
    <registry provider="org.apache.synapse.registry.url.SimpleURLRegistry">
        <!-- the root property of the simple URL registry helps resolve a resource URL as root + key -->
        <parameter name="root">file:repository/conf/sample/resources/</parameter>
        <!-- all resources loaded from the URL registry would be cached for this number of milli seconds -->
        <parameter name="cachableDuration">15000</parameter>
    </registry>

    <!-- define the request processing XSLT resource as a static URL source -->
    <localEntry key="xslt-key-req" src="file:repository/conf/sample/resources/transform/transform.xslt"/>

    <sequence name="main">
        <in>
            <!-- transform the custom quote request into a standard quote requst expected by the service -->
            <xslt key="xslt-key-req"/>
        </in>
        <out>
            <!-- transform the standard response back into the custom format the client expects -->
            <!-- the key is looked up in the remote registry and loaded as a 'dynamic' registry resource -->
            <xslt key="transform/transform_back.xslt"/>
        </out>
        <send/>
    </sequence>

</definitions>

Objective: Introduction to static and dynamic registry resources and the XSLT mediator

Prerequisites:
Start the Synapse configuration numbered 8: i.e. synapse -sample 8
Start the Axis2 server and deploy the SimpleStockQuoteService if not already done

This example uses the XSLT mediator to perform transformations, and the xslt transformations are specified as registry resources. The first resource 'xslt-key-req' is specified as a 'local' registry entry. Local entries do not place the resource on the registry, but simply make it available to the local configuration. If a local entry is defined with a key that already exists in the remote registry, the local entry will get higher preference and override the remote resource.

In this example you will notice the new 'registry' definition. Synapse comes with a simple URL based registry implementation SimpleURLRegistry. During initialization of the registry, the SimpleURLRegistry expects to find a property named 'root', which specifies a prefix for the registry keys used later. When the SimpleURLRegistry is used, this root is prefixed to the entry keys to form the complete URL for the resource being looked up. The registry caches a resource once requested, and caches it internally for a specified duration. Once this period expires, it will reload the meta information about the resource and reload its cached copy if necessary, the next time the resource is requested.

Hence the second XSLT resource key 'transform/transform_back.xslt' concatenated with the 'root' of the SimpleURLRegistry 'file:repository/conf/sample/resources/' forms the complete URL of the resource as 'file:repository/conf/sample/resources/transform/transform_back.xslt' and caches its value for a period of 15000 ms.

Execute the custom quote client as 'ant stockquote -Dmode=customquote ...' and analyze the the Synapse debug log output

ant stockquote -Daddurl=http://localhost:9000/services/SimpleStockQuoteService -Dtrpurl=http://localhost:8280/ -Dmode=customquote

The incoming message is now transformed into a standard stock quote request as expected by the SimpleStockQuoteService deployed on the local Axis2 instance, by the XSLT mediator. The XSLT mediator uses Xalan-J to perform the transformations. It is possible to configure the underlying transformation engine using properties where necessary. The response from the SimpleStockQuoteService is converted back into the custom format as expected by the client during the out message processing.

During the response processing you could see the SimpleURLRegistry fetching the resource as shown by the log message below

[HttpClientWorker-1] DEBUG SimpleURLRegistry ==> Repository fetch of resource with key : transform/transform_back.xslt

If you run the client again immediately (i.e within 15 seconds of the first request) you will not see the resource being reloaded by the registry as the cached value would be still valid.

However if you leave the system idle for 15 seconds or more and then retry the same request, you will now notice that the registry noticed the cached resource has expired and will check the meta information about the resource to check if the resource itself has changed and will require a fresh fetch from the source URL. If the meta data / version number indicates that a reload of the cached resource is not necessary (i.e. unless the resource itself actually changed) the updated meta information is used and the cache lease extended as appropriate.

[HttpClientWorker-1] DEBUG AbstractRegistry - Cached object has expired for key : transform/transform_back.xslt
[HttpClientWorker-1] DEBUG SimpleURLRegistry - Perform RegistryEntry lookup for key : transform/transform_back.xslt
[HttpClientWorker-1] DEBUG AbstractRegistry - Expired version number is same as current version in registry
[HttpClientWorker-1] DEBUG AbstractRegistry - Renew cache lease for another 15s 

Now edit the repository/conf/sample/resources/transform/transform_back.xslt file and add a blank line at the end. Now when you run the client again, and if the cache is expired, the resource would be re-fetched from its URL by the registry and this can be seen by the following debug log messages

[HttpClientWorker-1] DEBUG AbstractRegistry - Cached object has expired for key : transform/transform_back.xslt
[HttpClientWorker-1] DEBUG SimpleURLRegistry - Perform RegistryEntry lookup for key : transform/transform_back.xslt
[HttpClientWorker-1] INFO  SimpleURLRegistry - ==> Repository fetch of resource with key : transform/transform_back.xslt 

Thus the SimpleURLRegistry allows resource to be cached, and updates detected so that the changes could be reloaded without restarting the Synapse instance.

<definitions xmlns="http://ws.apache.org/ns/synapse"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">

    <registry provider="org.apache.synapse.registry.url.SimpleURLRegistry">
        <parameter name="root">file:./repository/conf/sample/resources/</parameter>
        <parameter name="cachableDuration">15000</parameter>
    </registry>

    <sequence name="main">
        <sequence key="sequence/dynamic_seq_1.xml"/>
    </sequence>

</definitions>

Objective: Introduction to dynamic sequences with a registry

Prerequisites:
Start the Synapse configuration numbered 9: i.e. synapse -sample 9
Start the Axis2 server and deploy the SimpleStockQuoteService if not already done

This example introduces the dynamic behaviour of Synapse through the use of a registry. Synapse supports dynamic definitions for sequences and endpoints, and as seen before, for resources. In this example we define a Synapse configuration which references a sequence definition specified as a registry key. The registry key resolves to the actual content of the sequence which would be loaded dynamically by Synapse at runtime, and cached appropriately as per its definition in the registry. Once the cache expires, Synapse would re-check the meta information for the definition and re-load the sequence definition if necessary and re-cache it again.

Once Synapse is started, execute the stock quote client as 'ant stockquote..'. You will notice that that Synapse fetches the definition of the sequence from the registry and executes its rules as follows:

ant stockquote -Daddurl=http://localhost:9000/services/SimpleStockQuoteService -Dtrpurl=http://localhost:8280/
[HttpServerWorker-1] DEBUG  SimpleURLRegistry - ==> Repository fetch of resource with key : sequence/dynamic_seq_1.xml
...
[HttpServerWorker-1] DEBUG SequenceMediator - Sequence mediator <dynamic_sequence> :: mediate()
...
[HttpServerWorker-1] INFO  LogMediator - message = *** Test Message 1 ***

Now if you execute the client immediately (i.e. within 15 seconds of the last execution) you will notice that the sequence was not reloaded. If you edit the sequence definition in repository/conf/sample/resources/sequence/dynamic_seq_1.xml (i.e. edit the log message to read as "*** Test Message 2 ***") and execute the client again, you will notice that the new message is not yet visible (i.e. if you execute this within 15 seconds of loading the resource for the first time) However, after 15 seconds elapsed since the original caching of the sequence, you will notice that the new sequence is loaded and executed by Synapse from the following log messages.

[HttpServerWorker-1] DEBUG  SimpleURLRegistry - ==> Repository fetch of resource with key : sequence/dynamic_seq_1.xml
...
[HttpServerWorker-1] DEBUG SequenceMediator - Sequence mediator <dynamic_sequence> :: mediate()
...
[HttpServerWorker-1] INFO  LogMediator - message = *** Test Message 2 ***

The cache timeout could be tuned appropriately by configuring the URL registry to suit the environment and the needs.

<definitions xmlns="http://ws.apache.org/ns/synapse"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">

    <registry provider="org.apache.synapse.registry.url.SimpleURLRegistry">
        <parameter name="root">file:repository/conf/sample/resources/</parameter>
        <parameter name="cachableDuration">15000</parameter>
    </registry>

    <sequence name="foo">
        <sequence key="xxx"/>
    </sequence>

    <sequence name="main">
        <in>
            <send>
                <endpoint key="endpoint/dynamic_endpt_1.xml"/>
            </send>
        </in>
        <out>
            <send/>
        </out>
    </sequence>

</definitions>

Objective: Introduction to dynamic endpoints with the Registry

Prerequisites:
Start the Synapse configuration numbered 10: i.e. synapse -sample 10
Start the Axis2 server and deploy the SimpleStockQuoteService if not already done
Start a second Axis2 server on HTTP port 9001 and HTTPS port 9003 as follows:

./axis2server.sh -http 9001 -https 9003

This example introduces dynamic endpoints, where the definition of an endpoint is stored in the registry. To follow this example execute the stock quote client as 'ant stockquote..' and see that the message is routed to the SimpleStockQuoteService on the default Axis2 instance on HTTP port 9000. Repeat the above example immediately again, and notice that the endpoint is cached and reused by Synapse - similarly to example # 8.

ant stockquote -Dtrpurl=http://localhost:8280/

Now edit the repository/conf/sample/resources/endpoint/dynamic_endpt_1.xml definition and update the address to "http://localhost:9001/services/SimpleStockQuoteService". After the cached value expires, the Registry loads the new definition of the endpoint, and then the messages can be seen being routed to the second sample Axis2 server on HTTP port 9001.

<definitions xmlns="http://ws.apache.org/ns/synapse"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">

    <registry provider="org.apache.synapse.registry.url.SimpleURLRegistry">
        <parameter name="root">file:./repository/conf/sample/resources/</parameter>
        <parameter name="cachableDuration">15000</parameter>
    </registry>

</definitions>

Objective: A full registry based configuration

Prerequisites:
Start the Synapse configuration numbered 11: i.e. synapse -sample 11
Start the Axis2 server and deploy the SimpleStockQuoteService if not already done

This example shows a full registry based Synapse configuration. Thus it is possible to start a remote configuration from multiple instances of Synapse in a clustered environment easily. The Synapse configuration held on a node hosting Synapse simply points to the registry and looks up the actual configuration by requesting the key 'synapse.xml'.

(Note: Full registry based configuration is not dynamic atleast for the moment. i.e. it is not reloading itself)

ant stockquote -Daddurl=http://localhost:9000/services/SimpleStockQuoteService -Dtrpurl=http://localhost:8280/
[HttpServerWorker-1] INFO LogMediator - message = This is a dynamic Synapse configuration

The actual synapse.xml loaded is:

<!-- a registry based Synapse configuration -->
<definitions xmlns="http://ws.apache.org/ns/synapse"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">

    <sequence name="main">
        <log level="custom">
            <property name="message" value="This is a dynamic Synapse configuration"/>
        </log>
        <send/>
    </sequence>

</definitions>

Objective: Demonstrate one-way messaging / fireAndForget through Synapse

Prerequisites:
Start the Axis2 server and deploy the SimpleStockQuoteService (Refer steps above)
Start the Synapse configuration numbered 1: i.e. synapse -sample 1

This example invokes the one-way 'placeOrder' operation on the SimpleStockQuoteService using the custom client which uses the Axis2 ServiceClient.fireAndForget() API. To test this, use 'ant -Dmode=placeorder...' and you will notice the one-way message flowing through Synapse into the sample Axis2 server instance, which reports the acceptance of the order as follows:

ant stockquote -Daddurl=http://localhost:9000/services/SimpleStockQuoteService -Dtrpurl=http://localhost:8280/ -Dmode=placeorder
SimpleStockQuoteService :: Accepted order for : 7482 stocks of IBM at $ 169.27205579038733

If you send your client request through TCPmon, you will notice that the SimpleStockQuoteService replies to Synapse with a HTTP 202 reply, and that Synapse in turns replies to the client with a HTTP 202 acknowledgment

Objective: Demonstrate dual channel messaging through Synapse

Prerequisites:
Start the Axis2 server and deploy the SimpleStockQuoteService (Refer steps above)
Start the Synapse configuration numbered 0: i.e. synapse -sample 0

This example invokes the same 'getQuote' operation on the SimpleStockQuoteService using the custom client which uses the Axis2 ServiceClient API with useSeparateListener set to true so that the response is coming through a different channel than the one which is used to send the request to a callback defined in the client. To test this, use 'ant -Dmode=dualquote...' and you will notice the dual channel invocation through Synapse into the sample Axis2 server instance, which reports the response back to the client over a different channel:

ant stockquote -Daddurl=http://localhost:9000/services/SimpleStockQuoteService -Dtrpurl=http://localhost:8280/ -Dmode=dualquote
Response received to the callback
Standard dual channel :: Stock price = $57.16686934968289

If you send your client request through TCPmon, you will notice that Synapse replies to the client with a HTTP 202 acknowledgment when you send the request and the communication between Synapse and the server happens on a single channel and then you get the response back from Synapse to the clients callback in a different channel (which cannot be observed through TCPmon)

Also you could see the wsa:Reply-To header being something like http://localhost:8200/axis2/services/anonService2 which implies that the reply is being on a different channel listening on the port 8200. Please note that it is required to engage addressing when using the dual channel invocation because it requires the wsa:Reply-To header.

<definitions xmlns="http://ws.apache.org/ns/synapse"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">

    <localEntry key="local-enrty-ep-key"
                src="file:repository/conf/sample/resources/endpoint/dynamic_endpt_1.xml"/>

    <localEntry key="local-enrty-sequence-key">
        <sequence name="dynamic_sequence">
            <log level="custom">
                <property name="message" value="*** Test Message 1 ***"/>
            </log>
        </sequence>
    </localEntry>

    <sequence name="main">
        <in>
            <sequence key="local-enrty-sequence-key"/>
            <send>
                <endpoint key="local-enrty-ep-key"/>
            </send>
        </in>
        <out>
            <send/>
        </out>
    </sequence>

</definitions>

Objective: Sequence and Endpoints as local registry entries

Prerequisites:
Start the Synapse configuration numbered 14: i.e. synapse -sample 14
Start the Axis2 server and deploy the SimpleStockQuoteService if not already done

This example shows sequences and endpoints fetched from local registry. Thus it is possible to have endpoints sequences as local registry entries including file entries. Execute the following command to see the sample working, where you will be able to see the log statement from the fetched sequence from the local entry and the endpoint will be fetched from the specified file at runtime and be cached in the system

ant stockquote -Dtrpurl=http://localhost:8280/

Advanced mediations with endpoints

<definitions xmlns="http://ws.apache.org/ns/synapse"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">

    <sequence name="main">
        <!-- filtering of messages with XPath and regex matches -->
        <filter source="get-property('To')" regex=".*/StockQuote.*">
            <then>
                <send>
                    <endpoint>
                        <address uri="http://localhost:9000/services/SimpleStockQuoteService" format="soap11"/>
                    </endpoint>
                </send>
                <drop/>
            </then>
        </filter>
        <send/>
    </sequence>

</definitions>

Objective: POX to SOAP conversion

Prerequisites:
Start the Synapse configuration numbered 50: i.e. synapse -sample 50

Start the Axis2 server and deploy the SimpleStockQuoteService if not already done

Execute the 'ant stockquote' specifying that the request should be a REST request as follows:

ant stockquote -Dtrpurl=http://localhost:8280/services/StockQuote -Drest=true

This example shows a HTTP REST request (as shown below) being transformed into a SOAP request and forwarded to the stock quote service.

POST /soap/StockQuote HTTP/1.1
Content-Type: application/xml; charset=UTF-8;action="urn:getQuote";
SOAPAction: urn:getQuote
User-Agent: Axis2
Host: 127.0.0.1
Transfer-Encoding: chunked

75
<m0:getQuote xmlns:m0="http://services.samples/xsd">
   <m0:request>
      <m0:symbol>IBM</m0:symbol>
   </m0:request>
</m0:getQuote>0
<definitions xmlns="http://ws.apache.org/ns/synapse"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">

    <sequence name="main">
        <in>
            <filter source="get-property('Action')" regex="urn:uploadFileUsingMTOM">
                <then>
                    <property name="example" value="mtom"/>
                    <send>
                        <endpoint>
                            <address uri="http://localhost:9000/services/MTOMSwASampleService"
                                     optimize="mtom"/>
                        </endpoint>
                    </send>
                </then>
            </filter>
            <filter source="get-property('Action')" regex="urn:uploadFileUsingSwA">
                <then>
                    <property name="example" value="swa"/>
                    <send>
                        <endpoint>
                            <address uri="http://localhost:9000/services/MTOMSwASampleService"
                                     optimize="swa"/>
                        </endpoint>
                    </send>
                </then>
            </filter>
        </in>
        <out>
            <filter source="get-property('example')" regex="mtom">
                <then>
                    <property name="enableMTOM" value="true" scope="axis2"/>
                </then>
            </filter>
            <filter source="get-property('example')" regex="swa">
                <then>
                    <property name="enableSwA" value="true" scope="axis2"/>
                </then>
            </filter>
            <send/>
        </out>
    </sequence>

</definitions>

Objective: MTOM and SwA optimizations and request/response correlation

Prerequisites:
Start the Synapse configuration numbered 51: i.e. synapse -sample 51
Start the Axis2 server and deploy the MTOMSwASampleService if not already done

Execute the 'ant optimizeclient' specifying MTOM optimization as follows:

ant optimizeclient -Dopt_mode=mtom

The configuration now sets a local message context property, and forwards the message to 'http://localhost:9000/services/MTOMSwASampleService' optimizing binary content as MTOM. By sending this message through TCPMon you would be able to see the actual message sent over the HTTP transport if required. Thus during response processing, by checking the local message property Synapse could identify the past information about the current message context, and uses this knowledge to transform the response back to the client in the same format as the original request.

When the client executes successfully, it will upload a file containing the ASF logo and receive its response back again and saves it into a temporary file.

[java] Sending file : ./../../repository/conf/sample/resources/mtom/asf-logo.gif as MTOM
[java] Saved response to file : ./../../work/temp/sampleClient/mtom-4417.gif

Next try SwA as:

ant optimizeclient -Dopt_mode=swa
[java] Sending file : ./../../repository/conf/sample/resources/mtom/asf-logo.gif as SwA
[java] Saved response to file : ./../../work/temp/sampleClient/swa-30391.gif

By using TCPMon and sending the message through it, one can inspect that the requests and responses sent are indeed MTOM optimized or sent as HTTP attachments as follows:

POST http://localhost:9000/services/MTOMSwASampleService HTTP/1.1
Host: 127.0.0.1
SOAPAction: urn:uploadFileUsingMTOM
Content-Type: multipart/related; boundary=MIMEBoundaryurn_uuid_B94996494E1DD5F9B51177413845353; type="application/xop+xml";
start="<0.urn:uuid:B94996494E1DD5F9B51177413845354@apache.org>"; start-info="text/xml"; charset=UTF-8
Transfer-Encoding: chunked
Connection: Keep-Alive
User-Agent: Synapse-HttpComponents-NIO

--MIMEBoundaryurn_uuid_B94996494E1DD5F9B51177413845353241
Content-Type: application/xop+xml; charset=UTF-8; type="text/xml"
Content-Transfer-Encoding: binary
Content-ID:
   <0.urn:uuid:B94996494E1DD5F9B51177413845354@apache.org>221b1
      <?xml version='1.0' encoding='UTF-8'?>
         <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
            <soapenv:Body>
               <m0:uploadFileUsingMTOM xmlns:m0="http://www.apache-synapse.org/test">
                  <m0:request>
                     <m0:image>
                        <xop:Include href="cid:1.urn:uuid:78F94BC50B68D76FB41177413845003@apache.org" xmlns:xop="http://www.w3.org/2004/08/xop/include" />
                     </m0:image>
                  </m0:request>
               </m0:uploadFileUsingMTOM>
            </soapenv:Body>
         </soapenv:Envelope>
--MIMEBoundaryurn_uuid_B94996494E1DD5F9B51177413845353217
Content-Type: image/gif
Content-Transfer-Encoding: binary
Content-ID:
         <1.urn:uuid:78F94BC50B68D76FB41177413845003@apache.org>22800GIF89a... << binary content >>
POST http://localhost:9000/services/MTOMSwASampleService HTTP/1.1
Host: 127.0.0.1
SOAPAction: urn:uploadFileUsingSwA
Content-Type: multipart/related; boundary=MIMEBoundaryurn_uuid_B94996494E1DD5F9B51177414170491; type="text/xml";
start="<0.urn:uuid:B94996494E1DD5F9B51177414170492@apache.org>"; charset=UTF-8
Transfer-Encoding: chunked
Connection: Keep-Alive
User-Agent: Synapse-HttpComponents-NIO

--MIMEBoundaryurn_uuid_B94996494E1DD5F9B51177414170491225
Content-Type: text/xml; charset=UTF-8
Content-Transfer-Encoding: 8bit
Content-ID:
   <0.urn:uuid:B94996494E1DD5F9B51177414170492@apache.org>22159
      <?xml version='1.0' encoding='UTF-8'?>
         <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
            <soapenv:Body>
               <m0:uploadFileUsingSwA xmlns:m0="http://www.apache-synapse.org/test">
                  <m0:request>
                     <m0:imageId>urn:uuid:15FD2DA2584A32BF7C1177414169826</m0:imageId>
                  </m0:request>
               </m0:uploadFileUsingSwA>
            </soapenv:Body>
         </soapenv:Envelope>22--34MIMEBoundaryurn_uuid_B94996494E1DD5F9B511774141704912
17
Content-Type: image/gif
Content-Transfer-Encoding: binary
Content-ID:
         <urn:uuid:15FD2DA2584A32BF7C1177414169826>22800GIF89a... << binary content >>
<definitions xmlns="http://ws.apache.org/ns/synapse"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">

    <sequence name="main" onError="errorHandler">
        <in>
            <send>
                <endpoint>
                    <loadbalance>
                        <endpoint>
                            <address uri="http://localhost:9001/services/LBService1">
                                <enableAddressing/>
                                <suspendDurationOnFailure>60</suspendDurationOnFailure>
                            </address>
                        </endpoint>
                        <endpoint>
                            <address uri="http://localhost:9002/services/LBService1">
                                <enableAddressing/>
                                <suspendDurationOnFailure>60</suspendDurationOnFailure>
                            </address>
                        </endpoint>
                        <endpoint>
                            <address uri="http://localhost:9003/services/LBService1">
                                <enableAddressing/>
                                <suspendDurationOnFailure>60</suspendDurationOnFailure>
                            </address>
                        </endpoint>
                    </loadbalance>
                </endpoint>
            </send>
            <drop/>
        </in>

        <out>
            <!-- Send the messages where they have been sent (i.e. implicit To EPR) -->
            <send/>
        </out>
    </sequence>

    <sequence name="errorHandler">
        <makefault response="true">
            <code xmlns:tns="http://www.w3.org/2003/05/soap-envelope" value="tns:Receiver"/>
            <reason value="COULDN'T SEND THE MESSAGE TO THE SERVER."/>
        </makefault>
        <send/>
    </sequence>

</definitions>

Objective: Demonstrate the simple load balancing among a set of endpoints

Prerequisites:
Start Synapse with sample configuration 52. (i.e. synapse -sample 52)
Deploy the LoadbalanceFailoverService by switching to <Synapse installation directory>/samples/axis2Server/src/LoadbalanceFailoverService directory and running ant.
Start three instances of sample Axis2 server on HTTP ports 9001, 9002 and 9003 and give some unique names to each server.

Example commands to run sample Axis2 servers from the <Synapse installation directory>/samples/axis2Server directory in Linux are listed below:

./axis2server.sh -http 9001 -https 9005 -name MyServer1
./axis2server.sh -http 9002 -https 9006 -name MyServer2
./axis2server.sh -http 9003 -https 9007 -name MyServer3

Now we are done with setting up the environment for load balance sample. Start the load balance and failover client using the following command:

ant loadbalancefailover -Di=100

This client sends 100 requests to the LoadbalanceFailoverService through Synapse. Synapse will distribute the load among the three endpoints mentioned in the configuration in round-robin manner. LoadbalanceFailoverService appends the name of the server to the response, so that client can determine which server has processed the message. If you examine the console output of the client, you can see that requests are processed by three servers as follows:

[java] Request: 1 ==> Response from server: MyServer1
[java] Request: 2 ==> Response from server: MyServer2
[java] Request: 3 ==> Response from server: MyServer3
[java] Request: 4 ==> Response from server: MyServer1
[java] Request: 5 ==> Response from server: MyServer2
[java] Request: 6 ==> Response from server: MyServer3
[java] Request: 7 ==> Response from server: MyServer1
...

Now run the client without the -Di=100 parameter to send infinite requests. While running the client shutdown the server named MyServer1. You can observe that requests are only distributed among MyServer2 and MyServer3 after shutting down MyServer1. Console output before and after shutting down MyServer1 is listed below (MyServer1 was shutdown after request 63):

...
[java] Request: 61 ==> Response from server: MyServer1
[java] Request: 62 ==> Response from server: MyServer2
[java] Request: 63 ==> Response from server: MyServer3
[java] Request: 64 ==> Response from server: MyServer2
[java] Request: 65 ==> Response from server: MyServer3
[java] Request: 66 ==> Response from server: MyServer2
[java] Request: 67 ==> Response from server: MyServer3
...

Now restart MyServer1. You can observe that requests will be again sent to all three servers roughly after 60 seconds. This is because we have specified <suspendDurationOnFailure> as 60 seconds in the configuration. Therefore, load balance endpoint will suspend any failed child endpoint only for 60 seconds after detecting the failure.

<definitions xmlns="http://ws.apache.org/ns/synapse"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">

    <sequence name="main" onError="errorHandler">
        <in>
            <send>
                <endpoint>
                    <failover>
                        <endpoint>
                            <address uri="http://localhost:9001/services/LBService1">
                                <enableAddressing/>
                                <suspendDurationOnFailure>60</suspendDurationOnFailure>
                            </address>
                        </endpoint>
                        <endpoint>
                            <address uri="http://localhost:9002/services/LBService1">
                                <enableAddressing/>
                                <suspendDurationOnFailure>60</suspendDurationOnFailure>
                            </address>
                        </endpoint>
                        <endpoint>
                            <address uri="http://localhost:9003/services/LBService1">
                                <enableAddressing/>
                                <suspendDurationOnFailure>60</suspendDurationOnFailure>
                            </address>
                        </endpoint>
                    </failover>
                </endpoint>
            </send>
            <drop/>
        </in>

        <out>
            <!-- Send the messages where they have been sent (i.e. implicit To EPR) -->
            <send/>
        </out>
    </sequence>

    <sequence name="errorHandler">
        <makefault response="true">
            <code xmlns:tns="http://www.w3.org/2003/05/soap-envelope" value="tns:Receiver"/>
            <reason value="COULDN'T SEND THE MESSAGE TO THE SERVER."/>
        </makefault>
        <send/>
    </sequence>

</definitions>

Objective: Demonstrate the failover sending

Prerequisites:
Start Synapse with sample configuration 53 (i.e. synapse -sample 53)
Deploy the LoadbalanceFailoverService and start three instances of sample Axis2 server as mentioned in sample 52.

Above configuration sends messages with the failover behavior. Initially the server at port 9001 is treated as primary and other two are treated as backups. Messages are always directed only to the primary server. If the primary server has failed, next listed server is selected as the primary. Thus, messages are sent successfully as long as there is at least one active server. To test this, run the loadbalancefailover client to send infinite requests as follows:

ant loadbalancefailover

You can see that all requests are processed by MyServer1. Now shutdown MyServer1 and inspect the console output of the client. You will observe that all subsequent requests are processed by MyServer2.

The console output with MyServer1 shutdown after request 127 is listed below:

...
[java] Request: 125 ==> Response from server: MyServer1
[java] Request: 126 ==> Response from server: MyServer1
[java] Request: 127 ==> Response from server: MyServer1
[java] Request: 128 ==> Response from server: MyServer2
[java] Request: 129 ==> Response from server: MyServer2
[java] Request: 130 ==> Response from server: MyServer2
...

You can keep on shutting down servers like this. Client will get a response till you shutdown all listed servers. Once all servers are shutdown, the error sequence is activated and a fault message is sent to the client as follows.

[java] COULDN'T SEND THE MESSAGE TO THE SERVER.

Once a server is detected as failed, it will be added to the active servers list again after 60 seconds (specified in <suspendDurationOnFailure> in the configuration). Therefore, if you have restarted any of the stopped servers and have shutdown all other servers, messages will be directed to the newly started server.

<definitions xmlns="http://ws.apache.org/ns/synapse"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">

    <sequence name="main" onError="errorHandler">
        <in>
            <send>
                <endpoint>
                    <!-- specify the session as the simple client session provided by Synapse for
                                            testing purpose -->
                    <session type="simpleClientSession"/>

                    <loadbalance>
                        <endpoint>
                            <address uri="http://localhost:9001/services/LBService1">
                                <enableAddressing/>
                            </address>
                        </endpoint>
                        <endpoint>
                            <address uri="http://localhost:9002/services/LBService1">
                                <enableAddressing/>
                            </address>
                        </endpoint>
                        <endpoint>
                            <address uri="http://localhost:9003/services/LBService1">
                                <enableAddressing/>
                            </address>
                        </endpoint>
                    </loadbalance>
                </endpoint>
            </send>
            <drop/>
        </in>

        <out>
            <!-- Send the messages where they have been sent (i.e. implicit To EPR) -->
            <send/>
        </out>
    </sequence>

    <sequence name="errorHandler">
        <makefault response="true">
            <code xmlns:tns="http://www.w3.org/2003/05/soap-envelope" value="tns:Receiver"/>
            <reason value="COULDN'T SEND THE MESSAGE TO THE SERVER."/>
        </makefault>
        <send/>
    </sequence>

</definitions>

Objective: Demonstrate the loadbalancing with session affinity using client initiated sessions

Prerequisites:
Start Synapse with sample configuration 54 (i.e. synapse -sample 54).
Deploy the LoadbalanceFailoverService and start three instances of the sample Axis2 server as in sample 52.

Above configuration is same as the load balancing configuration in sample 52, except that the session type is specified as "simpleClientSession". This is a client initiated session, which means that the client generates the session identifier and sends it with each request. In this sample session type, client adds a SOAP header named ClientID containing the identifier of the client. Synapse binds this ID with a server on the first request and sends all successive requests containing that ID to the same server. Now switch to samples/axis2Client directory and run the client using the following command to check this in action.

ant loadbalancefailover -Dmode=session

In the session mode, client continuously sends requests with three different client (session) IDs. One ID is selected among these three IDs for each request randomly. Then client prints the session ID with the responded server for each request. Client output for the first 10 requests are shown below.

[java] Request: 1 Session number: 1 Response from server: MyServer3
[java] Request: 2 Session number: 2 Response from server: MyServer2
[java] Request: 3 Session number: 0 Response from server: MyServer1
[java] Request: 4 Session number: 2 Response from server: MyServer2
[java] Request: 5 Session number: 1 Response from server: MyServer3
[java] Request: 6 Session number: 2 Response from server: MyServer2
[java] Request: 7 Session number: 2 Response from server: MyServer2
[java] Request: 8 Session number: 1 Response from server: MyServer3
[java] Request: 9 Session number: 0 Response from server: MyServer1
[java] Request: 10 Session number: 0 Response from server: MyServer1
... 

You can see that session number 0 is always directed to the server named MyServer1. That means session number 0 is bound to MyServer1. Similarly session 1 and 2 are bound to MyServer3 and MyServer2 respectively.

<definitions xmlns="http://ws.apache.org/ns/synapse"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">

    <sequence name="main" onError="errorHandler">
        <in>
            <send>
                <endpoint>
                    <!-- specify the session as the simple client session provided by Synapse for
                                     testing purpose -->
                    <session type="simpleClientSession"/>

                    <loadbalance>
                        <endpoint>
                            <failover>
                                <endpoint>
                                    <address uri="http://localhost:9001/services/LBService1">
                                        <enableAddressing/>
                                    </address>
                                </endpoint>
                                <endpoint>
                                    <address uri="http://localhost:9002/services/LBService1">
                                        <enableAddressing/>
                                    </address>
                                </endpoint>
                            </failover>
                        </endpoint>
                        <endpoint>
                            <failover>
                                <endpoint>
                                    <address uri="http://localhost:9003/services/LBService1">
                                        <enableAddressing/>
                                    </address>
                                </endpoint>
                                <endpoint>
                                    <address uri="http://localhost:9004/services/LBService1">
                                        <enableAddressing/>
                                    </address>
                                </endpoint>
                            </failover>
                        </endpoint>
                    </loadbalance>
                </endpoint>
            </send>
            <drop/>
        </in>

        <out>
            <!-- Send the messages where they have been sent (i.e. implicit To EPR) -->
            <send/>
        </out>
    </sequence>

    <sequence name="errorHandler">
        <makefault response="true">
            <code xmlns:tns="http://www.w3.org/2003/05/soap-envelope" value="tns:Receiver"/>
            <reason value="COULDN'T SEND THE MESSAGE TO THE SERVER."/>
        </makefault>
        <send/>
    </sequence>

</definitions>

Objective: Demonstrate the session affinity based load balancing with failover capability

Prerequisites:
Start Synapse with sample configuration 55 (i.e. synapse -sample 55).
Deploy the LoadbalanceFailoverService and start four sample Axis2 servers on HTTP ports 9001, 9002, 9003 and 9004 respectively (make sure to specify non-conflicting HTTPS ports).

This configuration also uses "simpleClientSession" to bind sessions as in the previous sample. But failover endpoints are specified as the child endpoints of the load balance endpoint. Therefore sessions are bound to the failover endpoints. Session information has to be replicated among the servers listed under each failover endpoint using some clustering mechanism. Therefore, if one endpoint bound to a session failed, successive requets for that session will be directed to the next endpoint in that failover group. Run the client using the following command to observe this behaviour.

ant loadbalancefailover -Dmode=session

You can see a client output as shown below.

...
[java] Request: 222 Session number: 0 Response from server: MyServer1
[java] Request: 223 Session number: 0 Response from server: MyServer1
[java] Request: 224 Session number: 1 Response from server: MyServer1
[java] Request: 225 Session number: 2 Response from server: MyServer3
[java] Request: 226 Session number: 0 Response from server: MyServer1
[java] Request: 227 Session number: 1 Response from server: MyServer1
[java] Request: 228 Session number: 2 Response from server: MyServer3
[java] Request: 229 Session number: 1 Response from server: MyServer1
[java] Request: 230 Session number: 1 Response from server: MyServer1
[java] Request: 231 Session number: 2 Response from server: MyServer3
...

Note that session 0 is always directed to MyServer1 and session 1 is directed to MyServer3. No requests are directed to MyServer2 and MyServer4 as they are kept as backups by failover endpoints. Now shutdown the server named MyServer1 while running the sample. You will observe that all successive requests for session 0 is now directed to MyServer2, which is the backup server for MyServer1's group. This is shown below, where MyServer1 was shutdown after the request 534.

...
[java] Request: 529 Session number: 2 Response from server: MyServer3
[java] Request: 530 Session number: 1 Response from server: MyServer1
[java] Request: 531 Session number: 0 Response from server: MyServer1
[java] Request: 532 Session number: 1 Response from server: MyServer1
[java] Request: 533 Session number: 1 Response from server: MyServer1
[java] Request: 534 Session number: 1 Response from server: MyServer1
[java] Request: 535 Session number: 0 Response from server: MyServer2
[java] Request: 536 Session number: 0 Response from server: MyServer2
[java] Request: 537 Session number: 0 Response from server: MyServer2
[java] Request: 538 Session number: 2 Response from server: MyServer3
[java] Request: 539 Session number: 0 Response from server: MyServer2
...
<definitions xmlns="http://ws.apache.org/ns/synapse"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">

    <sequence name="main">
        <in>
            <send>
                <!-- get epr from the given wsdl -->
                <endpoint>
                    <wsdl uri="file:repository/conf/sample/resources/proxy/sample_proxy_1.wsdl"
                          service="SimpleStockQuoteService"
                          port="SimpleStockQuoteServiceHttpSoap11Endpoint"/>
                </endpoint>
            </send>
        </in>

        <out>
            <send/>
        </out>
    </sequence>

</definitions>

Objective: Demonstrate the use of WSDL endpoints

Prerequisites:
Start the Synapse configuration numbered 56 (i.e. synapse -sample 56).
Deploy the SimpleStockQuoteService and start the sample Axis2 server.

This sample uses a WSDL endpoint inside the send mediator. WSDL endpoints can extract endpoint's address from the given WSDL. As WSDL documents can have many services and many ports inside each service, the service and port of the required endpoint has to be specified. As with address endpoints, QoS parameters for the endpoint can be specified in-line in the configuration. An excerpt taken from the sample_proxy_1.wsdl containing the specified service and port is listed below.

<wsdl:service name="SimpleStockQuoteService">
    <wsdl:port name="SimpleStockQuoteServiceHttpSoap11Endpoint" binding="ns:SimpleStockQuoteServiceSoap11Binding">
        <soap:address location="http://localhost:9000/services/SimpleStockQuoteService.SimpleStockQuoteServiceHttpSoap11Endpoint"/>
    </wsdl:port>
    <wsdl:port name="SimpleStockQuoteServiceHttpSoap12Endpoint" binding="ns:SimpleStockQuoteServiceSoap12Binding">
        <soap12:address location="http://localhost:9000/services/SimpleStockQuoteService.SimpleStockQuoteServiceHttpSoap12Endpoint"/>
    </wsdl:port>
</wsdl:service>

Specified service and port refers to the endpoint address "http://localhost:9000/services/SimpleStockQuoteService.SimpleStockQuoteServiceHttpSoap11Endpoint" according to the above WSDL. Now run the client using the following command.

ant stockquote -Dsymbol=IBM -Dmode=quote -Daddurl=http://localhost:8280

Client will print the quote price for IBM received from the server running on port 9000. Observe the Axis2 console and the Synapse console to verify this behavior.

<definitions xmlns="http://ws.apache.org/ns/synapse"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">

    <sequence name="main" onError="errorHandler">
        <in>
            <send>
                <endpoint name="dynamicLB">
                    <dynamicLoadbalance failover="true"
                                        algorithm="org.apache.synapse.endpoints.algorithms.RoundRobin">
                        <membershipHandler
                                class="org.apache.synapse.core.axis2.Axis2LoadBalanceMembershipHandler">
                            <property name="applicationDomain" value="apache.axis2.app.domain"/>
                        </membershipHandler>
                    </dynamicLoadbalance>
                </endpoint>
            </send>
            <drop/>
        </in>

        <out>
            <!-- Send the messages where they have been sent (i.e. implicit To EPR) -->
            <send/>
        </out>
    </sequence>

    <sequence name="errorHandler">
        <makefault response="true">
            <code xmlns:tns="http://www.w3.org/2003/05/soap-envelope" value="tns:Receiver"/>
            <reason value="COULDN'T SEND THE MESSAGE TO THE SERVER."/>
        </makefault>
        <send/>
    </sequence>

</definitions>

Objective: Demonstrate the simple dynamic load balancing among a set of nodes

Prerequisites:
Enable clustering and load balancing in the <Synapse installation directory>/ repository/conf/axis2.xml file. This can be done by setting the "enable" attribute of the "cluster" and "loadBalancer" elements. Also provide the IP address of you machine as the values of the "mcastBindAddress" and "localMemberHost" parameters.
Start Synapse with sample configuration 57. (i.e. synapse -sample 57)
Deploy the LoadbalanceFailoverService by switching to <Synapse installation directory>/samples/axis2Server/src/LoadbalanceFailoverService directory and running ant.
Enable clustering in the <Synapse installation directory>/samples/axis2Server/ repository/conf/axis2.xml file. This can be done by setting the "enable" attribute of the "cluster" element. Also provide the IP address of you machine as the values of the "mcastBindAddress" and "localMemberHost" parameters. Make sure that the "applicationDomain" of the membershipHandler is the same as the domain name specified in the axis2.xml files of the Axis2 servers. Then Start three instances of sample Axis2 server on HTTP ports 9001, 9002 and 9003 and give some unique names to each server.

Example commands to run sample Axis2 servers from the <Synapse installation directory>/samples/axis2Server directory in Linux are listed below:

./axis2server.sh -http 9001 -https 9005 -name MyServer1
./axis2server.sh -http 9002 -https 9006 -name MyServer2
./axis2server.sh -http 9003 -https 9007 -name MyServer3

Now we are done with setting up the environment for load balance sample. Start the load balance and failover client using the following command:

ant loadbalancefailover -Di=100

This client sends 100 requests to the LoadbalanceFailoverService through Synapse. Synapse will distribute the load among the three nodes mentioned in the configuration in a round-robin manner. LoadbalanceFailoverService appends the name of the server to the response, so that client can determine which server has processed the message. If you examine the console output of the client, you can see that requests are processed by three servers as follows:

[java] Request: 1 ==> Response from server: MyServer1
[java] Request: 2 ==> Response from server: MyServer2
[java] Request: 3 ==> Response from server: MyServer3
[java] Request: 4 ==> Response from server: MyServer1
[java] Request: 5 ==> Response from server: MyServer2
[java] Request: 6 ==> Response from server: MyServer3
[java] Request: 7 ==> Response from server: MyServer1
...

Now run the client without the -Di=100 parameter, i.e. ant loadbalancefailover, to send infinite requests. While running the client shutdown the server named MyServer1. You can observe that requests are only distributed among MyServer2 and MyServer3 after shutting down MyServer1. Console output before and after shutting down MyServer1 is listed below (MyServer1 was shutdown after request 63):

...
[java] Request: 61 ==> Response from server: MyServer1
[java] Request: 62 ==> Response from server: MyServer2
[java] Request: 63 ==> Response from server: MyServer3
[java] Request: 64 ==> Response from server: MyServer2
[java] Request: 65 ==> Response from server: MyServer3
[java] Request: 66 ==> Response from server: MyServer2
[java] Request: 67 ==> Response from server: MyServer3
...

Now restart MyServer1. You can observe that requests will be again sent to all three servers.

<definitions xmlns="http://ws.apache.org/ns/synapse"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">

    <sequence name="main" onError="errorHandler">
        <in>
            <send>
                <endpoint>
                    <loadbalance failover="true">
                        <member hostName="127.0.0.1" httpPort="9001" httpsPort="9005"/>
                        <member hostName="127.0.0.1" httpPort="9002" httpsPort="9006"/>
                        <member hostName="127.0.0.1" httpPort="9003" httpsPort="9007"/>
                    </loadbalance>
                </endpoint>
            </send>
            <drop/>
        </in>

        <out>
            <!-- Send the messages where they have been sent (i.e. implicit To EPR) -->
            <send/>
        </out>
    </sequence>

    <sequence name="errorHandler">
        <makefault response="true">
            <code xmlns:tns="http://www.w3.org/2003/05/soap-envelope" value="tns:Receiver"/>
            <reason value="COULDN'T SEND THE MESSAGE TO THE SERVER."/>
        </makefault>
        <send/>
    </sequence>

</definitions>

Objective: Demonstrate the simple static load balancing among a set of nodes

Prerequisites:
Start Synapse with sample configuration 58. (i.e. synapse -sample 58)
Deploy the LoadbalanceFailoverService by switching to <Synapse installation directory>/samples/axis2Server/src/LoadbalanceFailoverService directory and running ant.
Start three instances of sample Axis2 server on HTTP ports 9001, 9002 and 9003 and give some unique names to each server.

Example commands to run sample Axis2 servers from the <Synapse installation directory>/samples/axis2Server directory in Linux are listed below:

./axis2server.sh -http 9001 -https 9005 -name MyServer1
./axis2server.sh -http 9002 -https 9006 -name MyServer2
./axis2server.sh -http 9003 -https 9007 -name MyServer3

Now we are done with setting up the environment for load balance sample. Start the load balance and failover client using the following command:

ant loadbalancefailover -Di=100

This client sends 100 requests to the LoadbalanceFailoverService through Synapse. Synapse will distribute the load among the three nodes mentioned in the configuration in a round-robin manner. LoadbalanceFailoverService appends the name of the server to the response, so that client can determine which server has processed the message. If you examine the console output of the client, you can see that requests are processed by three servers as follows:

[java] Request: 1 ==> Response from server: MyServer1
[java] Request: 2 ==> Response from server: MyServer2
[java] Request: 3 ==> Response from server: MyServer3
[java] Request: 4 ==> Response from server: MyServer1
[java] Request: 5 ==> Response from server: MyServer2
[java] Request: 6 ==> Response from server: MyServer3
[java] Request: 7 ==> Response from server: MyServer1
...

Now run the client without the -Di=100 parameter, i.e. ant loadbalancefailover, to send infinite requests. While running the client shutdown the server named MyServer1. You can observe that requests are only distributed among MyServer2 and MyServer3 after shutting down MyServer1. Console output before and after shutting down MyServer1 is listed below (MyServer1 was shutdown after request 63):

...
[java] Request: 61 ==> Response from server: MyServer1
[java] Request: 62 ==> Response from server: MyServer2
[java] Request: 63 ==> Response from server: MyServer3
[java] Request: 64 ==> Response from server: MyServer2
[java] Request: 65 ==> Response from server: MyServer3
[java] Request: 66 ==> Response from server: MyServer2
[java] Request: 67 ==> Response from server: MyServer3
...

Now restart MyServer1. You can observe that requests will be again sent to all three servers.

Quality of Service addition or deduction samples in message mediation

<definitions xmlns="http://ws.apache.org/ns/synapse"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">

    <localEntry key="sec_policy" src="file:repository/conf/sample/resources/policy/policy_3.xml"/>

    <sequence name="main">
        <in>
            <send>
                <endpoint name="secure">
                    <address uri="http://localhost:9000/services/SecureStockQuoteService">
                        <enableSec policy="sec_policy"/>
                    </address>
                </endpoint>
            </send>
        </in>
        <out>
            <send/>
        </out>
    </sequence>

</definitions>

Objective: Connecting to endpoints with WS-Security for outgoing messages

Prerequisites:
You may also need to download and install the unlimited strength policy files for your JDK before using Apache Rampart (e.g. see http://java.sun.com/javase/downloads/index_jdk5.jsp)
Start the Synapse configuration numbered 100: i.e. synapse -sample 100
Start the Axis2 server and deploy the SecureStockQuoteService if not already done

Use the stock quote client to send a request without WS-Security. Synapse is configured to enable WS-Security as per the policy specified by 'policy_3.xml' for the outgoing messages to the SecureStockQuoteService endpoint hosted on the Axis2 instance. The debug log messages on Synapse shows the encrypted message flowing to the service and the encrypted response being received by Synapse. The wsse:Security header is then removed from the decrypted message and the response is delivered back to the client, as expected. You may execute the client as follows:

ant stockquote -Dtrpurl=http://localhost:8280/

The message sent by Synapse to the secure service can be seen as follows, when TCPMon is used.

POST http://localhost:9001/services/SecureStockQuoteService HTTP/1.1
Host: 127.0.0.1
SOAPAction: urn:getQuote
Content-Type: text/xml; charset=UTF-8
Transfer-Encoding: chunked
Connection: Keep-Alive
User-Agent: Synapse-HttpComponents-NIO

800
<?xml version='1.0' encoding='UTF-8'?>
   <soapenv:Envelope xmlns:xenc="http://www.w3.org/2001/04/xmlenc#" xmlns:wsa="http://www.w3.org/2005/08/addressing" ..>
      <soapenv:Header>
         <wsse:Security ..>
            <wsu:Timestamp ..>
               ...
            </wsu:Timestamp>
            <xenc:EncryptedKey..>
               ...
            </xenc:EncryptedKey>
            <wsse:BinarySecurityToken ...>
               <ds:SignedInfo>
               ...
               </ds:SignedInfo>
               <ds:SignatureValue>
               ...
               </ds:SignatureValue>
               <ds:KeyInfo Id="KeyId-29551621">
                  ...
               </ds:KeyInfo>
            </ds:Signature>
         </wsse:Security>
         <wsa:To>http://localhost:9001/services/SecureStockQuoteService</wsa:To>
         <wsa:MessageID>urn:uuid:1C4CE88B8A1A9C09D91177500753443</wsa:MessageID>
         <wsa:Action>urn:getQuote</wsa:Action>
      </soapenv:Header>
      <soapenv:Body xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="Id-3789605">
         <xenc:EncryptedData Id="EncDataId-3789605" Type="http://www.w3.org/2001/04/xmlenc#Content">
            <xenc:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#aes256-cbc" />
            <xenc:CipherData>
                <xenc:CipherValue>Layg0xQcnH....6UKm5nKU6Qqr</xenc:CipherValue>
            </xenc:CipherData>
         </xenc:EncryptedData>
      </soapenv:Body>
   </soapenv:Envelope>0
<definitions xmlns="http://ws.apache.org/ns/synapse"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">

    <sequence name="main">
        <in>
            <RMSequence single="true" version="1.0"/>
            <send>
                <endpoint name="reliable">
                    <address uri="http://localhost:9000/services/ReliableStockQuoteService">
                        <enableRM/>
                        <enableAddressing/>
                    </address>
                </endpoint>
            </send>
        </in>
        <out>
            <send/>
        </out>
    </sequence>

</definitions>
Objective: Demonstrate the message exchange between Synapse and the server using WS-ReliableMessaging (WS-RM) - 1.0

Prerequisites:
Deploy the ReliableStockQuoteService in the sample Axis2 server by switching to the samples/axis2Server/src/ReliableStockQuoteService directory and running the command 'ant'.
Start the sample Axis2 server on port 9000.
Start Synapse with the sample configuration 101 (i.e. synapse -sample 101).

In the above configuration, WS-RM is engaged to the endpoint using the <enableRM/> tag. It is possible to engage WS-RM to both Address and WSDL endpoints using this tag. In addition to the RM enabled endpoint, RMSequence mediator is specified before the send mediator. This mediator is used to specify the set of messages to be sent using a single RM sequence. In this sample it is specified as single message per sequence. It also specifies the version of the WS-RM to be used. Refer to the Synapse configuration language documentation for more information about the RMSequence mediator. RM related SOAP headers are removed form the message in the out mediator as WS-RM message exchange takes place only between the Synapse and the server. Now run the sample client using the following command.

ant stockquote -Dsymbol=IBM -Dmode=quote -Daddurl=http://localhost:8280

You can observe the client output displaying the quote price for IBM as follows:

[java] Standard :: Stock price = $189.2521262517493

There is no difference to be observed between the normal message exchange and WS-RM enabled message exchange as far as client and server outputs are considered. But if you look at the wire level messages, you would observe additional WS-RM messages and WS-RM elements. Synapse, the initiator of the RM sequence, first try to create a sequence by sending a message with CreateSequence element.

...
<soapenv:Body>
   <wsrm:CreateSequence xmlns:wsrm="http://schemas.xmlsoap.org/ws/2005/02/rm">
      <wsrm:AcksTo>
         <wsa:Address>http://www.w3.org/2005/08/addressing/anonymous</wsa:Address>
      </wsrm:AcksTo>
      <wsrm:Offer>
         <wsrm:Identifier>urn:uuid:546F6F33FB7D8BBE351179807372769</wsrm:Identifier>
      </wsrm:Offer>
   </wsrm:CreateSequence>
</soapenv:Body>
...

Sample Axis2 server responds to CreateSequence request with the following message:

...
<soapenv:Body>
   <wsrm:CreateSequenceResponse xmlns:wsrm="http://schemas.xmlsoap.org/ws/2005/02/rm">
      <wsrm:Identifier>urn:uuid:879853A6871A66641C1179807373270</wsrm:Identifier>
      <wsrm:Accept>
         <wsrm:AcksTo>
            <wsa:Address>http://localhost:9000/services/ReliableStockQuoteService</wsa:Address>
         </wsrm:AcksTo>
      </wsrm:Accept>
   </wsrm:CreateSequenceResponse>
</soapenv:Body>
...

Once the sequence is established, Synapse sends the request to the server with the pre-negotiated sequence ID.

<soapenv:Envelope xmlns:wsa="http://www.w3.org/2005/08/addressing"
                  xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
    <soapenv:Header>
        <wsa:To>http://localhost:9000/services/ReliableStockQuoteService</wsa:To>
        <wsa:MessageID>urn:uuid:DB9A5257B637DDA38B1179807372560712002-1515891720</wsa:MessageID>
        <wsa:Action>urn:getQuote</wsa:Action>
        <wsrm:Sequence xmlns:wsrm="http://schemas.xmlsoap.org/ws/2005/02/rm"
                       soapenv:mustUnderstand="1">
            <wsrm:Identifier>urn:uuid:879853A6871A66641C1179807373270</wsrm:Identifier>
            <wsrm:MessageNumber>1</wsrm:MessageNumber>
            <wsrm:LastMessage/>
        </wsrm:Sequence>
    </soapenv:Header>
    <soapenv:Body>
        <m0:getQuote xmlns:m0="http://services.samples/xsd">
            <m0:request>
                <m0:symbol>IBM</m0:symbol>
            </m0:request>
        </m0:getQuote>
    </soapenv:Body>
</soapenv:Envelope>

Synapse keeps on sending above message till the server responds with a valid response message with 200 OK HTTP header. If the server is not ready with a response, it will respond with 202 Accepted HTTP header for all requests. Once the server is ready with a response it will send the response message with sequence ID as follows.

<soapenv:Envelope xmlns:wsa="http://www.w3.org/2005/08/addressing"
                  xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
    <soapenv:Header>
        <wsa:MessageID>urn:uuid:879853A6871A66641C1179807373804</wsa:MessageID>
        <wsa:Action>http://services.samples/ReliableStockQuoteServicePortType/getQuoteResponse
        </wsa:Action>
        <wsa:RelatesTo>urn:uuid:DB9A5257B637DDA38B1179807372560712002-1515891720</wsa:RelatesTo>
        <wsrm:Sequence xmlns:wsrm="http://schemas.xmlsoap.org/ws/2005/02/rm"
                       soapenv:mustUnderstand="1">
            <wsrm:Identifier>urn:uuid:546F6F33FB7D8BBE351179807372769</wsrm:Identifier>
            <wsrm:MessageNumber>1</wsrm:MessageNumber>
            <wsrm:LastMessage/>
        </wsrm:Sequence>
        <wsrm:SequenceAcknowledgement xmlns:wsrm="http://schemas.xmlsoap.org/ws/2005/02/rm"
                                      soapenv:mustUnderstand="1">
            <wsrm:Identifier>urn:uuid:879853A6871A66641C1179807373270</wsrm:Identifier>
            <wsrm:AcknowledgementRange Lower="1" Upper="1"/>
        </wsrm:SequenceAcknowledgement>
    </soapenv:Header>
    <soapenv:Body>
        <ns:getQuoteResponse xmlns:ns="http://services.samples/xsd">
...

Now both Synapse and the server are done with the actual message exchange. Then Synapse sends a request to terminate the sequence as follows:

<soapenv:Envelope xmlns:wsa="http://www.w3.org/2005/08/addressing"
                  xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
    <soapenv:Header>
        <wsa:To>http://localhost:9000/services/ReliableStockQuoteService</wsa:To>
        <wsa:MessageID>urn:uuid:546F6F33FB7D8BBE351179807379591</wsa:MessageID>
        <wsa:Action>http://schemas.xmlsoap.org/ws/2005/02/rm/TerminateSequence</wsa:Action>
        <wsrm:SequenceAcknowledgement xmlns:wsrm="http://schemas.xmlsoap.org/ws/2005/02/rm"
                                      soapenv:mustUnderstand="1">
            <wsrm:Identifier>urn:uuid:546F6F33FB7D8BBE351179807372769</wsrm:Identifier>
            <wsrm:AcknowledgementRange Lower="1" Upper="1"/>
        </wsrm:SequenceAcknowledgement>
    </soapenv:Header>
    <soapenv:Body>
        <wsrm:TerminateSequence xmlns:wsrm="http://schemas.xmlsoap.org/ws/2005/02/rm">
            <wsrm:Identifier>urn:uuid:879853A6871A66641C1179807373270</wsrm:Identifier>
        </wsrm:TerminateSequence>
    </soapenv:Body>
</soapenv:Envelope>

Server responds to the sequence termination message, accepting to terminate the sequence as follows.

<soapenv:Envelope xmlns:wsa="http://www.w3.org/2005/08/addressing"
                  xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
    <soapenv:Header>
        <wsa:ReplyTo>
            <wsa:Address>http://localhost:9000/services/ReliableStockQuoteService</wsa:Address>
        </wsa:ReplyTo>
        <wsa:MessageID>urn:uuid:879853A6871A66641C1179807380190</wsa:MessageID>
        <wsa:Action>http://schemas.xmlsoap.org/ws/2005/02/rm/TerminateSequence</wsa:Action>
    </soapenv:Header>
    <soapenv:Body>
        <wsrm:TerminateSequence xmlns:wsrm="http://schemas.xmlsoap.org/ws/2005/02/rm">
            <wsrm:Identifier>urn:uuid:546F6F33FB7D8BBE351179807372769</wsrm:Identifier>
        </wsrm:TerminateSequence>
    </soapenv:Body>
</soapenv:Envelope>

Note that although each of above messages are separate SOAP messages, in most cases they will be exchanged in a single socket connection as HTTP Keep-Alive header is used.

<definitions xmlns="http://ws.apache.org/ns/synapse"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">

    <sequence name="main">
        <in>
            <RMSequence single="true" version="1.1"/>
            <send>
                <endpoint name="reliable">
                    <address uri="http://localhost:9000/services/ReliableStockQuoteService">
                        <enableRM/>
                        <enableAddressing/>
                    </address>
                </endpoint>
            </send>
        </in>
        <out>
            <send/>
        </out>
    </sequence>

</definitions>
Objective: Demonstrate the message exchange between Synapse and the server using WS-ReliableMessaging (WS-RM) - 1.1

This sample is as same as the previous one except it uses WS-RM 1.1 version where as the previous sample is using the RM version 1.0

Synapse Proxy service samples

<definitions xmlns="http://ws.apache.org/ns/synapse"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">

    <proxy name="StockQuoteProxy">
        <target>
            <endpoint>
                <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
            </endpoint>
            <outSequence>
                <send/>
            </outSequence>
        </target>
        <publishWSDL uri="file:repository/conf/sample/resources/proxy/sample_proxy_1.wsdl"/>
    </proxy>

</definitions>

Objective: Introduction to Synapse proxy services

Prerequisites:
Start the Synapse configuration numbered 150: i.e. synapse -sample 150
Start the Axis2 server and deploy the SimpleStockQuoteService if not already done

Once Synapse starts, you could go to http://localhost:8280/services/StockQuoteProxy?wsdl and view the WSDL generated for the proxy service defined in the configuration. This WSDL is based on the source WSDL supplied in the proxy service definition, and is updated to reflect the proxy service EPR.

Execute the stock quote client by requesting for a stock quote on the proxy service as follows:

ant stockquote -Daddurl=http://localhost:8280/services/StockQuoteProxy

An 'inSequence' or 'endpoint' or both of these would decide how the message would be handled after the proxy service receives the message. In the above example, the request received is forwarded to the sample service hosted on Axis2. The 'outSequence' defines how the response is handled before it is sent back to the client. By default, a proxy service is exposed over all transports configured for Synapse, unless these are specifically mentioned through the 'transports' attribute.

<definitions xmlns="http://ws.apache.org/ns/synapse"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">

    <localEntry key="proxy_wsdl"
                src="file:repository/conf/sample/resources/proxy/sample_proxy_1.wsdl"/>

    <endpoint name="proxy_2_endpoint">
        <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
    </endpoint>

    <sequence name="proxy_1">
        <send>
            <endpoint>
                <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
            </endpoint>
        </send>
    </sequence>

    <sequence name="out">
        <send/>
    </sequence>

    <proxy name="StockQuoteProxy1">
        <target inSequence="proxy_1" outSequence="out"/>
        <    publishWSDL key="proxy_wsdl"/>
    <
    /proxy>

    <    proxy name="StockQuoteProxy2">
        <target endpoint="proxy_2_endpoint" outSequence="out"/>
        <publishWSDL key="proxy_wsdl"/>
    </proxy>

</definitions>

Objective: Using custom sequences and endpoints for message mediation with proxy services

Prerequisites:
Start the Synapse configuration numbered 151: i.e. synapse -sample 151
Start the Axis2 server and deploy the SimpleStockQuoteService if not already done

This configuration creates two proxy services. The first proxy service 'StockQuoteProxy1' uses the sequence named 'proxy_1' to process incoming messages and the sequence named "out" to process outgoing responses. The second proxy service 'StockQuoteProxy2' is set to directly forward messages that are received to the endpoint named 'proxy_2_endpoint' without any mediation.

You could send a stock quote request to each of these proxy services and receive the reply generated by the actual service hosted on the Axis2 server instance.

ant stockquote -Daddurl=http://localhost:8280/services/StockQuoteProxy1

ant stockquote -Daddurl=http://localhost:8280/services/StockQuoteProxy2
<definitions xmlns="http://ws.apache.org/ns/synapse"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">

    <proxy name="StockQuoteProxy" transports="https">
        <target>
            <endpoint>
                <address uri="http://localhost:9000/services/SimpleStockQuoteService" format="pox"/>
            </endpoint>
            <outSequence>
                <send/>
            </outSequence>
        </target>
        <publishWSDL uri="file:repository/conf/sample/resources/proxy/sample_proxy_1.wsdl"/>
    </proxy>

</definitions>

Objective: Switching transports and message format from SOAP to REST/POX

Prerequisites:
Start the Synapse configuration numbered 152: i.e. synapse -sample 152
Start the Axis2 server and deploy the SimpleStockQuoteService if not already done

This configuration demonstrates how a proxy service could be exposed on a subset of available transports, and how it could switch from one transport to another. This example exposes the created proxy service only on HTTPS, and thus if the user tries to access it over HTTP, would result in a fault.

ant stockquote -Dtrpurl=http://localhost:8280/services/StockQuoteProxy
...
     [java] org.apache.axis2.AxisFault: The service cannot be found for the endpoint reference (EPR) /soap/StockQuoteProxy

Accessing this over HTTPS (ant stockquote -Dtrpurl=https://localhost:8243/services/StockQuoteProxy) causes the proxy service to access the SimpleStockQuoteService on the sample Axis2 server using REST/POX. This could be seen if the message exchange was captured using TCPMon as follows. The REST/POX response is now transformed back into a SOAP message and returned to the client.

POST http://localhost:9000/services/SimpleStockQuoteService HTTP/1.1
Host: 127.0.0.1
SOAPAction: urn:getQuote
Content-Type: application/xml; charset=UTF-8;action="urn:getQuote";
Transfer-Encoding: chunked
Connection: Keep-Alive
User-Agent: Synapse-HttpComponents-NIO

75
<m0:getQuote xmlns:m0="http://services.samples/xsd">
   <m0:request>
      <m0:symbol>IBM</m0:symbol>
   </m0:request>
</m0:getQuote>
HTTP/1.1 200 OK
Content-Type: application/xml; charset=UTF-8;action="http://services.samples/SimpleStockQuoteServicePortType/getQuoteResponse";
Date: Tue, 24 Apr 2007 14:42:11 GMT
Server: Synapse-HttpComponents-NIO
Transfer-Encoding: chunked
Connection: Keep-Alive

2b3
<ns:getQuoteResponse xmlns:ns="http://services.samples/xsd">
   <ns:return>
      <ns:change>3.7730036841862384</ns:change>
      <ns:earnings>-9.950236235550818</ns:earnings>
      <ns:high>-80.23868444613285</ns:high>
      <ns:last>80.50750970812187</ns:last>
      <ns:lastTradeTimestamp>Tue Apr 24 20:42:11 LKT 2007</ns:lastTradeTimestamp>
      <ns:low>-79.67368355714606</ns:low>
      <ns:marketCap>4.502043663670823E7</ns:marketCap>
      <ns:name>IBM Company</ns:name>
      <ns:open>-80.02229531286982</ns:open>
      <ns:peRatio>25.089295161182022</ns:peRatio>
      <ns:percentageChange>4.28842665653824</ns:percentageChange>
      <ns:prevClose>87.98107059692451</ns:prevClose>
      <ns:symbol>IBM</ns:symbol>
      <ns:volume>19941</ns:volume>
   </ns:return></ns:getQuoteResponse>
<definitions xmlns="http://ws.apache.org/ns/synapse"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">

    <proxy name="StockQuoteProxy">
        <target>
            <inSequence>
                <property name="preserveProcessedHeaders" value="true"/>
                <send>
                    <endpoint>
                        <address uri="http://localhost:9000/services/SecureStockQuoteService"/>
                    </endpoint>
                </send>
            </inSequence>
            <outSequence>
                <send/>
            </outSequence>
        </target>
        <publishWSDL uri="file:repository/conf/sample/resources/proxy/sample_proxy_1.wsdl"/>
    </proxy>

</definitions>

Objective: Routing the messages arrived to a proxy service without processing the MustUnderstand headers (Security header)

Prerequisites:
You may also need to download and install the unlimited strength policy files for your JDK before using Apache Rampart (e.g. see http://java.sun.com/javase/downloads/index_jdk5.jsp)
Start the Synapse configuration numbered 153: i.e. synapse -sample 153
Start the Axis2 server and deploy the SecureStockQuoteService if not already done

The proxy service will receive secure messages with security headers which are MustUnderstand. But hence element 'engageSec' is not present in the proxy configuration Synapse will not engage that Apache Rampart on this proxy service. It is expected that an MustUnderstand failure exception on the AxisEngine would occur before the message arrives Synapse. But Synapse handles this message and gets it in by setting all the headers which are MustUnderstand and not processed to processed state. This will enable Synapse to route the messages without reading the Security headers (just routing the messages from client to service, both of which are secure). To execute the client, send a stock quote request to the proxy service, and sign and encrypt the request by specifying the client side security policy as follows:

ant stockquote -Dtrpurl=http://localhost:8280/services/StockQuoteProxy -Dpolicy=./../../repository/conf/sample/resources/policy/client_policy_3.xml

By following through the debug logs or TCPMon output, you could see that the request received by the proxy service was signed and encrypted. Also, looking up the WSDL of the proxy service by requesting the URL http://localhost:8280/services/StockQuoteProxy?wsdl reveals the security policy attachments are not there and security is not engaged. When sending the message to the backend service, you could verify that the security headers were there as in the original message to Synapse from client, and that the response received does use WS-Security, and forwarded back to the client without any modification. You should note that this wont be a security hole because the message inside Synapse is signed and encrypted and can only be forwarded to a secure service to be useful.

<definitions xmlns="http://ws.apache.org/ns/synapse"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">

    <proxy name="LBProxy" transports="http" startOnLoad="true">
        <target faultSequence="errorHandler">
            <inSequence>
                <send>
                    <endpoint>
                        <session type="simpleClientSession"/>
                        <loadbalance algorithm="org.apache.synapse.endpoints.algorithms.RoundRobin">
                            <endpoint>
                                <address uri="http://localhost:9001/services/LBService1">
                                    <enableAddressing/>
                                    <suspendDurationOnFailure>20</suspendDurationOnFailure>
                                </address>
                            </endpoint>
                            <endpoint>
                                <address uri="http://localhost:9002/services/LBService1">
                                    <enableAddressing/>
                                    <suspendDurationOnFailure>20</suspendDurationOnFailure>
                                </address>
                            </endpoint>
                            <endpoint>
                                <address uri="http://localhost:9003/services/LBService1">
                                    <enableAddressing/>
                                    <suspendDurationOnFailure>20</suspendDurationOnFailure>
                                </address>
                            </endpoint>
                        </loadbalance>
                    </endpoint>
                </send>
                <drop/>
            </inSequence>
            <outSequence>
                <send/>
            </outSequence>
        </target>
        <publishWSDL uri="file:repository/conf/sample/resources/proxy/sample_proxy_2.wsdl"/>
    </proxy>

    <sequence name="errorHandler">
        <makefault response="true">
            <code xmlns:tns="http://www.w3.org/2003/05/soap-envelope" value="tns:Receiver"/>
            <reason value="COULDN'T SEND THE MESSAGE TO THE SERVER."/>
        </makefault>
        <send/>
    </sequence>

</definitions>

Objective: Load Balancing with Proxy Services

Prerequisites:
Sample setup is same as LoadBalance endpoints (#53 to #54)
Start the Synapse configuration numbered 154: i.e. synapse -sample 154
Start the Axis2 server and deploy the SecureStockQuoteService if not already done

Run the client with

  ant loadbalancefailover -Dmode=session -Dtrpurl=http://localhost:8280/services/LBProxy 

Functionality is similar to the sample #54.

<definitions xmlns="http://ws.apache.org/ns/synapse"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">

    <proxy name="StockQuoteProxy">
        <target>
            <endpoint>
                <address uri="http://localhost:9000/services/SimpleStockQuoteService">
                    <enableAddressing separateListener="true"/>
                </address>
            </endpoint>
            <outSequence>
                <send/>
            </outSequence>
        </target>
        <publishWSDL uri="file:repository/conf/sample/resources/proxy/sample_proxy_1.wsdl"/>
    </proxy>

</definitions>

Objective: Demonstrate the dual channel invocation with Synapse proxy services

Prerequisites:
Start the Synapse configuration numbered 155: i.e. synapse -sample 155
Start the Axis2 server and deploy the SimpleStockQuoteService if not already done

This sample will show the action of the dual channel invocation within client and Synapse as well as within Synapse and the actual server. Note that if you want to enable dual channel invocation you need to set the separateListener attribute to true of the enableAddressing element of the endpoint.

Execute the stock quote client by requesting for a stock quote on a dual channel from the proxy service as follows:

ant stockquote -Daddurl=http://localhost:8280/services/StockQuoteProxy -Dmode=dualquote

In the above example, the request received is forwarded to the sample service hosted on Axis2 and the endpoint specifies to enable addressing and do the invocation over a dual channel. If you observe this message flow by using a TCPmon, you could see that on the channel you send the request to Synapse the response has been written as an HTTP 202 Accepted, where as the real response from Synapse will come over a different channel which cannot be obsesrved unless you use tcpdump to dump all the TCP level messages.

At the same time you can observe the behaviour of the invocation between Synapse and the actual Axis2 service, where you can see a 202 Accepted message being delivered to Synapse as the response to the request. The actual response will be delivered to Synapse over a different channel.

QoS addition and deduction for service mediation (proxy) samples

<definitions xmlns="http://ws.apache.org/ns/synapse"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">

    <localEntry key="sec_policy" src="file:repository/conf/sample/resources/policy/policy_3.xml"/>

    <proxy name="StockQuoteProxy">
        <target>
            <inSequence>
                <send>
                    <endpoint>
                        <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
                    </endpoint>
                </send>
            </inSequence>
            <outSequence>
                <send/>
            </outSequence>
        </target>
        <publishWSDL uri="file:repository/conf/sample/resources/proxy/sample_proxy_1.wsdl"/>
        <enableSec/>
        <policy key="sec_policy"/>
    </proxy>

</definitions>

Objective: Using WS-Security signing and encryption with proxy services through WS-Policy

Prerequisites:
You may also need to download and install the unlimited strength policy files for your JDK before using Apache Rampart (e.g. see http://java.sun.com/javase/downloads/index_jdk5.jsp)

Start the Synapse configuration numbered 200: i.e. synapse -sample 200
Start the Axis2 server and deploy the SimpleStockQuoteService if not already done

The proxy service expects to receive a signed and encrypted message as specified by the security policy. Please see Apache Rampart and Axis2 documentation on the format of the policy file. The element 'engageSec' specifies that Apache Rampart should be engaged on this proxy service. Hence if Rampart rejects any request messages that does not conform to the specified policy, those messages will never reach the 'inSequence' to be processed. Since the proxy service is forwarding the received request to the simple stock quote service that does not use WS-Security, we are instructing Synapse to remove the wsse:Security header from the outgoing message. To execute the client, send a stock quote request to the proxy service, and sign and encrypt the request by specifying the client side security policy as follows:

ant stockquote -Dtrpurl=http://localhost:8280/services/StockQuoteProxy -Dpolicy=./../../repository/conf/sample/resources/policy/client_policy_3.xml

By following through the debug logs or TCPMon output, you could see that the request received by the proxy service was signed and encrypted. Also, looking up the WSDL of the proxy service by requesting the URLhttp://localhost:8280/services/StockQuoteProxy?wsdl reveals the security policy attachment to the supplied base WSDL. When sending the message to the backend service, you could verify that the security headers were removed, and that the response received does not use WS-Security, but that the response being forwarded back to the client is signed and encrypted as expected by the client.

<definitions xmlns="http://ws.apache.org/ns/synapse"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">

    <proxy name="StockQuoteProxy">
        <target>
            <inSequence>
                <send>
                    <endpoint>
                        <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
                    </endpoint>
                </send>
            </inSequence>
            <outSequence>
                <send/>
            </outSequence>
        </target>
        <publishWSDL uri="file:repository/conf/sample/resources/proxy/sample_proxy_1.wsdl"/>
        <enableRM/>
    </proxy>

</definitions>
Objective: Demonstrate the reliable message exchange between the client and Synapse using WS-ReliableMessaging (WS-RM)

Prerequisites:
Deploy the SimpleStockQuoteService in the sample Axis2 server and start it on port 9000.
Start Synapse with the sample configuration number 201 (i.e. synapse -sample 201).

In the above configuration, a proxy service is created with WS-RM enabled using the <enableRM/> tag. Therefore, this proxy service is capable of communicating with a WS-RM client. It also removes the WS-RM headers in the In Sequence before the message is sent to the backend server. This is required as the reliable messaging is applicable only between the client and Synapse. Now start the client with WS-RM as follows:

ant stockquote -Dsymbol=IBM -Dmode=quote -Daddurl=http://localhost:8280/services/StockQuoteProxy -Dwsrm=true

In this case, client sends a WS-RM enabled request to Synapse where Synapse sends normal request to the server. This can be observed by examining the wire level messages between the client and Synapse. These messages would be similar to the wire level messages shown in sample 101. Each message would perform a similar function to the messages discussed in sample 53.

Transport samples and switching transports

<definitions xmlns="http://ws.apache.org/ns/synapse"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">

    <proxy name="StockQuoteProxy" transports="jms">
        <target>
            <inSequence>
                <property action="set" name="OUT_ONLY" value="true"/>
            </inSequence>
            <endpoint>
                <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
            </endpoint>
            <outSequence>
                <send/>
            </outSequence>
        </target>
        <publishWSDL uri="file:repository/conf/sample/resources/proxy/sample_proxy_1.wsdl"/>
        <parameter name="transport.jms.ContentType">
            <rules>
                <jmsProperty>contentType</jmsProperty>
                <default>application/xml</default>
            </rules>
        </parameter>
    </proxy>

</definitions>

Objective: Introduction to switching transports with proxy services

Prerequisites:
Start the Axis2 server with the SimpleStockQuoteService deployed
Download, install and start a JMS server, and configure Synapse to listen on JMS (refer notes below)
Start the Synapse configuration numbered 250: i.e. synapse -sample 250

For this example we will use Apache ActiveMQ as the JMS provider. Simply download the binary distribution, extract it and launch the startup script to start the JMS broker.

Now you have to enable the JMS transport receiver of Synapse. Start by deploying the ActiveMQ client libraries into the Synapse runtime. Simply copy the following jars from the ActiveMQ distribution into SYNAPSE_HOME/lib directory:

  • activemq-core.jar
  • geronimo-j2ee_management.jar
  • geronimo-jms.jar

Now you need to add some entries into the axis2.xml file. For a default ActiveMQ v5.x installation, you may uncomment the Axis2 transport listener configuration found at repository/conf/axis2.xml as

<transportReceiver name="jms" class="org.apache.axis2.transport.jms.JMSListener"> ...

Once you start the Synapse configuration and request for the WSDL of the proxy service (http://localhost:8280/services/StockQuoteProxy?wsdl) you will notice that its exposed only on the JMS transport. This is because the configuration specified this requirement in the proxy service definition.

Now lets send a stock quote request on JMS, using the dumb stock quote client as follows:

ant jmsclient -Djms_type=pox -Djms_dest=dynamicQueues/StockQuoteProxy -Djms_payload=MSFT

On the Synapse debug log you will notice that the JMS listener received the request message as:

[JMSWorker-1] DEBUG ProxyServiceMessageReceiver -Proxy Service StockQuoteProxy received a new message...

Now if you examine the console running the sample Axis2 server, you will see a message indicating that the server has accepted an order as follows:

Accepted order for : 16517 stocks of MSFT at $ 169.14622538721846

In this sample, the client sends the request message to the proxy service exposed over JMS in Synsape. Synapse forwards this message to the HTTP EPR of the simple stock quote service hosted on the sample Axis2 server. Note that the operation is out-only and no response is sent back to the client. The transport.jms.ContentType property is necessary to allow the JMS transport to determine the content type of incoming messages. With the given configuration it will first try to read the content type from the 'contentType' message property and fall back to 'application/xml' (i.e. POX) if this property is not set. Note that the JMS client used in this example doesn't send any content type information.

Note: It is possible to instruct a JMS proxy service to listen to an already existing destination without creating a new one. To do this, use the parameter elements on the proxy service definition to specify the destination and connection factory etc.

e.g.

<parameter name="transport.jms.Destination">dynamicTopics/something.TestTopic</parameter>
<definitions xmlns="http://ws.apache.org/ns/synapse"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">

    <proxy name="StockQuoteProxy" transports="http">
        <target>
            <endpoint>
                <address
                        uri="jms:/SimpleStockQuoteService?transport.jms.ConnectionFactoryJNDIName=QueueConnectionFactory&java.naming.factory.initial=org.apache.activemq.jndi.ActiveMQInitialContextFactory&java.naming.provider.url=tcp://localhost:61616&transport.jms.DestinationType=queue"/>
            </endpoint>
            <inSequence>
                <property action="set" name="OUT_ONLY" value="true"/>
            </inSequence>
            <outSequence>
                <send/>
            </outSequence>
        </target>
        <publishWSDL uri="file:repository/conf/sample/resources/proxy/sample_proxy_1.wsdl"/>
    </proxy>

</definitions>

Objective: Demonstrate switching from HTTP to JMS

Prerequisites:
Download, install and start a JMS server
Configure sample Axis2 server for JMS (refer notes below)
Start the Axis2 server and deploy the SimpleStockQuoteService (see below)
Configure the Synase JMS transport (refer notes above - sample 250)
Start the Synapse configuration numbered 251: i.e. synapse -sample 251

To switch from HTTP to JMS, edit the samples/axis2Server/repository/conf/axis2.xml for the sample Axis2 server and enable JMS (refer notes above), and restart the server. Now you can see that the simple stock quote service is available in both JMS and HTTP in the sample Axis2 server. To see this, point your browser to the WSDL of the service at http://localhost:9000/services/SimpleStockQuoteService?wsdl. JMS URL for the service is mentioned as below:

jms:/SimpleStockQuoteService?transport.jms.ConnectionFactoryJNDIName=
QueueConnectionFactory&java.naming.factory.initial=org.apache.activemq.jndi.ActiveMQInitialContextFactory&
java.naming.provider.url=tcp://localhost:61616

You may also notice that the simple stock quote proxy service exposed in Synapse is now available only in HTTP as we have specified transport for that service as HTTP. To observe this, access the WSDL of stock quote proxy service at http://localhost:8280/services/StockQuoteProxy?wsdl.

This Synapse configuration creates a proxy service over HTTP and forwards received messages to the above EPR using JMS, and sends back the response to the client over HTTP once the simple stock quote service responds with the stock quote reply over JMS to the Synapse server. To test this, send a place order request to Synapse using HTTP as follows:

ant stockquote -Daddurl=http://localhost:8280/services/StockQuoteProxy -Dmode=placeorder -Dsymbol=MSFT

The sample Axis2 server console will print a message indicating that it has accepted the order as follows:

Accepted order for : 18406 stocks of MSFT at $ 83.58806051152119
<definitions xmlns="http://ws.apache.org/ns/synapse"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">

    <sequence name="text_proxy">
        <log level="full"/>
        <header name="Action" value="urn:placeOrder"/>
        <script language="js">
            var args = mc.getPayloadXML().toString().split(" ");
            mc.setPayloadXML(
            <placeOrder xmlns="http://services.samples">
            <order xmlns="http://services.samples/xsd">
            <price>{args[0]}</price>
            <quantity>{args[1]}</quantity>
            <symbol>{args[2]}</symbol>
            </order>
            </placeOrder>);
        </script>
        <property action="set" name="OUT_ONLY" value="true"/>
        <log level="full"/>
        <send>
            <endpoint>
                <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
            </endpoint>
        </send>
    </sequence>

    <sequence name="mtom_proxy">
        <log level="full"/>
        <property action="set" name="OUT_ONLY" value="true"/>
        <header name="Action" value="urn:oneWayUploadUsingMTOM"/>
        <send>
            <endpoint>
                <address uri="http://localhost:9000/services/MTOMSwASampleService" optimize="mtom"/>
            </endpoint>
        </send>
    </sequence>

    <sequence name="pox_proxy">
        <property action="set" name="OUT_ONLY" value="true"/>
        <header name="Action" value="urn:placeOrder"/>
        <send>
            <endpoint>
                <address uri="http://localhost:9000/services/SimpleStockQuoteService"
                         format="soap11"/>
            </endpoint>
        </send>
    </sequence>

    <sequence name="out">
        <send/>
    </sequence>

    <proxy name="JMSFileUploadProxy" transports="jms">
        <target inSequence="mtom_proxy" outSequence="out"/>
        <parameter name="transport.jms.ContentType">
            <rules>
                <bytesMessage>application/octet-stream</bytesMessage>
            </rules>
        </parameter>
        <parameter name="Wrapper">{http://services.samples/xsd}element</parameter>
    </proxy>

    <proxy name="JMSTextProxy" transports="jms">
        <target inSequence="text_proxy" outSequence="out"/>
        <parameter name="transport.jms.ContentType">
            <rules>
                <textMessage>text/plain</textMessage>
            </rules>
        </parameter>
        <parameter name="Wrapper">{http://services.samples/xsd}text</parameter>
    </proxy>

    <proxy name="JMSPoxProxy" transports="jms">
        <target inSequence="pox_proxy" outSequence="out"/>
        <parameter name="transport.jms.ContentType">application/xml</parameter>
    </proxy>

</definitions>

Objective: Pure POX/Text and Binary JMS Proxy services - including MTOM

Prerequisites:
Configure JMS for Synapse (Refer notes)
Start the Synapse configuration numbered 252: i.e. synapse -sample 252
Start the Axis2 server and deploy the SimpleStockQuoteService and the MTOMSwASampleService if not already done

This configuration creates three JMS proxy services named JMSFileUploadProxy, JMSTextProxy and JMSPoxProxy exposed over JMS queues with the same names as the services. The first part of this example demonstrates the pure text message support with JMS, where a user sends a space separated text JMS message of the form "<price> <qty> <symbol>". Synapse converts this message into a SOAP message and sends this to the SimpleStockQuoteServices' placeOrder operation. Synapse uses the script mediator to transform the text message into a XML payload using the JavaScript support available to tokenize the string. The proxy service property named "Wrapper" defines a custom wrapper element QName, to be used when wrapping text/binary content into a SOAP envelope.

Execute JMS client as follows. This will post a pure text JMS message with the content defined (e.g. "12.33 1000 ACP") to the specified JMS destination - dynamicQueues/JMSTextProxy

ant jmsclient -Djms_type=text -Djms_payload="12.33 1000 ACP" -Djms_dest=dynamicQueues/JMSTextProxy

Following the logs, you could notice that Synapse received the JMS text message and transformed it into a SOAP payload as follows. Notice that the wrapper element "{http://services.samples/xsd}text" has been used to hold the text message content.

[jms-Worker-1] INFO LogMediator To: , WSAction: urn:mediate, SOAPAction: urn:mediate, MessageID: ID:orcus.veithen.net-50631-1225235276233-1:0:1:1:1, Direction: request,
Envelope:
<?xml version="1.0" encoding="utf-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
  <soapenv:Body>
    <axis2ns1:text xmlns:axis2ns1="http://services.samples/xsd">12.33 1000 ACP</axis2ns1:text>
  </soapenv:Body>
</soapenv:Envelope>

Now, you could see how the script mediator created a stock quote request by tokenizing the text as follows, and sent the message to the placeOrder operation of the SimpleStockQuoteService.

[jms-Worker-1] INFO LogMediator To: , WSAction: urn:placeOrder, SOAPAction: urn:placeOrder, MessageID: ID:orcus.veithen.net-50631-1225235276233-1:0:1:1:1, Direction: request,
Envelope:
<?xml version="1.0" encoding="utf-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
  <soapenv:Body>
    <placeOrder xmlns="http://services.samples">
      <order xmlns="http://services.samples/xsd">
        <price>12.33</price>
        <quantity>1000</quantity>
        <symbol>ACP</symbol>
      </order>
    </placeOrder>
  </soapenv:Body>
</soapenv:Envelope>

The sample Axis2 server would now accept the one-way message and issue the following message:

samples.services.SimpleStockQuoteService :: Accepted order for : 1000 stocks of ACP at $ 12.33

The next section of this example demonstrates how a pure binary JMS message could be received and processed through Synapse. The configuration creates a proxy service named 'JMSFileUploadProxy' that accepts binary messages and wraps them into a custom element '{http://services.samples/xsd}element'. The received message is then forwarded to the MTOMSwASampleService using the SOAP action 'urn:oneWayUploadUsingMTOM' and optimizing binary content using MTOM. To execute this sample, use the JMS client to publish a pure binary JMS message containing the file './../../repository/conf/sample/resources/mtom/asf-logo.gif' to the JMS destination 'dynamicQueues/JMSFileUploadProxy' as follows:

ant jmsclient -Djms_type=binary -Djms_dest=dynamicQueues/JMSFileUploadProxy \
              -Djms_payload=./../../repository/conf/sample/resources/mtom/asf-logo.gif

Examining the Synapse debug logs reveals that the binary content was received over JMS and wrapped with the specified element into a SOAP infoset as follows:

[jms-Worker-1] INFO LogMediator To: , WSAction: urn:mediate, SOAPAction: urn:mediate, MessageID: ID:orcus.veithen.net-50702-1225236039556-1:0:1:1:1, Direction: request,
Envelope:
<?xml version="1.0" encoding="utf-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
  <soapenv:Body>
    <axis2ns1:element xmlns:axis2ns1="http://services.samples/xsd">R0lGODlhgw...AAOw==</axis2ns1:element>
  </soapenv:Body>
</soapenv:Envelope>

Thereafter the message was sent as a MTOM optimized message as specified by the 'format=mtom' attribute of the endpoint, to the MTOMSwASampleService using the SOAP action 'urn:oneWayUploadUsingMTOM'. Once received by the sample service, it is saved into a temporary file and could be verified for correctness.

Wrote to file : ./../../work/temp/sampleServer/mtom-4417.gif

The final section of this example shows how a POX JMS message received by Synapse is sent to the SimpleStockQuoteService as a SOAP message. Use the JMS client as follows to create a POX (Plain Old XML) message with a stock quote request payload (without a SOAP envelope), and send it to the JMS destination 'dynamicQueues/JMSPoxProxy' as follows:

ant jmsclient -Djms_type=pox -Djms_dest=dynamicQueues/JMSPoxProxy -Djms_payload=MSFT

Synapse converts the POX message into a SOAP payload and sends to the SimpleStockQuoteService after setting the SOAP action as 'urn:placeOrder'. The sample Axis2 server displays a successful message on the receipt of the message as:

samples.services.SimpleStockQuoteService :: Accepted order for : 19211 stocks of MSFT at $ 172.39703010684752
<definitions xmlns="http://ws.apache.org/ns/synapse"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">

    <proxy name="JMStoHTTPStockQuoteProxy" transports="jms">
        <target>
            <inSequence>
                <property action="set" name="OUT_ONLY" value="true"/>
            </inSequence>
            <endpoint>
                <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
            </endpoint>
            <outSequence>
                <send/>
            </outSequence>
        </target>
        <publishWSDL uri="file:repository/conf/sample/resources/proxy/sample_proxy_1.wsdl"/>
    </proxy>

    <proxy name="OneWayProxy" transports="http">
        <target>
            <inSequence>
                <log level="full"/>
            </inSequence>
            <endpoint>
                <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
            </endpoint>
            <outSequence>
                <send/>
            </outSequence>
        </target>
        <publishWSDL uri="file:repository/conf/sample/resources/proxy/sample_proxy_1.wsdl"/>
    </proxy>

</definitions>

Objective: Demonstrate one-way message bridging from JMS to HTTP and replying with a HTTP 202 Accepted response

Prerequisites:
Start the Axis2 server and deploy the SimpleStockQuoteService if not already done
Start the Synapse configuration numbered 253: i.e. synapse -sample 253

This example invokes the one-way 'placeOrder' operation on the SimpleStockQuoteService using the Axis2 ServiceClient.fireAndForget() API at the client. To test this, use 'ant -Dmode=placeorder...' and you will notice the one-way JMS message flowing through Synapse into the sample Axis2 server instance over HTTP, and Axis2 acknowledging it with a HTTP 202 Accepted response.

ant stockquote -Dmode=placeorder -Dtrpurl="jms:/JMStoHTTPStockQuoteProxy?\
transport.jms.ConnectionFactoryJNDIName=QueueConnectionFactory\
&java.naming.factory.initial=org.apache.activemq.jndi.ActiveMQInitialContextFactory\
&java.naming.provider.url=tcp://localhost:61616\
&transport.jms.ContentTypeProperty=Content-Type&transport.jms.DestinationType=queue"
SimpleStockQuoteService :: Accepted order for : 7482 stocks of IBM at $ 169.27205579038733

The second example shows how Synapse could be made to respond with a HTTP 202 Accepted response to a request received. The proxy service simply logs the message received and acknowledges it. On the Synapse console you could see the logged message, and if TCPMon was used at the client, you would see the 202 Accepted response sent back to the client from Synapse

ant stockquote -Dmode=placeorder -Dtrpurl=http://localhost:8280/services/OneWayProxy
HTTP/1.1 202 Accepted
Content-Type: text/xml; charset=UTF-8
Host: 127.0.0.1
SOAPAction: "urn:placeOrder"
Date: Sun, 06 May 2007 17:20:19 GMT
Server: Synapse-HttpComponents-NIO
Transfer-Encoding: chunked

0
<definitions xmlns="http://ws.apache.org/ns/synapse"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">

    <proxy name="StockQuoteProxy" transports="vfs">
        <parameter name="transport.vfs.FileURI">file:///home/user/test/in</parameter> <!--CHANGE-->
        <parameter name="transport.vfs.ContentType">text/xml</parameter>
        <parameter name="transport.vfs.FileNamePattern">.*\.xml</parameter>
        <parameter name="transport.PollInterval">15</parameter>
        <parameter name="transport.vfs.MoveAfterProcess">file:///home/user/test/original</parameter> <!--CHANGE-->
        <parameter name="transport.vfs.MoveAfterFailure">file:///home/user/test/original</parameter> <!--CHANGE-->
        <parameter name="transport.vfs.ActionAfterProcess">MOVE</parameter>
        <parameter name="transport.vfs.ActionAfterFailure">MOVE</parameter>

        <target>
            <endpoint>
                <address format="soap12"
                         uri="http://localhost:9000/services/SimpleStockQuoteService"/>
            </endpoint>
            <outSequence>
                <property name="transport.vfs.ReplyFileName"
                          expression="fn:concat(fn:substring-after(get-property('MessageID'), 'urn:uuid:'), '.xml')"
                          scope="transport"/>
                <property action="set" name="OUT_ONLY" value="true"/>
                <send>
                    <endpoint>
                        <address uri="vfs:file:///home/user/test/out"/> <!--CHANGE-->
                    </endpoint>
                </send>
            </outSequence>
        </target>
        <publishWSDL uri="file:repository/conf/sample/resources/proxy/sample_proxy_1.wsdl"/>
    </proxy>

</definitions>

Objective: Using the file system as transport medium using VFS transport listener and sender

Prerequisites:
Start the Axis2 server and deploy the SimpleStockQuoteService if not already done
Create three new directories in a test directory. e.g. in, out, original in /home/user/test. Open SYNAPSE_HOME/repository/conf/sample/synapse_sample_254.xml and edit the following values. Change transport.vfs.FileURI, transport.vfs.MoveAfterProcess, transport.vfs.MoveAfterFailure parameter values to the above in, original, original directories respectively. Change outSequence endpoint address uri to out directory with the prefix vfs:. Values you have to change are marked with <!--CHANGE-->
Start the Synapse configuration numbered 254: i.e. synapse -sample 254

Copy SYNAPSE_HOME/repository/conf/sample/resources/vfs/test.xml to the directory given in transport.vfs.FileURI above.

test.xml file content is as follows

<?xml version='1.0' encoding='UTF-8'?>
    <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:wsa="http://www.w3.org/2005/08/addressing">
    <soapenv:Body>
            <m0:getQuote xmlns:m0="http://services.samples">
                    <m0:request>
                            <m0:symbol>IBM</m0:symbol>
                    </m0:request>
            </m0:getQuote>
    </soapenv:Body>
</soapenv:Envelope>

VFS transport listener will pick the file from in directory and send it to the Axis2 service. The request XML file will be moved to original directory. The response from the Axis2 server will be saved to out directory.

<definitions xmlns="http://ws.apache.org/ns/synapse"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">

    <proxy name="StockQuoteProxy" transports="vfs">

        <target>
            <inSequence>
                <header name="Action" value="urn:getQuote"/>
            </inSequence>
            <endpoint>
                <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
            </endpoint>
            <outSequence>
                <property action="set" name="OUT_ONLY" value="true"/>
                <send>
                    <endpoint>
                        <address uri="mailto:user@host"/> <!--CHANGE-->
                    </endpoint>
                </send>
            </outSequence>
        </target>
        <publishWSDL uri="file:repository/conf/sample/resources/proxy/sample_proxy_1.wsdl"/>

        <parameter name="transport.vfs.FileURI">vfs:ftp://guest:guest@localhost/test?vfs.passive=true</parameter> <!--CHANGE-->
        <parameter name="transport.vfs.ContentType">text/xml</parameter>
        <parameter name="transport.vfs.FileNamePattern">.*\.xml</parameter>
        <parameter name="transport.PollInterval">15</parameter>
    </proxy>

</definitions>

Objective: Switching from FTP transport listener to mail transport sender

Prerequisites:
You will need access to an FTP server and an SMTP server to try this sample.

Start the Axis2 server and deploy the SimpleStockQuoteService if not already done

Enable mail transport sender in the Synapse axis2.xml. See Setting up mail transport sender

Create a new test directory in the FTP server. Open SYNAPSE_HOME/repository/conf/sample/synapse_sample_116.xml and edit the following values. Change transport.vfs.FileURI parameter value point to the test directory at the FTP server. Change outSequence endpoint address uri email address to a working email address. Values you have to change are marked with <!--CHANGE-->.

Start the Synapse configuration numbered 255: i.e. synapse -sample 255

Copy SYNAPSE_HOME/repository/conf/sample/resources/vfs/test.xml to the ftp directory given in transport.vfs.FileURI above.

VFS transport listener will pick the file from the directory in the FTP server and send it to the Axis2 service. The file in the FTP directory will be deleted. The response will be sent to the given email address.

<definitions xmlns="http://ws.apache.org/ns/synapse"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">

    <proxy name="StockQuoteProxy" transports="mailto">

        <target>
            <inSequence>
                <property name="senderAddress" expression="get-property('transport', 'From')"/>
                <log level="full">
                    <property name="Sender Address" expression="get-property('senderAddress')"/>
                </log>
                <send>
                    <endpoint>
                        <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
                    </endpoint>
                </send>
            </inSequence>
            <outSequence>
                <property name="Subject" value="Custom Subject for Response" scope="transport"/>
                <header name="To" expression="fn:concat('mailto:', get-property('senderAddress'))"/>
                <log level="full">
                    <property name="message" value="Response message"/>
                    <property name="Sender Address" expression="get-property('senderAddress')"/>
                </log>
                <send/>
            </outSequence>
        </target>
        <publishWSDL uri="file:repository/conf/sample/resources/proxy/sample_proxy_1.wsdl"/>

        <parameter name="transport.mail.Address">synapse.demo.1@gmail.com</parameter>
        <parameter name="transport.mail.Protocol">pop3</parameter>
        <parameter name="transport.PollInterval">5</parameter>
        <parameter name="mail.pop3.host">pop.gmail.com</parameter>
        <parameter name="mail.pop3.port">995</parameter>
        <parameter name="mail.pop3.user">synapse.demo.1</parameter>
        <parameter name="mail.pop3.password">mailpassword</parameter>
        <parameter name="mail.pop3.socketFactory.class">javax.net.ssl.SSLSocketFactory</parameter>
        <parameter name="mail.pop3.socketFactory.fallback">false</parameter>
        <parameter name="mail.pop3.socketFactory.port">995</parameter>
        <parameter name="transport.mail.ContentType">application/xml</parameter>

    </proxy>

</definitions>

Objective: Using the mail transport with Proxy services

Prerequisites:
You will need access to an email account
Start the Axis2 server and deploy the SimpleStockQuoteService if not already done
Enable mail transport sender in the Synapse axis2.xml. See Setting up mail transport sender
Start the Synapse configuration numbered 256: i.e. synapse -sample 256

Send an email with the following body and any custom Subject from your mail account.

<getQuote xmlns="http://services.samples">
   <request xmlns="http://services.samples/xsd">
       <symbol>IBM</symbol>
   </request>
</getQuote>

After a few seconds (e.g. 30s), you should receive a POX response in your email account with the stock quote reply.

Note that in this sample we used the transport.mail.ContentType property to make sure that the transport parses the request message as POX. If you remove this property, you may still be able to send requests using a standard mail client if instead of writing the XML in the body of the message, you add it as an attachment. In that case, you should use .xml as a suffix for the attachment and format the request as a SOAP 1.1 message. Indeed, for a file with suffix .xml the mail client will most likely use text/xml as the content type, exactly as required for SOAP 1.1. Sending a POX message using this approach will be a lot trickier, because most standard mail clients don't allow the user to explicitly set the content type.

<definitions xmlns="http://ws.apache.org/ns/synapse"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">

    <proxy name="OrderProcesserProxy40" transports="fix">
        <target>
            <endpoint>
                <address
                        uri="fix://localhost:19876?BeginString=FIX.4.0&SenderCompID=SYNAPSE&TargetCompID=EXEC"/>
            </endpoint>
            <inSequence>
                <log level="full"/>
            </inSequence>
            <outSequence>
                <log level="full"/>
                <send/>
            </outSequence>
        </target>

        <parameter name="transport.fix.AcceptorConfigURL">
            file:repository/conf/sample/resources/fix/fix-synapse.cfg
        </parameter>
        <parameter name="transport.fix.AcceptorMessageStore">file</parameter>
        <parameter name="transport.fix.InitiatorConfigURL">
            file:repository/conf/sample/resources/fix/synapse-sender.cfg
        </parameter>
        <parameter name="transport.fix.InitiatorMessageStore">file</parameter>
    </proxy>

</definitions>

Objective: Demonstrate the usage of the FIX (Financial Information eXchange) transport with proxy services

Prerequisites:
You will need the two sample FIX applications that come with Quickfix/J (Banzai and Executor). Configure the two applications to establish sessions with Synapse. See Configuring Sample FIX Applications
Start Banzai and Executor
Enable FIX transport in the Synapse axis2.xml. See Setting up FIX transport
Configure Synapse for FIX samples. See Configuring Synapse for FIX Samples
Open up the SYNAPSE_HOME/repository/conf/sample/synapse_sample_257.xml file and make sure that transport.fix.AcceptorConfigURL property points to the fix-synapse.cfg file you created. Also make sure that transport.fix. InitiatorConfigURL property points to the synapse-sender.cfg file you created. Once done you can start the Synapse configuration numbered 257: i.e. synapse -sample 257. Note that Synapse creates new FIX sessions with Banzai and Executor at this point.

Send an order request from Banzai to Synapse.

Synapse will forward the order request to the session with the Executor. The responses coming from the Executor will be sent back to Banzai.

To get an idea about the various transport parameters being used in this sample see FIX Transport Parameters .

<definitions xmlns="http://ws.apache.org/ns/synapse"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">

    <proxy name="FIXProxy" transports="http">
        <target>
            <endpoint>
                <address
                        uri="fix://localhost:19876?BeginString=FIX.4.0&SenderCompID=SYNAPSE&TargetCompID=EXEC"/>
            </endpoint>

            <inSequence>
                <property name="transport.fix.ServiceName" value="FIXProxy" scope="axis2-client"/>
                <log level="full"/>
            </inSequence>

            <outSequence>
                <log level="full"/>
                <send/>
            </outSequence>
        </target>

        <parameter name="transport.fix.InitiatorConfigURL">
            file:repository/conf/sample/resources/fix/synapse-sender.cfg
        </parameter>
        <parameter name="transport.fix.InitiatorMessageStore">file</parameter>
        <parameter name="transport.fix.SendAllToInSequence">false</parameter>
        <parameter name="transport.fix.DropExtraResponses">true</parameter>
    </proxy>

</definitions>

Objective: Demonstrate switching from HTTP to FIX

Prerequisites:
You will need the Executor sample application that comes with Quickfix/J. Configure Executor to establish a session with Synapse. See Configuring Sample FIX Applications
Start Executor
Enable FIX transport sender in the Synapse axis2.xml. See Setting up FIX transport
Configure Synapse for FIX samples. See Configuring Synapse for FIX Samples . There is no need to create the fix-synapse.cfg file for this sample. Having only the synapse-sender.cfg file is sufficient.
Go to the SYNAPSE_HOME/repository/conf/sample/synapse_sample_258.xml file and make sure that transport.fix.InitiatorConfigURL property points to the synapse-sender.cfg file you created. Once done you can start the Synapse configuration numbered 258: i.e. synapse -sample 258

Invoke the FIX Client as follows. This command sends a FIX message embedded in a SOAP message over HTTP.

ant fixclient -Dsymbol=IBM -Dqty=5 -Dmode=buy -Daddurl=http://localhost:8280/services/FIXProxy

Synapse will forward the order request to the session with the Executor. The first response coming from the Executor will be sent back over HTTP. Executor generally sends two responses for each incoming order request. But since the response has to be forwarded over HTTP only one can be sent back to the client.

<definitions xmlns="http://ws.apache.org/ns/synapse"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">

    <localEntry key="xslt-key-req"
                src="file:repository/conf/sample/resources/transform/transform_fix_to_http.xslt"/>

    <proxy name="FIXProxy" transports="fix">
        <target>
            <endpoint>
                <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
            </endpoint>
            <inSequence>
                <log level="full"/>
                <xslt key="xslt-key-req"/>
                <log level="full"/>
            </inSequence>
            <outSequence>
                <log level="full"/>
            </outSequence>
        </target>
        <parameter name="transport.fix.AcceptorConfigURL">
            file:repository/conf/sample/resources/fix/fix-synapse.cfg
        </parameter>
        <parameter name="transport.fix.AcceptorMessageStore">file</parameter>
    </proxy>

</definitions>

Objective: Demonstrate the capability of switching between FIX to HTTP

Prerequisites:
You will need the sample FIX blotter that come with Quickfix/J (Banzai). Configure the blotter to establish sessions with Synapse. See Configuring Sample FIX Applications
Start the Axis2 server and deploy the SimpleStockQuoteService if not already deployed
Start Banzai
Enable FIX transport in the Synapse axis2.xml. See Setting up FIX transport
Configure Synapse for FIX samples. See Configuring Synapse for FIX Samples
Open up the SYNAPSE_HOME/repository/conf/sample/synapse_sample_259.xml file and make sure that transport.fix.AcceptorConfigURL property points to the fix-synapse.cfg file you created. Once done you can start the Synapse configuration numbered 259: i.e. synapse -sample 259. Note that Synapse creates a new FIX session with Banzai at this point.

Send an order request from Banzai to Synapse. e.g. Buy DELL 1000 @ 100. User has to send a 'Limit' Order because price is a mandatory field for 'placeOrder' operation.

Synapse will forward the order request to one-way 'placeOrder' operation on the SimpleStockQuoteService. Synapse uses a simple XSLT mediator to transform the incoming FIX to a SOAP message.

<xsl:stylesheet version="2.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:fn="http://www.w3.org/2005/02/xpath-functions">
    <xsl:output method="xml" omit-xml-declaration="yes" indent="yes" />
  <xsl:template match="/">
    <m0:placeOrder xmlns:m0="http://services.samples">
        <m0:order>
            <m0:price><xsl:value-of select="//message/body/field[@id='44']"/></m0:price>
            <m0:quantity><xsl:value-of select="//message/body/field[@id='38']"/></m0:quantity>
            <m0:symbol><xsl:value-of select="//message/body/field[@id='55']"/></m0:symbol>
        </m0:order>
    </m0:placeOrder>
   </xsl:template>
</xsl:stylesheet>
      

To get an idea about the various transport parameters being used in this sample see FIX Transport Parameters .

<definitions xmlns="http://ws.apache.org/ns/synapse"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">

    <proxy name="FIXProxy" transports="fix">
        <target>
            <endpoint>
                <address
                        uri="jms:/QpidStockQuoteService?transport.jms.ConnectionFactoryJNDIName=qpidConnectionfactory&java.naming.factory.initial=org.apache.qpid.jndi.PropertiesFileInitialContextFactory&java.naming.provider.url=repository/conf/sample/resources/fix/conn.properties&transport.jms.ReplyDestination=replyQueue"/>
            </endpoint>
            <inSequence>
                <log level="full"/>
            </inSequence>
            <outSequence>
                <property name="transport.fix.ServiceName" value="FIXProxy" scope="axis2-client"/>
                <log level="full"/>
                <send/>
            </outSequence>
        </target>
        <parameter name="transport.fix.AcceptorConfigURL">
            file:repository/conf/sample/resources/fix/fix-synapse.cfg
        </parameter>
        <parameter name="transport.fix.AcceptorMessageStore">
            file
        </parameter>
    </proxy>

</definitions>

Objective: Demonstrate the capability of switching between FIX and AMQP protocols

Prerequisites:
You will need the sample FIX blotter that comes with Quickfix/J (Banzai). Configure the blotter to establish sessions with Synapse. See Configuring Sample FIX Applications

Configure the AMQP transport for Synapse. See Configure Synapse for AMQP Transport

Start the AMQP consumer, by switching to samples/axis2Client directory and running the consumer using the following command. Consumer will listen to the queue 'QpidStockQuoteService', accept the orders and reply to the queue 'replyQueue'.

ant amqpconsumer -Dpropfile=$SYNAPSE_HOME/repository/conf/sample/resources/fix/direct.properties

Start Banzai

Enable FIX transport in the Synapse axis2.xml. See Setting up FIX transport

Configure Synapse for FIX samples. See Configuring Synapse for FIX Samples

Open up the SYNAPSE_HOME/repository/conf/sample/synapse_sample_260.xml file and make sure that the transport.fix.AcceptorConfigURL property points to the fix-synapse.cfg file you created. Once done you can start the Synapse configuration numbered 260: i.e. synapse -sample 260. Note that Synapse creates a new FIX session with Banzai at this point.

Send an order request from Banzai to Synapse. e.g. Buy DELL 1000 @ MKT.

Synapse will forward the order request by binding it to a JMS message payload and sending it to the AMQP consumer. AMQP consumer will send a execution back to Banzai.

To get an idea about the various transport parameters being used in this sample see FIX Transport Parameters .

<definitions xmlns="http://ws.apache.org/ns/synapse"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">

    <proxy name="OrderProcesserProxy41" transports="fix">
        <target>
            <endpoint>
                <address
                        uri="fix://localhost:19877?BeginString=FIX.4.1&SenderCompID=SYNAPSE&TargetCompID=EXEC"/>
            </endpoint>
            <inSequence>
                <log level="full"/>
            </inSequence>
            <outSequence>
                <log level="full"/>
                <send/>
            </outSequence>
        </target>
        <parameter name="transport.fix.AcceptorConfigURL">
            file:repository/conf/sample/resources/fix/fix-synapse-m40.cfg
        </parameter>
        <parameter name="transport.fix.AcceptorMessageStore">file</parameter>
        <parameter name="transport.fix.InitiatorConfigURL">
            file:repository/conf/sample/resources/fix/synapse-sender-m.cfg
        </parameter>
        <parameter name="transport.fix.InitiatorMessageStore">file</parameter>
    </proxy>

</definitions>

Objective: Demonstrate the capability of switching between FIX versions e.g. FIX4.0 to FIX4.1

Prerequisites:
You will need the two sample FIX applications that come with Quickfix/J (Banzai and Executor). Configure the two applications to establish sessions with Synapse. See Configuring Sample FIX Applications.

Add the following lines to the Banzai configuration file (banzai.cfg).

DataDictionary=~/etc/spec/FIX40-synapse.xml

Note: FIX40-synapse.xml can be found at $SYNAPSE_HOME/repository/conf/samples/resources/fix. This is a custom FIX data dictionary file that has added tag 150,151 to the execution messages (35=8) of FIX4.0. Make sure the DataDictionary property of the banzai.cfg points to this data dictionary file.

Add the following lines to the Executor configuration file (executor.cfg).

[session]
BeginString=FIX.4.1
SocketAcceptPort=19877

Start Banzai and Executor using the custom configuration files.

Enable FIX transport in the Synapse axis2.xml. See Setting up FIX transport

Configure Synapse for FIX samples. We will be using two custom configuration files for Synapse in this sample. These two custom configuration files can be found at SYNAPSE_HOME/repository/conf/sample/resources/fix directory. The two files are called fix-synapse-m40.cfg and synapse-sender-m.cfg. You can point your Synapse configuration to these two files (this is already done in the supplied synapse_sample_261.xml file) or you may create copies of them and point the Synapse configuration to the copies. In either case make sure that the properties like FileStorePath and FileLogPath in the two files point to valid locations in your local file system.

Open up the SYNAPSE_HOME/repository/conf/sample/synapse_sample_261.xml file and make sure that transport.fix.AcceptorConfigURL property points to the fix-synapse-m40.cfg file described above and transport.fix.InitiatorConfigURL points to the synapse-sender-m.cfg file described above. Once done you can start the Synapse configuration numbered 261: i.e. synapse -sample 261. Note that Synapse creates a new FIX session with Banzai at this point.

Send an order request from Banzai to Synapse. e.g. Buy DELL 1000 @ MKT.

Synapse will forward the order request from FIX4.0 to the Executor that accepts FIX4.1 messages. Executor will send an ack and an execution back to Banzai.

To get an idea about the various transport parameters being used in this sample see FIX Transport Parameters .

<definitions xmlns="http://ws.apache.org/ns/synapse"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">

    <sequence name="CBR_SEQ">
        <in>
            <switch source="//message/body/field[@id='55']">
                <case regex="GOOG">
                    <send>
                        <endpoint>
                            <address
                                    uri="fix://localhost:19876?BeginString=FIX.4.0&SenderCompID=SYNAPSE&TargetCompID=EXEC"/>
                        </endpoint>
                    </send>
                </case>
                <case regex="MSFT">
                    <send>
                        <endpoint>
                            <address
                                    uri="fix://localhost:19877?BeginString=FIX.4.1&SenderCompID=SYNAPSE&TargetCompID=EXEC"/>
                        </endpoint>
                    </send>
                </case>
                <default/>
            </switch>
        </in>
        <out>
            <send/>
        </out>
    </sequence>

    <proxy name="FIXProxy" transports="fix">
        <target inSequence="CBR_SEQ"/>
        <parameter name="transport.fix.AcceptorConfigURL">
            file:repository/conf/sample/resources/fix/fix-synapse.cfg
        </parameter>
        <parameter name="transport.fix.AcceptorMessageStore">
            file
        </parameter>
        <parameter name="transport.fix.InitiatorConfigURL">
            file:repository/conf/sample/resources/fix/synapse-sender.cfg
        </parameter>
        <parameter name="transport.fix.InitiatorMessageStore">
            file
        </parameter>
    </proxy>

</definitions>

Objective: Demonstrate the capability of CBR FIX messages

Prerequisites:
You will need the two sample FIX applications that come with Quickfix/J (Banzai and Executor). Configure the two applications to establish sessions with Synapse. See Configuring Sample FIX Applications

Add the following lines to banzai.cfg.

DataDictionary=~/etc/spec/FIX40-synapse.xml

Note: FIX40-synapse.xml can be found at $SYNAPSE_HOME/repository/conf/samples/resources/fix. This is a custom FIX data dictionary file that has added tag 150,151 to the execution messages (35=8) of FIX4.0. Make sure the DataDictionary property of the banzai.cfg points to this data dictionary file.

Add the following lines to executor.cfg

[session]
BeginString=FIX.4.1
SocketAcceptPort=19877

Start Banzai and Executor using the custom config files.

Enable FIX transport in the Synapse axis2.xml. See Setting up FIX transport

Configure Synapse for FIX samples. See Configuring Synapse for FIX Samples

Open up the SYNAPSE_HOME/repository/conf/sample/synapse_sample_262.xml file and make sure that transport.fix.AcceptorConfigURL property points to the fix-synapse.cfg file you created and transport.fix.InitiatorConfigURL points to the synapse-sender.cfg file you created. Once done you can start the Synapse configuration numbered 262: i.e. synapse -sample 262. Note that Synapse creates a new FIX session with Banzai at this point.

Send an order request from Banzai to Synapse. e.g. Buy GOOG 1000 @ MKT, Buy MSFT 3000 @ MKT, Buy SUNW 500 @ 100.20

Synapse will forward the order requests with symbol 'GOOG' to FIX endpoint FIX-4.0 @ localhost:19876.

Synapse will forward the order requests with symbol 'MSFT' to FIX endpoint FIX-4.1 @ localhost:19877.

Synapse will not forward the orders with other symbols to any endpoint. (default case has kept blank in the configuration)

To get an idea about the various transport parameters being used in this sample see FIX Transport Parameters .

<definitions xmlns="http://ws.apache.org/ns/synapse"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">

    <proxy name="StockQuoteProxy" transports="jms">
        <target>
            <inSequence>
                <property action="set" name="OUT_ONLY" value="true"/>
            </inSequence>
            <endpoint>
                <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
            </endpoint>
            <outSequence>
                <send/>
            </outSequence>
        </target>
        <publishWSDL uri="file:repository/conf/sample/resources/proxy/sample_proxy_1.wsdl"/>
        <parameter name="transport.jms.ContentType">
            <rules>
                <jmsProperty>contentType</jmsProperty>
                <default>application/xml</default>
            </rules>
        </parameter>
    </proxy>

</definitions>

Objective: Introduction to switching transports with proxy services. The JMS provider will be JBoss Messaging(JBM).

Prerequisites:
Start the Axis2 server and deploy the SimpleStockQuoteService (Refer steps above)
Download , install and start JBM server, and configure Synapse to listen on JBM (refer notes below)
Start the Synapse configuration numbered 250: i.e. synapse -sample 250
We need to configure the required queues in JBM. Add the following entry to JBM jms configuration inside file-config/stand-alone/non-clustered/jbm-jms.xml. Once JBM is installed and started you should get a message as follows:

<queue name="StockQuoteProxy">
    <entry name="StockQuoteProxy"/>
</queue>

Once you started the JBM server with the above changes you'll be able to see the following on STDOUT.

10:18:02,673 INFO [org.jboss.messaging.core.server.impl.MessagingServerImpl]  JBoss Messaging Server version 2.0.0.BETA3 (maggot, 104) started 

You will now need to configure the Axis2 instance used by Synapse (not the sample Axis2 server) to enable JMS support using the above provider. Refer Axis2 documentation on setting up JMS in detail (http://ws.apache.org/axis2/1_1/jms-transport.html). You will also need to copy the jbm-core-client.jar, jbm-jms-client.jar, jnp-client.jar(these jars are inside client folder ) and jbm-transports.jar, netty.jar(these jars are from lib folder) jars from JBM into the lib directory to allow Synapse to connect to the JBM JMS provider. This was tested with JBM 2.0.0.BETA3

You need to add the following configuration for Axis2 JMS transport listener in axis2.xml found at repository/conf/axis2.xml.

<transportReceiver name="jms" class="org.apache.axis2.transport.jms.JMSListener">
    <parameter name="java.naming.factory.initial">org.jnp.interfaces.NamingContextFactory</parameter>
    <parameter name="java.naming.provider.url">jnp://localhost:1099</parameter>
    <parameter name="java.naming.factory.url.pkgs">org.jboss.naming:org.jnp.interfaces</parameter>
    <parameter name="transport.jms.ConnectionFactoryJNDIName">ConnectionFactory</parameter>
</transportReceiver>

And also uncomment the section for JMS transport sender in the same file.

Once you start the Synapse configuration 250 and request for the WSDL of the proxy service (http://localhost:8280/services/StockQuoteProxy?wsdl) you will notice that its exposed only on the JMS transport. This is because the configuration specified this requirement in the proxy service definition.

Now lets send a stock quote request on JMS, using the dumb stock quote client as follows:

ant jmsclient -Djms_type=pox -Djms_dest=StockQuoteProxy -Djms_payload=MSFT -Djava.naming.provider.url=jnp://localhost:1099 -Djava.naming.factory.initial=org.jnp.interfaces.NamingContextFactory -D=java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces

On the Synapse debug log you will notice that the JMS listener received the request message as:

[JMSWorker-1] DEBUG ProxyServiceMessageReceiver -Proxy Service StockQuoteProxy received a new message...

Now if you examine the console running the sample Axis2 server, you will see a message indicating that the server has accepted an order as follows:

Accepted order for : 16517 stocks of MSFT at $ 169.14622538721846

In this sample, the client sends the request message to the proxy service exposed over JMS in Synsape. Synapse forwards this message to the HTTP EPR of the simple stock quote service hosted on the sample Axis2 server. Note that the operation is out-only and no response is sent back to the client. The transport.jms.ContentType property is necessary to allow the JMS transport to determine the content type of incoming messages. With the given configuration it will first try to read the content type from the 'contentType' message property and fall back to 'application/xml' (i.e. POX) if this property is not set. Note that the JMS client used in this example doesn't send any content type information.

Note: It is possible to instruct a JMS proxy service to listen to an already existing destination without creating a new one. To do this, use the parameter elements on the proxy service definition to specify the destination and connection factory etc.

e.g.

<parameter name="transport.jms.Destination">dynamicTopics/something.TestTopic</parameter>
<definitions xmlns="http://ws.apache.org/ns/synapse"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">

    <proxy name="StockQuoteProxy" transports="http">
        <target>
            <endpoint>
                <address
                        uri="jms:/SimpleStockQuoteService?transport.jms.ConnectionFactoryJNDIName=QueueConnectionFactory&java.naming.factory.initial=org.apache.activemq.jndi.ActiveMQInitialContextFactory&java.naming.provider.url=tcp://localhost:61616&transport.jms.DestinationType=queue"/>
            </endpoint>
            <inSequence>
                <property action="set" name="transport.jms.ContentTypeProperty" value="Content-Type"
                          scope="axis2"/>
            </inSequence>
            <outSequence>
                <property action="remove" name="TRANSPORT_HEADERS" scope="axis2"/>
                <send/>
            </outSequence>
        </target>
        <publishWSDL uri="file:repository/conf/sample/resources/proxy/sample_proxy_1.wsdl"/>
    </proxy>

</definitions>

Objective: Demonstrate sending request response scenario with JMS transport

Prerequisites:
You need to set up synpase and axis2 server to use the JMS transport. See Sample 251 for more details.

This sample is similar to the Sample 251 . Only difference is we are expecting a response from the server. JMS transport uses transport.jms.ContentTypeProperty to determine the content type of the response message. If this property is not set JMS transport treats the incoming message as plain text.

In the out path we remove the message context property TRANSPORT_HEADERS. If these property is not removed JMS headers will be passed to the client.

Start Synpase using sample 264.

synapse.bat/synapse.sh -sample 264

Start Axis2 server with SimpleStockService deployed

Invoke the stockquote client using the following command.

ant stockquote -Daddurl=http://localhost:8280/services/StockQuoteProxy -Dsymbol=MSFT

The sample Axis2 server console will print a message indicating that it has received the request:

Generating quote for : MSFT

In the client side it shoud print a message indicating it has received the price.

 Standard :: Stock price = $154.31851804993238
<definitions xmlns="http://ws.apache.org/ns/synapse"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">

    <proxy name="StockQuoteProxy" transports="tcp">
        <target>
            <endpoint>
                <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
            </endpoint>
            <inSequence>
                <log level="full"/>
                <property name="OUT_ONLY" value="true"/>
            </inSequence>
        </target>
    </proxy>

</definitions>

Objective: Demonstrate receiving SOAP messages over TCP and forwarding them over HTTP

Prerequisites:
You need to configure Synpase to use the TCP transport. The sample Axis2 client should also be setup to send TCP requests. Refer Setting Up the TCP Transport section in the sample setup guide for more details.
Start Synpase using sample 265: ie synapse -sample 265
Start Axis2 server with SimpleStockService deployed

This sample is similar to Sample 250 . Only difference is instead of the JMS transport we will be using the TCP transport to receive messages. TCP is not an application layer protocol. Hence there are no application level headers available in the requests. Synapse has to simply read the XML content coming through the socket and dispatch it to the right proxy service based on the information available in the message payload itself. The TCP transport is capable of dispatching requests based on addressing headers or the first element in the SOAP body. In this sample, we will get the sample client to send WS-Addressing headers in the request. Therefore the dispatching will take place based on the addressing header values.

Invoke the stockquote client using the following command. Note the TCP URL in the command.

ant stockquote -Daddurl=tcp://localhost:6060/services/StockQuoteProxy -Dmode=placeorder

The TCP transport will receive the message and hand it over to the mediation engine. Synapse will dispatch the request to the StockQuoteProxy service based on the addressing header values.

The sample Axis2 server console will print a message indicating that it has received the request:

Thu May 20 12:25:01 IST 2010 samples.services.SimpleStockQuoteService  :: Accepted order #1 for : 17621 stocks of IBM at $ 73.48068475255796
<definitions xmlns="http://ws.apache.org/ns/synapse"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">

    <proxy name="StockQuoteProxy" transports="udp">
        <target>
            <endpoint>
                <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
            </endpoint>
            <inSequence>
                <log level="full"/>
                <property name="OUT_ONLY" value="true"/>
            </inSequence>
        </target>
        <parameter name="transport.udp.port">9999</parameter>
        <parameter name="transport.udp.contentType">text/xml</parameter>
        <publishWSDL uri="file:repository/conf/sample/resources/proxy/sample_proxy_1.wsdl"/>
    </proxy>

</definitions>

Objective: Demonstrate receiving SOAP messages over UDP and forwarding them over HTTP

Prerequisites:
You need to configure Synpase to use the UDP transport. The sample Axis2 client should also be setup to send UDP requests. Refer Setting Up the UDP Transport section in the sample setup guide for more details.
Start Synpase using sample 266: i.e. synapse -sample 266
Start Axis2 server with SimpleStockService deployed

This sample is similar to Sample 265 . Only difference is instead of the TCP transport we will be using the UDP transport to receive messages.

Invoke the stockquote client using the following command. Note the UDP URL in the command.

ant stockquote -Daddurl=udp://localhost:9999?contentType=text/xml -Dmode=placeorder

Since we have configured the content type as text/xml for the proxy service, incoming messages will be processed as SOAP 1.1 messages.

The sample Axis2 server console will print a message indicating that it has received the request:

Thu May 20 12:25:01 IST 2010 samples.services.SimpleStockQuoteService  :: Accepted order #1 for : 17621 stocks of IBM at $ 73.48068475255796

Introduction to Synapse Tasks

<definitions xmlns="http://ws.apache.org/ns/synapse"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">

    <task class="org.apache.synapse.startup.tasks.MessageInjector" name="CheckPrice">
        <property name="to" value="http://localhost:9000/services/SimpleStockQuoteService"/>
        <property name="soapAction" value="urn:getQuote"/>
        <property name="message">
            <m0:getQuote xmlns:m0="http://services.samples">
                <m0:request>
                    <m0:symbol>IBM</m0:symbol>
                </m0:request>
            </m0:getQuote>
        </property>
        <trigger interval="5"/>
    </task>

    <sequence name="main">
        <in>
            <send/>
        </in>
        <out>
            <log level="custom">
                <property xmlns:ax21="http://services.samples/xsd"
                          xmlns:ns="http://services.samples" name="Stock_Quote_on"
                          expression="//ns:return/ax21:lastTradeTimestamp/child::text()"/>
                <property xmlns:ax21="http://services.samples/xsd"
                          xmlns:ns="http://services.samples" name="For_the_organization"
                          expression="//ns:return/ax21:name/child::text()"/>
                <property xmlns:ax21="http://services.samples/xsd"
                          xmlns:ns="http://services.samples" name="Last_Value"
                          expression="//ns:return/ax21:last/child::text()"/>
            </log>
        </out>
    </sequence>

</definitions>

Objective: Introduce the concept of tasks and how simple trigger works

Prerequisites:
Build the SimpleStockQuoteService as mentioned above and start the sample Axis2 server
Start Synapse using sample 300: ie synapse -sample 300

When ever Synapse gets started with this configuration, a task will run periodically in 5 second intervals. You could limit the number of times that you want to run this task by adding a count attribute with an integer as the value, if the count is not present as in this sample this task will run until the server is shutdown.

One can write his/her own task class implementing the org.apache.synapse.task.Task interface and implementing the execute method to run the necessary logic. For this particular sample we have used the MessageInjector class which just injects a message specified into Synapse environment.

Advanced mediations with advanced mediators

The Synapse Script Mediator is a Synapse extension, and thus all prerequisites are not bundled by default with the Synapse distribution. Before you use some script mediators you may need to manually add the required jar files to the Synapse lib directory, and optionally perform other installation tasks as may be required by the individual scripting language. This is explained in the Samples Setup guide .

<definitions xmlns="http://ws.apache.org/ns/synapse"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">

    <registry provider="org.apache.synapse.registry.url.SimpleURLRegistry">
        <!-- the root property of the simple URL registry helps resolve a resource URL as root + key -->
        <parameter name="root">file:repository/conf/sample/resources/</parameter>
        <!-- all resources loaded from the URL registry would be cached for this number of milli seconds -->
        <parameter name="cachableDuration">15000</parameter>
    </registry>

    <localEntry key="stockquoteScript"
                src="file:repository/conf/sample/resources/script/stockquoteTransformRequest.js"/>

    <sequence name="main">
        <in>
            <!-- transform the custom quote request into a standard quote request expected by the service -->
            <script language="js" key="stockquoteScript" function="transformRequest"/>
            <send>
                <endpoint>
                    <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="js" key="script/stockquoteTransformResponse.js"
                    function="transformResponse"/>
            <send/>
        </out>
    </sequence>

</definitions>
<x><![CDATA[
  function transformRequest(mc) {
     var symbol = mc.getPayloadXML()..*::Code.toString();
     mc.setPayloadXML(
        <m:getQuote xmlns:m="http://services.samples">
           <m:request>
              <m:symbol>{symbol}</m:symbol>
           </m:request>
        </m:getQuote>);
  }

  function transformResponse(mc) {
     var symbol = mc.getPayloadXML()..*::symbol.toString();
     var price = mc.getPayloadXML()..*::last.toString();
     mc.setPayloadXML(
        <m:CheckPriceResponse xmlns:m="http://www.apache-synapse.org/test">
   <m:Code>{symbol}</m:Code>
   <m:Price>{price}</m:Price>
        </m:CheckPriceResponse>);
  }
]]></x>

Objective: Introduction to the script mediator

Prerequisites:
Start the Synapse configuration numbered 350: i.e. synapse -sample 350
Start the Axis2 server and deploy the SimpleStockQuoteService if not already done

This sample is similar to sample 8 but instead of using XSLT, the transformation is done with JavaScript and E4X. Note that the script source loaded from a resource must be specified within a CDATA tag within an XML element. The script used in this example has two functions, 'transformRequest' and 'transformResponse', and the Synapse configuration uses the function attribute to specify which function should be invoked. Use the stock quote client to issue a custom quote client as follows.:

ant stockquote -Daddurl=http://localhost:9000/services/SimpleStockQuoteService -Dtrpurl=http://localhost:8280/ -Dmode=customquote

Synapse uses the script mediator and the specified JavaScript function to convert the custom request to a standard quote request. Subsequently the response received is transformed and sent back to the client.

<definitions xmlns="http://ws.apache.org/ns/synapse"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">

    <sequence name="main">
        <in>
            <!-- transform the custom quote request into a standard quote requst expected by the service -->
            <script language="js">
                var symbol = mc.getPayloadXML()..*::Code.toString();
                mc.setPayloadXML(
                <m:getQuote xmlns:m="http://services.samples">
                <m:request>
                <m:symbol>{symbol}</m:symbol>
                </m:request>
                </m:getQuote>);
            </script>
            <send>
                <endpoint>
                    <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="js">
                var symbol = mc.getPayloadXML()..*::symbol.toString();
                var price = mc.getPayloadXML()..*::last.toString();
                mc.setPayloadXML(
                <m:CheckPriceResponse xmlns:m="http://services.samples/xsd">
                <m:Code>{symbol}</m:Code>
                <m:Price>{price}</m:Price>
                </m:CheckPriceResponse>);
            </script>
            <send/>
        </out>
    </sequence>

</definitions>

Objective: Introduction to in-line script mediation

Prerequisites:
Start the Synapse configuration numbered 351: i.e. synapse -sample 351
Start the Axis2 server and deploy the SimpleStockQuoteService if not already done

This example is functionally equivalent to sample # 350 and sample # 8, and demonstrates in-line script mediation in Synapse. Use the stock quote client to send a custom quote as in example # 350 to try this example.

<definitions xmlns="http://ws.apache.org/ns/synapse"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">

    <sequence name="main">
        <in>
            <!-- change the MessageContext into a response and set a response payload -->
            <script language="js">
                mc.setTo(mc.getReplyTo());
                mc.setProperty("RESPONSE", "true");
                mc.setPayloadXML(
                <ns:getQuoteResponse xmlns:ns="http://services.samples/xsd">
                <ns:return>
                <ns:last>99.9</ns:last>
                </ns:return>
                </ns:getQuoteResponse>);
            </script>
        </in>
        <send/>
    </sequence>

</definitions>

Objective: Accessing the Synapse APIs from scripting languages

Prerequisites:
Start the Synapse configuration numbered 352: i.e. bin/synapse -sample 352

This example shows how an in-line JavaScript mediator script could access the Synapse message context API to set its 'To' EPR and to set a custom property to mark it as a response. Execute the stock quote client, and you will receive the response "99.9" as the last sale price as per the above script.

ant stockquote -Daddurl=http://localhost:9000/services/SimpleStockQuoteService -Dtrpurl=http://localhost:8280/
...
stockquote:
     [java] Standard :: Stock price = $99.9
<definitions xmlns="http://ws.apache.org/ns/synapse"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">

    <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>
<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: Script mediators using Ruby

Prerequisites:
This sample uses Ruby so first setup support for this in Synapse as described at Configuring JRuby
Start the Synapse configuration numbered 353: i.e. bin/synapse -sample 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 which function to be invoked when used. Execute the stock quote client to send a custom stock quote as per example #350 and check the received stock quote response.

<definitions xmlns="http://ws.apache.org/ns/synapse"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">

    <sequence name="main">
        <in>
            <script language="rb">

                require 'rexml/document'
                include REXML
                newRequest= Document.new '<m:getQuote xmlns:m="http://services.samples"><m:request><m:symbol>...test...</m:symbol></m:request></m:getQuote>'
                newRequest.root.elements[1].elements[1].text =
                $mc.getPayloadXML().root.elements[1].get_text
                $mc.setPayloadXML(newRequest)

            </script>
            <send>
                <endpoint>
                    <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
                </endpoint>
            </send>
        </in>
        <out>
            <script language="rb">

                require 'rexml/document'
                include REXML
                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)

            </script>
            <send/>
        </out>
    </sequence>

</definitions>

Objective: Script mediators using Ruby(In-line Ruby Script)

Prerequisites:
This sample uses Ruby so first setup support for this in Synapse as described at Configuring JRuby
Start the Synapse configuration numbered 354: i.e. bin/synapse -sample 354
Start the Axis2 server and deploy the SimpleStockQuoteService if not already done

This sample is functionally equivalent to the sample 353.

Run the client with

 ant stockquote -Daddurl=http://localhost:9000/services/SimpleStockQuoteService -Dtrpurl=http://localhost:8280/ -Dmode=customquote

Following database mediators use Derby in a client/server configuration by using the network server. Therefore, to proceed with the following samples, you need a working Derby database server and you have to follow the steps in Sample Setup Guide before going through the samples.

<definitions xmlns="http://ws.apache.org/ns/synapse"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">

    <sequence name="myFaultHandler">
        <makefault response="true">
            <code xmlns:tns="http://www.w3.org/2003/05/soap-envelope" value="tns:Receiver"/>
            <reason expression="get-property('ERROR_MESSAGE')"/>
        </makefault>
        <send/>
        <drop/>
    </sequence>

    <sequence name="main" onError="myFaultHandler">
        <in>
            <log level="custom">
                <property name="text" value="** Looking up from the Database **"/>
            </log>
            <dblookup>
                <connection>
                    <pool>
                        <driver>org.apache.derby.jdbc.ClientDriver</driver>
                        <url>jdbc:derby://localhost:1527/synapsedb;create=false</url>
                        <user>synapse</user>
                        <password>synapse</password>
                    </pool>
                </connection>
                <statement>
                    <sql>select * from company where name =?</sql>
                    <parameter xmlns:m0="http://services.samples"
                               expression="//m0:getQuote/m0:request/m0:symbol" type="VARCHAR"/>
                    <result name="company_id" column="id"/>
                </statement>
            </dblookup>

            <switch source="get-property('company_id')">
                <case regex="c1">
                    <log level="custom">
                        <property name="text"
                                  expression="fn:concat('Company ID - ',get-property('company_id'))"/>
                    </log>
                    <send>
                        <endpoint>
                            <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
                        </endpoint>
                    </send>
                </case>
                <case regex="c2">
                    <log level="custom">
                        <property name="text"
                                  expression="fn:concat('Company ID - ',get-property('company_id'))"/>
                    </log>
                    <send>
                        <endpoint>
                            <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
                        </endpoint>
                    </send>
                </case>
                <case regex="c3">
                    <log level="custom">
                        <property name="text"
                                  expression="fn:concat('Company ID - ',get-property('company_id'))"/>
                    </log>
                    <send>
                        <endpoint>
                            <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
                        </endpoint>
                    </send>
                </case>
                <default>
                    <log level="custom">
                        <property name="text" value="** Unrecognized Company ID **"/>
                    </log>
                    <makefault response="true">
                        <code xmlns:tns="http://www.w3.org/2003/05/soap-envelope"
                              value="tns:Receiver"/>
                        <reason value="** Unrecognized Company ID **"/>
                    </makefault>
                    <send/>
                    <drop/>
                </default>
            </switch>
            <drop/>
        </in>

        <out>
            <send/>
        </out>

    </sequence>

</definitions>

Objective:Introduction to the dblookup mediator

Prerequisites:
Setting up Derby database as explained above.
Start the Synapse configuration numbered 360: i.e. synapse -sample 360
Start the Axis2 server and deploy the SimpleStockQuoteService if not already done

This sample demonstrates simple database read operations through Synapse. When a message arrives at dblookup mediator, it opens a connection to the database and executes the SQL query. The SQL query use '?' character for attributes that will be filled at runtime. The parameters define how to calculate the value of those attributes at runtime. In this sample a dblookup mediator has been used to extract 'id' of the company from the company database using the symbol which is evaluated using an xpath against the SOAP envelope. Then 'id' base switching will be done by a switch mediator.

When the IBM stock quote is requested,

ant stockquote -Daddurl=http://localhost:9000/services/SimpleStockQuoteService -Dtrpurl=http://localhost:8280/ -Dsymbol=IBM

Synapse console shows

INFO LogMediator text = ** Looking up from the Database **INFO LogMediator text = Company ID ? c1

For the SUN stock quote,

ant stockquote -Daddurl=http://localhost:9000/services/SimpleStockQuoteService -Dtrpurl=http://localhost:8280/ -Dsymbol=SUN

Synapse console shows

INFO LogMediator text = ** Looking up from the Database **INFO LogMediator text = Company ID ? c2

and for the MSFT stock quote,

ant stockquote -Daddurl=http://localhost:9000/services/SimpleStockQuoteService -Dtrpurl=http://localhost:8280/ -Dsymbol=MSFT
INFO LogMediator text = ** Looking up from the Database **

INFO LogMediator text = Company ID ? c2

For any other symbols, Synapse console shows

INFO LogMediator text = ** Unrecognized Company ID **

and the client gets a response which has following message.

** Unrecognized Company ID **

definitions xmlns="http://ws.apache.org/ns/synapse"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">

    <sequence name="main">
        <in>
            <send>
                <endpoint>
                    <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
                </endpoint>
            </send>
        </in>

        <out>
            <log level="custom">
                <property name="text" value="** Reporting to the Database **"/>
            </log>
            <dbreport>
                <connection>
                    <pool>
                        <driver>org.apache.derby.jdbc.ClientDriver</driver>
                        <url>jdbc:derby://localhost:1527/synapsedb;create=false</url>
                        <user>synapse</user>
                        <password>synapse</password>
                    </pool>
                </connection>
                <statement>
                    <sql>update company set price=? where name =?</sql>
                    <parameter xmlns:m1="http://services.samples/xsd"
                               xmlns:m0="http://services.samples"
                               expression="//m0:return/m1:last/child::text()" type="DOUBLE"/>
                    <parameter xmlns:m1="http://services.samples/xsd"
                               xmlns:m0="http://services.samples"
                               expression="//m0:return/m1:symbol/child::text()" type="VARCHAR"/>
                </statement>
            </dbreport>
            <send/>
        </out>
    </sequence>

</definitions>

Objective:Introduction to the dbreport mediator

Prerequisites:
Setting up Derby database as above.
Start the Synapse configuration numbered 361: i.e. synapse -sample 361
Start the Axis2 server and deploy the SimpleStockQuoteService if not already done

This sample demonstrates simple database write operations. The dbreport mediator writes (i.e. inserts one row) to a table using the message details. It works the same as the dblookup mediator. In this sample , dbreport mediator is used for updating the stock price of the company using the last quote value which is calculated by evaluating an XPath against the response message. After running this sample, user can check the company table using the Derby client tool. It will show the inserted value by the dbreport mediator.

Run the client using,

ant stockquote -Daddurl=http://localhost:9000/services/SimpleStockQuoteService -Dtrpurl=http://localhost:8280/ -Dsymbol=IBM

and then execute the following query using database client tool against synapsedb.

select price from company where name='IBM';

It will show some value as follows.

96.39535981018865

definitions xmlns="http://ws.apache.org/ns/synapse"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">

    <sequence name="main">
        <in>
            <send>
                <endpoint>
                    <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
                </endpoint>
            </send>
        </in>

        <out>
            <log level="custom">
                <property name="text" value="** Reporting to the Database **"/>
            </log>

            <dbreport>
                <connection>
                    <pool>
                        <driver>org.apache.derby.jdbc.ClientDriver</driver>
                        <url>jdbc:derby://localhost:1527/synapsedb;create=false</url>
                        <user>synapse</user>
                        <password>synapse</password>
                    </pool>
                </connection>
                <statement>
                    <sql>update company set price=? where name =?</sql>
                    <parameter xmlns:m1="http://services.samples/xsd"
                               xmlns:m0="http://services.samples"
                               expression="//m0:return/m1:last/child::text()" type="DOUBLE"/>
                    <parameter xmlns:m1="http://services.samples/xsd"
                               xmlns:m0="http://services.samples"
                               expression="//m0:return/m1:symbol/child::text()" type="VARCHAR"/>
                </statement>
            </dbreport>
            <log level="custom">
                <property name="text" value="** Looking up from the Database **"/>
            </log>
            <dblookup>
                <connection>
                    <pool>
                        <driver>org.apache.derby.jdbc.ClientDriver</driver>
                        <url>jdbc:derby://localhost:1527/synapsedb;create=false</url>
                        <user>synapse</user>
                        <password>synapse</password>
                    </pool>
                </connection>
                <statement>
                    <sql>select * from company where name =?</sql>
                    <parameter xmlns:m1="http://services.samples/xsd"
                               xmlns:m0="http://services.samples"
                               expression="//m0:return/m1:symbol/child::text()" type="VARCHAR"/>
                    <result name="stock_price" column="price"/>
                </statement>
            </dblookup>
            <log level="custom">
                <property name="text"
                          expression="fn:concat('Stock price - ',get-property('stock_price'))"/>
            </log>
            <send/>
        </out>
    </sequence>

</definitions>

Objective: Demonstrate the use of dbreport and dblookup mediators

Prerequisites:
Setting up Derby database as above
Start the Synapse configuration numbered 362: i.e. synapse -sample 362
Start the Axis2 server and deploy the SimpleStockQuoteService if not already done

In this sample ,the dbreport mediator works the same as the above sample. It updates the price for the given company using the response messages content. Then the dblookup mediator reads the last updated value from the company database and logs it.

When running client,

ant stockquote -Daddurl=http://localhost:9000/services/SimpleStockQuoteService -Dtrpurl=http://localhost:8280/ -Dsymbol=IBM

Synapse console shows,

INFO LogMediator text = ** Reporting to the Database **
...
INFO LogMediator text = ** Looking up from the Database **
...
INFO LogMediator text = Stock price - 153.47886496064808

Prior to run this sample please follow the 'Setting up Synapse DataSources' section in the sample setup guide .

<definitions xmlns="http://ws.apache.org/ns/synapse"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">

    <sequence name="myFaultHandler">
        <makefault response="true">
            <code xmlns:tns="http://www.w3.org/2003/05/soap-envelope" value="tns:Receiver"/>
            <reason expression="get-property('ERROR_MESSAGE')"/>
        </makefault>
        <send/>
        <drop/>
    </sequence>

    <sequence name="main" onError="myFaultHandler">
        <in>
            <log level="custom">
                <property name="text" value="** Looking up from the Database **"/>
            </log>
            <dblookup>
                <connection>
                    <pool>
                        <dsName>lookupdb</dsName>
                    </pool>
                </connection>
                <statement>
                    <sql>select * from company where name =?</sql>
                    <parameter xmlns:m0="http://services.samples"
                               expression="//m0:getQuote/m0:request/m0:symbol" type="VARCHAR"/>
                    <result name="company_id" column="id"/>
                </statement>
            </dblookup>

            <switch source="get-property('company_id')">
                <case regex="c1">
                    <log level="custom">
                        <property name="text"
                                  expression="fn:concat('Company ID - ',get-property('company_id'))"/>
                    </log>
                    <send>
                        <endpoint>
                            <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
                        </endpoint>
                    </send>
                </case>
                <case regex="c2">
                    <log level="custom">
                        <property name="text"
                                  expression="fn:concat('Company ID - ',get-property('company_id'))"/>
                    </log>
                    <send>
                        <endpoint>
                            <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
                        </endpoint>
                    </send>
                </case>
                <case regex="c3">
                    <log level="custom">
                        <property name="text"
                                  expression="fn:concat('Company ID - ',get-property('company_id'))"/>
                    </log>
                    <send>
                        <endpoint>
                            <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
                        </endpoint>
                    </send>
                </case>
                <default>
                    <log level="custom">
                        <property name="text" value="** Unrecognized Company ID **"/>
                    </log>
                    <makefault response="true">
                        <code xmlns:tns="http://www.w3.org/2003/05/soap-envelope"
                              value="tns:Receiver"/>
                        <reason value="** Unrecognized Company ID **"/>
                    </makefault>
                    <send/>
                    <drop/>
                </default>
            </switch>
            <drop/>
        </in>

        <out>
            <log level="custom">
                <property name="text" value="** Reporting to the Database **"/>
            </log>
            <dbreport>
                <connection>
                    <pool>
                        <dsName>reportdb</dsName>
                    </pool>
                </connection>
                <statement>
                    <sql>update company set price=? where name =?</sql>
                    <parameter xmlns:m0="http://services.samples"
                               xmlns:m1="http://services.samples/xsd"
                               expression="//m0:return/m1:last/child::text()" type="DOUBLE"/>
                    <parameter xmlns:m0="http://services.samples"
                               xmlns:m1="http://services.samples/xsd"
                               expression="//m0:return/m1:symbol/child::text()" type="VARCHAR"/>
                </statement>
            </dbreport>
            <log level="custom">
                <property name="text" value="** Looking up from the Database **"/>
            </log>
            <dblookup>
                <connection>
                    <pool>
                        <dsName>reportdb</dsName>
                    </pool>
                </connection>
                <statement>
                    <sql>select * from company where name =?</sql>
                    <parameter xmlns:m0="http://services.samples"
                               xmlns:m1="http://services.samples/xsd"
                               expression="//m0:return/m1:symbol/child::text()" type="VARCHAR"/>
                    <result name="stock_price" column="price"/>
                </statement>
            </dblookup>
            <log level="custom">
                <property name="text"
                          expression="fn:concat('Stock price - ',get-property('stock_price'))"/>
            </log>
            <send/>

        </out>

    </sequence>

</definitions>

Objective: Demonstrate the use of reusable database connection pools

Prerequisites:
Set up the database and Data sources according to the sample setup guide
Start the Synapse configuration numbered 363: i.e. synapse -sample 363
Start the Axis2 server and deploy the SimpleStockQuoteService if not already done

Runs the client as follows

ant stockquote -Daddurl=http://localhost:9000/services/SimpleStockQuoteService -Dtrpurl=http://localhost:8280/ -Dsymbol=IBM

Then the console output

INFO LogMediator text = ** Looking up from the Database ** ...
    INFO LogMediator text = Company ID - c1 ...
    INFO LogMediator text = ** Reporting to the Database ** ...
    INFO LogMediator text = ** Looking up from the Database ** ...
    INFO LogMediator text = Stock price - 183.3635460215262

This sample if functionally similar to sample 363 but uses a stored procedure to query the database instead of direct SQL statements. Prior to running this sample please follow the instructions given in the 'Setting up MySQL database server' section in the sample setup guide .

<definitions xmlns="http://ws.apache.org/ns/synapse"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">

    <sequence name="main">
        <in>
            <send>
                <endpoint>
                    <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
                </endpoint>
            </send>
        </in>

        <out>
            <log level="custom">
                <property name="text" value="** Reporting to the Database **"/>
            </log>

            <dbreport>
                <connection>
                    <pool>
                        <driver>com.mysql.jdbc.Driver</driver>
                        <url>jdbc:mysql://localhost:3306/synapsedb</url>
                        <user>user</user>
                        <password>password</password>
                    </pool>
                </connection>
                <statement>
                    <sql>call updateCompany(?,?)</sql>
                    <parameter xmlns:m0="http://services.samples"
                               xmlns:m1="http://services.samples/xsd"
                               expression="//m0:return/m1:last/child::text()" type="DOUBLE"/>
                    <parameter xmlns:m0="http://services.samples"
                               xmlns:m1="http://services.samples/xsd"
                               expression="//m0:return/m1:symbol/child::text()" type="VARCHAR"/>
                </statement>
            </dbreport>
            <log level="custom">
                <property name="text" value="** Looking up from the Database **"/>
            </log>
            <dblookup>
                <connection>
                    <pool>
                        <driver>com.mysql.jdbc.Driver</driver>
                        <url>jdbc:mysql://localhost:3306/synapsedb</url>
                        <user>user</user>
                        <password>password</password>
                    </pool>
                </connection>
                <statement>
                    <sql>call getCompany(?)</sql>
                    <parameter xmlns:m0="http://services.samples"
                               xmlns:m1="http://services.samples/xsd"
                               expression="//m0:return/m1:symbol/child::text()" type="VARCHAR"/>
                    <result name="stock_prize" column="price"/>
                </statement>
            </dblookup>
            <log level="custom">
                <property name="text"
                          expression="fn:concat('Stock Prize - ',get-property('stock_prize'))"/>
            </log>
            <send/>
        </out>
    </sequence>

</definitions>

Objective: Demonstrate the use of dblookup and dbreport mediators to execute a database Stored Procedures

Prerequisites:
Set up MySQL database server according to the sample setup guide
Edit the synapse_sample_364.xml configuration file and update the configuration with the appropriate database connection details
Start the Synapse configuration numbered 364: i.e. synapse -sample 364
Start the Axis2 server and deploy the SimpleStockQuoteService if not already done

Run the client as follows

ant stockquote -Daddurl=http://localhost:9000/services/SimpleStockQuoteService -Dtrpurl=http://localhost:8280/ -Dsymbol=IBM

Then you will get the following console output

INFO LogMediator text = ** Looking up from the Database ** ... 
INFO LogMediator text = Company ID - c1 ...  
INFO LogMediator text = Stock price - 183.3635460215262
<definitions xmlns="http://ws.apache.org/ns/synapse"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">

    <sequence name="main">
        <in>
            <throttle id="A">
                <policy>
                    <!-- define throttle policy -->
                    <wsp:Policy xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy"
                                xmlns:throttle="http://www.wso2.org/products/wso2commons/throttle">
                        <throttle:ThrottleAssertion>
                            <throttle:MaximumConcurrentAccess>10</throttle:MaximumConcurrentAccess>
                        </throttle:ThrottleAssertion>
                    </wsp:Policy>
                </policy>
                <onAccept>
                    <log level="custom">
                        <property name="text" value="**Access Accept**"/>
                    </log>
                    <send>
                        <endpoint>
                            <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
                        </endpoint>
                    </send>
                </onAccept>
                <onReject>
                    <log level="custom">
                        <property name="text" value="**Access Denied**"/>
                    </log>
                    <makefault response="true">
                        <code xmlns:tns="http://www.w3.org/2003/05/soap-envelope"
                              value="tns:Receiver"/>
                        <reason value="**Access Denied**"/>
                    </makefault>
                    <send/>
                    <drop/>
                </onReject>
            </throttle>
        </in>
        <out>
            <throttle id="A"/>
            <send/>
        </out>
    </sequence>

</definitions>

Objective: Demonstrate the use of throttle mediator for concurrency throttling

Prerequisites:
Deploy the SimpleStockQuoteService in sample Axis2 server and start it on port 9000
Start Synapse with the sample configuration 370 (i.e. synapse -sample 370)

Above configuration specifies a throttle mediator inside the in mediator. Therefore, all request messages directed to the main sequence will be subjected to throttling. Throttle mediator has 'policy', 'onAccept' and 'onReject' tags at top level. The 'policy' tag specifies the throttling policy for throttling messages. This sample policy only contains a component called "MaximumConcurrentAccess". This indicates the maximum number of concurrent requests that can pass through Synapse on a single unit of time. To test concurrency throttling, it is required to send concurrent requests to Synapse. If Synapse with above configuration, receives 20 requests concurrently from clients, then approximately half of those will succeed while the others being throttled. The client command to try this is as follows.

ant stockquote -Dsymbol=IBM -Dmode=quote -Daddurl=http://localhost:8280/

<definitions xmlns="http://ws.apache.org/ns/synapse"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">

    <sequence name="main">
        <in>
            <throttle id="A">
                <policy>
                    <!-- define throttle policy -->
                    <wsp:Policy xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy"
                                xmlns:throttle="http://www.wso2.org/products/wso2commons/throttle">
                        <throttle:ThrottleAssertion>
                            <wsp:All>
                                <throttle:ID throttle:type="IP">other</throttle:ID>
                                <wsp:ExactlyOne>
                                    <wsp:All>
                                        <throttle:MaximumCount>4</throttle:MaximumCount>
                                        <throttle:UnitTime>800000</throttle:UnitTime>
                                        <throttle:ProhibitTimePeriod wsp:Optional="true">10000
                                        </throttle:ProhibitTimePeriod>
                                    </wsp:All>
                                    <throttle:IsAllow>true</throttle:IsAllow>
                                </wsp:ExactlyOne>
                            </wsp:All>
                            <wsp:All>
                                <throttle:ID throttle:type="IP">192.168.8.200-192.168.8.222
                                </throttle:ID>
                                <wsp:ExactlyOne>
                                    <wsp:All>
                                        <throttle:MaximumCount>8</throttle:MaximumCount>
                                        <throttle:UnitTime>800000</throttle:UnitTime>
                                        <throttle:ProhibitTimePeriod wsp:Optional="true">10
                                        </throttle:ProhibitTimePeriod>
                                    </wsp:All>
                                    <throttle:IsAllow>true</throttle:IsAllow>
                                </wsp:ExactlyOne>
                            </wsp:All>
                            <wsp:All>
                                <throttle:ID throttle:type="IP">192.168.8.201</throttle:ID>
                                <wsp:ExactlyOne>
                                    <wsp:All>
                                        <throttle:MaximumCount>200</throttle:MaximumCount>
                                        <throttle:UnitTime>600000</throttle:UnitTime>
                                        <throttle:ProhibitTimePeriod wsp:Optional="true"/>
                                    </wsp:All>
                                    <throttle:IsAllow>true</throttle:IsAllow>
                                </wsp:ExactlyOne>
                            </wsp:All>
                            <wsp:All>
                                <throttle:ID throttle:type="IP">192.168.8.198</throttle:ID>
                                <wsp:ExactlyOne>
                                    <wsp:All>
                                        <throttle:MaximumCount>50</throttle:MaximumCount>
                                        <throttle:UnitTime>500000</throttle:UnitTime>
                                        <throttle:ProhibitTimePeriod wsp:Optional="true"/>
                                    </wsp:All>
                                    <throttle:IsAllow>true</throttle:IsAllow>
                                </wsp:ExactlyOne>
                            </wsp:All>
                        </throttle:ThrottleAssertion>
                    </wsp:Policy>
                </policy>
                <onAccept>
                    <log level="custom">
                        <property name="text" value="**Access Accept**"/>
                    </log>
                    <send>
                        <endpoint>
                            <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
                        </endpoint>
                    </send>
                </onAccept>
                <onReject>
                    <log level="custom">
                        <property name="text" value="**Access Denied**"/>
                    </log>
                    <makefault response="true">
                        <code xmlns:tns="http://www.w3.org/2003/05/soap-envelope"
                              value="tns:Receiver"/>
                        <reason value="**Access Denied**"/>
                    </makefault>
                    <send/>
                    <drop/>
                </onReject>
            </throttle>
        </in>
        <out>
            <throttle id="A"/>
            <send/>
        </out>
    </sequence>

</definitions>

Objective: Demonstrate the use of throttle mediator for restricting request counts

Prerequisites:
Deploy the SimpleStockQuoteService in sample Axis2 server and start it on port 9000
Start Synapse with the sample configuration 371 (i.e. synapse -sample 371)

Above configuration specifies a throttle mediator inside the in mediator. Therefore, all request messages directed to the main sequence will be subjected to throttling. Throttle mediator has policy, onAccept and onReject tags at the top level. Policy tag specifies the throttling policy to be applied for messages. It contains some IP address ranges and the maximum number of messages to be allowed for those ranges within a time period given in "UnitTime" tag. "ProhibitTimePeriod" tag specifies the time period to prohibit further requests after the received request count exceeds the specified time. Now run the client 5 times repetitively using the following command to see how throttling works.

ant stockquote -Dsymbol=IBM -Dmode=quote -Daddurl=http://localhost:8280/

For the first four requests you will get the quote prices for IBM as follows.

[java] Standard :: Stock price = $177.20143371883802

You will receive the following response for the fifth request.

[java] org.apache.axis2.AxisFault: **Access Denied**

Maximum number of requests within 800000 milliseconds is specified as 4 for any server (including localhost) other than the explicitly specified ones. Therefore, our fifth request is denied by the throttle mediator. You can verify this by looking at the Synapse console.

[HttpServerWorker-1] INFO  LogMediator - text = **Access Accept**
[HttpServerWorker-2] INFO  LogMediator - text = **Access Accept**
[HttpServerWorker-3] INFO  LogMediator - text = **Access Accept**
[HttpServerWorker-4] INFO  LogMediator - text = **Access Accept**
[HttpServerWorker-5] INFO  LogMediator - text = **Access Denied** 
<definitions xmlns="http://ws.apache.org/ns/synapse"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">

    <registry provider="org.apache.synapse.registry.url.SimpleURLRegistry">
        <!-- the root property of the simple URL registry helps resolve a resource URL as root + key -->
        <parameter name="root">file:repository/</parameter>
        <!-- all resources loaded from the URL registry would be cached for this number of milli seconds -->
        <parameter name="cachableDuration">150000</parameter>
    </registry>

    <sequence name="onAcceptSequence">
        <log level="custom">
            <property name="text" value="**Access Accept**"/>
        </log>
        <send>
            <endpoint>
                <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
            </endpoint>
        </send>
    </sequence>

    <sequence name="onRejectSequence" trace="enable">
        <log level="custom">
            <property name="text" value="**Access Denied**"/>
        </log>
        <makefault response="true">
            <code xmlns:tns="http://www.w3.org/2003/05/soap-envelope" value="tns:Receiver"/>
            <reason value="**Access Denied**"/>
        </makefault>
        <send/>
        <drop/>
    </sequence>

    <proxy name="StockQuoteProxy">
        <target>
            <inSequence>
                <throttle onReject="onRejectSequence" onAccept="onAcceptSequence" id="A">
                    <policy key="conf/sample/resources/policy/throttle_policy.xml"/>
                </throttle>
            </inSequence>
            <outSequence>
                <throttle id="A"/>
                <send/>
            </outSequence>
        </target>
        <publishWSDL uri="file:repository/conf/sample/resources/proxy/sample_proxy_1.wsdl"/>
    </proxy>

</definitions>

Objective: Use of both concurrency throttling and request rate based throttling

Prerequisites:
Deploy the SimpleStockQuoteService in sample Axis2 server and start it on port 9000
Start Synapse with the sample configuration 372 (i.e. synapse -sample 372)

Throttle policy is loaded from the ?throttle_policy. xml? . That policy contains merging policy from sample 370 and 371. To check the functionality, it requires to run a load test. The all enabled request from the concurrency throttling will be controlled by the access rate base throttling according to the policy.

Run the client as follows

ant stockquote -Daddurl=http://localhost:8280/services/StockQuoteProxy

You will get same results as in sample 371. If you run the load test, results will be different due to the effect of concurrency throttling.

Class mediator can be used to write your own custom mediation in Java and you have access to the SynapseMessageContext and to the full Synapse API in there. This is a useful extension mechanism within Synapse to extend its functionality. This class can contain fields for which you can assign values at runtime through the configuration.

<definitions xmlns="http://ws.apache.org/ns/synapse"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">

    <sequence name="fault">
        <makefault>
            <code xmlns:tns="http://www.w3.org/2003/05/soap-envelope" value="tns:Receiver"/>
            <reason value="Mediation failed."/>
        </makefault>
        <send/>
    </sequence>

    <sequence name="main" onError="fault">
        <in>
            <send>
                <endpoint name="stockquote">
                    <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
                </endpoint>
            </send>
        </in>
        <out>
            <class name="samples.mediators.DiscountQuoteMediator">
                <property name="discountFactor" value="10"/>
                <property name="bonusFor" value="5"/>
            </class>
            <send/>
        </out>
    </sequence>

</definitions>

Objective: Demonstrate the use of Class mediator to extend the mediation functionality

Prerequisites:
Make sure the synapse-samples-1.0.jar is in your class path (by default this jar is placed in the lib directory when installing Synapse)
Start Synapse with the sample configuration 380 (i.e. synapse -sample 380)
Start the sample Axis2 server and deploy the SimpleStockQuoteService.

In this configuration, Synapse hands over the request message to the specified endpoint, which sends it to the Axis2 server running on port 9000.

But the response message is passed through the class mediator before sending it back to the client. Two parameters named "discountFactor"

and "bonusFor" are passed to the instance mediator implementation class (i.e. samples.mediators.DiscountQuoteMediator) before each

invocation. Code of the mediator implementation class is shown below.

package samples.mediators;

import org.apache.synapse.MessageContext;
import org.apache.synapse.Mediator;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.soap.SOAPFactory;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.xml.namespace.QName;

public class DiscountQuoteMediator implements Mediator {

    private static final Log log = LogFactory.getLog(DiscountQuoteMediator.class);

    private String discountFactor="10";

    private String bonusFor="10";

    private int bonusCount=0;

    public DiscountQuoteMediator(){}

    public boolean mediate(MessageContext mc) {

        String price= mc.getEnvelope().getBody().getFirstElement().getFirstElement().
                getFirstChildWithName(new QName("http://services.samples/xsd","last")).getText();

        //converting String properties into integers
        int discount=Integer.parseInt(discountFactor);
        int bonusNo=Integer.parseInt(bonusFor);
        double currentPrice=Double.parseDouble(price);

        //discounting factor is deducted from current price form every response
        Double lastPrice = new Double(currentPrice - currentPrice * discount / 100);

        //Special discount of 5% offers for the first responses as set in the bonusFor property
        if (bonusCount <= bonusNo) {
            lastPrice = new Double(lastPrice.doubleValue() - lastPrice.doubleValue() * 0.05);
            bonusCount++;
        }

        String discountedPrice = lastPrice.toString();

        mc.getEnvelope().getBody().getFirstElement().getFirstElement().getFirstChildWithName
                (new QName("http://services.samples/xsd","last")).setText(discountedPrice);

        System.out.println("Quote value discounted.");
        System.out.println("Original price: " + price);
        System.out.println("Discounted price: " + discountedPrice);

        return true;
    }

    public String getType() {
        return null;
    }

    public void setTraceState(int traceState) {
        traceState = 0;
    }

    public int getTraceState() {
        return 0;
    }

    public void setDiscountFactor(String discount) {
        discountFactor=discount;
    }

    public String getDiscountFactor() {
        return discountFactor;
    }

    public void setBonusFor(String bonus){
        bonusFor=bonus;
    }

    public String getBonusFor(){
        return bonusFor;
    }
}

All classes developed for class mediation should implement the Mediator interface, which contains the mediate(...) method. mediate(...) method of the above class is invoked for each response message mediated through the main sequence, with the message context of the current message as the parameter. All details of the message including the SOAP headers, SOAP body and properties of the context hierarchy can be accessed from the message context. In this sample, the body of the message is retrieved and the discount percentage is subtracted from the quote price. If the quote request number is less than the number specified in the "bonusFor" property in the configuration, a special discount is given.

Now run the client using the following command.

ant stockquote -Dsymbol=IBM -Dmode=quote -Daddurl=http://localhost:8280

You will see the below output in the client console with the discounted quote value.

[java] Standard :: Stock price = $138.77458254967408

Now check the console running Synapse. You will see the original value and the discounted value for the requested quote as follows.

Quote value discounted.
Original price: 162.30945327447262
Discounted price: 138.77458254967408

<definitions xmlns="http://ws.apache.org/ns/synapse"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">

    <proxy name="JMSBinaryProxy" transports="jms">
        <target inSequence="BINARY_CBR_SEQ"/>
    </proxy>

    <sequence name="BINARY_CBR_SEQ">
        <in>
            <log level="full"/>
            <property action="set" name="OUT_ONLY" value="true"/>
            <class name="samples.mediators.BinaryExtractMediator">
                <property name="offset" value="11"/>
                <property name="length" value="4"/>
                <property name="variableName" value="symbol"/>
                <property name="binaryEncoding" value="utf-8"/>
            </class>
            <log level="custom">
                <property name="symbol" expression="get-property('symbol')"/>
            </log>
            <switch source="get-property('symbol')">
                <case regex="GOOG">
                    <send>
                        <endpoint>
                            <address
                                    uri="jms:/dynamicTopics/mdd.GOOG?transport.jms.ConnectionFactoryJNDIName=TopicConnectionFactory&java.naming.factory.initial=org.apache.activemq.jndi.ActiveMQInitialContextFactory&java.naming.provider.url=tcp://localhost:61616&transport.jms.DestinationType=topic"/>
                        </endpoint>
                    </send>
                </case>
                <case regex="MSFT">
                    <send>
                        <endpoint>
                            <address
                                    uri="jms:/dynamicTopics/mdd.MSFT?transport.jms.ConnectionFactoryJNDIName=TopicConnectionFactory&java.naming.factory.initial=org.apache.activemq.jndi.ActiveMQInitialContextFactory&java.naming.provider.url=tcp://localhost:61616&transport.jms.DestinationType=topic"/>
                        </endpoint>
                    </send>
                </case>
                <default/>
            </switch>
        </in>
    </sequence>

</definitions>

Objective: Demonstrate on CBR a message with binary payload

Prerequisites:
Make sure the synapse-samples-1.0.jar is in your class path (by default this jar is placed in the lib directory when installing Synapse)
Configure JMS transport using ActiveMQ (refer Sample Configuration Guide )
Start Synapse with the sample configuration 381 (i.e. synapse -sample 381)

In this configuration, a proxy has configured to accept incoming JMS messages. JMS messages contains a binary payload. User configure the offset, length, binary encoding of the text literal that it need to use for CBR. And a variable name to set the decoded value as a property. Configuration simply route the messages based on the text to different endpoints.

A JMS producer and two instances of a consumer used to demonstrate the CBR functionality.

Now run the first consumer using the following command.

ant mddconsumer -Djms_topic=mdd.MSFT

Now run the second consumer using the following command.

ant mddconsumer -Djms_topic=mdd.GOOG

Now run the market data producer to genenrate market data for symbol 'MSFT' using the following command.

ant mddproducer -Dsymbol=MSFT

Now run the market data producer to genenrate market data for symbol 'GOOG' using the following command.

ant mddproducer -Dsymbol=GOOG

You will see the below output in the client console(s) based on the symbol.

mddconsumer:
     [java]  Market data recived for symbol : topic://mdd.MSFT
     [java]  Market data recived for symbol : topic://mdd.MSFT

<definitions xmlns="http://ws.apache.org/ns/synapse"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">

    <!-- the SimpleURLRegistry allows access to a URL based registry (e.g. file:/// or http://) -->
    <registry provider="org.apache.synapse.registry.url.SimpleURLRegistry">
        <!-- the root property of the simple URL registry helps resolve a resource URL as root + key -->
        <parameter name="root">file:repository/conf/sample/resources/</parameter>
        <!-- all resources loaded from the URL registry would be cached for this number of milli seconds -->
        <parameter name="cachableDuration">15000</parameter>
    </registry>

    <localEntry key="xquery-key-req"
                src="file:repository/conf/sample/resources/xquery/xquery_req.xq"/>

    <proxy name="StockQuoteProxy">
        <target>
            <inSequence>
                <property name="body" expression="$body/child::*[position()=1]"/>
                <xquery key="xquery-key-req">
                    <variable name="payload" type="ELEMENT"/>
                </xquery>
                <send>
                    <endpoint>
                        <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
                    </endpoint>
                </send>
            </inSequence>
            <outSequence>
                <out>
                    <xquery key="xquery/xquery_res.xq">
                        <variable name="payload" type="ELEMENT"/>
                        <variable xmlns:m0="http://services.samples"
                                  xmlns:ax21="http://services.samples/xsd" name="code" type="STRING"
                                  expression="self::node()//m0:return/ax21:symbol/child::text()"/>
                        <variable xmlns:m0="http://services.samples"
                                  xmlns:ax21="http://services.samples/xsd" name="price"
                                  type="DOUBLE"
                                  expression="self::node()//m0:return/ax21:last/child::text()"/>
                    </xquery>
                    <send/>
                </out>
            </outSequence>
        </target>
        <publishWSDL uri="file:repository/conf/sample/resources/proxy/sample_proxy_1.wsdl"/>
    </proxy>

</definitions>

Objective: Introduction transformation using XQuery mediator

Prerequisites:
Start the Synapse configuration numbered 390: i.e. synapse -sample 390
Start the Axis2 server and deploy the SimpleStockQuoteService if not already done.

This example uses the XQuery mediator to perform transformations. This sample behaves the same as sample number 8 and the only difference is that this sample uses XQuery instead of XSLT for transformation.

Execute the custom quote client as 'ant stockquote -Dmode=customquote ...'

ant stockquote -Daddurl=http://localhost:8280/services/StockQuoteProxy -Dmode=customquote 

<definitions xmlns="http://ws.apache.org/ns/synapse"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">

    <!-- the SimpleURLRegistry allows access to a URL based registry (e.g. file:/// or http://) -->
    <registry provider="org.apache.synapse.registry.url.SimpleURLRegistry">
        <!-- the root property of the simple URL registry helps resolve a resource URL as root + key -->
        <parameter name="root">file:repository/conf/sample/resources/</parameter>
        <!-- all resources loaded from the URL registry would be cached for this number of milli seconds -->
        <parameter name="cachableDuration">15000</parameter>
    </registry>

    <proxy name="StockQuoteProxy">
        <target>
            <inSequence>
                <send>
                    <endpoint>
                        <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
                    </endpoint>
                </send>
            </inSequence>
            <outSequence>
                <out>
                    <xquery key="xquery/xquery_commisson.xq">
                        <variable name="payload" type="ELEMENT"/>
                        <variable name="commission" type="ELEMENT" key="misc/commission.xml"/>
                    </xquery>
                    <send/>
                </out>
            </outSequence>
        </target>
        <publishWSDL uri="file:repository/conf/sample/resources/proxy/sample_proxy_1.wsdl"/>
    </proxy>

</definitions>

Objective: Demonstrate the use of XQuery mediator to import external XML documents to the XQuery engine

Prerequisites:
Deploy the SimpleStockQuoteService in sample Axis2 server and start it on port 9000
Start Synapse with the sample configuration 391 (i.e. synapse -sample 391).

In this sample, data from commission.xml document is used inside XQuery . The stock quote price from the response and commission from the commission.xml document will be added and given as a new price .

Invoke the client as follows.

ant stockquote -Daddurl=http://localhost:8280/services/StockQuoteProxy
<definitions xmlns="http://ws.apache.org/ns/synapse"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">

    <proxy name="SplitAggregateProxy">
        <target>
            <inSequence>
                <iterate xmlns:m0="http://services.samples" expression="//m0:getQuote/m0:request"
                         preservePayload="true" attachPath="//m0:getQuote">
                    <target>
                        <sequence>
                            <send>
                                <endpoint>
                                    <address
                                            uri="http://localhost:9000/services/SimpleStockQuoteService"/>
                                </endpoint>
                            </send>
                        </sequence>
                    </target>
                </iterate>
            </inSequence>
            <outSequence>
                <aggregate>
                    <onComplete xmlns:m0="http://services.samples"
                                expression="//m0:getQuoteResponse">
                        <send/>
                    </onComplete>
                </aggregate>
            </outSequence>
        </target>
    </proxy>

</definitions>

Objective: Demonstrate the use of Iterate mediator to split the messages in to parts and process them asynchronously and then aggregate the responses coming in to Synapse

Prerequisites:
Deploy the SimpleStockQuoteService in sample Axis2 server and start it on port 9000
Start Synapse with the sample configuration 400 (i.e. synapse -sample 400).

In this sample, the message sent to Synapse is comprised of a number of elements of the same type. When Synapse receives this message it will iterate through those elements and then will send to the specified endpoint. When all the responses appear to Synapse then those messages will be aggregated to form the resultant response and will send back to the client.

Invoke the client as follows.

ant stockquote -Daddurl=http://localhost:8280/services/SplitAggregateProxy -Ditr=4

Cache mediator can be used to utilize the network bandwidth, to protect the backend service from being loaded with the same type of requests like browser refresh actions and also to speed up the execution of the web service. This mediator should be used with sense, because it is not applicable for each and every service (for example services with dynamic responses for a particular release)

<definitions xmlns="http://ws.apache.org/ns/synapse"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">

    <sequence name="main">
        <in>
            <cache timeout="20" scope="per-host" collector="false"
                   hashGenerator="org.wso2.caching.digest.DOMHASHGenerator">
                <implementation type="memory" maxSize="100"/>
            </cache>
            <send>
                <endpoint>
                    <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
                </endpoint>
            </send>
        </in>
        <out>
            <cache collector="true"/>
            <send/>
        </out>
    </sequence>

</definitions>

Objective: Demonstrate the use of Cache mediator in order to cache the response and use that cached response as the response for an identical xml request

Prerequisites:
Deploy the SimpleStockQuoteService in sample Axis2 server and start it on port 9000
Start Synapse with the sample configuration 420 (i.e. synapse -sample 420)

In this sample, the message sent to Synapse is checked for an existing cached response by calculating the hash value of the request. If there is a cache hit in Synapse then this request will not be forwarded to the actual service, rather Synapse responds to the client with the cached response. In case of a cache miss that particular message will be forwarded to the actual service and caches that response in the out path for the use of consecutive requests of the same type.

To observe this behaviour, invoke the client as follows.

ant stockquote -Dtrpurl=http://localhost:8280/

You could notice that if you send more than one requests within 20 seconds only the first request is forwarded to the actual service, and the rest of the requests will be served by the cache inside Synapse. You could observe this by looking at the printed line of the axis2 server, as well as by observing a constant rate as the response to the client instead of the random rate, which changes by each and every 20 seconds.

The Callout mediator calls the given service URL with the request message which is given by the source attribute, waits for the response and attaches the received response to the destination which is given by the target attribute. Both the source and the target can be a key or an XPath. In the case of the source, this key refers to either a message context property or to a local entry. For the target, this key refers to a message context property only.

<definitions xmlns="http://ws.apache.org/ns/synapse"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">

    <sequence name="main">
        <callout serviceURL="http://localhost:9000/services/SimpleStockQuoteService"
                 action="urn:getQuote">
            <source xmlns:s11="http://schemas.xmlsoap.org/soap/envelope/"
                    xmlns:s12="http://www.w3.org/2003/05/soap-envelope"
                    xpath="s11:Body/child::*[fn:position()=1] | s12:Body/child::*[fn:position()=1]"/>
            <target xmlns:s11="http://schemas.xmlsoap.org/soap/envelope/"
                    xmlns:s12="http://www.w3.org/2003/05/soap-envelope"
                    xpath="s11:Body/child::*[fn:position()=1] | s12:Body/child::*[fn:position()=1]"/>
        </callout>
        <property name="RESPONSE" value="true"/>
        <header name="To" action="remove"/>
        <send/>
        <drop/>
    </sequence>

</definitions>

Objective: Demonstrate the use of the callout mediator for the synchronized web service invocation

Prerequisites:
Deploy the SimpleStockQuoteService in sample Axis2 server and start it on port 9000
Start Synapse with the sample configuration 430 (i.e. synapse -sample 430)

In this sample, the callout mediator does the direct service invocation to the StockQuoteService using the client request, gets the response and sets it as the first child of the SOAP message body. Then using the send mediator, the message is sent back to the client.

Invoke the client as follows.

ant stockquote -Daddurl=http://localhost:9000/services/SimpleStockQuoteService -Dtrpurl=http://localhost:8280/
<definitions xmlns="http://ws.apache.org/ns/synapse"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">

    <proxy name="JSONProxy" transports="http https">
        <target>
            <endpoint>
                <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
            </endpoint>
            <inSequence>
                <log level="full"/>
                <xslt key="in_transform"/>
                <property name="messageType" scope="axis2" value="text/xml"/>
            </inSequence>
            <outSequence>
                <log level="full"/>
                <xslt key="out_transform"/>
                <property name="messageType" scope="axis2" value="application/json"/>
                <send/>
            </outSequence>
        </target>
    </proxy>

    <localEntry key="in_transform">
        <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                        xmlns:fn="http://www.w3.org/2005/02/xpath-functions"
                        xmlns:m0="http://services.samples" version="2.0" exclude-result-prefixes="m0 fn">
            <xsl:output method="xml" omit-xml-declaration="yes" indent="yes"/>
            <xsl:template match="*">
                <xsl:element name="{local-name()}" namespace="http://services.samples">
                    <xsl:copy-of select="attribute::*"/>
                    <xsl:apply-templates/>
                </xsl:element>
            </xsl:template>
        </xsl:stylesheet>
    </localEntry>

    <localEntry key="out_transform">
        <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
            <xsl:output method="xml" version="1.0" encoding="UTF-8"/>
            <xsl:template match="*">
                <xsl:element name="{local-name()}">
                    <xsl:apply-templates/>
                </xsl:element>
            </xsl:template>
        </xsl:stylesheet>
    </localEntry>

</definitions>

Objective: Demonstrate the ability to switch between JSON and XML/SOAP content interchange formats

Prerequisites:
Deploy the SimpleStockQuoteService in sample Axis2 server and start it on port 9000
Setup Synapse and the sample Axis2 client for JSON (Refer Synapse Samples Setup Guide for details)
Start Synapse with the sample configuration 440 (i.e. synapse -sample 440)

Invoke the JSON client as follows.

ant jsonclient -Daddurl=http://localhost:9000/services/SimpleStockQuoteService -Dtrpurl=http://localhost:8280/services/JSONProxy

JSON client will send a stockquote request to Synapse using the JSON content interchange format. Synapse will trnasform it into a SOAP request and forward to the Axis2 server. The SOAP response from the Axis2 server will be converted into a JSON message and sent back to the JSON client.

You may use a tool like TCPMon to monitor the JSON requests sent over the wire. A sample JSON request and response is shown below:

{"getQuote":{"request":{"symbol":"IBM"}}}
{"getQuoteResponse":{"return":{"change":3.853593376681722,"earnings":12.802850763714854,"high":67.92488310190126,"last":66.14619264746406,"lastTradeTimestamp":"Mon Aug 23 16:48:40 IST 2010","low":-66.04000424423522,"marketCap":-9334516.42324327,"name":"IBM Company","open":-64.61950137150009,"peRatio":-19.78600441437058,"percentageChange":5.411779328273005,"prevClose":71.2075112994578,"symbol":"IBM","volume":16842}}}
<definitions xmlns="http://ws.apache.org/ns/synapse"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">

    <sequence name="main">
        <in>
            <rewrite>
                <rule>
                    <action type="replace" regex="soap" value="services" fragment="path"/>
                </rule>
            </rewrite>
            <send/>
        </in>
        <out>
            <send/>
        </out>
    </sequence>

</definitions>

Objective: Demonstrate the basic functions of the URL rewrite mediator

Prerequisites:
Deploy the SimpleStockQuoteService in sample Axis2 server and start it on port 9000
Start Synapse with the sample configuration 450 (i.e. synapse -sample 450)

Invoke the Axis2 client as follows.

ant stockquote -Dtrpurl=http://localhost:8280 -Daddurl=http://localhost:9000/soap/SimpleStockQuoteService

Note that the address URL of the client request contains the context 'soap'. But in the Axis2 server all the services are deployed under a context named 'services' by default. Synapse will rewrite the To header of the request by replacing the 'soap' context with 'services. Hence the request will be delivered to the Axis2 server and the Axis2 client will receive a valid response.

<definitions xmlns="http://ws.apache.org/ns/synapse"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">

    <sequence name="main">
        <in>
            <rewrite>
                <rule>
                    <condition>
                        <and>
                            <equal type="url" source="host" value="localhost"/>
                            <not>
                                <equal type="url" source="protocol" value="https"/>
                            </not>
                        </and>
                    </condition>
                    <action fragment="protocol" value="https"/>
                    <action fragment="port" value="9002"/>
                </rule>
            </rewrite>
            <send/>
        </in>
        <out>
            <send/>
        </out>
    </sequence>

</definitions>

Objective: Demonstrate the ability of the URL rewrite mediator to evaluate conditions on messages and perform rewrites based on the results.

Prerequisites:
Deploy the SimpleStockQuoteService in sample Axis2 server and start it on port 9000
Start Synapse with the sample configuration 451 (i.e. synapse -sample 451)

Invoke the Axis2 client and send some requests to Synapse with different address URL values. If the address URL value contains localhost as the hostname and https as the protocol prefix, Synapse will route the message as it is. But if the hostname is localhost and the protocol is not https, Synapse will rewrite the URL by setting https as the protocol. The port number will also be set to the HTTPS port of the Axis2 server.

The condition evaluation feature is provided by the Synapse evaluator framework. Currently one can evaluate expressions on URL values, query parameters, transport headers, properties and SOAP envelope content using this framework. Hence URL rewriting can be done based on any of these aspects.

<definitions xmlns="http://ws.apache.org/ns/synapse"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">

    <sequence name="main">
        <in>
            <property name="http.port" value="9000"/>
            <property name="https.port" value="9002"/>
            <rewrite>
                <rule>
                    <action fragment="host" value="localhost"/>
                    <action fragment="path" type="prepend" value="/services"/>
                </rule>
                <rule>
                    <condition>
                        <equal type="url" source="protocol" value="http"/>
                    </condition>
                    <action fragment="port" xpath="get-property('http.port')"/>
                </rule>
                <rule>
                    <condition>
                        <equal type="url" source="protocol" value="https"/>
                    </condition>
                    <action fragment="port" xpath="get-property('https.port')"/>
                </rule>
            </rewrite>
            <log level="full"/>
            <send/>
        </in>
        <out>
            <send/>
        </out>
    </sequence>

</definitions>

Objective: Demonstrate the ability of the URL rewrite mediator to perform rewrites based on multiple rules.

Prerequisites:
Deploy the SimpleStockQuoteService in sample Axis2 server and start it on port 9000
Start Synapse with the sample configuration 452 (i.e. synapse -sample 452)

Invoke the Axis2 client as follows.

ant stockquote -Dtrpurl=http://localhost:8280 -Daddurl=http://test.com/SimpleStockQuoteService

The provided address URL does not contain a port number and the context. The URL rewrite mediator will replace the hostname to be 'localhost' and add the context '/services' to the path. Then it will add the appropriate port number to the URL by looking at the protocol prefix. Ultimately the service request will be routed the sample Axis2 server and the client will receive a valid response.

Another important aspect shown by this sample is the ability of the URL rewirte mediator to obtain the necessary values by executing XPath expressions. The port numbers are calculated by executing an XPath on the messages.

<definitions xmlns="http://ws.apache.org/ns/synapse"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">

    <registry provider="org.apache.synapse.registry.url.SimpleURLRegistry">
        <parameter name="root">file:repository/conf/sample/resources/</parameter>
        <parameter name="cachableDuration">15000</parameter>
    </registry>

    <sequence name="main">
        <!--Setting the Spring Mediator and its Spring Beans xml file location -->
        <!--Note that springtest is the bean id used in springCustomLogger.xml -->
        <spring bean="springtest" key="spring/springCustomLogger.xml"/>
        <send/>
    </sequence>

</definitions>

springCustomLogger.xml file

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC  "-//SPRING//DTD BEAN//EN"
    "http://www.springframework.org/dtd/spring-beans.dtd">

<beans>

   <bean id="springtest" class="samples.mediators.extentions.SpringCustomLogger" singleton="false">
	   <property name="userName"><value>"Synapse User"</value></property>
	   <property name="email"><value>"usr@synapse.org"</value></property>
   </bean>

</beans>

Objective: Demonstrate How to initialize and use a SpringBean as a mediator

Prerequisites:
Deploy the SimpleStockQuoteService in sample Axis2 server and start it on port 9000
Start Synapse with the sample configuration 460 (i.e. synapse -sample 460)

In this sample, the Spring Bean, SpringCustomLogger get initialized using springCustomLogger.xml file and then it log the message Id.

Invoke the client as follows.

ant stockquote -Daddurl=http://localhost:9000/services/SimpleStockQuoteService -Dtrpurl=http://localhost:8280/

If you have enabled logging for the samples.mediators package you will see an output similar to the following on the console:

2010-09-26 20:46:57,946 [-] [HttpServerWorker-1]  INFO SpringCustomLogger Starting Spring Meditor
2010-09-26 20:46:57,946 [-] [HttpServerWorker-1]  INFO SpringCustomLogger Bean in Initialized with User:["Synapse User"]
2010-09-26 20:46:57,946 [-] [HttpServerWorker-1]  INFO SpringCustomLogger E-MAIL:["usr@synapse.org"]
2010-09-26 20:46:57,946 [-] [HttpServerWorker-1]  INFO SpringCustomLogger Massage Id:  urn:uuid:383FA8B27D7CC549D91285514217720
2010-09-26 20:46:57,946 [-] [HttpServerWorker-1]  INFO SpringCustomLogger Logged....
<definitions xmlns="http://ws.apache.org/ns/synapse"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">

    <eventSource name="SampleEventSource">
        <subscriptionManager
                class="org.apache.synapse.eventing.managers.DefaultInMemorySubscriptionManager">
            <!--property name="registryURL" value="http://localhost:8180/wso2registry"/>
          <property name="username" value="admin"/>
          <property name="password" value="admin"/-->
            <property name="topicHeaderName" value="Topic"/>
            <    property name="topicHeaderNS" value="http://apache.org/aip"/>
        <    /subscriptionManager>
    </eventSource>

    <sequence name="PublicEventSource">
        <log level="full"/>
        <eventPublisher eventSourceName="SampleEventSource"/>
    </sequence>

    <proxy name="EventingProxy">
        <target inSequence="PublicEventSource"/>
    </proxy>

</definitions>

Objective: Demonstrate the use of the Eventing functionality built with Synapse

Prerequisites:
Deploy the SimpleStockQuoteService in sample Axis2 server and start it on port 9000
Start Synapse with the sample configuration 500 (i.e. synapse -sample 500)

In this sample, the event source creted based on the configuration. Event subscriber subscribes for the events, Event sender publish events and the SimpleStockQuoteService act as the Event Sink.

Invoke the client (Subscriber) as follows:

ant eventsubscriber

This will create a new subscription with the SimpleStockQuoteService deployed on the sample Axis2 server acting as the sink: whenever a new event is published, SimpleStockQuoteService will receive a message with that event. You should see a message like this:

[java] Subscription identifier: urn:uuid:6989F66706E73C69F5259116575749162017010321

You will need this identifier to modify the subscription in the next steps below. Now, invoke the client (Sender) as follows:

ant eventsender

This will send a placeOrder message to the EventingProxy. You should see this message in the Synapse logs. Note the presence of the following SOAP header in the request:

<aip:Topic xmlns:aip="http://apache.org/aip">synapse/event/test</aip:Topic>

Since there is a single subscription with SimpleStockQuoteService as the sink, Synapse will send the message to the sample Axis2 server and you should see the following message in its logs:

Accepted order for : 1000 stocks of GOOG at $ 10.1

To get the current status of the subscription, invoke the client as follows:

ant eventsubscriber -Dmode=getstatus -Didentifier=<identifier>

To renew the subscription, invoke the client as follows:

ant eventsubscriber -Dmode=renew -Didentifier=<identifier>
 -Dexpires=2009-12-31T21:07:00.000-08:00

Finally, in order to unsubscribe, use the following command:

ant eventsubscriber -Dmode=unsubscribe -Didentifier=<identifier>
<definitions xmlns="http://ws.apache.org/ns/synapse"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">

    <eventSource name="SampleEventSource">
        <subscriptionManager
                class="org.apache.synapse.eventing.managers.DefaultInMemorySubscriptionManager">
            <!--property name="registryURL" value="http://localhost:8180/wso2registry"/>
          <property name="username" value="admin"/>
          <property name="password" value="admin"/-->
            <property name="topicHeaderName" value="Topic"/>
            <property name="topicHeaderNS" value="http://apache.org/aip"/>
        </subscriptionManager>
        <subscription id="mysub1">
            <filter source="synapse/event/test"
                    dialect="http://synapse.apache.org/eventing/dialect/topicFilter"/>
            <endpoint>
                <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
            </endpoint>
        </subscription>
        <subscription id="mysub2">
            <filter source="synapse/event/test"
                    dialect="http://synapse.apache.org/eventing/dialect/topicFilter"/>
            <endpoint>
                <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
            </endpoint>
            <expires>2020-06-27T21:07:00.000-08:00</expires>
        </subscription>
    </eventSource>

    <sequence name="PublicEventSource">
        <log level="full"/>
        <eventPublisher eventSourceName="SampleEventSource"/>
    </sequence>

    <proxy name="EventingProxy">
        <target inSequence="PublicEventSource"/>
    </proxy>

</definitions>

Objective: Demonstrate static subscription capability of Synapse

Prerequisites:
Deploy the SimpleStockQuoteService in sample Axis2 server and start it on port 9000
Start Synapse with the sample configuration 501 (i.e. synapse -sample 501)

In this sample, two static subscriptions created by providing the SimpleStockQuoteService as the event sink.

Invoke the client (Sender) as follows.

ant eventsender

Event sender will send the events to the static subscriptions

 

<definitions xmlns="http://ws.apache.org/ns/synapse"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">

    <eventSource name="SampleEventSource">
        <subscriptionManager
                class="org.apache.synapse.eventing.managers.DefaultInMemorySubscriptionManager">
            <!--property name="registryURL" value="http://localhost:8180/wso2registry"/>
          <property name="username" value="admin"/>
          <property name="password" value="admin"/-->
            <property name="topicHeaderName" value="Topic"/>
            <property name="topicHeaderNS" value="http://apache.org/aip"/>
        </subscriptionManager>
        <subscription id="mysub1">
            <filter source="synapse/event/test"
                    dialect="http://synapse.apache.org/eventing/dialect/topicFilter"/>
            <endpoint>
                <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
            </endpoint>
        </subscription>
    </eventSource>

    <sequence name="PublicEventSource">
        <log level="full"/>
        <xslt key="xslt-key-req"/>
        <log level="full"/>
        <eventPublisher eventSourceName="SampleEventSource"/>
    </sequence>

    <proxy name="EventingProxy">
        <target inSequence="PublicEventSource"/>
    </proxy>

    <localEntry key="xslt-key-req"
                src="file:repository/conf/sample/resources/transform/transform_eventing.xslt"/>

</definitions>

Objective: Demonstrate the mediation capability of events before publishsing to event sink.

Prerequisites:
Deploy the SimpleStockQuoteService in sample Axis2 server and start it on port 9000
Start Synapse with the sample configuration 502 (i.e. synapse -sample 502)

In this sample, the event (order request) transform to a new order with different namesapce using XSLT mediator.

Invoke the client (Sender) as follows.

ant eventsender

Event publish after transformation.

         synapse_sample_600.xml
            |-- endpoints
            |   `-- foo.xml
            |-- events
            |   `-- event1.xml
            |-- local-entries
            |   `-- bar.xml
            |-- proxy-services
            |   |-- proxy1.xml
            |   |-- proxy2.xml
            |   `-- proxy3.xml
            |-- registry.xml
            |-- sequences
            |   |-- custom-logger.xml
            |   |-- fault.xml
            |   `-- main.xml
            |-- synapse.xml
            `-- tasks
                `-- task1.xml

       

Objective: Demonstrate the ability to construct the Synapse configuration from a file hierarchy

Prerequisites:
Deploy the SimpleStockQuoteService in sample Axis2 server and start it on port 9000
Start Synapse with the sample configuration 600 (i.e. synapse -sample 600)

Go to the SYNAPSE_HOME/repository/conf/sample directory and locate the subdirectory named synapse_sample_600.xml within it. When Synapse is started with the sample configuration 600, Synapse will load the configuration from this directory. You will find a number of subdirectories and a set of XML files in each of those directories. Synapse will parse all the XML files in this file hierarchy and construct the full Synapse configuration at startup. As a result when this sample is executed Synapse will start with four proxy services, several sequences, a task, an event source and some endpoint and local entry definitions.

The names of the subdirectories (eg: proxy-services, sequences, endpoints) are fixed and hence cannot be changed. Also the registry definition should go into a file named registry.xml which resides at the top level of the file hierarchy. It can also be specified in the synapse.xml file at top level. This synapse.xml file can include any item that can be normally defined in a synapse.xml file. The files which define proxy services, sequences, endpoints etc can have any name. These configuration files must have the .xml extension at the end of the name. Synapse will ignore any files which do not have the .xml extension.

None of the directories and files in the sample file hierachy are mandatory. You can leave entire directories out if you do not need them. For example if your configuration does not contain any proxy services you can leave the subdirectory named proxy-services out.

To use this feature you should simply pass a path to an existing directory when starting the Synapse server. The SynapseServer class which is responsible for starting the server accepts a file path as an argument from where to load the configuration. Generally we pass the path to the synapse.xml file as the value of this argument. If you pass a directory path instead, Synapse configuration will be loaded from the specified directory. Note the following line on the console when Synapse is loading the configuration from a file hierarchy.

2009-08-04 14:14:42,489 [-] [main]  INFO SynapseConfigurationBuilder Loaded Synapse configuration from the directory hierarchy at : /home/synapse/repository/conf/sample/synapse_sample_600.xml

This feature comes in handy when managing large Synapse configurations. It is easier to maintain a well structured file hierarchy than managing one large flat XML file.

Objective: Demonstrate the ability to monitor the Synapse configuration at runtime using the SynapseObserver interface

Open the synapse.properties file in the SYNAPSE_HOME/repository/conf directory using a text editor and uncomment the line which defines the simple logging Synapse observer.

synapse.observers=samples.userguide.SimpleLoggingObserver

Open the log4j.properties file in the SYNAPSE_HOME/lib directory and uncomment the line which sets the INFO log level to the samples.userguide package.

log4j.category.samples.userguide=INFO

Start Synapse using any of the sample configurations. The SimpleLoggingObserver will capture events that occur while constructing the Synapse configuration and log them on the console as follows.

 2009-08-06 14:30:24,578 [-] [main]  INFO SimpleLoggingObserver Simple logging observer initialized...Capturing Synapse events...
 2009-08-06 14:30:24,604 [-] [main]  INFO SimpleLoggingObserver Endpoint : a3 was added to the Synapse configuration successfully
 2009-08-06 14:30:24,605 [-] [main]  INFO SimpleLoggingObserver Endpoint : a2 was added to the Synapse configuration successfully
 2009-08-06 14:30:24,606 [-] [main]  INFO SimpleLoggingObserver Endpoint : null was added to the Synapse configuration successfully
 2009-08-06 14:30:24,611 [-] [main]  INFO SimpleLoggingObserver Local entry : a1 was added to the Synapse configuration successfully
 2009-08-06 14:30:24,649 [-] [main]  INFO SimpleLoggingObserver Proxy service : StockQuoteProxy2 was added to the Synapse configuration successfully
 2009-08-06 14:30:24,661 [-] [main]  INFO SimpleLoggingObserver Proxy service : StockQuoteProxy1 was added to the Synapse configuration successfully
 2009-08-06 14:30:24,664 [-] [main]  INFO SimpleLoggingObserver Sequence : main was added to the Synapse configuration successfully
 2009-08-06 14:30:24,701 [-] [main]  INFO SimpleLoggingObserver Sequence : fault was added to the Synapse configuration successfully

The SimpleLoggingObserver is implemented as follows. It does not override any of the event handler implementations in the AbstractSynapseObserver class. The AbstractSynapseObserver logs all the received events by default.

    package samples.userguide;

    import org.apache.synapse.config.AbstractSynapseObserver;

    public class SimpleLoggingObserver extends AbstractSynapseObserver {

        public SimpleLoggingObserver() {
            super();
            log.info("Simple logging observer initialized...Capturing Synapse events...");
        }
    }

Refer Synapse Synapse Extending Guide for more details on developing Synapse observers.

<definitions xmlns="http://ws.apache.org/ns/synapse"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">

    <priorityExecutor name="exec">
        <queues>
            <queue size="100" priority="1"/>
            <queue size="100" priority="10"/>
        </queues>
    </priorityExecutor>

    <proxy name="StockQuoteProxy">
        <target>
            <inSequence>
                <filter source="$trp:priority" regex="1">
                    <then>
                        <enqueue priority="1" sequence="priority_sequence" executor="exec"/>
                    </then>
                    <else>
                        <enqueue priority="10" sequence="priority_sequence" executor="exec"/>
                    </else>
                </filter>
            </inSequence>
            <outSequence>
                <send/>
            </outSequence>
        </target>
        <publishWSDL uri="file:repository/conf/sample/resources/proxy/sample_proxy_1.wsdl"/>
    </proxy>

    <sequence name="priority_sequence">
        <log level="full"/>
        <send>
            <endpoint>
                <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
            </endpoint>
        </send>
    </sequence>

</definitions>

Objective: Demonstrate the priority based mediation capability of synapse.

Prerequisites:
Deploy the SimpleStockQuoteService in sample Axis2 server and start it on port 9000. Priority is applied only when synapse is loaded with enough messages to consume its core number of threads. So to observe the priority based mediation, it is required to use a load testing tool like JMeter, SOAP UI or Apache bench.
Start Synapse with the sample configuration 650 (i.e. synapse -sample 650)

In this sample, client should send a HTTP header that specifies the priority of the message.This header name is priority. This header is retrieved in the synapse configuration using the $trp:priority XPath expression. Then it is matched against the value 1. If it has the value 1, message is executed with priority 1. Otherwise the message is executed with priority 10.

Here are two sample XML files that can be used to invoke the service using a tool like JMeter, or Ab. For SOAP UI, user can use the WSDL repository/conf/sample/resources/proxy/sample_proxy_1.wsdl to create the request. The only difference between the two demonstrated requests here is the symbol. One has the symbol as IBM and other has MSFT. For one type of request set the priority header to 1 and for the next set the priority header to 10. Then load synapse with high volume of traffic from both types of requests using the load testing tool. In the back end server it prints the symbol of the incoming requests. User should be able to see more of high priority symbol.

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
     <soapenv:Header xmlns:wsa="http://www.w3.org/2005/08/addressing">
        <wsa:To>http://localhost:8281/services/SimpleStockQuoteService</wsa:To>
        <wsa:MessageID>urn:uuid:1B57D0B0BF770678DE1261165228620</wsa:MessageID>
        <wsa:Action>urn:getQuote</wsa:Action>
     </soapenv:Header>
     <soapenv:Body>
        <m0:getQuote xmlns:m0="http://services.samples">
           <m0:request>
              <m0:symbol>IBM</m0:symbol>
           </m0:request>
        </m0:getQuote>
     </soapenv:Body>
</soapenv:Envelope>
           
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
     <soapenv:Header xmlns:wsa="http://www.w3.org/2005/08/addressing">
        <wsa:To>http://localhost:8281/services/SimpleStockQuoteService</wsa:To>
        <wsa:MessageID>urn:uuid:1B57D0B0BF770678DE1261165228620</wsa:MessageID>
        <wsa:Action>urn:getQuote</wsa:Action>
     </soapenv:Header>
     <soapenv:Body>
        <m0:getQuote xmlns:m0="http://services.samples">
           <m0:request>
              <m0:symbol>MSFT</m0:symbol>
           </m0:request>
        </m0:getQuote>
     </soapenv:Body>
</soapenv:Envelope>
           

Here is the priority configuration file used by the NHTTP transport to determine the priority based on HTTP level properties.

<priorityConfiguration>
    <priorityExecutor>
        <!-- two priorities specified with priority 10 and 1. Both priority messages has a queue depth of 100 -->
        <queues isFixedCapacity="true" nextQueue="org.apache.synapse.commons.executors.PRRNextQueueAlgorithm">
            <queue size="100" priority="10"/>
            <queue size="100" priority="1"/>
        </queues>
        <!-- these are the default values, values are put here to show their availability -->
        <threads core="20" max="100" keep-alive="5"/>
    </priorityExecutor>

    <!-- if a message comes that we cannot determine priority, we set a default priority of 1 -->
    <conditions defaultPriority="1">
        <condition priority="10">
            <!-- check for the header named priority -->
            <equal type="header" source="priority" value="5"/>
        </condition>
        <condition priority="1">
            <equal type="header" source="priority" value="1"/>
        </condition>
    </conditions>
</priorityConfiguration>

Objective: Demonstrate the priority based dispatching of NHTTP transport.

Prerequisites:
Deploy the SimpleStockQuoteService in sample Axis2 server and start it on port 9000. Priority is applied only when synapse is loaded with enough messages to consume its core number of threads. So to observe the priority based dispatching, it is required to use a load testing tool like JMeter, SOAP UI or Apache bench.
Open axis2.xml in repository/conf directory and uncomment the following parameter to the configuration. priorityConfigFile. Set the value to repository/conf/sample/resources/priority/priority-configuration.xml
Start Synapse with the sample configuration 150 (i.e. synapse -sample 150).

In this sample, client should send a HTTP header that specifies the priority of the message.This header name is priority. This header is retrieved in the prioirty configuration. Then it is matched against the value 1 and 10. Depending on this value message is executed with priority 1 or 10.

Here are two sample XML files that can be used to invoke the service using a tool like JMeter, or Apache Ab. For SOAP UI, user can use the WSDL repository/conf/sample/resources/proxy/sample_proxy_1.wsdl to create the request. The only difference between the two demonstrated requests here is the symbol. One has the symbol as IBM and other has MSFT. For one type of request set the priority header to 1 and for the next set the priority header to 10. Then load synapse with high volume of traffic from both types of requests using the load testing tool. In the back end server it prints the symbol of the incoming requests. User should be able to see more of high priority symbol.

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
     <soapenv:Header xmlns:wsa="http://www.w3.org/2005/08/addressing">
        <wsa:To>http://localhost:8281/services/SimpleStockQuoteService</wsa:To>
        <wsa:MessageID>urn:uuid:1B57D0B0BF770678DE1261165228620</wsa:MessageID>
        <wsa:Action>urn:getQuote</wsa:Action>
     </soapenv:Header>
     <soapenv:Body>
        <m0:getQuote xmlns:m0="http://services.samples">
           <m0:request>
              <m0:symbol>IBM</m0:symbol>
           </m0:request>
        </m0:getQuote>
     </soapenv:Body>
</soapenv:Envelope>
           
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
     <soapenv:Header xmlns:wsa="http://www.w3.org/2005/08/addressing">
        <wsa:To>http://localhost:8281/services/SimpleStockQuoteService</wsa:To>
        <wsa:MessageID>urn:uuid:1B57D0B0BF770678DE1261165228620</wsa:MessageID>
        <wsa:Action>urn:getQuote</wsa:Action>
     </soapenv:Header>
     <soapenv:Body>
        <m0:getQuote xmlns:m0="http://services.samples">
           <m0:request>
              <m0:symbol>MSFT</m0:symbol>
           </m0:request>
        </m0:getQuote>
     </soapenv:Body>
</soapenv:Envelope>
           

This sample describes how to use transaction mediator to participate in a distributed transaction

<definitions xmlns="http://ws.apache.org/ns/synapse"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">

    <sequence name="myFaultHandler">
        <log level="custom">
            <property name="text" value="** Rollback Transaction**"/>
        </log>
        <transaction action="rollback"/>
        <send/>
    </sequence>

    <sequence name="main" onError="myFaultHandler">
        <in>
            <send>
                <endpoint>
                    <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
                </endpoint>
            </send>
        </in>

        <out>
            <transaction action="new"/>

            <log level="custom">
                <property name="text" value="** Reporting to the Database esbdb**"/>
            </log>
            <dbreport useTransaction="true" xmlns="http://ws.apache.org/ns/synapse">
                <connection>
                    <pool>
                        <dsName>java:jdbc/XADerbyDS</dsName>
                        <icClass>org.jnp.interfaces.NamingContextFactory</icClass>
                        <url>localhost:1099</url>
                        <user>synapse</user>
                        <password>synapse</password>
                    </pool>
                </connection>
                <statement>
                    <sql>delete from company where name =?</sql>
                    <parameter expression="//m0:return/m1:symbol/child::text()"
                               xmlns:m0="http://services.samples"
                               xmlns:m1="http://services.samples/xsd"
                               type="VARCHAR"/>
                </statement>
            </dbreport>

            <log level="custom">
                <property name="text" value="** Reporting to the Database esbdb1**"/>
            </log>
            <dbreport useTransaction="true" xmlns="http://ws.apache.org/ns/synapse">
                <connection>
                    <pool>
                        <dsName>java:jdbc/XADerbyDS1</dsName>
                        <icClass>org.jnp.interfaces.NamingContextFactory</icClass>
                        <url>localhost:1099</url>
                        <user>synapse</user>
                        <password>synapse</password>
                    </pool>
                </connection>
                <statement>
                    <sql>INSERT into company values ('IBM','c4',12.0)</sql>
                </statement>
            </dbreport>
            <transaction action="commit"/>
            <send/>
        </out>
    </sequence>

</definitions>

Objective: Demonstrate the use of the transaction mediator in a distributed transaction

Prerequisites: Deploy the SimpleStockQuoteService in sample Axis2 server and start it on port 9000.

Start Synapse with the sample configuration 652 (i.e. synapse -sample 652).

To run this sample it is required to deploy synpase on JBoss application server(This is only tested with JBoss application sever), you can use the war distribution to deploy synapse on JBoss application server. Use the synpase_sample_652.xml as the synapse confiuration file and start JBoss with that synpase configuration file. Also you need to define two XA datasources for above two datasources. You'll need to refer JBoss documentation to see how to do this.

It also required to have two database instances, this will be used by the two XA datasources. Refer the Sample Setup Guide to see how you can set up the derby database server.

In this sample a record is delete from one database and it is added into the second database. If either of the operations(deleting from the 1st database and adding into the second database) fails everything will be roll backed. The records will be untoched.

Invoke the client as follows.

ant stockquote -Daddurl=http://localhost:9000/services/SimpleStockQuoteService -Dtrpurl=http://localhost:8280/ -Dsymbol=SUN/

A Synapse message store is a special channel that can be associated with an endpoint. Whenever the endpoint fails to deliever a message to the given address, the message will be stored in the message store. A redeliver processor can be engaged on the message store to retry such failed messages.

Message stores can be monitored using JMX and if needed a user can browse the messages stored in a message store and retry them manually. This construct can be used to implement the EIP pattern "dead letter channel".

<definitions xmlns="http://ws.apache.org/ns/synapse"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://ws.apache.org/ns/synapse http://synapse.apache.org/ns/2010/04/configuration/synapse_config.xsd">

    <!--Simple in Memory Message Store with name foo -->
    <messageStore name="foo" sequence="bar">
        <redelivery>
            <!--retry interval 1 sec -->
            <interval>1</interval>
            <!--Message will be stored after 2 redeliveries -->
            <maximumRedeliveries>2</maximumRedeliveries>
            <exponentialBackoff>true</exponentialBackoff>
            <backoffMutiplier>2</backoffMutiplier>
        </redelivery>
    </messageStore>

    <!-- Endpoint named SampleEndpoint-->
    <endpoint name="SampleEndpoint" onFault="foo">
        <address uri="http://localhost:9000/services/SimpleStockQuoteService">
            <suspendDurationOnFailure>2</suspendDurationOnFailure>
        </address>
    </endpoint>

    <sequence name="main">
        <!-- filtering of messages with XPath and regex matches -->
        <filter source="get-property('To')" regex=".*/StockQuote.*">
            <send>
                <endpoint key="SampleEndpoint"/>
            </send>
            <drop/>
        </filter>
        <send/>
    </sequence>

    <sequence name="bar">
        <log level="full"/>
    </sequence>

</definitions>

Objective: Introduction to Synapse Message Stores

Prerequisites:
Start the Synapse configuration numbered 700: i.e. synapse -sample 700
Start the Axis2 server and deploy the SimpleStockQuoteService if not already done

To Execute the Client :

ant stockquote -Dtrpurl=http://localhost:8280/soap/StockQuote

Since now you have the Axis2 Server Running when you run the client you will get the Stock generation output in Server console and the out put in the client side. Then try shutting down the Axis2 Server and running again. You will see synapse will try 2 times to deliver the message and store in on the MessageStore.It will execute the log sequence before storing the Message in the Message store.

You can then use the JMX view of Synapse Message Store by using the jconsole and view the stored Message.You can even re start the Axis2Server and manually redeliver the request using the Same JMX view.