1 22 23 package org.xquark.jdbc.datasource; 24 25 import java.io.PrintWriter ; 26 import java.sql.Connection ; 27 import java.sql.SQLException ; 28 29 import javax.sql.DataSource ; 30 31 import org.apache.commons.dbcp.ConnectionFactory; 32 import org.apache.commons.dbcp.PoolableConnectionFactory; 33 import org.apache.commons.dbcp.PoolingDataSource; 34 import org.apache.commons.pool.impl.GenericObjectPool; 35 36 37 public class SingleConnectionDataSource implements DataSource { 38 39 private PoolingDataSource dataSource; 40 private Connection singleConnection; 41 42 public SingleConnectionDataSource(Connection connection) throws SQLException { 43 singleConnection = connection; 44 45 GenericObjectPool connectionPool = new GenericObjectPool(); 46 connectionPool.setMaxActive(1); 47 connectionPool.setMaxIdle(1); 48 connectionPool.setMinIdle(1); 49 connectionPool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_FAIL); 50 51 ConnectionFactory jdbcConnectionFactory = new ConnectionFactory() { 52 53 public Connection createConnection() throws SQLException { 54 return singleConnection; 55 } 56 57 }; 58 59 PoolableConnectionFactory connectionFactory = 60 new PoolableConnectionFactory(jdbcConnectionFactory, 61 connectionPool, 62 null, 63 null, 64 false, 65 true); 66 if (connectionFactory == null) { 67 throw new SQLException ("Cannot create PoolableConnectionFactory"); 68 } 69 dataSource = new PoolingDataSource(connectionPool); 70 } 71 72 77 public Connection getConnection() throws SQLException { 78 return dataSource.getConnection(); 79 } 80 81 90 public Connection getConnection(String username, String password) throws SQLException { 91 return dataSource.getConnection(username, password); 92 } 93 94 99 public int getLoginTimeout() throws SQLException { 100 return dataSource.getLoginTimeout(); 101 } 102 103 108 public PrintWriter getLogWriter() throws SQLException { 109 return dataSource.getLogWriter(); 110 } 111 112 119 public void setLoginTimeout(int loginTimeout) throws SQLException { 120 dataSource.setLoginTimeout(loginTimeout); 121 } 122 123 130 public void setLogWriter(PrintWriter logWriter) throws SQLException { 131 dataSource.setLogWriter(logWriter); 132 } 133 134 } 135 | Popular Tags |