File: InstanceKeyDataSource.java

package info (click to toggle)
tomcat10 10.1.52-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 47,900 kB
  • sloc: java: 375,756; xml: 59,410; jsp: 4,741; sh: 1,381; perl: 324; makefile: 25; ansic: 14
file content (1385 lines) | stat: -rw-r--r-- 56,097 bytes parent folder | download | duplicates (5)
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
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.tomcat.dbcp.dbcp2.datasources;

import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Serializable;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.time.Duration;
import java.util.Properties;
import java.util.logging.Logger;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.Referenceable;
import javax.sql.ConnectionPoolDataSource;
import javax.sql.DataSource;
import javax.sql.PooledConnection;

import org.apache.tomcat.dbcp.dbcp2.Utils;
import org.apache.tomcat.dbcp.pool2.impl.BaseObjectPoolConfig;
import org.apache.tomcat.dbcp.pool2.impl.GenericKeyedObjectPoolConfig;
import org.apache.tomcat.dbcp.pool2.impl.GenericObjectPool;

/**
 * <p>
 * The base class for {@link SharedPoolDataSource} and {@link PerUserPoolDataSource}. Many of the
 * configuration properties are shared and defined here. This class is declared public in order to allow particular
 * usage with commons-beanutils; do not make direct use of it outside of <em>commons-dbcp2</em>.
 * </p>
 *
 * <p>
 * A J2EE container will normally provide some method of initializing the {@link DataSource} whose attributes are
 * presented as bean getters/setters and then deploying it via JNDI. It is then available to an application as a source
 * of pooled logical connections to the database. The pool needs a source of physical connections. This source is in the
 * form of a {@link ConnectionPoolDataSource} that can be specified via the {@link #setDataSourceName(String)} used
 * to lookup the source via JNDI.
 * </p>
 *
 * <p>
 * Although normally used within a JNDI environment, A DataSource can be instantiated and initialized as any bean. In
 * this case the {@link ConnectionPoolDataSource} will likely be instantiated in a similar manner. This class
 * allows the physical source of connections to be attached directly to this pool using the
 * {@link #setConnectionPoolDataSource(ConnectionPoolDataSource)} method.
 * </p>
 *
 * <p>
 * The dbcp package contains an adapter, {@link org.apache.tomcat.dbcp.dbcp2.cpdsadapter.DriverAdapterCPDS}, that can be
 * used to allow the use of {@link DataSource}'s based on this class with JDBC driver implementations that do not
 * supply a {@link ConnectionPoolDataSource}, but still provide a {@link java.sql.Driver} implementation.
 * </p>
 *
 * <p>
 * The <a href="package-summary.html">package documentation</a> contains an example using Apache Tomcat and JNDI and it
 * also contains a non-JNDI example.
 * </p>
 *
 * @since 2.0
 */
public abstract class InstanceKeyDataSource implements DataSource, Referenceable, Serializable, AutoCloseable {

    private static final long serialVersionUID = -6819270431752240878L;

    private static final String GET_CONNECTION_CALLED = "A Connection was already requested from this source, "
            + "further initialization is not allowed.";
    private static final String BAD_TRANSACTION_ISOLATION = "The requested TransactionIsolation level is invalid.";

    /**
     * Internal constant to indicate the level is not set.
     */
    protected static final int UNKNOWN_TRANSACTIONISOLATION = -1;

    /** Guards property setters - once true, setters throw IllegalStateException */
    private volatile boolean getConnectionCalled;

    /** Underlying source of PooledConnections */
    private ConnectionPoolDataSource dataSource;

    /** DataSource Name used to find the ConnectionPoolDataSource */
    private String dataSourceName;

    /** Description */
    private String description;

    /** Environment that may be used to set up a JNDI initial context. */
    private Properties jndiEnvironment;

    /** Login Timeout */
    private Duration loginTimeoutDuration = Duration.ZERO;

    /** Log stream */
    private PrintWriter logWriter;

    /** Instance key */
    private String instanceKey;

    /** Pool property defaults to {@link BaseObjectPoolConfig#DEFAULT_BLOCK_WHEN_EXHAUSTED}. */
    private volatile boolean defaultBlockWhenExhausted = BaseObjectPoolConfig.DEFAULT_BLOCK_WHEN_EXHAUSTED;

    /** Pool property defaults to {@link BaseObjectPoolConfig#DEFAULT_EVICTION_POLICY_CLASS_NAME}. */
    private String defaultEvictionPolicyClassName = BaseObjectPoolConfig.DEFAULT_EVICTION_POLICY_CLASS_NAME;

    /** Pool property defaults to {@link BaseObjectPoolConfig#DEFAULT_LIFO}. */
    private volatile boolean defaultLifo = BaseObjectPoolConfig.DEFAULT_LIFO;

    /** Pool property defaults to {@link GenericKeyedObjectPoolConfig#DEFAULT_MAX_IDLE_PER_KEY}. */
    private volatile int defaultMaxIdle = GenericKeyedObjectPoolConfig.DEFAULT_MAX_IDLE_PER_KEY;

    /** Pool property defaults to {@link GenericKeyedObjectPoolConfig#DEFAULT_MAX_TOTAL}. */
    private volatile int defaultMaxTotal = GenericKeyedObjectPoolConfig.DEFAULT_MAX_TOTAL;

    /** Pool property defaults to {@link BaseObjectPoolConfig#DEFAULT_MAX_WAIT}. */
    private Duration defaultMaxWaitDuration = BaseObjectPoolConfig.DEFAULT_MAX_WAIT;

    /** Pool property defaults to {@link BaseObjectPoolConfig#DEFAULT_MIN_EVICTABLE_IDLE_DURATION}. */
    private Duration defaultMinEvictableIdleDuration = BaseObjectPoolConfig.DEFAULT_MIN_EVICTABLE_IDLE_DURATION;

    /** Pool property defaults to {@link GenericKeyedObjectPoolConfig#DEFAULT_MIN_IDLE_PER_KEY}. */
    private volatile int defaultMinIdle = GenericKeyedObjectPoolConfig.DEFAULT_MIN_IDLE_PER_KEY;

    /** Pool property defaults to {@link BaseObjectPoolConfig#DEFAULT_NUM_TESTS_PER_EVICTION_RUN}. */
    private volatile int defaultNumTestsPerEvictionRun = BaseObjectPoolConfig.DEFAULT_NUM_TESTS_PER_EVICTION_RUN;

