Tuesday, December 20, 2011

How to implement a java.lang.Comparable

Java.lang.Comparable is an interface used for sorting collections. The classes implementing Comparables must implement the compareTo() method. Here is a simple example of how a comparable can be used. The example sorts a list of employees on the basis of their age. In this example we have a simple pojo named Employee.java implementing a java.lang.Comparable interface by overriding the compareTo method and a main class to demonstrate the functionality.

Employee.java:

package com.soft.model;

public class Employee implements Comparable{
private String name;
private String department;
private int age;
public String getName() {
            return name;
}
public void setName(String name) {
            this.name = name;
}
public String getDepartment() {
            return department;
}
public void setDepartment(String department) {
            this.department = department;
}
public int getAge() {
            return age;
}
public void setAge(int age) {
            this.age = age;
}
@Override
public int compareTo(Object o) {
            if(this.age>((Employee)o).getAge()){
                        return 1;
            } else if(this.age<((Employee)o).getAge()){
                        return -1;
            } else{
                        return 0;
            }
}
}



ComparableExample:

package com.soft.examples;

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

import com.soft.model.Employee;

public class ComparableExample {
            public static void main(String[] args) {
                        List<Employee> list= new ArrayList<Employee>();
                        Employee e=new Employee();
                        e.setName("Danial Fritz");
                        e.setDepartment("Field Based Development");
                        e.setAge(36);
                        list.add(e);
                        e=new Employee();
                        e.setName("Denis Khoo");
                        e.setDepartment("Project Management");
                        e.setAge(30);
                        list.add(e);
                        e=new Employee();
                        e.setName("Joe Kum");
                        e.setDepartment("Adminstration");
                        e.setAge(40);
                        list.add(e);
                        e=new Employee();
                        e.setName("Anil Kumar");
                        e.setDepartment("Information Technology");
                        e.setAge(26);
                        list.add(e);
                        System.out.println("************ Before Sorting ***********");
                        for (int i=0;i< list.size();i++){
                                    System.out.println(list.get(i).getName()+"-----"+list.get(i).getDepartment()+"-----"+list.get(i).getAge());
                        }
                        System.out.println("************ Age Sorting through Comparable ***********");
                        Collections.sort(list);
                        for (int i=0;i< list.size();i++){
                                    System.out.println(list.get(i).getName()+"-----"+list.get(i).getDepartment()+"-----"+list.get(i).getAge());
                        }
                       
            }
}


This functionality can also be achieved with a java.util.Comparator, the implementation of which is given at
The differences between java.util.Comparator and java.lang.Comparable interfaces are given at



How to implement a java.UtilComparator

Java.Util.Comparator is an interface used for sorting collections. The classes implementing Comparators must implement the compare() method. Here is a simple example of how a comparator can be used. In this example we have a simple pojo named Employee.java, 3 simple Comparator classes and a main class to demonstrate the functionality.

Employee.java:

package com.soft.model;

public class Employee {
private String name;
private String department;
private int age;
public String getName() {
            return name;
}
public void setName(String name) {
            this.name = name;
}
public String getDepartment() {
            return department;
}
public void setDepartment(String department) {
            this.department = department;
}
public int getAge() {
            return age;
}
public void setAge(int age) {
            this.age = age;
}

}

EmployeeNameComparator.java:

package com.soft.model;

import java.util.Comparator;

public class EmployeeNameComparator implements Comparator{

            public int compare(Object obj1, Object obj2) {
                        Employee e1=(Employee)obj1;
                        Employee e2=(Employee)obj2;
                        return e1.getName().compareTo(e2.getName());
            }
}


EmployeeDepartmentComparator.java

package com.soft.model;

import java.util.Comparator;

public class EmployeeDepartmentComparator implements Comparator {

            public int compare(Object obj1, Object obj2) {
                        Employee e1=(Employee)obj1;
                        Employee e2=(Employee)obj2;
                        return e1.getDepartment().compareTo(e2.getDepartment());
            }
}


EmployeeAgeComparator.java:

package com.soft.model;

import java.util.Comparator;

