Wednesday, 6 March 2013

Spring Web Services Using JAXB

Spring Web Services Example Easy Steps.....

Just a glimpse........
Spring Web Services is a product from Spring community to develop the web services in easier manner. Spring Web Services is following the strategy of contract-first web services. It focuses more on XML and lesser on Java implementation. In this article, we will learn how to write a simple web service application using Spring Web Services. It is expected that the reader has a fair amount of knowledge on Web services concepts before continuing with the article along with the basics of Spring Framework like Dependency Injection and Inversion of Control.

Spring Web Services Example :
In this article, we will design a simple application that'll ask for an employee id(consisting of two characters and five digits, e.g ab12345) and will return the employee details(here name & email id, e.g. Sidhartha Ray & ab@yahoo.co.in) using Spring Web Service in Eclipse IDE. This article will provide the content in a tutorial fashion in a step-by-step manner and parallely giving relevant details to that section. Generally speaking, developing web services involves writing artifacts in the server and the client tier. We will look into the details about those artifacts in the subsequent sections. Given below are the pre-requisite softwares to develop and run the application
 1.Java Development Kit (1.6 or later)
 2.Spring Web Service Framework (1.5.9)
 3.Eclipse3.4 or later (add plugin jaxb 2.0 or later)
 4.Web Server(Apache Tomcat 6)

And the following jar files
1.commons-logging-1.1.1.jar
2.spring.jar
3.spring-beans.jar 
(N.B. Get all the above jars by downloading spring framework 2.5.6 & spring web services 1.5.9)

Server-side artifacts :

The following steps are provided in building up the various server-side artifacts.
 1.Contract Design
 2.Defining the service interface
 3.Implementing the service interface
 4.Defining Spring Web-Service endpoints
 5.Configuring deployment descriptor.
 6.Configuring Spring’s Application Context.

Remember to build the server tier as a web application(Dynamic Web Project in Eclipse IDE), so that it can be made runnable in any web server.

Application folder structure in eclipse'll look like :
      

1.Contract design :

We will design the contract for the service through xml, i.e. a .wsdl(Web Service Description Language) file. The contract defines the input and the output messages that a service expects. Since we wanted to enforce restriction on the input and output, we will provide an XSD, i.e. a.xsd(XML Schema Definition) file. In our case, the request and the response messages will be simple string objects. The following definitions define the .xsd file & .wsdl file:

Employee.xsd
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    xmlns:tns="http://employee.com/schema" elementFormDefault="qualified"
    targetNamespace="http://employee.com/schema">
    <xsd:element name="EmployeeDetailsRequest">
        <xsd:complexType>
            <xsd:sequence>
                <xsd:element ref="tns:empId" />
            </xsd:sequence>
        </xsd:complexType>
    </xsd:element>
    <xsd:element name="EmployeeDetailsResponse">
        <xsd:complexType>
            <xsd:sequence>
                <xsd:element name="name" type="xsd:string" />
                <xsd:element name="email" type="xsd:string" />
            </xsd:sequence>
        </xsd:complexType>
    </xsd:element>
    <xsd:element name="empId">
        <xsd:simpleType>
            <xsd:restriction base="xsd:string">
                <xsd:pattern value="[a-z]{2}[0-9]{5}" />
            </xsd:restriction>
        </xsd:simpleType>
    </xsd:element>
</xsd:schema>

Now you can generate the service artifacts or jaxb classes by following steps :

i.) Right click on .xsd file >> select JAXB 2.0 >> select Run XJC >>(a pop up will appear) Give Package Name as "com.employee.schema" Output Directory as project's src directory >> Select Finish
ii.) Refresh your project directory and you'll find following four classes :