    /** Pool property defaults to {@link BaseObjectPoolConfig#DEFAULT_SOFT_MIN_EVICTABLE_IDLE_DURATION}. */
    private Duration defaultSoftMinEvictableIdleDuration = BaseObjectPoolConfig.DEFAULT_SOFT_MIN_EVICTABLE_IDLE_DURATION;

    /** Pool property defaults to {@link BaseObjectPoolConfig#DEFAULT_TEST_ON_CREATE}. */
    private volatile boolean defaultTestOnCreate = BaseObjectPoolConfig.DEFAULT_TEST_ON_CREATE;

    /** Pool property defaults to {@link BaseObjectPoolConfig#DEFAULT_TEST_ON_BORROW}. */
    private volatile boolean defaultTestOnBorrow = BaseObjectPoolConfig.DEFAULT_TEST_ON_BORROW;

    /** Pool property defaults to {@link BaseObjectPoolConfig#DEFAULT_TEST_ON_RETURN}. */
    private volatile boolean defaultTestOnReturn = BaseObjectPoolConfig.DEFAULT_TEST_ON_RETURN;

    /** Pool property defaults to {@link BaseObjectPoolConfig#DEFAULT_TEST_WHILE_IDLE}. */
    private volatile boolean defaultTestWhileIdle = BaseObjectPoolConfig.DEFAULT_TEST_WHILE_IDLE;

    /** Pool property defaults to {@link BaseObjectPoolConfig#DEFAULT_DURATION_BETWEEN_EVICTION_RUNS}. */
    private Duration defaultDurationBetweenEvictionRuns = BaseObjectPoolConfig.DEFAULT_DURATION_BETWEEN_EVICTION_RUNS;

    /** Connection factory property defaults to null. */
    private String validationQuery;

    /** Connection factory property defaults to -1 seconds. */
    private Duration validationQueryTimeoutDuration = Duration.ofSeconds(-1);

    /** Connection factory property defaults to false. */
    private volatile boolean rollbackAfterValidation;

    /** Connection factory property defaults to -1 milliseconds. */
    private Duration maxConnDuration = Duration.ofMillis(-1);

    /** Connection property defaults to false. */
    private Boolean defaultAutoCommit;

    /** Connection property defaults to {@link #UNKNOWN_TRANSACTIONISOLATION}. */
    private volatile int defaultTransactionIsolation = UNKNOWN_TRANSACTIONISOLATION;

    /** Connection property defaults to false. */
    private Boolean defaultReadOnly;

    /**
     * Default no-arg constructor for Serialization.
     */
    public InstanceKeyDataSource() {
    }

    /**
     * Throws an IllegalStateException, if a PooledConnection has already been requested.
     *
     * @throws IllegalStateException Thrown if a PooledConnection has already been requested.
     */
    protected void assertInitializationAllowed() throws IllegalStateException {
        if (getConnectionCalled) {
            throw new IllegalStateException(GET_CONNECTION_CALLED);
        }
    }

    /**
     * Closes the connection pool being maintained by this datasource.
     */
    @Override
    public abstract void close() throws SQLException;

    private void closeDueToException(final PooledConnectionAndInfo info) {
        if (info != null) {
            try {
                info.getPooledConnection().getConnection().close();
            } catch (final Exception e) {
                // do not throw this exception because we are in the middle
                // of handling another exception. But record it because
                // it potentially leaks connections from the pool.
                getLogWriter().println("[ERROR] Could not return connection to pool during exception handling. " + e.getMessage());
            }
        }
    }

    /**
     * Attempts to establish a database connection.
     */
    @Override
    public Connection getConnection() throws SQLException {
        return getConnection(null, null);
    }

    /**
     * Attempts to retrieve a database connection using {@link #getPooledConnectionAndInfo(String, String)} with the
     * provided user name and password. The password on the {@code PooledConnectionAndInfo} instance returned by
     * {@code getPooledConnectionAndInfo} is compared to the {@code password} parameter. If the comparison
     * fails, a database connection using the supplied user name and password is attempted. If the connection attempt
     * fails, an SQLException is thrown, indicating that the given password did not match the password used to create
     * the pooled connection. If the connection attempt succeeds, this means that the database password has been
     * changed. In this case, the {@code PooledConnectionAndInfo} instance retrieved with the old password is
     * destroyed and the {@code getPooledConnectionAndInfo} is repeatedly invoked until a
     * {@code PooledConnectionAndInfo} instance with the new password is returned.
     */
    @Override
    public Connection getConnection(final String userName, final String userPassword) throws SQLException {
        if (instanceKey == null) {
            throw new SQLException("Must set the ConnectionPoolDataSource "
                    + "through setDataSourceName or setConnectionPoolDataSource before calling getConnection.");
        }
        getConnectionCalled = true;
        PooledConnectionAndInfo info = null;
        try {
            info = getPooledConnectionAndInfo(userName, userPassword);
        } catch (final RuntimeException | SQLException e) {
            closeDueToException(info);
            throw e;
        } catch (final Exception e) {
            closeDueToException(info);
            throw new SQLException("Cannot borrow connection from pool", e);
        }

        // Password on PooledConnectionAndInfo does not match
        if (!(null == userPassword ? null == info.getPassword() : userPassword.equals(info.getPassword()))) {
            try { // See if password has changed by attempting connection
                testCPDS(userName, userPassword);
            } catch (final SQLException ex) {
                // Password has not changed, so refuse client, but return connection to the pool
                closeDueToException(info);
                throw new SQLException(
                        "Given password did not match password used to create the PooledConnection.", ex);
            } catch (final javax.naming.NamingException ne) {
                throw new SQLException("NamingException encountered connecting to database", ne);
            }
            /*
             * Password must have changed -> destroy connection and keep retrying until we get a new, good one,
             * destroying any idle connections with the old password as we pull them from the pool.
             */
            final UserPassKey upkey = info.getUserPassKey();
            final PooledConnectionManager manager = getConnectionManager(upkey);
            // Destroy and remove from pool
            manager.invalidate(info.getPooledConnection());
            // Reset the password on the factory if using CPDSConnectionFactory
            manager.setPassword(upkey.getPasswordCharArray());
            info = null;
            for (int i = 0; i < 10; i++) { // Bound the number of retries - only needed if bad instances return
                try {
                    info = getPooledConnectionAndInfo(userName, userPassword);
                } catch (final RuntimeException | SQLException e) {
                    closeDueToException(info);
                    throw e;
                } catch (final Exception e) {
                    closeDueToException(info);
                    throw new SQLException("Cannot borrow connection from pool", e);
                }
                if (info != null && userPassword != null && userPassword.equals(info.getPassword())) {
                    break;
                }
                if (info != null) {
                    manager.invalidate(info.getPooledConnection());
                }
                info = null;
            }
            if (info == null) {
                throw new SQLException("Cannot borrow connection from pool - password change failure.");
            }
        }

        final Connection connection = info.getPooledConnection().getConnection();
        try {
            setupDefaults(connection, userName);
            connection.clearWarnings();
            return connection;
        } catch (final SQLException ex) {
            Utils.close(connection, e -> getLogWriter().println("ignoring exception during close: " + e));
            throw ex;
        }
    }

