Friday, 20 December 2013

Java Program to Implement Binary Search Tree

Node.java
public class Node {
    public int info;
    public Node left;
    public Node right;
}

BinarySearchTree.java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Scanner;
public class BinarySearchTree {
    private Scanner scanner;
    private Node root;
    private int info;

    private BinarySearchTree() {
        scanner = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
    }

    public static void main(String[] args) {
        new BinarySearchTree().showMenu();
    }

    private void showMenu() {
        int choice;
        do {
            System.out.println("1.\tInsert in Binary Tree");
            System.out.println("2.\tDelete from Binary Tree");
            System.out.println("3.\tSearch");
            System.out.println("4.\tSearch Min");
            System.out.println("5.\tSearch Max");
            System.out.println("6.\tPre-order traversal of Binary Tree");
            System.out.println("7.\tPost-order traversal of Binary Tree");
            System.out.println("8.\tIn-order traversal of Binary Tree");
            System.out.println("9.\tExit");
            System.out.print("\nEnter choice:");
          
            choice = scanner.nextInt();
            switch(choice) {
            case 1:    //insert
                System.out.print("\nEnter info:");
                info = scanner.nextInt();
                root = insert(root, info);
                break;
            case 2:    //delete
                System.out.print("\nEnter info:");
                info = scanner.nextInt();
                root = delete(root, info);
                break;
            case 3:    //search
                System.out.print("\nEnter info:");
                info = scanner.nextInt();
                Node searchroot = search(root, info);
                if(searchroot != null)
                    System.out.println("Found!");
                else
                    System.out.println("Not Found!");
                break;
            case 4:    //search min
                Node min = searchMin(root);
                if(min != null)
                    System.out.println("Min >> " + min.info);
                else
                    System.out.println("Empty tree!");
                break;
            case 5:    //search max
                Node max = searchMax(root);
                if(max != null)
                    System.out.println("Max >> " + max.info);
                else
                    System.out.println("Empty tree!");
                break;
            case 6:    //preorder
                preorder(root);
                break;
            case 7:    //postorder
                postorder(root);
                break;
            case 8:    //inorder
                inorder(root);
                break;
            case 9:    //exit
                System.exit(0);
                break;
            default:
                System.out.println("Invalid option");
                break;
            }
        } while(true);
    }  

    private Node insert(Node root, int info) {
        if(root == null) {
            root = new Node();
            root.info = info;
        } else if(info < root.info) {
            root.left = insert(root.left, info);
        } else {
            root.right = insert(root.right, info);
        }
        return root;
    }
   
    private Node delete(Node root, int info) {
        if(root == null) {
            System.out.println("Element not found!");
        } else if(info < root.info) {
            root.left = delete(root.left, info);
        } else if(info > root.info) {
            root.right = delete(root.right, info);
        } else {
            if(root.left != null && root.right != null) {
                Node temp = searchMin(root.right);
                root.info = temp.info;
                root.right = delete(root.right, temp.info);
            } else {
                if(root.left == null) {
                    root = root.right;
                } else if(root.right == null) {
                    root = root.left;
                }
            }
        }
        return root;
    }

    private Node search(Node root, int info) {
        if(root == null) {
            return null;
        } else if(root.info == info) {
            return root;
        } else if(info < root.info) {
            return search(root.left, info);
        } else {
            return search(root.right, info);
        }
    }

    private Node searchMin(Node root) {
        if(root != null && root.left != null) {
            return searchMin(root.left);
        } else {
            return root;
        }
    }

    private Node searchMax(Node root) {
        if(root != null && root.right != null) {
            return searchMax(root.right);
        } else {
            return search(root.right, info);
        }
    }
  
    private void preorder(Node root) {
        if(root != null) {
            System.out.print(root.info + " -> ");
            preorder(root.left);
            preorder(root.right);
        }
    }

    private void postorder(Node root) {
        if(root != null) {
            postorder(root.left);
            postorder(root.right);
            System.out.print(root.info);
        }
    }

    private void inorder(Node root) {
        if(root != null) {
            inorder(root.left);
            System.out.print(root.info + " -> ");
            inorder(root.right);
        }
    }

}

Monday, 8 April 2013

JAXB Tutorial



JAXB

Introduction:

  • JAXB(Java Architecture for XML Binding) provides API to access and process a XML document
  • We can read or write XML files using JAXB. Unlike DOM, SAX or StAX parsers to use JAXB the developer need not be aware of XML parsing techniques.




