Thursday, March 19, 2015

pointcut and wild cards

Below is the code used to explain the logics
http://cgenit.blogspot.com/2015/03/create-simple-maven-app-to-test-and.html

We have made a simple applicatioon to test and run the AOP concept.
Here we have taken the logging aspect as a cross cutting concern.
Created LoginAspect.java and made it aspect using @Aspect and written advice using
@Before("execution(public String getName())")
The two object classes we have used is Circle and Triangle, where both having simple attribute name with getter and setter.
So we need to log it whenever the getter called.
We have created ShapeService class to get the object, for better standard way to present.
AppMain.java is used to test the application.

POM.XML  this include more dependencies , more than needed

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

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.test</groupId>
<artifactId>AOP</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>AOP</name>
<description>Aspect Oriented Programming</description>

<properties>
<jdk.version>1.6</jdk.version>
<spring.version>3.2.8.RELEASE</spring.version>
<spring.security.version>3.2.3.RELEASE</spring.security.version>
<jstl.version>1.2</jstl.version>
<javax.servlet.version>3.1.0</javax.servlet.version>
<mysql.connector.version>5.1.30</mysql.connector.version>
</properties>

<dependencies>
<!-- Spring 3 dependencies -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>

<!-- spring jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>

<!-- Spring Security -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>${spring.security.version}</version>
</dependency>

<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>${spring.security.version}</version>
</dependency>

<!-- AOP -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.7.3</version>
</dependency>

<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.6.11</version>
</dependency>

<!-- connect to mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.connector.version}</version>
</dependency>


</dependencies>
</project>
----------------------------------------------------------------------------------------

spring.xml  - bean definition
----------------------------------------------------------------------------------------
<?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-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">

<aop:aspectj-autoproxy />

<bean name="triangle" class="org.aop.model.Triangle">
<property name="name" value="Traingle name"></property>
</bean>

<bean name="circle" class="org.aop.model.Circle">
<property name="name" value="Circle name"></property>
</bean>

<bean name="shapeService" class="org.aop.service.ShapeService"
autowire="byName"></bean>

<bean name="loginAspect" class="org.aop.aspect.LoginAspect"></bean>

</beans>
----------------------------------------------------------------------------------------

Circle.java
----------------------------------------------------------------------------------------
package org.aop.model;

public class Circle {

private String name;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

}

----------------------------------------------------------------------------------------
Triangle.java
----------------------------------------------------------------------------------------
package org.aop.model;

public class Triangle {
private String name;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
}

----------------------------------------------------------------------------------------
ShapeService .java
----------------------------------------------------------------------------------------
package org.aop.service;

import org.aop.model.Circle;
import org.aop.model.Triangle;

public class ShapeService {

private Circle circle;
private Triangle triangle;

public Circle getCircle() {
return circle;
}

public void setCircle(Circle circle) {
this.circle = circle;
}

public Triangle getTriangle() {
return triangle;
}

public void setTriangle(Triangle triangle) {
this.triangle = triangle;
}

}

----------------------------------------------------------------------------------------
LoginAspect .java
----------------------------------------------------------------------------------------
package org.aop.aspect;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

@Aspect
public class LoginAspect {

@Before("execution(public String getName())")
public void loginAdvice() {
System.out.println("Login advice run::get method called");
}

}

--------------------------------------------------------------------------------------------------------------------------
AppMain .java
--------------------------------------------------------------------------------------------------------------------------
package org.aop.main;

import org.aop.service.ShapeService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class AppMain {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext(
"spring.xml");

// you need to cast if not use second parameter ShapeService.class
ShapeService shapeService = ctx.getBean("shapeService",
ShapeService.class);

System.out.println(shapeService.getTriangle().getName());
}

}

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

output Now
===============================================================
Login advice run::get method called
Traingle name


===============================================================


1. Need to limit only for specific class / object get method.
Above aspect's advice, the action taken is executed for each get method.
Limit only for circle getmethod();

we give the path to the method inside execution()

package org.aop.aspect;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

