Web Services & SOAP

Hey! Welcome back to my Programming Applications & Frameworks blog. From this article, I'm going to explain some facts about Web services & SOAP.

What are these Web applications and Web services?

Simply a Web service refers to software, that serves data in any format (XML/JSON etc) through some kind of web interface. That interface can be called API (Application programming interface). REST and SOAP are ways to design the API. In other words,  web service is 'server' and application is 'client'. The web application is an application that users access over the internet. Generally, any software that is accessed through a client web browser could be called a web application. W3C describes web service as a system of software allowing a different machine to interact with each other through a network. Web services achieve this task with the help of XML, SOAP, WSDL & UDDI open standards.

  • Web applications can be used to transfer data between web applications.
  • Web services can be accessed from any languages or platform.
  • A web application is meant for humans to read, while a web service meant for computers to read.
  • The web application is a completer application with a GUI, however, web services do not necessarily have a UI since it is used as a component in an application.
  • A web application can be accessed through browsers.

Do you know about WSDL?

WSDL (Web Service Definition Language) is an XML format describing network services as a set of endpoints operating on messages containing either document-oriented or procedure-oriented information. The operations and messages are described abstractly and then bound to a concrete network protocol and message format to define an endpoint. WSDL document uses the following elements in the definition of network services,
  • Types - A container for data type definitions using some type system.
  • Message - An abstract, typed definition of the data being communicated.
  • Operation - An abstract description of an action supported by the services.
  • Port type - An abstract set of operations supported by the service.
  • Binding - A concrete protocol and data format specification for the particular port type.
  • Port - A single endpoint defined as a combination of a binding and network address.
  • Service -A collection of related endpoints.

WSDL Document

The following example shows the WSDL definition of a simple service providing stock quotes. The service supports a single operation called 'GerLastTradePrice', which is deployed using the SOAP 1.1 protocol over HTTP. The request takes a ticker symbol of typing string and returns the prices as a float. This example uses a fixed XML format instead of SOAP encoding,

<?xml version="1.0"?>
<definitions name="StockQuote"

targetNamespace="http://example.com/stockquote.wsdl"
          xmlns:tns="http://example.com/stockquote.wsdl"
          xmlns:xsd1="http://example.com/stockquote.xsd"
          xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
          xmlns="http://schemas.xmlsoap.org/wsdl/">

    <types>
       <schema targetNamespace="http://example.com/stockquote.xsd"
              xmlns="http://www.w3.org/2000/10/XMLSchema">
           <element name="TradePriceRequest">
              <complexType>
                  <all>
                      <element name="tickerSymbol" type="string"/>
                  </all>
              </complexType>
           </element>
           <element name="TradePrice">
              <complexType>
                  <all>
                      <element name="price" type="float"/>
                  </all>
              </complexType>
           </element>
       </schema>
    </types>

    <message name="GetLastTradePriceInput">
        <part name="body" element="xsd1:TradePriceRequest"/>
    </message>

    <message name="GetLastTradePriceOutput">
        <part name="body" element="xsd1:TradePrice"/>
    </message>

    <portType name="StockQuotePortType">
        <operation name="GetLastTradePrice">
           <input message="tns:GetLastTradePriceInput"/>
           <output message="tns:GetLastTradePriceOutput"/>
        </operation>
    </portType>

    <binding name="StockQuoteSoapBinding" type="tns:StockQuotePortType">
        <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
        <operation name="GetLastTradePrice">
           <soap:operation soapAction="http://example.com/GetLastTradePrice"/>
           <input>
               <soap:body use="literal"/>
           </input>
           <output>
               <soap:body use="literal"/>
           </output>
        </operation>
    </binding>

    <service name="StockQuoteService">
        <documentation>My first service</documentation>
        <port name="StockQuotePort" binding="tns:StockQuoteBinding">
           <soap:address location="http://example.com/stockquote"/>
        </port>
    </service>

</definitions>

Let's discuss 'Port type' & 'Operation' elements in WSDL

This is the basic structure of  WSDL

