KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > mchange > v2 > c3p0 > impl > AbstractPoolBackedDataSource


1 /*
2  * Distributed as part of c3p0 v.0.9.1
3  *
4  * Copyright (C) 2005 Machinery For Change, Inc.
5  *
6  * Author: Steve Waldman <swaldman@mchange.com>
7  *
8  * This library is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU Lesser General Public License version 2.1, as
10  * published by the Free Software Foundation.
11  *
12  * This software is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15  * GNU Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public License
18  * along with this software; see the file LICENSE. If not, write to the
19  * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
20  * Boston, MA 02111-1307, USA.
21  */

22
23
24 package com.mchange.v2.c3p0.impl;
25
26 import java.io.*;
27 import java.sql.*;
28
29 import javax.sql.*;
30
31 import com.mchange.lang.ThrowableUtils;
32 import com.mchange.v2.c3p0.*;
33 import com.mchange.v2.log.*;
34
35 import java.beans.PropertyChangeEvent JavaDoc;
36 import java.beans.PropertyVetoException JavaDoc;
37 import java.beans.VetoableChangeListener JavaDoc;
38 import java.beans.PropertyChangeListener JavaDoc;
39 import java.util.Collection JavaDoc;
40 import java.util.Collections JavaDoc;
41 import java.util.Iterator JavaDoc;
42 import java.util.LinkedList JavaDoc;
43 import java.util.Map JavaDoc;
44 import java.util.Set JavaDoc;
45 import com.mchange.v2.c3p0.cfg.C3P0Config;
46
47 public abstract class AbstractPoolBackedDataSource extends PoolBackedDataSourceBase implements PooledDataSource
48 {
49     final static MLogger logger = MLog.getLogger( AbstractPoolBackedDataSource.class );
50
51     final static String JavaDoc NO_CPDS_ERR_MSG =
52         "Attempted to use an uninitialized PoolBackedDataSource. " +
53         "Please call setConnectionPoolDataSource( ... ) to initialize.";
54
55     //MT: protected by this' lock
56
transient C3P0PooledConnectionPoolManager poolManager;
57     transient boolean is_closed = false;
58     //MT: end protected by this' lock
59

60     protected AbstractPoolBackedDataSource( boolean autoregister )
61     {
62         super( autoregister );
63         setUpPropertyEvents();
64     }
65
66     protected AbstractPoolBackedDataSource(String JavaDoc configName)
67     {
68         this( true );
69         initializeNamedConfig( configName );
70     }
71
72     private void setUpPropertyEvents()
73     {
74         PropertyChangeListener JavaDoc l = new PropertyChangeListener JavaDoc()
75         {
76             public void propertyChange( PropertyChangeEvent JavaDoc evt )
77             { resetPoolManager(); }
78         };
79         this.addPropertyChangeListener( l );
80     }
81
82
83     protected void initializeNamedConfig(String JavaDoc configName)
84     {
85         try
86         {
87             if (configName != null)
88             {
89                 C3P0Config.bindNamedConfigToBean( this, configName );
90                 if ( this.getDataSourceName().equals( this.getIdentityToken() ) ) //dataSourceName has not been specified in config
91
this.setDataSourceName( configName );
92             }
93         }
94         catch (Exception JavaDoc e)
95         {
96             if (logger.isLoggable( MLevel.WARNING ))
97                 logger.log( MLevel.WARNING,
98                         "Error binding PoolBackedDataSource to named-config '" + configName +
99                         "'. Some default-config values may be used.",
100                         e);
101         }
102     }
103
104 // Commented out method is just super.getReference() with a lot of extra printing
105

106 // public javax.naming.Reference getReference() throws javax.naming.NamingException
107
// {
108
// System.err.println("getReference()!!!!");
109
// new Exception("PRINT-STACK-TRACE").printStackTrace();
110
// javax.naming.Reference out = super.getReference();
111
// System.err.println(out);
112
// return out;
113
// }
114

115     // report our ID token as dataSourceName if we have no
116
// name explicitly set
117
public String JavaDoc getDataSourceName()
118     {
119     String JavaDoc out = super.getDataSourceName();
120     if (out == null)
121         out = this.getIdentityToken();
122     return out;
123     }
124
125     //implementation of javax.sql.DataSource
126
public Connection getConnection() throws SQLException
127     {
128         PooledConnection pc = getPoolManager().getPool().checkoutPooledConnection();
129         return pc.getConnection();
130     }
131
132     public Connection getConnection(String JavaDoc username, String JavaDoc password) throws SQLException
133     {
134         PooledConnection pc = getPoolManager().getPool(username, password).checkoutPooledConnection();
135         return pc.getConnection();
136     }
137
138     public PrintWriter getLogWriter() throws SQLException
139     { return assertCpds().getLogWriter(); }
140
141     public void setLogWriter(PrintWriter out) throws SQLException
142     { assertCpds().setLogWriter( out ); }
143
144     public int getLoginTimeout() throws SQLException
145     { return assertCpds().getLoginTimeout(); }
146
147     public void setLoginTimeout(int seconds) throws SQLException
148     { assertCpds().setLoginTimeout( seconds ); }
149
150     //implementation of com.mchange.v2.c3p0.PoolingDataSource
151
public int getNumConnections() throws SQLException
152     { return getPoolManager().getPool().getNumConnections(); }
153
154     public int getNumIdleConnections() throws SQLException
155     { return getPoolManager().getPool().getNumIdleConnections(); }
156
157     public int getNumBusyConnections() throws SQLException
158     { return getPoolManager().getPool().getNumBusyConnections(); }
159
160     public int getNumUnclosedOrphanedConnections() throws SQLException
161     { return getPoolManager().getPool().getNumUnclosedOrphanedConnections(); }
162
163     public int getNumConnectionsDefaultUser() throws SQLException
164     { return getNumConnections();}
165
166     public int getNumIdleConnectionsDefaultUser() throws SQLException
167     { return getNumIdleConnections();}
168
169     public int getNumBusyConnectionsDefaultUser() throws SQLException
170     { return getNumBusyConnections();}
171
172     public int getNumUnclosedOrphanedConnectionsDefaultUser() throws SQLException
173     { return getNumUnclosedOrphanedConnections();}
174
175     public int getStatementCacheNumStatementsDefaultUser() throws SQLException
176     { return getPoolManager().getPool().getStatementCacheNumStatements(); }
177
178     public int getStatementCacheNumCheckedOutDefaultUser() throws SQLException
179     { return getPoolManager().getPool().getStatementCacheNumCheckedOut(); }
180
181     public int getStatementCacheNumConnectionsWithCachedStatementsDefaultUser() throws SQLException
182     { return getPoolManager().getPool().getStatementCacheNumConnectionsWithCachedStatements(); }
183
184     public float getEffectivePropertyCycleDefaultUser() throws SQLException
185     { return getPoolManager().getPool().getEffectivePropertyCycle(); }
186     
187     public long getStartTimeMillisDefaultUser() throws SQLException
188     { return getPoolManager().getPool().getStartTime(); }
189
190     public long getUpTimeMillisDefaultUser() throws SQLException
191     { return getPoolManager().getPool().getUpTime(); }
192     
193     public long getNumFailedCheckinsDefaultUser() throws SQLException
194     { return getPoolManager().getPool().getNumFailedCheckins(); }
195
196     public long getNumFailedCheckoutsDefaultUser() throws SQLException
197     { return getPoolManager().getPool().getNumFailedCheckouts(); }
198
199     public long getNumFailedIdleTestsDefaultUser() throws SQLException
200     { return getPoolManager().getPool().getNumFailedIdleTests(); }
201
202     public int getNumThreadsAwaitingCheckoutDefaultUser() throws SQLException
203     { return getPoolManager().getPool().getNumThreadsAwaitingCheckout(); }
204
205     public int getThreadPoolSize() throws SQLException
206     { return getPoolManager().getThreadPoolSize(); }
207
208     public int getThreadPoolNumActiveThreads() throws SQLException
209     { return getPoolManager().getThreadPoolNumActiveThreads(); }
210
211     public int getThreadPoolNumIdleThreads() throws SQLException
212     { return getPoolManager().getThreadPoolNumIdleThreads(); }
213
214     public int getThreadPoolNumTasksPending() throws SQLException
215     { return getPoolManager().getThreadPoolNumTasksPending(); }
216
217     public String JavaDoc sampleThreadPoolStackTraces() throws SQLException
218     { return getPoolManager().getThreadPoolStackTraces(); }
219
220     public String JavaDoc sampleThreadPoolStatus() throws SQLException
221     { return getPoolManager().getThreadPoolStatus(); }
222
223     public String JavaDoc sampleStatementCacheStatusDefaultUser() throws SQLException
224     { return getPoolManager().getPool().dumpStatementCacheStatus(); }
225     
226     public String JavaDoc sampleStatementCacheStatus(String JavaDoc username, String JavaDoc password) throws SQLException
227     { return assertAuthPool(username, password).dumpStatementCacheStatus(); }
228     
229     public Throwable JavaDoc getLastAcquisitionFailureDefaultUser() throws SQLException
230     { return getPoolManager().getPool().getLastAcquisitionFailure(); }
231
232     public Throwable JavaDoc getLastCheckinFailureDefaultUser() throws SQLException
233     { return getPoolManager().getPool().getLastCheckinFailure(); }
234
235     public Throwable JavaDoc getLastCheckoutFailureDefaultUser() throws SQLException
236     { return getPoolManager().getPool().getLastCheckoutFailure(); }
237
238     public Throwable JavaDoc getLastIdleTestFailureDefaultUser() throws SQLException
239     { return getPoolManager().getPool().getLastIdleTestFailure(); }
240
241     public Throwable JavaDoc getLastConnectionTestFailureDefaultUser() throws SQLException
242     { return getPoolManager().getPool().getLastConnectionTestFailure(); }
243     
244     public Throwable JavaDoc getLastAcquisitionFailure(String JavaDoc username, String JavaDoc password) throws SQLException
245     { return assertAuthPool(username, password).getLastAcquisitionFailure(); }
246
247     public Throwable JavaDoc getLastCheckinFailure(String JavaDoc username, String JavaDoc password) throws SQLException
248     { return assertAuthPool(username, password).getLastCheckinFailure(); }
249
250     public Throwable JavaDoc getLastCheckoutFailure(String JavaDoc username, String JavaDoc password) throws SQLException
251     { return assertAuthPool(username, password).getLastCheckoutFailure(); }
252
253     public Throwable JavaDoc getLastIdleTestFailure(String JavaDoc username, String JavaDoc password) throws SQLException
254     { return assertAuthPool(username, password).getLastIdleTestFailure(); }
255
256     public Throwable JavaDoc getLastConnectionTestFailure(String JavaDoc username, String JavaDoc password) throws SQLException
257     { return assertAuthPool(username, password).getLastConnectionTestFailure(); }
258     
259     public int getNumThreadsAwaitingCheckout(String JavaDoc username, String JavaDoc password) throws SQLException
260     { return assertAuthPool(username, password).getNumThreadsAwaitingCheckout(); }
261
262     public String JavaDoc sampleLastAcquisitionFailureStackTraceDefaultUser() throws SQLException
263     {
264         Throwable JavaDoc t = getLastAcquisitionFailureDefaultUser();
265         return t == null ? null : ThrowableUtils.extractStackTrace( t );
266     }
267     
268     public String JavaDoc sampleLastCheckinFailureStackTraceDefaultUser() throws SQLException
269     {
270         Throwable JavaDoc t = getLastCheckinFailureDefaultUser();
271         return t == null ? null : ThrowableUtils.extractStackTrace( t );
272     }
273     
274     public String JavaDoc sampleLastCheckoutFailureStackTraceDefaultUser() throws SQLException
275     {
276         Throwable JavaDoc t = getLastCheckoutFailureDefaultUser();
277         return t == null ? null : ThrowableUtils.extractStackTrace( t );
278     }
279
280     public String JavaDoc sampleLastIdleTestFailureStackTraceDefaultUser() throws SQLException
281     {
282         Throwable JavaDoc t = getLastIdleTestFailureDefaultUser();
283         return t == null ? null : ThrowableUtils.extractStackTrace( t );
284     }
285
286     public String JavaDoc sampleLastConnectionTestFailureStackTraceDefaultUser() throws SQLException
287     {
288         Throwable JavaDoc t = getLastConnectionTestFailureDefaultUser();
289         return t == null ? null : ThrowableUtils.extractStackTrace( t );
290     }
291     
292     public String JavaDoc sampleLastAcquisitionFailureStackTrace(String JavaDoc username, String JavaDoc password) throws SQLException
293     {
294         Throwable JavaDoc t = getLastAcquisitionFailure(username, password);
295         return t == null ? null : ThrowableUtils.extractStackTrace( t );
296     }
297
298     public String JavaDoc sampleLastCheckinFailureStackTrace(String JavaDoc username, String JavaDoc password) throws SQLException
299     {
300         Throwable JavaDoc t = getLastCheckinFailure(username, password);
301         return t == null ? null : ThrowableUtils.extractStackTrace( t );
302     }
303
304     public String JavaDoc sampleLastCheckoutFailureStackTrace(String JavaDoc username, String JavaDoc password) throws SQLException
305     {
306         Throwable JavaDoc t = getLastCheckoutFailure(username, password);
307         return t == null ? null : ThrowableUtils.extractStackTrace( t );
308     }
309
310     public String JavaDoc sampleLastIdleTestFailureStackTrace(String JavaDoc username, String JavaDoc password) throws SQLException
311     {
312         Throwable JavaDoc t = getLastIdleTestFailure(username, password);
313         return t == null ? null : ThrowableUtils.extractStackTrace( t );
314     }
315
316     public String JavaDoc sampleLastConnectionTestFailureStackTrace(String JavaDoc username, String JavaDoc password) throws SQLException
317     {
318         Throwable JavaDoc t = getLastConnectionTestFailure(username, password);
319         return t == null ? null : ThrowableUtils.extractStackTrace( t );
320     }
321
322     public void softResetDefaultUser() throws SQLException
323     { getPoolManager().getPool().reset(); }
324
325     public int getNumConnections(String JavaDoc username, String JavaDoc password) throws SQLException
326     { return assertAuthPool(username, password).getNumConnections(); }
327
328     public int getNumIdleConnections(String JavaDoc username, String JavaDoc password) throws SQLException
329     { return assertAuthPool(username, password).getNumIdleConnections(); }
330
331     public int getNumBusyConnections(String JavaDoc username, String JavaDoc password) throws SQLException
332     { return assertAuthPool(username, password).getNumBusyConnections(); }
333
334     public int getNumUnclosedOrphanedConnections(String JavaDoc username, String JavaDoc password) throws SQLException
335     { return assertAuthPool(username, password).getNumUnclosedOrphanedConnections(); }
336
337     public int getStatementCacheNumStatements(String JavaDoc username, String JavaDoc password) throws SQLException
338     { return assertAuthPool(username, password).getStatementCacheNumStatements(); }
339
340     public int getStatementCacheNumCheckedOut(String JavaDoc username, String JavaDoc password) throws SQLException
341     { return assertAuthPool(username, password).getStatementCacheNumCheckedOut(); }
342
343     public int getStatementCacheNumConnectionsWithCachedStatements(String JavaDoc username, String JavaDoc password) throws SQLException
344     { return assertAuthPool(username, password).getStatementCacheNumConnectionsWithCachedStatements(); }
345
346     public float getEffectivePropertyCycle(String JavaDoc username, String JavaDoc password) throws SQLException
347     { return assertAuthPool(username, password).getEffectivePropertyCycle(); }
348
349     public long getStartTimeMillis(String JavaDoc username, String JavaDoc password) throws SQLException
350     { return assertAuthPool(username, password).getStartTime(); }
351
352     public long getUpTimeMillis(String JavaDoc username, String JavaDoc password) throws SQLException
353     { return assertAuthPool(username, password).getUpTime(); }
354     
355     public long getNumFailedCheckins(String JavaDoc username, String JavaDoc password) throws SQLException
356     { return assertAuthPool(username, password).getNumFailedCheckins(); }
357
358     public long getNumFailedCheckouts(String JavaDoc username, String JavaDoc password) throws SQLException
359     { return assertAuthPool(username, password).getNumFailedCheckouts(); }
360
361     public long getNumFailedIdleTests(String JavaDoc username, String JavaDoc password) throws SQLException
362     { return assertAuthPool(username, password).getNumFailedIdleTests(); }
363
364     public void softReset(String JavaDoc username, String JavaDoc password) throws SQLException
365     { assertAuthPool(username, password).reset(); }
366
367     public int getNumBusyConnectionsAllUsers() throws SQLException
368     { return getPoolManager().getNumBusyConnectionsAllAuths(); }
369
370     public int getNumIdleConnectionsAllUsers() throws SQLException
371     { return getPoolManager().getNumIdleConnectionsAllAuths(); }
372
373     public int getNumConnectionsAllUsers() throws SQLException
374     { return getPoolManager().getNumConnectionsAllAuths(); }
375
376     public int getNumUnclosedOrphanedConnectionsAllUsers() throws SQLException
377     { return getPoolManager().getNumUnclosedOrphanedConnectionsAllAuths(); }
378
379     public int getStatementCacheNumStatementsAllUsers() throws SQLException
380     { return getPoolManager().getStatementCacheNumStatementsAllUsers(); }
381
382     public int getStatementCacheNumCheckedOutStatementsAllUsers() throws SQLException
383     { return getPoolManager().getStatementCacheNumCheckedOutStatementsAllUsers(); }
384
385     public synchronized int getStatementCacheNumConnectionsWithCachedStatementsAllUsers() throws SQLException
386     { return getPoolManager().getStatementCacheNumConnectionsWithCachedStatementsAllUsers(); }
387
388     public void softResetAllUsers() throws SQLException
389     { getPoolManager().softResetAllAuths(); }
390
391     public int getNumUserPools() throws SQLException
392     { return getPoolManager().getNumManagedAuths(); }
393
394     public Collection JavaDoc getAllUsers() throws SQLException
395     {
396         LinkedList JavaDoc out = new LinkedList JavaDoc();
397         Set JavaDoc auths = getPoolManager().getManagedAuths();
398         for ( Iterator JavaDoc ii = auths.iterator(); ii.hasNext(); )
399             out.add( ((DbAuth) ii.next()).getUser() );
400         return Collections.unmodifiableList( out );
401     }
402
403     public synchronized void hardReset()
404     {
405         resetPoolManager();
406     }
407
408     public synchronized void close()
409     {
410         resetPoolManager();
411         is_closed = true;
412         
413         C3P0Registry.markClosed(this);
414
415         if (Debug.DEBUG && Debug.TRACE == Debug.TRACE_MAX && logger.isLoggable(MLevel.FINEST))
416         {
417             logger.log(MLevel.FINEST,
418                     this.getClass().getName() + '@' + Integer.toHexString( System.identityHashCode( this ) ) +
419                     " has been closed. ",
420                     new Exception JavaDoc("DEBUG STACK TRACE for PoolBackedDataSource.close()."));
421         }
422     }
423
424     /**
425      * @deprecated the force_destroy argument is now meaningless, as pools are no longer
426      * potentially shared between multiple DataSources.
427      */

428     public void close(boolean force_destroy)
429     { close(); }
430
431     //other code
432
public synchronized void resetPoolManager() //used by other, wrapping datasources in package, and in mbean package
433
{ resetPoolManager( true ); }
434
435     public synchronized void resetPoolManager( boolean close_checked_out_connections ) //used by other, wrapping datasources in package, and in mbean package
436
{
437         if ( poolManager != null )
438         {
439             poolManager.close( close_checked_out_connections );
440             poolManager = null;
441         }
442     }
443
444     private synchronized ConnectionPoolDataSource assertCpds() throws SQLException
445     {
446         if ( is_closed )
447             throw new SQLException(this + " has been closed() -- you can no longer use it.");
448
449         ConnectionPoolDataSource out = this.getConnectionPoolDataSource();
450         if ( out == null )
451             throw new SQLException(NO_CPDS_ERR_MSG);
452         return out;
453     }
454
455     private synchronized C3P0PooledConnectionPoolManager getPoolManager() throws SQLException
456     {
457         if (poolManager == null)
458         {
459             ConnectionPoolDataSource cpds = assertCpds();
460             poolManager = new C3P0PooledConnectionPoolManager(cpds, null, null, this.getNumHelperThreads(), this.getIdentityToken());
461             if (logger.isLoggable(MLevel.INFO))
462                 logger.info("Initializing c3p0 pool... " + this.toString() /* + "; using pool manager: " + poolManager */);
463         }
464         return poolManager;
465     }
466
467     private C3P0PooledConnectionPool assertAuthPool( String JavaDoc username, String JavaDoc password ) throws SQLException
468     {
469     C3P0PooledConnectionPool authPool = getPoolManager().getPool(username, password, false);
470     if (authPool == null)
471         throw new SQLException("No pool has been yet been established for Connections authenticated by user '" +
472                    username + "' with the password provided. [Use getConnection( username, password ) " +
473                    "to initialize such a pool.]");
474     else
475         return authPool;
476     }
477
478     // serialization stuff -- set up bound/constrained property event handlers on deserialization
479
private static final long serialVersionUID = 1;
480     private static final short VERSION = 0x0001;
481
482     private void writeObject( ObjectOutputStream oos ) throws IOException
483     {
484         oos.writeShort( VERSION );
485     }
486
487     private void readObject( ObjectInputStream ois ) throws IOException, ClassNotFoundException JavaDoc
488     {
489         short version = ois.readShort();
490         switch (version)
491         {
492         case VERSION:
493             setUpPropertyEvents();
494             break;
495         default:
496             throw new IOException("Unsupported Serialized Version: " + version);
497         }
498     }
499 }
500
501
Popular Tags