Saturday, February 26, 2011

About Me

Dear Friend, thanks for stopping by to know my details, please have a look :-)

This is Deepak kumar modi, living in Bangalore, Silicon city of India. I completed my B.E. in Information Technology in 2006 from
BIT Sindri, Jharkhand. It is a prestigious government engineering college running from 1949 onwards. I got fascinated with Java in
third year of my engineering career when I learnt Applet and AWT programming. Every time I see the UI output, I feel Wow!! I have done
something... like a normal Software developer's wish, but that time it was being felt like a technical expert.

The story starts here: In our third year of Engineering there was a part time lecturer in our college who spent almost 3/4th of our
3rd Year just by teaching Basics of java like: ClassPath Settings, If-else, Switch-case, Packages, Displaying so many star and binary patterns using
various loops in programming. At the end of the year, we got a new female faculty. She was having a sound technical knowledge of
Java. Basically she only taught us UI based programming and it was amazing to see such real things in AWT and Database first time.
So although we all were going to tease her, we were learning too.

And once moved to Bangalore, programming became a part of our life. After sometime I started writing a blog and share errors and experiences
I am facing while development. This is basically for my notes.

Now whenever I have some leisure time, I update my blog.
At last thanks for patiently reading this. Hope you will like my blog and follow this.

Tuesday, February 8, 2011

Serialization in Java

Serialization in Java

Dear reader,
I have discussed here below topics:
1) What is serialization and how it works?
2) Impact of SerialVersionUID in Java files and on serialization behaviour.
3) Impact of serialization and de-serialization on Super class and base classes.
4) How to make a class or package non-serializable as few of classes in Java like "Thread, 
   ServerSocket, Socket, DatagramSocket etc" can't be serialized. The reason these classes
   are tightly coupled with Native OS implementation.

Java serialization has been around since the Java version 1.1 days. Serialization is a key/mechanism
of persisting a Java object for future use, so this persistence can be stored in File or DB anything.
But the storage of Java object is only possible if you convert an object into bits/bytes. 

Hence Serialization is a mechanism to convert a Java object into bit/byte streams so that it can 
be stored in either storage media or sent via network to another machine. Then the recipient or reader 
need to De-Serialize the same bit/bytes pattern and get the actual object.

It is something like Sender is encrypting a Password string and sent over network and then Recipient 
decrypts the same string and fetches the actual value. 


Let’s create a basic class named NonSerializableClass. 
-----------------------
    package com.java.serialize;
    public class NonSerializableClass {
    }
-----------------------

Now let’s try to serialize it. Here’s the code to serialize NonSerializableClass.
-----------------------
import java.io.*;
public class NonSerializableTest {
    public static void main(String[] args) {
            NonSerializableClass nonSerializableObj = new NonSerializableClass();            
            try {
                ObjectOutputStream out=new ObjectOutputStream(new FileOutputStream("HoldSerial.txt"));                
                out.writeObject(nonSerializableObj);
                out.close();                
            }
            catch(Exception e) {
                e.printStackTrace();
            }
    }
}
-----------------------
On running the program we encounter the following exception.
    Not Serializable Class
    java.io.NotSerializableException: com.java.serialize.NonSerializableClass

Serialization rule number 1:
The first rule of serialization is Not all classes are serializable.
For a class to be serialized it should implement Serializable interface. 

Here’s an example of a Serializable class.
-----------------------
    public class SerializableClass implements Serializable {
       private static final long serialVersionUID = 123L;
       public SerializableClass() {
        System.out.println("Inside SerializableClass constructor");
       }
    }
-----------------------

