Friday, May 28, 2010

Introduction to AOP (Aspect Oriented Programming)





Introduction to AOP (Aspect Oriented Programming)

AOP is a programming technique which isolates the secondary problems from the main problem. For example, solving the Salary Processing is the main problem.  Logging, Security, Transaction, etc are not the main problems but the issues need to be addressed with the main problem.

AOP is not a replacement for OOP, but a complement. Addressing the main problem with AOP is not a wise idea when we have proven, easy to develop OOP. Solving secondary problems along with main problem in OOP will burden the design with extra load. So the best approach is to solve the main problem with OOP and secondary problems with AOP.

How AOP works

In AOP approach, we solve all the secondary problems independently, and finally we will weave the secondary solutions into the mail solution.  Weaving is the process of joining main and secondary logics together. The object weaved is called Target

Types of AOP

There are two types in AOP
  1. Static
  2. Dynamic

Static AOP merges the main and secondary logic during the compilation time itself, so the running application has no overhead. In Java Static AOP is achieved by merging both the logics in bytecode.

Dynamic AOP on the other hand merges the main and secondary logic during the runtime, this gives more flexibility, and during runtime we can include different secondary logics according to the business logic. But remember flexibility always comes with its own price. The main technique used in java to achieve dynamic AOP is proxies.
  
AOP building blocks

Like every technology or concept , AOP also comes with lot of jargons and buzzwords. There are the actual building blocks of the AOP.

JoinPoint is the point in the application where we can insert secondary logic, for example method execution, object instantiation, etc.

Advice  is the actual secondary logic. Advice can be classified into different types according to the point where they are getting executed. Advice can be executed just before the joinpoint or after the joinpoint, etc.

Pointcut is collection of joinpoints . it can be a like all the methods in a class or all the classes in a packages or all dao classes in some packages, etc.

Aspects are the bundle of pointcuts and advice.  Aspect joins the advices with pointcuts.


Types of Advices

Based on the point of execution Advices can be classified as follows

1. Before Advices -  executes before the joinpoint
2. After Advice -  executes after the joinpoint
3. Around Advice - executes before and after the joinpoint
4. Throws Advices - executes when exception thrown from joinpoint
5. After Return Advise - executes when the joinpoint returns value.

For AOP example please refer – Two simple approaches to Spring AOP

Classification : simple introduction to AOP, AOP Concept, Simple AOP, what is advice, what is pointcut, what is joinpoint, what is aspect, what is weaving, what is target

Thursday, May 27, 2010

Two simple approaches of Spring AOP


One of the Strengths of Spring is its simplicity. Spring provides the same simplicity in programming complex AOP as well.

In this post I am trying to give two simple examples of Spring AOP implementations. one is annotation based and the another one is configuration based. annotation based approach and configuration based approach, both have their own advantages and disadvantages, as per the natural rule no solution is best for every scenario.

annotation based apporoch fits in some places and configuration based fits in some places. the selection needs to be done according to the context anyway.

I am taking simple example of printing execution start and end time for every method of a class.  

For the following Business Service class using AOP we are going to mark the execution start and stop time for every method in this class

public class CalculatorService {
     
      public int add(int x, int y){
            return x+y;
      }
     
      public int sub(int x, int y){
            return x-y;
      }

      public int mul(int x, int y){
            return x*y;
      }

      public int div(int x, int y){
            return x/y;
      }

}



Approach 1 - Annotation based.

First step we need to create an advise class

import java.text.SimpleDateFormat;
import java.util.Date;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;

@Aspect
public class TimeLogAdvise {
      SimpleDateFormat df = new SimpleDateFormat("dd:MM:yyyy h:m:s:S");

      @Pointcut("execution(* com.blogger.technoant.CalculatorService.*(..))")
      public void businessMethods() {
      }

      @Around("businessMethods()")
      public Object profile(ProceedingJoinPoint pjp) throws Throwable {

            System.out.println(pjp.getSignature().getName() + " Starts at "
                        + df.format(new Date()));
            Object obj = pjp.proceed();
            System.out.println(pjp.getSignature().getName() + " Ends at "
                        + df.format(new Date()));
            return obj;
      }
}

@Aspect - marks this class as annotation
@Pointcut - specifies the matching pattern for the pointcut
@Around - is the advise 


Step 2 is creating the applicationcontext.xml

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

      <aop:aspectj-autoproxy />
     
      <bean id="calculatorService" class="com.blogger.technoant.CalculatorService"/>
     
      <bean id="timeLogAdvise" class="com.blogger.technoant.TimeLogAdvise"/> 
     