@Aspect
public class LoginAspect {

@Before("execution(public String org.aop.model.Circle.getName())")
public void loginAdvice() {
System.out.println("Login advice run::get method called");
}

}

Output for main method
package org.aop.main;

import org.aop.service.ShapeService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class AppMain {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext(
"spring.xml");

// you need to cast if not use second parameter ShapeService.class
ShapeService shapeService = ctx.getBean("shapeService",
ShapeService.class);

System.out.println(shapeService.getCircle().getName());
}

}


Output
===============================================================
Login advice run::get method called
Circle name
===============================================================

Let's execute this for Triangle as well to get confirm
===============================================================
Traingle name
===============================================================


2. give a wild card. Execute for any getMethod

package org.aop.aspect;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

@Aspect
public class LoginAspect {

@Before("execution(public String *get*())")
public void loginAdvice() {
System.out.println("Login advice run::get method called");
}

}

-----------------
Main class
-----------------
package org.aop.main;

import org.aop.service.ShapeService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class AppMain {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext(
"spring.xml");

// you need to cast if not use second parameter ShapeService.class
ShapeService shapeService = ctx.getBean("shapeService",
ShapeService.class);

System.out.println(shapeService.getTriangle().getName());
System.out.println(shapeService.getCircle().getName());
}

}



output
===============================================================
Login advice run::get method called
Traingle name
Login advice run::get method called
Circle name

===============================================================

4. Next try with any return type and any parameter 
to test we put a parameter for getter for circle


------------------------------
package org.aop.model;

public class Circle {
private String name;

public String getName(String s) {
return name;
}

public void setName(String name) {
this.name = name;
}

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

package org.aop.aspect;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

@Aspect
public class LoginAspect {
@Before("execution(public * *get*(*))")
public void loginAdvice() {
System.out.println("Login advice run::get method called");
}

}
-------------------------------
in execution
1. first we have public - access modifier
2. *  pink star for any return type
3. * black star for any package structure and class 
4. * Next star for any method start fro get prefix
5. * Next, red star for any parameter 
--------------------------------

So the output will be - Note: For triangle get method advice / action logging not executing. It does not have parameter
===============================================================
Traingle name
Login advice run::get method called
Circle name
===============================================================

5. If we change the circle get for two parameters,
there won't be any executing advice, logging action

package org.aop.model;

public class Circle {
private String name;

public String getName(String s,String ss) {
return name;
}

public void setName(String name) {
this.name = name;
}

}

----------------------------------------------------------------------------------------------------
package org.aop.main;

import org.aop.service.ShapeService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class AppMain {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext(
"spring.xml");

// you need to cast if not use second parameter ShapeService.class
ShapeService shapeService = ctx.getBean("shapeService",
ShapeService.class);

System.out.println(shapeService.getTriangle().getName());
System.out.println(shapeService.getCircle().getName("s","ss"));
}

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

output
===============================================================
Traingle name
Circle name

===============================================================


6. How to make it for any parameter. use two dots(..) elipse instead of star (*)
Here Circle getter has three parameters

-------------------------------------------------------------------------------------
package org.aop.aspect;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

@Aspect
public class LoginAspect {
@Before("execution(public * *get*(..))")
public void loginAdvice() {
System.out.println("Login advice run::get method called");
}

}

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

-------------------------------------------------------------------------------------
package org.aop.model;

public class Circle {
private String name;

public String getName(String s,String ss,String sss) {
return name;
}

public void setName(String name) {
this.name = name;
}

}

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

-------------------------------------------------------------------------------------
package org.aop.main;

import org.aop.service.ShapeService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class AppMain {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext(
"spring.xml");

// you need to cast if not use second parameter ShapeService.class
ShapeService shapeService = ctx.getBean("shapeService",
ShapeService.class);

System.out.println(shapeService.getTriangle().getName());
System.out.println(shapeService.getCircle().getName("s","ss","SSS"));
}

}

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

output  Note: Advice run twice
===============================================================
Login advice run::get method called
Login advice run::get method called
Traingle name
Login advice run::get method called
Login advice run::get method called
Circle name

===============================================================

7. Let's run only for Circle getter with three parameters