Now let’s try to serialize this. Here’s the serialization code.
-----------------------
    public class SerializableTest {
        public static void main(String[] args) {
            SerializableClass serObj = new SerializableClass();
            try {
                File f = new File("C:\\obj.ser"); //File name can be any thing.
                f.createNewFile();
                System.out.println("Serializing Object");
                FileOutputStream out = new FileOutputStream(f); //Breaking one liner output stream into buffer.
                BufferedOutputStream buf = new BufferedOutputStream(out);
                ObjectOutputStream objOut = new ObjectOutputStream(buf);
                objOut.writeObject(serObj);
    
                objOut.close();
                buf.close();
                out.close();
                System.out.println("Serialization complete.");
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
-----------------------
Serialization works fine without throwing any exceptions. The output of the class run is
    Inside SerializableClass constructor
    Serializing Object
    Serialization complete.

Serialization rule number 2:
Only Classes implementing Serializable interface support serialization.
OK we were able to serialize the object, now let’s try to deserialize it. 

Here’s the source code...
-----------------------
    public class DeSerializeObjectTest {
        public static void main(String[] args) {
            try {
                File f = new File("C:\\obj.ser");     
                System.out.println("Deserializing Object");
                FileInputStream input = new FileInputStream(f);
                BufferedInputStream buf = new BufferedInputStream(input);
                ObjectInputStream objip = new ObjectInputStream(buf);
                Object obj = objip.readObject();
     
                SerializableClass ser = (SerializableClass)obj; 
                objip.close();
                buf.close();
                input.close();
     
                System.out.println("Deserialization complete.");
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
    }
-----------------------
The output is 
    Deserializing Object
    Deserialization complete.  //Note: Constructor didn't get invoked while deserializing.

So far so good, now let’s add an attribute to the class in question. 

Here’s the new source...
-----------------------
    public class SerializableWithParamClass implements Serializable {
        private static final long serialVersionUID = 137L;
        private String name = null;
        public SerializableWithParamClass() {
            System.out.println("Inside SerializableWithParamClass constructor.");
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
    }
-----------------------
Here’s the test class code...
    public class SerializableWithParamTest {
       public static void main(String[] args) {
             SerializableWithParamClass param = new SerializableWithParamClass();
             param.setName("Testing.......");
             System.out.println("Begining the serialization process.");
             File f = new File("C:\\paramObj.ser");
             try {   
                f.createNewFile();
                System.out.println("Serializing Object");
    
                FileOutputStream out = new FileOutputStream(f);
                BufferedOutputStream buf = new BufferedOutputStream(out);
                ObjectOutputStream objOut = new ObjectOutputStream(buf);
                objOut.writeObject(param);
     
                objOut.close();
                buf.close();
                out.close();
                System.out.println("Serialization complete.");
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println("Ending the serialization process.");
            System.out.println("Begining the deserialization process.");
            try {   
                System.out.println("Deserializing Object");
                BufferedInputStream buf = new BufferedInputStream(new FileInputStream(f));
                ObjectInputStream objip = new ObjectInputStream(buf);
                Object obj = objip.readObject();
     
                SerializableWithParamClass ser = (SerializableWithParamClass)obj;
                System.out.println("Name: " + ser.getName());
                objip.close();
                buf.close();                
                System.out.println("Deserialization complete.");
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            System.out.println("Ending the deserialization process.");
        }
    }
-----------------------
The output is as follows:
01    Inside SerializableWithParamClass constructor.
02    Begining the serialization process.
03    Serializing Object
04    Serialization complete.
05    Ending the serialization process.
06    Begining the deserialization process.
07    Deserializing Object
08    Name: Testing.......
09    Deserialization complete.
10    Ending the deserialization process.

I am sure you have noticed by now the attribute serialVersionUID. What’s the need for having this attribute? 
Whenever object is serialized Java stores the java major and minor version information. Along with this it 
also needs to store some kind of version information, something which says that I am version 1.0 of this class, 
on addition/deletion of an attribute or method it should say that I am version 2.0. The serialVersionUID 
serves this purpose. The developer can define a hard coded value as I have done or allow Java can produce 
the value at runtime which would be based on the evaluation of the class.

The reason to discuss: Suppose you have serialized your objects into a File and keep using after de-serialization.
       After 2 years, you have changed your original source code and added/deleted some methods, attributes etc
       and now serialized your objects again but keeping the older stored/serialized objects as it is with client. 
       Now if your old serialized objects need to de-serialize with new new code base, it won't work. 
       It will say java.io.InvalidClassException. I mean Version/SerialVersionUID is modified.

So what affects the value of serialVersionUID and what does not?
What affects SerialVersionUID change?
1.    Non-default Constructors
2.    Addition/Deletion of non-private static or instance methods as well as their access modifiers
3.    Addition/Deletion of static/instance attributes as well as their access modifiers
4.    The interfaces implemented by the class

What does not affect SerialVersionUID?
1.    Default Constructor
2.    Addition of private static or instance methods
3.    The class extended by the class to be serialized

One approach is to define a fixed value for serialVersionUID as I have done. The benefit is that if we 
have serialized an object and then added new attribute/method, as the serialVersionUID has not changed, 
the deserialization process is not hindered. Java force such old serialized objects to de-serialize 
using new source code if Version is same.

Let’s serialize an object of SerializableClass and then change the serialVersionUID from 123L to 124L
and then compile it.

Now on deserializing the old object we encounter the following exception:
1    Deserializing Object
2    java.io.InvalidClassException: com.java.serialize.SerializableClass; local class incompatible: 
stream classdesc serialVersionUID = 123, local class serialVersionUID = 124


Now let’s examine the impact of serialization on object hierarchy.
-------------------------     
    public class A {
       private String name = null;
       public A() {
           System.out.println("Inside A's constructor.");
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
    }
-------------------------     
    public class B extends A implements Serializable {
        private String detail = null;
        public B() {
            System.out.println("Inside B's constructor.");
        }
        public String getDetail() {
            return detail;
        }
        public void setDetail(String detail) {
           this.detail = detail;
        }
    }

Now let’s serialize and deserialize it. Here’s the code...
------------------------- 
    public class InheritTest {
        public static void main(String[] args) {
            B b = new B();
            b.setName("Test");
            b.setDetail("Test Details");
            System.out.println("Begining the serialization process.");
            File f = new File("C:\\inheritObj.ser");
            try {   
                f.createNewFile();
                System.out.println("Serializing Object");
     
                FileOutputStream out = new FileOutputStream(f);
                BufferedOutputStream buf = new BufferedOutputStream(out);
                ObjectOutputStream objOut = new ObjectOutputStream(buf);
                objOut.writeObject(b);
                objOut.close();
                buf.close();
                out.close();
                  System.out.println("Serialization complete.");
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println("Ending the serialization process.");
            System.out.println("Begining the deserialization process.");
            try {   
                System.out.println("Deserializing Object");
                FileInputStream input = new FileInputStream(f);
                BufferedInputStream buf = new BufferedInputStream(input);
                ObjectInputStream objip = new ObjectInputStream(buf);
                Object obj = objip.readObject();
     
                B bSer = (B)obj;
                System.out.println("Name: " + bSer.getName());
                System.out.println("Detail: " + bSer.getDetail());
                objip.close();
                buf.close();
                input.close();
                System.out.println("Deserialization complete.");
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            System.out.println("Ending the deserialization process.");
        }
    }
------------------------- 
The output generated is:
01    Inside A's constructor.
02    Inside B's constructor.
03    Begining the serialization process.
04    Serializing Object
05    Serialization complete.
06    Ending the serialization process.
07    Begining the deserialization process.
08    Deserializing Object
09    Inside A's constructor.
10    Name: null
11    Detail: Test Details
12    Deserialization complete.
13    Ending the deserialization process.

Note that during deserialization, the constructor of A is invoked and the attribute value of name is null.
Now let’s try two options. Make A implement Serializable and let B continue to implement Serializable. 
-------------------------     
    public class A implements Serializable{
        private String name = null;
        public A() {
            System.out.println("Inside A's constructor.");
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
    }
-------------------------     
    public class B extends A implements Serializable {
        private String detail = null;
        public B() {
            System.out.println("Inside B's constructor.");
        }
        public String getDetail() {
            return detail;
        }
        public void setDetail(String detail) {
            this.detail = detail;
        }
    }
-------------------------     
The output is 
01    Inside A's constructor.
02    Inside B's constructor.
03    Begining the serialization process.
04    Serializing Object
05    Serialization complete.
06    Ending the serialization process.
07    Begining the deserialization process.
08    Deserializing Object
09    Name: Test
10    Detail: Test Details
11    Deserialization complete.
12    Ending the deserialization process.

It is in line with our expectations. Super class constructor didn't invoke.
Now option two where A implements Serializable and B does not implement Serializable.
-------------------------     
    public class A implements Serializable{
        private String name = null;
        public A() {
            System.out.println("Inside A's constructor.");
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
    }
-------------------------     
    public class B extends A {
        private String detail = null;
        public B() {
            System.out.println("Inside B's constructor.");
        }
        public String getDetail() {
            return detail;
        }
        public void setDetail(String detail) {
            this.detail = detail;
        }
    }
-------------------------     
The output is
01    Inside A's constructor.
02    Inside B's constructor.
03    Begining the serialization process.
04    Serializing Object
05    Serialization complete.
06    Ending the serialization process.
07    Begining the deserialization process.
08    Deserializing Object
09    Name: Test
10    Detail: Test Details
11    Deserialization complete.
12    Ending the deserialization process.

The output remains unchanged. Super class constructor didn't invoke. 

Java Serialization rule no 3:
In Object hierarchy the root class needs to implement Serializable interface to ensure serializable 
of all attributes within the object hierarchy.
-------------------------

At Last I am discussing how to avoid making a class serializable. Note: If your super class
doesn't implement Serializable, it can't be serialized but if a sub-class implements, then the whole object
hierarchy can be serialized again.

To avoid this we need to re-define "writeObject() and readObject()" methods of ObjectOutputStream and 
ObjectInputStream. I am writing re-define because these methods are declared as final, so can't be overridden.

Below is the complete code:
--------------------
//Super class doesn't implement Serializable here but sub class does.
public class SuperClass {
    public SuperClass(){
        System.out.println("Super class constructor called");
    }
}
---------------
//Sub class
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class BaseClass extends SuperClass implements Serializable {
    public String name;
    public BaseClass(){
        System.out.println("Base class constructor called");
        name="Deepak modi";
    }
    public static void main(String[] args) throws IOException,ClassNotFoundException {
        BaseClass b=new BaseClass();
        ObjectOutputStream out=new ObjectOutputStream(new FileOutputStream("HoldSerial.txt"));
        out.writeObject(b);
        System.out.println("Base class object serialized/stored in a file");

        ObjectInputStream in=new ObjectInputStream(new FileInputStream("HoldSerial.txt"));
        BaseClass bIn=(BaseClass)in.readObject();
        System.out.println("Base class object de-serialized/read from file");
        System.out.println("Object: "+bIn);
        System.out.println("Object name value: "+bIn.name);
    }
    //Re-defining the method
    private void readObject(ObjectInputStream o) throws IOException, ClassNotFoundException {  
        System.out.println("These objects can't be de-serialized");
        throw new IOException("These objects can't be de-serialized");
    }  
    private void writeObject(ObjectOutputStream o) throws IOException {  
        System.out.println("These objects can't be serialized");
        throw new IOException("These objects can't be serialized");
    }     
    public String toString() {  
        return name;  
    }  
}

//Output when you run this main method:
Super class constructor called
Base class constructor called
These objects can't be serialized
Exception in thread "main" java.io.IOException: These objects can't be serialized
    at BaseClass.writeObject(BaseClass.java:33)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:585)
    at java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:917)
    at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1339)
    at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1290)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1079)
    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:302)
    at BaseClass.main(BaseClass.java:17)


//You uncomment the "readObject() and "writeObject()" and then see behavior:
I did that and here is the output:::::::::::

Super class constructor called
Base class constructor called
Base class object serialized/stored in a file
Super class constructor called
Base class object de-serialized/read from file
Object: Deepak modi
Object name value: Deepak modi

------------------------END-----------------------

Count of repeated entities in a List or Array

Reader, 
Writing a useful blog on how to find:
1) Count of repeated integers in a List. 
2) Count of repeated integers in an Array.
3) Missing element in an Array having some integers in a range, numbers are in random order.
4) Count of repeated entities (String, Double, Integer) in an Array.

Consider that I have a list of integers with the individual  values ranging from 0 to 9. The list size is large 
i.e. in thousands and these individual numbers keep repeating. 

I want an approach to determine the number of times an individual value is repeated in the list.
I have written two programs on this, please go as below:
===================================================
import java.util.ArrayList;
import java.util.List;
//commons-collections-3.2.1.jar
import org.apache.commons.collections.bag.HashBag;
public class HashBagCount {
    public static void main(String[] args) {
        List<Integer> values = new ArrayList<Integer>();
        values.add(1);
        values.add(1);
        values.add(1);
        values.add(12);
        values.add(3);
        values.add(12);
        values.add(1);
        values.add(3);
        values.add(12);
        values.add(3);
        values.add(3);

        HashBag bag = new HashBag();
        bag.addAll(values);   //Basically traversing the list

        int count = bag.getCount(1);
        System.out.println("Count 1 : "+count);

        count = bag.getCount(3);
        System.out.println("Count 13 : "+count);

        count = bag.getCount(12);
        System.out.println("Count 12 : "+count);
    }
}

//Output:
Count 1 : 4
Count 13 : 4
Count 12 : 3
===================================================
//Inside an Array, using Exclusive OR operator
import java.util.HashMap;
public class RepeatedElements {
    public static void main(String[] args) {
        int arr[]=new int[]{1,1,2,2,3,4,5,6,7,8,4,5,78,67,56,90,67,67};
        int count=0;
        HashMap map=new HashMap();

        for(int i=1;i<arr.length;i++){
            count=1;
            for(int j=0;j<i;j++){
                if((arr[i]^arr[j])==0) {
                    count++;
                    map.put(arr[i],count);
                    //System.out.println(arr[i]);
                }
            }    
        }
        System.out.println(map);
    }
}
//Output:
{2=2, 4=2, 67=3, 1=2, 5=2}
===================================================
public class FindMissingNumber {
    public static void main(String[] args) {
        int n=20;  //This is the size of array whose missing number to be found.
        //For below array it is 20.

        //Only 19 elements are available in below array.
        int arr[]=new int[]{1,2,4,3,7,6,5,8,9,10,0,12,15,14,13,18,16,17,19,20}; 
        int sumCurrArray=0;
        System.out.print("Array Elements: ");
        for(int i=0;i<arr.length;i++){
            System.out.print(arr[i]+" ");
            if(arr[i]==0)
                ;
            else
                sumCurrArray=sumCurrArray+arr[i];
        }
        System.out.println();

        int sum=(n*(n+1))/2;
        System.out.println("Sum of "+n+" elements: "+sum);
        System.out.println("Missing number: "+(sum-sumCurrArray));
    }
}
//Output:
Array Elements: 1 2 4 3 7 6 5 8 9 10 0 12 15 14 13 18 16 17 19 20 
Sum of 20 elements: 210
Missing number: 11
===================================================
Reader, Giving one more example below which works for all primitive data types. In fact it works for String 
array too. But just to remind: JVM maintains a Memory Pool for String variables. I mean to say, see the smaller
example below:
-----------------------------------
public class StringExample {
    public static void main(String[] args) {
        String s="a";
        String s1="a";
        String s2=new String("a");
        System.out.println(s==s1);   //Maintains a pool
        System.out.println(s==s2);   //No pool here.
        
    }
}
//Output
true
false
-----------------------------------
And hence the below example works fine for String array too but array should have Strings put 
into DOUBLE QUOTE like "deepak" and "deepak", not like "deepak" and new String("deepak"), please see below 
example:

public class RepeatedElementsDouble {
    public static void main(String[] args) {
        //double array[]=new double []{2,3,4,5,5.1,4.0,90,4.0,5.0,5.1,3.002,3.0};
        String array[]=new String []{"2","deepak","rajesh","deepak","5.1","2","90","90"};   //This is OK as per this Example.
        //String array[]=new String []{"2","deepak","rajesh",new String("deepak"),"5.1","2","90","90"}; //This is not OK.
        //int[] array = {1, 3, 5, 6, 2, 3, 6, 4, 3, 2, 1, 6, 3, 3, 6, 4, 8, 9, 0};

        boolean[] check = new boolean[array.length];  //By default all are false

        for(int i = 0; i < array.length; i++) {
            if(check[i])
                continue;
            int count = 0;

            for(int j = i; j < array.length; j++) {
                if(check[j])
                    continue;
            
                if(array[j] == array[i]) {
                    check[j] = true;
                    count++;
                }
            }
            System.out.println("\""+array[i] + "\" is present: " + count + " time.");
        }
    }
}
//Output:
"2" is present: 2 time.
"deepak" is present: 2 time.
"rajesh" is present: 1 time.
"5.1" is present: 1 time.
"90" is present: 2 time.

========================END===========================

Difference between JDBC and Hibernate

Difference between JDBC and Hibernate:

Dear reader,
This is a different type of blogs. Here you won't find usual answers for differences.
Let's see JDBC and HIBERNATE: in both cases developers have to write Database codes, the difference is 
only file types. In both cases expertise is needed if you write complex queries. But still there are
some major differences, I will put here:

1) In JDBC, Queries are database dependent. In Hibernate, queries are independent of underlying database.
Here we have vaious SQLDialects for each type of Databases. So JDBC supports only native Structured Query Language (SQL).
But Hibernate uses a powerful query language Hibernate Query Language (independent from type of database) that 
is expressed in a familiar SQL like syntax and includes full support for polymorphic queries. So You don't need to 
change the SQL scripts if you change databases.

2) With JDBC, it is developer’s responsibility to handle JDBC result set and convert it to Java objects through code 
to use this persistent data in application. So with JDBC, mapping between Java objects and database tables is done manually.  
Hibernate reduces lines of code by maintaining object-table mapping itself and returns result to application in form of Java 
objects. It relieves programmer from manual handling of persistent data, hence reducing the development time and maintenance cost.

3) With JDBC, caching is maintained by manual coding. Hibernate provides Caching as application frameworks.
Hibernate also provides features like Attaching/Detaching of objects, so that later you can merge it to Database.
Hibernate caches data at Level 1 and supports optional Level2 caching through third party software (ehcache,
TreeCache/JBoss cache etc.). So Caching is totally external to JDBC.


