Rajinder Menu

Spring - JDBC Integration (Part1)






I would like to know your comments and if you liked the article then please share it on social networking buttons.


Spring - JDBC Integration (Part-2)


Reference : Spring in Action (Third edition)  by Craig Walls


I would like to know your comments and if you liked the article then please share it on social networking buttons.


Core Java


Inheritance Series

  »Inheritance
  »Access Modifiers and Inheritance
  »Overriding
  »Hiding
  »Inheritance and constructors
  »Super Keyword
  »Constructor Chaining

Abstract Methods
Abstract Class

Interface Series

»What is Interface?
»Default Methods
»Static Methods in Interface?

Object Copying

» Copying Object by shallow Copy.
» Copying Object by deep copy.
» Copying Object by Copy Constructors.
» Defensive Copy Part 1:The problem and The Solution.
» Defensive Copy Part 2: Implementing Defensive copy by Copy Constructors.

String Series

» Strings in Java
» What do you understand by Immutablity of strings?
» String Pool
» What do you undesrtand by String interning?
» String equality Check: equals() or == ?
» In how many ways Strings can be compared?
» Why String is declared final?
» Why Strings in Java are immutable?
» Interned String and use of ==
» Hashcode Caching by String
» String Pool is possible due to String Immutability 
» String Concatenation

    √  String Concatenation operator +
    √  Using concat() method
    √  Using append() method
    √  Difference between concat() and + (String concatenation operator) 

Comparable and Comparator

» Comparable and Comparator -Part 1
» Comparable and Comparator -Part 2
» Comparable and Comparator -Part 3
» Comparable and Comparator -Part 4
» When to use Comparable and Comparator in java?
» Sorting based on multiple attributes of a Class.
» Using Comparable interface to compare objects of two different types.
» Difference between Comparable and Comparator Interfaces in java.

How to sort a Set using Collections.sort()


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

public class SetSorting{
public static void main(String args[]){

/*Creating HashSet*/
Set hSet = new HashSet();

Integer[] intArray = new Integer[10];

intArray[0]= new Integer(11);
intArray[1]= new Integer(22);
intArray[2]= new Integer(3);
intArray[3]= new Integer(3);
intArray[4]= new Integer(7);
intArray[5]= new Integer(17);
intArray[6]= new Integer(6);
intArray[7]= new Integer(13);
intArray[8]= new Integer(0);
intArray[9]= new Integer(1);


/*Adding Elements*/
hSet.add(intArray[0]);
hSet.add(intArray[1]);
hSet.add(intArray[2]);
hSet.add(intArray[3]);
hSet.add(intArray[4]);
hSet.add(intArray[5]);
hSet.add(intArray[6]);
hSet.add(intArray[7]);
hSet.add(intArray[8]);
hSet.add(intArray[9]);

System.out.println("Elements Before Sorting:");

for(Integer intVal:hSet){
System.out.println(intVal.intValue());
}

/*Using Collections.sort()*/
List list = new ArrayList(hSet);
Collections.sort(list);

System.out.println("Elements After Sorting:");

for(Integer intVal:list){
System.out.println(intVal.intValue());
}

}
}
Output:

Elements Before Sorting:
0
17
1
3
6
7
22
11
13
Elements After Sorting:
0
1
3
6
7
11
13
17
22


I would like to know your comments and if you liked the article then please share it on social networking buttons.


How to sort HashSet using Arrays.sort()


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

public class prac{
  public static void main(String args[]){

   /*Creating HashSet*/
   Set hSet = new HashSet();

   Integer[] intArray = new Integer[10];

   intArray[0]= new Integer(11);
   intArray[1]= new Integer(22);
   intArray[2]= new Integer(3);
   intArray[3]= new Integer(3);
   intArray[4]= new Integer(7);
   intArray[5]= new Integer(17);
   intArray[6]= new Integer(6);
   intArray[7]= new Integer(13);
   intArray[8]= new Integer(0);
   intArray[9]= new Integer(1);


   /*Adding Elements*/
   hSet.add(intArray[0]);
   hSet.add(intArray[1]);
   hSet.add(intArray[2]);
   hSet.add(intArray[3]);
   hSet.add(intArray[4]);
   hSet.add(intArray[5]);
   hSet.add(intArray[6]);
   hSet.add(intArray[7]);
   hSet.add(intArray[8]);
   hSet.add(intArray[9]);

   System.out.println("Elements Before Sorting:");

   for(Integer intVal:hSet){
     System.out.println(intVal.intValue());
   }

  /*Using Arrays.sort()*/
  Integer[] setArray = new Integer[0];
  setArray = hSet.toArray(setArray);
  Arrays.sort(setArray);
  System.out.println("Elements After Sorting:");

  for(Integer intVal:setArray){
    System.out.println(intVal.intValue());
  }
 }

}

