Tuesday, November 12

Java Serialization and Deserialization

Introduction: Serialization is the process of converting an object into a stream of bytes in order to store the object or transmit it to memory, a database, or a file.The reverse process of creating object from binary stream is called deserialization. A Java object is serializable if its class or any of its superclasses implements either the java.io.Serializable interface or its subinterface, java.io.Externalizable.

Serialization classes:

OutputStream : we’ll use FileOutputStream to write data to a file.
ObjectOutputStream : writes primitive data types and graphs of Java objects to an OutputStream.
 WriteObject() Method : it writes an object to the stream.

Deserialization classes:

InputStream : We’ll use FileInputStream as source stream.
ObjectInputStream: It reads from inputStream.
ReadObject() Method:  It reads raw bytes and convert to an object.

In this sample I’ll use a person class and an address class. The person class holds the reference of an address class. We will serialize the data and store it in c:\ project\ folder as tst.ser file. To deserialize the data we will create an instance of FileInputStream class that takes this tst.ser file as source.

Code:

import java.io.Serializable;

public class person implements Serializable {

            String fname;
            String lname;
            int age;
            address addr; //reference class
           
            public person()
            {}
           
            public person(String fn,String ln,int age,address a)
            {
                        this.fname=fn;
                        this.lname=ln;
                        this.age=age;
                        this.addr=a;
            }
           
            public String getFName() {return fname;}
            public String getLName() {return lname;}
            public int getAge() {return age;}
            public address getAddress() { return addr;}
           
            public String setFName(String fn) { return fname=fn;}
            public String setLName(String ln) { return lname=ln;}
            public int setAge(int a) { return age=a;}
            public address setAddress(address adr){return addr=adr;}
           
}
import java.io.Serializable;

public class address implements Serializable{
           
            String str;
            String city;
            String state;
            String zip;
           
            public address(){};
            public address(String a,String c,String s,String z)
            {
                        super();
                        this.str=a;this.city=c;this.state=s;this.zip=z;
            }
   
            public String getStreet(){return str;}
            public String getCity() {return city;}
            public String getState() {return state;}
            public String getZip(){return zip;}
           
            public String setStr(String st){return str=st;}
            public String setCity(String ct){return city=ct;}
            public String setSttae(String st){return state=st;}
            public String setZip(String zp){return zip=zp;}
           
           
}
import java.io.*;

public class serializeDeserailize {
           
            public static void main(String[] args)
            {
                        //create a person instance
                        person p=new person();
                        p.setFName("Adam");
                        p.setLName("Smith");
                        p.setAge(20);
                        //create an address instance
                        address a=new address();
                        a.setStr("Lake Shore Drive");
                        a.setCity("Chicago");
                a.setSttae("IL");
                        a.setZip("65987");
                        p.setAddress(a);
                       
           
                        //Serialize person object
                        try {
                                    FileOutputStream fos=new FileOutputStream("c:/project/tst.ser");
                                    ObjectOutputStream obj=new ObjectOutputStream (fos);
                                    obj.writeObject(p);
                                    obj.close();
                                    fos.close();
                                   
                                   
                           }catch (Exception e)
                        {
                                    e.printStackTrace();
                        }
                       
                        // Deserialize
                       
                        p=null;
                        try {
                                   
                                    InputStream fin=new FileInputStream("c:/project/tst.ser");
                                    ObjectInputStream in=new ObjectInputStream(fin);
                                    p=(person) in.readObject(); //cast to person object
                                    in.close();
                                    fin.close();
                       
                        }catch (Exception ex)
                        {
                                    ex.printStackTrace();
                        }
                       
                        System.out.println("After Deserialization:" );
                        System.out.println("First Name:" + p.getFName());
                        System.out.println("Last Name:" + p.getLName());
                        System.out.println(("Age:" + p.getAge()));
                        System.out.println("Address:" + p.getAddress().getStreet() + " " +  p.getAddress().getCity() + "," +  p.getAddress().getState() + "-" +  p.getAddress().getZip());
                       
            }

            }

