001 /* 002 Copyright (C) 2001-2003 Lionel Seinturier <Lionel.Seinturier@lip6.fr> 003 004 This program is free software; you can redistribute it and/or modify 005 it under the terms of the GNU Lesser General Public License as 006 published by the Free Software Foundation; either version 2 of the 007 License, or (at your option) any later version. 008 009 This program is distributed in the hope that it will be useful, 010 but WITHOUT ANY WARRANTY; without even the implied warranty of 011 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 012 GNU Lesser General Public License for more details. 013 014 You should have received a copy of the GNU Lesser General Public License 015 along with this program; if not, write to the Free Software 016 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ 017 018 package org.objectweb.jac.aspects.distrans.persistence; 019 020 import java.sql.Connection; 021 import java.sql.SQLException; 022 import java.util.HashMap; 023 import java.util.Map; 024 025 import org.enhydra.jdbc.pool.StandardXAPoolDataSource; 026 import org.enhydra.jdbc.standard.StandardXADataSource; 027 028 /** 029 * This class implements a cache of connections 030 * towards multiple XADataSource. 031 * Contrary to a simple pool that manages multiple connections 032 * towards a single XADataSource, this cache manages connections 033 * for each XADataSource registered in the cache. 034 * Hence, this is a pool of pools. 035 * 036 * @author Lionel Seinturier <Lionel.Seinturier@lip6.fr> 037 * @version 1.0 038 */ 039 public class XAPoolCache { 040 041 /** 042 * Cache of connections: 043 * - keys are StandardXADataSource objects 044 * - values are Connection objects 045 */ 046 private static Map pools = new HashMap(); 047 048 /** Size of each pool. */ 049 private final static int POOL_SIZE = 4; 050 051 052 /** 053 * Get a connection for a XADataSource. 054 * Either return the reference towards an already 055 * existing connection, or create a new one. 056 * 057 * @param ds the XADataSource instance 058 * @return a SQL connection 059 */ 060 public static Connection getConnection( StandardXADataSource ds ) 061 throws SQLException { 062 063 /** Check whether the connection is pooled and still open. */ 064 Connection connection = (Connection) pools.get(ds); 065 if ( connection!= null && !connection.isClosed() ) { 066 return connection; 067 } 068 069 StandardXAPoolDataSource pool = 070 new StandardXAPoolDataSource(POOL_SIZE); 071 pool.setUser( ds.getUser() ); 072 pool.setPassword( ds.getPassword() ); 073 pool.setTransactionManager( ds.getTransactionManager() ); 074 pool.setDataSource(ds); 075 076 connection = pool.getConnection(); 077 pools.put(ds,connection); 078 079 return connection; 080 } 081 082 }