-------------------------------------------------------------------------------------
package org.aop.model;

public class Circle {
private String name;

public String getName(String s,String ss,String sss) {
return name;
}

public void setName(String name) {
this.name = name;
}

}

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

-------------------------------------------------------------------------------------
package org.aop.main;

import org.aop.service.ShapeService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class AppMain {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext(
"spring.xml");

// you need to cast if not use second parameter ShapeService.class
ShapeService shapeService = ctx.getBean("shapeService",
ShapeService.class);

System.out.println(shapeService.getTriangle().getName());
System.out.println(shapeService.getCircle().getName("s","ss","SSS"));
}

}

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

-------------------------------------------------------------------------------------
package org.aop.aspect;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

@Aspect
public class LoginAspect {
@Before("execution(public * *get*(*,*,*))")
public void loginAdvice() {
System.out.println("Login advice run::get method called");
}

}

-------------------------------------------------------------------------------------
output  Note: Advice only run before circle getter
===============================================================
Traingle name
Login advice run::get method called
Circle name
===============================================================


8. Have another advice with same matching expression, secondAdvice
Both advice has matching @Before("execution(public * *get*())")

-------------------------------------------------------------------------------------
package org.aop.aspect;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

@Aspect
public class LoginAspect {
@Before("execution(public * *get*())")
public void loginAdvice() {
System.out.println("Login advice run::get method called");
}
@Before("execution(public * *get*())")
public void secondAdvice() {
System.out.println("Second advice executed.");
}


}

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

-------------------------------------------------------------------------------------
package org.aop.main;

import org.aop.service.ShapeService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class AppMain {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext(
"spring.xml");

// you need to cast if not use second parameter ShapeService.class
ShapeService shapeService = ctx.getBean("shapeService",
ShapeService.class);

System.out.println(shapeService.getTriangle().getName());
System.out.println(shapeService.getCircle().getName());
}

}

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

output  Two sets for Triangle and Circle
===============================================================
Login advice run::get method called
Second advice executed.
Login advice run::get method called
Second advice executed.
Traingle name
Login advice run::get method called
Second advice executed.
Login advice run::get method called
Second advice executed.
Circle name

===============================================================

9. Pointcut
As shown in above both advice has the same method, point where method/advice executes
So that is called pointcut
we can define Pointcut and share among two Advices. 
It is easy, and resusability.

Note: We have to use a dummy method. and we are giving the name of the dummy method(poincut) to match the advice / configure the advice.

I have used allGetters() dummy method to hold the PointCut
and changed @Before expression to "allGetters"


New Aspect
-------------------------------------------------------------------------------------
package org.aop.aspect;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;

@Aspect
public class LoginAspect {
@Before("allGetters()")
public void loginAdvice() {
System.out.println("Login advice run::get method called");
}
@Before("allGetters()")
public void secondAdvice() {
System.out.println("Second advice executed.");
}
@Pointcut("execution(public * *get*())")
public void allGetters(){}


}

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

-------------------------------------------------------------------------------------
package org.aop.main;

import org.aop.service.ShapeService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class AppMain {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext(
"spring.xml");

// you need to cast if not use second parameter ShapeService.class
ShapeService shapeService = ctx.getBean("shapeService",
ShapeService.class);

System.out.println(shapeService.getTriangle().getName());
System.out.println(shapeService.getCircle().getName());
}

}

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

output  Two sets for Triangle and Circle
===============================================================
Login advice run::get method called
Second advice executed.
Login advice run::get method called
Second advice executed.
Traingle name
Login advice run::get method called
Second advice executed.
Login advice run::get method called
Second advice executed.
Circle name

===============================================================


10. Not define Pointcut well.
You have to define the pointcut as a method to advice
That is, it needs to have ()  after method name  "allGetters()"
If fail to define ()  will have exception

Below allGetters  does not have ()

@Before("allGetters")
public void loginAdvice() {
System.out.println("Login advice run::get method called");
}