public class EmployeeAgeComparator implements Comparator{

            public int compare(Object obj1, Object obj2) {
                        Employee e1=(Employee)obj1;
                        Employee e2=(Employee)obj2;
                        if(e1.getAge()>e2.getAge()) {
                                    return 1;
                        }else if(e1.getAge()
                                    return -1;
                        } else{
                                    return 0;
                        }
            }
}


ComparatorExample.java:


package com.soft.examples;

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



import com.soft.model.Employee;
import com.soft.model.EmployeeAgeComparator;
import com.soft.model.EmployeeDepartmentComparator;
import com.soft.model.EmployeeMultipleFieldsComparator;
import com.soft.model.EmployeeNameComparator;

public class ComparatorExample {
public static void main(String[] args) {
List<Employee> list= new ArrayList<Employee>();
Employee e=new Employee();
e.setName("Danial Fritz");
e.setDepartment("Field Based Development");
e.setAge(36);
list.add(e);
e=new Employee();
e.setName("Denis Khoo");
e.setDepartment("Project Management");
e.setAge(30);
list.add(e);
e=new Employee();
e.setName("Joe Kum");
e.setDepartment("Adminstration");
e.setAge(40);
list.add(e);
e=new Employee();
e.setName("Anil Kumar");
e.setDepartment("Information Technology");
e.setAge(26);
list.add(e);
           
                       
System.out.println("************ Before Sorting ***********");
for (int i=0;i< list.size();i++){
System.out.println(list.get(i).getName()+"-----"+list.get(i).getDepartment()+"-----"+list.get(i).getAge());
}
System.out.println("************ Name Sorting ***********");
Collections.sort(list, new EmployeeNameComparator());
for (int i=0;i< list.size();i++){
System.out.println(list.get(i).getName()+"-----"+list.get(i).getDepartment()+"-----"+list.get(i).getAge());
}
System.out.println("************ Department Sorting ***********");
Collections.sort(list, new EmployeeDepartmentComparator());
for (int i=0;i< list.size();i++){
System.out.println(list.get(i).getName()+"-----"+list.get(i).getDepartment()+"-----"+list.get(i).getAge());
}
System.out.println("************ Age Sorting ***********");
Collections.sort(list, new EmployeeAgeComparator());
for (int i=0;i< list.size();i++){
System.out.println(list.get(i).getName()+"-----"+list.get(i).getDepartment()+"-----"+list.get(i).getAge());
}
}
}


This sorting can also be done through java.lang.Comparable, the implementation of which is given at
How to implement a java.lang.Comparable

The differences between java.util.Comparator and java.lang.Comparable are given at 





Differences between Comparator and Comparable

Following is a table of the differences between java.util.Comparator and  java.lang.Comparable  interfaces. If I have missed any point, please notify me of that.

The implementation of java.util.Comparator and java.lang.Comparable can be found at
Comparator and
Comparable respectively.



Comparator
Comparable
Package
Java.util
Java.lang
Method
public int compare (Object o1, Object o2)

returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second
public int compareTo(Object o)

returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object
Main Difference
Compares 2 objects provided to it.
Compares this object to the object given.


Used to implement natural ordering of objects. Implemented by String, Date and wrapper classes.


If any class implements Comparable interface 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.


Objects which implement Comparable in Java  can be used as keys in a sorted map or elements in a sorted set for example TreeSet, without specifying any Comparator.
Implementation
Normally, for a bean named Employee(String name, String Department, int Age), if we want to implement a name comparator, we need two classes: bean class(Employee) and comparator class as
public class Employee {} And
public class EmployeeNameComparator implements Comparator{}
For a bean name Employee(String name, String Department, int Age), if we want to implement a name comparable, we do not need to create a new class but instead we will implement it through the same Employee class as
public class Employee implements Comparable{}




Monday, December 19, 2011

PropertyUtils.getProperty: Invoking Java Reflection


I needed a way to automatically call the getters and setters of a class. I knew, this is possible with Java Reflection but how, I did not know. Here is a simple example which shows how we will be able to invoke the generic property getter and setter operations on Java objects.