Output:

Elements Before Sorting:
0
17
1
3
6
7
22
11
13
Elements After Sorting:
0
1
3
6
7
11
13
17
22



I would like to know your comments and if you liked the article then please share it on social networking buttons.



In how many ways Set elements can be traversed.(Generic).


Following example shows how to traverse elements of a Set.

Elements of a Set can be traversed mainly in two ways:

1) Using For-Each Loop
2) Using Iterator.

In this example we are using generic version of Set. Non-Generic version of this example is given here.

Note that unlike non-generic version here in for loop and iterator loop we did not need casting.
import java.util.Set;
import java.util.HashSet;
import java.util.Iterator;

public class HashSetExample{
public static void main(String args[]){

/*Creating HashSet*/
Set<Integer> hs = new HashSet<Integer>();

Integer[] intArray = new Integer[5];

intArray[0]= new Integer(1);
intArray[1]= new Integer(2);
intArray[2]= new Integer(3);
intArray[3]= new Integer(4);
intArray[4]= new Integer(5);

/*Adding Elements*/
hs.add(intArray[0]);
hs.add(intArray[1]);
hs.add(intArray[2]);
hs.add(intArray[3]);
hs.add(intArray[4]);


int sum=0;

/*Accessing Set elements using For-Each method*/
for(Integer i:hs){
sum = sum + i.intValue();
System.out.println(i.intValue());
}

System.out.println("Sum="+sum);

Integer intVal;

/*Accessing Set elements using 'iterator'*/
Iterator<Integer> iter = hs.iterator();  /*Note the use of generic iterator*/

while(iter.hasNext()){
intVal=iter.next();
System.out.println(intVal);
}
}
}


I would like to know your comments and if you liked the article then please share it on social networking buttons.


In how many ways Set elements can be traversed (Non-Generic).


Following example shows how to traverse elements of a Set.

Elements of a Set can be traversed mainly in two ways:

1) Using For-Each Loop
2) Using Iterator.

In this example we are using non-generic version of Set. Generic version of this example is given here.
Note that here both in for loop and iterator loop we needed casting.
import java.util.Set;
import java.util.HashSet;
import java.util.Iterator;

public class HashSetExample{
public static void main(String args[]){

/*Creating HashSet*/
Set hs = new HashSet();

Integer[] intArray = new Integer[5];

intArray[0]= new Integer(1);
intArray[1]= new Integer(2);
intArray[2]= new Integer(3);
intArray[3]= new Integer(4);
intArray[4]= new Integer(5);

/*Adding Elements*/
hs.add(intArray[0]);
hs.add(intArray[1]);
hs.add(intArray[2]);
hs.add(intArray[3]);
hs.add(intArray[4]);

int sum=0;

/*Accessing Set elements using For-Each method*/
for(Object o:hs){
/* sum = sum + o; will give error*/
sum = sum + ((Integer)o).intValue();
System.out.println((Integer)o);
}

System.out.println("Sum="+sum);

Integer intVal;
/*Accessing Set elements using 'iterator' provided by Set*/
Iterator iter = hs.iterator();
while(iter.hasNext()){
/*intVal=iter.next(); without casting it will give error.*/
intVal=(Integer)iter.next();
System.out.println(intVal);
}
}
}

I would like to know your comments and if you liked the article then please share it on social networking buttons.


How to use Hashset (Generic).


HashSet is an implementation of Set interface of Java Collections Framework.

Characteristics of HashSet:

1) It does not guarantee any order of its elements when get iterated.

2) It permits null to be one of its elements.

3) It is not synchronized. It is not safe to use HashSet object in multithreaded environment without using proper synchronization.

From Java5 onwards HashSet has been made generic.

Following example shows  how to do basic operations on a HashSet object. In this example we are using non-generic form of HashSet.

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