beans>

- is the indication we give to spring to identify advises.

Now the time to test the advise, following class can be used for testing

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

public class TimeLogDemo {
     
      public static void main(String args[]){
           
     ApplicationContext context = new ClassPathXmlApplicationContext("applicationcontext.xml");
     CalculatorService bc = (CalculatorService) context.getBean("calculatorService");
    
     bc.add(8, 4);
     bc.sub(8, 4);
     bc.mul(8, 4);
     bc.div(8, 4);

      }
}

to successfully execute the program you need to include following jar files in your classpath

spring, spring-sop, commons-logging,cglib, aspectj and aspectjweaver.





Approach 2 - Annotation based

In this approach advise will be a simple POJO class and all the AOP details will go to xml.
Step 1: creating the Advise POJO (without any annotation)
import java.text.SimpleDateFormat;
import java.util.Date;

import org.aspectj.lang.ProceedingJoinPoint;

public class TimeLogAdvisePOJO {

      SimpleDateFormat df = new SimpleDateFormat("dd:MM:yyyy h:m:s:S");


      public Object profile(ProceedingJoinPoint pjp) throws Throwable {

            System.out.println(pjp.getSignature().getName() + " Starts at "
                        + df.format(new Date()));
            Object obj = pjp.proceed();
            System.out.println(pjp.getSignature().getName() + " Ends at "
                        + df.format(new Date()));
            return obj;
      }
}

This is a simple class without any annotations, here we have used only one spring class ProceedingJoinPoint to get the name of the method. If we don’t want to print the name of the method it will be a simple POJO without any Spring dependency.

Step 2: xml configuration

<beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:aop="http://www.springframework.org/schema/aop"
      xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">

           
      <bean id="calculatorService" class="com.blogger.technoant.CalculatorService"/>
     
      <bean id="timeLogAdvise" class="com.blogger.technoant.TimeLogAdvisePOJO"/>   
     
      <aop:config>
       
            <aop:aspect id="myAspect" ref="timeLogAdvise">
           
            <aop:pointcut id="timeLogService"
                  expression="execution(* com.blogger.technoant.CalculatorService.*(..))"/>
             
             <aop:around
                              pointcut-ref="timeLogService"
                              method="profile"/>                 
   
                  aop:aspect>
            aop:config>
     
beans>

Now execute the same TimeLogDemo in the approach 1. 


Please write in comments if you have any problem executing this or any clarification or further info required.



Classifications: Spring AOP Example, Spring AOP annotation example, Spring AOP XML example, spring AOP logging example, spring AOP evaluation time, Spring AOP around advise example, DateFormat example, how to format date, how to create spring aop

Wednesday, May 12, 2010

Stopping a timed out thread



Some threads may run for long time than expected, to control this threads we may want to stop the thread if they are running for long time than expected. the following is an small example for how to do this.

The class MyThread is a thread which will be created from the ThreadTest class. MyThread has a private property requestedToStop which will be used to stop the thread (as stop method of the Thread is deprecated, this is one of the suggested approach to stop the thread). 


Class MyThread





package com.blogger.technoant;

public class MyThread extends Thread{
     
      private boolean requestedToStop=false;   
     
      @Override
      public void run() {
            while(!this.requestedToStop){
                  System.out.println("I am running....");
            }          
      }
     
      public void requestStop(){
            this.requestedToStop=true;
      }

}



Class - ThreadTest



package com.blogger.technoant;

public class ThreadTest  {
     
      public static void main(String args[]) throws Exception{
           
            final long TIMOUT_TIME=5*1000;
           
            MyThread myThread=new MyThread();
           
            Thread t1=new Thread(myThread);    
           
            t1.start();      
            t1.join(TIMOUT_TIME);        
           
            if(t1.isAlive()){
                  myThread.requestStop();
                  throw new Exception("Timed out. Thread executing for more than "+TIMOUT_TIME+" millisecs");
            }    
           
           
      }

}

I hope this example will help on how to stop thread on timeout.

One question may arise as the MyThread has extended Thread instead of implementing Runnable (which is always preferred). In MyThread class actually I am trying to extend the functionality of the Thread by adding smooth stop, so I feel extending thread has reason here.




Classification: How to Stop Thread, How to restrict thread execution, restrict thread execution time, control thread execution, stopping thread