Output:
First Name:Adam
Last Name:Smith
Age:20

Address:Lake Shore Drive Chicago,IL-65987

Monday, November 11

Java and MS SQL Server with JDBC Connection

We will need to add a jar file to our project library as SQL Server Driver for JDBC Service. The jar file is called “sqljdbc4.jar”.  This jar file can be downloaded from the following link:

The java.sql package contains API that performs all JDBC operations such as create and execute sql queries. The following are the important classes of java.sql package :

 Make Connection to database:

java.sql.DriverManager class makes connection with a driver.
Java.sql.Driver interface: provides API for registering and connecting drivers based on JDBC technology.

Send SQl statement to database:

Java.sql.Statement: send basic sql statement
Java.sql.Connection interface -- provides methods for creating statements and managing connections and their properties.

Retieve and Update Data:

Java.sql.Resultset Interface – provide access the result row by row.

There are two different authentication mode to connect to SQL server.


Windows Authentication Mode:
The first step is to setup ODBC. Start- Control panel -> Administrative tools -> ODBC -> add  select  “sql server” under name column. It will bring “create a new data source to Sql Server” window. Enter name , description and select the server from drop down box you like to connect. Click “next” and select “with windows NT authentication using the network login id” option and make sure to check “connect to Sql server to obtain default settings for the addition configuration options”. Click “next” and select the “change the default database to” option and select database from drop down box. Click “next” and then click “finish”. It will show “ODBC Microsoft SQL Server set up” window with server name, database name. Click “Test Data source” and it will show test result completed successfully.
Now the ODBC connection is completed. We’ll point to the Database connection string as jdbc:odbc:dsn name.

Code sample:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;


public class sqlconn {

           
            public static void main(String[] args)
            {
                         String DriverName="com.microsoft.sqlserver.jdbc.SQLServerDriver";
                         String connectionString="jdbc:odbc:mydb;
       
                         Connection con = null;
                         Statement query = null;
                    ResultSet rs = null;


                  try {
                        //dynamically load driver’s class file into memory                     
                          Class.forName(DriverName);
                    
                            // establish a connection
                          con=DriverManager.getConnection(connectionString);
                     
                      // Create and execute an SQL statement that returns some data.
                      String SQL = "SELECT TOP 10 * FROM Diagnosis";
                      query = con.createStatement();
                      rs = query.executeQuery(SQL);

                      // Iterate through the data in the result set and display it.
                      while (rs.next()) {
                         System.out.println("Diagnosis:" + rs.getString(4) + " " +         "DxCode:" + rs.getString(5));
                      }
                 
            } catch(ClassNotFoundException e) {
                        e.printStackTrace();
            } catch (Exception e) {
                          e.printStackTrace();
                       }
                      // close connection

                       finally {
                          if (rs != null) try { rs.close(); } catch(Exception e) {}
                          if (query != null) try { query.close(); } catch(Exception e) {}
                          if (con != null) try { con.close(); } catch(Exception e) {}
                       }
                    }
                 }

Output:
Diagnosis:CHOLERA DUE TO VIBRIO CHOLERAE DxCode:001.0
Diagnosis:CHOLERA DUE TO VIBRIO CHOLERAE EL TOR DxCode:001.1
Diagnosis:CHOLERA, UNSPECIFIED DxCode:001.9
Diagnosis:TYPHOID AND PARATYPHOID FEVERS DxCode:002
Diagnosis:TYPHOID FEVER DxCode:002.0
Diagnosis:PARATYPHOID FEVER A DxCode:002.1
Diagnosis:PARATYPHOID FEVER B DxCode:002.2

(2)Sql server Authentication Mode: We need to provide User credentials to connection string.
Just change the connection string as the following sample:
String connectionString="jdbc:sqlserver://yourSqlServerName;user=youruserid;password=yourpasswordpassword;databasename=yourdatabasename”;