Employee.wsdl
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<wsdl:definitions xmlns:emp="http://employee.com/schema" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://employee.com/employee" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" name="Employee" targetNamespace="http://employee.com/employee">
    <wsdl:types>
        <xsd:schema targetNamespace="http://employee.com/employee">
            <xsd:import namespace="http://employee.com/schema" schemaLocation="Employee.xsd"/>
        </xsd:schema>
    </wsdl:types>
    <wsdl:message name="EmployeeDetailsRequest">
        <wsdl:part element="emp:EmployeeDetailsRequest" name="EmployeeDetailsRequest"/>
    </wsdl:message>
    <wsdl:message name="EmployeeDetailsResponse">
        <wsdl:part element="emp:EmployeeDetailsResponse" name="EmployeeDetailsResponse"/>
    </wsdl:message>
    <wsdl:portType name="EmployeePortType">
        <wsdl:operation name="EmployeeDetails">
            <wsdl:input message="tns:EmployeeDetailsRequest"/>
            <wsdl:output message="tns:EmployeeDetailsResponse"/>
        </wsdl:operation>
    </wsdl:portType>
    <wsdl:binding name="EmployeeSOAPBinding" type="tns:EmployeePortType">
        <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
        <wsdl:operation name="EmployeeDetails">
            <soap:operation soapAction="http://employee.com/employee/EmployeeDetails"/>
            <wsdl:input>
                <soap:body use="literal"/>
            </wsdl:input>
            <wsdl:output>
                <soap:body use="literal"/>
            </wsdl:output>
        </wsdl:operation>
    </wsdl:binding>
    <wsdl:service name="EmployeeService">
        <wsdl:port binding="tns:EmployeeSOAPBinding" name="Employee">
            <soap:address location="http://localhost:8888/EmployeeWS/services/Employee"/>
        </wsdl:port>
    </wsdl:service>
</wsdl:definitions>

2.Defining the service interface :

Defining the service interface - The service interface represents the client-facing interface for invoking the service by passing in the required inputs. Note that the interface will be a simple POJO, the interface doesn’t need to extend or implement any of the spring web-service related APIs. In this example, the input will be a simple java string object.

EmployeeService.java
package com.employee.service;

import com.employee.schema.EmployeeDetailsRequest;
import com.employee.schema.EmployeeDetailsResponse;

public interface EmployeeService {
    EmployeeDetailsResponse getEmployeeDetails(EmployeeDetailsRequest request);
}


3.Implementing the service interface :
 
Implementing the service interface - Writing the implementation for the above service interface will be fairly straight-forward. It returns an EmployeeDetailsResponse object with name : Sidhartha Ray & Email : ab@yahoo.co.in if employee id is ab12345, else returns with name : Nitesh Yetta & Email : xy@yahoo.co.in.

EmployeeServiceImpl.java
package com.employee.service;

import com.employee.schema.EmployeeDetailsRequest;
import com.employee.schema.EmployeeDetailsResponse;

public class EmployeeServiceImpl implements EmployeeService{

    @Override
    public EmployeeDetailsResponse getEmployeeDetails(
            EmployeeDetailsRequest request) {
        EmployeeDetailsResponse response = new EmployeeDetailsResponse();
        if(request.getEmpId().equalsIgnoreCase("ab12345")){    //two char & five digits
            response.setEmail("ab@yahoo.co.in");
            response.setName("Sidhartha Ray");
        }else{
            response.setEmail("xy@yahoo.co.in");
            response.setName("Nitesh Yetta");
        }
        return response;
    }
}


4.Defining Spring Web-Service endpoint :

Defining endpoints - Endpoints are components for processing the input request messages and are usually responsible for invoking the desired service by passing in the required details. Spring Web Services implementation comes with two flavors of endpoints – message endpoints and payload endpoints. Message endpoints provide access to the raw input XML message including the XML header along with the XML body. On the other hand, Payload endpoints are useful in dealing with the XML body alone. In our simple application, we will define a Payload endpoint for parsing the input XML message for invoking the service.

EmployeeDetailsEndpoint.java
package com.employee.endpoint;

import org.springframework.oxm.Marshaller;
import org.springframework.ws.server.endpoint.AbstractMarshallingPayloadEndpoint;
import com.employee.schema.EmployeeDetailsRequest;
import com.employee.service.EmployeeService;

