Sunday, 12 February 2012

Implementing hashCode() and equals()


The methods hashCode() and equals() play a distinct role in the objects you insert into Java collections. The specific contract rules of these two methods are best described in the JavaDoc. Here I will just tell you what role they play. What they are used for, so you know why their implementations are important.

Few Thump rules:
  • If two objects are same then they must return same value in hashcode() and equals() method whenever invoked.
  • It is not necessary that two different object must have different hashcode values. it might be possible that they share common hash bucket.
JVM assigns unique hashcode value to each object when they are created in memory and if developers don’t override the hashcode method then there is no way the two object returns same hashcode value.
As the question comes in your mind that equals() method is used to compare objects that they are having same value or not but why should we override the hashcode method ?
The answer to the question is for the hash technique based data structures like HashMap and HashTable.
As you can see in above diagram that every object is placed in Hash bucket depending on the hashcode they have. It is not necessary that every different object must have different hashcode. hashcode is used to narrow the search result. When we try to insert any key in HashMap first it checks whether any other object present with same hashcode and if yes then it checks for the equals() method. If two objects are same then HashMap will not add that key instead it will replace the old value by new one.
What will happen if I don’t override the hashcode method?
Ans : If the object does not implement hashcode() method and used as key then we will not get the object back as shown in below code.
Code without implementation of equals() and hashcode()
package org.opensourzesupport;

import java.util.HashMap;

class Movie {

    private String name, actor;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getActor() {
        return actor;
    }

    public void setActor(String actor) {
        this.actor = actor;
    }

    public int getReleaseYr() {
        return releaseYr;
    }

    public void setReleaseYr(int releaseYr) {
        this.releaseYr = releaseYr;
    }
    private int releaseYr;
}

public class HashMapDemo {

    public static void main(String[] args) {

        Movie m = new Movie();
        m.setActor("Akshay");
        m.setName("Thank You");
        m.setReleaseYr(2011);

        Movie m1 = new Movie();
        m1.setActor("Akshay");
        m1.setName("Khiladi");
        m1.setReleaseYr(1993);

        Movie m2 = new Movie();
        m2.setActor("Akshay");
        m2.setName("Taskvir");
        m2.setReleaseYr(2010);

        Movie m3 = new Movie();
        m3.setActor("Akshay");
        m3.setName("Taskvir");
        m3.setReleaseYr(2010);

        HashMap<Movie, String> map = new HashMap<Movie, String>();
        map.put(m, "ThankYou");
        map.put(m1, "Khiladi");
        map.put(m2, "Tasvir");
        map.put(m3, "Duplicate Tasvir");

        //Iterate over HashMap
        for (Movie mm : map.keySet()) {
            System.out.println(map.get(mm).toString());
        }

        Movie m4 = new Movie();
        m4.setActor("Akshay");
        m4.setName("Taskvir");
        m4.setReleaseYr(2010);

        if (map.get(m4) == null) {
            System.out.println("----------------");
            System.out.println("Object not found");
            System.out.println("----------------");
        } else {
            System.out.println("----------------");
            System.out.println(map.get(m4).toString());
            System.out.println("----------------");
        }
    }
}
Output: Khiladi Tasvir ThankYou Duplicate Tasvir —————- Object not found —————-
As you can see in above program :
  1. Duplicate objects are added in Hashmap as a key (Because we have not overided the hashcode and equals method)
  2. We are not able to get back object from map (Because hashcode is not implemented)

Same program with equals and hashcode implementation:
package org.opensourzesupport;

import java.util.HashMap;

class Movie {

    private String name, actor;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getActor() {
        return actor;
    }

    public void setActor(String actor) {
        this.actor = actor;
    }

    public int getReleaseYr() {
        return releaseYr;
    }

    public void setReleaseYr(int releaseYr) {
        this.releaseYr = releaseYr;
    }
    private int releaseYr;

