Thursday, 4 April 2013

RESTful web service tutorial

In this post,we will see RESTful web service introduction.

Part-1:Introduction to web services
Part-2:SOAP web service introduction 
Part-3:RESTful web service introduction 
Part-4:SOAP web service example in java using eclipse
Part-5:JAX-WS web service eclipse tutorial
Part-6:JAX-WS web service deployment on tomcat 
Part-7:Create RESTful web service in java(JAX-RS) using jersey

REST is an architectural style which was brought in by Roy Fielding in 2000 in his doctoral thesis.

In the web services terms, REpresentational State Transfer (REST) is  a stateless client-server architecture in which the web services are viewed as resources and can be identified by their URIs. Web service clients that want to use these resources access via globally defined set of remote methods that describe the action to be performed on the resource.

It consists of two components REST server which provides access to the resources and a REST client which accesses and modify the REST resources.

In the REST architecture style, clients and servers exchange representations of resources by using a standardized interface and protocol.REST isn't protocol specific, but when people talk about REST they usually mean REST over HTTP.

The response from server is considered as the representation of the resources. This representation can be generated from one resource or more number of resources.


REST allows that resources have different representations, e.g.xml, json etc. The rest client can ask for specific representation via the HTTP protocol.

HTTP methods : 

RESTful web services use HTTP protocol methods for the operations they perform.Methods are:
  • GET:It defines a reading access of the resource without side-effects.This operation is idempotent i.e.they can be applied multiple times without changing the result
  • PUT :  It creates a new resource.It must also be idempotent.
  • DELETE : It removes the resources. The operations are idempotent i.e. they can get repeated without leading to different results.
  • POST :It updates an existing resource or creates a new resource.

Features of RESTful web services:

Resource identification through URI:Resources are identified by their URIs (typically links on internet). So, a client can directly access a RESTful Web Services using the URIs of the resources (same as you put a website address in the browser’s address bar and get some representation as response).

Uniform interface: Resources are manipulated using a fixed set of four create, read, update, delete operations: PUT, GET, POST, and DELETE.

Client-Server: A clear separation concerns is the reason behind this constraint. Separating concerns between the Client and Server helps improve portability in the Client and Scalability of the server components.

Stateless: each request from client to server must contain all the information necessary to understand the request, and cannot take advantage of any stored context on the server.

Cache: to improve network efficiency responses must be capable of being labeled as cacheable or non-cacheable.

Named resources - the system is comprised of resources which are named using a URL.

Interconnected resource representations - the representations of the resources are interconnected using URLs, thereby enabling a client to progress from one state to another.

Layered components - intermediaries, such as proxy servers, cache servers, gateways, etc, can be inserted between clients and resources to support performance, security, etc.

Self-descriptive messages: Resources are decoupled from their representation so that their content can be accessed in a variety of formats, such as HTML, XML, plain text, PDF, JPEG, JSON, and others. 

Create RESTful web services in java(JAX-RS) using jersey

In this post,we will develop RESTful web service using jersey in eclipse

Web service Tutorial Content:

Part-1:Introduction to web services
Part-2:SOAP web service introduction 
Part-3:RESTful web service introduction 
Part-4:SOAP web service example in java using eclipse
Part-5:JAX-WS web service eclipse tutorial
Part-6:JAX-WS web service deployment on tomcat 
Part-7:Create RESTful web service in java(JAX-RS) using jersey

Java API for RESTful Web Services (JAX-RS), is a set if APIs to developer REST service. JAX-RS is part of the Java EE6, and make developers to develop REST web application easily.

Jersey is the reference implementation for this specification. Jersey contains basically a REST server and a REST client. The core client can communicate with the server using jersey lib.

On the server side Jersey uses a servlet which scans predefined classes to identify RESTful resources. Via the web.xml configuration file for your web application.

The base URL of this servlet is:
http://your_domain:port/display-name/url-pattern/path_from_rest_class 
This servlet analyzes the incoming HTTP request and selects the correct class and method depending on  request. This selection is based on annotations provided in the class and methods. 

Prerequisites:


1) Open eclipse.
2) Create new dynamic web project named "RESTfulWebserviceExample"

3) Now go to location where you have download jersey and go to jersey-archive-1.17->lib
folder.you can have all jars but for now you can copy following jars
  • asm-3.1
  • jersey-client-1.17
  • jersey-core-1.17
  • jersey-server-1.17
  • jersey-servlet-1.17
  • jsr311-api-1.1.1
Paste all above copied jars to WebContent->WEB-INF->lib

Add all these jars to eclipse build path.
Right click on project(RESTfulWebserviceExample)->properties


Click on Java Build Path and then Add jars as shown in above diagram.

go to project->WebContent->WEB-INF->lib and select all jars then click on ok.

Click ok.Jersey jars added to class path.
4) Create new package named "org.arpit.javapostsforlearning.webservice"

5)Create  FeetToInchAndInchToFeetConversionService.java

package org.arpit.javapostsforlearning.webservice;
/**
* @author Arpit Mandliya
*/
 
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
 
@Path("ConversionService")
public class FeetToInchAndInchToFeetConversionService {
     @GET
     @Path("/InchToFeet/{i}")
      @Produces(MediaType.TEXT_XML)
      public String convertInchToFeet(@PathParam("i") int i) {
 
        int inch=i;
        double feet = 0;
        feet =(double) inch/12;
      
        return "<InchToFeetService>"
        + "<Inch>" + inch + "</Inch>"
          + "<Feet>" + feet + "</Feet>"
         + "</InchToFeetService>";
      }
 
      @Path("/FeetToInch/{f}")
      @GET
      @Produces(MediaType.TEXT_XML)
      public String convertFeetToInch(@PathParam("f") int f) {
       int inch=0;
          int feet = f;
          inch = 12*feet;
   
          return "<FeetToInchService>"
            + "<Feet>" + feet + "</Feet>"
            + "<Inch>" + inch + "</Inch>"
            + "</FeetToInchService>";
      }
}

@Path(/your_path_at_class_level) : Sets the path to base URL + /your_path_at_class_level. The base URL is based on your application name, the servlet and the URL pattern from the web.xml" configuration file.

@Path(/your_path_at_method_level): Sets path to base URL + /your_path_at_class_level+ /your_path_at_method_level

@Produces(MediaType.TEXT_XML [, more-types ]): @Produces defines which MIME type is delivered by a method annotated with @GET. In the example text ("text/XML") is produced.