4) Concurrency is handled manually in JDBC, in JDBC there is no check about the data which is already updated.
This check has to be added by the developer. In Hibernate, we have locking systems. Hibernate enables developer 
to define version type field into application, due to this Hibernate updates version field of table every time 
relational tuple is updated in form of Java object to that table. So if two users retrieve same tuple and then 
modify it and one user saves this modified tuple to database, version is automatically updated for this tuple 
by Hibernate. When other user tries to save updated tuple to database then it does not allow saving it because 
this user does not have updated data. This is achieved by Optimistic-lock.

5) Under the hood, Hibernate uses JDBC only. However developers have DAOs and POJOs to use
any where in application because of hibernate while writing business logics. So it is very easy to make a 
cleaner seperation of Data Access Layer from Business logic layer.

6) Hibernate supports "Lazy loading" of objects which JDBC doesn't support. This feature enable us to get only 
the required object instead of fetching all the entities associated with that. It fetches them only on request
by specifying the join in the queries.

7) Get Dynamic_insert and Dynamic_Update by specifying attribute <class name="P" table="PN" 
dynamic-update="true" dynamic-insert="true"> in *.hbm.xml file so that only few columns gets updated instead of
whole table each time you update a record in DB. So Causing enhanced performance in Hibernate.

8) Hibernate has an extremely good attribute "mutable", by default it is true. If you make a class as "Immutable" means
"mutable=false", then– insert=allowed, delete=allowed, update=not allowed.