    /**
     * Gets the pooled connection manager for the given key.
     *
     * @param upkey the key.
     * @return the pooled connection manager for the given key.
     */
    protected abstract PooledConnectionManager getConnectionManager(UserPassKey upkey);

    /**
     * Gets the value of connectionPoolDataSource. This method will return null, if the backing data source is being
     * accessed via JNDI.
     *
     * @return value of connectionPoolDataSource.
     */
    public ConnectionPoolDataSource getConnectionPoolDataSource() {
        return dataSource;
    }

    /**
     * Gets the name of the ConnectionPoolDataSource which backs this pool. This name is used to look up the data source
     * from a JNDI service provider.
     *
     * @return value of dataSourceName.
     */
    public String getDataSourceName() {
        return dataSourceName;
    }

    /**
     * Gets the default value for {@link GenericKeyedObjectPoolConfig#getBlockWhenExhausted()} for each per user pool.
     *
     * @return The default value for {@link GenericKeyedObjectPoolConfig#getBlockWhenExhausted()} for each per user
     *         pool.
     */
    public boolean getDefaultBlockWhenExhausted() {
        return this.defaultBlockWhenExhausted;
    }

    /**
     * Gets the default value for {@link GenericObjectPool#getDurationBetweenEvictionRuns()} for each per user pool.
     *
     * @return The default value for {@link GenericObjectPool#getDurationBetweenEvictionRuns()} for each per user pool.
     * @since 2.10.0
     */
    public Duration getDefaultDurationBetweenEvictionRuns() {
        return this.defaultDurationBetweenEvictionRuns;
    }

    /**
     * Gets the default value for {@link GenericKeyedObjectPoolConfig#getEvictionPolicyClassName()} for each per user
     * pool.
     *
     * @return The default value for {@link GenericKeyedObjectPoolConfig#getEvictionPolicyClassName()} for each per user
     *         pool.
     */
    public String getDefaultEvictionPolicyClassName() {
        return this.defaultEvictionPolicyClassName;
    }

    /**
     * Gets the default value for {@link GenericKeyedObjectPoolConfig#getLifo()} for each per user pool.
     *
     * @return The default value for {@link GenericKeyedObjectPoolConfig#getLifo()} for each per user pool.
     */
    public boolean getDefaultLifo() {
        return this.defaultLifo;
    }

    /**
     * Gets the default value for {@link GenericKeyedObjectPoolConfig#getMaxIdlePerKey()} for each per user pool.
     *
     * @return The default value for {@link GenericKeyedObjectPoolConfig#getMaxIdlePerKey()} for each per user pool.
     */
    public int getDefaultMaxIdle() {
        return this.defaultMaxIdle;
    }

    /**
     * Gets the default value for {@link GenericKeyedObjectPoolConfig#getMaxTotalPerKey()} for each per user pool.
     *
     * @return The default value for {@link GenericKeyedObjectPoolConfig#getMaxTotalPerKey()} for each per user pool.
     */
    public int getDefaultMaxTotal() {
        return this.defaultMaxTotal;
    }

    /**
     * Gets the default value for {@link GenericKeyedObjectPoolConfig#getMaxWaitDuration()} for each per user pool.
     *
     * @return The default value for {@link GenericKeyedObjectPoolConfig#getMaxWaitDuration()} for each per user pool.
     * @since 2.9.0
     */
    public Duration getDefaultMaxWait() {
        return this.defaultMaxWaitDuration;
    }

    /**
     * Gets the default value for {@link GenericKeyedObjectPoolConfig#getMaxWaitDuration()} for each per user pool.
     *
     * @return The default value for {@link GenericKeyedObjectPoolConfig#getMaxWaitDuration()} for each per user pool.
     * @deprecated Use {@link #getDefaultMaxWait()}.
     */
    @Deprecated
    public long getDefaultMaxWaitMillis() {
        return getDefaultMaxWait().toMillis();
    }

    /**
     * Gets the default value for {@link GenericKeyedObjectPoolConfig#getMinEvictableIdleDuration()} for each per user
     * pool.
     *
     * @return The default value for {@link GenericKeyedObjectPoolConfig#getMinEvictableIdleDuration()} for each per
     *         user pool.
     * @since 2.10.0
     */
    public Duration getDefaultMinEvictableIdleDuration() {
        return this.defaultMinEvictableIdleDuration;
    }

    /**
     * Gets the default value for {@link GenericKeyedObjectPoolConfig#getMinEvictableIdleDuration()} for each per user
     * pool.
     *
     * @return The default value for {@link GenericKeyedObjectPoolConfig#getMinEvictableIdleDuration()} for each per
     *         user pool.
     * @deprecated Use {@link #getDefaultMinEvictableIdleDuration()}.
     */
    @Deprecated
    public long getDefaultMinEvictableIdleTimeMillis() {
        return this.defaultMinEvictableIdleDuration.toMillis();
    }

    /**
     * Gets the default value for {@link GenericKeyedObjectPoolConfig#getMinIdlePerKey()} for each per user pool.
     *
     * @return The default value for {@link GenericKeyedObjectPoolConfig#getMinIdlePerKey()} for each per user pool.
     */
    public int getDefaultMinIdle() {
        return this.defaultMinIdle;
    }

    /**
     * Gets the default value for {@link GenericKeyedObjectPoolConfig#getNumTestsPerEvictionRun()} for each per user
     * pool.
     *
     * @return The default value for {@link GenericKeyedObjectPoolConfig#getNumTestsPerEvictionRun()} for each per user
     *         pool.
     */
    public int getDefaultNumTestsPerEvictionRun() {
        return this.defaultNumTestsPerEvictionRun;
    }

    /**
     * Gets the default value for {@link
     * GenericObjectPool#getSoftMinEvictableIdleDuration()} for each per user pool.
     *
     * @return The default value for {@link
     *         GenericObjectPool#getSoftMinEvictableIdleDuration()} for each per user pool.
     * @since 2.10.0
     */
    public Duration getDefaultSoftMinEvictableIdleDuration() {
        return this.defaultSoftMinEvictableIdleDuration;
    }

