1 /**************************************************************** 2 * Licensed to the Apache Software Foundation (ASF) under one * 3 * or more contributor license agreements. See the NOTICE file * 4 * distributed with this work for additional information * 5 * regarding copyright ownership. The ASF licenses this file * 6 * to you under the Apache License, Version 2.0 (the * 7 * "License"); you may not use this file except in compliance * 8 * with the License. You may obtain a copy of the License at * 9 * * 10 * http://www.apache.org/licenses/LICENSE-2.0 * 11 * * 12 * Unless required by applicable law or agreed to in writing, * 13 * software distributed under the License is distributed on an * 14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * 15 * KIND, either express or implied. See the License for the * 16 * specific language governing permissions and limitations * 17 * under the License. * 18 ****************************************************************/ 19 20 21 22 package org.apache.james.util.dbcp; 23 24 import org.apache.avalon.excalibur.datasource.DataSourceComponent; 25 import org.apache.avalon.framework.activity.Disposable; 26 import org.apache.avalon.framework.configuration.Configurable; 27 import org.apache.avalon.framework.configuration.Configuration; 28 import org.apache.avalon.framework.configuration.ConfigurationException; 29 import org.apache.avalon.framework.logger.AbstractLogEnabled; 30 import org.apache.commons.dbcp.BasicDataSource; 31 32 import java.io.PrintWriter; 33 import java.sql.Connection; 34 import java.sql.SQLException; 35 36 /** 37 * <p> 38 * This is a reliable DataSource implementation, based on the pooling logic provided by <a 39 * href="http://jakarta.apache.org/commons/dbcp.html">DBCP</a> and the configuration found in 40 * Avalon's excalibur code. 41 * </p> 42 * 43 * <p> 44 * This uses the normal <code>java.sql.Connection</code> object and 45 * <code>java.sql.DriverManager</code>. The Configuration is like this: 46 * <pre> 47 * <jdbc> 48 49 * <pool-controller min="<i>5</i>" max="<i>10</i>" connection-class="<i>my.overrided.ConnectionClass</i>"> 50 * <keep-alive>select 1</keep-alive> 51 * </pool-controller> 52 53 * <driver><i>com.database.jdbc.JdbcDriver</i></driver> 54 * <dburl><i>jdbc:driver://host/mydb</i></dburl> 55 * <user><i>username</i></user> 56 * <password><i>password</i></password> 57 * </jdbc> 58 * </pre> 59 * </p> 60 * <p> 61 * These configuration settings are available: 62 * <ul> 63 * <li><b>driver</b> - The class name of the JDBC driver</li> 64 * <li><b>dburl</b> - The JDBC URL for this connection</li> 65 * <li><b>user</b> - The username to use for this connection</li> 66 * <li><b>password</b> - The password to use for this connection</li> 67 * <li><b>keep-alive</b> - The SQL query that will be used to validate connections from this pool before returning them to the caller. If specified, this query <strong>MUST</strong> be an SQL SELECT statement that returns at least one row.</li> 68 * <li><b>max</b> - The maximum number of active connections allowed in the pool. 0 means no limit. (default 2)</li> 69 * <li><b>max_idle</b> - The maximum number of idle connections. 0 means no limit. (default 0)</li> 70 * <li><b>initial_size</b> - The initial number of connections that are created when the pool is started. (default 0)</li> 71 * <li><b>min_idle</b> - The minimum number of active connections that can remain idle in the pool, without extra ones being created, or zero to create none. (default 0)</li> 72 * <li><b>max_wait</b> - The maximum number of milliseconds that the pool will wait (when there are no available connections) for a connection to be returned before throwing an exception, or -1 to wait indefinitely. (default -1)</li> 73 * <li><b>testOnBorrow</b> - The indication of whether objects will be validated before being borrowed from the pool. If the object fails to validate, it will be dropped from the pool, and we will attempt to borrow another. (default true)</li> 74 * <li><b>testOnReturn</b> - The indication of whether objects will be validated before being returned to the pool. (default false)</li> 75 * <li><b>testWhileIdle</b> - The indication of whether objects will be validated by the idle object evictor (if any). If an object fails to validate, it will be dropped from the pool. (default false)</li> 76 * <li><b>timeBetweenEvictionRunsMillis</b> - The number of milliseconds to sleep between runs of the idle object evictor thread. When non-positive, no idle object evictor thread will be run. (default -1)</li> 77 * <li><b>numTestsPerEvictionRun</b> - The number of objects to examine during each run of the idle object evictor thread (if any). (default 3)</li> 78 * <li><b>minEvictableIdleTimeMillis</b> - The minimum amount of time an object may sit idle in the pool before it is eligable for eviction by the idle object evictor (if any). (default 1000 * 60 * 30)</li> 79 * </ul> 80 * 81 * @version CVS $Revision: 449269 $ 82 */ 83 public class JdbcDataSource extends AbstractLogEnabled 84 implements Configurable, 85 Disposable, 86 DataSourceComponent { 87 88 BasicDataSource source = null; 89 //Jdbc2PoolDataSource source = null; 90 //PoolingDataSource source = null; 91 92 /** 93 * @see org.apache.avalon.framework.configuration.Configurable#configure(Configuration) 94 */ 95 public void configure(final Configuration configuration) 96 throws ConfigurationException { 97 //Configure the DBCP 98 try { 99 String driver = configuration.getChild("driver").getValue(null); 100 Class.forName(driver); 101 102 String dburl = configuration.getChild("dburl").getValue(null); 103 String user = configuration.getChild("user").getValue(null); 104 String password = configuration.getChild("password").getValue(null); 105 106 // This inner class extends DBCP's BasicDataSource, and 107 // turns on validation (using Connection.isClosed()), so 108 // that the pool can recover from a server outage. 109 source = new BasicDataSource() { 110 protected synchronized javax.sql.DataSource createDataSource() 111 throws SQLException { 112 if (dataSource != null) { 113 return (dataSource); 114 } else { 115 javax.sql.DataSource ds = super.createDataSource(); 116 connectionPool.setTestOnBorrow(true); 117 connectionPool.setTestOnReturn(true); 118 return ds; 119 } 120 } 121 }; 122 123 source.setDriverClassName(driver); 124 source.setUrl(dburl); 125 source.setUsername(user); 126 source.setPassword(password); 127 source.setMaxActive(configuration.getChild("max").getValueAsInteger(2)); 128 source.setMaxIdle(configuration.getChild("max_idle").getValueAsInteger(0)); 129 source.setInitialSize(configuration.getChild("initial_size").getValueAsInteger(0)); 130 source.setMinIdle(configuration.getChild("min_idle").getValueAsInteger(0)); 131 //This is necessary, otherwise a connection could hang forever 132 source.setMaxWait(configuration.getChild("max_wait").getValueAsInteger(5000)); 133 source.setValidationQuery(configuration.getChild("keep-alive").getValue(null)); 134 source.setTestOnBorrow(configuration.getChild("testOnBorrow").getValueAsBoolean(true)); 135 source.setTestOnReturn(configuration.getChild("testOnReturn").getValueAsBoolean(false)); 136 source.setTestWhileIdle(configuration.getChild("testWhileIdle").getValueAsBoolean(false)); 137 source.setTimeBetweenEvictionRunsMillis(configuration.getChild("timeBetweenEvictionRunsMillis").getValueAsInteger(-1)); 138 source.setNumTestsPerEvictionRun(configuration.getChild("numTestsPerEvictionRun").getValueAsInteger(3)); 139 source.setMinEvictableIdleTimeMillis(configuration.getChild("minEvictableIdleTimeMillis").getValueAsInteger(1000 * 30 * 60)); 140 141 //Unsupported 142 //source.setLoginTimeout(configuration.getChild("login_timeout").getValueAsInteger(0)); 143 144 145 // DBCP uses a PrintWriter approach to logging. This 146 // Writer class will bridge between DBCP and Avalon 147 // Logging. Unfortunately, DBCP 1.0 is clueless about the 148 // concept of a log level. 149 final java.io.Writer writer = new java.io.CharArrayWriter() { 150 public void flush() { 151 // flush the stream to the log 152 if (JdbcDataSource.this.getLogger().isErrorEnabled()) { 153 JdbcDataSource.this.getLogger().error(toString()); 154 } 155 reset(); // reset the contents for the next message 156 } 157 }; 158 159 source.setLogWriter(new PrintWriter(writer, true)); 160 161 // Extra debug for first cut 162 getLogger().debug("max wait: " + source.getMaxWait()); 163 getLogger().debug("max idle: " + source.getMaxIdle()); 164 getLogger().debug("max active: " + source.getMaxActive()); 165 getLogger().debug("initial size: " + source.getInitialSize()); 166 getLogger().debug("TestOnBorrow: " + source.getTestOnBorrow()); 167 getLogger().debug("TestOnReturn: " + source.getTestOnReturn()); 168 getLogger().debug("TestWhileIdle: " + source.getTestWhileIdle()); 169 getLogger().debug("NumTestsPerEvictionRun(): " + source.getNumTestsPerEvictionRun()); 170 getLogger().debug("MinEvictableIdleTimeMillis(): " + source.getMinEvictableIdleTimeMillis()); 171 getLogger().debug("TimeBetweenEvictionRunsMillis(): " + source.getTimeBetweenEvictionRunsMillis()); 172 173 /* 174 //Another sample that doesn't work 175 GenericObjectPool connectionPool = new GenericObjectPool(null); 176 ConnectionFactory connectionFactory = 177 new DriverManagerConnectionFactory(dburl, user, password); 178 PoolableConnectionFactory poolableConnectionFactory = 179 new PoolableConnectionFactory(connectionFactory, connectionPool, null, null, false, true); 180 PoolingDataSource dataSource = new PoolingDataSource(connectionPool); 181 source = dataSource; 182 */ 183 184 /* 185 As documented on the DBCP website, which is wrong 186 DriverAdapterCPDS cpds = new DriverAdapterCPDS(); 187 cpds.setDriver(configuration.getChild("driver").getValue(null)); 188 cpds.setUrl(configuration.getChild("dburl").getValue(null)); 189 cpds.setUsername(configuration.getChild("user").getValue(null)); 190 cpds.setPassword(configuration.getChild("password").getValue(null)); 191 192 source = new Jdbc2PoolDataSource(); 193 source.setConnectionPoolDataSource(cpds); 194 source.setDefaultMaxActive(10); 195 source.setDefaultMaxWait(50); 196 */ 197 198 199 //Get a connection and close it, just to test that we connected. 200 source.getConnection().close(); 201 } catch (Exception e) { 202 throw new ConfigurationException("Error configurable datasource", e); 203 } 204 } 205 206 /** 207 * @see org.apache.avalon.framework.activity.Disposable#dispose() 208 */ 209 public void dispose() { 210 //Close all database connections 211 try { 212 source.close(); 213 } catch (SQLException sqle) { 214 sqle.printStackTrace(); 215 } 216 } 217 218 /** 219 * @see org.apache.avalon.excalibur.datasource.DataSourceComponent#getConnection() 220 */ 221 public Connection getConnection() throws SQLException { 222 return source.getConnection(); 223 } 224 }