--------------------------------End--------------------------------------

Friday, February 4, 2011

Java code to know the compiler version used while generating a Class file

Dear Reader,

I am writing a complete code to figure out what bytecode version a given class was compiled with. Please read carefully, this is a tested code.

Every '.class' file starts of with the following:

* Magic Number [4 bytes]
* Version Information [4 bytes]

A hexdump of a '.class' file reveals:

1.1 ==> CA FE BA BE 00 03 00 2D   (Decimal Value means Major Version: 45)
1.2 ==> CA FE BA BE 00 00 00 2E   (Decimal Value means Major Version: 46)
1.3 ==> CA FE BA BE 00 00 00 2F   (Decimal Value means Major Version: 47)
1.4 ==> CA FE BA BE 00 00 00 30   (Decimal Value means Major Version: 48)
1.5 ==> CA FE BA BE 00 00 00 31   (Decimal Value means Major Version: 49)
1.6 ==> CA FE BA BE 00 00 00 32   (Decimal Value means Major Version: 50)

/*
major      minor       Java platform version
45         3           1.0
45         3           1.1
46         0           1.2
47         0           1.3
48         0           1.4
49         0           1.5
50         0           1.6
*/

STEPS to see:
1) I have Java installed Version-1.5.
2) I will compile a simple java code using Source 1.2 and create a target file for version 1.2. Remember, You can compile using 
any version of Source code, but "target" tag says that your bytecode is ready for that JVM version, in this case 1.2.
3) Run the code to see whether it is compiled successfully to generate the output, however this step is not mandatory.
4) Check or verify what we want to do actually (getting version no of byte code compiled with).

