File: NewPooledConnection.java

package info (click to toggle)
c3p0 0.9.1.2-9+deb9u1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 3,152 kB
  • sloc: java: 29,115; xml: 791; makefile: 14; sh: 11
file content (748 lines) | stat: -rw-r--r-- 31,134 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
/*
 * Distributed as part of c3p0 v.0.9.1.2
 *
 * Copyright (C) 2005 Machinery For Change, Inc.
 *
 * Author: Steve Waldman <swaldman@mchange.com>
 *
 * This library is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 2.1, as 
 * published by the Free Software Foundation.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this software; see the file LICENSE.  If not, write to the
 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
 * Boston, MA 02111-1307, USA.
 */


package com.mchange.v2.c3p0.impl;

import java.util.*;
import java.sql.*;
import javax.sql.*;
import com.mchange.v2.c3p0.*;
import com.mchange.v2.c3p0.stmt.*;
import com.mchange.v2.c3p0.util.*;
import com.mchange.v2.log.*;

import java.lang.reflect.Method;
import com.mchange.v2.lang.ObjectUtils;
import com.mchange.v2.sql.SqlUtils;

public final class NewPooledConnection extends AbstractC3P0PooledConnection{

    private final static MLogger logger = MLog.getLogger( NewPooledConnection.class );

    private final static SQLException NORMAL_CLOSE_PLACEHOLDER = new SQLException("This pooled Connection was explicitly close()ed by " +
    "a client, not invalidated due to an error.");
    
    //MT: protected by class lock
    static Set holdabilityBugKeys = null;

    //MT: thread-safe post-constructor constants
    final Connection             physicalConnection;
    final ConnectionTester       connectionTester;
    final boolean                autoCommitOnClose;
    final boolean                forceIgnoreUnresolvedTransactions;
    final String                 preferredTestQuery;
    final boolean                supports_setHoldability;
    final boolean                supports_setReadOnly;
    final boolean                supports_setTypeMap;
    final int                    dflt_txn_isolation;
    final String                 dflt_catalog;
    final int                    dflt_holdability;
    final boolean                dflt_readOnly;
    final Map                    dflt_typeMap;
    final ConnectionEventSupport ces;

    //MT:  protected by this' lock
    GooGooStatementCache scache                    = null;
    Throwable            invalidatingException     = null;
    int                  connection_status         = ConnectionTester.CONNECTION_IS_OKAY;
    Set                  uncachedActiveStatements  = new HashSet(); //cached statements are managed by the cache
    Map                  resultSetsForStatements   = new HashMap(); //for both cached and uncached statements
    Set                  metaDataResultSets        = new HashSet();
    Set                  rawConnectionResultSets   = null;          //very rarely used, so we lazy initialize...
    boolean              connection_error_signaled = false;

    //MT: thread-safe, volatile
    volatile NewProxyConnection exposedProxy = null;
    volatile boolean isolation_lvl_nondefault = false; 
    volatile boolean catalog_nondefault       = false; 
    volatile boolean holdability_nondefault   = false; 
    volatile boolean readOnly_nondefault      = false; 
    volatile boolean typeMap_nondefault       = false; 

