Simulate Web services with Apache Synapse

Source: Internet
Author: User
Tags soap xpath xsl xslt wsdl

Apache Synapse is a simple, lightweight, high-performance Enterprise service Bus (ESB) that was released under Apache License Version 2.0 of the Apache software Foundation. With Apache Synapse, you can filter, transform, and use HTTP, HTTPS, Java™message Service (JMS), Simple Mail Transfer Protocol (SMTP), Post Office Protocol version 3 (POP3), FTP, file system, and many other transport media Route, manipulate, and monitor SOAP, binary files, XML, and plain text messages that pass through large enterprise systems. But what does an ESB product do in your daily life for a single developer? Simplified configuration, an instantly available feature set, an extensible architecture, and a small script make it a powerful multipurpose tool that you can use to accomplish a variety of tasks. This article will show you how to create a mock Web service using Apache Synapse.

Before you begin

About this tutorial

This tutorial discusses how to use the Apache Synapse ESB to create a mock Web service. Target WEB service clients and services can use any language, such as Microsoft®.net, Java, or PHP. You'll learn a few examples, starting with the most basic configuration, and then gradually building a more complex solution to create a mock Web service.

Prerequisite

This tutorial is written primarily for Web service developers, so you should be familiar with some of the Web services concepts. Having knowledge of Apache Synapse is useful for understanding this article. You must also have at least a basic knowledge of XSL transport (XSLT) and JavaScript code. If you are unfamiliar with these areas of knowledge, there are many resources on the network that can provide you with some basic information.

System Requirements

Apache Synapse requires JDK 1.5, which can be run in Linux®, Microsoft Windows®, and Solaris environments. Memory and disk space requirements are low, so you can easily run it on low-end systems without any problems.

In this tutorial, the command and directory names are provided in the Linux compatibility format. If your operating system is a different system, change the command and directory name accordingly. For example, in Windows, you must use the Synapse.bat script (instead of synapse.sh) to start the synapse instance.

What are mock Web services and why should I use them?

In your daily work, you may experience the following four scenarios:

Your boss asks you to write a program that relies on one or more remote WEB services. These WEB services can run on the production server, but may not be available on the test server. For third-party services, you do not even have access to code or binary files. Therefore, you must assemble some simulation services from the beginning to test your code. The possible scenario is that you did not test the bug fixes that you have made to the hotel reservation system by booking and later canceling the booking for the production server. Or do you plan to do the work?

You may be working from home, on the road, or on the fly, and you need a full set of WEB services that run offline so that you can try out the latest changes to your ordering processing system. This system examines the product through the directory service and orders the order Processing service.

You want to create an offline presentation, but you are not sure whether you can access the remote Web service and whether the service is always available to run. You need to make sure that when a potential customer sits in front of you, the WEB service call responds correctly-that is, no connection timeout is unexpected.

You may need to simulate different scenarios. What happens if a service responds to an error, or if an unexpected response occurs? It may be difficult to get the exact response you want from the managed test service. After two weeks of production, your program may not have been tested for rooms not available error response until this issue occurs.

In all these cases, you can solve these problems by creating fake Web services (that is, mock web services) to mimic the behavior of the actual Web services. The simulated Web service has the same interface and behavior as the actual Web service. During development and testing, you can exchange the actual Web service endpoints with the simulated Web service endpoints. This allows you to invoke the validation request message against the external Web service and return the required response message.

Apache Synapse Solution

The benefit of using Apache Synapse for simulating Web services is that when you address enterprise integration issues in this task, you can apply the same skills and methods that you get when you use an ESB without having to learn and invest in other tools. You can use available tools, scripting languages, style sheets, and even Java code to transform and process these responses the way you want.

Assume that you have installed and run some Apache Synapse samples. Apache Synapse comes with a number of examples that you can try with the help of a bundled sample server and client (see the Downloads section). If you haven't already done so, go to the Apache Synapse website and download the latest version (see the Resources section for links). Review the sample guide and try some of these examples. Follow the steps in the Guide to start the operation immediately. In this article, by using some of the Synapse configurations, you will use the same sample client in Apache Synapse and simulate the same sample server behavior.

The Synapse configuration is an XML file written in a domain-specific language that you can use to tell Synapse what to do with the received message.

In these examples, you will use a simple XSL style sheet and script code. Even if you are unfamiliar with these things, you can modify the examples provided and use them to easily meet your needs.

Setup Example

First you will install Apache Synapse and prepare the environment to experiment with these examples:

Download the latest version of Apache Synapse and extract the distribution version to a directory (see Resources for a link to download Apache Synapse).

