KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > commons > dbcp > PoolingDriver


1 /*
2  * Copyright 1999-2004 The Apache Software Foundation.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16
17 package org.apache.commons.dbcp;
18
19 import java.io.IOException JavaDoc;
20 import java.io.InputStream JavaDoc;
21 import java.sql.CallableStatement JavaDoc;
22 import java.sql.Connection JavaDoc;
23 import java.sql.DatabaseMetaData JavaDoc;
24 import java.sql.Driver JavaDoc;
25 import java.sql.DriverManager JavaDoc;
26 import java.sql.DriverPropertyInfo JavaDoc;
27 import java.sql.PreparedStatement JavaDoc;
28 import java.sql.SQLException JavaDoc;
29 import java.sql.SQLWarning JavaDoc;
30 import java.sql.Statement JavaDoc;
31 import java.util.HashMap JavaDoc;
32 import java.util.Map JavaDoc;
33 import java.util.NoSuchElementException JavaDoc;
34 import java.util.Properties JavaDoc;
35 import java.util.Set JavaDoc;
36
37 import org.apache.commons.jocl.JOCLContentHandler;
38 import org.apache.commons.pool.ObjectPool;
39 import org.xml.sax.SAXException JavaDoc;
40
41
42 /**
43  * A {@link Driver} implementation that obtains
44  * {@link Connection}s from a registered
45  * {@link ObjectPool}.
46  *
47  * @author Rodney Waldhoff
48  * @author Dirk Verbeeck
49  * @version $Revision: 1.12 $ $Date: 2004/05/17 18:39:44 $
50  */

