Thursday, March 24, 2011

JAXWS annotations

In the previous post I discussed how to create a simple JAX-WS enabled web service. For accomplishing the same we used the following 2 annotations:

  1. @WebService
  2. @WebMethod

By using the above 2 annotations and a number of pre-defined defaults for annotations not added we were able to generate a WSDL mapping to the Java implementation. In case we wish to customize the WSDL generated, JAX-WS gives us a set of annotations that can be used. The different annotations come from 3 different JSR's and can be used to customize the different parts of the WSDL. The different JSR's are:

  1. Web Services Metadata Annotations (JSR 181)
  2. JAX-WS Annotations (JSR 224)
  3. JAX-WS Common Annotations (JSR 250)

One point worth noting here is that these annotations are useful in customizing the WSDL file but not the JAXB binding part of it. If we want to customize the JAXB binding (i.e. the XSD Schema details) we need to add JAXB annotations on the JAXB classes (request/response parameters).

To get a list of each of the annotations in JAXWS please refer the following site.

Wednesday, March 16, 2011

JAX-WS Hello World Example

    In this article I provide a step-by-step illustrated example on creating a simple Hell World Service example by using JAX-WS.

Service – Hello World service exposing one method called greet. The method implementation accepts a first name and a last name and returns a greeting string.

Stack – JAX-WS with Glassfish Server, Eclipse for development.



Procedure:

Step 1: Create a Dynamic Web Project in eclipse, with the name "JAXWSHelloWorld".





Step 2: Create a simple implementation class called com.jaxws.example.HelloWorldEndpoint. It will contain a single public method called greet() which accepts 2 strings (firstname and lastName) and returns a greeting message. Then annotate the class with the @WebService annotation and the greet method with @WebMethod annotation.

The @WebService has the serviceName attribute. The value of this attribute is the name of the service in the WSDL and also the URL at which the service is available.

The @WebMethod has the attribute operationName. The value of this attribute is the name of the operation defined in the WSDL.

Please note these are not mandatory and are used only for reference/ease of debugging.

The sample source is given below.



Note: The values attributes of annotation are optional. More details on what they mean will be explained later.


Step 3: Create the related resources (JAXB binding files, WSDL and schema files and corresponding classes). For the run the wsgen bat available with JDK 1.6 or Glassfish with the following parameters:

wsgen –verbose –cp build/classes –s src –wsdl –r WebContent\WEB-INF\wsdl –d build\classes com.jaxws.example.HelloWorldEndpoint

-verbose : prints the operation being executed

- cp <folder> : the location of the base folder where the class file of the Endpoint (HelloWorldEndpoint) is located.

-s <folder> : the location where the generated source files (JAXB binding) are stored

-wsdl : specifies that the WSDL should be generated

-r <folder> : the location of the folder where the resources/artifacts will be generated

-d <folder> : the location of the folder where the generated class files (of JAXB Binding and JAXWS files) will be kept.





Step 4: Deploy the application on the server (Glassfish). To deploy the application, import the glassfish server into eclipse and then just simply right click the project choose Run As > Server. When the server starts monitor the logs. In the logs you will see a line about the WebService Endpoint successfully deployed and the location of the endpoint.

Note: The location is of the format -> http://url:portNumber/applicationName/serviceName[Of Endpoint]





