Tuesday, September 2, 2014

Conditional Pointcut in AspectJ

Conditional Pointcut in AspectJ

Well, I came to a situation in which i wanted my advice for the pointcut to be executed on some conditions.

You may be thinking, why not just put a condition inside the advice itself. Yeah, that's kind of workaround.

AspectJ has given way to use condition in pointcut itself to filter your execution, similar to java.

Let us understand this with an example.

1. Consider I have an Advice for a pointcut, on execution ,in  getting the price of car, to do some logging.

pointcut getPriceOnCall() : execution(Double com.test.java.Vehicle.getPrice());
Double around(): getPriceOnCall(){
System.out.println("this: " + thisJoinPoint.getThis());
System.out.println("this: " + thisJoinPointStaticPart.toLongString());
LOGGER.log(Level.INFO, "just after call and before starting execution");
Double price= proceed();
LOGGER.log(Level.INFO, "preceed called");
return price;
}

2. I want to have a logging only when car's minimum price is greater than some value.
     Then, here we can use if(true) or if(false) pointcut.

pointcut getPriceOnCall() : execution(Double com.test.java.Vehicle.getPrice()) && if(((Vehicle)thisJoinPoint.getThis()).getMinPrice()>30000);
Double around(): getPriceOnCall(){
System.out.println("this: " + thisJoinPoint.getThis());
System.out.println("this: " + thisJoinPointStaticPart.toLongString());
LOGGER.log(Level.INFO, "just after call and before starting execution");
Double price= proceed();
LOGGER.log(Level.INFO, "preceed called");
return price;
}

Here You can see that I have put a condition with if(...) pointcut. So only when this condition is true then only this advice is going to be executed.




When using the annotation style, it is not possible to write a full Java expression within the annotation value so the syntax differs slightly, whilst providing the very same semantics and runtime behaviour. An if() pointcut expression can be declared in an @Pointcut , but must have either an empty body (if(), or be one of the expression forms if(true) or if(false) . The annotated method must be public, static, and return a boolean. The body of the method contains the condition to be evaluated. For example:

@Pointcut("call(* *.*(int)) && args(i) && if()")
     public static boolean someCallWithIfTest(int i) {
        return i > 0;
     }

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

Cheers!!!

Wednesday, August 27, 2014

Sunday, August 17, 2014

Dynamic Suite for Junit Test cases.

Well, Today I am going to talk about a situation is which i had been (few months back) while developing a Test suite for Junit.

Test Suite: Its a program which runs list of Junit Test cases in one go.

It has got very simple piece of code.

eg.

@RunWith(Suite.class)
@SuiteClasses({Test1.class,Test2.class})
public class StaticTestSuite {

}

So, In above example we can see that we need to provide all the list of classes to be executed by the Test Suite. But, this is a static kind of Suite. Every time you have to make changes to this file to enter the Test class name.

Dynamic Situation: Suppose we have a huge list of test cases and those test cases are dynamic which keeps on added and deleted. What would we do in this case?
Yes, We would need a dynamic Suite which dynamically picks up the test classes from the classpath and include it into Suite.


Easy Solution could be Extending Suite Class. 
Let us understand this by following easy example.

1. Create 2 simple Junit Test case.

 package com.test.junit;

import org.junit.Test;


public class Test1 {
@Test
public void testIt1(){
System.out.println("Test 1 Executed.");
}
}

package com.test.junit;

import org.junit.Test;

public class Test2 {

@Test
public void testIt(){
System.out.println("Test 2 Executed.");
}
}

-----------------------------------------------------------------------------------------------------------
2. Now create the Dynamic Suite class which extends Suite.

package com.test.junit.run;

import java.io.IOException;

import org.junit.runners.Suite;
import org.junit.runners.model.InitializationError;

public class DynamicSuite extends Suite {

    public DynamicSuite(Class<?> setupClass) throws InitializationError, IOException {
       super(setupClass, DynamicTestRun.suite());
    }
}

Here we can see that, Suite class is extended, and its constructor is providing all the list of Testcases to Suite.
------------------------------------------------------------------------------------------------------------
3. Now Implement the logic of scanning all the Test cases from the class path. I have used PathMatchingResourcePatternResolver of spring framework to find the resources(class files) with given pattern.(You can implement you own scanner.)

eg.

package com.test.junit.run;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

import org.junit.runner.RunWith;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

@RunWith(DynamicSuite.class)
public class DynamicTestRun {
public static Class<?>[] suite() throws IOException {
List<Class<?>> classList= listMatchingClasses("classpath:/com/test/**/Test*.class");
return  (Class<?>[]) classList.toArray(new Class[classList.size()]);
}

public static List<Class<?>> listMatchingClasses(String matchPattern) throws IOException {
   List<Class<?>> classes = new LinkedList<Class<?>>();
   PathMatchingResourcePatternResolver scanner = new PathMatchingResourcePatternResolver();
   Resource[] resources = scanner.getResources(matchPattern);

   for (Resource resource : resources) {
       Class<?> clazz = getClassFromResource(resource);
       classes.add(clazz);
   }
   return classes;
}

public static Class<?> getClassFromResource(Resource resource) {
   try {
       String resourceUri = resource.getURI().toString();
       System.out.println(resourceUri);
       if(resourceUri.indexOf("com") != -1)
        resourceUri = resourceUri.substring(resourceUri.indexOf("com")).replace(".class", "").replace("/", ".");
       return Class.forName(resourceUri);
   } catch (Exception ex) {
       ex.printStackTrace();
   }
   return null;
}

}

Please do comment if you have some better solution to it and also have any question on this. I would be glad to answer it.
Thank You.
Cheers. :)

PS:  You can access the sample code from following location:
https://github.com/sanjar/Day_Today/tree/master/org.sanjar.test.junit