Thursday, 18 April 2013

Object to JSON Conversion

Below code uses Jackson Json API to convert an Object into a JSON String

We will be converting Person class which has Company instance composed in it.


class Person {
 String name;
 int age;
 Company company;
 
 /**
  * @return the company
  */
 public Company getCompany() {
  return company;
 }
 
 public Person(String name, int age, Company company){
  this.name = name;
  this.age = age;
  this.company = company;
 }
 
 /**
  * @return the age
  */
 public int getAge() {
  return age;
 }
 
 /**
  * @return the name
  */
 public String getName() {
  return name;
 }
}

class Company {
 String companyName;
 float salary;
 
 public Company(String companyName, float salary) {
  this.companyName=companyName;
  this.salary = salary;
 }
 
 /**
  * @return the salary
  */
 public float getSalary() {
  return salary;
 }
 /**
  * @return the companyName
  */
 public String getCompanyName() {
  return companyName;
 }
}


If we don't create the getter methods then the below exception will come:

Exception in thread "main" org.codehaus.jackson.map.JsonMappingException: No serializer found for class com.blogspot.javasampleprogram.Person and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS) )

package com.blogspot.javasampleprogram;

import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;

import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.map.ObjectMapper;

/**
 * @author http://java-sample-program.blogspot.in/  
 * Object to Json Conversion
 */
public class JsonStringGenerator {
 

 /**
  * Method to get a JSON string representing the object
  * supplied.
  * @param object for which JSON string is required
  * @return Json String
  * @throws IOException
  */
 public static String createJsonString(Object object) throws IOException {
  Writer writer = new StringWriter();
  JsonFactory factory = new JsonFactory();
  JsonGenerator generator = factory.createJsonGenerator(writer);
  generator.setCodec(new ObjectMapper());
  generator.writeObject(object);
  generator.close();
  System.out.println("Json string " + writer.toString());
  return writer.toString();
 }
 
 public static void main(String[] args)  throws IOException {
  Company company = new Company("ABC", 15001.90f);
  Person p1 = new Person("Jason Stathom", 36, company);
  createJsonString(p1);
 }
 
}

Result: {"company":{"salary":15001.9,"companyName":"ABC"},"age":36,"name":"Jason Stathom"}

We will have to add the following Jackson API dependency:


<dependency>
  <groupId>org.codehaus.jackson</groupId>
  <artifactId>com.springsource.org.codehaus.jackson.mapper</artifactId>
  <version>1.4.3</version>
</dependency>

Wednesday, 17 April 2013

HashMap to JSON String

Below code uses Jackson Json API to convert a HashMap into a JSON String


package com.blogspot.javasampleprogram;

import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.HashMap;

import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.map.ObjectMapper;

/**
 * @author http://java-sample-program.blogspot.in/  
 * HashMap to Json String generator
 */
public class JsonStringGenerator {
 

 /**
  * Method to convert map into json format
  * @param map with data to be converted into json
  * @return json string
  */
 public static String createJsonString(HashMap jsonMap) throws IOException {
  System.out.println("Map:"+jsonMap);
  Writer writer = new StringWriter();
  JsonGenerator jsonGenerator = new JsonFactory().
        createJsonGenerator(writer);
  ObjectMapper mapper = new ObjectMapper();
  mapper.writeValue(jsonGenerator, jsonMap);
  jsonGenerator.close();
  System.out.println(writer.toString());
  return writer.toString();
 }
 
 public static void main(String[] args)  throws IOException {
  HashMap<String, String> map = new HashMap<String, String>();
  map.put("1", "Jason Stathom");
  map.put("2", "Brad Pitt");
  map.put("3", "Angelina");
  createJsonString(map);
 }
 
}

Result: {"3":"Angelina","2":"Brad Pitt","1":"Jason Stathom"}

We will have to add following dependency:

<dependency>
  <groupId>org.codehaus.jackson</groupId>
  <artifactId>com.springsource.org.codehaus.jackson.mapper</artifactId>
  <version>1.4.3</version>
</dependency>

Thursday, 21 March 2013

How to write CLOB fields

Below code shows the way to write CLOB fields to the database:

import java.io.ByteArrayInputStream;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * @author http://java-sample-program.blogspot.in/  
 * Write CLOB to database
 */
public class ClobTest {

 public static void main(String[] args) throws Exception{
 Connection con = null;
 CallableStatement stmt = null;
 
 try {
 
  Class.forName("oracle.jdbc.driver.OracleDriver");
  con = DriverManager.getConnection("jdbc:oracle:thin:@IPAddress:Port:Database",
    "username","password");
  stmt = con.prepareCall("{call CLOBTEST.saveClob(?)}");
  String xmlString = "1234567890";
  
  stmt.setAsciiStream(1,new ByteArrayInputStream(xmlString.getBytes()),
     xmlString.getBytes().length);
  
  stmt.execute();
  System.out.println("executed successfully");
  
 }catch(Exception e){
  e.printStackTrace();
 } finally {
  try{
   if(stmt != null){ 
    stmt.close();
   }
   if(con!= null){
    con.close();     
   }
  }catch (SQLException e) {
   e.printStackTrace();
  }
 }
 
 }

}

CLOB to String Conversion

Below code shows the two ways to convert database CLOB to String code.

1) Convert CLOB to String using BufferedReader:

import java.io.BufferedReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author http://java-sample-program.blogspot.in/  
 * Convert CLOB to String using BufferedReader
 */
public class ClobTest {