The example uses a class (Employye.java) and calls the employee.getName() method through reflection using PropertyUtils.getProperty(object, propertyName) and PropertyUtils.getProperty(object, propertyName, propertyValue) methods.

This example depends on the following three jars.
and

Please download trhe jars and add them to your project path.

  1. Employee Class:
Make the employee class as.

public class Employee {
private String name;
public String getName() {
            return name;
}
public void setName(String name) {
            this.name = name;
}
}
  1. Main Class
import org.apache.commons.beanutils.PropertyUtils;
public class PropertyUtilsExample {
            public static void main(String[] args) {
                        Employee e=new Employee();
                        e.setName("John");
                        try{
                        String s=(String)PropertyUtils.getProperty(e,"name");
                        System.out.println(s);
                        PropertyUtils.setProperty(e, "name","Mark");
                        s=(String)PropertyUtils.getProperty(e, "name");
                        System.out.println(s);
                        }catch(Exception ee){
                                   
                        }
            }

}

  1. Output:
Output of the program is

John
Mark  

Hope it helps someone, cheers.

Thursday, December 15, 2011

Populating An Array List on Form Submit in Struts 2.0

I always came across situations where I wanted that if there may have been some way to populate a whole list by a form submit. This feature was there with the request.getParameterValues(), but it would always return a String array. I needed this in the following two situations.
  1. Populating a list on form submit (String, int, float, double, boolean)
  2. Populating a list of keys and their values.


Populating a list on form submit:
            This is very simple. Write the following html in a jsp file say index.jsp

            <form action="submitAction.action" method="post">
                  <input type="text" name="idList" /><br>
                  <input type="text" name="idList" /><br>
                  <input type="text" name="idList" /><br>
                  <input type="text" name="idList" /><br>
                  <input type="text" name="idList" /><br>
                  <input type="text" name="idList" /><br>
                  <input type="submit" value="submit">
            </form>

Yes, Struts 2.0 works with normal html tags but they can only be used for submit purposes and not for display. For display, we will have to use <s:property> tag of Struts 2.0 if we want to use html tags.
Now make an action in struts.xml as
  
<action name="view" class="com.soft.struts.actions.SubmitAction" method="execute">
<result name="view" >view.jsp</result>
</action>

Now create a class named SubmitAction.java and declare a list as a private member in the action class and make its getter/setter as.

private List<int> idList;

public List<int> getIdList() {
      return idList;
}

public void setIdList(List<int> idList) {
      this.idList = idList;
}

That’s it in the action class. Now make a method for the action declared in Struts.xml as follows
      public String execute() throws Exception {
            for(int i=0; i<idList.size;i++){
                  System.out.println(idList.get(i));
}
            return "view";
      }
Make a jsp named view.jsp at the root of the application, so that the action forwards request to it.

That’s it. When you run the application and insert values into the text fields of the index.jsp and then press submit. Those values will automatically be inserted into the idList and you will be able to access the list in execute function.

Populating a list of keys and their values:
            This one is a bit tricky. If you want to populate a list of hidden keys and a list of their values, write the following html

<form action="submitAction.action" method="post">
           <input type="hidden" name="keyList" value=”Address1”/><br>
           <input type="text" name="valueList" /><br>

           <input type="hidden" name="keyList" value=”City”/><br>
           <input type="text" name="valueList" /><br>

           <input type="hidden" name="keyList" value=”State”/><br>
           <input type="text" name="valueList" /><br>

           <input type="submit" value="submit">
</form>

In the action class, declare two private lists and make their getters and setters as
     
private List<String> keyList;
      private List<String> valueList;

      public List<String> getKeyList() {
            return keyList;
      }

      public void setKeyList(List<String> keyList) {
            this.keyList = keyList;
      }

      public List<String> getValueList() {
            return valueList;
      }

      public void setValueList(List<String> valueList) {
            this.valueList = valueList;
      }


When you press submit, the keys will be populated into keyList and the values will be populated into valueList in the same order.

I hope it may help someone out there.

Tuesday, April 26, 2011