    // public API
    public NewPooledConnection(Connection con, 
                    ConnectionTester connectionTester,
                    boolean autoCommitOnClose, 
                    boolean forceIgnoreUnresolvedTransactions,
                    String  preferredTestQuery,
                    ConnectionCustomizer cc,
                    String pdsIdt) throws SQLException
                    { 
        try
        {
            if (cc != null)
                cc.onAcquire( con, pdsIdt );
        }
        catch (Exception e)
        { throw SqlUtils.toSQLException(e); }

        this.physicalConnection                = con; 
        this.connectionTester                  = connectionTester;
        this.autoCommitOnClose                 = autoCommitOnClose;
        this.forceIgnoreUnresolvedTransactions = forceIgnoreUnresolvedTransactions;
        this.preferredTestQuery                = preferredTestQuery;
        this.supports_setHoldability           = C3P0ImplUtils.supportsMethod(con, "setHoldability", new Class[]{ int.class });
        this.supports_setReadOnly              = C3P0ImplUtils.supportsMethod(con, "setReadOnly", new Class[]{ boolean.class });
        this.supports_setTypeMap               = C3P0ImplUtils.supportsMethod(con, "setTypeMap", new Class[]{ Map.class });
        this.dflt_txn_isolation                = con.getTransactionIsolation();
        this.dflt_catalog                      = con.getCatalog();
        this.dflt_holdability                  = (supports_setHoldability ? carefulCheckHoldability(con) : ResultSet.CLOSE_CURSORS_AT_COMMIT);
        this.dflt_readOnly                     = (supports_setReadOnly ? carefulCheckReadOnly(con) : false);
        this.dflt_typeMap                      = (supports_setTypeMap && (carefulCheckTypeMap(con) == null) ? null : Collections.EMPTY_MAP);
        this.ces                               = new ConnectionEventSupport(this);
                    }

    private static int carefulCheckHoldability(Connection con)
    {
        try { return con.getHoldability(); }
        catch (Exception e)
        {
            if (false)
            {
                if (logger.isLoggable(MLevel.FINER))
                    logger.log(MLevel.FINER, con + " threw an Exception when we tried to check its default " +
                                    "holdability. This is not usually a problem! It just means the Connection " +
                                    "doesn't support the holdability property, and c3p0 works around this.", e);
            }
            return ResultSet.CLOSE_CURSORS_AT_COMMIT;
        }
        catch (Error e) // Some DB2 drivers apparently throw an Error here, but I'm not comfortable swallowing Errors
        {
            synchronized (NewPooledConnection.class)
            {
                if (holdabilityBugKeys == null)
                    holdabilityBugKeys = new HashSet();
                String hbk = holdabilityBugKey(con, e);
                if (! holdabilityBugKeys.contains(hbk) )
                {
                    if (logger.isLoggable(MLevel.WARNING))
                        logger.log(MLevel.WARNING, con + " threw an Error when we tried to check its default " +
                                        "holdability. This is probably due to a bug in your JDBC driver that c3p0 can harmlessly " +
                                        "work around (reported for some DB2 drivers). Please verify that the error stack trace is consistent" +
                                        "with the getHoldability() method not being properly implemented, and is not due to some deeper problem. " +
                                        "This message will not be repeated for Connections of type " + con.getClass().getName() + " that " +
                                        "provoke errors of type " + e.getClass().getName() + " when getHoldability() is called.", e);
                    holdabilityBugKeys.add(hbk);
                }
            }
            return ResultSet.CLOSE_CURSORS_AT_COMMIT;
        }
    }
        
    private static String holdabilityBugKey(Connection con, Error err)
    { return con.getClass().getName() + '|' + err.getClass().getName(); }

    private static boolean carefulCheckReadOnly(Connection con)
    {
        try { return con.isReadOnly(); }
        catch (Exception e)
        {
            if (false)
            {
                if (logger.isLoggable(MLevel.FINER))
                    logger.log(MLevel.FINER, con + " threw an Exception when we tried to check its default " +
                                    "read only state. This is not usually a problem! It just means the Connection " +
                                    "doesn't support the readOnly property, and c3p0 works around this.", e);
            }
            return false;
        }
    }

    private static Map carefulCheckTypeMap(Connection con)
    {
        try { return con.getTypeMap(); }
        catch (Exception e)
        {
            if (false)
            {
                if (logger.isLoggable(MLevel.FINER))
                    logger.log(MLevel.FINER, con + " threw an Exception when we tried to check its default " +
                                    "type map. This is not usually a problem! It just means the Connection " +
                                    "doesn't support the typeMap property, and c3p0 works around this.", e);
            }
            return null;
        }
    }