output  Two sets for Triangle and Circle
First to get bean triangle and execute getter
at this point Pointcut comes to play
fails as not well defined
===============================================================
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'triangle' defined in class path resource [spring.xml]: Initialization of bean failed; nested exception is java.lang.IllegalArgumentException: Pointcut is not well-formed: expecting '(' at character position 0
allGetters
^

at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:529)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:296)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:293)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:628)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:83)
at org.aop.main.AppMain.main(AppMain.java:9)
Caused by: java.lang.IllegalArgumentException: Pointcut is not well-formed: expecting '(' at character position 0
allGetters
^

at org.aspectj.weaver.tools.PointcutParser.resolvePointcutExpression(PointcutParser.java:316)
at org.aspectj.weaver.tools.PointcutParser.parsePointcutExpression(PointcutParser.java:294)
at org.springframework.aop.aspectj.AspectJExpressionPointcut.buildPointcutExpression(AspectJExpressionPointcut.java:209)
at org.springframework.aop.aspectj.AspectJExpressionPointcut.buildPointcutExpression(AspectJExpressionPointcut.java:196)
at org.springframework.aop.aspectj.AspectJExpressionPointcut.checkReadyToMatch(AspectJExpressionPointcut.java:185)
at org.springframework.aop.aspectj.AspectJExpressionPointcut.getClassFilter(AspectJExpressionPointcut.java:166)
at org.springframework.aop.support.AopUtils.canApply(AopUtils.java:208)
at org.springframework.aop.support.AopUtils.canApply(AopUtils.java:262)
at org.springframework.aop.support.AopUtils.findAdvisorsThatCanApply(AopUtils.java:294)
at org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.findAdvisorsThatCanApply(AbstractAdvisorAutoProxyCreator.java:118)
at org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.findEligibleAdvisors(AbstractAdvisorAutoProxyCreator.java:88)
at org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.getAdvicesAndAdvisorsForBean(AbstractAdvisorAutoProxyCreator.java:69)
at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.wrapIfNecessary(AbstractAutoProxyCreator.java:359)
at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.postProcessAfterInitialization(AbstractAutoProxyCreator.java:322)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsAfterInitialization(AbstractAutowireCapableBeanFactory.java:409)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1518)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:521)
... 11 more


===============================================================



Create Simple maven app to Test and write AOP

We have made a simple applicatioon to test and run the AOP concept.
Here we have taken the logging aspect as a cross cutting concern.
Created LoginAspect.java and made it aspect using @Aspect and written advice using
@Before("execution(public String getName())")
The two object classes we have used is Circle and Triangle, where both having simple attribute name with getter and setter.
So we need to log it whenever the getter called.
We have created ShapeService class to get the object, for better standard way to present.
AppMain.java is used to test the application.


1. create AOP - simple maven app
2. create xml - spring.xml

need to have name spaces with aop , search for xml with aspectj-autoproxy
<aop:aspectj-autoproxy />

3. create service class ShapeService
4. create model, dto class Triangle,Circle

just add one variable name;

ShapeService add reference to model

5. let's create bean definition for Triangle

      <bean name="triangle" class="org.aop.model.Triangle">
<property name="name" value="Traingle name"></property>
</bean>

<bean name="circle" class="org.aop.model.Circle">
<property name="name" value="Circle name"></property>
</bean>
<bean name="shapeService" class="org.aop.service.ShapeService"
autowire="byName"></bean>

6. Test bean creation with main method

public class AppMain {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext(
"spring.xml");

// you need to cast if not use second parameter ShapeService.class
ShapeService shapeService = ctx.getBean("shapeService",
ShapeService.class);

System.out.println(shapeService.getCircle().getName());
}

}

Once you run main method output will be

===============
Circle name
=====================

7. for AOP you need below dependencies

               <dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.7.3</version>
</dependency>

<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.6.11</version>
</dependency>

8. Use case we are discussing is adding log.
First thing = we need to write Aspect = LoginAspect


public class LoginAspect {

public void loginAdvice() {
System.out.println("Login advice run::get method called");
}

}

9. Aspect may contain more than once advice. This is standard terminology.
Next we need to convert the std class for Aspect.
use annotation @Aspect

