1   /**
2    * Copyright (c) 2000-2010 Liferay, Inc. All rights reserved.
3    *
4    * This library is free software; you can redistribute it and/or modify it under
5    * the terms of the GNU Lesser General Public License as published by the Free
6    * Software Foundation; either version 2.1 of the License, or (at your option)
7    * any later version.
8    *
9    * This library is distributed in the hope that it will be useful, but WITHOUT
10   * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
11   * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
12   * details.
13   */
14  
15  package com.liferay.portal.spring.aop;
16  
17  import com.liferay.portal.kernel.util.MethodTargetClassKey;
18  
19  import java.lang.annotation.Annotation;
20  import java.lang.reflect.Method;
21  
22  import java.util.Map;
23  import java.util.concurrent.ConcurrentHashMap;
24  
25  import org.aopalliance.intercept.MethodInvocation;
26  
27  /**
28   * <a href="AnnotationChainableMethodAdvice.java.html"><b><i>View Source</i></b>
29   * </a>
30   *
31   * @author Shuyang Zhou
32   * @author Brian Wing Shun Chan
33   */
34  public abstract class AnnotationChainableMethodAdvice<T extends Annotation>
35      extends ChainableMethodAdvice {
36  
37      public abstract Class<T> getAnnotationClass();
38  
39      public abstract T getNullAnnotation();
40  
41      protected MethodTargetClassKey buildMethodTargetClassKey(
42          MethodInvocation methodInvocation) {
43  
44          Method method = methodInvocation.getMethod();
45  
46          Class<?> targetClass = null;
47  
48          Object thisObject = methodInvocation.getThis();
49  
50          if (thisObject != null) {
51              targetClass = thisObject.getClass();
52          }
53  
54          return new MethodTargetClassKey(method, targetClass);
55      }
56  
57      protected T findAnnotation(MethodTargetClassKey methodTargetClassKey){
58          T annotation = annotations.get(methodTargetClassKey);
59  
60          if (annotation != null) {
61              return annotation;
62          }
63  
64          Method method = methodTargetClassKey.getMethod();
65  
66          Method targetMethod = methodTargetClassKey.getTargetMethod();
67  
68          Class<T> annotationClass = getAnnotationClass();
69  
70          if (targetMethod != null) {
71              annotation = targetMethod.getAnnotation(annotationClass);
72          }
73  
74          if (annotation == null) {
75              annotation = method.getAnnotation(annotationClass);
76          }
77  
78          if (annotation == null) {
79              annotation = getNullAnnotation();
80          }
81  
82          annotations.put(methodTargetClassKey, annotation);
83  
84          return annotation;
85      }
86  
87      protected Map<MethodTargetClassKey, T> annotations =
88          new ConcurrentHashMap<MethodTargetClassKey, T>();
89  
90  }