//Java code
//Deepak.java
public class Deepak {
public static void main(String ar[]){
System.out.println("Deepak K. Modi, Expert in java programming");
}
}

//Use command prompt to compile and generate class file (Make sure JAVA_HOME and PATH is set to run java commands).
C:\DOCUME~1\dmodi>  javac -source 1.2 -target 1.2 Deepak.java

C:\DOCUME~1\dmodi>  java Deepak
Deepak K. Modi, Expert in java programming

After getting output, now you have to run "javap" command to see the version no of compiler using that this 
class file "Deepak.class" got generated.

C:\DOCUME~1\dmodi>  javap -verbose Deepak
Compiled from "Deepak.java"
public class Deepak extends java.lang.Object
SourceFile: "Deepak.java"
minor version: 0
major version: 46
Constant pool:
const #1 = Method       #6.#15; //  java/lang/Object."<init>":()V
-----some other contents-------
-----some other contents-------


//That's all, you got the output, see the "Major version" and "Minor Version" displayed above and 
compare with the Table given above in the blog for Java Platform Version.



//Testing again using 1.5 version:

C:\DOCUME~1\dmodi>  javac -source 1.5 -target 1.5 Deepak.java

C:\DOCUME~1\dmodi>  java Deepak
Deepak K. Modi, Expert in java programming

