Source Code Cross Referenced for JdbcDataSource.java in  » Web-Mail » james-2.3.1 » org » apache » james » util » dbcp » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Java Source Code / Java Documentation
1. 6.0 JDK Core
2. 6.0 JDK Modules
3. 6.0 JDK Modules com.sun
4. 6.0 JDK Modules com.sun.java
5. 6.0 JDK Modules sun
6. 6.0 JDK Platform
7. Ajax
8. Apache Harmony Java SE
9. Aspect oriented
10. Authentication Authorization
11. Blogger System
12. Build
13. Byte Code
14. Cache
15. Chart
16. Chat
17. Code Analyzer
18. Collaboration
19. Content Management System
20. Database Client
21. Database DBMS
22. Database JDBC Connection Pool
23. Database ORM
24. Development
25. EJB Server geronimo
26. EJB Server GlassFish
27. EJB Server JBoss 4.2.1
28. EJB Server resin 3.1.5
29. ERP CRM Financial
30. ESB
31. Forum
32. GIS
33. Graphic Library
34. Groupware
35. HTML Parser
36. IDE
37. IDE Eclipse
38. IDE Netbeans
39. Installer
40. Internationalization Localization
41. Inversion of Control
42. Issue Tracking
43. J2EE
44. JBoss
45. JMS
46. JMX
47. Library
48. Mail Clients
49. Net
50. Parser
51. PDF
52. Portal
53. Profiler
54. Project Management
55. Report
56. RSS RDF
57. Rule Engine
58. Science
59. Scripting
60. Search Engine
61. Security
62. Sevlet Container
63. Source Control
64. Swing Library
65. Template Engine
66. Test Coverage
67. Testing
68. UML
69. Web Crawler
70. Web Framework
71. Web Mail
72. Web Server
73. Web Services
74. Web Services apache cxf 2.0.1
75. Web Services AXIS2
76. Wiki Engine
77. Workflow Engines
78. XML
79. XML UI
Java
Java Tutorial
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java Source Code / Java Documentation » Web Mail » james 2.3.1 » org.apache.james.util.dbcp 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


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:         *   &lt;jdbc&gt;
044:
045:         *     &lt;pool-controller min="<i>5</i>" max="<i>10</i>" connection-class="<i>my.overrided.ConnectionClass</i>"&gt;
046:         *       &lt;keep-alive&gt;select 1&lt;/keep-alive&gt;
047:         *     &lt;/pool-controller&gt;
048:
049:         *     &lt;driver&gt;<i>com.database.jdbc.JdbcDriver</i>&lt;/driver&gt;
050:         *     &lt;dburl&gt;<i>jdbc:driver://host/mydb</i>&lt;/dburl&gt;
051:         *     &lt;user&gt;<i>username</i>&lt;/user&gt;
052:         *     &lt;password&gt;<i>password</i>&lt;/password&gt;
053:         *   &lt;/jdbc&gt;
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:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.