The 'Port type' element combines multiple message elements to form a complete one-way or round-trip operation. For example, a Port type can combine one request and one response message into a single request/response operation. This is most commonly used in SOAP services. A port type can define multiple operations.
Ex:- 
<portType name = "Hello_PortType">
   <operation name = "sayHello">
      <input message = "tns:SayHelloRequest"/>
      <output message = "tns:SayHelloResponse"/>
   </operation>
</portType>

  • The portType element defines a single operation, called ''sayHello''.
  • The operation consists of a single input message.

Patterns of Operation

WSDL supports 4 basic patterns in operations,
  1. One-way
  2. Request-response
  3. Solicit-response
  4. Notification
  • One-way - The service receives a message. The operation, therefore, has a single input element.
  • Request-response - Ther service receives a message and sends a response. The operation, therefore, has one input element, followed by one output element. To encapsulate errors, an optional fault element can also be specified.
  • Solicit-response - The service sends a message and receives a response. The operation, therefore, has one output element, followed by one input element. To encapsulate errors, an optional fault element can also be specified.
  • Notification - The service sends a message. The operation, therefore, has a single output element.

Bindings -

A binding defines message format and protocol details for operations and messages defined by a particular portType. There may be any number of bindings for a given portType. The grammar for binding is as follows,

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

An operation element within a binding specifies binding information for the operation with the same name within the binding's portType. Since operation names are not required to be unique (for example, in the case of overloading of method names), the name attribute in the operation binding element might not be enough to uniquely identify an operation. In that case, the correct operation should be identified by providing the name attributes of the corresponding WSDL: input and wsdl: output elements.

Services -

A service groups a set of related ports together, The name attribute provides a unique name among all services defined within in the enclosing WSDL document.


<wsdl:definitions .... >
    <wsdl:service name="nmtoken"> *
        <wsdl:port .... />*
    </wsdl:service>
</wsdl:definitions>

None of the ports communicate with each other (e.g. the output of one port is not the input of another). If a service has several ports that share a port type but employ different bindings or addresses, the ports are alternatives. Each port provides semantically equivalent behavior (within the transport and message format limitations imposed by each binding). This allows a consumer of a WSDL document to choose the particular port(s) to communicate with based on some criteria (protocol, distance, etc.). By examining its ports, we can determine a service's port types. This allows a consumer of a WSDL document to determine if it wishes to communicate to a particular service based on whether or not it supports several port types. This is useful if there is some implied relationship between the operations of the port types, and that the entire set of port types must be present in order to accomplish a particular task.

Let's get to know how does SOAP is used with HTTPS

SOAP is a 'messaging protocol' and in a nutshell, is a just another XML language. Its purpose is the data exchange over networks. its concern is the encapsulation of these data and the rules for transmitting and receiving them. HTTP is an 'application protocol' and SOAP messages are placed as the HTTP payload. Although there is the overhead of HTTP, it has the advantage that it is a protocol that is open to firewalls, well-understood and widely-supported. Therefore web services can be accessed and exposed via technology already in place. 

Why SOAP use with HTTP?
SOAP defines a data encapsulation format. The major of traffic on the web is via HTTP. HTTP is literally everywhere and supported by a well-established infrastructure of servers and clients. Additionally, it is a very well understood protocol. The people who created SOAP wanted to use this ready infrastructure and SOAP messages were designed so that they can be tunneled over HTTP. In the specs, they do not refer to any other non HTTP binding but specifically, refer to HTTP as an example for transfer. Therefore the reason to use HTTP is,
  • HTTP is popular and successful.
  • HTTP infrastructure is in place so no extra cost to deploy web services.
  • HTTP traffic is open to firewalls, so there are no problems during web service functioning as a result of network security.

Structure of a SOAP message

A SOAP message is encoded as an XML document, consisting of and 'Énvelope' element, which contains an optional 'Header' element, and a mandatory 'Body' element. The 'Fault' element, contained in 'Body', is used for reporting errors.


The SOAP envelope - 'Envelope' is the root element in every SOAP message, and contains two child elements, an optional 'Header' element, and a mandatory 'Body' element.

The SOAP header - 'Header' is an optional sub-element of the SOAP envelope, and is used to pass application-related information that is to be processed by SOAP nodes along the message path.

The SOAP body - 'Body' is a mandatory sub-element of the SOAP envelope, which contains information intended for the ultimate recipient of the message.

