KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > example > ConnectionInterceptor


1 package example;
2
3 import java.lang.reflect.Method JavaDoc;
4
5 import java.sql.Connection JavaDoc;
6
7 import javax.naming.InitialContext JavaDoc;
8 import javax.naming.NamingException JavaDoc;
9
10 import javax.sql.DataSource JavaDoc;
11
12 import org.aopalliance.intercept.MethodInterceptor;
13 import org.aopalliance.intercept.MethodInvocation;
14
15 /**
16  * The require connection interceptor.
17  */

18 public class ConnectionInterceptor implements MethodInterceptor {
19   private DataSource JavaDoc _dataSource;
20   private int _connParamIndex = -1;
21
22   /**
23    * Configures the data source based on the annotation value.
24    */

25   public void setValue(String JavaDoc jndiName)
26     throws NamingException JavaDoc
27   {
28     String JavaDoc name = jndiName;
29
30     if (name.indexOf(':') < 0)
31       name = "java:comp/env/" + jndiName;
32     
33     _dataSource = (DataSource JavaDoc) new InitialContext JavaDoc().lookup(name);
34   }
35   
36   public Object JavaDoc invoke(MethodInvocation inv) throws Throwable JavaDoc
37   {
38     if (_connParamIndex < 0)
39       _connParamIndex = getParamIndex(inv.getMethod());
40
41     Object JavaDoc []args = inv.getArguments();
42       
43     Connection JavaDoc oldConn = (Connection JavaDoc) args[_connParamIndex];
44     Connection JavaDoc conn = oldConn;
45
46     try {
47       if (conn == null) {
48     conn = _dataSource.getConnection();
49     
50     args[_connParamIndex] = conn;
51       }
52       
53       return inv.proceed();
54     } finally {
55       if (oldConn == null && conn != null)
56     conn.close();
57     }
58   }
59
60   /**
61    * Returns the parameter index of the Connection parameter.
62    *
63    * @param method the calling method.
64    */

65   private int getParamIndex(Method JavaDoc method)
66   {
67     Class JavaDoc []paramTypes = method.getParameterTypes();
68
69     for (int i = 0; i < paramTypes.length; i++) {
70       if (Connection JavaDoc.class.equals(paramTypes[i]))
71     return i;
72     }
73
74     throw new IllegalArgumentException JavaDoc(method.toString());
75   }
76 }
77
Popular Tags