    public synchronized Connection getConnection() throws SQLException
    {
        try
        {
            //throw new SQLException("NOT IMPLEMENTED");
            if ( exposedProxy == null )
            {
                exposedProxy = new NewProxyConnection( physicalConnection, this );
            }
            else
            {
//              System.err.println("c3p0 -- Uh oh... getConnection() was called on a PooledConnection when " +
//              "it had already provided a client with a Connection that has not yet been " +
//              "closed. This probably indicates a bug in the connection pool!!!");

                if ( logger.isLoggable( MLevel.WARNING ) )
                    logger.warning("c3p0 -- Uh oh... getConnection() was called on a PooledConnection when " +
                                    "it had already provided a client with a Connection that has not yet been " +
                    "closed. This probably indicates a bug in the connection pool!!!");

            }
            return exposedProxy;
        }
        catch ( Exception e )
        {
            SQLException sqle = handleThrowable( e );
            throw sqle;
        }
    }

    public synchronized int getConnectionStatus()
    { return connection_status; }

    public synchronized void closeAll() throws SQLException
    { 
        try
        {
            closeAllCachedStatements(); 
        }
        catch ( Exception e )
        {
            SQLException sqle = handleThrowable( e );
            throw sqle;
        }
    }

    public synchronized void close() throws SQLException
    { close( null ); }

    public void addConnectionEventListener(ConnectionEventListener cel)
    { ces.addConnectionEventListener( cel );  }

    public void removeConnectionEventListener(ConnectionEventListener cel)
    { ces.removeConnectionEventListener( cel );  }

    // api for C3P0PooledConnectionPool
    public synchronized void initStatementCache( GooGooStatementCache scache )
    { this.scache = scache; }

    public synchronized GooGooStatementCache getStatementCache()
    { return scache; }

    //api for NewProxyConnections
    void markNewTxnIsolation( int lvl ) //intentionally unsync'd -- isolation_lvl_nondefault is marked volatile
    { 
        this.isolation_lvl_nondefault = (lvl != dflt_txn_isolation); 
        //System.err.println("isolation_lvl_nondefault: " + isolation_lvl_nondefault);
    }

    void markNewCatalog( String catalog ) //intentionally unsync'd -- catalog_nondefault is marked volatile
    { 
        this.catalog_nondefault = ObjectUtils.eqOrBothNull(catalog, dflt_catalog); 
    }

    void markNewHoldability( int holdability ) //intentionally unsync'd -- holdability_nondefault is marked volatile
    { 
        this.holdability_nondefault = (holdability != dflt_holdability); 
    }

    void markNewReadOnly( boolean readOnly ) //intentionally unsync'd -- readOnly_nondefault is marked volatile
    { 
        this.readOnly_nondefault = (readOnly != dflt_readOnly); 
    }

    void markNewTypeMap( Map typeMap ) //intentionally unsync'd -- typeMap_nondefault is marked volatile
    { 
        this.typeMap_nondefault = (typeMap != dflt_typeMap);
    }

    synchronized Object checkoutStatement( Method stmtProducingMethod, Object[] args ) throws SQLException
    { return scache.checkoutStatement( physicalConnection, stmtProducingMethod, args ); }

    synchronized void checkinStatement( Statement stmt ) throws SQLException
    { 
        cleanupStatementResultSets( stmt );
        scache.checkinStatement( stmt );
    }

    synchronized void markActiveUncachedStatement( Statement stmt )
    { uncachedActiveStatements.add( stmt );  }

    synchronized void markInactiveUncachedStatement( Statement stmt )
    {
        cleanupStatementResultSets( stmt );
        uncachedActiveStatements.remove( stmt );  
    }

    synchronized void markActiveResultSetForStatement( Statement stmt, ResultSet rs )
    {
        Set rss = resultSets( stmt, true );
        rss.add( rs );
    }