    @Override
    public boolean equals(Object o) {
        Movie m = (Movie) o;
        return m.actor.equals(this.actor) && m.name.equals(this.name) && m.releaseYr == this.releaseYr;
    }

    @Override
    public int hashCode() {
        return actor.hashCode() + name.hashCode() + releaseYr;
    }
}

public class HashMapDemo {

    public static void main(String[] args) {

        Movie m = new Movie();
        m.setActor("Akshay");
        m.setName("Thank You");
        m.setReleaseYr(2011);

        Movie m1 = new Movie();
        m1.setActor("Akshay");
        m1.setName("Khiladi");
        m1.setReleaseYr(1993);

        Movie m2 = new Movie();
        m2.setActor("Akshay");
        m2.setName("Taskvir");
        m2.setReleaseYr(2010);

        Movie m3 = new Movie();
        m3.setActor("Akshay");
        m3.setName("Taskvir");
        m3.setReleaseYr(2010);

        HashMap<Movie, String> map = new HashMap<Movie, String>();
        map.put(m, "ThankYou");
        map.put(m1, "Khiladi");
        map.put(m2, "Tasvir");
        map.put(m3, "Duplicate Tasvir");

        //Iterate over HashMap
        for (Movie mm : map.keySet()) {
            System.out.println(map.get(mm).toString());
        }

        Movie m4 = new Movie();
        m4.setActor("Akshay");
        m4.setName("Taskvir");
        m4.setReleaseYr(2010);

        if (map.get(m4) == null) {
            System.out.println("----------------");
            System.out.println("Object not found");
            System.out.println("----------------");
        } else {
            System.out.println("----------------");
            System.out.println(map.get(m4).toString());
            System.out.println("----------------");
        }
    }
}
Output: Khiladi Duplicate Tasvir ThankYou —————- Duplicate Tasvir —————- As you can see :
  • Duplicate Keys are not added instead there values are replaced.
  • Now the object is retrieved from the Map.







Saturday, 11 February 2012

UML class diagrams for java

UML class diagrams allow us to denote the static contents of — and the relationships between — classes.   In a class diagram we can show the member variables, and member functions of a class. We can also show whether one class inherits from another, or whether it holds a reference to another. In short, we can depict all the source code dependencies between classes.
This can be valuable. It can be much easier to evaluate the dependency structure of a system from a diagram than from source code. Diagrams make certain dependency structures visible. We cansee dependency cycles, and determine how best to break them. We can see when abstract classes depend upon concrete classes, and determine a strategy for rerouting such dependencies.

The Basics


                                           
                                              Figure : 1.0

Fig 1.0 shows the simplest form of class diagram. The class named Helpis represented as a simple rectangle. This diagram represents nothing more than the code shown to its right.
A class icon can be subdivided into compartments. The top compartment is for the name of the class, the second is for the variables of the class, and the third is for the methods of the class.
Figure 1.1 shows these compartments and how they translate into code.


