Saturday, September 29, 2012

Comparator Example


When will you use Comparator and Comparable interfaces?
-java.util.Comparator and java.lang.Comparable
java.util.Comparator compares some other class’s instances, while java.lang.Comparable compares itself with another object.

Comparator vs Comparable in Java

Here are some of the common differences, which is worth remembering to answer this question if asked during a telephonic or face to face interview:

1) Comparator in Java is defined in java.util package while Comparable interface in Java is defined in java.lang package, which very much says that Comparator should be used as an utility to sort objects which Comparable should be provided by default.

2) Comparator interface in Java has method public int compare (Object o1, Object o2) which returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second. While Comparable interface has method public int compareTo(Object o) which returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.

3) If you see then logical difference between these two is Comparator in Java compare two objects provided to him, while Comparable interface compares "this" reference with the object specified.

4) Comparable in Java is used to implement natural ordering of object. In Java API String, Date and wrapper classes implements Comparable interface.Its always good practice to override compareTo() for value objects.

5) If any class implement Comparable interface in Java then collection of that object either List or Array can be sorted automatically by using Collections.sort() or Arrays.sort() method and object will be sorted based on there natural order defined by CompareTo method.

6)Objects which implement Comparable in Java can be used as keys in a SortedMap like TreeMap or elements in a SortedSet for example TreeSet, without specifying any Comparator.

public class Person implements Comparable {
    private int person_id;
    private String name;
   
    /**
     * Compare current person with specified person
     * return zero if person_id for both person is same
     * return negative if current person_id is less than specified one
     * return positive if specified person_id is greater than specified one
     */
    @Override
    public int compareTo(Object o) {
        Person p = (Person) o;
        return this.person_id - o.person_id ;
    }
    ….
}


/**
 * Comparator implementation which sorts Person objects on person_id field
 */
public class SortByPerson_ID implements Comparator{

    public int compare(Object o1, Object o2) {
        Person p1 = (Person) o;
        Person p2 = (Person) o;
        return p1.getPersonId() - p2.getPersonId();
    }
}


Use Collection.sort to sort custom class and user defined comparator

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.ListIterator;

@SuppressWarnings("rawtypes")
class employee implements Comparable {
    private String name;
    private Double salary;
   
    public employee(String name, Double salary) {
        super();
        this.name = name;
        this.salary = salary;
    }

    public String getName() {
        return name;
    }

    public Double getSalary() {
        return salary;
    }

    public String toString(){
        return "Name = "+getName()+", Salary = "+getSalary();
    }

    @Override
    public int compareTo(Object o) {
        if(!(o instanceof employee))
            throw new ClassCastException();
       
        employee e = (employee)o;
        return name.compareTo(e.getName());
    }
   
    static class SalaryComparator implements Comparator {
        @Override
        public int compare(Object o1, Object o2) {
            if(! (o1 instanceof employee) || !(o2 instanceof employee))
                throw new ClassCastException();
           
            employee e1 = (employee) o1;
            employee e2 = (employee) o2;
            return (int) (e1.getSalary() - e2.getSalary());
        }       
    }     
}

public class collectionUtil {