10. Now we have advice
need to tell spring , congiure that logging need to happen when getName() called
For this moment , I need to run before
Then we have to tell before what

   1. So we include:: @Before
   2. say when:: "execution"
   3. tell execution which method::  public String getName()

@Before("execution(public String getName())")



@Aspect
public class LoginAspect {

@Before("execution(public String getName())")
public void loginAdvice() {
System.out.println("Login advice run::get method called");
}

}

11. Now we need to give bean definition.

<bean name="loginAspect" class="org.aop.aspect.LoginAspect"></bean>

12. Run and get the output

=====================================
Login advice run::get method called
Circle name

===================================

So what happens if we run for Triangle

public class AppMain {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext(
"spring.xml");

// you need to cast if not use second parameter ShapeService.class
ShapeService shapeService = ctx.getBean("shapeService",
ShapeService.class);

System.out.println(shapeService.getTriangle().getName());
}

}


=====================================
Login advice run::get method called
Traingle name

===================================


Note : We have not code inside objects. Spring framework does the work for us.

Final coding

POM.XML  this include more dependencies , more than needed

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

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.test</groupId>
<artifactId>AOP</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>AOP</name>
<description>Aspect Oriented Programming</description>

<properties>
<jdk.version>1.6</jdk.version>
<spring.version>3.2.8.RELEASE</spring.version>
<spring.security.version>3.2.3.RELEASE</spring.security.version>
<jstl.version>1.2</jstl.version>
<javax.servlet.version>3.1.0</javax.servlet.version>
<mysql.connector.version>5.1.30</mysql.connector.version>
</properties>

<dependencies>
<!-- Spring 3 dependencies -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>

<!-- spring jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>

<!-- Spring Security -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>${spring.security.version}</version>
</dependency>

<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>${spring.security.version}</version>
</dependency>

<!-- AOP -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.7.3</version>
</dependency>

<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.6.11</version>
</dependency>

<!-- connect to mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.connector.version}</version>
</dependency>


</dependencies>
</project>
----------------------------------------------------------------------------------------

spring.xml  - bean definition
----------------------------------------------------------------------------------------
<?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-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">

<aop:aspectj-autoproxy />

<bean name="triangle" class="org.aop.model.Triangle">
<property name="name" value="Traingle name"></property>
</bean>

<bean name="circle" class="org.aop.model.Circle">
<property name="name" value="Circle name"></property>
</bean>

<bean name="shapeService" class="org.aop.service.ShapeService"
autowire="byName"></bean>

<bean name="loginAspect" class="org.aop.aspect.LoginAspect"></bean>

</beans>
----------------------------------------------------------------------------------------

Circle.java
----------------------------------------------------------------------------------------
package org.aop.model;

public class Circle {

private String name;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

}

----------------------------------------------------------------------------------------
Triangle.java
----------------------------------------------------------------------------------------
package org.aop.model;

public class Triangle {
private String name;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
}

----------------------------------------------------------------------------------------
ShapeService .java
----------------------------------------------------------------------------------------
package org.aop.service;

import org.aop.model.Circle;
import org.aop.model.Triangle;

public class ShapeService {

private Circle circle;
private Triangle triangle;

public Circle getCircle() {
return circle;
}

public void setCircle(Circle circle) {
this.circle = circle;
}

public Triangle getTriangle() {
return triangle;
}

public void setTriangle(Triangle triangle) {
this.triangle = triangle;
}

}

----------------------------------------------------------------------------------------
LoginAspect .java
----------------------------------------------------------------------------------------
package org.aop.aspect;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

@Aspect
public class LoginAspect {

@Before("execution(public String getName())")
public void loginAdvice() {
System.out.println("Login advice run::get method called");
}

}

--------------------------------------------------------------------------------------------------------------------------
AppMain .java
--------------------------------------------------------------------------------------------------------------------------
package org.aop.main;

import org.aop.service.ShapeService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class AppMain {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext(
"spring.xml");

// you need to cast if not use second parameter ShapeService.class
ShapeService shapeService = ctx.getBean("shapeService",
ShapeService.class);

System.out.println(shapeService.getTriangle().getName());
}

}

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




