Skip to main content

Web services choreography in practice

Jerome Josephraj lives in Essex, United Kingdom and has published an article on Struts and Web Services for the IBM Web site. He is also an official reviewer for the Jakarta Struts Cookbook and Web Service, Now book proposal. You can reach Jerome at jerome_josephraj@hotmail.com.

Summary:  Find out how you can use the Web Service Choreography Interface (WSCI) to weave different Web services into meaningful business processes. Jerome Josephraj presents a simple stock trading example that highlights the shortfalls of using Web Services Description Language (WSDL) for business process integration, and how you can utilize Web Service Choreography (WSC) to overcome these shortfalls.

Date:  10 May 2005
Level:  Intermediate
Activity:  3365 views

Introduction

As more and more corporations are jumping onto the Web service bandwagon, researchers forecast that Web services will provide more than just a single-ended process. In general, composite applications are increasing in importance, and corporations are increasingly using Web services as part of more complex process interactions. WSC aims precisely at this trend.

The WSCI is an XML-based interface description language that works in conjunction with WSDL. Its goal is to use the power of Web services to allow corporations to create business processes that mirror today's dynamic and ever-changing business needs. Corporations can expose their application software and resources as Web services so that other corporations can dynamically find and use them in their business processes. Creating a business process requires not only a clear definition of collaboration patterns of all its components, but also a way of depicting standard Business-to-Business (B2B) interactions.

The following sections illustrate how a simple online stock trading company uses Web services and WSDL to expose services, the shortfalls of this approach, and how WSC can help overcome these shortfalls. The scope of this article is to give an explanation of WSC, provide information on the value of WSC, and learn about some of its features.


Online trading company using Web services

The need and role of WSC is best explained by going through a simple stock trading example. For the sake of brevity, let's go through most of the actions involved. I do not go through all of the steps to buy and sell stocks, since it's not the scope of this article. Instead, I present a simple stock trading application example. Figure 1 below depicts step-by-step business processes required to buy and sell stocks using an online Web application.


Figure 1. Stock trading business processes
Stock trading business processes

Use case

The online stock trading application gets stock details from a third party Web service, such as xmethods.net, and provides it to the user. The user might pick up a stock, which he or she is interested in, and request more details. The online trading company uses one of the third party's Web services to get the details.

Once the user decides which stock to buy, he or she places a buy order. The online application uses one of its own internal processes to buy stock(s) from the stock market. The online trading application then requests the user to confirm the buy order and enforces a timeout period for the user to confirm the order. Failure to confirm the order in a minute will result in a timeout message to the user.

Once the order has been confirmed by the user, the online trading application deducts the necessary cost from the user's account. To do that, it uses one of the existing third party Web services. It uses one Web service to validate the credit card and a second Web service to debit the money. Both steps have to be processed as a logical unit of work, and failure in one of the services will result in a failure message to the user. If the credit card is validated successfully and the funds are successfully transferred from the users account, the online application buys the required number of stocks from the market. The user is allowed to place more than one buy order, and each buy order will be treated as a separate logical unit of work.

A sell order has similar steps as a buy order. The user places a sell order and confirms it when prompted. Once confirmed, the online application places the sell order and credits the user's account after validating customer account details.

In order to increase their business channels and collaborate with other systems, the online trading company can expose a Buy/Sell application as a Web service. In the case of a simple Web service, you can map the steps above to operations in a WSDL file. The customer, using Web service software such as Microsoft VBA editor or an external application calling the Web service, can call these WSDL operations to place a buy or sell order. The following link illustrates how to accomplish this task in VBA: http://www.microsoft.com/office/previous/xp/webservices/toolkit.asp). Figure 1 above depicts the WSDL operations and mapping between business processes.


WSDL woes