If you have not yet installed JDK 1.5, install JDK 1.5 and point the JAVA_HOME environment variable to its installation directory.

Install Apache Ant and add the Apache Ant bin directory to the PATH environment variable (see Resources for related links).

Download the sample package from the download section and unzip it into a directory.

From the sample package, copy the mocks directory to the Apache Synapse repository/conf/sample/resources directory. Figure 1 shows the location where these files are copied in the Synapse directory structure.

Copy the five Synapse configuration files into the Apache Synapse repository/conf/sample directory (see figure 1).

Figure 1. Location of the sample file

You can try the Synapse sample configuration file by using the same mechanism that Synapse uses to start the binding sample configuration. This is why these configuration files are named Synapse_sample_*.xml and are located in the sample directory.

A sample client has been written to bind to the Synapse distribution to generate different types of requests, process their responses, and display the output. (For more information, see the Synapse Sample Guide in the Resources section.) )

When you run the client, you can use tools such as Apache TCPMon to see what happened (see Resources for links). Configure the monitoring tool to listen on 8081 and then forward to port 8080. You are setting up the tool to intercept messages exchanged between the client and the Synapse. TCPMon shows what the client is sending, and Synapse what is being sent back. If you are not using TCPMon, replace port 8081 with 8080 when you run the sample Client command later.

Done. Now you can start the binding simulation Web service with Apache Synapse. You can start with the simplest examples and gradually build more complex configurations.

Sample requests and Responses

First you'll emulate the simplest example scenario: Instruct Apache Synapse to send a fixed response regardless of the request received:

By entering the Synapse Bin directory and using the command

./synapse.sh-sample Mock1-simple

, use the Synapse_sample_mock1-simple.xml configuration to start synapse. This launches the Synapse instance using the Synapse_sample_mock1-simple.xml configuration, which is the file that you copied earlier into Repository/conf/sample.

After Synapse is started, go to the Synapse samples/axis2client directory and run the sample client as follows:

Ant stockquote-dtrpurl=http://localhost:8081/

The sample client will create for the symbol IBM

GetQuote

The request is manipulated and sent to the endpoint address http://localhost:8081/soap/StockQuote. The stock price extracted from the received response is then printed. If you are using a tool such as TCPMon, you can see that the client is sending a

GetQuote

The action request message, and Synapse is sent back to a

Getquoteresponse

The response message.

Note that this is similar to example 0 in the Synapse Sample guide (see Resources for related links). But you do not use the addressing header. This is to make the example as simple and understandable as possible. Instead of using the sample server, you simulated the server response using Synapse. Listing 1 shows the Synapse configuration that you have already used.

Listing 1. Synapse configuration for simple requests and responses: Synapse_sample_mock1-simple.xml

<definitions xmlns= "Http://ws.apache.org/ns/synapse" > <localentry key= "getquoteresponse_xsl" src= "file: Repository/conf/sample/resources/mocks/getquoteresponse.xsl "/> <in> <xslt key=" GetQuoteResponse_xsl "/ > <property name= "RESPONSE" value= "true"/> 

In the configuration, you have used a simple stylesheet transformation to replace the content of the request message with the content of the response message and identify it as a response so that Synapse it back to the requester. You also removed the WS addressing header, if it exists. Otherwise, Synapse will use the header to provide the message. In this simplest case, regardless of what the request is, you configure Synapse to send back this pinned message. You can try to call this endpoint with a different request message, and it will reply with the same response message. You can change the message content in the stylesheet and change the Synapse response. Now use

Ant stockquote-dtrpurl=http://localhost:8081/-dmode=fullquote-dsymbol=abc
Run the sample client as shown below. This will send the full stock quote request to the symbol ABC.

If you monitor the request message, you can see that this is

Getfullquote
Operation request message, with stock symbol ABC. But Synapse still sends the same response as before.

Listing 2 is the style sheet getquoteresponse.xsl you have used. You are simply replacing the current request message with the content of the response message.

Listing 2. Style sheets for simple requests and responses: getquoteresponse.xsl

<xsl:stylesheet version= "2.0" xmlns:xsl= "Http://www.w3.org/1999/XSL/Transform" > <xsl:output method= "xml"/ > <xsl:template match= "/" > <soapenv:envelope xmlns:soapenv= "http://schemas.xmlsoap.org/soap/envelope/" > <soapenv:Body> <ns:getquoteresponse xmlns:ns= "http://services.samples/xsd" > <ns:return type= " Samples.services.GetQuoteResponse "> <ns:change>-2.920874334221886</ns:change> <ns:sym bol>ibm</ns:symbol> <ns:volume>9343</ns:volume> </ns:return> </ns:getquoterespon se> </soapenv:Body> </soapenv:Envelope> </xsl:template></xsl:stylesheet>