Step 5: The web service is deployed. Hit the URL of the endpoint specified during deployment [http://locahost:8080/JAXWSHelloWorld/HelloWorld] in my case. You should be able to see a dynamically generated page detailing the service and operations exposed.






Step 6: The Web service is now deployed. To confirm check the WSDL deployed the link for which is available on the generated screen. [http://localhost:8080/JAXWSHelloWorld/HelloWorld?wsdl] in my case.



This is a generated WSDL by the JAXWS implementation (Glassfish in my case). The Service is of the type document/literal [wrapped]. The XSD is also available.

Step 7: To test the service, use Web Service Explorer available with eclipse or SOAPUI and set the endpoint to the location of the endpoint. The sample request response in my case are as given below.

 Request:  
 <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:q0="http://example.jaxws.com/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">  
   <soapenv:Body>  
    <q0:greet>  
      <arg0>Aditya</arg0>  
      <arg1>Keyal</arg1>  
    </q0:greet>  
   </soapenv:Body>  
 </soapenv:Envelope>  

 Response  
 <S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">  
   <S:Body>  
    <ns2:greetResponse xmlns:ns2="http://example.jaxws.com/">  
      <return>Hello AdityaKeyal</return>  
    </ns2:greetResponse>  
   </S:Body>  
 </S:Envelope>  


The above example is available for download here. It is a complete eclipse project. Just download and import into eclipse and build then deploy on Glassfish for it to run.

JAX-WS explained in layman terms with an example

    JAX-WS, often touted as the "Holy Grail" of Java Web Services, is the most popular technology available in recent years; however what is disappointing is the lack of any detailed information that tries to clearly explain in layman terms what is JAX-WS? In this article I try to explain to the best what "JAX-WS" is with an example.

JAX-WS -> is a specification (JSR 224) provided by Sun which consists of a set of API used for creating Web Services. We have heard this statement in almost every web site but what this really means?

JAX-WS, like all specifications, is divided into 2 parts:

  1. The First part consists of an API provided by SUN. This API is accompanied by a JSR. The API consists of a set of interfaces, annotations, xml files and abstract classes (sometimes maybe a few base classes) which are to be used when using that feature. One very important thing about this API that should be noted is that the API in itself is not capable of achieving the intended objective of the specification. The JSR lays down a set of rules and regulations governing the API.
  2. The Second part of any specification is the implementation. The implementation follows all the rules laid down by the JSR and uses the API (i.e. provides all implementation for interfaces, and classes that use the annotations to get the desired objective) to provide a base. For example, in EJB 3.0 by annotating a class by @Stateless annotation we can create an EJB. The @Stateless annotation is useless by itself, however when this class is deployed on an EJB 3.0 enabled server (which contains an implementation for EJB 3.0 API) the server makes sense of the annotation and creates the corresponding EJB and gives the desired result.
Similarly in the case of JAX-WS, we have 2 parts: the API which is available from SUN and multiple reference implementations by different vendors like: Sun (JDK 1.6), Apache (CXF, AXIS 2), IBM (Web sphere), ORACLE (Weblogic App Server), Glassfish (Metro).

How to create a Web Services: As discussed in a previous article JAX-WS supports Java First, WSDL First and Meet in the Middle approach. However for the most basic discussion, I shall be using a Java First approach to create a sample web service. A few of the important features that JAX-WS provides are:

  1. JAXB data binding framework which can be switched ON or OFF.
  2. Automatic generation of WSDL when using Java First
  3. Automatic generation of Binding data when using Java First
  4. Automatic generation of skeleton classes when using WSDL First
  5. Automatic generation of Binding when using WSDL First.
  6. Customization for both Java First and WSDL First approaches.
The simplest way to create a web service consists of the following steps:

  1. Create an implementation class
  2. Annotate the class with @WebService annotation
  3. Annotate the methods to be exposed with @WebMethod annotation
  4. Generate WSDL, XSD and Binding classes using wsgen functionality (glassfish)
  5. Deploy the service on server (Glassfish)
  6. Get WSDL
  7. Test service using Eclipse Web Service Explorer
Check out the step by step illustrated JAX-WS example here.

Sunday, March 13, 2011

When “WSDL First”? When “Java First”? Where do we “Meet in the Middle”?

In most of the books that I have read on JAX-WS, JAX-RPC or any other on Java Web Services, one of the initial chapters is inadvertently based on "the different approaches to developing services", discussing Java or WSDL First approach. What I have always found unsatisfying about these chapters is the fact that they talk of how we can create/implement such methodologies, but, never about why or even when we use which approach? This article I try to explain when and why do we use the different approaches rather than how do we use them.

For the purpose of discussion let us consider the following case study.

    "An online book store wants to expose its products as a service. It would be offering search services to any customer that maybe interested in looking up data about the books that it has in stock. The book store sells Books and Periodicals"

Data to be exposed
BooksPeriodicals
TitleTitle
NameName
Publishing HousePublishing House
AuthorEditor
Revision NumberPrint Date


Business View:

In the above table, it is evident that according to the business, a book and a periodical are 2 totally different entities. Conceptually also a book is a onetime published entity while a periodical is a regularly published entity. They have different business significance and probably different business sections. So when the business team tries to visualize a Book or a Periodical in a web service, they see it as an xml with the below defined attributes:

 <Book>  
   <title></title>  
   <name></name>  
   <publishingHouse></publishingHouse>  
   <author></author>  
   <revisionNumber></revisionNumber>  
 </Book>  
 <Periodicals>  
   <title></title>  
   <name></name>  
   <publishingHouse></publishingHouse>  
   <editor></editor>  
   <printDate></printDate>  
 </Periodicals>  

Architect/Technical View:

When an architect or a technical designer is asked to look at the same problem given above, he will try to apply all the principles of OOP and create a design solution that looks like the one give below:



As shown above, the use inheritance to extract out the common properties by creating a base class and then extending the base class to create the actual classes of Books and Periodicals; is one of the first solutions provided. This extraction probably also has ramifications on the signature and number of methods exposed.

It must be noted that both the views are correct and proper. The Business is trying to visualize a solution that is more acceptable to them while the designer/technical architect is trying to visualize a solution more palatable to his taste. The choice of "WSDL First" approach or "Java First" approach largely depends on whether we choose the business vision (WSDL) of the web service or whether we choose a Technical vision (Java) of the web service. If we try to please them both, we may adopt to bridge the gap and "meet in the middle". This is definitely a great solution but a tedious one sing satisfying both business and technical viewpoint often has ramifications on the kind of technologies and the stack structure that we may use.

Note: The above article is based squarely on the design of server side components. When designing a client side more often than not we will go for a WSDL First since we would be consuming a web service and not creating one.

Web Service Addressing Mechanisms

    Any web service request from a client to a service goes through the process defined below at the server-side:

  1. The request is received by a Servlet (for a HTTP request)
  2. The Servlet identifies which Endpoint to call (using a strategy mapping)
  3. The Servlet identifies which method/operation in the endpoint to call (using same/alternative strategy)
  4. The Incoming request XML is un-marshaled into an Object (method parameters)
  5. The method is invoked using the parameters from step 4



When we are using a web service framework/toolkit, all of the steps identified above (i.e. step a to step e) are configurable through code/configuration files. The 2 major configurable/customizable feature that are generally provided by any framework are

  1. Addressing System – (step b and c)
  2. Marshalling System (step d)
We limit our discussion to the addressing system in this article and leave the marshalling system for discussion in a later article.

Addressing is the process of identifying the endpoint when a web service request is received by a server/service. In the case of rpc/literal (refer here) this identification is comparatively simpler since the operation name is already available in the incoming request. In the case of document/literal the task gets a lot more challenging since the incoming soap request contains a document alone(which may or maynot have any direct relation to the endpoint/method) and identification of an operation is difficult. In such a case the identification of the operation is determined by some strategy which is commonly known as addressing strategy. Few of the commonly used strategies are discussed below:

    In the above example, the servlet shown in the figure above would be mapped to /* URLs and receive all incoming requests. Once the request is received, based on the URL it would identify which Endpoint and which operation does it invoke.

  • SOAPActionBasedAddressingStrategy
    – In this strategy, the endpoints are mapped to the incoming 'soapAction' value (present in the header of the protocol of the request e.g. HTTP Header). This value could be pre-decided and mentioned in the WSDL (soap:action tag). Since the 'soapAction' value can be different for different method invocations, the method identification (step c) can be resolved using this method also. It should be noted here that soapAction attribute is not supported under SOAP specification 1.2. Hence this approach is applicable only as long as we use SOAP 1.1.


  • PayloadRootQNameAddressingStrategy
    – In this strategy (most commonly used for document-wrapped style) the operations/endpoints are identified by using the PayloadRootQName of the incoming request. PayloadRootQName signifies the Fully Qualified Name (namespace with tag) of the root tag of payload (the contents of the SOAP Body).
    Example:
     <soap:Body>  
       <tns:DocumentRoot xmlns:tns="http://example.com/document" >  
        <tns:SomeContent>…</tns:SomeContent>  
       </tns:DocumentRoot>  
     </soap:Body>  
    
In the above example the PayloadRootQName would be {http://example.com/document}DocumentRoot. The system can map such unique QNames to specific methods in endpoints or endpoints with pre-defined methods.



  • WS-AddressingBasedStrategy – WS-Addressing specifies a transport neutral routing mechanism based on a 'To' and 'Action' tag present in the SOAP:Header. The 'To' tag identifies the destination (the endpoint) and the 'Action' tag signifies the operation (the method). This combination is used to identify step b and step c. Both these data can be specified in a WSDL (through the usage of wsa tags) to communicate to a client. The biggest advantage of using ws-addressing is that it is an industry standard specified by WS-I for promoting inter-operability.
    Example:

     <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://www.w3.org/2003/05/soap-envelope"  
     xmlns:wsa="http://www.w3.org/2005/08/addressing">  
     <SOAP-ENV::Header>  
      <wsa:MessageID>urn:uuid:21363e0d-2645-4eb7-8afd-2f5ee1bb25cf</wsa:MessageID>  
      <wsa:ReplyTo>  
       <wsa:Address>http://example.com/business/client1</wsa:Address>  
      </wsa:ReplyTo>  
      <wsa:To S:mustUnderstand="true">http://example/com/fabrikam</wsa:To>  
      <wsa:Action>http://example.com/fabrikam/mail/Delete</wsa:Action>  
     </SOAP-ENV:Header>  
     <SOAP-ENV:Body>  
      <f:Delete xmlns:f="http://example.com/fabrikam">  
       <f:maxCount>42</f:maxCount>  
      </f:Delete>  
     </SOAP-ENV:Body>  
     </SOAP-ENV:Envelope>  
    

In the above example, each unique Action is mapped to an operation.

In all the above discussed strategies, it is the responsibility of the Server Side toolkit (Axis or JAX-WS or Spring-WS) to use some form of metadata (annotations or xml file) to create a map of "strategy value versus the operation/endpoint" and invoke the correct method when a particular request is received by the toolkit. Once the proper method is identified, the toolkit can then go on to un-marshal the incoming request and invoke the identified method. It should also be noted, that there is no sure shot formula in addressing strategy to decide which has to be applied when. The choice of a strategy id decided based on a number of considerations which includes

  • Which version of SOAP we are using?
  • Which strategies are supported by our framework?
  • What level of scalability and complexity is needed?
Most of the above considerations decide finally what kind of addressing strategy is adopted.However this is not the only consideration, often a number of other considerations such as technical viability, development time and cost of development take precedence.

Sunday, March 6, 2011

SOAP Service using Basic J2EE

In the previous article we discussed about creating a REST service using Basic J2EE. Here we expand our discussion to SOAP services. ABC Inc is now expanding and adding clients by the day. To increase the facilities offered they have now decided to move from REST to SOAP form of Web Services. As a prototype we will try to create the same order service as discussed before in a SOAP service.

    The transition from REST to SOAP has a few features that need to be looked into. A few of them are:

  1. The service operation no longer is decided by the HTTP methods. We need a new addressing strategy.
  2. The data/order can no longer be identified through URL (resourceId), We need to pass the data through XML.
  3. The Body content would now be a standardized SOAP Envelope.
  4. The authentication/encryption and other metadata is sent through SOAP Headers.
There could be a few more features that need to be added. However for the purpose of discussion we shall limit ourselves to the above mentioned points. Thus our new Servlet (com.abc.orderservice.SOAPEndpoint) looks something like the following.


 public class SOAPEndpoint extends HttpServlet {  
      @Override  
      protected void doGet(HttpServletRequest req, HttpServletResponse resp)  
                throws ServletException, IOException {  
                // process only POST requests   
           throw new IllegalArgumentException("GET NOT Supported");  
      }  
      @Override  
      protected void doPost(HttpServletRequest req, HttpServletResponse resp)  
                throws ServletException, IOException {  
           processSOAPMessage(req,resp);  
      }  
      private void processSOAPMessage(HttpServletRequest req,  
                HttpServletResponse resp) throws IOException {  
           String operation = req.getHeader("soapAction");  
           InputStream inputStream = req.getInputStream();  
           String soapXML = convertStreamToString(inputStream);  
           String payload = extractPayloadFromSOAPXML(soapXML);  
           String soapHeader = extractHeaderBlockFromSOAPXML(soapXML);  
           String orderId = extractOrderIdFromHeader(soapHeader);  
           if("http://localhost:8080/GETORDER".equalsIgnoreCase(operation)){  
                // get order xml from DB using order id  
 // enclose Order XML in the SOAP:Body and send back a SOAP:Envelope XML.  
           }else if("http://localhost:8080/POSTORDER".equalsIgnoreCase(operation)){  
                // set/store order xml into DB using order id and payload.  
           }  
      }  
 }  



As evident from the above snippet, the main operational method in the endpoint is the processSOAPMessage(HttpServletRequest, HttpServletResponse). The salient features of the method are as given below:

  1. Extract the SOAP Action header from the HTTP Header. This stores the name of the operation to be performed. (This is called the addressing strategy. Different strategies will be discussed later).
  2. Convert the HTTP Body to SOAP XML.
  3. Extract the SOAP Body from SOAP XML which contains the payload/order XML
  4. Extract the SOAP Headers from SOAP XML which contains the order id, authentication data and any encryption data.
  5. Process the business logic.
As is evident from the above steps, process a. through d. would be almost common throughout all implementations of ABC Inc and also for any other implementation code for web services. This "boilerplate" code can be standardized so as to reduce the effort required for development of web services. Examples of such framework or toolkit are Axis, JAX-WS and Spring-WS.

Create REST using Basic J2EE

    We have already seen what a REST Web Service looks like. Let us try to create a sample for the same. Consider an Order Service example for a company ABC Inc. which needs a service (OrderService) for its clients. In its most basic form, it will have 2 operations

  1. To retrieve an order when an order id is passed. (HTTP GET)
  2. To store an order. (HTTP POST)
Any client who wishes to know the details of a particular order can just pass the order id and retrieve the order xml which contains all the order data. Alternatively if we need to create a new order or update an existing order, we can "POST" the data (the complete order xml) and save it. ABC Inc has decided to implement such a service using REST owing to the simplicity of the service.

In a true REST service, all data is viewed as resources. Thus each order (i.e. the order xml) is a unique xml which is identified by a unique URL. (eg. http://localhost:8080/RestOrderService/order/123 corresponds to the order xml against the order id 123, while http://localhost:8080/RestOrderService/order/456 will correspond to the order xml against the order id 456). Depending on the HTTP method (GET/POST/DELETE/PUT) we will either retrieve (GET) or store (POST) the data.

    Thus the service endpoint can be implemented as a Servlet (com.abc.orderservice.RestEndpoint) targeting all requests with /order/* URL. The Servlet overrides 2 methods the doGet method and doPost method. The doGet method is used to retrieve the XML from the database and stream back to the user. The doPost method is used to send the new order xml to the service. The order xml is contained in the HTTP Body, where it is read and then stored in the database. The sample code is given below.

 public class RestEndpoint extends HttpServlet {  
      @Override // This method is for the get verb.  
      protected void doGet(HttpServletRequest req, HttpServletResponse resp)  
                throws ServletException, IOException {  
           String orderId = req.getPathTranslated();   
 // Authenticate User  
           // retrieve file from DB using id = orderId  
           OutputStream out = resp.getOutputStream();  
           out.write("<?xml version=\"1.0\" > <order><id>1234</id><custId>2122</custId></order>".getBytes());  
           // stream back the response retrieved from DB.  
      }  
      @Override // this method is for the post verb  
      protected void doPost(HttpServletRequest req, HttpServletResponse resp)  
                throws ServletException, IOException {  
           String orderId = req.getPathTranslated();  
           InputStream orderXML = req.getInputStream();  
 // Validate Incoming XML  
           //store orderXML stream in DB against the orderId.   
      }  
 }  

Looks simple right? It is. However before we actually "publish" this service, we need to add a few features like

  1. Validation of incoming XML data
  2. Authentication of User
  3. Buffered streaming of data
  4. Exception Handling
And as our service functionality expands we land up repeating a large part of the code in multiple places (all the above mentioned code). Thus we actually spend a large amount of time in actually performing repetitive tasks like those listed above instead of concentrating on business logic. What if this code, commonly known as "boilerplate code", could be extracted out into an API and we could have someone else do the job for us using either configuration metadata or interceptors. (We can achieve the same by actually ourselves doing the same job however one should realize that it would take more time than writing the business logic itself). This is where toolkits like JAX-WS, Axis and Spring-WS come in. They help us provide the boilerplate code that we need to provide for our service and make our lives simpler. We look at another example using SOAP in the next article where we actually see how hugely repetitive tasks are extracted and moved into frameworks (or toolkits) to make web service development easier.


 

Friday, March 4, 2011

What are ReST, SOAP, JSON?


    Last week I was having a discussion with a friend regarding his current project, frankly it was a wonderful conversation until he said the following statement to me – "We are NOT using Web Services, We are using ReST". That's when suddenly it all seemed so pointless, if ignorance is bliss then he must be grinning from teeth to teeth. This article I try to bust the myths and misconceptions about ReST and another (not so) popular technology JSON. If people have followed my articles they remember about how we have many layers in the web service stack. IMHO the most powerful layer of the entire stack is the XML Messaging Layer, which deals with the actual data being transferred between client-and-server. The most popular way of transferring data is undoubtedly SOAP, but ReST and JSON are replacements for SOAP in that layer. The remaining layers of the stack can and would be retained as it is. So let us try and understand the differences between them.


ReST – Representational State Transfer is an idea that was conceptualized by Roy Fielding in the year 2000. This deals with the passing of vanilla XML documents (without any SOAP Envelope, Head or Body) as the XML Message over the HTTP network protocol. So put simply if we take the SOAP Payload (or the contents of SOAP Body) and pass it directly over HTTP we get ReST. Is it really that simple? Yes.
If we were to really understand ReST as Fielding conceptualized it, then we need to visualize the service as a URI. For example if I am talking of an order service (maybe books or ticketing or purchase order) , then such a service would be available to me at the following url: http://exampleurl.com/ServiceProviderName/orderService, At this service/URL we could perform 4 different operations (CRUD operations) using the HTTP verbs.


OperationSQL VerbHTTP Verb
Create New OrdercreatePUT
Retrieve Existing OrderselectGET
Update Existing OrderupdatePOST
Delete/Cancel existing orderdeleteDELETE




Thus if we want to add a fifth operation then we actually need to create a new service (i.e. a new URL) and then define all 4 or fewer verbs with the operation. Also there is currently no standard way to describe the ReST service (i.e. no IDL/WSDL), so the contents of the request would have to be pre-determined between the client and the server (this is not entirely true since WSDL 2.0 now supports ReST). Another important feature of ReST is it is always stateless, we DO NOT maintain any session between 2 interactions. [Also it should be noted that there is no standard way of providing Security or Reliability in ReST unlike SOAP]. Given so many limitations is ReST actually useful or is it just a fad. Well actually there are a number of places/situations where ReST is useful:
  1. Where the service is not complicated, (i.e. no requirements of security and state)
  2. When high level of scalability/performance is needed. (ReST allows for caching to increase the scalability)
  3. Bandwidth is of importance and needs to be limited. (In SOAP we are passing a lot of extra data all the time, ReST allows for URI based identification of resources)
  4. ReST allows easy aggregation of services.
I think the most popular usage of ReST is in blogging. If any of you have tried to post to a blog site using Microsoft Word, or retrieve a blog using Word, you are using ReST.




JSON – JavaScript Object Notation involves passing data in formatted text (NOT XML) across HTTP protocol. The main advantage of using JSON is that it is directly understood by JavaScript so we do not need to further process the data. JSON is almost exclusively used by AJAX clients and allows for easy serialization/de-serialization of data. The bandwidth is also minimized and speed is increased. The most popular user of JSON is Google. Almost all Google operations (gmail, http chat client, google docs) exclusively use JSON. The popularity of JSON is still very limited and hence I will not discuss too much into it. If you want to know more about it please do a Google search on it and get the required data.
In my next article I try to create a simple web service implementation for ReST and then port it to SOAP.


Edited:


The following table shows briefly the differences between SOAP,REST and JSON


SOAPRESTJSON
Message FormatXML inside a SOAP envelopeXMLTEXT
Interface DefinitionWSDL 1.1 , WSDL 2.0WSDL 2.0None
TransportHTTP, FTP, MIME, SMTP, JMS, etcHTTPHTTP (AJAX)


Wednesday, March 2, 2011

WSDL – What, Where and How

    In this article we briefly discuss the Web Service Description Language or WSDL. To know about the basis of WSDL and where they fit in the context of Web Services please read here. WSDL (generically Service Description, SD) is a XML based document that lets us describe the complete information of a service offering. It can contain definitions for the following things related to a web service:

  • Types – Allows for custom data type definition
  • Message – Defines data being sent to, and received from, the web service
  • Operation – Defines one abstract operation supplied by the web service
  • Port Type – Defines an interface, consisting of one or more operations of a web service
  • Binding – Specifies the protocol and data format to be used by a particular port type
  • Port – Defines an web service endpoint by assigning a network address to a binding
  • Service – The grouping of one or more web service endpoint(s)




The picture above shows the basic structure of a WSDL. A WSDL is divided into 2 main parts the abstract definition and the concrete definition. The abstract definition deals with the "What" part of the service, ("What" – What are the operations provided, What are the data needed,). The concrete definition deals with the "Where" and "How" part of a service description (Where is the service located, How is the request shaped and How is the service accessed).

When we try to map a WSDL to an implementation code (like Java) the abstract definition part of the WSDL maps to a set of interfaces which contains all the exposed operations, parameters that need to be passed and the return types. The message elements are mapped to POJO's whose structure is governed by the wsdl:type defined schema. These message types serve as the parameters passed in a method/operation. A single portType element is directly mapped to an Interface (popularly known as Service Endpoint Interface or SEI) which enlists all the operations enclosed within that portType. The operation tag contains the information pertaining to the input to be passed (wsdl:input), return type (wsdl:output) and custom faults (wsdl:fault). The other information that we can gather from the operation tag is whether it is a one-way operation or a request-response model. Based on the above information we can have the basic information of "What" the service has to offer. However we still do not know "How" this information is encoded into a message.

The concrete definition elements of the WSDL structure provides the information regarding "How" should the message be shaped? What element should go in the body and what element in the Head? Which protocol does the service use? Where is the service located? The binding is the most important element when it comes to giving information related to the message structure. The binding tag is mapped to a portType tag and follows the same structure. The only difference is that the binding tag has provision for "extensions". These extensions allow us to bind an implementation to the abstract portType. We can specify the format of the message (SOAP), format of message (which of the parameters are passed in the soap:head or soap:body), the network protocol used for communication. It also provides data regarding the SOAP Encoding. To know more about the syntax of these elements please read here.