package pt.iscte.ci.aop.pooling; import java.sql.Connection; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * * This code has been adapted from the book AspectJ in Action. * * TODO: This class must be more than this, namely to consider factors such as * the size of the pool. * * @author Paulo Zenida * */ public class FenixDBConnectionPool implements DBConnectionPool { private List pooledConnections = new ArrayList(); private Map> connectionsDescriptionMap = new HashMap>(); synchronized public Connection getConnection(String url, String username, String password) throws SQLException { final DBConnectionDescription desc = new DBConnectionDescription(url, username, password); final List connectionsList = getConnections(desc); if (connectionsList == null) { return null; } for (int size = pooledConnections.size(), i = 0; i < size; ++i) { final Connection connection = pooledConnections.get(i); if (connectionsList.contains(connection)) { pooledConnections.remove(connection); if (!connection.isClosed()) { return connection; } } } return null; } synchronized public boolean putConnection(final Connection connection) { pooledConnections.add(connection); return true; } synchronized public void registerConnection(Connection connection, String url, String username, String password) { final DBConnectionDescription desc = new DBConnectionDescription(url, username, password); List connectionsList = getConnections(desc); if (connectionsList == null) { connectionsList = new ArrayList(); connectionsDescriptionMap.put(desc, connectionsList); } connectionsList.add(connection); } private List getConnections(DBConnectionDescription desc) { return connectionsDescriptionMap.get(desc); } }