AOP Issues - Erros come building maven project with AOP

1. Bean creation exception

Issue :: U have missed few dependencies need for AOP , maven dependencies
aspectjrt and aspectjweaver
------------------------------------------------------------------------------------------------------

Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.aop.config.internalAutoProxyCreator': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator]: Constructor threw exception; nested exception is java.lang.NoClassDefFoundError: org/aspectj/lang/annotation/Around
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1037)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:983)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:487)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:296)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:293)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:198)
at org.springframework.context.support.AbstractApplicationContext.registerBeanPostProcessors(AbstractApplicationContext.java:741)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:83)
at org.aop.main.AppMain.main(AppMain.java:9)
Caused by: org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator]: Constructor threw exception; nested exception is java.lang.NoClassDefFoundError: org/aspectj/lang/annotation/Around
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:163)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:87)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1030)
... 12 more
Caused by: java.lang.NoClassDefFoundError: org/aspectj/lang/annotation/Around
at org.springframework.aop.aspectj.annotation.ReflectiveAspectJAdvisorFactory.(ReflectiveAspectJAdvisorFactory.java:74)
at org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator.(AnnotationAwareAspectJAutoProxyCreator.java:53)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:148)
... 14 more
Caused by: java.lang.ClassNotFoundException: org.aspectj.lang.annotation.Around
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 21 more

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


Answer:: add below dependencies, you can select version

               <dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.7.3</version>
</dependency>

<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.6.11</version>
</dependency>


what is AOP Aspect Oriented Programming

Aspect oriented programming amis to increase the modularity by allowing the seperation of cross cutting concerns.
If we compare Aspect oriented programming with object oriented programming , unit of modularity in OOP is an object and where as in AOP the unit of modularity is an Aspect.
In AOP,Aspect works as the modularization of concern known as a crosscutting concern.
Cross cutting concern is an behaviour that "cuts" across multiple points in object model, yet it is distinctly different.
AOP let abstract and encapsulate cross cutting concerns. eg:Logging, Transaction, Security

Wednesday, March 18, 2015

Retrieve Entity object with a embedded key

There are two types of objects.
Entity objects and value objects. Embedded key comes to action where value object / embedded object becomes a primary key for Entity object.

Eg : If we define two classes UserDetails.java - Entity and LoginName - value object/ embedded. Then we set LoginName as a primary key for UserDetail object.

So when we retrieve the UserDetail object from table via hibernate , (session.get.. ) , we have to provide the LoginName object as the serializable key to identify the raw data.

HibernateTest.java -  this class has the retrieve logic

----------------------------------------------------------------------------------------
import java.util.Date;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import dto.user.Address;
import dto.user.LoginName;
import dto.user.UserDetails;

public class HibernateTest {
public static void main(String[] args) {
UserDetails user = new UserDetails();
// user.setUserId(1);

LoginName loginName = new LoginName();
loginName.setFirstName("firstName");
loginName.setLastname("lastname");

user.setUserId(loginName);
user.setUserName("First User");
user.setJoinDate(new Date());
user.setDescription("FU description");

Address homeAddress = new Address();
homeAddress.setCity("hCity");
homeAddress.setPincode("hPincode");
homeAddress.setState("hstate");
homeAddress.setStreet("hstreet");

Address officeAddress = new Address();
officeAddress.setCity("oCity");
officeAddress.setPincode("oPincode");
officeAddress.setState("ostate");
officeAddress.setStreet("ostreet");

user.setHomeAddress(homeAddress);
user.setOfficeAddress(officeAddress);
// create session factory - one object- get session from SessionFactory
// need configuration to build sessionFactory
// new Configuration().configure()
// u need to have hibernate.cfg.xml in default place resources

SessionFactory sessionFactory = new Configuration().configure()
.buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(user);
session.getTransaction().commit();
session.close();

// retrieve object
user = null;
session = sessionFactory.openSession();
session.beginTransaction();
user = (UserDetails) session.get(UserDetails.class, loginName);
System.out.println(user);
}
}



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


