1 package example; 2 3 import java.lang.reflect.Method ; 4 5 import java.sql.Connection ; 6 7 import javax.naming.InitialContext ; 8 import javax.naming.NamingException ; 9 10 import javax.sql.DataSource ; 11 12 import org.aopalliance.intercept.MethodInterceptor; 13 import org.aopalliance.intercept.MethodInvocation; 14 15 18 public class ConnectionInterceptor implements MethodInterceptor { 19 private DataSource _dataSource; 20 private int _connParamIndex = -1; 21 22 25 public void setValue(String jndiName) 26 throws NamingException 27 { 28 String name = jndiName; 29 30 if (name.indexOf(':') < 0) 31 name = "java:comp/env/" + jndiName; 32 33 _dataSource = (DataSource ) new InitialContext ().lookup(name); 34 } 35 36 public Object invoke(MethodInvocation inv) throws Throwable 37 { 38 if (_connParamIndex < 0) 39 _connParamIndex = getParamIndex(inv.getMethod()); 40 41 Object []args = inv.getArguments(); 42 43 Connection oldConn = (Connection ) args[_connParamIndex]; 44 Connection 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 65 private int getParamIndex(Method method) 66 { 67 Class []paramTypes = method.getParameterTypes(); 68 69 for (int i = 0; i < paramTypes.length; i++) { 70 if (Connection .class.equals(paramTypes[i])) 71 return i; 72 } 73 74 throw new IllegalArgumentException (method.toString()); 75 } 76 } 77 | Popular Tags |