    /**
     * Gets the default value for {@link
     * GenericObjectPool#getSoftMinEvictableIdleTimeMillis()} for each per user pool.
     *
     * @return The default value for {@link
     *         GenericObjectPool#getSoftMinEvictableIdleTimeMillis()} for each per user pool.
     * @deprecated Use {@link #getDefaultSoftMinEvictableIdleDuration()}.
     */
    @Deprecated
    public long getDefaultSoftMinEvictableIdleTimeMillis() {
        return this.defaultSoftMinEvictableIdleDuration.toMillis();
    }

    /**
     * Gets the default value for {@link
     * GenericObjectPool#getTestOnBorrow()} for each per user pool.
     *
     * @return The default value for {@link
     *         GenericObjectPool#getTestOnBorrow()} for each per user pool.
     */
    public boolean getDefaultTestOnBorrow() {
        return this.defaultTestOnBorrow;
    }

    /**
     * Gets the default value for {@link
     * GenericObjectPool#getTestOnCreate()} for each per user pool.
     *
     * @return The default value for {@link
     *         GenericObjectPool#getTestOnCreate()} for each per user pool.
     */
    public boolean getDefaultTestOnCreate() {
        return this.defaultTestOnCreate;
    }

    /**
     * Gets the default value for {@link
     * GenericObjectPool#getTestOnReturn()} for each per user pool.
     *
     * @return The default value for {@link
     *         GenericObjectPool#getTestOnReturn()} for each per user pool.
     */
    public boolean getDefaultTestOnReturn() {
        return this.defaultTestOnReturn;
    }

    /**
     * Gets the default value for {@link
     * GenericObjectPool#getTestWhileIdle()} for each per user pool.
     *
     * @return The default value for {@link
     *         GenericObjectPool#getTestWhileIdle()} for each per user pool.
     */
    public boolean getDefaultTestWhileIdle() {
        return this.defaultTestWhileIdle;
    }

    /**
     * Gets the default value for {@link GenericObjectPool#getDurationBetweenEvictionRuns ()} for each per user pool.
     *
     * @return The default value for {@link GenericObjectPool#getDurationBetweenEvictionRuns ()} for each per user pool.
     * @deprecated Use {@link #getDefaultDurationBetweenEvictionRuns()}.
     */
    @Deprecated
    public long getDefaultTimeBetweenEvictionRunsMillis() {
        return this.defaultDurationBetweenEvictionRuns.toMillis();
    }

    /**
     * Gets the value of defaultTransactionIsolation, which defines the state of connections handed out from this pool.
     * The value can be changed on the Connection using Connection.setTransactionIsolation(int). If this method returns
     * -1, the default is JDBC driver dependent.
     *
     * @return value of defaultTransactionIsolation.
     */
    public int getDefaultTransactionIsolation() {
        return defaultTransactionIsolation;
    }

    /**
     * Gets the description. This property is defined by JDBC as for use with GUI (or other) tools that might deploy the
     * datasource. It serves no internal purpose.
     *
     * @return value of description.
     */
    public String getDescription() {
        return description;
    }

    /**
     * Gets the instance key.
     *
     * @return the instance key.
     */
    protected String getInstanceKey() {
        return instanceKey;
    }

    /**
     * Gets the value of jndiEnvironment which is used when instantiating a JNDI InitialContext. This InitialContext is
     * used to locate the back end ConnectionPoolDataSource.
     *
     * @param key
     *            JNDI environment key.
     * @return value of jndiEnvironment.
     */
    public String getJndiEnvironment(final String key) {
        String value = null;
        if (jndiEnvironment != null) {
            value = jndiEnvironment.getProperty(key);
        }
        return value;
    }

    /**
     * Gets the value of loginTimeout.
     *
     * @return value of loginTimeout.
     * @deprecated Use {@link #getLoginTimeoutDuration()}.
     */
    @Deprecated
    @Override
    public int getLoginTimeout() {
        return (int) loginTimeoutDuration.getSeconds();
    }

    /**
     * Gets the value of loginTimeout.
     *
     * @return value of loginTimeout.
     * @since 2.10.0
     */
    public Duration getLoginTimeoutDuration() {
        return loginTimeoutDuration;
    }

    /**
     * Gets the value of logWriter.
     *
     * @return value of logWriter.
     */
    @Override
    public PrintWriter getLogWriter() {
        if (logWriter == null) {
            logWriter = new PrintWriter(new OutputStreamWriter(System.out, StandardCharsets.UTF_8));
        }
        return logWriter;
    }

    /**
     * Gets the maximum permitted lifetime of a connection. A value of zero or less indicates an
     * infinite lifetime.
     *
     * @return The maximum permitted lifetime of a connection. A value of zero or less indicates an
     *         infinite lifetime.
     * @since 2.10.0
     */
    public Duration getMaxConnDuration() {
        return maxConnDuration;
    }

    /**
     * Gets the maximum permitted lifetime of a connection. A value of zero or less indicates an
     * infinite lifetime.
     *
     * @return The maximum permitted lifetime of a connection. A value of zero or less indicates an
     *         infinite lifetime.
     * @deprecated Use {@link #getMaxConnDuration()}.
     */
    @Deprecated
    public Duration getMaxConnLifetime() {
        return maxConnDuration;
    }

    /**
     * Gets the maximum permitted lifetime of a connection in milliseconds. A value of zero or less indicates an
     * infinite lifetime.
     *
     * @return The maximum permitted lifetime of a connection in milliseconds. A value of zero or less indicates an
     *         infinite lifetime.
     * @deprecated Use {@link #getMaxConnLifetime()}.
     */
    @Deprecated
    public long getMaxConnLifetimeMillis() {
        return maxConnDuration.toMillis();
    }

    @Override
    public Logger getParentLogger() throws SQLFeatureNotSupportedException {
        throw new SQLFeatureNotSupportedException();
    }

    /**
     * This method is protected but can only be implemented in this package because PooledConnectionAndInfo is a package
     * private type.
     *
     * @param userName The user name.
     * @param userPassword The user password.
     * @return Matching PooledConnectionAndInfo.
     * @throws SQLException Connection or registration failure.
     */
    protected abstract PooledConnectionAndInfo getPooledConnectionAndInfo(String userName, String userPassword)
            throws SQLException;

    /**
     * Gets 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. If not
     * specified, {@link Connection#isValid(int)} will be used to validate connections.
     *
     * @return The SQL query that will be used to validate connections from this pool before returning them to the
     *         caller.
     */
    public String getValidationQuery() {
        return this.validationQuery;
    }