Other classes needed to test this application

UserDetails.java
----------------------------------------------------------------------------------------
package dto.user;

import java.util.Date;

import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.Lob;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;

@Entity
@Table(name = "USER_DETAILS")
public class UserDetails {

@EmbeddedId
private LoginName userId;
@Basic
private String userName;

@Temporal(TemporalType.TIMESTAMP)
private Date joinDate;
@Transient
private String notInTable;
@Embedded
@AttributeOverrides({
@AttributeOverride(name = "street", column = @Column(name = "HOME_STREET_NAME")),
@AttributeOverride(name = "city", column = @Column(name = "HOME_CITY_NAME")),
@AttributeOverride(name = "state", column = @Column(name = "HOME_STATE_NAME")),
@AttributeOverride(name = "pincode", column = @Column(name = "HOME_PINCODE")) })
private Address homeAddress;
@Embedded
@AttributeOverrides({
@AttributeOverride(name = "street", column = @Column(name = "OFFICE_STREET_NAME")),
@AttributeOverride(name = "city", column = @Column(name = "OFFICE_CITY_NAME")),
@AttributeOverride(name = "state", column = @Column(name = "OFFICE_STATE_NAME")),
@AttributeOverride(name = "pincode", column = @Column(name = "OFFICE_PINCODE")) })
private Address officeAddress;

@Lob
private String description;

public LoginName getUserId() {
return userId;
}

public void setUserId(LoginName userId) {
this.userId = userId;
}

public String getUserName() {
return userName;
}

public void setUserName(String userName) {
this.userName = userName;
}

public Date getJoinDate() {
return joinDate;
}

public void setJoinDate(Date joinDate) {
this.joinDate = joinDate;
}

public String getNotInTable() {
return notInTable;
}

public void setNotInTable(String notInTable) {
this.notInTable = notInTable;
}

public String getDescription() {
return description;
}

public void setDescription(String description) {
this.description = description;
}

public Address getHomeAddress() {
return homeAddress;
}

public void setHomeAddress(Address homeAddress) {
this.homeAddress = homeAddress;
}

public Address getOfficeAddress() {
return officeAddress;
}

public void setOfficeAddress(Address officeAddress) {
this.officeAddress = officeAddress;
}

@Override
public String toString() {
return "UserDetails [userId=" + userId + ", userName=" + userName
+ ", joinDate=" + joinDate + ", notInTable=" + notInTable
+ ", homeAddress=" + homeAddress + ", officeAddress="
+ officeAddress + ", description=" + description + "]";
}
}

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

LoginName.java
----------------------------------------------------------------------------------------
package dto.user;

import java.io.Serializable;

import javax.persistence.Embeddable;

@Embeddable
public class LoginName implements Serializable {

/**
*
*/
private static final long serialVersionUID = -121704761597041786L;
private String firstName;
private String lastname;

public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

public String getLastname() {
return lastname;
}

public void setLastname(String lastname) {
this.lastname = lastname;
}

@Override
public String toString() {
return "LoginName [firstName=" + firstName + ", lastname=" + lastname
+ "]";
}

}

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

hibernate.cfg.xml
-----------------------------------------------------------------------------------------
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.bytecode.use_reflection_optimizer">false</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">root123</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test1</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>

<!-- drop and recreate databse on startup -->
<!-- <property name="hbm2ddl.auto">create</property> -->
<property name="hbm2ddl.auto">create</property>

<!-- dto classes annotated -->
<!-- previously <mapping resource="com/common/Stock.hbm.xml"></mapping> -->
<!-- if you do not have class the u have to comment -->
<!-- <mapping class="com.common.Stock"></mapping> -->
<mapping class="dto.user.UserDetails"></mapping>
</session-factory>
</hibernate-configuration>


------------------------------------------------------------------------------------------
Output of test class - HibernateTest.java
-------------------------------------------------------------------------------------------

