8.5. Managing Complex Web Service Interactions

An application may have multiple interactions with the same Web service, it may access different Web services, or it may expose many Web service endpoints. There may be different types of interactions. An application may be both a service and a client. A service endpoint may receive documents of multiple types and hence needs to handle them accordingly. All this makes for complexity in managing Web service interactions.

Message-level metadata and a canonical data model are common helper strategies that support complex interactions, and they are good building blocks for adding functionality to a Web service message exchange. By consolidating Web service endpoints, you can make an application's Web service interactions more manageable.

8.5.1. Passing Context Information on Web Service Calls

Web services may need to exchange context information when handling messages. This context data augments the message contents by providing some extra information about the contents and may include information on how to handle the message itself. For example, a purchase order consists of the message contents—items to purchase, customer and financial information—and you also may need to pass some extra information about the message, such as its processing priority. The Web service may also need additional context information indicating how to process the message, such as processing instructions or hints. This context information is often passed along with the message. The following are some use cases where such additional data may be needed.

  • Security information needs to be embedded within the document. For example, you may want to include some message-level security or add a digital signature to an accounts payment document as part of a credit card transaction.

  • A correlation identifier needs to be included with the message to indicate that the message is associated with a logical group of messages exchanged in a workflow.

  • Transactional or reliability information may be included along with the message contents to indicate additional quality of service activities that should be applied before processing the message contents.

  • A message needs to be processed on a priority basis.

Several strategies exist for including context information with a message exchange, as follows:

  1. Context information can be passed as an extra parameter in the Web service method. You can define the Web service interface to accept not only the XML document message, but to also include a second parameter that encapsulates metadata.

  2. Context information also can be passed as part of the document itself. You can embed the extra metadata within the XML document. When you parse the document, you extract the needed information.

  3. Context information also can be passed in the SOAP message header. You can embed the metadata in the SOAP message header and write a handler to extract it and pass it to the endpoint.

The first strategy, including context information as part of the service interface by adding an extra field for the input parameters or return values, effectively makes the context information part of the WSDL. For example, Code Example 8.3 shows how the boolean parameter priorityProcessing is added to the submitPurchaseOrder method. The value of the parameter indicates whether the order should be processed before other orders. Besides complicating the service interface, you must remember to update the interface—and regenerate the WSDL—if you add to or change the context information. For these reasons, the strategy of including context information as part of the service interface results in code that is harder to maintain.

Code example 8.3. Context information in a Service Interface
public interface MyWebService extends Remote {
// priorityProcessing is the data indicating that the purchase
// order needs to be processed on a priority basis
public String submitPurchaseOrder(PurchaseOrder poObject,
          boolean priorityProcessing) throws RemoteException;
}

The second strategy embeds the information directly in the message contents. (See Code Example 8.4.) You create additional elements within the XML document itself, making the context information part of the data model—either part of the request parameter message or the reply return data. Add the necessary elements to the message schema, then add the data elements to the XML document before sending the message. The receiving endpoint parses the document and extracts the information into its application code. There are disadvantages to this strategy. You must revise the document schema when you change the context information. To retrieve the context information, you must parse the document, which can be costly especially if the document passes through intermediaries. There is also no logical separation between the schema for the document request and the schema for the context information. For these reasons, embedding the context information in the message contents may also result in code that is harder to maintain.

Code example 8.4. Context Information in a Document
<PurchaseOrder>
<Id>123456789 </Id>
...
<POContextInfo> <!-- This is where the context data begins -->
   <PriorityProcessing>True</PriorityProcessing>
   <!-- Other context data elements -->
						</POContextInfo>
...
</PurchaseOrder>

The third strategy is to embed context information as a new subelement in a message's SOAP header. For this strategy, clients need to embed this information in a SOAP header and the service needs to extract it. The service can use a JAX-RPC handler to intercept the SOAP message and then extract the header while still keeping it associated with the document. The handler uses this context information to take appropriate actions before the business logic is invoked in the endpoint. This strategy is more elegant because it does not require you to modify the XML schema for the data model exported by the service. Instead, the handler unobtrusively determines the context information from the envelope's header, leaving the message body untouched and unaffected. See Code Example 8.5, which shows how to add context infromation to a SOAP header.

This strategy is preferred to the others since it keeps the context information separate from the document contents and the service interface. This strategy also lets you encapsulate the context information processing in a handler, which keeps the handling logic for context information removed from the business logic.