    /**
     * Returns the timeout in seconds before the validation query fails.
     *
     * @return The timeout in seconds before the validation query fails.
     * @deprecated Use {@link #getValidationQueryTimeoutDuration()}.
     */
    @Deprecated
    public int getValidationQueryTimeout() {
        return (int) validationQueryTimeoutDuration.getSeconds();
    }

    /**
     * Returns the timeout Duration before the validation query fails.
     *
     * @return The timeout Duration before the validation query fails.
     */
    public Duration getValidationQueryTimeoutDuration() {
        return validationQueryTimeoutDuration;
    }

    /**
     * Gets the value of defaultAutoCommit, which defines the state of connections handed out from this pool. The value
     * can be changed on the Connection using Connection.setAutoCommit(boolean). The default is {@code null} which
     * will use the default value for the driver.
     *
     * @return value of defaultAutoCommit.
     */
    public Boolean isDefaultAutoCommit() {
        return defaultAutoCommit;
    }

    /**
     * Gets the value of defaultReadOnly, which defines the state of connections handed out from this pool. The value
     * can be changed on the Connection using Connection.setReadOnly(boolean). The default is {@code null} which
     * will use the default value for the driver.
     *
     * @return value of defaultReadOnly.
     */
    public Boolean isDefaultReadOnly() {
        return defaultReadOnly;
    }

    /**
     * Tests whether a rollback will be issued after executing the SQL query that will be used to validate connections from
     * this pool before returning them to the caller.
     *
     * @return true if a rollback will be issued after executing the validation query
     */
    public boolean isRollbackAfterValidation() {
        return this.rollbackAfterValidation;
    }

    @Override
    public boolean isWrapperFor(final Class<?> iface) throws SQLException {
        return iface.isInstance(this);
    }

    /**
     * Sets the back end ConnectionPoolDataSource. This property should not be set if using JNDI to access the
     * data source.
     *
     * @param dataSource
     *            Value to assign to connectionPoolDataSource.
     */
    public void setConnectionPoolDataSource(final ConnectionPoolDataSource dataSource) {
        assertInitializationAllowed();
        if (dataSourceName != null) {
            throw new IllegalStateException("Cannot set the DataSource, if JNDI is used.");
        }
        if (this.dataSource != null) {
            throw new IllegalStateException("The CPDS has already been set. It cannot be altered.");
        }
        this.dataSource = dataSource;
        instanceKey = InstanceKeyDataSourceFactory.registerNewInstance(this);
    }

    /**
     * Sets the name of the ConnectionPoolDataSource which backs this pool. This name is used to look up the data source
     * from a JNDI service provider.
     *
     * @param dataSourceName
     *            Value to assign to dataSourceName.
     */
    public void setDataSourceName(final String dataSourceName) {
        assertInitializationAllowed();
        if (dataSource != null) {
            throw new IllegalStateException("Cannot set the JNDI name for the DataSource, if already "
                    + "set using setConnectionPoolDataSource.");
        }
        if (this.dataSourceName != null) {
            throw new IllegalStateException("The DataSourceName has already been set. It cannot be altered.");
        }
        this.dataSourceName = dataSourceName;
        instanceKey = InstanceKeyDataSourceFactory.registerNewInstance(this);
    }

    /**
     * Sets the value of defaultAutoCommit, which defines the state of connections handed out from this pool. The value
     * can be changed on the Connection using Connection.setAutoCommit(boolean). The default is {@code null} which
     * will use the default value for the driver.
     *
     * @param defaultAutoCommit
     *            Value to assign to defaultAutoCommit.
     */
    public void setDefaultAutoCommit(final Boolean defaultAutoCommit) {
        assertInitializationAllowed();
        this.defaultAutoCommit = defaultAutoCommit;
    }

    /**
     * Sets the default value for {@link GenericKeyedObjectPoolConfig#getBlockWhenExhausted()} for each per user pool.
     *
     * @param blockWhenExhausted
     *            The default value for {@link GenericKeyedObjectPoolConfig#getBlockWhenExhausted()} for each per user
     *            pool.
     */
    public void setDefaultBlockWhenExhausted(final boolean blockWhenExhausted) {
        assertInitializationAllowed();
        this.defaultBlockWhenExhausted = blockWhenExhausted;
    }

    /**
     * Sets the default value for {@link GenericObjectPool#getDurationBetweenEvictionRuns ()} for each per user pool.
     *
     * @param defaultDurationBetweenEvictionRuns The default value for
     *        {@link GenericObjectPool#getDurationBetweenEvictionRuns ()} for each per user pool.
     * @since 2.10.0
     */
    public void setDefaultDurationBetweenEvictionRuns(final Duration defaultDurationBetweenEvictionRuns) {
        assertInitializationAllowed();
        this.defaultDurationBetweenEvictionRuns = defaultDurationBetweenEvictionRuns;
    }

    /**
     * Sets the default value for {@link GenericKeyedObjectPoolConfig#getEvictionPolicyClassName()} for each per user
     * pool.
     *
     * @param evictionPolicyClassName
     *            The default value for {@link GenericKeyedObjectPoolConfig#getEvictionPolicyClassName()} for each per
     *            user pool.
     */
    public void setDefaultEvictionPolicyClassName(final String evictionPolicyClassName) {
        assertInitializationAllowed();
        this.defaultEvictionPolicyClassName = evictionPolicyClassName;
    }

    /**
     * Sets the default value for {@link GenericKeyedObjectPoolConfig#getLifo()} for each per user pool.
     *
     * @param lifo
     *            The default value for {@link GenericKeyedObjectPoolConfig#getLifo()} for each per user pool.
     */
    public void setDefaultLifo(final boolean lifo) {
        assertInitializationAllowed();
        this.defaultLifo = lifo;
    }

    /**
     * Sets the default value for {@link GenericKeyedObjectPoolConfig#getMaxIdlePerKey()} for each per user pool.
     *
     * @param maxIdle
     *            The default value for {@link GenericKeyedObjectPoolConfig#getMaxIdlePerKey()} for each per user pool.
     */
    public void setDefaultMaxIdle(final int maxIdle) {
        assertInitializationAllowed();
        this.defaultMaxIdle = maxIdle;
    }

    /**
     * Sets the default value for {@link GenericKeyedObjectPoolConfig#getMaxTotalPerKey()} for each per user pool.
     *
     * @param maxTotal
     *            The default value for {@link GenericKeyedObjectPoolConfig#getMaxTotalPerKey()} for each per user pool.
     */
    public void setDefaultMaxTotal(final int maxTotal) {
        assertInitializationAllowed();
        this.defaultMaxTotal = maxTotal;
    }