public class HashSetExample{
public static void main(String args[]){

/*Creating HashSet*/
Set s = new HashSet();

/*Adding Elements*/
s.add("A");
s.add("B");
s.add("C");
s.add("D");

/*Following line will give error as this HashSet can only accept elements of type String*/
//s.add(new Integer(1));  /*Error*/

/*Checking if HashSet contains this element*/
if(s.contains("C"))
System.out.println("HashSet contains C");
else
System.out.println("HashSet does NOT contains C");

if(s.contains("E"))
System.out.println(" HashSet contains E");
else
System.out.println("HashSet does NOT contains E");

/*Obtaining size of HashSet*/
int setSize= s.size();
System.out.println("Size  of Set:"+setSize);

/*Removing element from HashSet*/
boolean b = s.remove("A");
System.out.println("Removed A ?:"+b);
b = s.remove("F");
System.out.println("Removed F?:"+b+ "  (Already F is Not in the set)");

/*Checking size again after removing*/
setSize= s.size();
System.out.println("Size  After removing :"+setSize);

/*Making HashSet Empty*/
b= s.isEmpty();
System.out.println(" Set Empty? :"+b);
s.clear();
b= s.isEmpty();
System.out.println(" Set Empty? :"+b);

/*Checking again the size*/
setSize= s.size();
System.out.println(" Size  After Clearing :"+setSize);
}
}
Output:

HashSet contains C
HashSet does NOT contains E
Size  of Set:4
Removed A ?:true
Removed F?:false  (Already F is Not in the set)
Size  After removing :3
 Set Empty? :false
 Set Empty? :true
 Size  After Clearing :0


I would like to know your comments and if you liked the article then please share it on social networking buttons.


How to use HashSet(Non-Generic).


HashSet is an implmentation of Set interface of Java Collections Framework.

Characteristics of HashSet:

1) It does not guarantee any order of its elements when get iterated.

2) It permits null to be one of its elements.

3) It is not synchronized. It is not safe to use HashSet object in multithreaded environment without using proper synchronization.

From Java5 onwards HashSet has been made generic.

Following example shows  how to do basic operations on a HashSet object. In this example we are using non-generic form of HashSet.

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

public class HashSetExample{
public static void main(String args[]){

/*Creating HashSet*/
Set s = new HashSet();

/*Adding Elements*/
s.add("A");
s.add("B");
s.add("C");
s.add("D");

/*Checking if HashSet contains this element*/
if(s.contains("C"))
System.out.println("HashSet contains C");
else
System.out.println("HashSet does NOT contains C");

if(s.contains("E"))
System.out.println(" HashSet contains E");
else
System.out.println("HashSet does NOT contains E");

/*Obtaining size of HashSet*/
int setSize= s.size();
System.out.println("Size  of Set:"+setSize);

/*Removing element from HashSet*/
boolean b = s.remove("A");
System.out.println("Removed A ?:"+b);
b = s.remove("F");
System.out.println("Removed F?:"+b+ "  (Already F is Not in the set)");

/*Checking size again after removing*/
setSize= s.size();
System.out.println("Size  After removing :"+setSize);

/*Making HashSet Empty*/
b= s.isEmpty();
System.out.println(" Set Empty? :"+b);
s.clear();
b= s.isEmpty();
System.out.println(" Set Empty? :"+b);

/*Checking again the size*/
setSize= s.size();
System.out.println(" Size  After Clearing :"+setSize);
}
}

Output:


HashSet contains C
HashSet does NOT contains E
Size  of Set:4
Removed A ?:true
Removed F?:false  (Already F is Not in the set)
Size  After removing :3
 Set Empty? :false
 Set Empty? :true
 Size  After Clearing :0

I would like to know your comments and if you liked the article then please share it on social networking buttons.


Examples


How to declare After, After-Returning and After-Throwing advice using @AspectJ


This example shows how to use annotations to write an aspect using @AspectJ feature which was introduced in AspectJ 5. With this we do not need to define the advices and pointcuts in XML file.

In following example we have written an aspect named OurAspect.java which contains three advices named ourAfterAdvice(), ourAfterReturningAdvice() and ourAfterThrowingAdvice().

ourAfterAdvice() is a after-advice called every time after a method completes its execution, regardless whether the method has completed its execution successfully or not.

ourAfterReturningAdvice() is a after-returning advice called after a method completes its execution BUT only when method returns succesfully (no exception).

Similarly ourAfterThrowingAdvice() is a after-throwing advice called after a method completes its execution BUT  only when method could not be completed succesfully (i.e exception).

Steps

1) Write EmployeeService interface and its implementation EmployeeServiceImpl.
2) Write MainApp class which use methods of  EmployeeService interface.
3) Write aspect class named OurAspect.java using annotations.
4) Enabling @AspectJ support in XML file

Technologies Used
1) Spring-framework-3.0.6.RELEASE
2) Eclipse Java EE IDE Helios Release (Eclipse version 3.6)
3) Java SE 6




Code
EmployeeService.java

package examples.springaop.anno;