The SOAP fault - 'Fault' is a sub-element of the SOAP body. which is used for reporting errors.


MIME Header

When a SOAP message is wrapped for transmission in HTTP, suitable MIME headers must be created. At a minimum, the wrapper must include the 'Çontent-Type' and 'Content-Length' headers along with the 'SOAPAction' header. Earlier in this chapter similarly, when a message is received, any MIME headers that accompany it must be extracted from the protocol-specific wrapper and be made part of the created 'SOAPMessage'. The MIME headers associated with a 'SOAPMessage'are held in an object of type 'java.xml.soap.mimeheaders.

In terms of the structure of an encapsulated SOAP message, the MIME headers logically appear outside the envelope, where they form the protocol-specific wrapper. In the case of a SOAP message with attachments, in addition to the headers in the outer wrapper, the SOAP message part and each of the attachment parts have their own collection of MIME headers that distinct from those of the wrapper.

JAX-WS annotations

Java API for XML-Based Web Services (JAX-WS) relies on the use of annotations to specify metadata associated with web services implementations and to simplify the development of web services. Annotations describe how a server-side service implementation is accessed as a web service or how a client-side Java class accesses web services. we Use annotations to configure bindings, handler chains, set names of portType, service and other WSDL parameters. Annotations are used in mapping Java to WSDL and schema, and at runtime to control how the JAX-WS runtime processes and response to web service invocations.


1. @WebService -

This JAX-WS annotation can be used in 2 ways. If we are annotating this over a class, it means that we are trying to mark the class as implementing the Web Service, in other words, Service Implementation Bean (SIB). Or we are marking this over an interface, it means that we are defining a Web Service Interface (SEI), in other words, Service Endpoint Interface. Ex:-

package com.javacodegeeks.examples.jaxWsAnnotations.webservice;
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;
@WebService
@SOAPBinding(style=Style.RPC)
public interface WSAnnotationWebServiceI {
    @WebMethod
    float celsiusToFarhenheit(float celsius);
}


2. @WenMethod -

JAX-WS annotation can be applied over method only. This specified that the method represents a web service operation.

3. @WebResult -

From following SEI & SIB you can get an idea about the web result


package com.javacodegeeks.examples.jaxWsAnnotations.webresult;
import javax.jws.WebMethod;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;
@WebService
@SOAPBinding(style = Style.RPC)
public interface WSAnnotationsWebResultI {
    @WebMethod
    @WebResult(partName="farhenheitResponse")
    float celsiusToFarhenheit(float celsius);
}

4. @SOAPBinding

Demonstration of SOAPBinding JAX-WS annotation has already been shown. This annotation is used to specify the SOAP messaging style which can either be RPC or Document. This style represents the encoding style of the message sent to and fro while using the web service.


5. @WebServiceClient

package com.javacodegeeks.examples.jaxWsAnnotations.webservice;
import javax.xml.ws.Endpoint;
public class WSPublisher {
    public static void main(String[] args) {
        Endpoint.publish("http://127.0.0.1:9999/ctf", new WsAnnotationsWebServiceImpl());
    }
}

5. @RequestWrapper -

RequestWrapper JAX-WS annotation is used to annotate methods in the Service Endpoint Interface with the request wrapper bean to be used at runtime. It has 4 optional elements; className that represents the request wrapper bean name, localName that represents element’s local name, partName that represent the part name of the wrapper part in the generated WSDL file, and targetNamespace that represents the element’s namespace.

package com.javacodegeeks.examples.jaxWsAnnotations.wrapper;
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;
import javax.xml.ws.RequestWrapper;
@WebService
@SOAPBinding(style=Style.RPC)
public interface WSRequestWrapperInterface {
    @WebMethod
    @RequestWrapper(localName="CTF",
    targetNamespace="http://javacodegeeks.com/tempUtil",
    className="com.javacodegeeks.examples.jaxWsAnnotations.webservice.CTF")
    float celsiusToFarhenheit(float celsius);
}


That's all for this article and hope you had a good knowledge of web services and SOAP. See you guys with another interesting topic on Programming Applications & Frameworks. Thank you.



References -

Comments

Popular Posts