@PathParam: Used to inject values from the URL into a method parameter.This way you inject inch in convertFeetToInch method and convert that to feet.
6)Now you need to create web.xml and put it under /RESTfulWebserviceExample/WebContent/WEB-INF/
<?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>RESTfulWebServiceExample</display-name>
  <servlet>
    <servlet-name>Jersey REST Service</servlet-name>
    <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
    <init-param>
      <param-name>com.sun.jersey.config.property.packages</param-name>
      <param-value>org.arpit.javapostsforlearning.webservices</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>Jersey REST Service</servlet-name>
    <url-pattern>/rest/*</url-pattern>
  </servlet-mapping>
</web-app> 
In above <param-value>,put your web service package.
8) Run project:right click on project->run as ->run on server
9) Test your REST service under: "http://localhost:8080/RESTfulWebServiceExample/rest/ConversionService/FeetToInch/2". 

You will get output as :

If You see web service information page then you are done.

Creating a Restful Web Service Client:

Create ConversionServiceClient.java under org.arpit.javapostsforlearning.websevices.client

package org.arpit.javapostsforlearning.webservices.client;

import javax.ws.rs.core.MediaType;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;

public class ConversionServiceClient {
    static final String REST_URI = "http://localhost:8080/RESTfulWebServiceExample";
    static final String INCH_TO_FEET = "/ConversionService/InchToFeet/";
    static final String FEET_TO_INCH = "/ConversionService/FeetToInch/";

    public static void main(String[] args) {

        int inch=12;
        int feet=2;

        ClientConfig config = new DefaultClientConfig();
        Client client = Client.create(config);
        WebResource service = client.resource(REST_URI);

        WebResource addService = service.path("rest").path(INCH_TO_FEET+inch);
        System.out.println("INCH_TO_FEET Response: " + getResponse(addService));
        System.out.println("INCH_TO_FEET Output as XML: " + getOutputAsXML(addService));
        System.out.println("---------------------------------------------------");

        WebResource subService = service.path("rest").path(FEET_TO_INCH+feet);
        System.out.println("FEET_TO_INCH Response: " + getResponse(subService));
        System.out.println("FEET_TO_INCH Output as XML: " + getOutputAsXML(subService));
        System.out.println("---------------------------------------------------");

    }

    private static String getResponse(WebResource service) {
        return service.accept(MediaType.TEXT_XML).get(ClientResponse.class).toString();
    }

    private static String getOutputAsXML(WebResource service) {
        return service.accept(MediaType.TEXT_XML).get(String.class);
    }
}

Run above program
Output:
INCH_TO_FEET Response: GET http://localhost:8080/RESTfulWebServiceExample/rest/ConversionService/InchToFeet/12 returned a response status of 200 OK
INCH_TO_FEET Output as XML: <InchToFeetService><Inch>12</Inch><Feet>1.0</Feet></InchToFeetService>
---------------------------------------------------
FEET_TO_INCH Response: GET http://localhost:8080/RESTfulWebServiceExample/rest/ConversionService/FeetToInch/2 returned a response status of 200 OK
FEET_TO_INCH Output as XML: <FeetToInchService><Feet>2</Feet><Inch>24</Inch></FeetToInchService>
---------------------------------------------------
Source:Download 

Friday, 29 March 2013

JAX-WS web service eclipse tutorial

In this tutorial,we will see how we can develop JAX-WS endpoint and client step by step.

Web service Tutorial Content:

Part-1:Introduction to web services
Part-2:SOAP web service introduction 
Part-3:RESTful web service introduction 
Part-4:SOAP web service example in java using eclipse
Part-5:JAX-WS web service eclipse tutorial
Part-6:JAX-WS web service deployment on tomcat 
Part-7:Create RESTful web service in java(JAX-RS) using jersey

Prerequisites:

  1. JDK 1.6
  2. Eclipse IDE

Steps for creating JAX-WS webservice endpoint.

1) Open Eclipse IDE
2) Create java project named "JAXWSServer"


3)Create new package named "org.arpit.javapostsforlearning.webservice"

 4)Create JAXWSService Endpoint Interface.
HelloWorld.java
package org.arpit.javapostsforlearning.webservice;
import javax.jws.WebMethod;
import javax.jws.WebService;

@WebService
public interface HelloWorld {

 @WebMethod public String helloWorld(String name);
}
5)Create JAXWSService Endpoint implementation class.
HelloWorldImpl.java
package org.arpit.javapostsforlearning.webservice;
import javax.jws.WebService;

@WebService(endpointInterface="org.arpit.javapostsforlearning.webservice.HelloWorld")
public class HelloWorldImpl implements HelloWorld{

 public String helloWorld(String name) {
  return "Hello world from "+name;
 }

}
6) Create Endpoint publisher.
HelloWorldWSPublisher.java
package org.arpit.javapostsforlearning.webservice;
import javax.xml.ws.Endpoint;

public class HelloWorldWSPublisher {
 public static void main(String[] args) {
  Endpoint.publish("http://localhost:8080/WS/HelloWorld",new HelloWorldImpl());
 }
}
Run above program.Your webservice is published.You can check your service wsdl at http://localhost:8080/WS/HelloWorld?wsdl

Steps for creating JAXWS Client


1)Open eclipse and create a new java project JAXWSClient.
3) Now we need to generate the client stubs.So open your command line, and enter the wsimport command:
cd %project_home%/src
wsimport -s . http://localhost:8080/WS/HelloWorld?wsdl
you will find java classes generated and compiled under src->org->arpit->javapostsforlearning->webservice

4) Lets create client class now.
create JAXWSClient.java under src->org.arpit.javapostsforlearning.webservice.client
package org.arpit.javapostsforlearning.webservice.client;
import org.arpit.javapostsforlearning.webservice.HelloWorld;
import org.arpit.javapostsforlearning.webservice.HelloWorldImplService;

public class JAXWSClient {

    /**
     * @author Arpit Mandliya
     */
    public static void main(String[] args) {
        
        HelloWorldImplService helloWorldService = new HelloWorldImplService();
        HelloWorld helloWorld = helloWorldService.getHelloWorldImplPort();
        System.out.println(helloWorld.helloWorld("Arpit"));
    }
}

5) Run above program and you will get following output.
Hello world from Arpit

Congratulation,you have successfully created web service endpoint and client.Now in next post,we will deploy it on Tomcat.

SOAP web service example in java using eclipse

In this post,we will see SOAP web service example.

Web service Tutorial Content:

Part-1:Introduction to web services
Part-2:SOAP web service introduction 
Part-3:RESTful web service introduction 
Part-4:SOAP web service example in java using eclipse
Part-5:JAX-WS web service eclipse tutorial
Part-6:JAX-WS web service deployment on tomcat 
Part-7:Create RESTful web service in java(JAX-RS) using jersey

In this post,we will create hello world SOAP web service example in eclipse.Eclipse provides good API for creating web services.Eclipse will do all work for you-creating WSDL,stub,endpoints etc.

Steps for creating web services in eclipse:

1.Create new dynamic web project and name it "SimpleSOAPExample".
 2.Create new package named "org.arpit.javapostsforlearning.webservices"

3.Create a simple java class named "HelloWorld.java"
package org.arpit.javapostsforlearning.webservices;

public class HelloWorld {

    public String sayHelloWorld(String name)
    {
        return "Hello world from "+ name;
    }
}

4.Right click on project->new->web service


 5.Click on next.

In service implementation text box,write fully qualified class name of above created class(HelloWorld.java) and move both above slider to maximum level (i.e. Test service and Test Client level) and click on finish.You are done!!A new project named "SimpleSOAPExampleClient" will be created in your work space.


6.
Click on start server.
7.After clicking start server,eclipse will open test web service API.With this test API,you can test your web service.


You are done!!.But to understand more about web services,you need to explore more.You can explore above created "SimpleSOAPExampleClient" and learn more about web services.
In next post,you will see JAXWS web service example.


SOAP web service tutorial

In this post,we will see introduction to SOAP web services.

Web service Tutorial Content:

Part-1:Introduction to web services
Part-2:SOAP web service introduction 
Part-3:RESTful web service introduction 
Part-4:SOAP web service example in java using eclipse
Part-5:JAX-WS web service eclipse tutorial
Part-6:JAX-WS web service deployment on tomcat 
Part-7:Create RESTful web service in java(JAX-RS) using jersey

Simple Object Access Protocol (SOAP) is a standard protocol specification for message exchange based on XML. Communication between the web service and client happens using XML messages.

A simple web service architecture have two components
  • Client
  • Service provider