 public static void main(String[] args) throws Exception{
 Connection con = null;
 PreparedStatement pstmt = null;
 ResultSet rs = null;
 
 try {
 
  Class.forName("oracle.jdbc.driver.OracleDriver");
  con = DriverManager.getConnection("jdbc:oracle:thin:@IPAddress:Port:Database",
    "username","password");
  pstmt = con.prepareStatement("SELECT clobCol FROM TableName");
  rs = pstmt.executeQuery();
  
  while(rs.next()){   
   
   StringBuffer strOut = new StringBuffer();
   String aux;
   try {
    BufferedReader br = new BufferedReader(rs.getClob("clobCol").
      getCharacterStream());
    while ((aux=br.readLine())!=null) {
     strOut.append(aux);
     strOut.append(System.getProperty("line.separator"));
    }
   }catch (Exception e) {
    e.printStackTrace();
   }
   String clobStr = strOut.toString();
   System.out.println(clobStr);
  } 
  
 }catch(Exception e){
  e.printStackTrace();
 } finally {
  try{
   if(pstmt != null){ 
    pstmt.close();
   }
   if(rs!= null){ 
    rs.close();
   }     
   if(con!= null){
    con.close();     
   }
  }catch (SQLException e) {
   e.printStackTrace();
  }
 }
 
 }
 
}

Use the above method if a very large Clob can be returned by the database.

2) Convert CLOB to String using getSubString() method:

import java.io.BufferedReader;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author http://java-sample-program.blogspot.in/  
 * Convert CLOB to String using getSubString() method
 */
public class ClobTest {

 public static void main(String[] args) throws Exception{
 Connection con = null;
 PreparedStatement pstmt = null;
 ResultSet rs = null;
 
 try {
 
  Class.forName("oracle.jdbc.driver.OracleDriver");
  con = DriverManager.getConnection("jdbc:oracle:thin:@IPAddress:Port:Database",
    "username","password");
  pstmt = con.prepareStatement("SELECT clobCol FROM TableName");
  rs = pstmt.executeQuery();
  
  while(rs.next()){   
   Clob clob = rs.getClob("clobCol");
   if (clob != null) {  
    String clobStr = clob.getSubString(1, (int) clob.length());
    System.out.println(clobStr);
   }
  } 
  
 }catch(Exception e){
  e.printStackTrace();
 } finally {
  try{
   if(pstmt != null){ 
    pstmt.close();
   }
   if(rs!= null){ 
    rs.close();
   }     
   if(con!= null){
    con.close();     
   }
  }catch (SQLException e) {
   e.printStackTrace();
  }
 }
 
 }
 
}

Sunday, 2 December 2012

Copy as HTML Eclipse plugin

'Copy as HTML' eclipse plugin
'Copy as HTML' eclipse plugin
Usually we face problems while copying our code to many of the blog sites or forums, as they require us to convert our code to html form so that it can be best displayed in its pure form.

The Copy as HTML eclipse IDE plugin allows us to directly copy our code as HTML and paste it to our blogs or forums without any formatting.
Download Copy as HTML eclipse plugin Copy as HTML eclipse plugin

Steps to install the plugin:
  1. Download the Copy as HTML eclipse plugin
  2. Copy it to the 'dropins' folder of your eclipse installation
  3. If 'dropins' folder is not present then copy it to the 'plugins' folder of your eclipse installation
  4. Restart eclipse IDE
  5. That's it