    synchronized void markInactiveResultSetForStatement( Statement stmt, ResultSet rs )
    { 
        Set rss = resultSets( stmt, false );
        if (rss == null)
        {
            if (logger.isLoggable( MLevel.FINE ))
                logger.fine( "ResultSet " + rs + " was apparently closed after the Statement that created it had already been closed." );
        }
        else if ( ! rss.remove( rs ) )
            throw new InternalError("Marking a ResultSet inactive that we did not know was opened!");
    }

    synchronized void markActiveRawConnectionResultSet( ResultSet rs )
    {
        if (rawConnectionResultSets == null)
            rawConnectionResultSets = new HashSet();
        rawConnectionResultSets.add( rs );
    }

    synchronized void markInactiveRawConnectionResultSet( ResultSet rs )
    { 
        if ( ! rawConnectionResultSets.remove( rs ) )
            throw new InternalError("Marking a raw Connection ResultSet inactive that we did not know was opened!");
    }

    synchronized void markActiveMetaDataResultSet( ResultSet rs )
    { metaDataResultSets.add( rs ); }

    synchronized void markInactiveMetaDataResultSet( ResultSet rs )
    { metaDataResultSets.remove( rs ); }

    // internal synchronization to avoid sync'ed event multicasts
    void markClosedProxyConnection( NewProxyConnection npc, boolean txn_known_resolved ) 
    {
        SQLException trouble = null;
        try
        {
            synchronized( this )
            {
                try
                {
                    if (npc != exposedProxy)
                        throw new InternalError("C3P0 Error: An exposed proxy asked a PooledConnection that was not its parents to clean up its resources!");

                    List closeExceptions = new LinkedList();
                    cleanupResultSets( closeExceptions );
                    cleanupUncachedStatements( closeExceptions );
                    checkinAllCachedStatements( closeExceptions );
                    if ( closeExceptions.size() > 0 )
                    {
//                      System.err.println("[c3p0] The following Exceptions occurred while trying to clean up a Connection's stranded resources:");
                        if ( logger.isLoggable( MLevel.INFO ) )
                            logger.info("[c3p0] The following Exceptions occurred while trying to clean up a Connection's stranded resources:");
                        for ( Iterator ii = closeExceptions.iterator(); ii.hasNext(); )
                        {
                            Throwable t = (Throwable) ii.next();
//                          System.err.print("[c3p0 -- conection resource close Exception]: ");
//                          t.printStackTrace();
                            if ( logger.isLoggable( MLevel.INFO ) )
                                logger.log( MLevel.INFO, "[c3p0 -- conection resource close Exception]", t );
                        }
                    }
                    reset( txn_known_resolved );
                }
                catch (SQLException e) //Connection failed to reset!
                {
                    //e.printStackTrace();
                    if (Debug.DEBUG && logger.isLoggable( MLevel.FINE ))
                        logger.log(MLevel.FINE, "An exception occurred while reseting a closed Connection. Invalidating Connection.", e);

                    updateConnectionStatus( ConnectionTester.CONNECTION_IS_INVALID );
                }
            }
        }
        finally
        {
            if (trouble != null)
                fireConnectionErrorOccurred( trouble ); //should not be invoked from a sync'ed block
            else
            {
                exposedProxy = null; //volatile
                fireConnectionClosed(); //should not be invoked from a sync'ed block
            }
        }
    }

    private void reset( boolean txn_known_resolved ) throws SQLException
    {
        C3P0ImplUtils.resetTxnState( physicalConnection, forceIgnoreUnresolvedTransactions, autoCommitOnClose, txn_known_resolved );
        if (isolation_lvl_nondefault)
        {
            physicalConnection.setTransactionIsolation( dflt_txn_isolation );
            isolation_lvl_nondefault = false; 
            //System.err.println("reset txn isolation: " + dflt_txn_isolation);
        }
        if (catalog_nondefault)
        {
            physicalConnection.setCatalog( dflt_catalog );
            catalog_nondefault = false; 
        }
        if (holdability_nondefault) //this cannot go to true if holdability is not supported, so we don't have to check.
        {
            physicalConnection.setHoldability( dflt_holdability );
            holdability_nondefault = false; 
        }
        if (readOnly_nondefault)
        {
            physicalConnection.setReadOnly( dflt_readOnly );
            readOnly_nondefault = false; 
        }
        if (typeMap_nondefault)
        {
            physicalConnection.setTypeMap( dflt_typeMap );
            typeMap_nondefault = false;
        }
    }