A well-defined Web service for buying and selling stocks works if all the processes are atomic, or, in other words, they don't share any state. But in this case, WSDL alone addresses some of the core requirements for business process integration such as:

  • Sequencing of processes
    A service consumer, which uses the buy/sell Web service, can call the operations in any sequence. For example, a service consumer can call a cash transfer operation before calling a placeBuyOrder or a placeSellOrder operation. WSDL doesn't prevent calling operations in any sequence. A Web service application, which uses WSDL, has to cater to this in its application logic above.
  • Message correlation
    Correlation is the simple idea of sending a message out to someone, expecting to receive a response back (more than likely at a later point), and using some common piece of data in the returned message instance to tie it up (in other words, correlate) with the sending message instance. In a business process interaction, it's very important to understand and describe the correlation between the message instances. WSDL doesn't have the capability of correlating the message instances. In other words, it doesn't maintain state between operations. In a typical business process integration, processes generally share state in order to provide a collaborated process. All operations exposed using WSDL are stateless. It doesn't have a feature of correlating between message instances.

    In this example, when a user places a buy order as a next step, the Web service application requests that the user confirm the order. The user might decide to change the number of stocks or might change the order buy date. Since the order is changed, he or she has to place a buy order again. This back and forth conversation might happen several times, and the user might invoke several buy orders, or, in other words, might invoke several conversations with the Web service application. However, a Web service that uses only WSDL doesn't have the capability of correlating message instances.
  • Unit of work
    In order for a Web service to be part of a long message exchange, it's important to clearly define when the message exchange is actually triggered, when it's considered to terminate, and which parts of it can be considered as managed in a transactional way.

    In this example, the operations placeBuyOrder, confirmBuyOrder, and the process of debit money have to be done in one unit of work. The Web service has to execute all three operations successfully, or you have to restore the operations to a consistent state prior to the execution. You cannot use operations for distributed transactions exposed in WSDL. In WSDL, the scope of a transaction is restricted to individual operations and doesn't span beyond more than one operation.
  • Exception handling
    Even though WSDL uses fault code to throw any exception, it doesn't deal with modeling artifacts like checking for a particular message, declaring an exception timeout, or declaring an exception only for a set of operations and not for the whole Web service.

    It's imperative to have a proper exception modeling artifact for process interaction. In this example, if a user takes more than a minute to confirm a buy or sell order, the Web service throws a timeout exception.
  • Context
    In a business process interaction, it's important that the processes involved establish a context to share information. This information might be a set of declarations, exceptional events, or transactional properties. WSDL doesn't provide any features for processes to operate within a context.


Figure 2. Stock trading using WSDL
Stock trading using WSDL

How WSC helps

WSC helps resolve all the above mentioned shortfalls for process integration by using WSDL as a base, extending functionality. The following sections explain how WSCI addresses these shortfalls:

Context

When aggregating a number of services to create a composite business service, the services need to share a context. The context element sets up an environment to execute the activities. The context element also ensures that a set of activities are performed as a group, and all activities within a context can share a set of declarations, set of exceptional events, and transaction properties.

The context definition has local properties and local process definitions. Local properties are only available to the activities executing in this context. Local process definitions designate exactly those processes that might be instantiated in this context. To call or spawn a local process, it must come from a context where the definition of the local process is visible.

In Listing 1 below, the local process definition has different contexts for buying and selling a stock. If a fault occurs in buying a stock process, it's restricted to that process. As an example, if the contexts are not defined, a fault in the sell process can throw the user out of the Web service instead of sending the state to the placeSellOrder state. A snippet of the WSCI definition is given below:


Listing 1. Example for context element
		