JAXB Implementation:

  • JAXB API is a set of interfaces for which we have various implementations. As part of Metro there is a project for JAXB providing reference implementation. JSR 222 is developed by JCP for JAXB. Latest version of JAXB as of now is JAXB 2.2.

  • In this article we use Metro’s JAXB reference implementation. To run the sample code associated, you should download jaxb implementation and the jar files to the classpath.

  • There are two operations you can perform using JAXB

1.      Marshalling :Converting a java object to XML 
2.      UnMarshalling :Converting a XML to java object

For Marshaling:

 


@XmlRootElement: This annotation defines root element of XML file.
@XmlType(propOrder = {"list of attributes in order"}):This is used to define order of elements in XML file.This is optional.
@XmlElement:This is used to define element in XML file.It sets name of entity.  
@XmlElementWrapper(name = "name to be given to that wrapper"):It generates a wrapper element around XML representation.E.g.In above example, it will generate <bookList> around each <book> element

For Unmarshaling:

Example: 


Book.java
package trg.jaxb.bookStore;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

@XmlRootElement(name="book")
@XmlType(propOrder={"name", "author", "publisher", "isbn"})
public class Book {
    private String name;
    private String author;
    private String isbn;
    private String publisher;

    public Book() {
        super();
    }
    public Book(String name, String author, String isbn, String publisher) {
        super();
        this.name = name;
        this.author = author;
        this.isbn = isbn;
        this.publisher = publisher;
    }
    public String getName() {
        return name;
    }
    @XmlElement(name="title")
    public void setName(String name) {
        this.name = name;
    }
    public String getAuthor() {
        return author;
    }
    public void setAuthor(String author) {
        this.author = author;
    }
    public String getIsbn() {
        return isbn;
    }
    public void setIsbn(String isbn) {
        this.isbn = isbn;
    }
    public String getPublisher() {
        return publisher;
    }
    public void setPublisher(String publisher) {
        this.publisher = publisher;
    }

}



BookStore.java
package trg.jaxb.bookStore;
import java.util.List;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

@XmlRootElement(name="bookStore", namespace="trg.jaxb.bookStore")
@XmlType(propOrder={"name", "location", "bookList"})
public class BookStore {
    private String name;
    private String location;
    private List<Book> bookList;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getLocation() {
        return location;
    }
    public void setLocation(String location) {
        this.location = location;
    }
    @XmlElement(name="book")
    @XmlElementWrapper(name="bookList")
    public List<Book> getBookList() {
        return bookList;
    }
    public void setBookList(List<Book> bookList) {
        this.bookList = bookList;
    }

}

 

JAXBMarshalDemo.java
package trg.jaxb.bookStore;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

public class JAXBMarshalDemo {
    private static final String BOOKSTORE_XML = "KharadiBookStore.xml";
    public static void main(String[] args) {
        List<Book> bookList = new ArrayList<Book>(4);
        bookList.add(new Book("Stauts 2 In Action", "A. King", "ISBN-0001", "Wrox Pub."));
        bookList.add(new Book("Spring 3 In Action", "B. King", "ISBN-0002", "Apprentice Hall"));
        bookList.add(new Book("Hibernate 3 In Action", "C. King", "ISBN-0003", "Kalyani Pub."));
        bookList.add(new Book("JSF In Action", "D. King", "ISBN-0004", "ABC Pub."));
      
        BookStore bookStore = new BookStore();
        bookStore.setName("Kharadi Book Store");
        bookStore.setLocation("Kharadi");
        bookStore.setBookList(bookList);
        try {
            JAXBContext jaxbContext = JAXBContext.newInstance(BookStore.class);
            Marshaller marshaller = jaxbContext.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            //render the xml tree on console....
            marshaller.marshal(bookStore, System.out);
            //write the xml tree to a file
            marshaller.marshal(bookStore, new File(BOOKSTORE_XML));
        } catch (JAXBException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

 

JAXBUnmarshalDemo.java
package trg.jaxb.bookStore;

import java.io.File;
import java.io.IOException;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.xml.sax.SAXException;

public class JAXBUnmarshalDemo {
    private static final String BOOKSTORE_XML = "BookStore.xml";
    public static void main(String[] args) {
        try {
            JAXBContext jaxbContext = JAXBContext.newInstance(BookStore.class);
            System.out.println("Books from .xml file...\n\n");
           
            Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File("D:\\Sidharth\\Web Services\\workspace - WS\\SidWsTrg_JAXB_BookStore\\BookStore.xml"));
            doc.getDocumentElement().normalize();
            System.out.println("Name : " + doc.getChildNodes().item(0).getChildNodes().item(1).getChildNodes().item(0).getNodeValue());

            Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
            BookStore bookStore = (BookStore) unmarshaller.unmarshal(new File(BOOKSTORE_XML));
            for(Book book : bookStore.getBookList())
                System.out.println("Book -> " + book.getName() + " : " + book.getAuthor() + " : " + book.getPublisher() + " : " + book.getIsbn());
        } catch (JAXBException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

 

Download Link :  SidWsTrg_JAXB_BookStore


Generating Java Beans from XML Schema(.xsd files):


  • Set CLASSPATH for jaxb-api.jar, jaxb-impl.jar & jaxb-xjc.jar

  • Create xsd’s & run the following command:

                   $xjc [options]  <file>.xsd

E.g. ...\workspace - WS\SidWsTrg_JAXB_XSD_To_Bean\src>xjc -p trg.jaxb  Employee.xsd


Employee.xsd
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    xmlns:tns="http://trg.jaxb/employee" elementFormDefault="qualified"
    targetNamespace="http://trg.jaxb/employee">
    <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>

Run the below mentioned command(N.B. jars must be at classpath):

\workspace - WS\SidWsTrg_JAXB_XSD_To_Bean\src>xjc -p trg.jaxb  Employee.xsd

Download Link :  SidWsTrg_JAXB_XSD_To_Bean

Wednesday, 6 March 2013

How to set properties of a bean from properties file in spring

How to set properties of a bean from properties file.......

This can be accomplished by PropertyPlaceholderConfigurer class

Bean.java
package props;

public class Bean {
private String value1, value2;
public String getValue1() {
return value1;
}
public void setValue1(String value1) {
this.value1 = value1;
}
public String getValue2() {
return value2;
}
public void setValue2(String value2) {
this.value2 = value2;
}
}


ApplicationResource.properties
bean.value1=Sidhartha
bean.value2=Ray

context.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.5.xsd">
<bean name="properties" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="ApplicationResource.properties"/>
</bean>
<bean id="bean" class="props.Bean">
<property name="value1" value="${bean.value1}"/>
<property name="value2" value="${bean.value2}"/>
</bean>
</beans>

Client.java

package props;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Client {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("context.xml");
Bean bean = context.getBean("bean", Bean.class);
System.out.println(bean.getValue1() + " - " + bean.getValue2());
}
}

Web Services Using Tomcat & Axis Framework

Developing SOAP Based Web Services Using Tomcat-6 & Axis-1....

Download Tomcat 6  & Axis 1.2RC2

Installing Axis on Tomcat
Explode the axis zip folder. Now you need to deploy the Axis engine to Tomcat:
Here's how to do it:

Copy "..\axis-1_2\webapps\axis" into "..\apache-tomcat-6.0.36\webapps" folder.
Also add activation.jar & mail.jar into "..\apache-tomcat-6.0.36\webapps\axis\WEB-INF\lib"


Verify that Axis has been deployed correctly:

http://localhost:8085/axis/




Publishing Web Services with Axis

Let's say we have a simple class like the following:
HelloService.java 
 
package com.ws;
public class HelloService {
 public String sayHello(String name){
  return "Hello " + name + " !";
 } 
        public String sayBye(String name){
  return "Bye " + name + " !";
 }
}

How do we go about making this class available via SOAP?
There are a couple of answers to that question, but we'll start with an easy solution.

At first compile the class :

Goto HelloService.java's folder in command promt & compile,

javac -d . HelloService.java

Now copy that .class file & paste it into ..\apache-tomcat-6.0.36\webapps\axis\WEB-INF\classes along with the package structure(here com\ws\HelloService.class).

Ok, now the last step is registering your Web Service so that Axis is aware of it. A Web Service can be registered with a Web Service Deployment Descriptor (WSDD) file. A deployment descriptor contains a bunch of things you want to "deploy" into Axis - i.e. make available to the Axis engine.
Here's a simple wsdd file for our WebService:

HelloService.wsdd

<deployment xmlns="http://xml.apache.org/axis/wsdd/"                     xmlns:java="http://xml.apache.org/axis/wsdd/providers/java">
    <service name="HelloService" provider="java:RPC">
        <parameter name="className" value="com.ws.HelloService" />
        <parameter name="allowedMethods" value="*" />
    </service>
</deployment>





Pretty simple, really - the outermost element tells the engine that this is a WSDD deployment,and defines the "java" namespace. Then the service element actually defines the service for us. A service is a targeted chain which means it may have any of: a request flow, a provider, and a response flow.

In this case, our provider is "java:RPC", which is built into Axis, and indicates a Java RPC service. We need to tell the RPCProvider that it should instantiate and call the correct class (e.g. test.HelloService), and another to tell the engine that any public method on that class may be called via SOAP (that's what the "*" means)
Now save your wsdd file as HelloService.wsdd and run the Admin which is an Utility to deploy the WebService :

java -classpath %AXIS_HOME%/lib/axis.jar;%AXIS_HOME%/lib/commons-discovery-0.2.jar;%AXIS_HOME%/lib/commons-logging-1.0.4.jar;%AXIS_HOME%/lib/saaj.jar;%AXIS_HOME%/lib/jaxrpc.jar org.apache.axis.utils.Admin server HelloService.wsdd

If everything was Ok now you should see the WebService deployed on Axis: check the "List" option from the URL http://localhost:8085/axis/

Obtaining WSDL for deployed services
Now you can see your wsdl file something like this.......

http://localhost:8085/axis/services/HelloService?wsdl

<?xml version="1.0" encoding="UTF-8"?>
<wsdl:definitions targetNamespace="http://localhost:8085/axis/services/HelloService"           xmlns:apachesoap="http://xml.apache.org/xml-soap" xmlns:impl="http://localhost:8085/axis/services/HelloService" xmlns:intf="http://localhost:8085/axis/services/HelloService" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:wsdlsoap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<!--WSDL created by Apache Axis version: 1.4
Built on Apr 22, 2006 (06:55:48 PDT)-->

   <wsdl:message name="sayHelloRequest">
      <wsdl:part name="in0" type="xsd:string"/>
   </wsdl:message>
   <wsdl:message name="sayHelloResponse">
      <wsdl:part name="sayHelloReturn" type="xsd:string"/>
   </wsdl:message>
   <wsdl:portType name="HelloService">
      <wsdl:operation name="sayHello" parameterOrder="in0">
         <wsdl:input message="impl:sayHelloRequest" name="sayHelloRequest"/>
         <wsdl:output message="impl:sayHelloResponse" name="sayHelloResponse"/>
      </wsdl:operation>
   </wsdl:portType>
   <wsdl:binding name="HelloServiceSoapBinding" type="impl:HelloService">
      <wsdlsoap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/>
      <wsdl:operation name="sayHello">
         <wsdlsoap:operation soapAction=""/>
         <wsdl:input name="sayHelloRequest">
            <wsdlsoap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" namespace="http://ws.com" use="encoded"/>
         </wsdl:input>
         <wsdl:output name="sayHelloResponse">
            <wsdlsoap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" namespace="http://localhost:8085/axis/services/HelloService" use="encoded"/>
         </wsdl:output>
      </wsdl:operation>
   </wsdl:binding>
   <wsdl:service name="HelloServiceService">
      <wsdl:port binding="impl:HelloServiceSoapBinding" name="HelloService">
         <wsdlsoap:address location="http://localhost:8085/axis/services/HelloService"/>
      </wsdl:port>
   </wsdl:service>
</wsdl:definitions>



The client
Let's take a look at an example Web Service Client that will call the sayhello method of the HelloService Web Service
 
Client.java
 
package com.ws;

import java.net.MalformedURLException;
import org.apache.axis.AxisFault;
import org.apache.axis.client.Call;

public class Client{
  public static void main(String [] args) throws MalformedURLException, AxisFault  {
   String endpoint = "http://localhost:8085/axis/services/HelloService?wsdl";
   Call client = new Call(endpoint);
   String response = (String)client.invoke("http://localhost:8085/axis/services/HelloService",
          "sayHello",new Object [] {"Sidhartha"});
   System.out.println(response);
     }
}


Generating Java Classes from WSDL

Another approach is to generate Java Classes starting from WSDL contract. You can use the
AdminClient to follow this approach:

java -classpath %AXIS_HOME%/lib/wsdl4j-1.5.1.jar;%AXIS_HOME%/lib/axis.jar;%AXIS_HOME%/lib/commons-discovery-0.2.jar;%AXIS_HOME%/lib/commons-logging-1.0.4.jar;%AXIS_HOME%/lib/saaj.jar;%AXIS_HOME%/lib/jaxrpc.jar org.apache.axis.wsdl.WSDL2Java http://localhost:8085/axis/services/HelloService?wsdl

This will generate the following classes under the service namespace which is localhost\axis\services\HelloService

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 :