    synchronized boolean isStatementCaching()
    { return scache != null; }

    //synchrnized internally to avoid holding locks during event multicast
    SQLException handleThrowable( Throwable t )
    {
        boolean fire_cxn_error = false;
        SQLException sqle = null;
        try
        {
            synchronized (this)
            {
                if (Debug.DEBUG && Debug.TRACE == Debug.TRACE_MAX && logger.isLoggable( MLevel.FINER ))
                    logger.log( MLevel.FINER, this + " handling a throwable.", t );

                sqle = SqlUtils.toSQLException( t );
                //logger.warning("handle throwable ct: " + connectionTester);

                int status;
                if (connectionTester instanceof FullQueryConnectionTester)
                    status = ((FullQueryConnectionTester) connectionTester).statusOnException( physicalConnection, sqle, preferredTestQuery );
                else
                    status = connectionTester.statusOnException( physicalConnection, sqle );

                updateConnectionStatus( status ); 
                if (status != ConnectionTester.CONNECTION_IS_OKAY)
                {
                    if (Debug.DEBUG)
                    {
//                      System.err.print(this + " invalidated by Exception: ");
//                      t.printStackTrace();
                        if ( logger.isLoggable( MLevel.FINE ) )
                            logger.log(MLevel.FINE, this + " invalidated by Exception.", t);
                    }

                    /*
                  ------
                  A users have complained that SQLExceptions ought not close their Connections underneath
                  them under any circumstance. Signalling the Connection error after updating the Connection
                  status should be sufficient from the pool's perspective, because the PooledConnection
                  will be marked broken by the pool and will be destroyed on checkin. I think actually
                  close()ing the Connection when it appears to be broken rather than waiting for users
                  to close() it themselves is overly aggressive, so I'm commenting the old behavior out.
                  The only potential downside to this approach is that users who do not close() in a finally
                  clause properly might see their close()es skipped by exceptions that previously would
                  have led to automatic close(). But relying on the automatic close() was never reliable
                  (since it only ever happened when c3p0 determined a Connection to be absolutely broken),
                  and is generally speaking a client error that c3p0 ought not be responsible for dealing
                  with. I think it's right to leave this out. -- swaldman 2004-12-09
                  ------

                try { close( t ); }
                catch (SQLException e)
                    {
                    e.printStackTrace();
                    throw new InternalError("C3P0 Error: NewPooledConnection's private close() method should " +
                                "suppress any Exceptions if a throwable cause is provided.");
                    }
                     */


                    if (! connection_error_signaled)
                        fire_cxn_error = true;
                    else
                    {
//                      System.err.println("[c3p0] Warning: PooledConnection that has already signalled a Connection error is still in use!");
//                      System.err.println("[c3p0] Another error has occurred [ " + t + " ] which will not be reported to listeners!");
                        if ( logger.isLoggable( MLevel.WARNING ) )
                        {
                            logger.log(MLevel.WARNING, "[c3p0] A PooledConnection that has already signalled a Connection error is still in use!");
                            logger.log(MLevel.WARNING, "[c3p0] Another error has occurred [ " + t + " ] which will not be reported to listeners!", t);
                        }
                    }
                }
            }// end sync'ed block
        }// end try block
        finally
        {
            if (fire_cxn_error)
            {
                fireConnectionErrorOccurred( sqle ); //should not be invoked from a sync'ed block
                connection_error_signaled = true;
            }
        }
        return sqle;
    }

//  private methods

//  should NOT be called from sync'ed method
    private void fireConnectionClosed()
    {
        assert (! Thread.holdsLock(this));
        ces.fireConnectionClosed(); 
    }

//  should NOT be called from sync'ed method
    private void fireConnectionErrorOccurred(SQLException error)
    { 
        assert (! Thread.holdsLock(this));
        ces.fireConnectionErrorOccurred( error ); 
    }

//  methods below must be called from sync'ed methods