So as in above diagram,how client will communicate to service provider.So in order to communicate client must know some information for e.g.
  • Location of webservices server
  • Functions available,signature and return types of function.
  • Communication protocal
  • Input output formats
Service provider will create a standard XML file which will have all above information.So If this file is given to client then client will be able to access web service. This XML file is called WSDL.

What is WSDL?

WSDL stands for Web Service Description Language. It is an XML file that describes
the technical details of how to implement a web service, more specifically the URI,
port, method names, arguments, and data types. Since WSDL is XML, it is both
human-readable and machine-consumable, which aids in the ability to call and bind to
services dynamically.using this WSDL file we can understand things like,
  •     Port / Endpoint – URL of the web service
  •     Input message format
  •     Output message format
  •     Security protocol that needs to be followed
  •     Which protocol the web service uses

Ways to access web service:

There are two ways to access web service.
  • If Service provider knows client:If service provider knows its client then it will provide its wsdl to client and client will be able to access web service.


  • Service provider register its WSDL to UDDI and client can access it from UDDI:UDDI stands for Universal Description, Discovery and Integration.It is a directory service. Web services can register with a UDDI and make themselves available through it for discovery.So following steps are involved.
    1. Service provider registers with UDDI.
    2. Client searches for service in UDDI.
    3. UDDI returns all service providers offering that service.
    4. Client chooses service provider
    5. UDDI returns WSDL of chosen service provider.
    6. Using WSDL of service provider,client accesses web service.

In next post,we will see SOAP hello world example in java using eclipse.

Web Service tutorial

In this post,we will see introduction to web services and some jargona of web services.

Web service Tutorial Content:

Part-1:Introduction to web services
Part-2:SOAP web service introduction 
Part-3:RESTful web service introduction 
Part-4:SOAP web service example in java using eclipse
Part-5:JAX-WS web service eclipse tutorial
Part-6:JAX-WS web service deployment on tomcat 
Part-7:Create RESTful web service in java(JAX-RS) using jersey

Web service is a way of communication that allows interoperability between different applications on different platforms, for example, a java based application on Windows can communicate with a .Net based one on Linux. The communication can be done through a set of XML messages over HTTP protocol.

Web services are browsers and operating system independent service, which means it can run on any browser without the need of making any changes. Web Services take Web-applications to the Next Level.

The World Wide Web Consortium (W3C) has defined the web services. According to W3C, “Web Services are the message-based design frequently found on the Web and in enterprise software. The Web of Services is based on technologies such as HTTP, XML, SOAP, WSDL, SPARQL, and others.”


Lets say,you are a java developer and  you can publish your functions on internet or lan through java web service so any other developer(lets say .Net developer) can access your function.

Why you need to learn web services:

Reuse already developed(old) functionality into new software:

Lets understand with very simple example.Lets say you are developing a finance software for a company on java and you have old .net software which manages salary of employees.So rather then developing new software for employee part,you can use old software and for other parts like infrastructure you can develop your own functionalities.

Usability :

Web Services allow the business logic of many different systems to be exposed over the Web. This gives your applications the freedom to chose the Web Services that they need. Instead of re-inventing the wheel for each client, you need only include additional application-specific business logic on the client-side. This allows you to develop services and/or client-side code using the languages and tools that you want.

Interoperability :

This is the most important benefit of Web Services. Web Services typically work outside of private networks, offering developers a non-proprietary route to their solutions.Web Services also let developers use their preferred programming languages. In addition, thanks to the use of standards-based communications methods, Web Services are virtually platform-independent.

Loosely Coupled:

Each service exists independently of the other services that make up the application. Individual pieces of the application to be modified without impacting unrelated areas.

Ease of Integration:

Data is isolated between applications creating ’silos’. Web Services act as glue between these and enable easier communications within and across organisations.

Deployability :

Web Services are deployed over standard Internet technologies. This makes it possible to deploy Web Services even over the fire wall to servers running on the Internet on the other side of the globe. Also thanks to the use of proven community standards, underlying security (such as SSL) is already built-in.

Some jargons used in Web services:

Simple Object Access Protocol(SOAP):

SOAP is a protocol specification for exchanging structured information in the implementation of Web services in computer networks. It relies on XML as its message format.

Web Service Description Language(WSDL):

WSDL stands for Web Service Description Language. It is an XML file that describes
the technical details of how to implement a web service, more specifically the URI,
port, method names, arguments, and data types. Since WSDL is XML, it is both
human-readable and machine-consumable, which aids in the ability to call and bind to
services dynamically.

Elements of WSDL are:

Description:
It is the root element of a WSDL 2.0 file. It usually contains a set of name space declarations which are used throughout the WSDL file. 

Types:
The WSDL types element describes the data types used by your web service.Data types are usually specified by XML schema.It can be described in any language as long as your web services API supports it.

Binding:
The WSDL binding element describes how your web service is bound to a protocol. In other words, how your web service is accessible. To be accessible, the web service must be reachable using some network protocol. This is called "binding" the web service to the protocol.

Interface:
The WSDL interface element describes the operations supported by your web service.It is similar to methods in programming language.Client can only call one opertion per request. 

Service:
It describes the endpoint of your web service. In other words, the address where the web service can be reached.

Endpoint:
The endpoint element describes the address of the web service. The endpoint binding attribute describes what binding element this endpoint uses.i.e. protocol with which you will access web service. The address attribute describes the URI at which you can access the service.

Message:
The message element describes the data being exchanged between the Web service providers and consumers.

Sample WSDL file:
   <?xml version="1.0" encoding="UTF-8"?>
<wsdl:definitions targetNamespace="http://webservices.javapostsforlearning.arpit.org" xmlns:apachesoap="http://xml.apache.org/xml-soap" xmlns:impl="http://webservices.javapostsforlearning.arpit.org" xmlns:intf="http://webservices.javapostsforlearning.arpit.org" 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:types>
  <schema elementFormDefault="qualified" targetNamespace="http://webservices.javapostsforlearning.arpit.org" xmlns="http://www.w3.org/2001/XMLSchema">
   <element name="sayHelloWorld">
    <complexType>
     <sequence>
      <element name="name" type="xsd:string"/>
     </sequence>
    </complexType>
   </element>
   <element name="sayHelloWorldResponse">
    <complexType>
     <sequence>
      <element name="sayHelloWorldReturn" type="xsd:string"/>
     </sequence>
    </complexType>
   </element>
  </schema>
 </wsdl:types>
   <wsdl:message name="sayHelloWorldRequest">
      <wsdl:part element="impl:sayHelloWorld" name="parameters"/>
   </wsdl:message>
   <wsdl:message name="sayHelloWorldResponse">
      <wsdl:part element="impl:sayHelloWorldResponse" name="parameters"/>
   </wsdl:message>
   <wsdl:portType name="HelloWorld">
      <wsdl:operation name="sayHelloWorld">
         <wsdl:input message="impl:sayHelloWorldRequest" name="sayHelloWorldRequest"/>
         <wsdl:output message="impl:sayHelloWorldResponse" name="sayHelloWorldResponse"/>
      </wsdl:operation>
   </wsdl:portType>
   <wsdl:binding name="HelloWorldSoapBinding" type="impl:HelloWorld">
      <wsdlsoap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
      <wsdl:operation name="sayHelloWorld">
         <wsdlsoap:operation soapAction=""/>
         <wsdl:input name="sayHelloWorldRequest">
            <wsdlsoap:body use="literal"/>
         </wsdl:input>
         <wsdl:output name="sayHelloWorldResponse">
            <wsdlsoap:body use="literal"/>
         </wsdl:output>
      </wsdl:operation>
   </wsdl:binding>
   <wsdl:service name="HelloWorldService">
      <wsdl:port binding="impl:HelloWorldSoapBinding" name="HelloWorld">
         <wsdlsoap:address location="http://localhost:8080/SimpleSOAPExample/services/HelloWorld"/>
      </wsdl:port>
   </wsdl:service>