There are some performance implications of this strategy, since each Web service endpoint invocation runs this handler to manipulate the SOAP message. The context information may be needed in only a few cases, but the handler runs with every invocation. This strategy may also be more difficult to implement.

Code example 8.5. Context Information in SOAP Headers
<SOAP-ENV:Envelope xmlns:SOAP-ENV="SoapEnvelopeURI"
       SOAP-ENV:encodingStyle="SoapEncodingURI">
   <SOAP-ENV:Header>
						<ci:PriorityProcessing>True</ci:PriorityProcessing>
						</SOAP-ENV:Header>
<SOAP-ENV:Body>
        <opc:submitPurchaseOrder xmlns:opc="ServiceURI">
          <opc:PurchaseOrder>
            <!-- contents of PurchaseOrder document -->
             </opc:PurchaseOrder>
        </opc:submitPurchaseOrder>
    </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

Sometimes, the handler needs to pass the context information (or the results of processing the context information) to the endpoint implementation. The way to do this is to use the JAX-RPC MessageContext interface, since this interface is available to both JAX-RPC and EJB service endpoints. If the handler sets the context information in the MessageContext interface, the service endpoint can access it. To illustrate, you first set up a handler class similar to the one shown in Code Example 8.6.

Code example 8.6. Passing Context Information from Handler to Endpoint
public class MyMessageHandler extends
          javax.xml.rpc.handler.GenericHandler {
   public boolean handleRequest(MessageContext mc) {
       SOAPMessage msg = ((SOAPMessageContext)mc).getMessage() ;
       SOAPPart sp = msg.getSOAPPart();
       SOAPEnvelope se = sp.getEnvelope();
       SOAPHeader header = se.getHeader();
       SOAPBody body = se.getBody();
       if (header == null) {
           // raise error
       }
       for (Iterator iter = header.getChildElements();
                     iter.hasNext();) {
           SOAPElement element = (SOAPElement) iter.next();
           if (element.getElementName().getLocalName()
                  .equals("PriorityProcessing")) {
              mc.setProperty("PriorityProcessing",
                 element.getValue());
           }
       }
   ...
   return true;
}

Then, you can get access to MessageContext in the endpoint that receives the request. For an EJB service endpoint, MessageContext is available with the bean's SessionContext. Code Example 8.7 shows the enterprise bean code for the endpoint.

Code example 8.7. Endpoint Receiving Context Information from a Handler
public class EndpointBean implements SessionBean {
   private SessionContext sc;
   public void businessMethod() {
      MessageContext msgc= sc.getMessageContext();
      String s = (String)msgc.getProperty("PriorityProcessing");
      Boolean priority = new Boolean(s);
      ...
   }
   public void setSessionContext(SessionContext sc) {
      this.sc = sc;
   }
   ...
}

8.5.2. Handling Multiple Document Types

A Web service, over time, invariably will need to expand its ability to accept documents of different types. Developers may add new functionality to the same service interface, and this functionality mandates new document types. Although you can accommodate these changes by adding new methods to the interface to accept alternate forms or types of documents, this approach may result in an explosion in the number of methods.

A better strategy for handling multiple document types is to design the service interface with this possibility in mind. You can do so by writing a generic method to represent a document-centric interaction. For example, instead of having multiple methods for each document type such as submitSupplierInvoice, submitSupplier2Invoice, and submitBillingInfo, the endpoint interface has a single method called submitDocument that receives all document types. To accept any type of document, you need to use xsd:anyType as the parameter type for the submitDocument method. The service interface does not have to change to accommodate new document types, just the service implementation changes. See Code Example 3.19 on page 110 for an example.

Since your interface changed to a single method, the implementation needs to change appropriately. The submitDocument method needs to map these documents to the processing logic that handles them. You can apply a Command pattern to this strategy to achieve flexibility in handling these documents. With a Command pattern, you place the commands to manage all schemas of the various document types in one place, identifying each command by schema type. To add a new schema, you simply add a new command that handles the new schema.

Figure 8.10 illustrates how you might apply this strategy. The Web service receives different types of documents from its clients. Each type of document maps to a schema. The service maintains a separate command for each document type represented by its schema. The command mapping happens in the interaction layer, separate from the processing layer and the business logic.

Figure 8.10. Using a Command Pattern to Handle Multiple Document Types


Using this strategy to handle multiple document types has an additional benefit: You can have the contents of the document, rather than the invoked method, determine the processing. To do so, you extend the logic of the command selection to include some of the document content. For example, if you wanted to apply business logic specific to a requestor, you might choose a command based on document type plus the identity of the requestor. For example, the adventure builder enterprise can apply additional business logic—such as verifying an invoice's authenticity—to invoices sent in by less trusted partners.

Create an interface that has a single method to receive documents of different types. Use the Command pattern to map each document to its processing logic.

8.5.3. Consolidating Web Service Interactions

Consolidating Web service interactions is a good way to simplify the complexity of a Web service application. What starts as a straightforward Web service application with basic interactions between a client and a single service often grows into an application that exposes more endpoints and may itself act as a client to other services. The application communication becomes more complicated, and the business logic often becomes closely tied to a particular service. When the number of Web service interactions grows beyond a certain point, you may want to factor out common code for reuse.

For service interactions that rely on document passing, consider using a centralized manager that can broker the Web service interactions and consolidate the interaction layer of your Web services. This centralized manager can be responsible for both incoming and outgoing Web service interactions, and it can also consolidate all client access to a service. A centralized manager strategy applies only to interactions involving document passing, because such interactions can use an interface with a single method to handle all possible documents. Interfaces that pass objects as parameters do not have the flexibility to be this generic—a method passing or returning an object must declare the object type, which can only map to a single document type. The centralized manager needs to handle multiple document types by using the strategy described in “Handling Multiple Document Types” on page 371.

Take, for example, the order processing center interactions with its various suppliers. The order processing center is both a client of and a service to multiple suppliers. The order processing center and the suppliers engage in XML document exchange interactions, and often the interactions are asynchronous since they may span a fair amount of time. Without a centralized manager, your enterprise may have many point-to-point interactions among internal modules and external partners. This may result in the Web service code existing in many places throughout the enterprise. Each endpoint in these point-to-point interactions replicates the same work done by other endpoints, as do each of the clients. Keep in mind that as the number of services you expose grows, it becomes harder to manage this complexity.

Figure 8.11 illustrates how a centralized manager can simplify an enterprise's interactions with its external partners. The top part of the figure shows several entities of an enterprise each communicating with various external partners. The bottom part of the figure shows how much simpler it is to route the same interactions through a centralized manager.

Figure 8.11. Enterprise Interactions with External Partners


To simplify things, the order processing center uses this centralized manager strategy to consolidate the Web service interaction layer code. The centralized manager handles all the Web service requests from the suppliers—it does any necessary preprocessing and interaction layer work, then dispatches requests to the appropriate processing layer business action component. To illustrate, we implemented this strategy between the order processing center Order Filler submodule and the supplier Web services. The centralized manager handles XML documents sent in by suppliers. The centralized manager extracts information from these incoming requests, and this information lets it know how to handle the request. It may reformat the message content or transform the content to the internal canonical form used by the enterprise. The centralized manager routes the reformatted message to the correct target system. It can also validate incoming documents and centralize the management of document schemas. For outgoing Web service calls, the centralized manager acts as the client on behalf of the internal modules.

Not only does it centralize interaction layer and client functionality so that it is easier to manage incoming and outgoing Web service messages, use of this strategy also decouples components that access a service from those that focus on business logic. Your enterprise ends up with a clean Web service layer that is decoupled from the processing layer.

For handling incoming requests, you can establish a single interface and endpoint that all clients use. You can add context information to each request to enable an easy identification of the type of the request, such as purchase order or invoice. When this single endpoint acts as the interaction layer for several Web services, it can perform a number of functions, depending on what is available to it. If it has access to schemas, the endpoint can perform validation and error checking. If it has access to style sheets, the endpoint can transform incoming requests to match the canonical data model.

The centralized manager may also handle security tasks appropriate for the interaction layer and can translate incoming documents to an internal, enterprise-wide canonical data model. The key point is that the centralized manager needs access to information that enables it to perform these services.

A centralized manager may also use a message router to route requests to the appropriate business component recipients in the processing layer. A message router is responsible for mapping requests to recipients.

As the number of Web service interactions grow within your enterprise, consider consolidating them in a centralized manager.

8.5.4. Canonical Data Model

Establishing a canonical data model is a good strategy for exchanging messages that rely on different data models. (See “Data Transformation” on page 275 for more details on using a canonical data model.) The adventure builder enterprise receives messages from suppliers through the centralized manager, which provides a natural place to hold a canonical data model. The canonical data model we use is represented in XML. The order processing center provides the canonical data model used for its interaction with the Web site.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset