Friday 15 June 2012

Getting Spring WebApplicationContext object in Spring non managed bean

In spring non managed bean its difficult to initialize the object using the spring framework. For this either you can use

ApplicationContext context = new ClassPathXmlApplicationContext("springapp-servlet.xml");

but using the above code loads the springapp-servlet.xml once again in the memory. In case of standalone application the above code will be fine but in case its a application running on server, loading the xml again will be costlier.So for getting the Spring WebApplicationContext object you can do as code marked in colored background. 


package com.lntinfotech.office.common;


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

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.lntinfotech.office.dao.DAOImpl;
import com.lntinfotech.office.dao.DAOIntf;
import com.lntinfotech.office.domain.JiraTicket;

public class DWRImpl {
private Logger logger = LoggerFactory.getLogger(getClass());

public List<JiraTicket> jiraTicketDetails(String jiraTicket,
HttpServletRequest req, HttpServletResponse res) {
logger.debug("--> jiraTicketDetails(String name)  " + jiraTicket);
List<JiraTicket> list = new ArrayList<JiraTicket>();
try {
WebApplicationContext applicationContext = WebApplicationContextUtils
.getRequiredWebApplicationContext(req.getSession()
.getServletContext());

logger.debug("--> applicationContext   " + applicationContext);

DAOIntf daoIntf = (DAOImpl) applicationContext.getBean("daoIntf");
                        /* the above code gets the DAOImpl object via Spring IOC
                        * and its initializes all the other objects mapped in the spring                              WebApplicationContext
                        * removed unwanted code from the method......
                        */
} catch (Exception e) {
logger.error("Error   : ", e);
return null;
}
logger.debug("<-- jiraTicketDetails(String name)");
return list;
}

}

Custom Converter in Struts 2.3 and utilizing using annotations


In Struts we can write our own custom converter by extending to the StrutsTypeConverter and overriding the methods of the parent class. In the below example i have converted the string value received from the jsp to a Role object using the Struts annotation and the custom converter. I have not kept the Role class over here as you can convert this string to any object as per your requirement. Please don't forget to create a constructor in the POJO class as per the requirement other wise this converter wont work.

I have not overridden the convertToString method of the StrutsTypeConverter. This only because I am not using this conversion. It depends on the developer to override the methods according to the application need.


package com.lntinfotech.office.common;

import java.util.Map;

import org.apache.struts2.util.StrutsTypeConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.lntinfotech.office.domain.Role;
import com.opensymphony.xwork2.conversion.TypeConversionException;

public class RoleConverter extends StrutsTypeConverter {
private Logger logger=LoggerFactory.getLogger(getClass());
@Override
public Role convertFromString(Map context, String[] values, Class toClass){
logger.debug("--> convertFromString String :"+values[0]);
Role role;
if (values != null && values.length > 0 && values[0] != null
&& values[0].length() > 0) {
try {
int id=Integer.valueOf(values[0]);
role=new Role(id);

} catch (Exception e) {
throw new TypeConversionException(e);
}
logger.debug("<-- convertFromString String :"+values[0]);
return role;
}
logger.debug("<-- convertFromString null");
return null;
}

@Override
public String convertToString(Map arg0, Object arg1) {
logger.debug("--> convertToString(Map arg0, Object arg1)");
// TODO Auto-generated method stub
return null;
}

}

In the above class we have created the a converter. So to use this we can use the Struts annotation. In the action class where you need this conversion to happen just annotate as 
@TypeConversion and give the complete path of the converter. I have removed other variables and method as its not necessary for this example. At run time when we are getting the dynamic value from the frontend the below code will call the converter and convert the value to the Role object and process the form as per the code. 

package com.lntinfotech.office.controller;

public class RegistrationAction extends ActionSupport {
private static final long serialVersionUID = 1L;

private Logger logger = LoggerFactory.getLogger(getClass());
        private Role role;

        public Role getRole() {
return role;
}

@TypeConversion(converter = "com.lntinfotech.office.common.RoleConverter")
public void setRole(Role role) {
this.role = role;
}

        @Action(value = "/createuser", results = {
@Result(location = "registrationSuccess.jsp", name = "success"),
@Result(location = "registration.jsp", name = "input"),
@Result(location = "registration.jsp", name = "error") }, className = "registerUser")
public String createUser() {
logger.debug("--> createUser()");
        //method code removed.
        return "success";
}

}

Casting list of array of objects and utilizing the same in jsp


In the below code the DAO class returns a list of objects. Now we need to iterate it and get the values of all the classes separately.
In the debug mode the list of array of object will look like as below.



Now to iterate this kind of list you need to first iterate as usual list and then cast it to Object array. Once its casted then we can get individual POJO classes. Only we need is to cast as per the sequence of the  POJO class. Please find the below code.

List mainMenu = daoIntf.getMenu();
logger.debug("List size "+mainMenu.size());
logger.debug("lsit  : "+mainMenu.get(0));
Iterator itr=mainMenu.iterator();
while(itr.hasNext()){
Object[] str=(Object[])itr.next();
logger.debug("str.length :"+str.length);
//menu=(Menu)str[0];
subMenuRole=(SubMenuRole)str[0];
subMenu=(SubMenu)str[1];
logger.debug("Menu Name :  " +subMenu.getMenu().getName()+ "  SubMenu :  "+subMenu.getName()+" Role : "+subMenuRole.getRole().getName());
}

We are setting the list in the session as we have got from the DAO class. In this list there are 2 POJO classes so we need to iterate and show it in the front end. 

menu.jsp

In the below jsp, please note the <s:iterator> tag is iterating the list which we have set in the session and we have given the list name during iteration is "usermenu". Once we have iterated the list then you can point to the pojo class by using the list name "usermenu[i]" where i is the sequence of pojo class which we have used to iterate the list in the java coding above. 

<%@ taglib prefix="s" uri="/struts-tags"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
</head>

<body>
<div class="arrowlistmenu">
<s:iterator value="%{#session.mainMenuList}" var="usermenu"
status="user">
<s:if test="#user.first  == true">
<c:set var="menuElement" scope="page">
<s:property value="#usermenu[0].name" />
</c:set>
<h3 class="menuheader expandable">${menuElement}</h3>
<ul class="categoryitems">
</s:if>
<c:set var="currentMenuElement" scope="page">
<s:property value="#usermenu[0].name" />
</c:set>

<c:choose>
<c:when test="${currentMenuElement==menuElement}">
<li>
<a href="<%=request.getContextPath() %>/<s:property value="#usermenu[2].link" />.html"><s:property value="#usermenu[2].name" /></a>
</li>

</c:when>
<c:otherwise>
</ul>
<c:set var="menuElement" scope="page">
<s:property value="#usermenu[0].name" />
</c:set>
<h3 class="menuheader expandable">${menuElement}</h3>
<ul class="categoryitems">
<c:if test="${currentMenuElement==menuElement}">
<li>
<a href="<%=request.getContextPath() %>/<s:property value="#usermenu[2].link" />.html"><s:property value="#usermenu[2].name" /></a>
</li>
</c:if>
</c:otherwise>
</c:choose>
<s:if test="#user.last  == true">
</ul>
</s:if>
</s:iterator>
</div>
</body>
</html>


Hope this code helps some of the developers.

Tuesday 12 June 2012

Difference between Comparable and Comparator interface and usage


Comparable interface provide compareTo method which can be used to do sorting in natural order but the Comparator interface provide the method compare which takes two arguments which can be used to sort based on more than one parameter.

For instance I have created a class UserDetails and comparing via Comparable interface and Comparator interface. Using comparator interface I am comparing the fname, in case the fname is equal then the sorting is done based on lName.

------------------------------------------------------------------------
public class UserDetails implements Comparable {
String fName;
String lName;

public UserDetails(String fName, String lName) {
super();
this.fName = fName;
this.lName = lName;
}

public String getfName() {
return fName;
}

public void setfName(String fName) {
this.fName = fName;
}

public String getlName() {
return lName;
}

public void setlName(String lName) {
this.lName = lName;
}

@Override
public int compareTo(Object o) {
// System.out.println("inside compareTo");
return getfName().compareTo(((UserDetails) o).getfName());
}

public String toString() {
return fName + " : " + lName;
}
}

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

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

public class NameComparator implements Comparator {

// this comparator compares the first name and if its same it compares with
// the last name and gives the output
@Override
public int compare(Object o1, Object o2) {
UserDetails userDetails1 = (UserDetails) o1;
UserDetails userDetails2 = (UserDetails) o2;
if (userDetails1.getfName().equals(userDetails1.getfName())) {
return userDetails1.getlName().compareTo(userDetails1.getlName());
}else {
return userDetails1.getfName().compareTo(userDetails1.getfName());
}
}

public static void main(String args[]) {
List<UserDetails> userList = new ArrayList<UserDetails>();
userList.add(new UserDetails("Prajith", "k"));
userList.add(new UserDetails("Prajith", "a"));
userList.add(new UserDetails("Prajith", "A"));
userList.add(new UserDetails("Chandan", "urs"));
userList.add(new UserDetails("Gayatri", "c"));
userList.add(new UserDetails("Geeta", "P"));
userList.add(new UserDetails("Ajay", "kumar"));
userList.add(new UserDetails("Beena", "P"));
userList.add(new UserDetails("Akita", "D"));
/*
*Comparing using the comparator interface implementation 
* In assending order of the  fname and lname,
*/
Collections.sort(userList, new NameComparator());
System.out.println("Name Comparator output :  " + userList);

// In desending order of the  fname and lname
Collections.sort(userList, Collections.reverseOrder(new NameComparator()));
System.out.println("Name Comparator output in decending order  : "
+ userList);
/*
*Comparing using the Comparable interface implementation 
* In assending order of the fname 
*/
Collections.sort(userList);
System.out.println("Name Comparator output using Comparable interface :  " + userList);

// In desending order of the fname
Collections.sort(userList, Collections.reverseOrder());
System.out.println("Name Comparator output using Comparable interface in decending order  : "+ userList);
}

}
------------------------------------------------------------------------

Output of the above program is as below.
------------------------------------------------------------------------

Name Comparator output :  [Prajith : k, Prajith : a, Prajith : A, Chandan : urs, Gayatri : c, Geeta : P, Ajay : kumar, Beena : P, Akita : D]

Name Comparator output in decending order  : [Prajith : k, Prajith : a, Prajith : A, Chandan : urs, Gayatri : c, Geeta : P, Ajay : kumar, Beena : P, Akita : D]

Name Comparator output using Comparable interface :  [Ajay : kumar, Akita : D, Beena : P, Chandan : urs, Gayatri : c, Geeta : P, Prajith : k, Prajith : a, Prajith : A]

Name Comparator output using Comparable interface in decending order  : [Prajith : k, Prajith : a, Prajith : A, Geeta : P, Gayatri : c, Chandan : urs, Beena : P, Akita : D, Ajay : kumar]
------------------------------------------------------------------------

Tuesday 5 June 2012

Java Collections

Collection: Java collection is simply an object that groups multiple elements into a single unit. Collections are used to store, retrieve, manipulate, and communicate aggregate data. 


Benefits of Java Collection framework:
1. Reduces programming efforts.
2. Increase programming speed and quality. 
3. Reduces efforts to design new APIs.
4. Standard collections interface are reusable.


Interfaces:


===========================================================
Collection Interface : 
This interface is root of collection hierarchy. Java platform does't provide any direct implementation of the this interface but provides implementations of more specific subinterfaces, such as Set, List and Queue.  Collection interface is generic. A Collection represents group of objects, known as its elements.


Interface declaration :
public interface Collection<E> extends Iterable<E>


Known Exception : UnsupportedOperationException
===========================================================
Set Interface : 
This interface implements Collections interface. In this type of collections no duplicate values are allowed.  


Interface declaration :
public interface Set <E> extends Collection <E>


Features : 
1. Set does not allow duplicate elements.
2. Set contains at most one null element.
3. Set is unordered collection.
4. Set does not allow positional access.


Known Exception :NullPointerException or ClassCastException
----------------------------------------------------------------------------------------------------------
General purpose Implementation classes of Set Interface are :
1. HashSet :
This class implements the Set interface backed by Hash table.
Class declaration :
public class HastSet <E> extends AbstractSet <E>
implements Set <E>, Cloneable, Serializable
Features : 








1. HashSet does not allow duplicate elements.
2. HashSet contains at most one null element.
3. HashSet is unordered collection.
4. HashSet does not allow positional access.
5. Unsychronized collection set.

HashSet can be converted into a synchronized collection. 
ex.

Set s = Collections.synchronizedSet(new HashSet(.........));
----------------------------------------------------------------------------------------------------------
2. LinkedHashSet :
This class implements the Set interface and extends to HashSet. It maintains the order in which the elements were inserted in this set.

Class declaration :
public class LinkedHashSet <E> extends HashSet <E>
implements Set <E>, Cloneable, Serializable

Features :
It carries all the features of HashSet except the ordering of collection maintained by the LinkedHashSet is the order in which the elements were inserted into it.

HashSet can be converted into a synchronized collection. 
ex.

Set s = Collections.synchronizedSet(new LinkedHashSet(.........));
===========================================================
SortedSet interface :
This interface extends to set interface. This set guarantees that its iterator will traverse the set in ascending element order, sorted according to the natural ordering of its elements.

Class declaration :
public class SortedSet <E> extends Set <E>

Features :
1. Ordered collection set.
2. Does not allow duplicate elements.
3. All element inserted into an sorted set must implement Comparable interface.
----------------------------------------------------------------------------------------------------------
General purpose Implementation classes of SortedSet Interface are :
1. TreeSet :
This set implements SortedSet interface. 
Class declaration :
public class TreeSet <E> extends AbstractSet <E>
implements SortedSet <E>, Cloneable, Serializable
Features :
Carries all the features of the SortedSet interface and this class is unsynchronized.

Can be converted to synchronized collection.
ex.
SortedSet s = Collections.synchronizedSortedSet(new TreeSet(...));

===========================================================
List Interface : 
This interface implements Collections interface. An ordered Collection also known as sequence.








Interface declaration :
public interface List <E> extends Collection <E>








Features : 
1. List allows duplicate elements.
2. List contains null elements.
3. List is a ordered collection.
4. Allows positional access.
5.List interface provides specialized Iterator called ListIterator that allows insertion, replacement and bidirectional access in addition to the normal operations that the iterator interface provides.

Known Exception :NullPointerException or ClassCastException
----------------------------------------------------------------------------------------------------------
General purpose Implementation classes of SortedSet Interface are :
1. ArrayList :

This ArrayList implements List interface. 

Class declaration :
public class ArrayList <E> extends AbstractList <E>
implements List <E>, RandomAccess, Cloneable, Serializable

Features :
1. Resizable-array implementation of the List interface.
2. Permits duplicate elements.
3. Both LinkedList and the ArrayList maintain the order in which the elements are inserted.
4. Roughly equivalent to Vector except that it is unsynchronized.
5.The iterators returned by this class's iterator and listIterator methods are fail-fast.

Can be converted to synchronized collection.
ex.
List list = Collections.synchronizedList(new ArrayList(...));
----------------------------------------------------------------------------------------------------------
2. LinkedList :
Doubly-linked list implementation of List interface. In addition to implementing the List interface the linkedList class provides uniformly named methods to get, remove and insert element at the beginning and end of the list. These operations allow linked lists to be use as a stack, queue, or double-ended queue(deque).Provide better performance if the elements are frequently inserted or deleted within the list. Also implements Queue interface. When accessed via the queue interface, LinkedList behaves as FIFO (First In First Out) Queue.
Class declaration :
public class LinkedList <E> extends AbstractSequentialList <E>
implements List <E>, Queue <E>, Cloneable, Serializable
Features :
1. Resizable-array implementation of the List interface.
2. Permits duplicate elements.
3. Both LinkedList and the ArrayList maintain the order in which the elements are inserted.
4. All of the operations perform as could be expected for a doubly-linked list
5. Unsynchronized list.
Can be converted to synchronized collection.
ex.
List list = Collections.synchronizedList(new LinkedList(...));

===========================================================
Map interface : 
An object which maps keys to value. A map can not contain duplicate values and each key can map to only one value.



Class declaration :
public interface Map <K,V>

Features :
1. Object maps key and value.
2. Map cannot contain duplicate key.
3. Each key can map at most one value.
4. Map at most contain one null key value.
5. Unordered collection.

Exception : NullPointerException, ClassCastException or UnsupportedOpertionException







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

General purpose Implementation classes of Map Interface are :
1. HashMap :
Hash table based implementation of the Map interface.
Class declaration :
public class HashMap <K,V> extends AbstractMap <K,V>
implements Map <K,V>, Cloneable, Serializable
Features : 
1. Unsynchronized map.
2. Unordered map.
3. Allows null key and value at most one.
4. HashMap is roughly equivalent to the Hash table except that it is unsynchronized and allows null.
HashMap can be converted into a synchronized map. 
ex.
Map m = Collections.synchronizedMap(new HashMap(...));
----------------------------------------------------------------------------------------------------------

2. LinkedHashMap :

Hash table and linked list implementation of the Map interface,
 with predictable iteration order. This implementation differs from HashMap in that it maintains a doubly-linked list running through
 all of its entries.  This linked list defines the iteration ordering,
 which is normally the order in which keys were inserted into the map
 (insertion-order).  Note that insertion order is not affected
 if a key is re-inserted into the map.

Class declaration :
public class LinkedHashMap <K,V> extends HashMap <K,V>
implements Map <K,V>
Features : 
1. Unsynchronized map.
2. Maintain the insertion order.
LinkedHashMap can be converted into a synchronized map. 
ex.
Map m = Collections.synchronizedMap(new LinkedHashMap(...));
===========================================================

SortedMap interface : 

A map whose mapping are automatically sorted by key, either in keys natural ordering by a compartor provided when a sortedMap instance is created. It extends Map interface.

Interface declaration :
public interface SortedMap <K,V> extends Map <K,V>
Features :
1. Sorted Key in ascending.
2. EntrySet, KeySet for iterating over map
----------------------------------------------------------------------------------------------------------
General purpose Implementation classes of SortedMap Interface is :

TreeMap :

Implementation of SortedMap interface.

Class declaration :
public class TreeMap <K,V> extends AbstractMap <K,V>
implements SortedMap <K,V>, Cloneable, Serializable
Features : 
1. ascending key order.
2. Iterator are fail-safe.
===========================================================

Legacy Implementations - Older collection classes have
been retrofitted to implement the collection interfaces.

Vector :
Synchronized resizable-array implementation of the List interface
with additional "legacy methods." 

 
Class declaration :
public class Vector <E> extends AbstractList <E>
implements List <E>, RandomAccess, Cloneable, Serializable
Features : 
1. Synchronized resizable array implementation od List interface with additional Legacy methods.
2. Size of vector can grow or shrink as the needed to accommodate adding and removing items after the vector has been created.
----------------------------------------------------------------------------------------------------------

Hashtable :
Synchronized hash table implementation of the Map interface
that does not allow null keys or values, with additional
"legacy methods."

Class declaration :
public class Hashtable <K,V> extends Dictionary <K,V> 
implements Map<K,V>, Cloneable , Serializable

Features:
1. Synchronized Map.
2. Does not allow null values for key and value.
===========================================================

Difference between HashMap & HashTable

1. HashTable is synchronized while HashMap is't.
2. Iterator in HashMap is fail-safe while enumerator in Hashtable is't.
3. HashMap permits null value in it but Hashtable does't.


Difference between ArrayList & LinkedList

1. ArrayList can Random access elements in the list so its faster while accessing, even though the LinkedList has the method get(int index), the LinkedList has to iterate over the list to get the index value so its slower as compared to ArrayList while doing random access.
2. LinkedList is faster while doing the delete and add operations than ArrayList.

Reference of the Collection