</wsdl:definitions>
    Universal Description, Discovery and Integration(UDDI):

    UDDI stands for Universal Description, Discovery and Integration.It is a directory service. Web services can register with a UDDI and make themselves available through it for discovery

    Web service design approaches:

    Contract last or Bottom up approach:
    When using contract last approach,you first write your java code then you create web service contract(WSDL) .There are various kinds of tools which can generate WSDL on the basis of java code.
    Contract first or Top Down Approach :
    It  is reverse of contract first.Here you first define web service contract.You define all the elements of WSDL first then after that you create your java logic.

    JAX-WS webservice deployment on tomcat

    In previous post,we have seen how to develop JAX-WS web service end point and client.In this post,we will see how we can deploy web service end point to application server.

    Web service Tutorial Content:

    Part-1:Introduction to web services
    Part-2:SOAP web service introduction
    Part-3:SOAP web service example in java using eclipse
    Part-4:JAX-WS web service eclipse tutorial
    Part-5:JAX-WS web service deployment on tomcat
    


    Here we will use tomcat as application server.

    1) Open eclipse.
    2) Create new web project named "HelloWorldWS"
    3) Create new package named "org.arpit.javapostsforlearning.webservice"

     4) Create JAXWSService Interface.
    HelloWorld.java
    package org.arpit.javapostsforlearning.webservice;
    import javax.jws.WebMethod;
    import javax.jws.WebService;
    
    @WebService
    public interface HelloWorld {
    
     @WebMethod public String helloWorld(String name);
    }
    
    5)Create JAXWSService implementation class.
    HelloWorldImpl.java
    package org.arpit.javapostsforlearning.webservice;
    import javax.jws.WebService;
    
    @WebService(endpointInterface="org.arpit.javapostsforlearning.webservice.HelloWorld")
    public class HelloWorldImpl implements HelloWorld{
    
     public String helloWorld(String name) {
      return "Hello world from "+name;
     }
    
    }
    

    6) Now , you need generate Web Services classes, open your command line, and type :
    cd %project_home%
    wsgen -s src -d build/classes -cp build/classes org.arpit.javapostsforlearning.webservice.HelloworldImpl
    Now we will have two class generated under src/org/arpit/javapostsforlearning/webservice/jaxws

    7)Now you need to create web.xml and put it under /HelloWorldWS/WebContent/WEB-INF/
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app
         xmlns="http://java.sun.com/xml/ns/j2ee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
                             http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
         version="2.4">
         <display-name>HellooWorldWS</display-name>
       <listener>
         <listener-class>
            com.sun.xml.ws.transport.http.servlet.WSServletContextListener
         </listener-class>
       </listener>
       <servlet>
          <servlet-name>HelloWorldWS</servlet-name>
          <servlet-class>
            com.sun.xml.ws.transport.http.servlet.WSServlet
          </servlet-class>
       </servlet>
       <servlet-mapping>
         <servlet-name>HelloWorldWS</servlet-name>
         <url-pattern>/HelloWorldWS</url-pattern>
       </servlet-mapping>
    </web-app>
    we have inserted three things here 1.listner-class 2.servlet 3.servlet-mapping
    8) Now we will add sun-jaxws.xml under HelloWorldWS/WebContent/WEB-INF/.It will have endpoint definition.

    <?xml version="1.0" encoding="UTF-8"?>
    <endpoints xmlns="http://java.sun.com/xml/ns/jax-ws/ri/runtime" version="2.0">
      <endpoint
         name="HelloWorldWS"
         implementation="org.arpit.javapostsforlearning.webservice.HelloWorldImpl"
         url-pattern="/HelloWorldWS"/>
    </endpoints> 
    9) We need to download some jaxws jars and put jars under /HelloWorldWS/WebContent/WEB-INF/lib.
    you can download attached library from attachment.
    10) Now export your project as war and put it under your Tomcat webapps folder.
    11) Run tomcat
    If You see web service information page then you are done.
    Source:Download 
    

    Tuesday, 12 March 2013

    serialVersionUID in java Serialization

    serialVersionUID is used to ensure that same class(That was used during Serialization) is loaded during Deserialization.serialVersionUID is used for version control of object.
    If you have used Serialization then You might have seen  serialVersionUID because whenever you implement Serializable interface your IDE will give you warning.

    Serialversionuid Syntax:

    As per java docs
    ANY-ACCESS-MODIFIER static final long serialVersionUID = 42L;

    serialVersionUID must be Static and final.You can assign any number to it.
    Lets see an example:
    Create Employee.java in src->org.arpit.javapostsforlearning

    1.Employee.java
    package org.arpit.javapostsforlearning;
    import java.io.Serializable;
    public class Employee implements Serializable{
    
             private static final long serialVersionUID = 1L;
    
        int employeeId;
        String employeeName;
        String department;
        
        public int getEmployeeId() {
            return employeeId;
        }
        public void setEmployeeId(int employeeId) {
            this.employeeId = employeeId;
        }
        public String getEmployeeName() {
            return employeeName;
        }
        public void setEmployeeName(String employeeName) {
            this.employeeName = employeeName;
        }
        public String getDepartment() {
            return department;
        }
        public void setDepartment(String department) {
            this.department = department;
        }
    }

    Create SerializeMain.java in src->org.arpit.javapostsforlearning

    2.SerializeMain.java
    package org.arpit.javapostsforlearning;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.ObjectOutputStream;
     public class SerializeMain {
    
     /**
      * @author Arpit Mandliya
      */
     public static void main(String[] args) {
    
      Employee emp = new Employee();
      emp.setEmployeeId(101);
      emp.setEmployeeName("Arpit");
      emp.setDepartment("CS");
      try
      {
       FileOutputStream fileOut = new FileOutputStream("employee.ser");
       ObjectOutputStream outStream = new ObjectOutputStream(fileOut);
       outStream.writeObject(emp);
       outStream.close();
       fileOut.close();
      }catch(IOException i)
      {
       i.printStackTrace();
      }
     }
    }
    Create DeserializeMain.java in src->org.arpit.javapostsforlearning
    3.DeserializeMain.java
    package org.arpit.javapostsforlearning;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    
    public class DeserializeMain {
     /**
      * @author Arpit Mandliya
      */
     public static void main(String[] args) {
      
      Employee emp = null;
           try
           {
              FileInputStream fileIn =new FileInputStream("employee.ser");
              ObjectInputStream in = new ObjectInputStream(fileIn);
              emp = (Employee) in.readObject();
              in.close();
              fileIn.close();
           }catch(IOException i)
           {
              i.printStackTrace();
              return;
           }catch(ClassNotFoundException c)
           {
              System.out.println("Employee class not found");
              c.printStackTrace();
              return;
           }
           System.out.println("Deserialized Employee...");
           System.out.println("Emp id: " + emp.getEmployeeId());
           System.out.println("Name: " + emp.getEmployeeName());
           System.out.println("Department: " + emp.getDepartment());
     }
    }
    

    4.Run it:

    First run SerializeMain.java then DeserializeMain.java and you will get following output:
    Deserialized Employee...
    Emp id: 101
    Name: Arpit
    Department: CS
    So when you run program,it was completed successfully and employee.ser has been created on disk.If you again run DeserializeMain.java,it will again run successfully. Now change value of variable serial to
     private static final long serialVersionUID = 2L;
    
    and if you now run DeserializeMain.java it will give you following error.
    java.io.InvalidClassException: org.arpit.javapostsforlearning.Employee; local class incompatible: stream classdesc serialVersionUID = 1, local class serialVersionUID = 2
    
    So here during deserialization,we got error.It complained about Serialvesionuid being changed.But how does it know? because serialversionuid is a static variable and we know that "We can not serialize static variables".How does it store  serialversionuid? yes ,there is exception.Inspite of serialversionuid being static,it get serialized.So ObjectOutputStream writes every time to output stream and ObjectInputStream reads it back and if it does not have same values as in current version of class then it throw InvalidClassException.

    Why serialversionuid is required?

    In real time,It is possible that you have serialized a object in a file and you deserialized it after few months on different JVM.In between serialization and deserialization class declaration has been changed.So it is a good idea to maintain version system and serialversionid does exactly same thing.It checks if you are deserializing same object which you have serialized.

    Best Practices:

    Java docs says:
    "the default serialVersionUID computation is highly sensitive to class details that may vary depending on compiler implementations, and can thus result in unexpected InvalidClassExceptions during deserialization".

    So it says you must declare serialVersionUID because it give us more control.for e.g. Default rules for generating serialVersionUID can be too strict in some cases. For example when the visibility of a field changes, the serialVersionUID changes too. or sometimes you just want to forbid deserialization of old serialized object then you can just change serialVersionUID.

    Is this enough?.No,you must not only declare it but also maintain it.So most important part is maintaining  serialVersionUID otherwise every thing will run without any exceptions.You should change serialVersionUID when there is some change in the definition of data stored in the class for example data type of field is changed.

    Sunday, 10 March 2013

    Serialization in java

    Java provides mechanism called serialization to persists java objects in a form of ordered or sequence of bytes that includes the object's data as well as information about the object's type and the types of data stored in the object.

    So if we need to serialize any object then it can be read and deserialize it using object's type and other information so we can retrieve original object.

    Classes ObjectInputStream and ObjectOutputStream are high-level streams that contain the methods for serializing and deserializing an object.
    ObjectOutputStream has many method for serializing object but commonly used method is
        private void writeObject(ObjectOutputStream os) throws IOException
        { 
            
        }
    
    Similarly ObjectInputStream has
        private void readObject(ObjectInputStream is) throws IOException, ClassNotFoundException
        {
            
        }
    

    Need of Serialization?

    Serialization is usually used when there is need to send your data over network or to store in files. By data I mean objects and not text.

    Now the problem is your Network infrastructure and your Hard disk are hardware components that understand bits and bytes but not Java objects.

    Serialization is the translation of Java object's values/states to bytes to send it over network or to save it.On other hand,Deserialization is conversion of byte code to corresponding java objects.

    Concept of serialVersionUID :

    serialVersionUID is used to ensure that same class(That was used during Serialization) is loaded during Deserialization.serialVersionUID is used for version control of object.You can read more at serialVersionUID in java serialization


    For Serialization:
    steps are :
    Lets take an example:
    Create Employee.java in src->org.arpit.javapostsforlearning

    1.Employee.java
    package org.arpit.javapostsforlearning;
    import java.io.Serializable;
    public class Employee implements Serializable{ 
       private static final long serialVersionUID = 1L;    
      int employeeId;
        String employeeName;
        String department;
        
        public int getEmployeeId() {
            return employeeId;
        }
        public void setEmployeeId(int employeeId) {
            this.employeeId = employeeId;
        }
        public String getEmployeeName() {
            return employeeName;
        }
        public void setEmployeeName(String employeeName) {
            this.employeeName = employeeName;
        }
        public String getDepartment() {
            return department;
        }
        public void setDepartment(String department) {
            this.department = department;
        }
    }
    As you can see above,if you want to serialize any class then it must implement Serializable interface which is marker interface.
    Marker interface in Java is interfaces with no field or methods or in simple word empty interface in java is called marker interface
    Create SerializeMain.java in src->org.arpit.javapostsforlearning

    2.SerializeMain.java
    package org.arpit.javapostsforlearning;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.ObjectOutputStream;
     public class SerializeMain {
    
     /**
      * @author Arpit Mandliya
      */
     public static void main(String[] args) {
    
      Employee emp = new Employee();
      emp.setEmployeeId(101);
      emp.setEmployeeName("Arpit");
      emp.setDepartment("CS");
      try
      {
       FileOutputStream fileOut = new FileOutputStream("employee.ser");
       ObjectOutputStream outStream = new ObjectOutputStream(fileOut);
       outStream.writeObject(emp);
       outStream.close();
       fileOut.close();
      }catch(IOException i)
      {
       i.printStackTrace();
      }
     }
    }

    For Deserialization:

    Steps are:
    Create DeserializeMain.java in src->org.arpit.javapostsforlearning

    3.DeserializeMain.java
    package org.arpit.javapostsforlearning;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    
    public class DeserializeMain {
     /**
      * @author Arpit Mandliya
      */
     public static void main(String[] args) {
      
      Employee emp = null;
           try
           {
              FileInputStream fileIn =new FileInputStream("employee.ser");
              ObjectInputStream in = new ObjectInputStream(fileIn);
              emp = (Employee) in.readObject();
              in.close();
              fileIn.close();
           }catch(IOException i)
           {
              i.printStackTrace();
              return;
           }catch(ClassNotFoundException c)
           {
              System.out.println("Employee class not found");
              c.printStackTrace();
              return;
           }
           System.out.println("Deserialized Employee...");
           System.out.println("Emp id: " + emp.getEmployeeId());
           System.out.println("Name: " + emp.getEmployeeName());
           System.out.println("Department: " + emp.getDepartment());
     }
    }

    4.Run it:

    First run SerializeMain.java then DeserializeMain.java and you will get following output:
    Deserialized Employee...
    Emp id: 101
    Name: Arpit
    Department: CS
    So we have serialize an employee object and then deserialized it.It seems very simple but it can be very complex when reference object,inheritance come into the picture.So we will see different cases one by one and how we can apply serialization in different scenarios.

    Case 1-What if an object has a reference to other objects

    We have seen very simple case of serialization,now what if it also a reference to other objects.How will it serialized then? will reference object will also get serialized?.Yes,You don't have to explicitly serialize reference objects.When you serialize any object and if it contain any other object reference then Java serialization serialize that object's entire object graph.
    For example:Lets say,Employee now has reference to address object and Address can have reference to some other object(e.g.Home) then when you serialize Employee object all other reference objects such as address and home will be automatically serialized. Lets create Address class  and add object of Address as a reference to above employee class.

    Employee.java:

    package org.arpit.javapostsforlearning;
    import java.io.Serializable;
    
    public class Employee implements Serializable{ 
    
     private static final long serialVersionUID = 1L;
     int employeeId;
     String employeeName;
     String department;
     Address address;
     
     public int getEmployeeId() {
      return employeeId;
     }
     public void setEmployeeId(int employeeId) {
      this.employeeId = employeeId;
     }
     public String getEmployeeName() {
      return employeeName;
     }
     public void setEmployeeName(String employeeName) {
      this.employeeName = employeeName;
     }
     public String getDepartment() {
      return department;
     }
     public void setDepartment(String department) {
      this.department = department;
     }
     public Address getAddress() {
      return address;
     }
     public void setAddress(Address address) {
      this.address = address;
     }
    }

    Create Address.java in org.arpit.javapostsforlearning
    Address.java:
    package org.arpit.javapostsforlearning;
    public class Address {
    
     int homeNo;
     String street;
     String city;
     public Address(int homeNo, String street, String city) {
      super();
      this.homeNo = homeNo;
      this.street = street;
      this.city = city;
     }
     public int getHomeNo() {
      return homeNo;
     }
     public void setHomeNo(int homeNo) {
      this.homeNo = homeNo;
     }
     public String getStreet() {
      return street;
     }
     public void setStreet(String street) {
      this.street = street;
     }
     public String getCity() {
      return city;
     }
     public void setCity(String city) {
      this.city = city;
     }
    }
    Create SerializeDeserializeMain.java in org.arpit.javapostsforlearning
    SerializeDeserializeMain.java:
    package org.arpit.javapostsforlearning;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    
    public class SerializeDeserializeMain {
     /**
      * @author Arpit Mandliya
      */
     public static void main(String[] args) {
    
      Employee emp = new Employee();
      emp.setEmployeeId(101);
      emp.setEmployeeName("Arpit");
      emp.setDepartment("CS");
      Address address=new Address(88,"MG road","Pune");
      emp.setAddress(address);
      //Serialize
      try
      {
       FileOutputStream fileOut = new FileOutputStream("employee.ser");
       ObjectOutputStream outStream = new ObjectOutputStream(fileOut);
       outStream.writeObject(emp);
       outStream.close();
       fileOut.close();
      }catch(IOException i)
      {
       i.printStackTrace();
      }
    
      //Deserialize
      emp = null;
      try
      {
       FileInputStream fileIn =new FileInputStream("employee.ser");
       ObjectInputStream in = new ObjectInputStream(fileIn);
       emp = (Employee) in.readObject();
       in.close();
       fileIn.close();
      }catch(IOException i)
      {
       i.printStackTrace();
       return;
      }catch(ClassNotFoundException c)
      {
       System.out.println("Employee class not found");
       c.printStackTrace();
       return;
      }
      System.out.println("Deserialized Employee...");
      System.out.println("Emp id: " + emp.getEmployeeId());
      System.out.println("Name: " + emp.getEmployeeName());
      System.out.println("Department: " + emp.getDepartment());
      address=emp.getAddress();
      System.out.println("City :"+address.getCity());
     }
    }
    Run it :
    When you run SerializeDeserializeMain.java.You will get following output

    java.io.NotSerializableException: org.arpit.javapostsforlearning.Address
        at java.io.ObjectOutputStream.writeObject0(Unknown Source)
        at java.io.ObjectOutputStream.defaultWriteFields(Unknown Source)
        at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
        at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
        at java.io.ObjectOutputStream.writeObject0(Unknown Source)
        at java.io.ObjectOutputStream.writeObject(Unknown Source) 
    We got exception what went wrong.I forgot to mention,Address class must also be serializable.So you have to make Address serializable by implement serialzable interface.

    Address.java:
    import java.io.Serializable;
    
    public class Address implements Serializable{
    
     private static final long serialVersionUID = 1L;
     int homeNo;
     String street;
     String city;
     public Address(int homeNo, String street, String city) {
      super();
      this.homeNo = homeNo;
      this.street = street;
      this.city = city;
     } 
     public int getHomeNo() {
      return homeNo;
     }
     public void setHomeNo(int homeNo) {
      this.homeNo = homeNo;
     }
     public String getStreet() {
      return street;
     }
     public void setStreet(String street) {
      this.street = street;
     }
     public String getCity() {
      return city;
     }
     public void setCity(String city) {
      this.city = city;
     }
    }
    Run again:
    When you run again SerializeDeserializeMain.java.You will get following output

    Deserialized Employee...
    Emp id: 101
    Name: Arpit
    Department: CS
    City :Pune 

    Case 2:What if you don't have access to reference object's source code(e.g you don't have access to above Address class)
    If you don't have access to address class then how will you implement serializable interface in Address class.Is there any alternative to that? yes there is,You can create another class which extends address and make it serialzable but It can fails in many cases:
    • What if class is declared as final
    • What if class have reference to other non serializable object.
    So then how will  you serialize Employee object? so solution is you can make it transient.If you don't want to serialize any field then make it transient.
    transient Address address 
    So after making address transient in Employee class when you run program.You will get nullPointerException because during deserialization address reference will be null

    Case 3:What if you still want to save state of reference object(e.g above address object):
    If you make address transient then during deserialization it will return null.But what if you still want to have same state as when you have serialized address object.Java serialization provides a mechnism such that if you have private methods with particular signature then they will get called during serialization and deserialization so we will override writeObject and readObject method of employee class and they will be called during serialization and deserialization of Employee object.

    Employee.java:
    package org.arpit.javapostsforlearning;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.io.Serializable;
    
    public class Employee implements Serializable{ 
     private static final long serialVersionUID = 1L;
    
    int employeeId;
     String employeeName;
     String department;
     transient Address address;
    
     public int getEmployeeId() {
      return employeeId;
     }
     public void setEmployeeId(int employeeId) {
      this.employeeId = employeeId;
     }
     public String getEmployeeName() {
      return employeeName;
     }
     public void setEmployeeName(String employeeName) {
      this.employeeName = employeeName;
     }
     public String getDepartment() {
      return department;
     }
     public void setDepartment(String department) {
      this.department = department;
     }
     public Address getAddress() {
      return address;
     }
     public void setAddress(Address address) {
      this.address = address;
     }
    
     private void writeObject(ObjectOutputStream os) throws IOException, ClassNotFoundException
     { 
      try {
       os.defaultWriteObject();
       os.writeInt(address.getHomeNo());
       os.writeObject(address.getStreet());
       os.writeObject(address.getCity());
      } 
      catch (Exception e) 
      { e.printStackTrace(); }
     }
     
     private void readObject(ObjectInputStream is) throws IOException, ClassNotFoundException
     {
      try {
       is.defaultReadObject();
       int homeNo=is.readInt();
       String street=(String) is.readObject();
       String city=(String) is.readObject();
       address=new Address(homeNo,street,city);
    
      } catch (Exception e) { e.printStackTrace(); }
     }
    }

    One thing should be kept in mind that ObjectInputStream should read data in same sequence in which we have written data to ObjectOutputStream.

    Create Address.java in org.arpit.javapostsforlearning
    Address.java:
    package org.arpit.javapostsforlearning;
    import java.io.Serializable;
    
    public class Address {
    
     int homeNo;
     String street;
     String city;
     
     
     public Address(int homeNo, String street, String city) {
      super();
      this.homeNo = homeNo;
      this.street = street;
      this.city = city;
     }
     public int getHomeNo() {
      return homeNo;
     }
     public void setHomeNo(int homeNo) {
      this.homeNo = homeNo;
     }
     public String getStreet() {
      return street;
     }
     public void setStreet(String street) {
      this.street = street;
     }
     public String getCity() {
      return city;
     }
     public void setCity(String city) {
      this.city = city;
     }
    }

    Create SerializeDeserializeMain.java in org.arpit.javapostsforlearning
    SerializeDeserializeMain.java:
    package org.arpit.javapostsforlearning;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    
    public class SerializeDeserializeMain {
     /**
      * @author Arpit Mandliya
      */
     public static void main(String[] args) {
    
      Employee emp = new Employee();
      emp.setEmployeeId(101);
      emp.setEmployeeName("Arpit");
      emp.setDepartment("CS");
      Address address=new Address(88,"MG road","Pune");
      emp.setAddress(address);
      //Serialize
      try
      {
       FileOutputStream fileOut = new FileOutputStream("employee.ser");
       ObjectOutputStream outStream = new ObjectOutputStream(fileOut);
       outStream.writeObject(emp);
       outStream.close();
       fileOut.close();
      }catch(IOException i)
      {
       i.printStackTrace();
      }
    
      //Deserialize
      emp = null;
      try
      {
       FileInputStream fileIn =new FileInputStream("employee.ser");
       ObjectInputStream in = new ObjectInputStream(fileIn);
       emp = (Employee) in.readObject();
       in.close();
       fileIn.close();
      }catch(IOException i)
      {
       i.printStackTrace();
       return;
      }catch(ClassNotFoundException c)
      {
       System.out.println("Employee class not found");
       c.printStackTrace();
       return;
      }
      System.out.println("Deserialized Employee...");
      System.out.println("Emp id: " + emp.getEmployeeId());
      System.out.println("Name: " + emp.getEmployeeName());
      System.out.println("Department: " + emp.getDepartment());
      address=emp.getAddress();
      System.out.println("City :"+address.getCity());
     }
    }

    Run it :
    When you run SerializeDeserializeMain.java.You will get following output
    Deserialized Employee...
    Emp id: 101
    Name: Arpit
    Department: CS
    City :Pune

    so now we got same state of address object as it was before serialization.

    Inheritance in Serialization:

    Now we will see how inheritance affects serialization.So there can be muliple cases whether super class is serializable or not.If not then how will you handle that and how it works.Lets see by example.
    We will create Person.java which will be superclass of Employee.


    Case 4: What  if superclass is Serializable?
    If superclass is serialzable then all its subclasses are automatically serializable.

    Case 5:What if superclass is not Serializable?
    If super class is not serializable then we have to handle it quite differently.
    • If superclass is not serializable then it must have no argument constructor.
    Person.java
    package org.arpit.javapostsforlearning;
    public class Person {
     
     String name="default";
     String nationality;
     
     public Person()
     {
      System.out.println("Person:Constructor");
     }
    
     public Person(String name, String nationality) {
      super();
      this.name = name;
      this.nationality = nationality;
     }
     
     public String getName() {
      return name;
     }
    
     public void setName(String name) {
      this.name = name;
     }
    
     public String getNationality() {
      return nationality;
     }
    
     public void setNationality(String nationality) {
      this.nationality = nationality;
     }
    
    }

    Create Employee.java in org.arpit.javapostsforlearning
    Employee.java:
    package org.arpit.javapostsforlearning;
    import java.io.Serializable;
    
    public class Employee extends Person implements Serializable{ 
     private static final long serialVersionUID = 1L;
     int employeeId;
     String department;
     
     public Employee(int employeeId,String name,String department,String nationality)
     {
      super(name,nationality);
      this.employeeId=employeeId;
      this.department=department;
      System.out.println("Employee:Constructor");
     }
     
     public int getEmployeeId() {
      return employeeId;
     }
     public void setEmployeeId(int employeeId) {
      this.employeeId = employeeId;
     }
     
     public String getDepartment() {
      return department;
     }
     public void setDepartment(String department) {
      this.department = department;
     }
    }
    Create SerializeDeserializeMain.java in org.arpit.javapostsforlearning
    SerializeDeserializeMain.java:
    package org.arpit.javapostsforlearning;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    
    public class SerializeDeserializeMain {
    
     /**
      * @author Arpit Mandliya
      */
     public static void main(String[] args) {
    
      //Serialize
      Employee emp = new Employee(101,"Arpit","CS","Indian");
      System.out.println("Before serializing");
      System.out.println("Emp id: " + emp.getEmployeeId());
      System.out.println("Name: " + emp.getName());
      System.out.println("Department: " + emp.getDepartment());
      System.out.println("Nationality: " + emp.getNationality());
      System.out.println("************");
      System.out.println("Serializing");
      try
      {
       FileOutputStream fileOut = new FileOutputStream("employee.ser");
       ObjectOutputStream outStream = new ObjectOutputStream(fileOut);
       outStream.writeObject(emp);
       outStream.close();
       fileOut.close();
      }catch(IOException i)
      {
       i.printStackTrace();
      }
    
      //Deserialize
      System.out.println("************");
      System.out.println("Deserializing");
      emp = null;
      try
      {
       FileInputStream fileIn =new FileInputStream("employee.ser");
       ObjectInputStream in = new ObjectInputStream(fileIn);
       emp = (Employee) in.readObject();
       in.close();
       fileIn.close();
      }catch(IOException i)
      {
       i.printStackTrace();
       return;
      }catch(ClassNotFoundException c)
      {
       System.out.println("Employee class not found");
       c.printStackTrace();
       return;
      }
      System.out.println("After serializing");
      System.out.println("Emp id: " + emp.getEmployeeId());
      System.out.println("Name: " + emp.getName());
      System.out.println("Department: " + emp.getDepartment());
      System.out.println("Nationality: " + emp.getNationality());
     }
    }

    Run it :
    When you run SerializeDeserializeMain.java.You will get following output
    If superclass is not Serializable then all values of the instance variables inherited from super class will be initialized by calling constructor of Non-Serializable Super class during deserialization process. so here name is inherited from person so during deserialization,name is initialized to default.

    Case 6-What if superclass is Serializable but you don't want subclass to be Serializable
    If you don't want subclass to serializable then you need to implement writeObject() and readObject() method and need to throw NotSerializableException from this methods.

    Case 7-Can you Serialize static variables?
    No,you can't.As you know static variable are at class level not at object level and you serialize a object so you can't serialize static variables.

    Summary:

    • Serialization is the translation of your Java object's values/states to bytes to send it over network or save it.On other hand,Deserialization is conversion of byte code to corresponding java objects.
    • Good thing about Serialization is entire process is JVM independent, meaning an object can be serialized on one platform and deserialized on an entirely different platform.\
    • If you want to serialize any class then it must implement Serializable interface which is marker interface. 
    • Marker interface in Java is interface with no field or methods or in simple word empty interface in java is called marker interface
    • serialVersionUID is used to ensure that same object(That was used during Serialization) is loaded during Deserialization.serialVersionUID is used for version control of object.
    • When you serialize any object and if it contain any other object reference then Java serialization serialize that object's entire object graph.
    • If you don't want to serialize any field,then make it trasient.
    • If superclass is Serializable then its subclasses are automatically Serializable.
    • If superclass is not Serializable then all values of the instance variables inherited from super class will be initialized by calling constructor of Non-Serializable Super class during deserialization process.
    • If you don't want subclass to serializable then you need to implement writeObject() and readObject() method and need to throw NotSerializableException from this methods.
    • You can't serialize static variables.

    Sunday, 3 March 2013

    Hibernate inheritance:Table per concrete class

    This is 8 of 8 parts of tutorial series

    Tutorial Content:

    Part-1:Introduction to hibernate framework
    Part-2:Hibernate hello world example in eclipse
    Part-3:Hibernate one to one mapping example
    Part-4:Hibernate one to many mapping example
    Part-5:Hibernate many to many mapping example
    Part-6:Hibernate inheritance:Table per class hierarchy
    Part-7:Hibernate inheritance:table per subclass
    Part-8:Hibernate inheritance:Table per concrete class 
     
    In this tutorial,we will see how to implement inheritance in hibernate.There are 3 ways in which you can implement inheritance in hibernate.In this post,we will see one of them i.e.one table per concrete class.

    Inheritance in hibernate:

    Java is object oriented language and inheritance is one of main functionalities of java.Relation model can implement "is a" and "has a" relationship but hibernate provides us way to implement class hierarchy in a different ways.

    Table per concrete class:

    Lets say we have following class hierarchy.We have shape class as base class and Rectangle and Circle inherit from Shape class.

     In  table per concrete class ,One table will be created for each concrete class..So there table will be created SHAPE,RECTANGLE and CIRCLE and subclass repeats property of parent class.

    As per our class diagram,we will create three classes-Shape.java,Rectangle.java and Circle.java

    1.Shape.java

    This is our root class of entity class hierarchy.
    Create Shape.java in src->org.arpit.javapostsforlearning.

    package org.arpit.javapostsforlearning;
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    import javax.persistence.Inheritance;
    import javax.persistence.InheritanceType;
    import javax.persistence.Table;
    
    
    @Entity
    @Table(name="SHAPE")
    @Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
    public class Shape {
    
     @Id
     @GeneratedValue(strategy = GenerationType.TABLE)
     @Column(name="Shape_Id")
     int shapeId;
     @Column(name="Shape_Name")
     String shapeName;
      
     public Shape()
     {
      
     }
     public Shape(String shapeName)
     {
      this.shapeName=shapeName;
     }
     //getters and setters
     
    }
    
    Shape is our root class so some annotations needs to be used with root class for implementing inheritance.

    @Inheritance:

    For implementing inheritance in hiberante,@Inheritance annotation is used.It defines inheritance strategy to be implement for entity class hierarchy.For one table per class hierarhcy,we have used Table_Per_Class as inheritance strategy.This annotation is defined at root level or sub hierarchy level where different strategy is to be applied.

    2.Rectangle.java

    This is our child class. Create Rectangle.java in src->org.arpit.javapostsforlearning.
    package org.arpit.javapostsforlearning;import javax.persistence.Column;
    import javax.persistence.Column;
    import javax.persistence.Entity;
    
    @Entity
    @Table(name="RECTANGLE")
    public class Rectangle extends Shape{
    
     @Column(name="Rectangle_Length")
     int length;
     @Column(name="Rectangle_Breadth")
     int breadth;
     // getters and setters
     
     public Rectangle()
     {
      
     }
     
     public Rectangle(String shapeName,int length,int breadth)
     {
      super(shapeName);
      this.length=length;
      this.breadth=breadth;
     }
     
     // getters and setters
    }
    

    3.Circle.java

    This is our second child class.
    Create Circle .java in src->org.arpit.javapostsforlearning.
    package org.arpit.javapostsforlearning;import javax.persistence.Column;import javax.persistence.Column;
    import javax.persistence.Entity;
    
    @Entity
    @Table(name="CIRCLE")
    public class Circle extends Shape{
    
     @Column(name="Circle_Radius")
     int radius;
     
     public Circle()
     {
      
     }
     public Circle(String shapeName,int radius)
     {
      super(shapeName);
      this.radius=radius;
      
     }
     // getters and setters
    }
    
    

    4.Hiberante.cfg.xml:

    Create a file named "hibernate.cfg.xml" in src folder.
    <?xml version='1.0' encoding='utf-8'?>
    <!DOCTYPE hibernate-configuration PUBLIC
            "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
            "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
    
    <hibernate-configuration>
    
        <session-factory>
    
            <!-- Database connection settings -->
            <property name="connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
            <property name="connection.url">jdbc:sqlserver://localhost:1433;database=UserInfo</property>
            <property name="connection.username">sa</property>
            <property name="connection.password"></property>
    
            <!-- JDBC connection pool (use the built-in) -->
            <property name="connection.pool_size">1</property>
    
            <!-- SQL dialect -->
            <property name="dialect">org.hibernate.dialect.SQLServer2005Dialect</property>
    
            <!-- Enable Hibernate's automatic session context management -->
            <property name="current_session_context_class">thread</property>
    
            <!-- Disable the second-level cache  -->
            <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
    
            <!-- Echo all executed SQL to stdout -->
            <property name="show_sql">true</property>
    
            <!-- Drop and re-create the database schema on startup -->
            <property name="hbm2ddl.auto">create</property>
    
      <mapping class="org.arpit.javapostsforlearning.Shape"></mapping>
      <mapping class="org.arpit.javapostsforlearning.Rectangle"></mapping>
      <mapping class="org.arpit.javapostsforlearning.Circle"></mapping>
    
        </session-factory>
    
    </hibernate-configuration>
    
    

    5.Main Class:

    package org.arpit.javapostsforlearning;
    
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.hibernate.cfg.Configuration;
    import org.hibernate.service.ServiceRegistry;
    import org.hibernate.service.ServiceRegistryBuilder;
    
    public class HibernateMain {
    
     public static void main(String[] args) {
      
      Shape shape=new Shape("Sqaure");
      Rectangle rectangle=new Rectangle("Rectangle", 10, 20);  
      Circle circle=new Circle("Circle", 4);
        
      Configuration configuration=new Configuration();
      configuration.configure();
      ServiceRegistry sr= new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
      SessionFactory sf=configuration.buildSessionFactory(sr);
      Session ss=sf.openSession();
      
      ss.beginTransaction();
      ss.save(shape);
      ss.save(rectangle);
      ss.save(circle);
      ss.getTransaction().commit();
      ss.close();
      
     }
    }

    Project Structure:

     

    6.Run it:

    When you run it,you will get following output.

    Hibernate: create table Circle (Shape_Id int not null, Shape_Name varchar(255), Circle_Radius int, primary key (Shape_Id))
    Hibernate: create table Rectangle (Shape_Id int not null, Shape_Name varchar(255), Rectangle_Breadth int, Rectangle_Length int, primary key (Shape_Id))
    Hibernate: create table SHAPE (Shape_Id int not null, Shape_Name varchar(255), primary key (Shape_Id))
    Hibernate: create table hibernate_sequences ( sequence_name varchar(255),  sequence_next_hi_value int ) 
    Feb 05, 2013 11:17:13 PM org.hibernate.tool.hbm2ddl.SchemaExport execute
    INFO: HHH000230: Schema export complete
    Hibernate: select sequence_next_hi_value from hibernate_sequences with (updlock, rowlock ) where sequence_name = 'SHAPE'
    Hibernate: insert into hibernate_sequences(sequence_name, sequence_next_hi_value) values('SHAPE', ?)
    Hibernate: update hibernate_sequences set sequence_next_hi_value = ? where sequence_next_hi_value = ? and sequence_name = 'SHAPE'
    Hibernate: insert into SHAPE (Shape_Name, Shape_Id) values (?, ?)
    Hibernate: insert into Rectangle (Shape_Name, Rectangle_Breadth, Rectangle_Length, Shape_Id) values (?, ?, ?, ?)
    Hibernate: insert into Circle (Shape_Name, Circle_Radius, Shape_Id) values (?, ?, ?)


    7.SQL output:

    SHAPE table in database.




    Rectangle table in database




    CIRCLE table in database





     

    Java tutorial for beginners Copyright © 2011 - |- Template created by O Pregador - |- Powered by Blogger Templates