public class EmployeeDetailsEndpoint extends AbstractMarshallingPayloadEndpoint{
    private EmployeeService service;
    public EmployeeDetailsEndpoint(EmployeeService service,
            Marshaller marshaller) {
        super(marshaller);
        this.service = service;
    }
    @Override
    protected Object invokeInternal(Object arg0) throws Exception {
        return service.getEmployeeDetails((EmployeeDetailsRequest)arg0);
    }
}
Here as we want to use JAXB for marshalling/unmarshalling, we have gone through AbstractMarshallingPayloadEndpoint.
The method invokeInternal will be called when an XML request is received by the framework and the whole xml content will be available in the requestElement. The rest of the code does the job of finding the request string from the input XML, invoke the employee service and then constructs the appropriate XML response.

5.Configuring deployment descriptor :

The web application’s deployment descriptor must be configured with a servlet that is capable of dispatching web service message to the appropriate handler. This happens to be the MessageDispatcherServlet servlet.

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>EmployeeWS</display-name>
  <servlet>
      <servlet-name>EmployeeWS</servlet-name>
      <servlet-class>org.springframework.ws.transport.http.MessageDispatcherServlet</servlet-class>
      <init-param>
          <param-name>contextConfigLocation</param-name>
          <param-value>/WEB-INF/spring/context/ApplicationContext.xml</param-value>
      </init-param>
  </servlet>
  <servlet-mapping>
      <servlet-name>EmployeeWS</servlet-name>
    <url-pattern>/*</url-pattern>  
  </servlet-mapping>
</web-app>

In the above XML, we have routed all requests to the servlet spring-ws-service which in-turns maps to MessageDispatcherServlet. The above dispatcher servlet will search for a configuration file representing the spring application context for looking up the definition for various spring beans. By default, the name of the configuration file will be derived from the servlet name. If the name of the servlet is xyz, then the name of the configuration file will be xyz-servlet.xml. In our case, the configuration file will be spring-ws-servlet.xml. We can also give any name to the Spring Configuration File by just adding the following init-param to the MessageDispatcherServlet :

       <init-param>
          <param-name>contextConfigLocation</param-name>
          <param-value>/WEB-INF/spring/context/ApplicationContext.xml</param-value>
      </init-param>

6.Configuring Spring’s Application Context :

The minimal requirement of the spring application configuration file that resides in a web server is to contain the following entries:
 i Endpoints definition
 ii Endpoint mappings definition
 iii WSDL Definition

spring-ws-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:oxm="http://www.springframework.org/schema/oxm"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
        http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-1.5.xsd">
    <!-- For Hand-Written contract(.wsdl) -->
    <bean id="EmployeeService"
        class="org.springframework.ws.wsdl.wsdl11.SimpleWsdl11Definition">
        <constructor-arg value="/wsdl/Employee.wsdl" />
    </bean>
    <oxm:jaxb2-marshaller id="marshaller"
        contextPath="com.employee.schema" />
    <oxm:jaxb2-marshaller id="unmarshaller"
        contextPath="com.employee.schema" />
    <!-- Endpoint Mapping... -->
    <bean name="service" class="com.employee.service.EmployeeServiceImpl" />
    <bean id="employeeDetailsEndpoint" class="com.employee.endpoint.EmployeeDetailsEndpoint">
        <constructor-arg ref="service" />
        <constructor-arg ref="marshaller" />
    </bean>
    <bean name="endPointMapping"
        class="org.springframework.ws.server.endpoint.mapping.PayloadRootQNameEndpointMapping">
        <property name="mappings">
            <props>
                <prop key="{http://employee.com/schema}EmployeeDetailsRequest">employeeDetailsEndpoint</prop>
            </props>
        </property>
    </bean>
</beans>

Now Deploy the application into tomcat server & hit the url to see the .wsdl:

http://<server-address>:<port>/EmployeeWS/services/EmployeeService.wsdl
OR
http://<server-address>:<port>/EmployeeWS/<MessageDispatcherServlet_name_from_deployment_descriptor>/<wsdl_bean_name_from_spring_app_context>.wsdl


B. Test service Using soapUI




Reference :

No comments:

Post a Comment