    /**
     * Sets the default value for {@link GenericKeyedObjectPoolConfig#getMaxWaitDuration()} for each per user pool.
     *
     * @param maxWaitMillis
     *            The default value for {@link GenericKeyedObjectPoolConfig#getMaxWaitDuration()} for each per user pool.
     * @since 2.9.0
     */
    public void setDefaultMaxWait(final Duration maxWaitMillis) {
        assertInitializationAllowed();
        this.defaultMaxWaitDuration = maxWaitMillis;
    }

    /**
     * Sets the default value for {@link GenericKeyedObjectPoolConfig#getMaxWaitMillis()} for each per user pool.
     *
     * @param maxWaitMillis
     *            The default value for {@link GenericKeyedObjectPoolConfig#getMaxWaitMillis()} for each per user pool.
     * @deprecated Use {@link #setDefaultMaxWait(Duration)}.
     */
    @Deprecated
    public void setDefaultMaxWaitMillis(final long maxWaitMillis) {
        setDefaultMaxWait(Duration.ofMillis(maxWaitMillis));
    }

    /**
     * Sets the default value for {@link GenericKeyedObjectPoolConfig#getMinEvictableIdleDuration()} for each per user
     * pool.
     *
     * @param defaultMinEvictableIdleDuration
     *            The default value for {@link GenericKeyedObjectPoolConfig#getMinEvictableIdleDuration()} for each
     *            per user pool.
     * @since 2.10.0
     */
    public void setDefaultMinEvictableIdle(final Duration defaultMinEvictableIdleDuration) {
        assertInitializationAllowed();
        this.defaultMinEvictableIdleDuration = defaultMinEvictableIdleDuration;
    }

    /**
     * Sets the default value for {@link GenericKeyedObjectPoolConfig#getMinEvictableIdleDuration()} for each per user
     * pool.
     *
     * @param minEvictableIdleTimeMillis
     *            The default value for {@link GenericKeyedObjectPoolConfig#getMinEvictableIdleDuration()} for each
     *            per user pool.
     * @deprecated Use {@link #setDefaultMinEvictableIdle(Duration)}.
     */
    @Deprecated
    public void setDefaultMinEvictableIdleTimeMillis(final long minEvictableIdleTimeMillis) {
        assertInitializationAllowed();
        this.defaultMinEvictableIdleDuration = Duration.ofMillis(minEvictableIdleTimeMillis);
    }

    /**
     * Sets the default value for {@link GenericKeyedObjectPoolConfig#getMinIdlePerKey()} for each per user pool.
     *
     * @param minIdle
     *            The default value for {@link GenericKeyedObjectPoolConfig#getMinIdlePerKey()} for each per user pool.
     */
    public void setDefaultMinIdle(final int minIdle) {
        assertInitializationAllowed();
        this.defaultMinIdle = minIdle;
    }

    /**
     * Sets the default value for {@link GenericKeyedObjectPoolConfig#getNumTestsPerEvictionRun()} for each per user
     * pool.
     *
     * @param numTestsPerEvictionRun
     *            The default value for {@link GenericKeyedObjectPoolConfig#getNumTestsPerEvictionRun()} for each per
     *            user pool.
     */
    public void setDefaultNumTestsPerEvictionRun(final int numTestsPerEvictionRun) {
        assertInitializationAllowed();
        this.defaultNumTestsPerEvictionRun = numTestsPerEvictionRun;
    }

    /**
     * Sets the value of defaultReadOnly, which defines the state of connections handed out from this pool. The value
     * can be changed on the Connection using Connection.setReadOnly(boolean). The default is {@code null} which
     * will use the default value for the driver.
     *
     * @param defaultReadOnly
     *            Value to assign to defaultReadOnly.
     */
    public void setDefaultReadOnly(final Boolean defaultReadOnly) {
        assertInitializationAllowed();
        this.defaultReadOnly = defaultReadOnly;
    }

    /**
     * Sets the default value for {@link
     * GenericObjectPool#getSoftMinEvictableIdleDuration()} for each per user pool.
     *
     * @param defaultSoftMinEvictableIdleDuration
     *            The default value for {@link
     *            GenericObjectPool#getSoftMinEvictableIdleDuration()} for each per user pool.
     * @since 2.10.0
     */
    public void setDefaultSoftMinEvictableIdle(final Duration defaultSoftMinEvictableIdleDuration) {
        assertInitializationAllowed();
        this.defaultSoftMinEvictableIdleDuration = defaultSoftMinEvictableIdleDuration;
    }

    /**
     * Sets the default value for {@link
     * GenericObjectPool#getSoftMinEvictableIdleTimeMillis()} for each per user pool.
     *
     * @param softMinEvictableIdleTimeMillis
     *            The default value for {@link
     *            GenericObjectPool#getSoftMinEvictableIdleTimeMillis()} for each per user pool.
     * @deprecated Use {@link #setDefaultSoftMinEvictableIdle(Duration)}.
     */
    @Deprecated
    public void setDefaultSoftMinEvictableIdleTimeMillis(final long softMinEvictableIdleTimeMillis) {
        assertInitializationAllowed();
        this.defaultSoftMinEvictableIdleDuration = Duration.ofMillis(softMinEvictableIdleTimeMillis);
    }

    /**
     * Sets the default value for {@link
     * GenericObjectPool#getTestOnBorrow()} for each per user pool.
     *
     * @param testOnBorrow
     *            The default value for {@link
     *            GenericObjectPool#getTestOnBorrow()} for each per user pool.
     */
    public void setDefaultTestOnBorrow(final boolean testOnBorrow) {
        assertInitializationAllowed();
        this.defaultTestOnBorrow = testOnBorrow;
    }

    /**
     * Sets the default value for {@link
     * GenericObjectPool#getTestOnCreate()} for each per user pool.
     *
     * @param testOnCreate
     *            The default value for {@link
     *            GenericObjectPool#getTestOnCreate()} for each per user pool.
     */
    public void setDefaultTestOnCreate(final boolean testOnCreate) {
        assertInitializationAllowed();
        this.defaultTestOnCreate = testOnCreate;
    }

    /**
     * Sets the default value for {@link
     * GenericObjectPool#getTestOnReturn()} for each per user pool.
     *
     * @param testOnReturn
     *            The default value for {@link
     *            GenericObjectPool#getTestOnReturn()} for each per user pool.
     */
    public void setDefaultTestOnReturn(final boolean testOnReturn) {
        assertInitializationAllowed();
        this.defaultTestOnReturn = testOnReturn;
    }

