001: /****************************************************************
002: * Licensed to the Apache Software Foundation (ASF) under one *
003: * or more contributor license agreements. See the NOTICE file *
004: * distributed with this work for additional information *
005: * regarding copyright ownership. The ASF licenses this file *
006: * to you under the Apache License, Version 2.0 (the *
007: * "License"); you may not use this file except in compliance *
008: * with the License. You may obtain a copy of the License at *
009: * *
010: * http://www.apache.org/licenses/LICENSE-2.0 *
011: * *
012: * Unless required by applicable law or agreed to in writing, *
013: * software distributed under the License is distributed on an *
014: * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
015: * KIND, either express or implied. See the License for the *
016: * specific language governing permissions and limitations *
017: * under the License. *
018: ****************************************************************/package org.apache.james.util.dbcp;
019:
020: import org.apache.avalon.excalibur.datasource.DataSourceComponent;
021: import org.apache.avalon.framework.activity.Disposable;
022: import org.apache.avalon.framework.configuration.Configurable;
023: import org.apache.avalon.framework.configuration.Configuration;
024: import org.apache.avalon.framework.configuration.ConfigurationException;
025: import org.apache.avalon.framework.logger.AbstractLogEnabled;
026: import org.apache.commons.dbcp.BasicDataSource;
027:
028: import java.io.PrintWriter;
029: import java.sql.Connection;
030: import java.sql.SQLException;
031:
032: /**
033: * <p>
034: * This is a reliable DataSource implementation, based on the pooling logic provided by <a
035: * href="http://jakarta.apache.org/commons/dbcp.html">DBCP</a> and the configuration found in
036: * Avalon's excalibur code.
037: * </p>
038: *
039: * <p>
040: * This uses the normal <code>java.sql.Connection</code> object and
041: * <code>java.sql.DriverManager</code>. The Configuration is like this:
042: * <pre>
043: * <jdbc>
044:
045: * <pool-controller min="<i>5</i>" max="<i>10</i>" connection-class="<i>my.overrided.ConnectionClass</i>">
046: * <keep-alive>select 1</keep-alive>
047: * </pool-controller>
048:
049: * <driver><i>com.database.jdbc.JdbcDriver</i></driver>
050: * <dburl><i>jdbc:driver://host/mydb</i></dburl>
051: * <user><i>username</i></user>
052: * <password><i>password</i></password>
053: * </jdbc>
054: * </pre>
055: * </p>
056: * <p>
057: * These configuration settings are available:
058: * <ul>
059: * <li><b>driver</b> - The class name of the JDBC driver</li>
060: * <li><b>dburl</b> - The JDBC URL for this connection</li>
061: * <li><b>user</b> - The username to use for this connection</li>
062: * <li><b>password</b> - The password to use for this connection</li>
063: * <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>
064: * <li><b>max</b> - The maximum number of active connections allowed in the pool. 0 means no limit. (default 2)</li>
065: * <li><b>max_idle</b> - The maximum number of idle connections. 0 means no limit. (default 0)</li>
066: * <li><b>initial_size</b> - The initial number of connections that are created when the pool is started. (default 0)</li>
067: * <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>
068: * <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>
069: * <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>
070: * <li><b>testOnReturn</b> - The indication of whether objects will be validated before being returned to the pool. (default false)</li>
071: * <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>
072: * <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>
073: * <li><b>numTestsPerEvictionRun</b> - The number of objects to examine during each run of the idle object evictor thread (if any). (default 3)</li>
074: * <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>
075: * </ul>
076: *
077: * @version CVS $Revision: 494012 $
078: */
079: public class JdbcDataSource extends AbstractLogEnabled implements
080: Configurable, Disposable, DataSourceComponent {
081:
082: BasicDataSource source = null;
083:
084: //Jdbc2PoolDataSource source = null;
085: //PoolingDataSource source = null;
086:
087: /**
088: * @see org.apache.avalon.framework.configuration.Configurable#configure(Configuration)
089: */
090: public void configure(final Configuration configuration)
091: throws ConfigurationException {
092: //Configure the DBCP
093: try {
094: String driver = configuration.getChild("driver").getValue(
095: null);
096: Class.forName(driver);
097:
098: String dburl = configuration.getChild("dburl").getValue(
099: null);
100: String user = configuration.getChild("user").getValue(null);
101: String password = configuration.getChild("password")
102: .getValue(null);
103:
104: // This inner class extends DBCP's BasicDataSource, and
105: // turns on validation (using Connection.isClosed()), so
106: // that the pool can recover from a server outage.
107: source = new BasicDataSource() {
108: protected synchronized javax.sql.DataSource createDataSource()
109: throws SQLException {
110: if (dataSource != null) {
111: return (dataSource);
112: } else {
113: javax.sql.DataSource ds = super
114: .createDataSource();
115: connectionPool.setTestOnBorrow(true);
116: connectionPool.setTestOnReturn(true);
117: return ds;
118: }
119: }
120: };
121:
122: source.setDriverClassName(driver);
123: source.setUrl(dburl);
124: source.setUsername(user);
125: source.setPassword(password);
126: source.setMaxActive(configuration.getChild("max")
127: .getValueAsInteger(2));
128: source.setMaxIdle(configuration.getChild("max_idle")
129: .getValueAsInteger(0));
130: source.setInitialSize(configuration
131: .getChild("initial_size").getValueAsInteger(0));
132: source.setMinIdle(configuration.getChild("min_idle")
133: .getValueAsInteger(0));
134: //This is necessary, otherwise a connection could hang forever
135: source.setMaxWait(configuration.getChild("max_wait")
136: .getValueAsInteger(5000));
137: source.setValidationQuery(configuration.getChild(
138: "keep-alive").getValue(null));
139: source.setTestOnBorrow(configuration.getChild(
140: "testOnBorrow").getValueAsBoolean(true));
141: source.setTestOnReturn(configuration.getChild(
142: "testOnReturn").getValueAsBoolean(false));
143: source.setTestWhileIdle(configuration.getChild(
144: "testWhileIdle").getValueAsBoolean(false));
145: source.setTimeBetweenEvictionRunsMillis(configuration
146: .getChild("timeBetweenEvictionRunsMillis")
147: .getValueAsInteger(-1));
148: source.setNumTestsPerEvictionRun(configuration.getChild(
149: "numTestsPerEvictionRun").getValueAsInteger(3));
150: source.setMinEvictableIdleTimeMillis(configuration
151: .getChild("minEvictableIdleTimeMillis")
152: .getValueAsInteger(1000 * 30 * 60));
153:
154: //Unsupported
155: //source.setLoginTimeout(configuration.getChild("login_timeout").getValueAsInteger(0));
156:
157: // DBCP uses a PrintWriter approach to logging. This
158: // Writer class will bridge between DBCP and Avalon
159: // Logging. Unfortunately, DBCP 1.0 is clueless about the
160: // concept of a log level.
161: final java.io.Writer writer = new java.io.CharArrayWriter() {
162: public void flush() {
163: // flush the stream to the log
164: if (JdbcDataSource.this .getLogger()
165: .isErrorEnabled()) {
166: JdbcDataSource.this .getLogger().error(
167: toString());
168: }
169: reset(); // reset the contents for the next message
170: }
171: };
172:
173: source.setLogWriter(new PrintWriter(writer, true));
174:
175: // Extra debug for first cut
176: getLogger().debug("max wait: " + source.getMaxWait());
177: getLogger().debug("max idle: " + source.getMaxIdle());
178: getLogger().debug("max active: " + source.getMaxActive());
179: getLogger().debug(
180: "initial size: " + source.getInitialSize());
181: getLogger().debug(
182: "TestOnBorrow: " + source.getTestOnBorrow());
183: getLogger().debug(
184: "TestOnReturn: " + source.getTestOnReturn());
185: getLogger().debug(
186: "TestWhileIdle: " + source.getTestWhileIdle());
187: getLogger().debug(
188: "NumTestsPerEvictionRun(): "
189: + source.getNumTestsPerEvictionRun());
190: getLogger().debug(
191: "MinEvictableIdleTimeMillis(): "
192: + source.getMinEvictableIdleTimeMillis());
193: getLogger()
194: .debug(
195: "TimeBetweenEvictionRunsMillis(): "
196: + source
197: .getTimeBetweenEvictionRunsMillis());
198:
199: /*
200: //Another sample that doesn't work
201: GenericObjectPool connectionPool = new GenericObjectPool(null);
202: ConnectionFactory connectionFactory =
203: new DriverManagerConnectionFactory(dburl, user, password);
204: PoolableConnectionFactory poolableConnectionFactory =
205: new PoolableConnectionFactory(connectionFactory, connectionPool, null, null, false, true);
206: PoolingDataSource dataSource = new PoolingDataSource(connectionPool);
207: source = dataSource;
208: */
209:
210: /*
211: As documented on the DBCP website, which is wrong
212: DriverAdapterCPDS cpds = new DriverAdapterCPDS();
213: cpds.setDriver(configuration.getChild("driver").getValue(null));
214: cpds.setUrl(configuration.getChild("dburl").getValue(null));
215: cpds.setUsername(configuration.getChild("user").getValue(null));
216: cpds.setPassword(configuration.getChild("password").getValue(null));
217:
218: source = new Jdbc2PoolDataSource();
219: source.setConnectionPoolDataSource(cpds);
220: source.setDefaultMaxActive(10);
221: source.setDefaultMaxWait(50);
222: */
223:
224: //Get a connection and close it, just to test that we connected.
225: source.getConnection().close();
226: } catch (Exception e) {
227: throw new ConfigurationException(
228: "Error configurable datasource", e);
229: }
230: }
231:
232: /**
233: * @see org.apache.avalon.framework.configuration.Configurable#dispose()
234: */
235: public void dispose() {
236: //Close all database connections
237: try {
238: source.close();
239: } catch (SQLException sqle) {
240: sqle.printStackTrace();
241: }
242: }
243:
244: /**
245: *
246: */
247: public Connection getConnection() throws SQLException {
248: return source.getConnection();
249: }
250: }
|