Search This Blog

Friday, September 23, 2011

Java Socket DayTime Service

DayTimeServer.java

import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;


public class DayTimeServer
{

    ServerSocket serverSocket;
    Socket clientSocket;
    DataOutputStream dos;


    public DayTimeServer()
    {
        try
        {
            serverSocket = new ServerSocket(13);
            while(true)
            {
                System.out.print("Time Server Start....");
                clientSocket=serverSocket.accept();
                dos=new DataOutputStream(clientSocket.getOutputStream());
                Date date=new Date();
                dos.writeUTF(date.toString());
            }
           
        }
        catch (IOException ex)
        {
            Logger.getLogger(DayTimeServer.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    public static  void  main(String args[])
    {
        new DayTimeServer();
    }
}

DayTimeClient.java

import java.io.DataInputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class DayTimeClient
{
    Socket dtSocket;
    DataInputStream dis;

    public DayTimeClient()
    {
        try
        {
           
            dtSocket = new Socket("localhost", 13);
            dis=new DataInputStream(dtSocket.getInputStream());
            System.out.print("-: Day And Time :-\n"+dis.readUTF()+"\n");
        }
        catch (UnknownHostException ex) {
            Logger.getLogger(DayTimeClient.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(DayTimeClient.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    public static  void  main(String args[])
    {
        new DayTimeClient();
    }
}

How To Run :
Fisrst Start DayTimeServer.java
Second Start DayTimeClient.java

Sunday, September 11, 2011

Serialization In Java

What is Serialization?
 Serializable is a marker interface. When an object has to be transferred over a network ( typically through rmi or EJB) or persist the state of an object to a file, the object Class needs to implement Serializable interface. Implementing this interface will allow the object converted into bytestream and transfer over a network
 
What is the need of Serialization?
The serialization is used :-
  • To send state of one or more object’s state over the network through a socket.
  • To save the state of an object in a file.
  • An object’s state needs to be manipulated as a stream of bytes.

What is use of serialVersionUID ?
During object serialization, the default Java serialization mechanism writes the metadata about the object, which includes the class name, field names and types, and superclass. This class definition is stored as a part of the serialized object. This stored metadata enables the deserialization process to reconstitute the objects and map the stream data into the class attributes with the appropriate type Everytime an object is serialized the java serialization mechanism automatically computes a hash value. ObjectStreamClass's computeSerialVersionUID() method passes the class name, sorted member names, modifiers, and interfaces to the secure hash algorithm (SHA), which returns a hash value.The serialVersionUID is also called suid.
So when the serilaize object is retrieved , the JVM first evaluates the suid of the serialized class and compares the suid value with the one of the object. If the suid values match then the object is said to be compatible with the class and hence it is de-serialized. If not InvalidClassException exception is thrown.

Changes to a serializable class can be compatible or incompatible. Following is the list of changes which are compatible:
  • Add fields
  • Change a field from static to non-static
  • Change a field from transient to non-transient
  • Add classes to the object tree
List of incompatible changes:
  • Delete fields
  • Change class hierarchy
  • Change non-static to static
  • Change non-transient to transient
  • Change type of a primitive field
So, if no suid is present , inspite of making compatible changes, jvm generates new suid thus resulting in an exception if prior release version object is used .
The only way to get rid of the exception is to recompile and deploy the application again.

If we explicitly metion the suid using the statement:

private final static long serialVersionUID = <integer value>


then if any of the metioned compatible changes are made the class need not to be recompiled. But for incompatible changes there is no other way than to compile again.

Are the static variables saved as the part of serialization?
No. The static variables belong to the class and not to an object they are not the part of the state of the object so they are not saved as the part of serialized object.

What is a transient variable?
These variables are not included in the process of serialization and are not the part of the object’s serialized state.

step 1. Implement The java.io.Serializable Interface
DocumentBean .java
import java.util.Date;

public class DocumentBean implements java.io.Serializable
{
    String docTitle;
    String date;
    int noOfPage;
    String docSize;   
   
    public DocumentBean(String docTitle,String data,int noOfPage,String docSize)
    {
        // TODO Auto-generated constructor stub
        this.docTitle=docTitle;
        this.date=data;
        this.noOfPage=noOfPage;
        this.docSize=docSize;
       
    }
    public String getDocTitle() {
        return docTitle;
    }
    public void setDocTitle(String docTitle) {
        this.docTitle = docTitle;
    }
    public String getDate() {
        return date;
    }
    public void setDate(String date) {
        this.date = date;
    }
    public int getNoOfPage() {
        return noOfPage;
    }
    public void setNoOfPage(int noOfPage) {
        this.noOfPage = noOfPage;
    }
    public String getDocSize() {
        return docSize;
    }
    public void setDocSize(String docSize) {
        this.docSize = docSize;
    }   
}
step 2 : Serialize The Object using ObjectOutputStream SerializeDocument.java

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.Date;

public class SerializeDocument
{   
    public static void main(String[] args)
    {       
        Date dt=new Date();
        DocumentBean bean=new DocumentBean("Java The Complate Refereance",dt.toString(),5,"A4");
        try
        {
            FileOutputStream fos=new FileOutputStream("Doc.txt");
            ObjectOutputStream oos=new ObjectOutputStream(fos);
            oos.writeObject(bean);
            System.out.println("Complate...");
        }
        catch (FileNotFoundException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
step 3 : DeSerialize The Object using ObjectInputStream DeSerializeDocument.java

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;

public class DeSerializeDocument
{
    public static void main(String[] args)
    {
        try
        {
            FileInputStream fis=new FileInputStream("Doc.txt");
            ObjectInputStream ois=new ObjectInputStream(fis);
            DocumentBean bean=(DocumentBean)ois.readObject();
            System.out.println("Doc Titel :"+bean.getDocTitle());
            System.out.println("Doc Page :"+bean.getNoOfPage());
            System.out.println("Doc Size :"+bean.getDocSize());
            System.out.println("Doc Date :"+bean.getDate());           
           
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
       
    }
}