// Collection of code snippets by Arne Vajhøj 
// (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
package adv1;

import java.lang.reflect.Field;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

aspect DbTrick {
    pointcut dbm() : call(@DatabaseMethod public * *.*(..));
    Object around() throws SQLException : dbm() {
        try {
            Field f = thisJoinPoint.getTarget().getClass().getDeclaredField("con");
            ManagedConnection mc = f.getAnnotation(ManagedConnection.class);
            Connection con = null;
            Object res;
            try {
                con = DriverManager.getConnection(mc.constr(), mc.un(), mc.pw());
                f.setAccessible(true);
                f.set(thisJoinPoint.getTarget(), con);
                res = proceed();
            } finally {
                if(con != null) con.close();
            }
            return res;
        } catch(NoSuchFieldException | IllegalAccessException ex) {
            throw new RuntimeException(ex.getMessage());
        }
    }
}