    /**
     * @param args
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static void main(String[] args) {
        String[] names = { "A", "E", "C", "B", "D" };
        Double[] salaries = { 2.0, 5.0, 6.0, 4.0, 3.0 };
       
        List l = new ArrayList();

        for (int i=0; i < names.length; i++)
            l.add(new employee(names[i], salaries[i]));
       
        Collections.sort(l);
        ListIterator litre = l.listIterator();
        while (litre.hasNext()) {
            //Object object = (//Object) litre.next();
            System.out.println(litre.next());
        }
       
        System.out.println("============================");
       
        Collections.sort(l, new employee.SalaryComparator());
        litre = l.listIterator();
        while (litre.hasNext()) {
            //Object object = (//Object) litre.next();
            System.out.println(litre.next());
        }
       
    }

}

Static Block

If you need to do computation in order to initialize your static variable, you can declare a static block which gets executed exactly once, when the class is first loaded.

Following example shows a class that has static method, some static variable and static initialization,

class useStatic {
  static int a=3;
  static int b;

  static void sMethod(int x){
    System.out.println ("x = "+x);
    System.out.println ("a = "+a);
    System.out.println ("b = "+b);
  }

  static {
     System.out.println (" static block initialized");
     b = a * 4;
  }

  public static void main(String arg[]){
   sMethod(42);
  }

As soon as the useStatic class is loaded, all the static statement are executed. First a is set to 3, then the static block executes (printing a message), and finally b is initalized to a*4 or 12. The main is call,  which calls sMethod() , passing 42 to x so the output is x= 42,a = 3, b = 12.  

the o/p is look's like :

static block initialized
x = 42
a = 3
b = 12

Hope this example helps you to understand static .....

Thursday, September 27, 2012

Hibernate general flow

Hibernate is a pure Java object-relational mapping (ORM) and persistence framework that allows you to map plain old Java objects to relational database tables using (XML/annotation) configuration files.

Hibernat general flow

Wednesday, September 26, 2012

What is static ?

Static means one per Class, not one for each object.

Static means one per Class, not one for each object no matter how many instance of a class might exist, this means that you can use them without creating an instance of a class. 
Static method are implicitly final, because overriding is done based on the type of a class and are attached to a class, not on object.  static method in a super class can be shadowed by another static method in a sub class, as long as the original method was not declared final. However, you can't override a static method with a non static method. 
In other words, you can't change a static method into an instance method in a class.

What is Static Import?
In order to access static members, it is necessary to qualify references with the class they came from. For example, one must say: double r = Math.cos(Math.PI * theta); or System.out.println("Blah blah blah"); You may want to avoid unnecessary use of static class members like Math. and System. For this use static import. For example above code when changed using static import is changed to:
import static java.lang.System.out;
import static java.lang.Math.PI;
import static java.lang.Math.cos;
...
double r = cos(PI * theta);
out.println("Blah blah blah");
...

So whats the advantage of using above technique? 1) readability of the code. 2) Instead of writing name of static class, directly write the method or member variable name. NOTE: Ambiguous static import is not allowed. i.e. if you have imported java.lang.System.out and you want to import mypackage.Someclass.out, the compiler will throw an error. Thus you can import only one member out.

serialization in java

What is the purpose of serialization in java?

Serialization is a conversion of an object to a series of byte, so that the object can be easily saved to persistent storage or streamed across a communication link, The byte stream can then be deserialized - converted into a replica of an original object.


Transient : If any variable is defined by using keyword “transient”, then object will not serialize that variable. During deserialization default value of that datatype will be set.
Static : as static variables are class level variables, so it is not serialzed as the object state.

We can do the Serialization process by implementing Serializable interface.

class SerialDemo implements java.io.Serializable

The above step tells the compiler that you are going to implement serialization.
Which basically means that the object is going to be saved or persisted.

use FileOutputStream class and ObjectOutputStream class.

FileOutuptStream Creates an output file stream to write to the file with the specified name. A new FileDescriptor object is created to represent this file connection.

An ObjectOutputStream writes primitive data types and graphs of Java objects to an OutputStream. The objects can be write using an ObjectOutputStream.

Save the file using

writeObject(obj);


Program for Serialization


What if you have something top secret, like your password which should not be saved. You mark it as transient!

transient int i;


Create a class Employee to collect information.

package com.javabynataraj.iopack;

class Employee implements java.io.Serializable {
 
 public String name;
 public String address;
 public transient int SSN;
 public int number;

 public void mailCheck() {
    System.out.println("Mailing a check to " + name + " " + address);
  }
}


then create a main class to persist the Employee details in a file.

package com.javabynataraj.iopack;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

public class Serial {
 public static void main(String[] args) {
  Employee e = new Employee();
  e.name = "Muralidhar";
  e.address = "JavabynataraJ,SatyaTechnologies";
  e.SSN = 11111;
  e.number = 101;
  try {
   System.out.println("Before Serialization");
   FileOutputStream fileOut = new FileOutputStream("employee.ser");
   ObjectOutputStream out = new ObjectOutputStream(fileOut);
   out.writeObject(e);
   out.close();
   fileOut.close();
   System.out.println("End of Serialization");
  } catch (IOException i){
   i.printStackTrace();
  }
 }
}

Deserialization is a process of converting the data from files or database converting to Stream of bytes using class Objects.

The Deserialization can be done after serializing the data only.Then we can read the data from the serialized files.

Convert your Serialized file into file form.


File fromFile = new File("Emp.ser");




By using the below two classes we can do the process of deserialization.

#1. FileInputStream
#2. ObjectInputStream

A FileInputStream obtains input bytes from a file in a file system. What files are available depends on the host environment.


FileInputStream fis = new FileInputStream(fromFile);



An ObjectInputStream deserializes primitive data and objects previously written using an ObjectOutputStream. This can be Converts the Serialized file into the Object form.


ObjectInputStream ois = new ObjectInputStream(fis);



To get the object of a serialized file we have to typecast into our class Employee to read the values in a file using variable names.


Employee emp = (Employee) ois.readObject();



After that close all the object connections.

You should write the  Employee class already written in Serialization.(check it there)

Program for Deserialization:


package javabynataraj.iopack;

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

public class Deserial {
    public static void main(String arg[]) {
        File fromFile = new File("Emp.ser");
        try {
            FileInputStream fis = new FileInputStream(fromFile);
            ObjectInputStream ois = new ObjectInputStream(fis);
            Employee emp = (Employee) ois.readObject();
            System.out.println("Deserialized data: \n"+ emp.eno + " "+ emp.ename +" "+ emp.esal+" "+emp.eaddr+ "  from Emp.ser");
            ois.close();
        } catch(IOException e) {
            System.out.println("Deserialization failed");
            System.out.println(e);
            System.exit(1);
        } catch(ClassNotFoundException e) {
            System.out.println("Deserialization failed");
            System.out.println(e);
            System.exit(1);
        }
    }
}

Referance: shivasoft.in and  javabynataraj.blogspot.in

Ajax call with Strut2

Ajax Call with Strut2
//----- Write in JavaScript---------------------
function findAppointment(strValue) {

 if (typeof XMLHttpRequest != "undefined") {
  xmlHttp = new XMLHttpRequest();
 } else if (window.ActiveXObject) {
  xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
 }

 if (xmlHttp == null) {
  alert("Browser is campatible ...tht must IE");
 }

 var id = strValue.value;
 var url = "getDetailsAjax"; // URL
 url += "?id=" + id;  // Parameters

 xmlHttp.onreadystatechange = getDts; // get response method
 xmlHttp.open("POST", url, true);
 xmlHttp.send(null);
}

// here you will get the response of your ajax call 
function getDts () {
 if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete") {
  var data = xmlHttp.responseText;
  alert(data);
 }
}


<!—Ajax Struts Configuration Call  -->      
<action name="*Ajax" class="com.ajax.DetailsAction" method="{1}">
 <result type="stream">    
  <param name="inputName">inputeStream</param>
 </result>
</action>

// Action method of DetailsAction
public String getDetailsAjax () throws Exception{
 String ajaxString = new String()
 try {  
  ajaxString += “sandeep”;
  inputeStream = new StringBufferInputStream(ajaxString);
  inputeStream.reset();
 } catch (Exception e) {
  e.printStackTrace();   
 }
 return SUCCESS;
}


Some Nice Oracle Queries

 
To fetch Duplicate Rows

 Select * from emp 
   where rowid notin (select max(rowid) from emp group by empno);
 
Delete nth Row

delete from emp 
  where empno = (select empno from 
    (select empno,rownum from emp group by empno,rownum 
       having rownum = &n));

Select alternate rows

  select * from emp where rowid in 
    (select decode(mod(rownum,2),0,rowid) from emp);

To find last 3 rows

  select * from emp e1 where 3 > 
   (select count(rowid) from emp e
    where e.rowid < e1.rowid);

To find first 3 rows 

 select * from emp where rownum <=3 
 
Select nth row

 select * from emp where rowid in 
       (select decode(rownum,&n,rowid) from emp);
or
     select * from emp where (rowid,&n) in 
       (select rowid,rownum from emp);

Select nth and mth row

   select * from emp where rowid in
   (select decode(rownum,&m,rowid,&n,rowid) from emp);

Find out last n rows in table

  select * from emp where rowid not in
   (select rowid from emp group by rownum,rowid 
     having rownum <= (select count(*) - &n from emp);

Find row between m & n including m & n

  select * from emp where rowid in 
   (select rowid from emp group by rownum having rownum > &n 
    and rownum < &m);

Find last row of table

  select * from emp where rowid in
   (select max(rowid) from emp);

Rename column

 alter table emp rename column empno to eno;

Rename table 

 rename emp to employee;

Employee name starting with s,p,a

  select * from emp where substr(empname,1,1) in ('s','p','a');

Display 2nd highest sal department wise

 select * from emp a where 1 = 
  (select count(distinct sal) from emp b where a.sal < b.sal and a.dept=b.dept);

To create table from existing table without data

 create table emp1 as (select * from emp where 1=2);

Display max sal along with all details

  select * from emp where sal in (select max(sal) from emp);

Last n row

  select * from emp minus select * from emp 
   where rownum <= (select max(rownum)-&n from emp);
 or
  select * from emp e1 where &n > (select count(rowid) from emp e2
   where e1.rowid < e2.rowid );

Delete n row

 Delete form emp where empno = (select empno from (select empno,rownum from emp 
   group by empno,rownum having rownum = &n));

Convert sal into string
 
 select tochar(to_date(sal,'J'),'JSP') salinWord from emp;

Find out null & total nul column

  Note: comm and mgr are the column of table emp

  select sum(decode(comm,null,1,0)) comm_null, sum(decode(mgr,null,1,0)) mgr_null
   sum(comm_null + mgr_null) Total_null from emp;

Find no. of employee working in each dept. & total no. of employee

  select sum(decode(deptno,10,1,1) dept_10, sum(decode(deptno,20,1,1) dept_20,
   sum(decode(deptno,30,1,1) dept_30, sum(decode(deptno,40,1,1) dept_40,
   count(*) total from emp;
 or
  select deptno,count(empno) from emp group by deptno;

No. of employee hired in one month

 select to_char(hiredate,'Mon'),count(hiredate) from emp 
  group by to_char(hiredate,'Mon');

Total no. of column in the table

  select count(*) from col where tname = &tablename; 

To find employee joined on same date

  select * from emp e1 where 2 <= (select count(*) from emp e2 
    where e1.hiredate = e2.hiredate);

To find the no. of employee working under each manager or employee

  select mgr,count(empno) from emp where mgr is not null group by mgr;

Maximun no. of employee working under which employee/manager

  select * from (select mgr,count(empno) No from emp where mgr is not null
   group by mgr) where No = (select max(No) from (select mgr,count(empno) from emp
   where mgr is not null group by mgr));

No. of employee hired on same date

  select hiredate,No from (select hiredate,count(empno) No from emp group by hiredate);

Nth Highest Salary 

  Generic
  SELECT name, salary FROM employee e1 WHERE N-1 = (SELECT COUNT(DISTINCT salary) 
  FROM employee e2 WHERE e2.salary > e1.salary)
  Sql Server 
  SELECT TOP 1 salary FROM 
  ( SELECT DISTINCT TOP N salary FROM employee ORDER BY salary DESC ) AS temp 
  ORDER BY salary
  My Sql
  SELECT salary FROM employee ORDER BY salary DESC LIMIT N-1, 1

  postgres - need to set limit and offset properly
  SELECT salary FROM employee ORDER BY salary DESC LIMIT N-1 OFFSET 1

please try at your end....

Tuesday, September 25, 2012

Lazy/Eager Loading Using Hibernate

Lazy/Eager Loading Using Hibernate
Today's post will focus on why and how we use the concepts known 
as LAZY and EAGER loading in an application and how to use 
Spring's hibernate template to load our LAZY entities in an EAGER 
fashion.

And of course as the title itself suggests, we will show this by 
an example. The scenario is as such;

You are a parent who has a kid with a lot of toys. But the current 
issue is whenever you call him (we assume you have a boy), he comes 
to you with all his toys as well. Now this is an issue since you do 
not want him carrying around his toys all the time.

So being the rationale parent, you go right ahead and define the toys 
of the child as LAZY. Now whenever you call him, he just comes to you 
without his toys.

But you are faced with another issue. When the time comes for a family
trip, you want him to bring along his toys because the kid will be 
bored with the trip otherwise. But since you strictly enforced LAZY 
on the child's toy, you are unable to ask him to bring along the toys. 
This is where EAGER fetching comes into play. Let us first see our 
domain classes.

 
package com.fetchsample.example.domain;

import java.util.HashSet;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;

/**
 * Holds information about the child
 * 
 * @author dinuka.arseculeratne
 * 
 */
@Entity
@Table(name = "CHILD")
@NamedQuery(name = "findChildByName", 
query = "select DISTINCT(chd) from Child chd left join fetch chd.toyList 
where chd.childName=:chdName")
public class Child {

 public static interface Constants {
  public static final String FIND_CHILD_BY_NAME_QUERY = "findChildByName";

  public static final String CHILD_NAME_PARAM = "chdName";
 }

 @Id
 @GeneratedValue(strategy = GenerationType.AUTO)
 /**
  * The primary key of the CHILD table
  */
 private Long childId;

 @Column(name = "CHILD_NAME")
 /**
  * The name of the child
  */
 private String childName;

 @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
 /**
  * The toys the child has. We do not want the child to have the 
  * same toy more than once, so we have used a set here.
  */
 private Set toyList = new HashSet();

 public Long getChildId() {
  return childId;
 }

 public void setChildId(Long childId) {
  this.childId = childId;
 }

 public String getChildName() {
  return childName;
 }

 public void setChildName(String childName) {
  this.childName = childName;
 }

 public Set getToyList() {
  return toyList;
 }

 public void addToy(Toy toy) {
  toyList.add(toy);
 }

}

------------------------------------------------

 
package com.fetchsample.example.domain;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * Hols data related to the toys a child possess
 * 
 * @author dinuka.arseculeratne
 * 
 */
@Entity
@Table(name = "TOYS")
public class Toy {

 @Id
 @GeneratedValue(strategy = GenerationType.AUTO)
 @Column(name = "TOY_ID")
 /**
  * The primary key of the TOYS table
  */
 private Long toyId;

 @Column(name = "TOY_NAME")
 /**
  * The name of the toy
  */
 private String toyName;

 public Long getToyId() {
  return toyId;
 }

 public void setToyId(Long toyId) {
  this.toyId = toyId;
 }

 public String getToyName() {
  return toyName;
 }

 public void setToyName(String toyName) {
  this.toyName = toyName;
 }

 @Override
 public int hashCode() {
  final int prime = 31;
  int result = 1;
  result = prime * result + ((toyName == null) ? 0 : toyName.hashCode());
  return result;
 }

 @Override
 /**
  * Overriden because within the child class we use a Set to
  * hold all unique toys
  */
 public boolean equals(Object obj) {
  if (this == obj)
   return true;
  if (obj == null)
   return false;
  if (getClass() != obj.getClass())
   return false;
  Toy other = (Toy) obj;
  if (toyName == null) {
   if (other.toyName != null)
    return false;
  } else if (!toyName.equals(other.toyName))
   return false;
  return true;
 }

 @Override
 public String toString() {
  return "Toy [toyId=" + toyId + ", toyName=" + toyName + "]";
 }

}

So as you can see, we have two simple entities representing the child 
and toy. The child has a one-to-many relationship with the toys which 
means one child can have many toys (oh how i miss my childhood days). 
Afterwards we need to interact with the data, so let us go ahead and 
define out DAO(Data access object) interface and implementation.  

 
package com.fetchsample.example.dao;

import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.fetchsample.example.domain.Child;

/**
 * The basic contract for dealing with the {@link Child} entity
 * 
 * @author dinuka.arseculeratne
 * 
 */
@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
public interface ChildDAO {

 /**
  * This method will create a new instance of a child in the child table
  * 
  * @param child
  *            the entity to be persisted
  */
 public void persistChild(Child child);

 /**
  * Retrieves a child without his/her toys
  * 
  * @param childId
  *            the primary key of the child table
  * @return the child with the ID passed in if found
  */
 public Child getChildByIdWithoutToys(Long childId);

 /**
  * Retrieves the child with his/her toys
  * 
  * @param childId
  *            the primary key of the child table
  * @return the child with the ID passed in if found
  */
 public Child getChildByIdWithToys(Long childId);

 /**
  * Retrieves the child by the name and with his/her toys
  * 
  * @param childName
  *            the name of the child
  * @return the child entity that matches the name passed in
  */
 public Child getChildByNameWithToys(String childName);

}

--------------------------------------------
 
package com.fetchsample.example.dao.hibernate;

import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.fetchsample.example.dao.ChildDAO;
import com.fetchsample.example.domain.Child;

/**
 * The hibernate implementation of our {@link ChildDAO} interface
 * 
 * @author dinuka.arseculeratne
 * 
 */
public class ChildDAOHibernateImpl extends HibernateDaoSupport implements
  ChildDAO {

 /**
  * {@inheritDoc}
  */
 public void persistChild(Child child) {
  getHibernateTemplate().persist(child);
 }

 /**
  * {@inheritDoc}
  */
 public Child getChildByIdWithoutToys(Long childId) {
  return getHibernateTemplate().get(Child.class, childId);
 }

 /**
  * {@inheritDoc}
  */
 public Child getChildByIdWithToys(Long childId) {
  Child child = getChildByIdWithoutToys(childId);
  /**
   * Since by default the toys are not loaded, we call the hibernate
   * template's initialize method to populate the toys list of that
   * respective child.
   */
  getHibernateTemplate().initialize(child.getToyList());
  return child;
 }

 /**
  * {@inheritDoc}
  */
 public Child getChildByNameWithToys(String childName) {
  return (Child) getHibernateTemplate().findByNamedQueryAndNamedParam(
    Child.Constants.FIND_CHILD_BY_NAME_QUERY,
    Child.Constants.CHILD_NAME_PARAM, childName).get(0);

 }

}

A simple contract. I have four main methods. The first one of course 
just persists a child entity to the database.

The second method retrieves the Child by the primary key passed in, 
but does not fetch the toys.

The third method first fetches the Child and then retrieves the 
Child's toys using the Hibernate template's initialize() method. 
Note that when you call the initialize() method, hibernate will 
fetch you LAZY defined collection to the Child proxy you retrieved.

The final method also retrieves the Child's toys, but this time using 
a named query. If we go back to the Child entity's Named query, you 
can see that we have used "left join fetch". It is the keyword fetch 
that actually will initialize the toys collection as well when 
returning the Child entity that qualifies. Finally i have my main 
class to test our functionality;

 
package com.fetchsample.example;

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

import com.fetchsample.example.dao.ChildDAO;
import com.fetchsample.example.domain.Child;
import com.fetchsample.example.domain.Toy;

/**
 * A test class
 * 
 * @author dinuka.arseculeratne
 * 
 */
public class ChildTest {

 public static void main(String[] args) {
  ApplicationContext context = new ClassPathXmlApplicationContext(
    "com/fetchsample/example/spring-context.xml");

  /**
   * First we initialize a child
   */
  Child child = new Child();

  /**
   * A cool ben 10 action figure
   */
  Toy ben10 = new Toy();
  ben10.setToyName("Ben 10 figure");

  /**
   * A even more cooler spider man action figure
   */
  Toy spiderMan = new Toy();
  spiderMan.setToyName("Spider man figure");

  child.setChildName("John");
  /**
   * Add the toys to the collection
   */
  child.addToy(ben10);
  child.addToy(spiderMan);

  ChildDAO childDAO = (ChildDAO) context.getBean("childDAO");

  childDAO.persistChild(child);

  Child childWithoutToys = childDAO.getChildByIdWithoutToys(1L);
  // The following line will throw a lazy initialization error since we have
  // defined fetch type as LAZY in the Child domain class.
  // System.out.println(childWithToys.getToyList().size());

  Child childWithToys = childDAO.getChildByIdWithToys(1L);
  System.out.println(childWithToys.getToyList().size());

  Child childByNameWithToys = childDAO.getChildByNameWithToys("John");

  System.out.println(childByNameWithToys.getToyList().size());

 }
}

--------------------------------------------
 
package com.fetchsample.example;

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

import com.fetchsample.example.dao.ChildDAO;
import com.fetchsample.example.domain.Child;
import com.fetchsample.example.domain.Toy;

/**
 * A test class
 * 
 * @author dinuka.arseculeratne
 * 
 */
public class ChildTest {

 public static void main(String[] args) {
  ApplicationContext context = new ClassPathXmlApplicationContext(
    "com/fetchsample/example/spring-context.xml");

  /**
   * First we initialize a child
   */
  Child child = new Child();

  /**
   * A cool ben 10 action figure
   */
  Toy ben10 = new Toy();
  ben10.setToyName("Ben 10 figure");

  /**
   * A even more cooler spider man action figure
   */
  Toy spiderMan = new Toy();
  spiderMan.setToyName("Spider man figure");

  child.setChildName("John");
  /**
   * Add the toys to the collection
   */
  child.addToy(ben10);
  child.addToy(spiderMan);

  ChildDAO childDAO = (ChildDAO) context.getBean("childDAO");

  childDAO.persistChild(child);

  Child childWithoutToys = childDAO.getChildByIdWithoutToys(1L);
  // The following line will throw a lazy initialization error since we have
  // defined fetch type as LAZY in the Child domain class.
  // System.out.println(childWithToys.getToyList().size());

  Child childWithToys = childDAO.getChildByIdWithToys(1L);
  System.out.println(childWithToys.getToyList().size());

  Child childByNameWithToys = childDAO.getChildByNameWithToys("John");

  System.out.println(childByNameWithToys.getToyList().size());

 }
}

Defining your base Entity as LAZY is a good practice since
in many occasions, you might not want the collections within 
an entity, but just want to interact with the data in your base 
entity. But in the event of you needing the data of your collections,
then you can use either of the methods mentioned before.

Referance: Dinuka Arseculeratne (Dzone)

Monday, September 10, 2012

Encapsulation in Object Oriented Programming

Encapsulation in Object Oriented Programming
Encapsulation is one of the four fundamentals of the Object oriented 
programming.

What is Encapsulation?

Encapsulation is a language mechanism to restrict the access of the 
Objects components to other Objects or Classes. 

Encapsulation helps in enforcing the security of the data related to a 
particular object. In the programming models like Structural, procedural 
and Modular programming, there was not much provision to safeguard the 
data from the other procedures or functions. This can lead to the misuse
of data or even the design by responsibility principle of OOAD can be 
some times breached.

Every Object in Object oriented programming has full control of what 
members (Fields and methods) to be accessible to its peers in a package,
outside the package and should only be visible to its own members alone.

Encapsulation in Object Oriented Programming is implemented by mentioning
 the Access Modifiers like public, protected, private and default access.

The access to the data  and methods can be restricted to a package, 
classes level etc.,

Encapsulation with Example

Let me explain the concept of Encapsulation with an example.  Say, you 
are a student in a class and some of the things you and your friends know,
say nick names, should not be revealed to the professors, your parents 
does not have knowledge of you not attending the classes or poor 
performance in a subject etc.,

In our own life, we would like to shield/share some information to a 
group of people. In the same fashion, object as instances of a class has
full control of its members. 

When a class is created and its members are defined, the access modifiers 
are applied to its fields and methods.

When an object is created using that particular class, the access will be 
restricted based on the defined access of the members.

Encapsulation is nothing but hiding the features that are not relevant 
for other objects but are essential for their own features.

For Example, I have create a class Car which has two methods:
 
1.move().
2.internalCombustion()

The move method depends on internalCombustion() method. But an Employee 
needs only move method and need not be aware of internalCombustion 
behavior.So, the internalCombustion behavior can be declared private so
that it can be only visible to the members inside the class.

Summary:

Encapsulation is a primary fundamental principle in Object oriented
programming. It is used to enforce the security to restrict the 
visibility of the members to other components. 

Notification Div & Css

Notification Div & Css


//CSS
.note{
 background-color: #E6E6FC;
 border: 1px solid #D1D1E8;
 padding: 20px;
 margin: 20px 0px;
 -webkit-border-radius: 4px;
 -moz-border-radius: 4px;
 border-radius: 4px;
}

Notification message <!-- html Div --> <div class="note"> Notification message </div>
.download { padding: 40px 85px; border: 1px solid #CEEBCE; background: url('/images/download.png') no-repeat 20px 20px #DFF7DF; margin-bottom: 20px; -webkit-border-radius: 4px; -moz-border-radius: 4px; border-radius: 4px; }
<div class="download"> Notification message with Image </div>

Wednesday, September 5, 2012

Why to override Hashcode in java?

Understand hashCode() and equals() in HashMap
Look at the below given Example:

import java.util.Date;
import java.util.HashMap;
import java.util.Map;


public class HCode {
 public static void main(String[] args) {
  Map m = new HashMap();
  
  TestHC s1 = new TestHC("Sunday");
  TestHC s2 = new TestHC("Monday");
  TestHC s3 = new TestHC("Sunday");
  
  System.out.println("First object:-");
  m.put(s1, "Sunday");
  System.out.println("\n Second object:-");
  m.put(s2, "Monday");
  System.out.println("\n Third object:-");
  m.put(s3, "Sunday");
  System.out.println("\n Map size :-"+m.size());
  System.out.println("\n Map :- "+m.toString());
  
 }
}

class TestHC{
 String day;
 TestHC(String d) { day = d; }
   public boolean equals(Object o) {
       System.out.println("**calling equals()**");
      return ((TestHC)o).day == this.day;
   }
 
   /* public int hashCode() { 
      System.out.println("**calling hashcode()**");
     return new Date().getDay()+1;
    }*/

}


Output:
First object:-

Second object:-

Third object:-

Map size :-3

Map :- {TestHC@addbf1=Monday, TestHC@42e816=Sunday, TestHC@19821f=Sunday}

In the above code we commented the hashcode method and there is no call
for equals method,now if you check the output you will see map contain 
three elements/Objects which is wrong since the key of two of our object
is same that's "Sunday".

Now just uncomment the hashcode method and run the program the output is:

First object:-
**calling hashcode()**

 Second object:-
**calling hashcode()**
**calling equals()**

 Third object:-
**calling hashcode()**
**calling equals()**
**calling equals()**

 Map size :-2
**calling hashcode()**
**calling hashcode()**

 Map :- {TestHC@4=Monday, TestHC@4=Sunday}

Here you can see the equals and hashcode methods are called and the 
same key elements/Objects are removed the output itself tell's you 
what exactly happen.

Note:-
1. Find the right bucket - hashCode()
2. Search the bucket for the right element - using equals()

 

Polymorphism

Polymorphism
Polymorphism is a capability of an action or methods to do different things based on the object that it is action upon. In other words, It allows us to define one interface and have multiple implementation. The method overriding is an example of run-time polymorphism