    /*
     *  If a throwable cause is provided, the PooledConnection is known to be broken (cause is an invalidating exception)
     *  and this method will not throw any exceptions, even if some resource closes fail.
     *
     *  If cause is null, then we think the PooledConnection is healthy, and we will report (throw) an exception
     *  if resources unexpectedlay fail to close.
     */
    private void close( Throwable cause ) throws SQLException
    {
        if ( this.invalidatingException == null )
        {
            List closeExceptions = new LinkedList();

            // cleanup ResultSets
            cleanupResultSets( closeExceptions );

            // cleanup uncached Statements
            cleanupUncachedStatements( closeExceptions );

            // cleanup cached Statements
            try
            { closeAllCachedStatements(); }
            catch ( SQLException e )
            { closeExceptions.add(e); }

            // cleanup physicalConnection
            try
            { physicalConnection.close(); }
            catch ( SQLException e )
            {
                if (logger.isLoggable( MLevel.FINER ))
                    logger.log( MLevel.FINER, "Failed to close physical Connection: " + physicalConnection, e );

                closeExceptions.add(e); 
            }

            // update our state to bad status and closed, and log any exceptions
            if ( connection_status == ConnectionTester.CONNECTION_IS_OKAY )
                connection_status = ConnectionTester.CONNECTION_IS_INVALID;
            if ( cause == null )
            {
                this.invalidatingException = NORMAL_CLOSE_PLACEHOLDER;

                if ( logger.isLoggable( MLevel.FINEST ) )
                    logger.log( MLevel.FINEST, this + " closed by a client.", new Exception("DEBUG -- CLOSE BY CLIENT STACK TRACE") );

                logCloseExceptions( null, closeExceptions );

                if (closeExceptions.size() > 0)
                    throw new SQLException("Some resources failed to close properly while closing " + this);
            }
            else
            {
                this.invalidatingException = cause;
                if (Debug.TRACE >= Debug.TRACE_MED)
                    logCloseExceptions( cause, closeExceptions );
                else
                    logCloseExceptions( cause, null );
            }
        }
    }

    private void cleanupResultSets( List closeExceptions )
    {
        cleanupAllStatementResultSets( closeExceptions );
        cleanupUnclosedResultSetsSet( metaDataResultSets, closeExceptions );
        if ( rawConnectionResultSets != null )
            cleanupUnclosedResultSetsSet( rawConnectionResultSets, closeExceptions );
    }

    private void cleanupUnclosedResultSetsSet( Set rsSet, List closeExceptions )
    {
        for ( Iterator ii = rsSet.iterator(); ii.hasNext(); )
        {
            ResultSet rs = (ResultSet) ii.next();
            try
            { rs.close(); }
            catch ( SQLException e )
            { closeExceptions.add(e); }

            ii.remove();
        }
    }

    private void cleanupStatementResultSets( Statement stmt )
    {
        Set rss = resultSets( stmt, false );
        if ( rss != null )
        {
            for ( Iterator ii = rss.iterator(); ii.hasNext(); )
            {
                try
                { ((ResultSet) ii.next()).close(); }
                catch ( Exception e )
                {
//                  System.err.print("ResultSet close() failed: ");
//                  e.printStackTrace();
                    if ( logger.isLoggable( MLevel.INFO ) )
                        logger.log(MLevel.INFO, "ResultSet close() failed.", e);
                }
            }
        }
        resultSetsForStatements.remove( stmt );
    }