51 public class PoolingDriver implements Driver JavaDoc {
52     /** Register an myself with the {@link DriverManager}. */
53     static {
54         try {
55             DriverManager.registerDriver(new PoolingDriver());
56         } catch(Exception JavaDoc e) {
57         }
58     }
59
60     /** The map of registered pools. */
61     protected static HashMap JavaDoc _pools = new HashMap JavaDoc();
62
63     /** Controls access to the underlying connection */
64     private static boolean accessToUnderlyingConnectionAllowed = false;
65
66     public PoolingDriver() {
67     }
68
69     /**
70      * Returns the value of the accessToUnderlyingConnectionAllowed property.
71      *
72      * @return true if access to the underlying is allowed, false otherwise.
73      */

74     public static synchronized boolean isAccessToUnderlyingConnectionAllowed() {
75         return accessToUnderlyingConnectionAllowed;
76     }
77
78     /**
79      * Sets the value of the accessToUnderlyingConnectionAllowed property.
80      * It controls if the PoolGuard allows access to the underlying connection.
81      * (Default: false)
82      *
83      * @param allow Access to the underlying connection is granted when true.
84      */

85     public static synchronized void setAccessToUnderlyingConnectionAllowed(boolean allow) {
86         accessToUnderlyingConnectionAllowed = allow;
87     }
88
89     /**
90      * WARNING: This method throws DbcpExceptions (RuntimeExceptions)
91      * and will be replaced by the protected getConnectionPool method.
92      *
93      * @deprecated This will be removed in a future version of DBCP.
94      */

95     public synchronized ObjectPool getPool(String JavaDoc name) {
96         try {
97             return getConnectionPool(name);
98         }
99         catch (Exception JavaDoc e) {
100             throw new DbcpException(e);
101         }
102     }
103     
104     public synchronized ObjectPool getConnectionPool(String JavaDoc name) throws SQLException JavaDoc {
105         ObjectPool pool = (ObjectPool)(_pools.get(name));
106         if(null == pool) {
107             InputStream JavaDoc in = this.getClass().getResourceAsStream(String.valueOf(name) + ".jocl");
108             if(null != in) {
109                 JOCLContentHandler jocl = null;
110                 try {
111                     jocl = JOCLContentHandler.parse(in);
112                 }
113                 catch (SAXException JavaDoc e) {
114                     throw new SQLNestedException("Could not parse configuration file", e);
115                 }
116                 catch (IOException JavaDoc e) {
117                     throw new SQLNestedException("Could not load configuration file", e);
118                 }
119                 if(jocl.getType(0).equals(String JavaDoc.class)) {
120                     pool = getPool((String JavaDoc)(jocl.getValue(0)));
121                     if(null != pool) {
122                         registerPool(name,pool);
123                     }
124                 } else {
125                     pool = ((PoolableConnectionFactory)(jocl.getValue(0))).getPool();
126                     if(null != pool) {
127                         registerPool(name,pool);
128                     }
129                 }
130             }
131             else {
132                 throw new SQLException JavaDoc("Configuration file not found");
133             }
134         }
135         return pool;
136     }
137
138     public synchronized void registerPool(String JavaDoc name, ObjectPool pool) {
139         _pools.put(name,pool);
140     }
141
142     public synchronized void closePool(String JavaDoc name) throws SQLException JavaDoc {
143         ObjectPool pool = (ObjectPool) _pools.get(name);
144         if (pool != null) {
145             _pools.remove(name);
146             try {
147                 pool.close();
148             }
149             catch (Exception JavaDoc e) {
150                 throw new SQLNestedException("Error closing pool " + name, e);
151             }
152         }
153     }
154     
155     public synchronized String JavaDoc[] getPoolNames() throws SQLException JavaDoc{
156         Set JavaDoc names = _pools.keySet();
157         return (String JavaDoc[]) names.toArray(new String JavaDoc[names.size()]);
158     }
159
160     public boolean acceptsURL(String JavaDoc url) throws SQLException JavaDoc {
161         try {
162             return url.startsWith(URL_PREFIX);
163         } catch(NullPointerException JavaDoc e) {
164             return false;
165         }
166     }
167
168     public Connection JavaDoc connect(String JavaDoc url, Properties JavaDoc info) throws SQLException JavaDoc {
169         if(acceptsURL(url)) {
170             ObjectPool pool = getConnectionPool(url.substring(URL_PREFIX_LEN));
171             if(null == pool) {
172                 throw new SQLException JavaDoc("No pool found for " + url + ".");
173             } else {
174                 try {
175                     Connection JavaDoc conn = (Connection JavaDoc)(pool.borrowObject());
176                     if (conn != null) {
177                         conn = new PoolGuardConnectionWrapper(conn);
178                     }
179                     return conn;
180                 } catch(SQLException JavaDoc e) {
181                     throw e;
182                 } catch(NoSuchElementException JavaDoc e) {
183                     throw new SQLNestedException("Cannot get a connection, pool exhausted", e);
184                 } catch(RuntimeException JavaDoc e) {
185                     throw e;
186                 } catch(Exception JavaDoc e) {
187                     throw new SQLNestedException("Cannot get a connection, general error", e);
188                 }
189             }
190         } else {
191             return null;
192         }
193     }
194
195     public int getMajorVersion() {
196         return MAJOR_VERSION;
197     }
198
199     public int getMinorVersion() {
200         return MINOR_VERSION;
201     }
202
203     public boolean jdbcCompliant() {
204         return true;
205     }
206
207     public DriverPropertyInfo JavaDoc[] getPropertyInfo(String JavaDoc url, Properties JavaDoc info) {
208         return new DriverPropertyInfo JavaDoc[0];
209     }
210
211     /** My URL prefix */
212     protected static String JavaDoc URL_PREFIX = "jdbc:apache:commons:dbcp:";
213     protected static int URL_PREFIX_LEN = URL_PREFIX.length();
214
215     // version numbers
216
protected static int MAJOR_VERSION = 1;
217     protected static int MINOR_VERSION = 0;
218
219     /**
220      * PoolGuardConnectionWrapper is a Connection wrapper that makes sure a
221      * closed connection cannot be used anymore.
222      */

223     private class PoolGuardConnectionWrapper extends DelegatingConnection {
224
225         private Connection JavaDoc delegate;
226     
227         PoolGuardConnectionWrapper(Connection JavaDoc delegate) {
228             super(delegate);
229             this.delegate = delegate;
230         }
231
232         protected void checkOpen() throws SQLException JavaDoc {
233             if(delegate == null) {
234                 throw new SQLException JavaDoc("Connection is closed.");
235             }
236         }
237     
238         public void close() throws SQLException JavaDoc {
239             checkOpen();
240             this.delegate.close();
241             this.delegate = null;
242             super.setDelegate(null);
243         }
244
245         public boolean isClosed() throws SQLException JavaDoc {
246             if (delegate == null) {
247                 return true;
248             }
249             return delegate.isClosed();
250         }
251
252         public void clearWarnings() throws SQLException JavaDoc {
253             checkOpen();
254             delegate.clearWarnings();
255         }
256
257         public void commit() throws SQLException JavaDoc {
258             checkOpen();
259             delegate.commit();
260         }
261
262         public Statement JavaDoc createStatement() throws SQLException JavaDoc {
263             checkOpen();
264             return delegate.createStatement();
265         }
266
267         public Statement JavaDoc createStatement(int resultSetType, int resultSetConcurrency) throws SQLException JavaDoc {
268             checkOpen();
269             return delegate.createStatement(resultSetType, resultSetConcurrency);
270         }
271
272         public boolean equals(Object JavaDoc obj) {
273             if (delegate == null){
274                 return false;
275             }
276             return delegate.equals(obj);
277         }
278
279         public boolean getAutoCommit() throws SQLException JavaDoc {
280             checkOpen();
281             return delegate.getAutoCommit();
282         }
283
284         public String JavaDoc getCatalog() throws SQLException JavaDoc {
285             checkOpen();
286             return delegate.getCatalog();
287         }
288
289         public DatabaseMetaData JavaDoc getMetaData() throws SQLException JavaDoc {
290             checkOpen();
291             return delegate.getMetaData();
292         }
293
294         public int getTransactionIsolation() throws SQLException JavaDoc {
295             checkOpen();
296             return delegate.getTransactionIsolation();
297         }
298
299         public Map JavaDoc getTypeMap() throws SQLException JavaDoc {
300             checkOpen();
301             return delegate.getTypeMap();
302         }
303
304         public SQLWarning JavaDoc getWarnings() throws SQLException JavaDoc {
305             checkOpen();
306             return delegate.getWarnings();
307         }
308
309         public int hashCode() {
310             if (delegate == null){
311                 return 0;
312             }
313             return delegate.hashCode();
314         }
315
316         public boolean isReadOnly() throws SQLException JavaDoc {
317             checkOpen();
318             return delegate.isReadOnly();
319         }
320
321         public String JavaDoc nativeSQL(String JavaDoc sql) throws SQLException JavaDoc {
322             checkOpen();
323             return delegate.nativeSQL(sql);
324         }
325
326         public CallableStatement JavaDoc prepareCall(String JavaDoc sql) throws SQLException JavaDoc {
327             checkOpen();
328             return delegate.prepareCall(sql);
329         }
330
331         public CallableStatement JavaDoc prepareCall(String JavaDoc sql, int resultSetType, int resultSetConcurrency) throws SQLException JavaDoc {
332             checkOpen();
333             return delegate.prepareCall(sql, resultSetType, resultSetConcurrency);
334         }
335
336         public PreparedStatement JavaDoc prepareStatement(String JavaDoc sql) throws SQLException JavaDoc {
337             checkOpen();
338             return delegate.prepareStatement(sql);
339         }
340
341         public PreparedStatement JavaDoc prepareStatement(String JavaDoc sql, int resultSetType, int resultSetConcurrency) throws SQLException JavaDoc {
342             checkOpen();
343             return delegate.prepareStatement(sql, resultSetType, resultSetConcurrency);
344         }
345
346         public void rollback() throws SQLException JavaDoc {
347             checkOpen();
348             delegate.rollback();
349         }
350
351         public void setAutoCommit(boolean autoCommit) throws SQLException JavaDoc {
352             checkOpen();
353             delegate.setAutoCommit(autoCommit);
354         }
355
356         public void setCatalog(String JavaDoc catalog) throws SQLException JavaDoc {
357             checkOpen();
358             delegate.setCatalog(catalog);
359         }
360
361         public void setReadOnly(boolean readOnly) throws SQLException JavaDoc {
362             checkOpen();
363             delegate.setReadOnly(readOnly);
364         }
365
366         public void setTransactionIsolation(int level) throws SQLException JavaDoc {
367             checkOpen();
368             delegate.setTransactionIsolation(level);
369         }
370
371         public void setTypeMap(Map JavaDoc map) throws SQLException JavaDoc {
372             checkOpen();
373             delegate.setTypeMap(map);
374         }
375
376         public String JavaDoc toString() {
377             if (delegate == null){
378                 return null;
379             }
380             return delegate.toString();
381         }
382
383         // ------------------- JDBC 3.0 -----------------------------------------
384
// Will be commented by the build process on a JDBC 2.0 system
385

386 /* JDBC_3_ANT_KEY_BEGIN */
387
388         public int getHoldability() throws SQLException JavaDoc {
389             checkOpen();
390             return delegate.getHoldability();
391         }
392     
393         public void setHoldability(int holdability) throws SQLException JavaDoc {
394             checkOpen();
395             delegate.setHoldability(holdability);
396         }
397
398         public java.sql.Savepoint JavaDoc setSavepoint() throws SQLException JavaDoc {
399             checkOpen();
400             return delegate.setSavepoint();
401         }
402
403         public java.sql.Savepoint JavaDoc setSavepoint(String JavaDoc name) throws SQLException JavaDoc {
404             checkOpen();
405             return delegate.setSavepoint(name);
406         }
407
408         public void releaseSavepoint(java.sql.Savepoint JavaDoc savepoint) throws SQLException JavaDoc {
409             checkOpen();
410             delegate.releaseSavepoint(savepoint);
411         }
412
413         public void rollback(java.sql.Savepoint JavaDoc savepoint) throws SQLException JavaDoc {
414             checkOpen();
415             delegate.rollback(savepoint);
416         }
417
418         public Statement JavaDoc createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException JavaDoc {
419             checkOpen();
420             return delegate.createStatement(resultSetType, resultSetConcurrency, resultSetHoldability);
421         }
422
423         public CallableStatement JavaDoc prepareCall(String JavaDoc sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException JavaDoc {
424             checkOpen();
425             return delegate.prepareCall(sql, resultSetType, resultSetConcurrency, resultSetHoldability);
426         }
427
428         public PreparedStatement JavaDoc prepareStatement(String JavaDoc sql, int autoGeneratedKeys) throws SQLException JavaDoc {
429             checkOpen();
430             return delegate.prepareStatement(sql, autoGeneratedKeys);
431         }
432
433         public PreparedStatement JavaDoc prepareStatement(String JavaDoc sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException JavaDoc {
434             checkOpen();
435             return delegate.prepareStatement(sql, resultSetType, resultSetConcurrency, resultSetHoldability);
436         }
437
438         public PreparedStatement JavaDoc prepareStatement(String JavaDoc sql, int[] columnIndexes) throws SQLException JavaDoc {
439             checkOpen();
440             return delegate.prepareStatement(sql, columnIndexes);
441         }
442
443         public PreparedStatement JavaDoc prepareStatement(String JavaDoc sql, String JavaDoc[] columnNames) throws SQLException JavaDoc {
444             checkOpen();
445             return delegate.prepareStatement(sql, columnNames);
446         }
447
448 /* JDBC_3_ANT_KEY_END */
449
450         /**
451          * @see org.apache.commons.dbcp.DelegatingConnection#getDelegate()
452          */

453         public Connection JavaDoc getDelegate() {
454             if (isAccessToUnderlyingConnectionAllowed()) {
455                 return super.getDelegate();
456             } else {
457                 return null;
458             }
459         }
460
461         /**
462          * @see org.apache.commons.dbcp.DelegatingConnection#getInnermostDelegate()
463          */

464         public Connection JavaDoc getInnermostDelegate() {
465             if (isAccessToUnderlyingConnectionAllowed()) {
466                 return super.getInnermostDelegate();
467             } else {
468                 return null;
469             }
470         }
471     }
472 }
473
Popular Tags