INFO: HHH000227: Running hbm2ddl schema export
Hibernate: drop table if exists USER_DETAILS
Hibernate: create table USER_DETAILS (firstName varchar(255) not null, lastname varchar(255) not null, description longtext, HOME_CITY_NAME varchar(255), HOME_PINCODE varchar(255), HOME_STATE_NAME varchar(255), HOME_STREET_NAME varchar(255), joinDate datetime, OFFICE_CITY_NAME varchar(255), OFFICE_PINCODE varchar(255), OFFICE_STATE_NAME varchar(255), OFFICE_STREET_NAME varchar(255), userName varchar(255), primary key (firstName, lastname))
Mar 18, 2015 4:49:46 PM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000230: Schema export complete
Hibernate: insert into USER_DETAILS (description, HOME_CITY_NAME, HOME_PINCODE, HOME_STATE_NAME, HOME_STREET_NAME, joinDate, OFFICE_CITY_NAME, OFFICE_PINCODE, OFFICE_STATE_NAME, OFFICE_STREET_NAME, userName, firstName, lastname) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
Hibernate: select userdetail0_.firstName as firstNam1_0_0_, userdetail0_.lastname as lastname2_0_0_, userdetail0_.description as descript3_0_0_, userdetail0_.HOME_CITY_NAME as HOME_CIT4_0_0_, userdetail0_.HOME_PINCODE as HOME_PIN5_0_0_, userdetail0_.HOME_STATE_NAME as HOME_STA6_0_0_, userdetail0_.HOME_STREET_NAME as HOME_STR7_0_0_, userdetail0_.joinDate as joinDate8_0_0_, userdetail0_.OFFICE_CITY_NAME as OFFICE_C9_0_0_, userdetail0_.OFFICE_PINCODE as OFFICE_10_0_0_, userdetail0_.OFFICE_STATE_NAME as OFFICE_11_0_0_, userdetail0_.OFFICE_STREET_NAME as OFFICE_12_0_0_, userdetail0_.userName as userNam13_0_0_ from USER_DETAILS userdetail0_ where userdetail0_.firstName=? and userdetail0_.lastname=?
UserDetails [userId=LoginName [firstName=firstName, lastname=lastname], userName=First User, joinDate=2015-03-18 16:49:44.0, notInTable=null, homeAddress=Address [street=hstreet, city=hCity, state=hstate, pincode=hPincode], officeAddress=Address [street=ostreet, city=oCity, state=ostate, pincode=oPincode], description=FU description]



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


Error which can come if you do not provide correct class object as key

let's give a String as key instead of object of LoginName.java

                session = sessionFactory.openSession();
session.beginTransaction();
user = (UserDetails) session.get(UserDetails.class, "firstName");
System.out.println(user);
-------------------------------------------------------------------------------------------

Exception in thread "main" org.hibernate.TypeMismatchException: Provided id of the wrong type for class dto.user.UserDetails. Expected: class dto.user.LoginName, got class java.lang.String
at org.hibernate.event.internal.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:134)
at org.hibernate.internal.SessionImpl.fireLoad(SessionImpl.java:1070)
at org.hibernate.internal.SessionImpl.access$2000(SessionImpl.java:176)
at org.hibernate.internal.SessionImpl$IdentifierLoadAccessImpl.load(SessionImpl.java:2551)
at org.hibernate.internal.SessionImpl.get(SessionImpl.java:955)
at HibernateTest.main(HibernateTest.java:56)



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


Error in trying to retrieve using "NULL" value as key

session = sessionFactory.openSession();
session.beginTransaction();
loginName =null;
user = (UserDetails) session.get(UserDetails.class, loginName);
System.out.println(user);

Here I have set loginName =null;

------------------------------------------------------------------------------------------------
Exception in thread "main" java.lang.IllegalArgumentException: id to load is required for loading
at org.hibernate.event.spi.LoadEvent.(LoadEvent.java:109)
at org.hibernate.event.spi.LoadEvent.(LoadEvent.java:79)
at org.hibernate.internal.SessionImpl$IdentifierLoadAccessImpl.load(SessionImpl.java:2548)
at org.hibernate.internal.SessionImpl.get(SessionImpl.java:955)
at HibernateTest.main(HibernateTest.java:57)

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