Struts 2.0 Installation Tutorial

This is a very basic tutorial for the installation of Struts 2.0. This tutorial is intended for newbies and beginners.




  1. First of all download Struts 2.0 at http://apache.mirrors.pair.com//struts/binaries/struts-2.2.1.1-all.zip
  2. Unzip to a folder.
  3. Go to lib folder in it. Copy the following jars and add those to the lib folder in your project as shown in the figure. The jars to be copied are as under.

    1) commons-fileupload-1.2.1.jar
    2) commons-io-1.3.2.jar
    3) freemarker-2.3.16.jar
    4) ognl-3.0.jar
    5) struts2-core-2.2.1.1.jar
    6) xwork-core-2.2.1.1.jar 

  4.  Also make sure that your project contains javassist-3.7.ga.jar. If not, you can download it from here http://mirrors.ibiblio.org/pub/mirrors/maven2/jboss/javassist/3.7.ga/javassist-3.7.ga.jar
  5. Open web.xml and paste the following lines to it.
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app id="WebApp_9" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">


    <display-name>Struts Blank</display-name>


    <filter>
    <filter-name>struts2</filter-name>
    <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>


    <filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>/*</url-pattern>
    </filter-mapping>


    <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>


    </web-app>
  6. Make a file named struts.xml and place it at the root of the src folder as shown in figure. Copy the following lines to it.
    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">


    <struts>
    <package name="default" namespace="/" extends="struts-default">
    <default-action-ref name="index" />
    <action name="view" class="com.soft.struts.actions.ExampleAction" method="execute">
    <result name="view" >view.jsp</result>
    </action>
    </package>


    <!-- Add packages here -->


    </struts>
  7. I have named the action as view. Now we need to make a class named com.soft.struts.actions.ExampleAction.java and a jsp file named view.jsp. So make a package named com.soft.struts.actions.
  8. Create a class named ExampleAction.java and copy the following lines of code to it.

    package com.soft.struts.actions;
    import com.opensymphony.xwork2.ActionSupport;
    public class ExampleAction extends ActionSupport {
    private String message;
    public String execute() throws Exception {
    message="Hello World";
    return "view";
    }
    public String getMessage() {
    return message;
    }
    public void setMessage(String message) {
    this.message = message;
    }
    }

    The action class should always extend com.opensymphony.xwork2.ActionSupport
  9. Now, make a jsp page named view.jsp at the root of the webRoot folder and copy these lines of code.
    <%@ taglib prefix="s" uri="/struts-tags" %>
    <html>
    <head>
    </head>
    <body>
    <s:property value="message"/>
    </body>
    </html>

    To use struts tags we must always have this line in our jsps
    <%@ taglib prefix="s" uri="/struts-tags" %>
  10. Now, we need to make a link to the view.action. So make a jsp named index.jsp, place it at the root of webRoot and copy the following lines to it.
    <html>
    <head>
    <title>index.jsp</title>
    </head>
    <body>
    <a href="view.action">Test the struts action.</a>
    </body>
    </html>
  11. That is it. Now make a war file of it and deploy it to a tomcat server. When you visit index.jsp, you will see a link, click on that link and it will take you to the view.action.

This simple application declares a string named message(getters and setters are necessary) in class ExampleAction.java and shows it on view.jsp through the struts tag <s:property value="message"/>.

Hope it helps someone.

Monday, April 25, 2011

Text rotation in IE7


It was very difficult for me to rotate text in IE7. I googled a lot but couldnt find any easy solution. Here is a piece of html and css which worked for me.

<style>
div.content {
position: relative;
float:left;
width: 45px;
height: 85px;
border: black 1px solid;
}

.txtblock {
-webkit-transform: rotate(-90deg);
-moz-transform: rotate(-90deg);

-o-transform: rotate(-90deg);

filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=3);
}

.txtblock {
position: absolute;
font-weight:bold;
}
</style>

<div class="content ">
<div id="Div1" class="txtblock">Awkward</div>
</div>


Inside a relative div, make an absolute div and apply the moz webkit transformation on that. The preview is on the right.