Showing posts with label Webservice. Show all posts
Showing posts with label Webservice. Show all posts

Friday, January 19, 2018

Replace Namespace with XSLT in OSB

Recently, I'm working on a project and the vendor changed their framework for implementing their web services. This change caused their web service cannot fully compatible with existing WSDLs and the second level element will not have a correct namespace as before.

Before the change, the request will like below.
<ns0:getRelatedContacts xmlns:ns0="http://ws.crm.victor.com" xmlns:ns1="http://lib.ws.victor.com">
    <ns0:contactRequest>
        <ns1:FAID>FAID_1</ns1:FAID>
        <ns1:subscriptionId>subscriptionId_1</ns1:subscriptionId>
    </ns0:contactRequest>
</ns0:getRelatedContacts>

After the vendor change, the request will like below. The elment contactRequest lost its namespace.
<ns0:getRelatedContacts xmlns:ns0="http://ws.crm.victor.com" xmlns:ns1="http://lib.ws.victor.com">
    <contactRequest>
        <ns1:FAID>FAID_1</ns1:FAID>
        <ns1:subscriptionId>subscriptionId_1</ns1:subscriptionId>
    </contactRequest>
</ns0:getRelatedContacts>

The response has the same issue and second level element will not have a namespace. Due to the vendor cried they might take too much effort to fix it (I don't think it is true. :)), our team has to provide a solution to fix and make the service behavior we exposed to clients same as before and hence we need to find out a way to fix the namespace issue.

Definitely, there isn't a out-box solution. We have to create some code by ourselves to resolve this specific issue.

For replacing namespace, it is pretty simple with XSLT and can be done by a element copy. The next issue is to find out the second level element in the request to remove the namespace and adding the namespace back in response.

Here are the code for removing namespace from request.
<xsl:stylesheet version="1.0"  xmlns:xsd="http://www.w3.org/2001/XMLSchema"  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
   
   <xsl:template match="/">
    <xsl:apply-templates/>
  </xsl:template>
  
  <xsl:template match="*[count(ancestor::node())=2]">
    <xsl:element name="{local-name()}">
      <xsl:copy-of select="@*"/>
      <xsl:apply-templates select='@*|node()'/>
    </xsl:element>
  </xsl:template>

  <xsl:template match='@*|node()'>
    <xsl:copy>
        <xsl:apply-templates select='@*|node()'/>
    </xsl:copy>
  </xsl:template>
</xsl:stylesheet>

Here are the code for adding namespace back in response.
<xsl:stylesheet version="1.0"  xmlns:xsd="http://www.w3.org/2001/XMLSchema"  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
      
   <xsl:template match="/">
    <xsl:apply-templates/>
  </xsl:template>
  
  <xsl:template match="*[count(ancestor::node())=2]">
    <xsl:element name="{local-name()}" namespace="{namespace-uri(parent::node())}">
      <xsl:copy-of select="@*"/>
      <xsl:apply-templates select='@*|node()'/>
    </xsl:element>
  </xsl:template>

  <xsl:template match='@*|node()'>
    <xsl:copy>
        <xsl:apply-templates select='@*|node()'/>
    </xsl:copy>
  </xsl:template>
</xsl:stylesheet>

The above codes were tested in OSB 11g and 12c. They worked as what I expected.

Tuesday, May 14, 2013

OSB-SOAP Action Header Issue

Issue:
Recently, I worked on an existing code developed by somebody else long time ago and a defect was opened for SOAP action header issue. The invoked web service always complained 'no SOAPAction header!'.

As the business service was developed by vendor and they used RPC style, we have to define the business service as any XML service. (If we defined as a WSDL webservice, OSB threw exception when it got the response - unrecognized response.) As the business service was set an any XML service, it looks like the the OSB can automatically set soap action header.

Resolution:
In OSB proxy service, before the service callout, put a replace action to replace the soap action hdead in outbound.
In this application, I just used the soap action header of inbound to replace the one of outbound by the easiest way. (From the OSB console, I saw the soap action header is empty string for the initial request and same as the one needed for the service call, then I just copied them from Inbound Request.)

Note: A Transport Headers action looks like not work properly and the soap xml was modified by OSB automatically and caused an additional soap body was added to the soap envelop incorrectly.

SOAPAction References:

Thursday, September 06, 2012

Web Service Data Binding Style



Wrapper Style - the root element of the message (wrapper element) is the operation name, which is not part of the payload.  The children of the root element must map directly to parameters of the operation's signature.

Non-Wrapper Style (bare) - the entire message is passed to the service operation. The reply message is handled in a similar way.

Wrapper or Non-Wrapper can only be used in conjunction with the document/literal style defined in WSDL.  It defines how web service request or reply messages are interpreted.


public String helloworld(
        @WebParam(name = "firstName")String firstName, 
        @WebParam(name = "lastName") String lastName );
The request looks like:
<soap:Envelope 
    xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" 
    xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <soap:Body>
    <helloworld xmlns="http://personservice">
      <firstName>John</firstName>
      <lastName>Doe</lastName>
    </helloworld>
  </soap:Body>
</soap:Envelope>

public String helloworld(
        @WebParam(name = "name", targetNamespace="http://www.myname.com") 
        Name name );
The request looks like:
<soap:Envelope 
    xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" 
    xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <soap:Body>
    <ns0:name xmlns:ns0="http://www.myname.com">
      <firstName>John</firstName>
      <lastName>Doe</lastName>
    </ns0:name>
  </soap:Body>
</soap:Envelope>


In JAX-WS, "SOAPBinding" annotation can be used to specify the style.
@SOAPBinding(parameterStyle=SOAPBinding.ParameterStyle.BARE)

Note
The parameter style "WRAPPED" is the default. In JAX-RPC the "WRAPPED" style is specified in the web service mapping xml file by adding "wrapped-element" element to the service endpoint mapping.

The wsdl2java will automatically assume " WRAPPED" if operation name matches the wrapper element name.

Wrapper or Non-Wrapper are a data binding style and not part of the contract of a web service, also it is not mentioned in the WSDL file.The web service client can be implemented with "non-wrapper" style for and should interoperate with a "wrapper" service without a hitch in theory at least.

The wrapper style is supported widely event it is not universally. The wrapper style is really an RPC-style binding over "document/literal" WSDL style. The method name is explicitly provided in the message.

Advantages of wrapper style.



  • Wrapper service can only have one message part in WSDL, which guarantees that the message (consisting of the method element that contains parameters) will be represented by one XML document with a single schema.
  • RPC style message definitions in WSDL have to use schema types, whereas with the document style we can refer directly to element names. This makes XML message representation more "precise", it is also easier to validate.

The wrapper style has one interesting drawback as it may not be immediately obvious. If a service signature changed, for example, a new parameter was added, clients will have to change as well. With wrapper style, all parameters have to be present in the XML message although they can be defined as null using "xsd:nil" attribute. This is despite the fact that the element corresponding to the parameter can be defined as optional in the schema. The non-wrapper style does not have this problem and adding a new optional element does not affect clients as binding is always name-based. This creates somewhat tighter coupling between wrapper style consumers and providers.

JAX-WS does impose some additional restrictions on the wrapper style. The most important one is the wrapper element's content type must be "sequence". By this, a method's signature always represented as an ordered list of arguments.

For non-wrapper style, the most obscure thing is how a SOAP engine decides which operation to invoke based on the message type when a web service has multiple operations as operation name is not explicitly provided by the message. The "SOAPAction" header can be used for that purpose, however this header is HTTP-only and also optional in JAX-WS. For "non-wrapper", each operation must accept a message that corresponds to a unique XML element name. Note that it is not enough to define different WSDL messages using "wsdl:message" element, each message must be represented by a different element in the schema. Web service engines use unique element names to determine Java method names that correspond to WSDL operations. This also means that with non-wrapper you CANNOT have different operation names processing the same message.

The wrapper does not support overloaded methods.
The non-wrapper does not support methods with the same signature.

Thursday, March 01, 2012

XML Schema - Structure Style

XML Schema  Design Pattern: Russian Doll, Salami Slice, Venetian Blind, and Garden of Eden

Russian Doll
The Russian Doll design approach has a schema structure mirroring the instance document structure, e.g., declare a Book element and within it declare a Title element followed by a Publisher element:

<xsd:element name="Book">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="Title" type="xsd:string"/>
<xsd:element name="Publisher" type="xsd:string"/>
</xsd:sequence>
</xsd:complexType>
</element>

The instance document has all its components bundled together. Likewise, the schema is designed to bundle together all its element declarations.


Salami Slice
Salami Slice design disassembles the instance document into its individual components. In the schema, we define each component (as an element declaration), and then assemble them together:


<xsd:element name="Title" type="xsd:string"/>
<xsd:element name="Publisher" type="xsd:string"/>
<xsd:element name="Book">
<xsd:complexType>
<xsd:sequence>
<xsd:element ref="Title"/>
<xsd:element ref="Publisher"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>


Note how the schema declared each component individually (Title, and Publisher) and then assembled them together in the creation of the Book component


Venetian Blind

Similar to the Russian Doll approach in that they both use a single global element.  The Venetian Blind approach describes a modular approach by naming and defining all type definitions globally (as opposed to the Salami Slice approach which declares elements globally and types locally).  Each globally defined type describes an individual "slat" and can be reused by other components.  In addition, all the locally declared elements can be namespace qualified or namespace unqualified (the slats can be "opened" or "closed") depending on the elementFormDefault attribute setting at the top of the schema.  If the namespace is unqualified then the local elements in the instance document must not be qualified with the prefix of the namespace.


<?xml version="1.0" encoding="UTF-8"?>
<xs:schema targetNamespace="TargetNamespace" xmlns:TN="TargetNamespace" xmlns:xs="http://www.w3.org/2001/XMLSchema"
elementFormDefault="qualified" attributeFormDefault="unqualified">
   <xs:element name="Book" type="TN:BookType" maxOccurs="unbounded"/>
   <xs:complexType name="BookType">
       <xs:sequence>
           <xs:element name="Title" type="xsd:string"/>
           <xs:element name="Publisher"type="xsd:string"/>
           <xs:element name="PeopleInvolved" type="TN:PeopleInvolvedType" maxOccurs="unbounded"/>
       </xs:sequence>
   </xs:complexType>
   <xs:complexType name="PeopleInvolvedType">
       <xs:sequence>
           <xs:element name="Author"type="xsd:string"/>
       </xs:sequence>
   </xs:complexType>
</xs:schema>




Garden of Eden
The Garden of Eden design is a combination of Venetian Blind and Salami Slice. You define all the elements and types in the global namespace and refer to the elements as required.

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema targetNamespace="TargetNamespace" xmlns:TN="TargetNamespace"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
elementFormDefault="qualified" attributeFormDefault="unqualified">
   <xs:complexType name="BookType">
       <xs:sequence>
           <xs:element ref="Title"/>
           <xs:element ref="Publisher"/>
           <xs:element ref="PeopleInvolved" maxOccurs="unbounded"/>
       </xs:sequence>
   </xs:complexType>
   <xs:complexType name="PeopleInvolvedType">
       <xs:sequence>
           <xs:element ref="Author"/>
       </xs:sequence>
   </xs:complexType>
   <xsd:element name="PeopleInvolved type="TN:PeopleInvolvedType"/>
   <xs:element name="Title" type="xsd:string"/>
   <xs:element name="Publisher"type="xsd:string"/>
   <xs:element name="Author"type="xsd:string"/>
   <xs:element name="Book" type="TN:BookType" maxOccurs="unbounded"/>
</xs:schema>

Because it exposes all its elements and types globally, Garden of Eden, like Salami Slice, is completely reusable. However, because Garden of Eden exposes multiple elements as global ones, there are many potential root elements.



Thursday, March 18, 2010

Stub caching and concurrent reuse problems in Axis

Reference Stub caching and concurrent reuse problems

Somebody tried to cache the generated stubs for reusing by concurrent clients
because instantiating of them takes too long. But every time he started 4+ concurrent clients for the same web-service, he would receive some weird exceptions from the core of Axis. This happened only in case of caching the stubs and not issue for creating new stub for every client but the performance.

Some people replied the question and mentioned the cache of stub was not hoped and the internals of the stubs may screw up if cached! If you are using the usual no
args constructor of the stub, the stub may need to create its own configuration context and that may take significant time. You can cache the config context and create the stub passing in your config context, instead of caching stub.

In the mail list, also somebody mentioned they had found two important factors to keep in mind when reusing stubs:

  1. The stubs are not thread safe, so you cannot use the same stub in
    two concurrent threads

  2. Recently discovered that even the stub constructor is not thread safe! So two concurrent threads cannot call the constructor at the same time.



If you have a typical architecture that reuses client processing threads, then each needs their own stub but once it creates a stub it can continue to use that indefinitely.

Another useful thing to do is:

options.setProperty(HTTPConstants.REUSE_HTTP_CLIENT, new Boolean(true));

Tuesday, January 19, 2010

JAX-WS Implementations

There are multiple APIs for the Java platform, e.g. for database access or web applications. The developer has to code against a standard not against a product. The particular tools and servers stay replaceable. For example a web application can be operated with both the Application Server IBM Web Sphere and the Web Container Apache Tomcat. Due to the standardization by the Java Enterprise Edition the exchange of a server can be done with little effort.

Unfortunately, Web Services are a different story. Indeed there is the JAX-WS specification, but there are still too many unanswered questions as well as alternative approaches of applying Web Services. Which SOAP implementation is suitable depends on the requirements and the environment. The sections below are describing the tools and standards that are available for developers of Web Services.

Apache Axis2
Axis 2 is the follow-up of the popular Axis1 framework. Axis2 is based on a completely new architecture and has been re-developed from scratch.

The deployment of services for Axis 1 has often been criticized. Therefore Axis 2 has a completely new deployment model. An Axis 2 runtime is a Web application and can be installed on every JEE compliant Application Server. The Axis 2 web application itself is a container for Web Services now. Web Services are packed into an own file format with the file extension aar. Due to these archives, Web Services can be installed and configured by a simple user interface at run time. In Axis 2 the services can be configured by the traditional deployment descriptors, e.g. the file services.xml.

Modules providing additional functionality, for example WS-* standard support, can also be installed during runtime. A Web Service is regarded as an independent package which can be installed into the Axis 2 runtime environment.

Writing an Axis 2 project requires a lot of knowledge about the build tool Ant. Knowledge about the build tool is essential to write an Axis 2 project. For example the WSDL2JAVA task is generating a temporary project including a build-file. Then the projects build-file has to call the generated build-file. If a Web Service uses a library, e.g. a JDBC driver, then the library has to be copied into the generated project using Ant on each build. So development with Axis 2 will be very difficult if you are not familiar with Ant.

Apache CXF
CXF is also a project of the Apache software foundation. CXF came up from a fusion of the XFire and Ionas Celtix projects.

CXF was developed with the intention to integrate it into other systems. This is reflected in CXF API and the use of the Spring framework. Therefore it is very simple to integrate CXF into existing systems.

CXF respectively its predecessor XFire was integrated into numerous open and closed source projects like ServiceMix or Mule.

A proprietary API as well as the standardized JAX-WS interface are available for the development and use of Web Services.

JAX-WS
The Java API for XML based Web Services is the successor of the JAX-RPC specification. JAX-WS respectively its predecessor is message based and supports asynchronous communication. The Configuration is managed by annotations therefore Java 5 or higher is required. JAX-WS isn't downwardly compatible to its predecessor JAX-RPC. With JAX-WS it is pretty easy to write and consume Web Services. The default values of numerous parameters are comfortable for the programmer, so that simple Pojos declared with a @WebService annotation can be used as a Service. Listing 1 shows a simple implementation of a Web Service using the @WebService annotation.

import javax.jws.WebService;
import javax.jws.WebMethod;

@WebService
public class HelloWorldService {

public String helloWorld() {
return "Hello World!";
}
}

Listing 1: HelloWorld Web Service using JAX-WS

A suitable WSDL document can also be generated from the class. Other annotations can concertedly exert influence of the WSDL document. For example other namespaces or element names can be used. If JAXB is already known, its annotations can be used to define the serialization in every detail. With the contract first approach a Service Interface, JAXB annotated classes for serialization and a skeleton for the implementation can be generated. According to the WSDL document the generated classes can have numerous annotations. Annotations are also the main point of criticism of JAX-WS. Despite this criticism the JAX-WS specification came out well. It is well attuned and combinable with other Java and Java EE specifications. For example, Listing 2 shows a stateless EJB 3.0 Bean which acts as a Web Service at the same time.

@WebService
@Stateless
public class MyService{
public String hello(String name) {
return "Hallo"+name;
}
}

Listing 2: Stateless SessionBean acting as Web Service

JAX-WS Reference Implementation
The JAX-WS Reference Implementation represents the core piece of the Web Services protocol stack Metro. The Metro Stack provides support for the following Web Services standards:

WS-Addressing
WS-Policy
Web Services Security aka WS-Security
WS-Transaction
WS-Reliable Messaging
WS-Trust
WS-SecureConversation

Metro is documented in detail. Apart from the JAX-WS, JAXB and JWS specifications there are numerous tutorials und samples. The Netbeans IDE as well as the tutorials of the enterprise pack makes it particularly easy to get started. Of course, Eclipse can also be used for the development with Metro.

Web applications containing Web Services which have been realized with JAX-WS are executable in the Glassfish Application Server. To make services also executable in other application servers, two libraries (JAX-WS and JAXB) have to be installed. Application servers such as JBoss, WebSphere or Tomcat can be upgraded with JAX-WS within about 10 minutes.

Performance
Due to the modern streaming XML parser, the performance of all three SOAP engines is very well. The ping time for a locale roundtrip is about 2-4 milliseconds (message size about 3KB, Dual Core Notebook). Therefore the time delay by the SOAP communication is negligible in many projects.

WS-* Standards
The support of the WS-Standard family can also be decisive for the selection of a SOAP engine. For example, messages sent to services can be secured with signatures as described in the Web Service Security standard (in short WSS). Table 1 shows the support for WS*-Standards of the toolkits.

Conclusion
None of the Web Services frameworks is in general superior to the others. Axis 2 is structured modularly, has many features and can be used as an application server for Web Services. A special feature of Axis 2 is the support of removable binding frameworks, for example XMLBeans. Axis 2 together with the XMLBeans framework included is well suited for Web Services which are using very complex schema definitions. The disadvantages of Axis 2 are its complexity as well as the insufficient JAX-WS support. Therefore anyone who wants to work with JAX-WS should choose Apache CXF or the reference implementation.

Those who prefer a seamless integration with the Spring framework are well advised with the JAX-WS implementation. Furthermore CXF is slim and easy to use. CXF is the tool of choice if a SOAP engine has to be embedded into an existing software.

Who just wants to code against the standard is well advised with the JAX-WS implementation. The enterprise pack of the Netbeans development environment supports JAX-WS RI very well. Only a few clicks are needed to build a server or to call a Web Service.

I hope this article could help you with the decision for a WS toolkit.

StandardsAxis2CXFJAX-WS/Metro
WS-AddressingXXX
WS-CoordinationX(2)X
WS-MetadataExchangeX
WS-PolicyXXX
WS-ReliableMessagingX(3)XX
Web Services SecurityX(1)X(4)X
WS-SecureConversationX(1)X
WS-SecurityPolicyX
WS-TransactionX(2)X
WS-TrustXX
WS-Federation

Table 1: Support for WS-* Standards (stand: Juli 2008)

(1) Supported by the additional module Apache Rampart
(2) Supported by the additional module Apache Kandula2
(3) Supported by the additional module Apache Sandesha2
(4) By Apache WSS4J Interceptor

JAX-RCP vs JAX-WS

JAX-RPC
A specification/API for Java developers to develop SOAP based interoperable web services. This API is now obsolete, and may be dropped from the next JEE version.

JAX-WS
The successor to JAX-RPC. It requires Java 5.0, and is not backwards-compatible to JAX-RPC. This article describes the high-level differences to JAX-RPC.

SAAJ
Another specification/API for using SOAP envelopes with or without attachments. It operates on a lower level than JAX-RPC or JAX-WS, both of which will use SOAP envelopes based on SAAJ if needed.

JAX-RPC 2.0 (Java API for XML Based RPC) has been renamed to JAX-WS 2.0 (Java API for XML Web Services).

This was done for a number of reasons, but the main reasons are:
The JAX-RPC name is misleading, developers assume that all JAX-RPC is about is just RPC, not Web Services.

By renaming JAX-RPC to JAX-WS we can eliminate this confusion. JAX-RPC 2.0 uses JAXB for all databinding.

As the bindings are different in JAX-RPC 1.1, it introduced a number of source compatibility issues. The migration from JAX-RPC 1.1 to JAX-RPC 2.0 is not cookie cutter as generated Java code and schemas will be different than those generated by JAX-RPC 1.1.

Although the renaming does not ease this migration, it does let the developer know that these are two separate technologies, hence the more difficult migration is more palatable.

Maintaining binary compatibility with the JAX-RPC 1.1 APIs, was hindering our goal of ease-of-development. Because we had this binary compatibility requirement, many legacy APIs were exposed such as the various methods on javax.xml.rpc.Service and the javax.xml.rpc.Call. Having these legacy APIs around would confuse developers. By renaming JAX-RPC 2.0 to JAX-WS 2.0 we no longer have this binary compatibility requirement and we can rid the APIs of these legacy methods and interfaces and we can focus on a new set of APIs that are easier to understand and use.

WebService Implementations
Apache Axis
An open source implementation of the Java WS APIs for sending and receiving SOAP messages. Axis 1 supports JAX-RPC and SAAJ, while Axis 2 supports SAAJ and JAX-WS.

Apache SOAP
The first SOAP implementation. It is now obsolete. It's better to use Apache Axis to avail oneself of the latest features.

Sun JWSDP
Sun Java Webservices Developer Pack, is an implementation of JAX-RPC, SAAJ and various other XML Java technologies. It is now deprecated in favor of GlassFish.

Metro
The web services stack used in GlassFish?. It supports SAAJ, JAX-WS, WS-Security and other standards.

JAX-RS
It is a Java API for RESTful web services.
Jersey is the reference implementation of the JAX-RS API, as defined in the JSR-311 standard for RESTful web services.

For more info, see http://faq.javaranch.com/java/WebServicesFaq.

Wednesday, November 25, 2009

Web Services Security for Axis

Web Services Authentication with Axis

Web Services Authentication with Axis 2

What's New in WSDL 2.0

WSDL 1.2 was renamed WSDL 2.0 because of its substantial differences from WSDL 1.1. Some of these changes include:

.Adding further semantics to the description language. This is one of the reasons for making targetNamespace a required attribute of the definitions element in WSDL 2.0.

.Removal of message constructs. These are specified using the XML schema type system in the types element.

.No support for operator overloading.

.PortTypes renamed to interfaces. Support for interface inheritance is achieved by using the extends attribute in the interface element.

.Ports renamed to endpoints.

(From http://www.xml.com/pub/a/ws/2004/05/19/wsdl2.html)

Wednesday, October 21, 2009

JAX-RS: The Java API for RESTful Web Services

JAX-RS: The Java API for RESTful Web Services

http://www.developer.com/java/article.php/3843846/JAX-RS-The-Java-API-for-RESTful-Web-Services.htm

Friday, October 24, 2008

Reap the benefits of document style Web services

http://www.ibm.com/developerworks/webservices/library/ws-docstyle.html

James McCarthy (mailto:jmccarthy@symmetrysolutions.com?subject=Reap), President and CTO, Symmetry Solutions, Inc.

While most Web services are built around remote procedure calls, the WSDL specification allows for another kind of Web services architecture: document style, in which whole documents are exchanged between service clients and servers. In this article, James McCarthy explains what document style is and when you should use it.

Buried deep in the Web Service Definition Language (WSDL) specification is a very subtle switch that can turn the SOAP binding of a Web service from a remote procedure call to a pass-through document. The style attribute within the SOAP protocol binding can contain one of two values: rpc or document. When the attribute is set to document style, the client understands that it should make use of XML schemas rather than remote procedure calling conventions. This article will provide a description of this WSDL switch, describe its benefits, and explain when you should use pass-through documents.
Setting your service to use document style
First, let's briefly touch on a few point about WSDL to understand how this subtle change occurs. WSDL is an XML specification that is used to describe network services and the protocol-specific requirements for reaching an endpoint (the service). WSDL describes services in abstract terms; through an extensible binding definition, it is able to define the protocol and data format specifications for calling a service in concrete terms. The following grammar, taken directly from the WSDL specification, shows the extensibility elements contained within a binding:

Listing 1. WSDL grammar for extending elements within a binding

<wsdl:definitions .... >
<wsdl:binding name=3D"nmtoken" type=3D"qname"> *
<-- extensibility element (1) --> *
<wsdl:operation name=3D"nmtoken"> *
<-- extensibility element (2) --> *
<wsdl:input name=3D"nmtoken"? > ?
<-- extensibility element (3) -->=20
</wsdl:input>
<wsdl:output name=3D"nmtoken"? > ?
<-- extensibility element (4) --> *
</wsdl:output>
<wsdl:fault name=3D"nmtoken"> *
<-- extensibility element (5) --> *
</wsdl:fault>
</wsdl:operation>
</wsdl:binding>
< /wsdl:definitions>

The WSDL specification (see the Resources section below for a link) currently describes three binding extensions: HTTP GET/POST, MIME, and SOAP version 1.1. The binding extensions defined in HTTP GET/POST and MIME are used to define the requirements to communicate with standard Web applications that may or may not return XML documents. When sending or returning an XML document, the HTTP GET/POST binding extension is implicitly document style.
The SOAP binding extension is used to define a service that supports the SOAP envelope protocol. The SOAP envelope is a simple schema that is designed to contain an XML message, providing an application-specific header and a body portion of the message. The SOAP binding extension allows the WSDL document to declare the requirements of a SOAP message so that the application is able to properly communicate with the service. The SOAP extension allows the style of the SOAP message to be declared as either document or RPC. If the style attribute is declared in the soap:binding element, then that style becomes the default for all soap:operation elements that do not explicitly declare a style attribute. If the style attribute is not declared in the soap:binding element, then the default style is document. Here is an explicit declaration of document style:

Regardless of the declaration within the soap:binding element, the soap:operation element can override the declaration for each operation, like so:

In a SOAP message for which document style is declared, the message is placed directly into the body portion of the SOAP envelope, either as-is or encoded. If the style is declared as RPC, the message is enclosed within a wrapper element, with the name of the element taken from the operation name attribute and the namespace taken from the operation namespace attribute.

Benefits of document style
No one can dispute that the ability to invoke a cross-platform remote procedure call using XML is extremely useful and is a compelling argument for using Web services. But if Web services were constrained exclusively to RPC messaging, the reach of the technology would be limited. Fortunately, developers have a choice of using either RPC or document style messaging and are able to use the right technology for the tasks they face.

  • With document style, you can make full use of XML
    The XML specification was developed to allow ordinary data that is usually locked up in a proprietary format to be described in an open format that is human readable, self-describing, and self-validating. When a Web service uses document messaging, it can use the full capabilities of XML to describe and validate a high-level business document. When a service uses RPC message formatting, the XML describes the method and the parameters encoded for the method call and cannot be used to enforce high-level business rules. In order to enforce these rules, the RPC message must include an XML document as a string parameter and hide the validation within the method being called. For this reason, some of the benefits of XML are lost, or at least hidden within the back-end application.

  • Document style does not require a rigid contract
    Another reason to use document messaging is that a remote procedure call is meant to be relatively static and any changes to the interface would break the contract between the service and the application. If a service is widely distributed, then it is likely that a large number of applications have produced stub code from its WSDL document. Changing the WSDL would cause all of the applications that rely on a specific method signature to break and a lot of support lines to ring. Good design dictates that the method signature of an RPC message service should never change. With document messaging, the rules are less rigid and many enhancements and changes can be made to the XML schema without breaking the calling application.

  • Document style is better suited for asynchronous processing
    When businesses are using a Web-based application to exchange information over the Internet, the application should be able to use a guaranteed delivery mechanism to improve its reliability, scalability, and performance. To achieve this, an application will generally use asynchronous message queues. Since a document message is usually self-contained, it is better suited for asynchronous processing and can be placed directly into the queue. The reliability of the application is improved because the message queue guarantees the delivery of the message even if the target application is not currently active; performance is improved because the Web application simply delivers the document to a queue and is then free to perform other tasks; and scalability is improved because the document is offloaded to one or more instances of an application that handles its processing.

  • Document style makes object exchange more flexible
    The design of a business document is often very well suited to object-oriented architectures. As a result, two applications may be designed to exchange the state of an object by using XML. In contrast with object serialization, in an object exchange, each end of the exchange is free to design the object as it sees fit as long as the exchange conforms to the agreed upon XML document format. One reason for not using object serialization is to support client-side and server-side implementations of an object. Many current industry-specific XML schemas are designed as client/server architectures in which the processing that is done at the client is separate from the processing intended at the server. As is often the case, the client is simply requesting or saving information in a specific document format that is persisted at the server. Certainly, this type of exchange could be done using an RPC message, but the encoding scheme of such a message places constraints on the design of the object at each end. These constraints are not a problem with document style.


    When to use document style
    When should you use document style? The short answer: Anytime you are not interfacing to a preexisting remote procedure call, the benefits of document style may outweigh the extra effort that is often required to interface to the service. A caveat: The effort to build a service that uses document messaging is usually greater than the effort required to build an RPC message service. This extra effort usually involves the design of an XML schema or support for a preexisting schema, as well as the extraction of relevant information from a document. The schema design is important because the XML parser uses the schema to validate the document, supporting the intended business rules. Additional effort is required by the service to extract relevant information from the document to be used while handling the request. In contrast, an RPC message only requires the design of the method interface, from which it will automatically marshal and unmarshal the parameters.
    When making your decision to publish a service, you might want to consider the following questions. I'll examine the consequences of your answers in the following sections.
    Is this service interfacing to a preexisting procedure call and is the procedure call stateless?
    Is the service to be used only within your organization, or by outside users as well?
    Is one of the parameters simply an XML document specification?
    Does the service require a request/response architecture?
    Do the parameters represent complex structures that may benefit from an XML document schema for validation?
    Can all of the information that needs to be exchanged be reasonably contained in memory?

  • Use document style when maintaining application state
    You should consider a document architecture for your service if multiple procedures must be called in a particular sequence to maintain application state. If multiple procedure calls are required, then the procedure is not stateless and the service must maintain application state. Maintaining state within a Web service can be difficult; in the case of a remote procedure call, very few client platforms will generate stub code that is able to support state information. One possible solution is to use document architecture and pass the contents of an entire transaction within the document. In this case, the service will perform the calls to ensure that the proper sequence is maintained inside the service and state information is not maintained beyond a single transaction. If state information is still required, it can be built in to the resulting document, or the client application can maintain a token that identifies its state to the service.

  • Use document style to publish services for outside partners
    If an application is being published outside of the organization, the publisher has very little control over who is relying on the service and what the consequences will be if any changes are made. In such cases, it may be more advantageous to use document messaging and support a common exchange protocol such as ebXML. Common exchange protocols are evolving to improve the management of external exchanges so that new trading partner agreements can be rapidly deployed. Also, if your service does not require a request/response architecture, then common exchange protocols are better designed to handle authentication, reliable message delivery, and asynchronous request/response.

  • Use document style to ease validation and use of complex documents
    If your service is using a string parameter to pass or return an XML document, or if one of its parameters is an object with a complex structure that requires custom handling, then document messaging may be the better alternative. Hiding the true meaning of a parameter within a string can often lead to valid calls with invalid parameters. If the service publishes an XML document schema, then it is easier to validate against that schema prior to calling the service. A complex structure is often used to pass hundreds of pieces of information making up a complete transaction. When dealing with complex structures, a remote procedure service may have to deal with custom marshaling code while the application is still responsible for meticulously validating each element of the structure. If document messaging is used, then the application programmer can offload validation to the document designer using an XML schema, and no custom marshaling code is required.

  • Use document style to minimize in-memory processing
    One final consideration when choosing between document and RPC messaging is the amount of information that may need to be handled. Since most if not all of the implementations that marshal parameters in RPC messaging perform this operation in-memory, memory constraints may make RPC messaging unfeasible. Many document-messaging services are able to choose between DOM and SAX handling of the document and as a result are able to minimize in-memory processing. This is particularly critical for a Web service that may be required to handle thousands of requests, many simultaneously.


    Conclusion
    When designing your next Web service, you need to consider all of the options that the current WSDL specification gives you. Before starting with a procedural interface, consider how the service will be used, who will be using it, and the type and volume of information that needs to be exchanged. Designing and developing a document style Web service may require a little more effort, but in many cases the effort will pay off in the quality of information and the reliability of the exchange.

    Resources
    "Deploying Web services with WSDL," Bilal Siddiqui (developerWorks, November 2001) is a good introduction to the Web services and Web Services Description Language.
    Check out the specifications for WSDL and SOAP.
    The XMethods site is hosting a demo Web service that is built using document style.
    Check out the latest on IBM's Web Services initiative.


  •