<context>
	<foreach select="ns1:arrayOfStockList/leg[position()>1]">
		<process name = "PlaceBuyOrder" instantiation = "other">
			<action name = "PlaceBuyOrder" 
					role= "tns:trader"
					operation= "tns:placeBuyOrder">
			</action>
		</process>
	</foreach>
	<process name = "ConfirmBuyOrder" instantiation = "other">
		<action name = "ConfirmBuyOrder"
				role= "tns:trader"
				operation= "tns:confirmBuyOrder" >
			<correlate correlation = 
			"defs:buyStockCorrelation" instantiation= "true" />
		</action>
		<exception>
			<onTimeout property = 
			"tns:confirmationTime"
			  type= "duration"
			  reference="tns:PlaceBuyOrder@end">
			  <compensate transaction = "tns:reverseBuyOrders"/>
			</onTimeout>
		</exception>
	</process>
	<process name="transferMoney" instantiation="other">
		<action name = "cashTransaction"
				role= "tns:trader"
				operation= "tns:debitMoney" >
		</action>
	</process>
	<exception>
		<onMessage>
			<action name = "reverseBuyOrders"
				role= "tns:trader"
				operation= "tns:cancelBuyOrder">
			</action>
			<fault code = "tns:creditCardTxFaultCode"/>
		</onMessage>
	</exception>
</context>

Sequencing of processes

In order to call more granular business processes in a sequence and to group them under a global business process, WSC uses an interface element sequence. As the name suggests, it makes sure the system calls the processes in a sequence. When a service consumer wants to buy a stock, the interface element calls the cash transfer operation before the buy process. This is achieved by defining all operations called in a sequence within the sequence element, as shown in Listing 2 below.


Listing 2. Example for sequencing element
			
<sequence>
        <!-- Web service Choreography Sequence -->
	<operation name="placeBuyOrder">
		<input message="buySellOrderRequest"/>
		<output message="buySellOrderResponse"/>
	</operation>
	<operation name="confirmBuyOrder">
		<input message="buySellOrderResponse"/>
		<output message="buySellOrderResponse"/>
	</operation>
	<operation name="debitMoney">
		<input message="creditCardDetails"/>
		<output message="debitMoneyResponse"/>
	</operation>
</sequence>

Message correlation

In WSC, you can create instances implicitly when messages arrive for the service. The instances created in WSC are identified using key fields within data messages. In this example, it's important to correlate between the confirmBuyOrder and placeBuyOrder process because each process could have happened in a prior instance. When the confirm order is sent to the service consumer, the consumer might change the order (for example, the user might change the quantity due to a change in price) and place the buy order again. This conversation might happen several times between the service consumer and the Web service.

The service consumer might place more than one buy order, which can trigger more than one conversation. You need to be able to identify each conversation. For this, a placeOrderId is used. By providing this mechanism, the service consumer can place as many buy orders as he or she wants, and each one participates in a separate conversation. For each conversation, a unique placeOrderId is created.

You can achieve this by defining a correlation element with a property that has a unique ID. In this particular case, it's the stock code, as shown in Listing 3 below.


Listing 3. Example for correlation element
			
<correlation name = "buysellCorrelation"
property = "tns:placeOrderId" />

Unit of work

WSCI uses a transaction element to model the behavior of a Web service and treats a number of activities as a single unit of work. A Web service uses a WSCI transaction to communicate to other services its ability to either completely execute those activities or to restore to a consistent state prior to the execution.

In the buying or selling a stock example, the online trading company talks to different Web services that the third party (such as a third party credit card Web service) provides. If an exception process occurs or can't complete the transaction with any one of the third party providers, the Web service has to make sure to go back to the previous state. This is achieved by using a transaction element and a compensation element. Listing 4 illustrates a snippet of the code.


Listing 4. Example for transaction element
					
<transaction name = "reverseBuyOrder"= "atomic">
<compensation>
<action name = "reverseBuyOrder"= "tns:trader"= 
"tns:reverseBuyOrder"/>
</compensation>
</transaction>

The transaction can be called in a compensation element when 
an exception occurs as shown below:

<onTimeout property = "tns:confirmationTime"= "duration"=
"tns:PlaceBuyOrder@end">
<compensate transaction = "tns:reverseBuyOrder"/>
</onTimeout>

Exception handling

In business process integration, handling exceptions and taking the appropriate route is as important as handling normal cases (such as happy flow). For this, WSCI uses exception elements. WSCI allows declaring exceptional behavior that is exhibited by a Web service at a given point in choreography. The declaration of exceptional behavior is part of the context definition and associate exceptions, with a set of activities that the Web service performs in response to those exceptions. Exceptions are a WSCI modeling artifact designed to model the exceptional behavior exhibited by a Web service, at a given point of a conversation. They do not need to necessarily represent any "technical failure".

WSCI can raise an exception based on a fault message from WSDL, a message content, or an event (for example, Timeout event). The occurrence of an exception causes the current context to terminate after the activities associated with the exception have been performed. Thus, WSCI supports the concept of "recoverable exceptions" that do not cause the overall choreography to terminate (similar to the throw/catch concept in Java™). However, the occurrence of a fault, for which no exceptional behavior is defined, causes the context to be terminated and the fault to be raised in the parent context. More abstractly, exception handling behavior defined in a parent context definition can act as the default behavior for all its children, and, in reverse, exception handling behavior defined in a context definition can be used to override exception handling behavior defined in its parent.

In Listing 5, when a user takes more than a minute to confirm an order, the application has to time out. In WSC, this is handled by using a timeout feature. The timeout element is actually an event element, which is used inside an exception element. After one minute, a timeout event is triggered, and the system uses the compensation element to go back to previous placeBuyOrder state.


Listing 5. Example for exception and timeout element
			
<exception>
<onTimeout property = "tns:expiryTime"
type = "duration"
reference="tns:ReserveSeats@end">
<compensate transaction = "tns:seatReservation"/>
</onTimeout>
</exception>


Figure 3. Stock trading using WSCI
Stock trading using WSCI

Other features in WSCI

Table 1 below lists other useful WSCI features. For a complete list, refer to the WSCI document.

Table 1. WSCI elements

Element name Short description Example
SelectorThe selector element selects a property value from a message. It's useful to abstract a complex message into a set of properties. You can use the selector element to get the total count of shares from the getAllStocksResponse message:
<selector property = "tns:stockCount"
            element = "tns: ArrayOfStockList
            xpath = "count (./StockList)" />
            

CallThe call element calls an arbitrary operation (for example, a call to a third party Web service) inbetween an action. This is atomic in nature, and the action fails if a fault occurs in the called process.If the application wants to log all transactions for auditing and reconciliation purposes, an arbitary process can be called to log this:
<process name = "DebitMoney" instantiation = "other">
<action name = "debitMoney"
role = "tns:trader"
operation = "tns:debitMoney">
</action>
<call process = "auditTransactions"/>
</action>
</process>

All activityThe all activity element is similar to the sequence activity, where all operations defined within this are performed, but the activities defined in this element can be performed in non-sequential order.In this example, the buy order and debiting money can be performed in any order:
<all>
	<operation name="confirmBuyOrder">
		<input message="buySellOrderResponse"/>
		<output message="buySellOrderResponse"/>
	</operation>
	<operation name="debitMoney">
		<input message="creditCardDetails"/>
		<output message="debitMoneyResponse"/>
	</operation>
</all>


ForeachThe foreach element performs activities in a loop based on a condition. It's similar to a Java for loop.It performs PlaceSellOrder for each stock in the arrayOfStocks:
<foreach select="ns1:arrayOfStockList/leg[position()>1]">
<process name = "PlaceSellOrder" instantiation = "other">
<action name = "PlaceSellOrder"= "tns:trader"= "tns:placeSellOrder">
</action>
</process>
</foreach>

SwitchThe switch element selects an activity from a list of activities based on a condition. The order of condition is very important, and the condition which evaluates to true will execute first. It's similar to a Java case statement.It performs the appropriate action when the condition is true. If the condition isn't true, it performs the default action:
<switch>
<case>
<condition>tns:reverseBuyOrder</condition>
<action name = "reverseBuyOrder"
role = "tns:trader"
operation = "tns:reverseBuyOrder"/>
</case>
<default>
<action name = "confirmBuyOrder"
role = "tns:trader"
operation = "tns:confirmBuyOrder"/>
</default>
</switch>

UntilThe until element performs all activities based on a Boolean value. It performs these activities at least once. It's similar to a Java do while statement.
<until>
<condition>tns:creditCardProcessed</condition>
<process name = "DebitMoney" instantiation = "other">
<action name = "debitMoney"
role = "tns:trader"
operation = "tns:debitMoney">
</action>
</process>
</until>


WhileThe while element performs all activities zero or more times based on a Boolean value. It's similar to a Java while statement.
<while>
<condition>tns:creditCardProcessed</condition>
<process name = "DebitMoney" instantiation = "other">
<action name = "debitMoney"
role = "tns:trader"
operation = "tns:debitMoney">
</action>
</process>
</while>

DelayThe delay element runs an activity with the specified delay period. If an exception occurs within that activity, the activity might complete before the specified time.
<exception>
<delay property = "tns:delayTime"
type = "duration"
reference="tns:delayBuyingStock">
</delay>
</exception>

CallThe call element instantiates a process and waits for it to complete. The call element is useful to call an internal process.
<call process = "tns:audit" />

SpawnThe spawn element instantiates a process but doesn't wait for it to complete.
<Spawn process = "tns:logBuyTransaction" />

JoinThe join element waits for an instance of a spawned process to complete. If no instance exists or all instances have already completed, the activity completes.
<join process = "tns:logBuyTransaction" />


Conclusion

Until now, there hasn't been a standard way to describe the flow of messages exchanged by a Web service participating in a choreographed interaction with other services. BEA Systems, Intalio, SAP AG, and Sun Microsystems developed WSCI to address this issue. In this article, you've learned some of the basic functions provided by WSCI through a simple example. But I've only scratched the surface. In order to understand more about WSCI, you might want to read the WSCI specification and write a simple example application using WSCI.



Download

DescriptionNameSizeDownload method
WSCI For Stock Buy Sell_attachmentWSCIForStockBuySell_attachment.xml5 KB HTTP

Information about download methods


Resources

About the author

Jerome Josephraj lives in Essex, United Kingdom and has published an article on Struts and Web Services for the IBM Web site. He is also an official reviewer for the Jakarta Struts Cookbook and Web Service, Now book proposal. You can reach Jerome at jerome_josephraj@hotmail.com.

Comments (Undergoing maintenance)



Trademarks  |  My developerWorks terms and conditions

Help: Update or add to My dW interests

What's this?

This little timesaver lets you update your My developerWorks profile with just one click! The general subject of this content (AIX and UNIX, Information Management, Lotus, Rational, Tivoli, WebSphere, Java, Linux, Open source, SOA and Web services, Web development, or XML) will be added to the interests section of your profile, if it's not there already. You only need to be logged in to My developerWorks.

And what's the point of adding your interests to your profile? That's how you find other users with the same interests as yours, and see what they're reading and contributing to the community. Your interests also help us recommend relevant developerWorks content to you.

View your My developerWorks profile

Return from help

Help: Remove from My dW interests

What's this?

Removing this interest does not alter your profile, but rather removes this piece of content from a list of all content for which you've indicated interest. In a future enhancement to My developerWorks, you'll be able to see a record of that content.

View your My developerWorks profile

Return from help

static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=SOA and Web services, XML
ArticleID=82857
ArticleTitle=Web services choreography in practice
publish-date=05102005
author1-email=jerome_josephraj@hotmail.com
author1-email-cc=

My developerWorks community

Tags

Help
Use the search field to find all types of content in My developerWorks with that tag.

Use the slider bar to see more or fewer tags.

Popular tags shows the top tags for this particular content zone (for example, Java technology, Linux, WebSphere).

My tags shows your tags for this particular content zone (for example, Java technology, Linux, WebSphere).

Use the search field to find all types of content in My developerWorks with that tag. Popular tags shows the top tags for this particular content zone (for example, Java technology, Linux, WebSphere). My tags shows your tags for this particular content zone (for example, Java technology, Linux, WebSphere).

Rate a product. Write a review.

Special offers