`Steps to Use
  1. Select the code or text to be copied
  2. Select 'Copy as HTML' option or press 'cntrl+shift+3'
  3. Paste it your superb blog
Eclipse Plugin - Copy as HTML
Copy as HTML

Modify default settings of Copy as HTML Eclipse plugin

The Copy as HTML eclipse plugin gives you some flexibility to make modifications to its default settings which require some changes to the plugin.properties file that comes with the plugin jar file.

Steps to modify default settings in windows (having Winrar installed):
  1. Close eclipse and take the backup of the jar file (in case something goes wrong, we can always replace the file)
  2. Open the jar file using Winrar
  3. Double click on plugin.properties file
  4. Make and Save changes to the file and close it
  5. Winrar will prompt you to confirm the updation. Press Yes.
  6. Close Winrar and restart eclipse
In case Winrar is not installed on your system then we can use the 'jar' command utility to extract the contents, make changes in the plugin.properties file and then again create a jar file.

There are 3 properties that can be changed:
  1. com.blogspot.javasampleprogram.fontsize - valid values are 10px,11px etc
  2. com.blogspot.javasampleprogram.codeblockheight - valid values are auto, 100%, 100px, 200px etc
  3. com.blogspot.javasampleprogram.alternatebackground - valid values are Y or N. Set Y if you need alternate background else N
Please do let me know, if you face any issues or want any new feature to be added. 

Sunday, 18 November 2012

Spring AOP Advice Ordering

Spring AOP Advice Ordering
Spring AOP Advice Ordering

If you are new to spring AOP. You can go through my previous blog:

Now before we create the sample code for Spring AOP advice ordering, lets see what Spring framework website says on advice ordering:

What happens when multiple pieces of advice all want to run at the same join point? 

Spring AOP follows the same precedence rules as AspectJ to determine the order of advice execution. The highest precedence advice runs first "on the way in" (so given two pieces of before advice, the one with highest precedence runs first). "On the way out" from a join point, the highest precedence advice runs last (so given two pieces of after advice, the one with the highest precedence will run second).
When two pieces of advice defined in different aspects both need to run at the same join point, unless you specify otherwise the order of execution is undefined. You can control the order of execution by specifying precedence. This is done in the normal Spring way by either implementing the org.springframework.core.Ordered interface in the aspect class or annotating it with the Order annotation. Given two aspects, the aspect returning the lower value from Ordered.getValue() (or the annotation value) has the higher precedence.
When two pieces of advice defined in the same aspect both need to run at the same join point, the ordering is undefined (since there is no way to retrieve the declaration order via reflection for javac-compiled classes). Consider collapsing such advice methods into one advice method per join point in each aspect class, or refactor the pieces of advice into separate aspect classes - which can be ordered at the aspect level.

Spring AOP Advice Ordering Example

In the example below we are trying to use all the 5 advices on the same joinpoint. 
We are going to use the same example that we used in our previous blog on Spring AOP.
We are taking a scenario where there is a small party and different advices are getting used to cater different situations:
  1. @Before advice - Will be used for authentication of guests. Only people in guest list can come. 
  2. @Around advice - Will be used for Audit. Guest's entry and exit timings should be noted. 
  3. @AfterThrowing - Will be used for Exception handling. If a guest gets too drunk then call a cab. 
  4. @AfterReturning - Will be used to Check Normal flow. Give good bye gift to guests who didn't get too drunk.
  5. @After - Will be used to handle both normal or Exception conditions. Send a thank you email to all the guest irrespective of whether they were drunk or not.
We want that the advices to be executed in the following order.
@Before advice
@Around advice
@AfterThrowing
@AfterReturning
@After


Folder structure of the project:


Spring AOP Advice Ordering
Spring AOP Advice Ordering

Lets start with creating a PartyService with letsParty() method to show the use of advices.
 package com.blogspot.javasampleprogram.service;  
 /**  
  * @author http://java-sample-program.blogspot.in/  
  */  
 public interface IPartyService {  
      public void letsParty(PartyPeople people) throws Exception;  
 }  
PartyService Implementation class
 package com.blogspot.javasampleprogram.service;  
 import com.blogspot.javasampleprogram.exception.GotTooDrunkException;  
 /**  
  * @author http://java-sample-program.blogspot.in/  
  */  
 public class PartyServiceImpl implements IPartyService {  
      /**  
       * guests wait for some time in party then leave.  
       * If a guest gets too drunk then they are taken out.  
       */  
      public void letsParty(PartyPeople people) throws Exception {  
                Thread.sleep(200);  
                // if people get drunk then get them out
                if (people.isDrunk()) {  
                     throw new GotTooDrunkException();  
                }  
      }  
 }  

Data transfer object that stores the information of people coming in.
 package com.blogspot.javasampleprogram.service;  
 import java.io.Serializable;  
 /**  
  * @author http://java-sample-program.blogspot.in/  
  */  
 public class PartyPeople implements Serializable {  
      public PartyPeople(){};  
      
      public PartyPeople(String name){this.name = name;};  
      
      public PartyPeople(String name, boolean isDrunk) {
        this.name = name; 
        this.drunk = isDrunk;
      };  
      public String name;  
      public boolean drunk;  
      
     /**  
       * @return the drunk  
       */  
      public boolean isDrunk() {  
           return drunk;  
      }  
      /**  
       * @param drunk the drunk to set  
       */  
      public void setDrunk(boolean drunk) {  
           this.drunk = drunk;  
      }  
      /**  
       * @return the name  
       */  
      public String getName() {  
           return name;  
      }  
      /**  
       * @param name the name to set  
       */  
      public void setName(String name) {  
           this.name = name;  
      }  
 }  
Exception thrown when the guest is not in guestlist
 package com.blogspot.javasampleprogram.exception;  
 /**  
  * @author http://java-sample-program.blogspot.in/  
  */  
 public class NotOnListException extends Exception {  
      public NotOnListException() {  
           super();  
      }  
      public NotOnListException(String message) {  
           super(message);  
      }  
 }  
Exception thrown when the guest becomes too drunk
 package com.blogspot.javasampleprogram.exception;  
 /**  
  * @author http://java-sample-program.blogspot.in/  
  */  
 public class GotTooDrunkException extends Exception {  
      public GotTooDrunkException() {  
           super();  
      }  
      public GotTooDrunkException(String message) {  
           super(message);  
      }  
 }  

Spring AOP advices :

  1. Before Advice
Before advice is given Order (1) as it should be executed before the Around advice.
Note: On the way in to a joinpoint, the advice with lowest Order value gets executed first.

 package com.blogspot.javasampleprogram.aspect;  

 import org.aspectj.lang.JoinPoint;  
 import org.aspectj.lang.annotation.Aspect;  
 import org.aspectj.lang.annotation.Before;  
 import org.springframework.core.annotation.Order;  
 import com.blogspot.javasampleprogram.exception.NotOnListException;  
 import com.blogspot.javasampleprogram.service.PartyPeople;  

 /**  
  * @author http://java-sample-program.blogspot.in/  
  */  

 @Aspect  
 @Order(value=1)  
 public class BeforePartyAspect {  

      /**  
       * Advice to log entering and exit of guests.  
       * @param proceedingJoinPoint  
       * @return  
       */  
      @Before(value="(execution(* com.blogspot.javasampleprogram.service.*.*(..)))")  
      public void checkGuestList(JoinPoint joinPoint) throws NotOnListException {  

           // get method arguments   
           Object[] args = joinPoint.getArgs();  

           // getting the method argument using Joinpoint API  
           PartyPeople partyPeople = (PartyPeople)args[0];  

           boolean onGuestList = false;  
           // checking guest list  
           for (int i = 0; i < partyPeoples.length; i++) {  
                if (partyPeople.getName().equals(partyPeoples[i].getName())) {  
                     onGuestList = true;  
                     break;  
                }  
           }  

           if (!onGuestList) {  
                throw new NotOnListException(partyPeople.getName()+" trying to gatecrash.");  
           }  
      }  

      PartyPeople[] partyPeoples = {new PartyPeople("jason statham"),  
                                          new PartyPeople("john travolta"),            
                                          new PartyPeople("arnold"),            
                                          new PartyPeople("christian bale"),            
                                          new PartyPeople("Vin Diesel")  
      };  
 }  


2. Around Advice

Around advice is given Order (2) as it should be executed after the Before advice

 package com.blogspot.javasampleprogram.aspect;  
 
 import java.util.Calendar;  
 import org.aspectj.lang.ProceedingJoinPoint;  
 import org.aspectj.lang.annotation.Around;  
 import org.aspectj.lang.annotation.Aspect;  
 import org.springframework.core.annotation.Order;  
 import com.blogspot.javasampleprogram.service.PartyPeople;  
 
 /**  
  * @author http://java-sample-program.blogspot.in/  
  */  
 @Aspect  
 @Order(value=2)  
 public class AroundPartyAspect {  
 
      /**  
       * Advice to log entering and exit of guests.  
       * @param proceedingJoinPoint  
       * @return  
       * @throws Throwable   
       */  
      @Around(value="(execution(* com.blogspot.javasampleprogram.service.*.*(..)))")  
      public void audit(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {  
 
           // get method arguments   
           Object[] args = proceedingJoinPoint.getArgs();  
 
           // getting the method argument using Joinpoint API  
           PartyPeople partyPeople = (PartyPeople)args[0];  
 
          //auditing entry and exit  
           System.out.println(partyPeople.getName()+" came in at "+Calendar.getInstance().get(Calendar.HOUR_OF_DAY)+":"+Calendar.getInstance().get(Calendar.MINUTE));  

           try {  
                proceedingJoinPoint.proceed();  
           } finally {  
                // exit time kept in finally block so that even if there is any exception from method  
                // the exit time still gets audited  
                System.out.println(partyPeople.getName()+" left at "+Calendar.getInstance().get(Calendar.HOUR_OF_DAY)+":"+Calendar.getInstance().get(Calendar.MINUTE));  
           }  
      }  
 }  

3. AfterThrowing advice

Afterthrowing advice is given Order (5) as it should be executed first after the exit from the join point.
Note: On the way out from the joinpoint, the advice with highest Order value gets executed first.
 package com.blogspot.javasampleprogram.aspect;  

 import org.aspectj.lang.JoinPoint;  
 import org.aspectj.lang.annotation.AfterThrowing;  
 import org.aspectj.lang.annotation.Aspect;  
 import org.springframework.core.annotation.Order;  
 import com.blogspot.javasampleprogram.exception.GotTooDrunkException;  
 import com.blogspot.javasampleprogram.service.PartyPeople;  

 /**  
  * @author http://java-sample-program.blogspot.in/  
  */  

 @Aspect  
 @Order(5)  
 public class AfterThrowingPartyAspect {  

      /**  
       * Advice to send thank You Email to all guests, irrespective of whether they were   
       * too drunk or not.  
       * @param joinPoint  
       */  
      @AfterThrowing(value="(execution(* com.blogspot.javasampleprogram.service.*.*(..)))", throwing="exception")  
      public void callCabForDrunkGuests(JoinPoint joinPoint, Exception exception) {  

           if (exception instanceof GotTooDrunkException) {  
                // get method arguments   
                Object[] args = joinPoint.getArgs();  
                // getting the method argument using Joinpoint API  
                PartyPeople partyPeople = (PartyPeople)args[0];  
                System.out.println(partyPeople.getName()+" got too drunk. Calling cab!!");  
           }   
           // No need to handle NotOnListException as exceptions thrown by @Before advice never come to @AfterThrowing  
      }  
 }  

4. AfterReturning Advice

AfterReturning advice is given Order(4) as it should be executed after AfterThrowing advice and before After advice. 
 package com.blogspot.javasampleprogram.aspect;  

 import org.aspectj.lang.JoinPoint;  
 import org.aspectj.lang.annotation.AfterReturning;  
 import org.aspectj.lang.annotation.Aspect;  
 import org.springframework.core.annotation.Order;  
 import com.blogspot.javasampleprogram.service.PartyPeople;  

 /**  
  * @author http://java-sample-program.blogspot.in/  
  */  

 @Aspect  
 @Order(4)  
 public class AfterReturningPartyAspect {  

      /**  
       * Advice to give party gift to guests who came out without getting too drunk.  
       * @param joinPoint  
       */  
      @AfterReturning(value="(execution(* com.blogspot.javasampleprogram.service.*.*(..)))")  
      public void givePartyGift(JoinPoint joinPoint) {  

           // get method arguments   
           Object[] args = joinPoint.getArgs();  

           // getting the method argument using Joinpoint API  
           PartyPeople partyPeople = (PartyPeople)args[0];  
           System.out.println(partyPeople.getName()+" got party gift.");  
      }  
 }  

5. After advice

After advice is given Order(3) as it should be executed last on the way out.
 package com.blogspot.javasampleprogram.aspect;  

 import org.aspectj.lang.JoinPoint;  
 import org.aspectj.lang.annotation.After;  
 import org.aspectj.lang.annotation.Aspect;  
 import org.springframework.core.annotation.Order;  
 import com.blogspot.javasampleprogram.service.PartyPeople;  

 /**  
  * @author http://java-sample-program.blogspot.in/  
  */  

 @Aspect  
 @Order(3)  
 public class AfterPartyAspect {  

      /**  
       * Advice to send thank You Email to all guests, irrespective of whether they were   
       * too drunk or not.  
       * @param joinPoint  
       */  
      @After(value="(execution(* com.blogspot.javasampleprogram.service.*.*(..)))")  
      public void sendThankYouEmail(JoinPoint joinPoint) {  
 
          // get method arguments   
          Object[] args = joinPoint.getArgs();  

          // getting the method argument using Joinpoint API  
          PartyPeople partyPeople = (PartyPeople)args[0];  
          System.out.println("Sent thank you email to "+partyPeople.getName()+". Thank you "+partyPeople.getName()+" for coming to "+joinPoint.getSignature().getName());  
      }  
 }  

Spring configuration file
 <?xml version="1.0" encoding="UTF-8" standalone="no"?>   
  <beans xmlns="http://www.springframework.org/schema/beans"   
    xmlns:aop="http://www.springframework.org/schema/aop"   
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
    xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd   
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">   

    <!-- The @AspectJ support is enabled by including the below tag -->     
    <aop:aspectj-autoproxy/>   

    <bean id="partyService"    
     class="com.blogspot.javasampleprogram.service.PartyServiceImpl" />   

   <!-- Aspect -->  
      <bean id="beforePartyAspect" class="com.blogspot.javasampleprogram.aspect.BeforePartyAspect" />  
      <bean id="aroundPartyAspect" class="com.blogspot.javasampleprogram.aspect.AroundPartyAspect" />  
      <bean id="afterThrowingPartyAspect" class="com.blogspot.javasampleprogram.aspect.AfterThrowingPartyAspect" />  
      <bean id="afterReturningPartyAspect" class="com.blogspot.javasampleprogram.aspect.AfterReturningPartyAspect" />  
      <bean id="afterPartyAspect" class="com.blogspot.javasampleprogram.aspect.AfterPartyAspect" />  

  </beans>   

Run the PartyTest to see who gets party gift and who got drunk:
 package com.blogspot.javasampleprogram.test;  

 import org.springframework.context.ApplicationContext;  
 import org.springframework.context.support.ClassPathXmlApplicationContext;  
 import com.blogspot.javasampleprogram.exception.NotOnListException;  
 import com.blogspot.javasampleprogram.service.IPartyService;  
 import com.blogspot.javasampleprogram.service.PartyPeople;  

 public class PartyTest {  

      public static void main(String[] args) {  

           ApplicationContext context1 = new ClassPathXmlApplicationContext(new String[] { "appContext.xml" });  

           PartyPeople guest1 = new PartyPeople("jason statham", false);  
           PartyPeople guest2 = new PartyPeople("john travolta", true);  
           PartyPeople guest3 = new PartyPeople("adam sandler", true);  

           System.out.println("--------------------------------------");  

           IPartyService partyService = (IPartyService)context1.getBean("partyService");  

           // in guest list and not drunk  
           try {  
                partyService.letsParty(guest1);  
           } catch (NotOnListException e) {System.out.println(e.getMessage());}  
           catch (Exception e) {}  
           System.out.println("--------------------------------------");  

           // in guest list and drunk. Even if exception is thrown still the exit time is audited  
           try {  
                partyService.letsParty(guest2);  
           } catch (NotOnListException e) {System.out.println(e.getMessage());}  
           catch (Exception e) {}  
           System.out.println("--------------------------------------");  

           // not in guest list and drunk.   
           try {  
                partyService.letsParty(guest3);  
           } catch (NotOnListException e) {System.out.println(e.getMessage());}  
           catch (Exception e) {}  
           System.out.println("--------------------------------------");  
      }  
 }  
Output:
 --------------------------------------  
 jason statham came in at 13:38  
 jason statham got party gift.  
 Sent thank you email to jason statham. Thank you jason statham for coming to letsParty  
 jason statham left at 13:38  
 --------------------------------------  
 john travolta came in at 13:38  
 john travolta got too drunk. Calling cab!!  
 Sent thank you email to john travolta. Thank you john travolta for coming to letsParty  
 john travolta left at 13:38  
 --------------------------------------  
 adam sandler trying to gatecrash.  
 --------------------------------------  

Lets analyse  the results:
Jason who was in the guest list and was not drunk was given the party gift (AfterReturning advice) and was sent thank you email (After advice) and his entry and exit time was audited (Around advice).

John was on the guest list but was drunk so he was not given party gift and cab was called for him (AfterThrowing advice) and was sent thank you email (After advice) and his entry and exit time was audited (Around advice).

Adam who was not on the guest list, was not allowed to enter the party at all (Before advice).

Conclusions

  1. On the way in to a joinpoint, the advice with lowest Order value gets executed first.
  2. On the way out from the joinpoint, the advice with highest Order value gets executed first.
  3. When two pieces of advice defined in the same aspect both need to run at the same join point, the ordering is undefined.
Jar files used:
  1. aspectjrt-1.5.3.jar
  2. org.springframework.context-3.0.4.RELEASE.jar
  3. org.springframework.beans-3.0.3.RELEASE.jar
  4. org.springframework.core-3.0.3.RELEASE.jar
  5. org.springframework.asm-3.0.3.RELEASE.jar
  6. org.springframework.expression-3.0.3.RELEASE.jar
  7. org.springframework.aop-3.0.3.RELEASE.jar
  8. com.springsource.org.aopalliance-1.0.0.jar
  9. aspectjweaver-1.6.8.jar



Spring AOP Sample code

Spring AOP Advice example

Spring AOP

As a developer we often consider concerns like business logic, performance, logging, security and so forth while implementing any module. If a single concern is implemented in multiple modules, it leads to lower code reuse and code scattering. For example consider a data access module. If one of the client code need authentication to access the database and another client code may need no authentication at all then placing the authentication code inside the database code might make our code unusable. This is where AOP comes into picture.

AOP (aspect oriented programming) is a programming methodology that enable the modularization of  concerns that cut across multiple types and objects.

AOP Terminologies:


  1. Aspect: a modularization of a concern that cuts across multiple classes. 
  2. Join point: a point during the execution of a program, such as the execution of a method.
  3. Advice: action taken by an aspect at a particular join point. Different types of advice include "around," "before", "after" advice etc. 
  4. Pointcut: a predicate that matches join points.  
Spring AOP supports 5 types of advices:

  1. Before advice: Advice that executes before a join point, but which does not have the ability to prevent execution flow proceeding to the join point (unless it throws an exception).
  2. After returning advice: Advice to be executed after a join point completes normally: for example, if a method returns without throwing an exception.
  3. After throwing advice: Advice to be executed if a method exits by throwing an exception.
  4. After (finally) advice: Advice to be executed regardless of the means by which a join point exits (normal or exceptional return).
  5. Around advice: Advice that surrounds a join point such as a method invocation. It is also responsible for choosing whether to proceed to the join point or to shortcut the advised method execution by returning its own return value or throwing an exception.

Spring AOP Example

In this example, we are taking a scenario where there is a small party and how different advices can be used to cater different situations:







  • @Before advice - Will be used for authentication of guests. Only people in guest list can come. 
  • @Around advice - Will be used for Audit. Guest's entry and exit timings should be noted. 
  • @AfterThrowing - Will be used for Exception handling. If a guest gets too drunk then call a cab. 
  • @AfterReturning - Will be used to Check Normal flow. Give good bye gift to guests who didn't get too drunk.
  • @After - Will be used to handle both normal or Exception conditions. Send a thank you email to all the guest irrespective of whether they were drunk or not.


  • Package Structure:
    Spring AOP Sample code


    Lets start with creating a PartyService with letsParty() method to show the use of advices.
     package com.blogspot.javasampleprogram.service;  
     /**  
      * @author http://java-sample-program.blogspot.in/  
      */  
     public interface IPartyService {  
          public void letsParty(PartyPeople people) throws Exception;  
     }  
    
    PartyService Implementation class
     package com.blogspot.javasampleprogram.service;  
     import com.blogspot.javasampleprogram.exception.GotTooDrunkException;  
     /**  
      * @author http://java-sample-program.blogspot.in/  
      */  
     public class PartyServiceImpl implements IPartyService {  
          /**  
           * guests wait for some time in party then leave.  
           * If a guest gets too drunk then they are taken out.  
           */  
          public void letsParty(PartyPeople people) throws Exception {  
                    Thread.sleep(200);  
                    // if people get drunk then get them out
                    if (people.isDrunk()) {  
                         throw new GotTooDrunkException();  
                    }  
          }  
     }  
    

    Data transfer object that stores the information of people coming in.
     package com.blogspot.javasampleprogram.service;  
     import java.io.Serializable;  
     /**  
      * @author http://java-sample-program.blogspot.in/  
      */  
     public class PartyPeople implements Serializable {  
          public PartyPeople(){};  
          
          public PartyPeople(String name){this.name = name;};  
          
          public PartyPeople(String name, boolean isDrunk) {
            this.name = name; 
            this.drunk = isDrunk;
          };  
          public String name;  
          public boolean drunk;  
          
         /**  
           * @return the drunk  
           */  
          public boolean isDrunk() {  
               return drunk;  
          }  
          /**  
           * @param drunk the drunk to set  
           */  
          public void setDrunk(boolean drunk) {  
               this.drunk = drunk;  
          }  
          /**  
           * @return the name  
           */  
          public String getName() {  
               return name;  
          }  
          /**  
           * @param name the name to set  
           */  
          public void setName(String name) {  
               this.name = name;  
          }  
     }  
    
    Exception thrown when the guest is not in guestlist
     package com.blogspot.javasampleprogram.exception;  
     /**  
      * @author http://java-sample-program.blogspot.in/  
      */  
     public class NotOnListException extends Exception {  
          public NotOnListException() {  
               super();  
          }  
          public NotOnListException(String message) {  
               super(message);  
          }  
     }  
    
    Exception thrown when the guest becomes too drunk
     package com.blogspot.javasampleprogram.exception;  
     /**  
      * @author http://java-sample-program.blogspot.in/  
      */  
     public class GotTooDrunkException extends Exception {  
          public GotTooDrunkException() {  
               super();  
          }  
          public GotTooDrunkException(String message) {  
               super(message);  
          }  
     }  
    

    Spring AOP advices :

    1. Before Advice 

    Before advice will authenticate guests. Only people in guest list can come.
     package com.blogspot.javasampleprogram.aspect;  
    
     import org.aspectj.lang.JoinPoint;  
     import org.aspectj.lang.annotation.Aspect;  
     import org.aspectj.lang.annotation.Before;  
     import com.blogspot.javasampleprogram.exception.NotOnListException;  
     import com.blogspot.javasampleprogram.service.PartyPeople;  
     /**  
      * @author http://java-sample-program.blogspot.in/  
      */  
     @Aspect  
     public class BeforePartyAspect {  
          /**  
           * Advice to log entering and exit of guests.  
           * @param proceedingJoinPoint  
           */  
          @Before(value="(execution(* com.blogspot.javasampleprogram.service.*.*(..)))")  
          public void checkGuestList(JoinPoint joinPoint) throws NotOnListException {  
               // get method arguments   
               Object[] args = joinPoint.getArgs();  
               
               // getting the method argument using Joinpoint API  
               PartyPeople partyPeople = (PartyPeople)args[0];  
               
               boolean onGuestList = false;  
               // checking guest list  
               for (int i = 0; i < partyPeoples.length; i++) {  
                    if (partyPeople.getName().equals(partyPeoples[i].getName())) {  
                         onGuestList = true;  
                         break;  
                    }  
               }  
               
               if (!onGuestList) {  
                    throw new NotOnListException(partyPeople.getName()+" trying to gatecrash.");  
               }  
          }  
    
          // guest list
          PartyPeople[] partyPeoples = {new PartyPeople("jason statham"),  
                                              new PartyPeople("john travolta"),            
                                              new PartyPeople("arnold"),            
                                              new PartyPeople("christian bale"),            
                                              new PartyPeople("Vin Diesel")  
          };  
     }  
    
    Spring application context file appContext.xml 
     <?xml version="1.0" encoding="UTF-8" standalone="no"?>  
     <beans xmlns="http://www.springframework.org/schema/beans"  
          xmlns:aop="http://www.springframework.org/schema/aop"  
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
          xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd  
               http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">  
         
         <!-- The @AspectJ support is enabled by including the below tag -->     
         <aop:aspectj-autoproxy/>  
         
         <bean id="partyService"   
           class="com.blogspot.javasampleprogram.service.PartyServiceImpl" />  
         
         <!-- Aspect -->  
         <bean id="beforePartyAspect" class="com.blogspot.javasampleprogram.aspect.BeforePartyAspect" />  
     </beans>  
    
    Run PartyTest, 'adam sandler' who is not on the list will be caught by the before advice.
     package com.blogspot.javasampleprogram.test;
      
     import org.springframework.context.ApplicationContext;  
     import org.springframework.context.support.ClassPathXmlApplicationContext;  
     import com.blogspot.javasampleprogram.exception.NotOnListException;  
     import com.blogspot.javasampleprogram.service.IPartyService;  
     import com.blogspot.javasampleprogram.service.PartyPeople;  
    
     public class PartyTest {  
    
          public static void main(String[] args) {  
               ApplicationContext context1 = new ClassPathXmlApplicationContext(new String[] { "appContext.xml" });  
    
               PartyPeople guest1 = new PartyPeople("jason statham", false);  
               PartyPeople guest2 = new PartyPeople("adam sandler", true);  
    
               IPartyService partyService = (IPartyService)context1.getBean("partyService");  
    
               // in guest list  
               try {  
                    partyService.letsParty(guest1);  
               } catch (NotOnListException e) {System.out.println(e.getMessage());}  
               catch (Exception e) {}  
    
               System.out.println("--------------------------------------");  
    
               // @before advice throws NotOnListException   
               try {  
                    partyService.letsParty(guest2);  
               } catch (NotOnListException e) {System.out.println(e.getMessage());}  
               catch (Exception e) {}  
    
               System.out.println("--------------------------------------");  
          }  
     }  
    
    Output
     --------------------------------------  
     adam sandler trying to gatecrash.  
     --------------------------------------  
    

    2. Around advice

    Audits the entry and exit time of guests.
     package com.blogspot.javasampleprogram.aspect;  
     
     import java.util.Calendar;  
     import org.aspectj.lang.ProceedingJoinPoint;  
     import org.aspectj.lang.annotation.Around;  
     import org.aspectj.lang.annotation.Aspect;  
     import com.blogspot.javasampleprogram.service.PartyPeople;  
     
     /**  
      * @author http://java-sample-program.blogspot.in/  
      */  
     @Aspect  
     public class AroundPartyAspect {  
          /**  
           * Advice to log entering and exit of guests.  
           * @param proceedingJoinPoint  
           * @throws Throwable   
           */  
          @Around(value="(execution(* com.blogspot.javasampleprogram.service.*.*(..)))")  
          public void audit(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {  
     
               // get method arguments   
               Object[] args = proceedingJoinPoint.getArgs();  
    
               // getting the method argument using Joinpoint API  
               PartyPeople partyPeople = (PartyPeople)args[0];  
               
               //auditing entry and exit  
               System.out.println(partyPeople.getName()+" came in at "+Calendar.getInstance().get(Calendar.HOUR_OF_DAY)+":"+Calendar.getInstance().get(Calendar.MINUTE));  
               
               try {  
                    proceedingJoinPoint.proceed();  
               } finally {  
                    // exit time kept in finally block so that even if there is any exception from method  
                    // the exit time still gets audited  
                    System.out.println(partyPeople.getName()+" left at "+Calendar.getInstance().get(Calendar.HOUR_OF_DAY)+":"+Calendar.getInstance().get(Calendar.MINUTE));  
               }  
          }  
     }  
    
    Spring configuration file
     <?xml version="1.0" encoding="UTF-8" standalone="no"?>  
     <beans xmlns="http://www.springframework.org/schema/beans"  
          xmlns:aop="http://www.springframework.org/schema/aop"  
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
          xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd  
               http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">  
        
         <!-- The @AspectJ support is enabled by including the below tag -->     
         <aop:aspectj-autoproxy/>  
        
         <bean id="partyService"   
           class="com.blogspot.javasampleprogram.service.PartyServiceImpl" />  
         
         <!-- Aspect -->  
         <bean id="aroundPartyAspect" class="com.blogspot.javasampleprogram.aspect.AroundPartyAspect" />  
     </beans>  
    

    Run the PartyTest, the entry and exit time of each guest is audited.
     package com.blogspot.javasampleprogram.test;  
     
     import org.springframework.context.ApplicationContext;  
     import org.springframework.context.support.ClassPathXmlApplicationContext;  
     import com.blogspot.javasampleprogram.exception.NotOnListException;  
     import com.blogspot.javasampleprogram.service.IPartyService;  
     import com.blogspot.javasampleprogram.service.PartyPeople;  
    
     public class PartyTest {  
     
         public static void main(String[] args) {  
    
               ApplicationContext context1 = new ClassPathXmlApplicationContext(new String[] { "appContext.xml" });  
    
               PartyPeople guest1 = new PartyPeople("jason statham", false);  
               PartyPeople guest2 = new PartyPeople("john travolta", true);  
    
               System.out.println("--------------------------------------");  
               IPartyService partyService = (IPartyService)context1.getBean("partyService");  
    
               // in guest list and not drunk  
               try {  
                    partyService.letsParty(guest1);  
               } catch (NotOnListException e) {System.out.println(e.getMessage());}  
               catch (Exception e) {}  
               System.out.println("--------------------------------------");  
    
               // in guest list and drunk. Even if exception is thrown still the exit time is audited  
               try {  
                    partyService.letsParty(guest2);  
               } catch (NotOnListException e) {System.out.println(e.getMessage());}  
               catch (Exception e) {}  
               System.out.println("--------------------------------------");  
          }  
     }  
    

     --------------------------------------  
     jason statham came in at 10:25  
     jason statham left at 10:25  
     --------------------------------------  
     john travolta came in at 10:25  
     john travolta left at 10:25  
     --------------------------------------  
    

    3. AfterThrowing advice

    Handle the GotTooDrunkException and calls cab for the drunk guests.
     package com.blogspot.javasampleprogram.aspect;  
     
     import org.aspectj.lang.JoinPoint;  
     import org.aspectj.lang.annotation.AfterThrowing;  
     import org.aspectj.lang.annotation.Aspect;  
     import com.blogspot.javasampleprogram.exception.GotTooDrunkException;  
     import com.blogspot.javasampleprogram.service.PartyPeople;  
     
     /**  
      * @author http://java-sample-program.blogspot.in/  
      */  
     @Aspect  
     public class AfterThrowingPartyAspect {  
     
         /**  
           * Advice to send thank You Email to all guests, irrespective of whether they were   
           * too drunk or not.  
           * @param joinPoint  
           */  
          @AfterThrowing(value="(execution(* com.blogspot.javasampleprogram.service.*.*(..)))", throwing="exception")  
          public void callCabForDrunkGuests(JoinPoint joinPoint, Exception exception) {  
    
               if (exception instanceof GotTooDrunkException) {  
                         // get method arguments   
                         Object[] args = joinPoint.getArgs();  
    
                         // getting the method argument using Joinpoint API  
                         PartyPeople partyPeople = (PartyPeople)args[0];  
                         System.out.println(partyPeople.getName()+" got too drunk. Calling cab!!");  
               }   
               // No need to handle NotOnListException as exceptions thrown by @Before advice never come to @AfterThrowing  
          }  
     }  
    

    Spring configuration file
     <?xml version="1.0" encoding="UTF-8" standalone="no"?>   
      <beans xmlns="http://www.springframework.org/schema/beans"   
        xmlns:aop="http://www.springframework.org/schema/aop"   
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
        xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd   
           http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">   
    
        <!-- The @AspectJ support is enabled by including the below tag -->     
        <aop:aspectj-autoproxy/>   
    
        <bean id="partyService"    
         class="com.blogspot.javasampleprogram.service.PartyServiceImpl" />   
    
        <!-- Aspect -->   
        <bean id="afterThrowingPartyAspect" class="com.blogspot.javasampleprogram.aspect.AfterThrowingPartyAspect" />   
      </beans>   
    

    Run the above test again. Called cabs for guests, who got too drunk.
     --------------------------------------  
     john travolta got too drunk. Calling cab!!  
     --------------------------------------  
    

    4. AfterReturning Advice

    If the guest is not drunk then no exception will be thrown from method and afterreturning advice will give gifts to these guests.
     package com.blogspot.javasampleprogram.aspect;  
     
     import org.aspectj.lang.JoinPoint;  
     import org.aspectj.lang.annotation.AfterReturning;  
     import org.aspectj.lang.annotation.Aspect;  
     import com.blogspot.javasampleprogram.service.PartyPeople;  
     
     /**  
      * @author http://java-sample-program.blogspot.in/  
      */  
     @Aspect  
     public class AfterReturningPartyAspect {  
          /**  
           * Advice to give party gift to guests who came out without getting too drunk.  
           * @param joinPoint  
           */  
          @AfterReturning(value="(execution(* com.blogspot.javasampleprogram.service.*.*(..)))")  
          public void givePartyGift(JoinPoint joinPoint) {  
               // get method arguments   
               Object[] args = joinPoint.getArgs();  
              
               // getting the method argument using Joinpoint API  
               PartyPeople partyPeople = (PartyPeople)args[0];  
              
               System.out.println(partyPeople.getName()+" got party gift.");  
          }  
     }  
    

    Spring configuration file
     <?xml version="1.0" encoding="UTF-8" standalone="no"?>   
      <beans xmlns="http://www.springframework.org/schema/beans"   
        xmlns:aop="http://www.springframework.org/schema/aop"   
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
        xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd   
           http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">   
    
        <!-- The @AspectJ support is enabled by including the below tag -->     
        <aop:aspectj-autoproxy/>   
    
        <bean id="partyService"    
         class="com.blogspot.javasampleprogram.service.PartyServiceImpl" />   
    
        <!-- Aspect -->   
        <bean id="afterReturningPartyAspect" class="com.blogspot.javasampleprogram.aspect.AfterReturningPartyAspect" />   
      </beans>   
    

    Run the above test again. Gift given to only those guests which were not drunk or for which the GotTooDrunkException was not thrown.
     --------------------------------------  
     jason statham got party gift.  
     --------------------------------------  
    

    5. After Advice

     package com.blogspot.javasampleprogram.aspect;  
     
     import org.aspectj.lang.JoinPoint;  
     import org.aspectj.lang.annotation.After;  
     import org.aspectj.lang.annotation.Aspect;  
     import com.blogspot.javasampleprogram.service.PartyPeople;  
     /**  
      * @author http://java-sample-program.blogspot.in/  
      */  
     @Aspect  
     public class AfterPartyAspect {  
          /**  
           * Advice to send thank You Email to all guests, irrespective of whether they were   
           * too drunk or not.  
           * @param joinPoint  
           */  
          @After(value="(execution(* com.blogspot.javasampleprogram.service.*.*(..)))")  
          public void sendThankYouEmail(JoinPoint joinPoint) {  
     
              // get method arguments   
              Object[] args = joinPoint.getArgs();  
    
              // getting the method argument using Joinpoint API  
              PartyPeople partyPeople = (PartyPeople)args[0];  
              
              System.out.println("Sent thank you email to "+partyPeople.getName()+". Thank you "+partyPeople.getName()+" for coming to "+joinPoint.getSignature().getName());  
          }  
     }  
    
    Spring configuration file
     <?xml version="1.0" encoding="UTF-8" standalone="no"?>   
      <beans xmlns="http://www.springframework.org/schema/beans"   
        xmlns:aop="http://www.springframework.org/schema/aop"   
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
        xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd   
           http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">   
    
        <!-- The @AspectJ support is enabled by including the below tag -->     
        <aop:aspectj-autoproxy/>   
    
        <bean id="partyService"    
         class="com.blogspot.javasampleprogram.service.PartyServiceImpl" />   
    
        <!-- Aspect -->   
        <bean id="afterPartyAspect" class="com.blogspot.javasampleprogram.aspect.AfterPartyAspect" />   
      </beans>   
    
    Run the test again. Every guest (drunk or not drunk) was sent a thank you email.
     --------------------------------------  
     Sent thank you email to jason statham. Thank you jason statham for coming to letsParty  
     --------------------------------------  
     Sent thank you email to john travolta. Thank you john travolta for coming to letsParty  
     --------------------------------------  
    

    My next blog will apply all these advices and in proper order using the @Order annotation.


    Jar files used:
    1. aspectjrt-1.5.3.jar
    2. org.springframework.context-3.0.4.RELEASE.jar
    3. org.springframework.beans-3.0.3.RELEASE.jar
    4. org.springframework.core-3.0.3.RELEASE.jar
    5. org.springframework.asm-3.0.3.RELEASE.jar
    6. org.springframework.expression-3.0.3.RELEASE.jar
    7. org.springframework.aop-3.0.3.RELEASE.jar
    8. com.springsource.org.aopalliance-1.0.0.jar
    9. aspectjweaver-1.6.8.jar