public interface EmployeeService{
   
    public void addEmployee();
    public String getEmployeebyName(String id);
   
}


EmployeeServiceImpl.java

package examples.springaop.anno;

public class EmployeeServiceImpl implements EmployeeService{
   
    public void addEmployee(){
       
        System.out.println("\n\n\naddEmployee() called. One Employee Added !");
    }
    public String getEmployeebyName(String id) throws NullPointerException{
       
        System.out.println("\n\n\ngetEmployeebyName() called.");
       

        if(id==null)
            throw new NullPointerException("ID cannot be null!");
       
        String empName = "Name"+id;
        return empName;
       
    }
   
}

MainApp.java

package examples.springaop.anno;

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

public class MainApp{
public static void main(String args[]){
   
    ApplicationContext appContext = new ClassPathXmlApplicationContext("resources/ApplicationContext.xml");
    EmployeeService empService = (EmployeeService)appContext.getBean("empService");
   
    empService.addEmployee();
   
    empService.getEmployeebyName("id1");
   
    /*Causing exception to be thrown by this method*/
    empService.getEmployeebyName(null);
}
}

OurAspect.java

package examples.springaop.anno;

import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;

@Aspect
public class OurAspect{

@Pointcut("execution(* examples.springaop.xml.EmployeeService.addEmployee(..))")
public void addEmpPointcut(){
   
}

@Pointcut("execution(* examples.springaop.xml.EmployeeService.getEmployeebyName(..))")
public void getEmpPointcut(){
   
}

@After("addEmpPointcut()|| getEmpPointcut()")
public void ourAfterAdvice(){
    System.out.println("This is After Advice, called after the method completion (in both Normal or Exceptional completion).");
   
 }

@AfterReturning("addEmpPointcut() || getEmpPointcut()")
public void ourAfterReturningAdvice(){
    System.out.println("This is After Returning Advice, called only when method completes its execution succesfully(i.e NO Exception)");
   
}

@AfterThrowing("addEmpPointcut()|| getEmpPointcut()")
public void ourAfterThrowingAdvice(){
    System.out.println("This is After Throwing Advice, called when method COULD NOT be completed succesfully(i.e Exception thrown)");
   
}

}

Here we have used @Aspect annotation on class OurAspect  to declare it as an aspect.

Next we have used @Pointcut annotation to declare pointcuts. @Pointcut is declared on methods. Here method names will be treated as pointcut ids, similar to what we do in

tag.(see example).

We have used @After, @AfterReturning and @AfterThrowing annotations to mark after, after-returning and after-throwing advices respectively.

Note how multiple pointcuts have been applied to single advice using ||. This means corresponding advice will be applied  to both methods defined in that @Pointcut annotation.

ApplicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="https://www.springframework.org/schema/beans"

xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"

xmlns:aop="https://www.springframework.org/schema/aop"

xsi:schemaLocation="https://www.springframework.org/schema/beans

https://www.springframework.org/schema/beans/spring-beans-3.0.xsd

https://www.springframework.org/schema/aop

https://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

<bean id="empService" class="examples.springaop.anno.EmployeeServiceImpl"/>

<bean id="empAspect" class="examples.springaop.anno.OurAspect"/>

<aop:aspectj-autoproxy/>

</beans>

For enabling @AspectJ support we have added following in XML file

<aop:aspectj-autoproxy/>

This will create proxies for those methods which are specified in pointcuts.

Note here pointcuts and advices are not defined in XMl file.

Output

addEmployee() called. One Employee Added !
This is After Advice, called after the method completion (in both Normal or Exceptional completion).
This is After Returning Advice, called only when method completes its execution succesfully(i.e NO Exception)

getEmployeebyName() called.
This is After Advice, called after the method completion (in both Normal or Exceptional completion).
This is After Returning Advice, called only when method completes its execution succesfully(i.e NO Exception)

getEmployeebyName() called.
This is After Advice, called after the method completion (in both Normal or Exceptional completion).
This is After Throwing Advice, called when method COULD NOT be completed succesfully(i.e Exception thrown)
Exception in thread "main" java.lang.NullPointerException: ID cannot be null!
    at examples.springaop.xml.EmployeeServiceImpl.getEmployeebyName(EmployeeServiceImpl.java:15)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)



Note the advices called after the three method calls in output.

We have applied after, after-returning and after-throwing advices to both methods. But not all advices have been called every time.

Since addEmployee()has not thrown  any exception so after-throwing advice is not been called after this method.

Similarly first call of getEmployeebyName() method returns successfully so after-returning advice got called but not the after-throwing advice. 