C:\DOCUME~1\dmodi>  javap -verbose Deepak
Compiled from "Deepak.java"
public class Deepak extends java.lang.Object
SourceFile: "Deepak.java"
minor version: 0
major version: 49
Constant pool:
const #1 = Method       #6.#15; //  java/lang/Object."<init>":()V
-----some other contents-------
-----some other contents-------


--------------------------------------END-------------------------------------

Thursday, February 3, 2011

Java code: How to crop images and compare them

Java code: How to crop images and compare them

Dear Reader,
I have written a complete code to crop images and compare them for identity. Basically such type of application is
used in Security scenarios where Image verification/matching is involved. Ex: Finger Print matching, Palm reader matching in 
companies where we have security system installed.

These APIs are fully functional and I have tested in my system.
There are two Java classes:

1) CropImageFile.java  (For Cropping the Source Image and generating Duplicate image).
2) CompareImageFiles.java (For Verifying the Source Image and Duplicate image).

Please go through the codes carefully, I have clearly written the File Paths, where it is getting stored and 
manually moved in other directory for matching purpose. You can tweak the code to suit your purpose.

Steps to work in Security System:
1) First Save Finger Print or Palm images of Authentic employees in a Authentic directory/Folder.

2) Crop them using our tool, as We need a portion of the images only. Full image is not necessary. Assume
a size of 400*200 dimension.