    private void cleanupAllStatementResultSets( List closeExceptions )
    {
        for ( Iterator ii = resultSetsForStatements.keySet().iterator(); ii.hasNext(); )
        {
            Object stmt = ii.next();
            Set rss = (Set) resultSetsForStatements.get( stmt );
            for (Iterator jj = rss.iterator(); jj.hasNext(); )
            {
                ResultSet rs = (ResultSet) jj.next();
                try
                { rs.close(); }
                catch ( SQLException e )
                { closeExceptions.add(e); }
            }
        }
        resultSetsForStatements.clear();
    }

    private void cleanupUncachedStatements( List closeExceptions )
    {
        for ( Iterator ii = uncachedActiveStatements.iterator(); ii.hasNext(); )
        {
            Statement stmt = (Statement) ii.next();
            try
            { stmt.close(); }
            catch ( SQLException e )
            { closeExceptions.add(e); }

            ii.remove();
        }
    }

    private void checkinAllCachedStatements( List closeExceptions )
    {
        try
        {
            if (scache != null)
                scache.checkinAll( physicalConnection );
        }
        catch ( SQLException e )
        { closeExceptions.add(e); }
    }

    private void closeAllCachedStatements() throws SQLException
    {
        if (scache != null)
            scache.closeAll( physicalConnection );
    }

    private void updateConnectionStatus(int status)
    {
        switch ( this.connection_status )
        {
        case ConnectionTester.DATABASE_IS_INVALID:
            //can't get worse than this, do nothing.
            break;
        case ConnectionTester.CONNECTION_IS_INVALID:
            if (status == ConnectionTester.DATABASE_IS_INVALID)
                this.connection_status = status;
            break;
        case ConnectionTester.CONNECTION_IS_OKAY:
            if (status != ConnectionTester.CONNECTION_IS_OKAY)
                this.connection_status = status;
            break;
        default:
            throw new InternalError(this + " -- Illegal Connection Status: " + this.connection_status);
        }
    }

    private Set resultSets( Statement stmt, boolean create )
    { 
        Set out = (Set) resultSetsForStatements.get( stmt ); 
        if ( out == null && create )
        {
            out = new HashSet();
            resultSetsForStatements.put( stmt, out );
        }
        return out;
    }

//  used by C3P0PooledConnectionPool
    Connection getPhysicalConnection()
    { return physicalConnection; }

//  static utility functions
    private static void logCloseExceptions( Throwable cause, Collection exceptions )
    {
        if ( logger.isLoggable( MLevel.INFO ) )
        {
            if (cause != null)
            {
                // 		System.err.println("[c3p0] A PooledConnection died due to the following error!");
                // 		cause.printStackTrace();
                logger.log(MLevel.INFO, "[c3p0] A PooledConnection died due to the following error!", cause);
            }
            if ( exceptions != null && exceptions.size() > 0)
            {
                if ( cause == null )
                    logger.info("[c3p0] Exceptions occurred while trying to close a PooledConnection's resources normally.");
                //System.err.println("[c3p0] The following Exceptions occurred while trying to close a PooledConnection's resources normally.");
                else
                    logger.info("[c3p0] Exceptions occurred while trying to close a Broken PooledConnection.");
                //System.err.println("[c3p0] The following Exceptions occurred while trying to close a broken PooledConnection.");
                for ( Iterator ii = exceptions.iterator(); ii.hasNext(); )
                {
                    Throwable t = (Throwable) ii.next();
                    // 			System.err.print("[c3p0 -- close Exception]: ");
                    // 			t.printStackTrace();
                    logger.log(MLevel.INFO, "[c3p0] NewPooledConnection close Exception.", t);
                }
            }
        }
    }
        
    // JDBC 4.1
 
	public void addStatementEventListener(StatementEventListener arg0) {
	}

	public void removeStatementEventListener(StatementEventListener arg0) {
	}
}