In Listing 2, you have defined the implicit master sequence. All of the mediation elements in the top level (for example, the in mediator in this instance) belong to the sequence. Each request received by the Synapse is passed through this sequence. In the following example, you host a virtual Web service that has its own endpoint address and its own Web Service Description Language (WSDL).

Set up the proxy service

This time, you host a virtual Web service in Synapse, which returns a predefined response message as in the previous example. In addition, the virtual Web service publishes the WSDL that you customized to emulate the actual Web service. This example is similar to the simple Proxy service example 150 in the Synapse sample guide (see Resources for related links).

Start synapse from the Synapse_sample_mock2-proxy.xml configuration as shown below:

./synapse.sh-sample Mock2-proxy

To view the Web service WSDL, go to http://localhost:8080/soap/StockQuoteService?wsdl in your Web browser. This is the custom WSDL that you provided for the proxy service.

You can use

Ant Stockquote-dtrpurl=http://localhost:8081/soap/stockquoteservice
Run the sample client.

You can get stock quotes as you did in the previous example. In this example, you have sent the request message to the location that hosts the proxy service. Listing 3 is the Synapse configuration you are using.

Listing 3. Synapse configuration for setting up the Proxy service: Synapse_sample_mock2-proxy.xml

<definitions xmlns= "Http://ws.apache.org/ns/synapse" > <localentry key= "getquoteresponse_xsl" src= "file: Repository/conf/sample/resources/mocks/getquoteresponse.xsl "/> <proxy name=" StockQuoteService "> < target> <inSequence> <xslt key= "getquoteresponse_xsl"/> <property name= "RESPONSE" value= "true"/&    Gt  

In this scenario, you define the name of the

StockQuoteService
's Proxy service. As the name implies, the proxy service is the virtual service running in the ESB. It has an exact endpoint location, and you can provide custom WSDL for the service, so that the service behaves exactly like any other Web service residing on a remote server.

Assume that you are building a client for a remote production service. You can get the WSDL, host the language like this and process the request message in order to simulate the actual service in a matter of minutes. You can even set ws-security, ws-reliablemessaging, and other additions to this service to simulate the actual situation. You can use Synapse to easily add these quality of service (QoS) additions to existing production services.

The request message sent to this service will be

Insequence
The intermediary in the.
Insequence
The content is the same as the contents of the in mediator in the previous example. You have replaced the request message with a response message and identified it as a response message.

This configuration does not contain a master sequence. You only process the virtual service

StockQuoteService
The request message received. If you send a request message to Http://localhost:8081/,Synapse as in the previous instance, the message is logged and discarded. This is the default behavior when there is no master sequence.

You have successfully hosted the virtual service in the ESB. Now replace the request message payload with the given response and identify it as a response so that Synapse sends back the response as if it were from the sample server.

So far, you have sent a fixed response message to all received request messages. Next you will learn how to customize the response message based on the content of the request message.

Proxy Service with custom response

In this example, instead of sending a fixed response, the response is changed based on the content of the request message. As in the preceding example, you use a style sheet to convert a request message to a response message, while extracting some values from the request message and placing them in the response message.

To configure startup synapse with Synapse_sample_mock3-customquote.xml:

./synapse.sh-sample Mock3-customquote

Use

Ant Stockquote-dtrpurl=http://localhost:8081/soap/stockquoteservice-dsymbol=abc
Run the sample client.

If you monitor the response message, you can see that it has the same symbol as the request message. Change the symbol value and run it again. The response message will include the given request symbol value.

Listing 4 is the Synapse configuration you are using.

Listing 4. Synapse configuration for Proxy service with custom response: Synapse_sample_mock3-customquote.xml

<definitions xmlns= "Http://ws.apache.org/ns/synapse" > <localentry key= "customgetquoteresponse_xsl" src= " File:repository/conf/sample/resources/mocks/customgetquoteresponse.xsl "/> <proxy name=" StockQuoteService " > <target> <inSequence> <xslt key= "customgetquoteresponse_xsl"/> <property name= "RESPONSE "Value=" true "/> 

Your stylesheet extracts the content from the request message and uses some of the content to customize the response. In this case, you are using only the

<xsl:value-of/>
element to extract the request data and place it in the response message.

Listing 5. Style sheet for proxy service with custom response: customgetquoteresponse.xsl