Figure : 1.1
Notice the character in front of the variables and functions in the class icon. A dash (–) denotes private, a hash (#) denotes protected, and a plus (+)denotes public.
The type of a variable, or a function argument is shown after the colon following the variable or argument name. Similarly, the return value of a function is shown after the colon following the function.
This kind of detail is sometimes useful, but should not be used very often. UML diagrams are not the place to declare variables and functions. Such declarations are better done in source code. Use these adornments only when they are essential to the purpose of the diagram.

Association

Associations between classes most often represent instance variables that hold references to other objects. For example, in  Figure 1.2 we see an association between Phone and Button. The direction of the arrow tells us that Phone holds a reference to Button. The name near the arrowhead is the name of the instance variable. The number near the arrowhead tells us how many references are held.
Figure : 1.2
Figure 1.2 Association.
In Figure 1.2 we saw that 13 Button objects were connected to the Mobile object. In Figure 1.3, we see what happens when there is no limit. A Phonebookis connected to many PhoneNumber objects. The star means many. In Java this is most commonly implemented with a Vector, a List, or some other container type.


Figure : 1.3

Inheritance

You have to be very careful with your arrowheads in UML. Figure 1.4 shows why. The little arrowhead pointing at Employee denotes inheritance1. If you draw your arrowheads carelessly, it may be hard to tell whether you mean inheritance or association. To make it clearer, I often make inheritance relationships vertical and associations horizontal.


Figure : 1.4

In UML all arrowheads point in the direction of source code dependency. Since it is the SalariedEmployee class that mentions the name of Employee, the arrowhead points at Employee. So, in UML, inheritance arrows point at the base class.
UML has a special notation for the kind of inheritance used between a Java class and a Java interface. It is shown, in Figure 1.5, as a dashed inheritance arrow2. In the diagrams to come, you'll probably catch me forgetting to dash the arrows that point to interfaces. I suggest you forget to dash the arrows that you draw on white boards too. Life's too short to be dashing arrows.



                                                                         Figure : 1.5




REST vs SOAP Web Services


I am seeing a lot of new web services are implemented using a RESTstyle architecture these days rather than a SOAP one. Lets step back a second and explain what REST is.
What is a REST Web Service
The acronym REST stands for Representational State Transfer, this basically means that each unique URL is a representation of some object. You can get the contents of that object using an HTTP GET, to delete it, you then might use a POST, PUT, or DELETE to modify the object (in practice most of the services use a POST for this).
Who's using REST?
All of Yahoo's web services use REST, including Flickr, del.icio.us API uses it, pubsub, bloglines, technorati, and both eBay, and Amazon have web services for both REST and SOAP.
Who's using SOAP?
Google seams to be consistent in implementing their web services to use SOAP, with the exception of Blogger, which uses XML-RPC. You will find SOAP web services in lots of enterprise software as well.
REST vs SOAP
As you may have noticed the companies I mentioned that are using REST api's haven't been around for very long, and their apis came out this year mostly. So REST is definitely the trendy way to create a web service, if creating web services could ever be trendy (lets face it you use soap to wash, and you rest when your tired). The main advantages of REST web services are:
  • Lightweight - not a lot of extra xml markup
  • Human Readable Results
  • Easy to build - no toolkits required
SOAP also has some advantages:
  • Easy to consume - sometimes
  • Rigid - type checking, adheres to a contract
  • Development tools
For consuming web services, its sometimes a toss up between which is easier. For instance Google's AdWords web service is really hard to consume (in CF anyways), it uses SOAP headers, and a number of other things that make it kind of difficult. On the converse, Amazon's REST web service can sometimes be tricky to parse because it can be highly nested, and the result schema can vary quite a bit based on what you search for.
Which ever architecture you choose make sure its easy for developers to access it, and well documented.

Saturday, 14 January 2012

JSF 2 Lifecycle





1 Restore View
2 Apply requests Process events
3 Process Validations
4 Update model values Process events
5 Invoke applications Process events
6 Render response





























        

Restore view

RestoreView is the first phase in the JSF  lifecycle. This phase is used for constructing view to display in the front end. Every view has it's own view id and it is stored in the FacesContext's session object. JSF  View is collection of components associated with its current state. There is two types of state saving mechanism,
  1. Server (default)
  2. Client
Default value is server. If you specify state saving method as server, the state of each components will be stored in the server. If it is client, it will be stored in the client side as hidden variables. This value is configured using javax.faces.STATE_SAVING_METHOD parameter name in your web.xml context params as follows:

1.<context-param>
2.<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
3.<param-value>client</param-value>
4.</context-param>

Apply Requests

After the component tree is restored, each component in the tree extracts its new value from the request parameters by using its decode method. The value is then stored locally on the component. If the conversion of the value fails, an error message associated with the component is generated and queued on FacesContext. This message will be displayed during the render response phase, along with any validation errors resulting from the process validations phase.

Process Validations

During this phase, the JavaServer Faces implementation processes all validators registered on the components in the tree. It examines the component attributes that specify the rules for the validation and compares these rules to the local value stored for the component.

Update Model Values 

After the JavaServer Faces implementation determines that the data is valid, it can walk the component tree and set the corresponding server-side object properties to the components' local values. The JavaServer Faces implementation will update only the bean properties pointed at by an input component's value attribute.
If the local data cannot be converted to the types specified by the bean properties, the life cycle advances directly to the render response phase so that the page is rerendered with errors displayed. This is similar to what happens with validation errors.

Invoke Applications

During this phase, the JavaServer Faces implementation handles any application-level events, such as submitting a form or linking to another page.
At this point, if the application needs to redirect to a different web application resource or generate a response that does not contain any JavaServer Faces components, it can call FacesContext.responseComplete.
If the view being processed was reconstructed from state information from a previous request and if a component has fired an event, these events are broadcast to interested listeners.

Render Response 

During this phase, the JavaServer Faces implementation delegates authority for rendering the page to the JSP container if the application is using JSP pages. If this is an initial request, the components represented on the page will be added to the component tree as the JSP container executes the page. If this is not an initial request, the components are already added to the tree so they needn't be added again. In either case, the components will render themselves as the JSP container traverses the tags in the page.

Friday, 13 January 2012

Database Metadata

    Metadata is data about data.
    Database metadata is information about a database.
    Database metadata provides information about the structure of a database and its tables,     views, and   stored procedures.

JDBC provides four interfaces that deal with database metadata
  1. java.sql.DatabaseMetaData: about the database as a whole: table names, table indexes, database product name and version, and actions the database supports.
  2. java.sql.ResultSetMetaData: about the types and properties of the columns in a ResultSet object.
  3. java.sql.ParameterMetaData: about the types and properties of the parameters in a PreparedStatement object.
  4. javax.sql.RowSetMetaData: about the columns in a RowSet object.
JDBC DatabaseMetaData is an interface of java.sql.*; package. DatabaseMetaData is generally implemented by the Database application vendors to know the capability of Database Management System in combination with the driver based JDBC technology. This interface is the tool for the user who need to discover how to deal with underlying database. Some meta data methods returns the string in form of ResultSet object. Then we retrieve data from this object with getInt(), and getString() methods. Some metadata objects takes argument also.

Example :


public class JDBCDatabaseMetaDataExample {
        public static void main(String args[]) {
                try {
                        // Loading database driver
                        Class.forName("com.mysql.jdbc.Driver");

                        // Connecting to the database
                        Connection conn = DriverManager.getConnection(
                                        "jdbc:mysql://localhost:3306/student", "root", "root");

                        DatabaseMetaData metaData = conn.getMetaData();
                        ResultSet rs = metaData.getTypeInfo();
                        System.out.println("Printing All 
                        Premitive DataTypes supported by this Database Applications\n");
                        while (rs.next()) {
                                System.out.println(rs.getString(1));
                        }
                        rs.close();
                        Statement stmt = conn.createStatement();
                        ResultSet resultSet = stmt.executeQuery("SELECT * FROM student");
                        ResultSetMetaData md = resultSet.getMetaData();
                        System.out.println("\n Fetching Query.............");
                        for (int i = 1; i <= md.getColumnCount(); i++)
                                System.out.print(md.getColumnLabel(i) + " ");
                        System.out.println();
                        while (resultSet.next()) {
                                for (int i = 1; i <= md.getColumnCount(); i++)
                                        System.out.print(resultSet.getString(i) + " ");
                                System.out.println();
                        }
                        resultSet.close();
                        stmt.close();
                        conn.close();
                } catch (SQLException e) {
                        System.out.println(e.toString());
                } catch (Exception e) {
                        System.out.println(e);
                }
        }
}







What are Java Comparators and Comparables?

Comparable

A comparable object is capable of comparing itself with another object. The class itself must implements the java.lang.Comparable interface in order to be able to compare its instances.

Comparator

A comparator object is capable of comparing two different objects. The class is not comparing its instances, but some other class’s instances. This comparator class must implement the java.util.Comparator interface.

Do we need to compare objects?

The simplest answer is yes. When there is a list of objects, ordering these objects into different orders becomes a must in some situations. For example; think of displaying a list of employee objects in a web page. Generally employees may be displayed by sorting them using the employee id. Also there will be requirements to sort them according to the name or age as well. In these situations both these (above defined) concepts will become handy.

How to use these?

There are two interfaces in Java to support these concepts, and each of these has one method to be implemented by user.
Those are;

java.lang.Comparable: int compareTo(Object o1)
This method compares this object with o1 object. Returned int value has the following meanings.
  1. positive – this object is greater than o1
  2. zero – this object equals to o1
  3. negative – this object is less than o1

java.util.Comparator: int compare(Object o1, Objecto2)
This method compares o1 and o2 objects. Returned int value has the following meanings.

  • positive – o1 is greater than o2
  • zero – o1 equals to o2
  • negative – o1 is less than o2



  • java.util.Collections.sort(List) and java.util.Arrays.sort(Object[]) methods can be used to sort using natural ordering of objects.
    java.util.Collections.sort(List, Comparator) and java.util.Arrays.sort(Object[], Comparator) methods can be used if a Comparator is available for comparison.

    The above explained Employee example is a good candidate for explaining these two concepts. First we’ll write a simple Java bean to represent the Employee.


    public class Employee {
    private int empId;
    private String name;
    private int age;
    
    public Employee(int empId, String name, int age) {
    // set values on attributes
    }
    // getters & setters
    }
    


    Next we’ll create a list of Employees for using in different sorting requirements. Employees are added to a List without any specific order in the following class.

    import java.util.*;
    
    public class Util {
    
    public static List<Employee> getEmployees() {
    
    List<Employee> col = new ArrayList<Employee>();
    
    col.add(new Employee(5, "Frank", 28));
    col.add(new Employee(1, "Jorge", 19));
    col.add(new Employee(6, "Bill", 34));
    col.add(new Employee(3, "Michel", 10));
    col.add(new Employee(7, "Simpson", 8));
    col.add(new Employee(4, "Clerk",16 ));
    col.add(new Employee(8, "Lee", 40));
    col.add(new Employee(2, "Mark", 30));
    
    return col;
    }
    }

    Sorting in natural ordering

    Employee’s natural ordering would be done according to the employee id. For that, above Employee class must be altered to add the comparing ability as follows.

    public class Employee implements Comparable<Employee> {
    private int empId; private String name; private int age; /** * Compare a given Employee with this object. * If employee id of this object is * greater than the received object, * then this object is greater than the other. */ public int compareTo(Employee o) { return this.empId - o.empId ; } }


    The new compareTo() method does the trick of implementing the natural ordering of the instances. So if a collection of Employee objects is sorted using Collections.sort(List) method; sorting happens according to the ordering done inside this method.

    We’ll write a class to test this natural ordering mechanism. Following class use the Collections.sort(List) method to sort the given list in natural order.

    
    import java.util.*;
    
    public class TestEmployeeSort {
    
    public static void main(String[] args) {     
    List coll = Util.getEmployees();
    Collections.sort(coll); // sort method
    printList(coll);
    }
    
    private static void printList(List<Employee> list) {
    System.out.println("EmpId\tName\tAge");
    for (Employee e: list) {
    System.out.println(e.getEmpId() + "\t" + e.getName() + "\t" + e.getAge());
    }
    }
    }

    Run the above class and examine the output. It will be as follows. As you can see, the list is sorted correctly using the employee id. As empId is an int value, the employee instances are ordered so that the int values ordered from 1 to 8.

    EmpId Name Age
    1 Jorge 19
    2 Mark 30
    3 Michel 10
    4 Clerk 16
    5 Frank 28
    6 Bill 34
    7 Simp 8
    8 Lee 40

    Sorting by other fields

    If we need to sort using other fields of the employee, we’ll have to change the Employee class’s compareTo() method to use those fields. But then we’ll loose this empId based sorting mechanism. This is not a good alternative if we need to sort using different fields at different occasions. But no need to worry; Comparator is there to save us.

    By writing a class that implements the java.util.Comparator interface, you can sort Employees using any field as you wish even without touching the Employee class itself; Employee class does not need to implement java.lang.Comparable or java.util.Comparator interface.

    Sorting by name field

    Following EmpSortByName class is used to sort Employee instances according to the name field. In this class, inside the compare() method sorting mechanism is implemented. In compare() method we get two Employee instances and we have to return which object is greater.

    public class EmpSortByName implements Comparator<Employee>{
    
    public int compare(Employee o1, Employee o2) {
    return o1.getName().compareTo(o2.getName());
    }
    }



    Watch out: Here, String class’s compareTo() method is used in comparing the name fields (which are Strings).

    Now to test this sorting mechanism, you must use the Collections.sort(List, Comparator) method instead of Collections.sort(List) method. Now change the TestEmployeeSort class as follows. See how the EmpSortByName comparator is used inside sort method.

    
    import java.util.*;
    
    public class TestEmployeeSort {
    
    public static void main(String[] args) {
    
    List coll = Util.getEmployees();
    //Collections.sort(coll);
    //use Comparator implementation
    Collections.sort(coll, new EmpSortByName());
    printList(coll);
    }
    
    private static void printList(List<Employee> list) {
    System.out.println("EmpId\tName\tAge");
    for (Employee e: list) {
    System.out.println(e.getEmpId() + "\t" + e.getName() + "\t" + e.getAge());
    }
    }
    }


    Now the result would be as follows. Check whether the employees are sorted correctly by the name String field. You’ll see that these are sorted alphabetically.

    EmpId Name Age
    6 Bill 34
    4 Clerk 16
    5 Frank 28
    1 Jorge 19
    8 Lee 40
    2 Mark 30
    3 Michel 10
    7 Simp 8

    Sorting by empId field

    Even the ordering by empId (previously done using Comparable) can be implemented using Comparator; following class
    does that.

    public class EmpSortByEmpId implements Comparator<Employee>{
    
    public int compare(Employee o1, Employee o2) {
    return o1.getEmpId() - o2.getEmpId();
    }
    }


    Monday, 5 December 2011

    Specifying EntityManagementFactory in xml

    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> 
            <property name="persistenceUnitName" value=my_persistanceunit"/> 
            <property name="dataSource" ref="dataSource"/> 
            <property name="persistenceXmlLocation" value="classpath:META-INF/persistence.xml"/> 
            <property name="loadTimeWeaver"> 
                <bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver"/> 
            </property> 
            <property name="jpaVendorAdapter"> 
                <bean class="org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter">               
                    <property name="showSql" value="true"/>  
                    <property name="generateDdl" value="false"/> 
                    <property name="database" value="ORACLE"/> 
                </bean> 
            </property> 
        </bean>

    persistance.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
    http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
      <!-- <persistence xmlns="http://java.sun.com/xml/ns/persistence"
                 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                 xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
                 version="2.0">-->
      <persistence-unit name="my_persistanceunit" transaction-type="RESOURCE_LOCAL">
        <description>my oracle db Persistence Unit</description>
        <class>com.my.MyEntityClass</class>
        <properties>
      </persistence-unit>
    </persistence>

    Use -javaagent:.lib/spring-instrument-3.0.4.RELEASE.jar  as commandline argument