3) Verification step: Let a Stranger put his Finger/Palm at device and crop the recorded image. 
Use our tool to verify the image from files that are stored in the Authentic Directory (where we have stored 
authentic images). You can use a loop to compare with all the files. I have given code for only one file match.

Codes:
//CropImageFile.java
import java.awt.image.BufferedImage;
import java.io.*;

import javax.imageio.ImageIO;
public class CropImageFile {
public static void main(String[] args) {
cropImage();
}
public static void cropImage() {
byte[] bytesOut = null;
try {
int x1 = 0, y1 = 0, cw = 0, ch = 0;
String str[] = new String[]{"10","10","400","200"};

x1 = str[0].equals("") ? 50 : Integer.parseInt(str[0]);
y1 = str[1].equals("") ? 50 : Integer.parseInt(str[1]);
cw = str[2].equals("") ? 50 : Integer.parseInt(str[2]);
ch = str[3].equals("") ? 50 : Integer.parseInt(str[3]);

String oldFileName="D:\\Ears\\Old_Another_File.JPG";
FileInputStream oldFile = new FileInputStream(oldFileName);

File newFile = new File("D:\\Ears\\New_Another_File.JPG");
FileOutputStream fout = new FileOutputStream(newFile);

BufferedImage bimage = ImageIO.read(oldFile);
BufferedImage bi = null;
bi = bimage.getSubimage(x1, y1, cw, ch);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
String format = oldFileName.substring(oldFileName.lastIndexOf(".") + 1);
if (bi != null) {
ImageIO.write(bi, format, baos);
}
bytesOut = baos.toByteArray();
fout.write(bytesOut);
System.out.println("New file with cropped dimension is created.");
fout.close();
}
catch(Exception exp){
exp.printStackTrace();
}
}
}