<xsl:stylesheet version= "2.0" xmlns:xsl= "Http://www.w3.org/1999/XSL/Transform" > <xsl:output method= "xml"/ > <xsl:template match= "/" > <soapenv:envelope xmlns:soapenv= "http://schemas.xmlsoap.org/soap/envelope/" > <soapenv:Body> <ns:getquoteresponse xmlns:ns= "http://services.samples/xsd" > <ns:return type= " Samples.services.GetQuoteResponse "> <ns:change>-2.920874334221886</ns:change> <ns:sym bol><xsl:value-of select= "Ns:getquote/ns:request/ns:symbol"/></ns:symbol> <ns:volume>9343& lt;/ns:volume> </ns:return> </ns:getQuoteResponse> </soapenv:Body> </soapenv:envelope> ; </xsl:template></xsl:stylesheet>

In this example, you use the Stylesheet transformation to build an appropriate response message that uses the content extracted from the request message. If you look at the WSDL in this Web service, you can see that there are three more operations in this Web service. At this point, Synapse will send the same response for any request message type that is sent to this proxy service. In the following section, you will perform additional operations on the Web service.

Full Agent Service

Now let's use style sheet transformations to implement a complete set of stock quote service operations. You will test the action name element in the request message and replace it with the appropriate response.

To configure startup synapse with Synapse_sample_mock4-fullservice.xml:

./synapse.sh-sample Mock4-fullservice

Run the sample client as follows:

Ant Stockquote-dtrpurl=http://localhost:8081/soap/stockquoteservice-dmode=quote

Will

Quote

Change to the value of

Fullquote

Marketactivity

And

PlaceOrder

, and run the above command. The sample client sends different request types in each scenario. The Synapse will send the appropriate response based on the requested message sent.

Listing 6 is the Synapse configuration you are using.

Listing 6. Synapse configuration for full proxy service: Synapse_sample_mock4-fullservice.xml

<definitions xmlns= "Http://ws.apache.org/ns/synapse" > <localentry key= "simplestockquoteservice_xsl" src= " File:repository/conf/sample/resources/mocks/simplestockquoteservice.xsl "/> <proxy name=" StockQuoteService " > <target> <inSequence> <filter xpath= "//ns:placeorder" xmlns:ns= "http://services.samples/xsd"    ; <log format= "full"/> <drop/> </filter> <xslt key= "simplestockquoteservice_xsl"/> <PR  Operty name= "RESPONSE" value= "true"/> 

In the style sheet, you will test what the request message is and replace it with the appropriate response message.

PlaceOrder

An operation is an exception, and it is an incoming operation only. This means that

PlaceOrder

The operation is not responding. You use the filter mediator to test whether the request contains an XPath expression that uses the

PlaceOrder

Elements. If so, the request is logged and the message is discarded in case a further mediation occurs. It's not as expected.

PlaceOrder

Action to send the response back to the client.

Listing 7 is a style sheet for the full proxy service. You will use the action name to examine these elements and replace the message with the appropriate response message on discovery.

Listing 7. Style sheet for full proxy service: simplestockquoteservice.xsl

<xsl:stylesheet version= "2.0" xmlns:xsl= "http://www.w3.org/1999/XSL/Transform" xmlns:ns= "http// Services.samples/xsd "> <xsl:output method=" xml "/> <xsl:template match="/"> <soapenv:envelope xmlns : soapenv= "http://schemas.xmlsoap.org/soap/envelope/" > <soapenv:Body> <xsl:if test= "Ns:getquote" > & Lt;ns:getquoteresponse > ... </ns:getQuoteResponse> </xsl:if> <xsl:if test= "ns:getfullquo TE "> <ns:getfullquoteresponse xmlns:ns=" http://services.samples/xsd "> ... </ns:getfullquoter esponse> </xsl:if> <xsl:if test= "ns:getmarketactivity" > <ns:getmarketactivityresponse xmlns:ns = "Http://services.samples/xsd" > ... </ns:getMarketActivityResponse> </xsl:if> </soapenv:bod Y> </soapenv:Envelope> </xsl:template></xsl:stylesheet>

You have used a simple stylesheet to successfully simulate a complete WEB service operation in Synapse. In the next section, you will add additional virtual WEB services to your existing configuration.

Service Group

In this step, you will add another virtual Web service LBService1. LBService1 is another Web service that is provided with a sample server bound in Synapse to demonstrate load balancing and failover examples. Here you only perform simulations in Synapse.

To configure startup synapse with Synapse_sample_mock5-twoproxy.xml:

./synapse.sh-sample Mock5-twoproxy



Simulate Web services with Apache Synapse

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.