    /**
     * Sets the default value for {@link
     * GenericObjectPool#getTestWhileIdle()} for each per user pool.
     *
     * @param testWhileIdle
     *            The default value for {@link
     *            GenericObjectPool#getTestWhileIdle()} for each per user pool.
     */
    public void setDefaultTestWhileIdle(final boolean testWhileIdle) {
        assertInitializationAllowed();
        this.defaultTestWhileIdle = testWhileIdle;
    }

    /**
     * Sets the default value for {@link GenericObjectPool#getDurationBetweenEvictionRuns()} for each per user pool.
     *
     * @param timeBetweenEvictionRunsMillis The default value for
     *        {@link GenericObjectPool#getDurationBetweenEvictionRuns()} for each per user pool.
     * @deprecated Use {@link #setDefaultDurationBetweenEvictionRuns(Duration)}.
     */
    @Deprecated
    public void setDefaultTimeBetweenEvictionRunsMillis(final long timeBetweenEvictionRunsMillis) {
        assertInitializationAllowed();
        this.defaultDurationBetweenEvictionRuns = Duration.ofMillis(timeBetweenEvictionRunsMillis);
    }

    /**
     * Sets the value of defaultTransactionIsolation, which defines the state of connections handed out from this pool.
     * The value can be changed on the Connection using Connection.setTransactionIsolation(int). The default is JDBC
     * driver dependent.
     *
     * @param defaultTransactionIsolation
     *            Value to assign to defaultTransactionIsolation
     */
    public void setDefaultTransactionIsolation(final int defaultTransactionIsolation) {
        assertInitializationAllowed();
        switch (defaultTransactionIsolation) {
            case Connection.TRANSACTION_NONE:
            case Connection.TRANSACTION_READ_COMMITTED:
            case Connection.TRANSACTION_READ_UNCOMMITTED:
            case Connection.TRANSACTION_REPEATABLE_READ:
            case Connection.TRANSACTION_SERIALIZABLE:
                break;
            default:
                throw new IllegalArgumentException(BAD_TRANSACTION_ISOLATION);
        }
        this.defaultTransactionIsolation = defaultTransactionIsolation;
    }

    /**
     * Sets the description. This property is defined by JDBC as for use with GUI (or other) tools that might deploy the
     * datasource. It serves no internal purpose.
     *
     * @param description
     *            Value to assign to description.
     */
    public void setDescription(final String description) {
        this.description = description;
    }

    /**
     * Sets the JNDI environment to be used when instantiating a JNDI InitialContext. This InitialContext is used to
     * locate the back end ConnectionPoolDataSource.
     *
     * @param properties
     *            the JNDI environment property to set which will overwrite any current settings
     */
    void setJndiEnvironment(final Properties properties) {
        if (jndiEnvironment == null) {
            jndiEnvironment = new Properties();
        } else {
            jndiEnvironment.clear();
        }
        jndiEnvironment.putAll(properties);
    }

    /**
     * Sets the value of the given JNDI environment property to be used when instantiating a JNDI InitialContext. This
     * InitialContext is used to locate the back end ConnectionPoolDataSource.
     *
     * @param key
     *            the JNDI environment property to set.
     * @param value
     *            the value assigned to specified JNDI environment property.
     */
    public void setJndiEnvironment(final String key, final String value) {
        if (jndiEnvironment == null) {
            jndiEnvironment = new Properties();
        }
        jndiEnvironment.setProperty(key, value);
    }

    /**
     * Sets the value of loginTimeout.
     *
     * @param loginTimeout
     *            Value to assign to loginTimeout.
     * @since 2.10.0
     */
    public void setLoginTimeout(final Duration loginTimeout) {
        this.loginTimeoutDuration = loginTimeout;
    }

    /**
     * Sets the value of loginTimeout.
     *
     * @param loginTimeout
     *            Value to assign to loginTimeout.
     * @deprecated Use {@link #setLoginTimeout(Duration)}.
     */
    @Deprecated
    @Override
    public void setLoginTimeout(final int loginTimeout) {
        this.loginTimeoutDuration = Duration.ofSeconds(loginTimeout);
    }

    /**
     * Sets the value of logWriter.
     *
     * @param logWriter
     *            Value to assign to logWriter.
     */
    @Override
    public void setLogWriter(final PrintWriter logWriter) {
        this.logWriter = logWriter;
    }

    /**
     * <p>
     * Sets the maximum permitted lifetime of a connection. A value of zero or less indicates an infinite lifetime.
     * </p>
     * <p>
     * Note: this method currently has no effect once the pool has been initialized. The pool is initialized the first time one of the following methods is
     * invoked: {@link #getConnection()}, {@link #setLogWriter(PrintWriter)}, {@link #setLoginTimeout(Duration)}, {@link #getLoginTimeoutDuration()},
     * {@link #getLogWriter()}.
     * </p>
     *
     * @param maxConnLifetimeMillis The maximum permitted lifetime of a connection. A value of zero or less indicates an infinite lifetime.
     * @since 2.9.0
     */
    public void setMaxConnLifetime(final Duration maxConnLifetimeMillis) {
        this.maxConnDuration = maxConnLifetimeMillis;
    }

    /**
     * <p>
     * Sets the maximum permitted lifetime of a connection in milliseconds. A value of zero or less indicates an infinite lifetime.
     * </p>
     * <p>
     * Note: this method currently has no effect once the pool has been initialized. The pool is initialized the first time one of the following methods is
     * invoked: {@link #getConnection()}, {@link #setLogWriter(PrintWriter)}, {@link #setLoginTimeout(Duration)}, {@link #getLoginTimeoutDuration()},
     * {@link #getLogWriter()}.
     * </p>
     *
     * @param maxConnLifetimeMillis The maximum permitted lifetime of a connection in milliseconds. A value of zero or less indicates an infinite lifetime.
     * @deprecated Use {@link #setMaxConnLifetime(Duration)}.
     */
    @Deprecated
    public void setMaxConnLifetimeMillis(final long maxConnLifetimeMillis) {
        setMaxConnLifetime(Duration.ofMillis(maxConnLifetimeMillis));
    }

    /**
     * Sets whether a rollback will be issued after executing the SQL query that will be used to validate connections from
     * this pool before returning them to the caller. Default behavior is NOT to issue a rollback. The setting will only
     * have an effect if a validation query is set
     *
     * @param rollbackAfterValidation
     *            new property value
     */
    public void setRollbackAfterValidation(final boolean rollbackAfterValidation) {
        assertInitializationAllowed();
        this.rollbackAfterValidation = rollbackAfterValidation;
    }