//CompareImageFiles.java
import java.io.*;
import java.util.Arrays;

public class CompareImageFiles {
private static int BUFFSIZE=2000;
private static byte buff1[]=new byte[2000];
private static byte buff2[]=new byte[2000];

public static void main(String[] args) throws Exception {
String fileName1="D:\\Ears\\To_Compare\\New1.png";
String fileName2 = "D:\\Ears\\To_Compare\\New2.png";
String fileName3 = "D:\\Ears\\To_Compare\\New3.png";

System.out.println("Comparison result of both files : "+fileContentsEquals(fileName1,fileName2));
System.out.println("Comparison result of both files : "+fileContentsEquals(fileName1,fileName3));

fileName1="D:\\Ears\\To_Compare\\New_Another_File1.JPG";
fileName2 = "D:\\Ears\\To_Compare\\New_Another_File2.JPG";
fileName3 = "D:\\Ears\\To_Compare\\New_Another_File3.JPG";
System.out.println("Comparison result of both files : "+fileContentsEquals(fileName1,fileName2));
System.out.println("Comparison result of both files : "+fileContentsEquals(fileName2,fileName3));

}

public static boolean inputStreamEquals(InputStream is1, InputStream is2) {
if(is1 == is2) return true;
if(is1 == null && is2 == null) {
return true;
}
if(is1 == null || is2 == null) {
return false;
}
try {
int read1 = -1;
int read2 = -1;
do {
int offset1 = 0;
while (offset1 < BUFFSIZE && (read1 = is1.read(buff1, offset1, BUFFSIZE-offset1)) >= 0) {
offset1 += read1;
}

int offset2 = 0;
while (offset2 < BUFFSIZE && (read2 = is2.read(buff2, offset2, BUFFSIZE-offset2)) >= 0) {
offset2 += read2;
}
if(offset1 != offset2) {
return false;
}
if(offset1 != BUFFSIZE) {
Arrays.fill(buff1, offset1, BUFFSIZE, (byte)0);
Arrays.fill(buff2, offset2, BUFFSIZE, (byte)0);
}
if(!Arrays.equals(buff1, buff2)){
return false;
}
} while(read1 >= 0 && read2 >= 0);
if(read1 < 0 && read2 < 0) return true;    // both at EOF
return false;

} catch (Exception ei) {
return false;
}
}

public static boolean fileContentsEquals(File file1, File file2) {
InputStream is1 = null;
InputStream is2 = null;
if(file1.length() != file2.length())  {
System.out.println("Either of the file is not available or size differs");
return false;
}
try {
is1 = new FileInputStream(file1);
is2 = new FileInputStream(file2);
return inputStreamEquals(is1, is2);

} catch (Exception ei) {
return false;
} finally {
try {
if(is1 != null) is1.close();
if(is2 != null) is2.close();
} catch (Exception ei2) {}
}
}

public static boolean fileContentsEquals(String fn1, String fn2) {
return fileContentsEquals(new File(fn1), new File(fn2));
}
}

//Both classes have separate main methods, can be used individually also.