But second call to getEmployeebyName()has thrown exception. Here we have intentionally thrown the exception. As method has not completed its execution succesfully so after-throwing advice has been called not the after-returning advice.

Also note that after advice is called every time.

Jars Used

org.springframework.context-3.0.6.RELEASE.jar
org.springframework.core-3.0.6.RELEASE.jar
org.springframework.beans-3.0.6.RELEASE.jar
commons-logging-1.1.1.jar
org.springframework.asm-3.0.6.RELEASE.jar
org.springframework.aop-3.0.6.RELEASE.jar
com.springsource.org.aopalliance-1.0.0.jar
org.springframework.expression-3.0.6.RELEASE.jar
aspectjweaver-1.6.8.jar


I would like to know your comments and if you liked the article then please share it on social networking buttons.


How to declare Before and After Advice


This example shows how to write an aspect as a simple java class (i.e a POJO) with no AOP related info defined in it. AOP related info is defined declaratively in XML configuration file.

Following example contains an aspect named OurAspect.java which contains two advices named ourBeforeAdvice() and ourAfterAdvice(). These advices are applied to the methods (pointcuts) defined in XML file.

ourBeforeAdvice() is a before-advice called every time before a method starts its execution and ourAfterAdvice() is a after-advice called every time after a method completes its execution.

Steps

1. Write EmployeeService interface and its implementation EmployeeServiceImpl.
2. Write MainApp class which uses the methods of  EmployeeService interface.
3. Write an aspect class named OurAspect.java.
4. Define pointcuts(methods) where advices would be applied in XML file.

Technologies Used

1) Spring-framework-3.0.6.RELEASE
2) Eclipse Java EE IDE Helios Release (Eclipse version 3.6)
3) Java SE 6




Code

EmployeeService.java

package examples.springaop.xml;

public interface EmployeeService{
   
    public void addEmployee();
    public String getEmployeebyName(String id);
   
}

EmployeeServiceImpl.java

package examples.springaop.xml;

public class EmployeeServiceImpl implements EmployeeService{
   
    public void addEmployee(){
       
        System.out.println("addEmployee() called ! One Employee Added !");
    }
    public String getEmployeebyName(String id){
       
        String empName = "Name"+id;
        return empName;
       
    }
   
}

MainApp.java

package examples.springaop.xml;

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



public class MainApp{
public static void main(String args[]){
   
    ApplicationContext appContext = new ClassPathXmlApplicationContext("resources/ApplicationContext.xml");
    EmployeeService empService = (EmployeeService)appContext.getBean("empService");
   
    empService.addEmployee();
}
}

OurAspect.java

package examples.springaop.xml;

public class OurAspect{
   
 public void ourBeforeAdvice(){
     System.out.println("\n\nThis is Before Advice, called before the method.\n");
   
 }

public void ourAfterAdvice(){
    System.out.println("\nThis is After Advice, called after the method.");
   
 }
}

ApplicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="https://www.springframework.org/schema/beans"

xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"

xmlns:aop="https://www.springframework.org/schema/aop"

xsi:schemaLocation="https://www.springframework.org/schema/beans

https://www.springframework.org/schema/beans/spring-beans-3.0.xsd

https://www.springframework.org/schema/aop

https://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

<bean id="empService" class="examples.springaop.xml.EmployeeServiceImpl"/>

<bean id="empAspect" class="examples.springaop.xml.OurAspect"/>

<aop:config>

    <aop:aspect ref="empAspect">

    <aop:before pointcut= "execution(* examples.springaop.xml.EmployeeService.addEmployee(..))"

        method="ourBeforeAdvice"/>

<aop:after pointcut= "execution(* examples.springaop.xml.EmployeeService.addEmployee(..))"

        method="ourAfterAdvice"/>

</aop:aspect>

</aop:config>

</beans>


Output

    This is Before Advice, called before the method.

     addEmployee() called ! One Employee Added !

    This is After Advice, called after the method.


Jars Used
org.springframework.context-3.0.6.RELEASE.jar
org.springframework.core-3.0.6.RELEASE.jar
org.springframework.beans-3.0.6.RELEASE.jar
commons-logging-1.1.1.jar
org.springframework.asm-3.0.6.RELEASE.jar
org.springframework.aop-3.0.6.RELEASE.jar
com.springsource.org.aopalliance-1.0.0.jar
org.springframework.expression-3.0.6.RELEASE.jar
aspectjweaver-1.6.8.jar


I would like to know your comments and if you liked the article then please share it on social networking buttons.