    /**
     * Sets up the defaults for a given connection.
     *
     * @param connection The target connection.
     * @param userName   The user name for the connection.
     * @throws SQLException if a database access error occurs or this method is called on a closed connection
     */
    protected abstract void setupDefaults(Connection connection, String userName) throws SQLException;

    /**
     * Sets 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. If not
     * specified, connections will be validated using {@link Connection#isValid(int)}.
     *
     * @param validationQuery
     *            The SQL query that will be used to validate connections from this pool before returning them to the
     *            caller.
     */
    public void setValidationQuery(final String validationQuery) {
        assertInitializationAllowed();
        this.validationQuery = validationQuery;
    }

    /**
     * Sets the timeout duration before the validation query fails.
     *
     * @param validationQueryTimeoutDuration
     *            The new timeout duration.
     */
    public void setValidationQueryTimeout(final Duration validationQueryTimeoutDuration) {
        this.validationQueryTimeoutDuration = validationQueryTimeoutDuration;
    }

    /**
     * Sets the timeout in seconds before the validation query fails.
     *
     * @param validationQueryTimeoutSeconds
     *            The new timeout in seconds
     * @deprecated Use {@link #setValidationQueryTimeout(Duration)}.
     */
    @Deprecated
    public void setValidationQueryTimeout(final int validationQueryTimeoutSeconds) {
        this.validationQueryTimeoutDuration = Duration.ofSeconds(validationQueryTimeoutSeconds);
    }

    /**
     * Tests and returns whether a JNDI context can be created to lookup a ConnectionPoolDataSource to then access a PooledConnection connection.
     *
     * @param userName     An optional user name, may be null.
     * @param userPassword An optional user user password, may be null.
     * @return A ConnectionPoolDataSource from a JNDI context.
     * @throws javax.naming.NamingException if a naming exception is encountered.
     * @throws SQLException                 if a ConnectionPoolDataSource or PooledConnection is not available.
     */
    protected ConnectionPoolDataSource testCPDS(final String userName, final String userPassword)
            throws javax.naming.NamingException, SQLException {
        // The source of physical database connections
        ConnectionPoolDataSource cpds = this.dataSource;
        if (cpds == null) {
            Context ctx = null;
            if (jndiEnvironment == null) {
                ctx = new InitialContext();
            } else {
                ctx = new InitialContext(jndiEnvironment);
            }
            final Object ds = ctx.lookup(dataSourceName);
            if (!(ds instanceof ConnectionPoolDataSource)) {
                throw new SQLException("Illegal configuration: DataSource " + dataSourceName + " ("
                        + ds.getClass().getName() + ") doesn't implement javax.sql.ConnectionPoolDataSource");
            }
            cpds = (ConnectionPoolDataSource) ds;
        }
        // try to get a connection with the supplied userName/password
        PooledConnection conn = null;
        try {
            if (userName != null) {
                conn = cpds.getPooledConnection(userName, userPassword);
            } else {
                conn = cpds.getPooledConnection();
            }
            if (conn == null) {
                throw new SQLException("Cannot connect using the supplied userName/password");
            }
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (final SQLException ignored) {
                    // at least we could connect
                }
            }
        }
        return cpds;
    }

    /**
     * @since 2.6.0
     */
    @Override
    public synchronized String toString() {
        final StringBuilder builder = new StringBuilder(super.toString());
        builder.append('[');
        toStringFields(builder);
        builder.append(']');
        return builder.toString();
    }

    /**
     * Appends this instance's fields to a string builder.
     *
     * @param builder the target string builder.
     */
    protected void toStringFields(final StringBuilder builder) {
        builder.append("getConnectionCalled=");
        builder.append(getConnectionCalled);
        builder.append(", dataSource=");
        builder.append(dataSource);
        builder.append(", dataSourceName=");
        builder.append(dataSourceName);
        builder.append(", description=");
        builder.append(description);
        builder.append(", jndiEnvironment=");
        builder.append(jndiEnvironment);
        builder.append(", loginTimeoutDuration=");
        builder.append(loginTimeoutDuration);
        builder.append(", logWriter=");
        builder.append(logWriter);
        builder.append(", instanceKey=");
        builder.append(instanceKey);
        builder.append(", defaultBlockWhenExhausted=");
        builder.append(defaultBlockWhenExhausted);
        builder.append(", defaultEvictionPolicyClassName=");
        builder.append(defaultEvictionPolicyClassName);
        builder.append(", defaultLifo=");
        builder.append(defaultLifo);
        builder.append(", defaultMaxIdle=");
        builder.append(defaultMaxIdle);
        builder.append(", defaultMaxTotal=");
        builder.append(defaultMaxTotal);
        builder.append(", defaultMaxWaitDuration=");
        builder.append(defaultMaxWaitDuration);
        builder.append(", defaultMinEvictableIdleDuration=");
        builder.append(defaultMinEvictableIdleDuration);
        builder.append(", defaultMinIdle=");
        builder.append(defaultMinIdle);
        builder.append(", defaultNumTestsPerEvictionRun=");
        builder.append(defaultNumTestsPerEvictionRun);
        builder.append(", defaultSoftMinEvictableIdleDuration=");
        builder.append(defaultSoftMinEvictableIdleDuration);
        builder.append(", defaultTestOnCreate=");
        builder.append(defaultTestOnCreate);
        builder.append(", defaultTestOnBorrow=");
        builder.append(defaultTestOnBorrow);
        builder.append(", defaultTestOnReturn=");
        builder.append(defaultTestOnReturn);
        builder.append(", defaultTestWhileIdle=");
        builder.append(defaultTestWhileIdle);
        builder.append(", defaultDurationBetweenEvictionRuns=");
        builder.append(defaultDurationBetweenEvictionRuns);
        builder.append(", validationQuery=");
        builder.append(validationQuery);
        builder.append(", validationQueryTimeoutDuration=");
        builder.append(validationQueryTimeoutDuration);
        builder.append(", rollbackAfterValidation=");
        builder.append(rollbackAfterValidation);
        builder.append(", maxConnDuration=");
        builder.append(maxConnDuration);
        builder.append(", defaultAutoCommit=");
        builder.append(defaultAutoCommit);
        builder.append(", defaultTransactionIsolation=");
        builder.append(defaultTransactionIsolation);
        builder.append(", defaultReadOnly=");
        builder.append(defaultReadOnly);
    }

    @Override
    @SuppressWarnings("unchecked")
    public <T> T unwrap(final Class<T> iface) throws SQLException {
        if (isWrapperFor(iface)) {
            return (T) this;
        }
        throw new SQLException(this + " is not a wrapper for " + iface);
    }
}