-
Notifications
You must be signed in to change notification settings - Fork 250
Expand file tree
/
Copy pathTestBasicDataSource.java
More file actions
1217 lines (1063 loc) · 46.1 KB
/
Copy pathTestBasicDataSource.java
File metadata and controls
1217 lines (1063 loc) · 46.1 KB
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
/*
* 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.commons.dbcp2;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadMXBean;
import java.sql.Connection;
import java.sql.SQLException;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Stream;
import javax.management.AttributeNotFoundException;
import javax.management.MBeanAttributeInfo;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.sql.DataSource;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
/**
* TestSuite for BasicDataSource
*/
public class TestBasicDataSource extends TestConnectionPool {
private static final String CATALOG = "test catalog";
protected BasicDataSource ds;
protected BasicDataSource createDataSource() throws Exception {
return new BasicDataSource();
}
@Override
protected Connection getConnection() throws Exception {
return ds.getConnection();
}
@BeforeEach
public void setUp() throws Exception {
ds = createDataSource();
ds.setDriverClassName("org.apache.commons.dbcp2.TesterDriver");
ds.setUrl("jdbc:apache:commons:testdriver");
ds.setMaxTotal(getMaxTotal());
ds.setMaxWait(getMaxWaitDuration());
ds.setDefaultAutoCommit(Boolean.TRUE);
ds.setDefaultReadOnly(Boolean.FALSE);
ds.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
ds.setDefaultCatalog(CATALOG);
ds.setUsername("userName");
ds.setPassword("password");
ds.setValidationQuery("SELECT DUMMY FROM DUAL");
ds.setConnectionInitSqls(Arrays.asList("SELECT 1", "SELECT 2"));
ds.setDriverClassLoader(new TesterClassLoader());
ds.setJmxName("org.apache.commons.dbcp2:name=test");
}
@Override
@AfterEach
public void tearDown() throws Exception {
super.tearDown();
ds.close();
ds = null;
}
@Test
void testAccessToUnderlyingConnectionAllowed() throws Exception {
ds.setAccessToUnderlyingConnectionAllowed(true);
assertTrue(ds.isAccessToUnderlyingConnectionAllowed());
try (final Connection conn = getConnection()) {
Connection dconn = ((DelegatingConnection<?>) conn).getDelegate();
assertNotNull(dconn);
dconn = ((DelegatingConnection<?>) conn).getInnermostDelegate();
assertNotNull(dconn);
assertInstanceOf(TesterConnection.class, dconn);
}
}
@Test
void testClose() throws Exception {
ds.setAccessToUnderlyingConnectionAllowed(true);
// active connection is held open when ds is closed
final Connection activeConnection = getConnection();
final Connection rawActiveConnection = ((DelegatingConnection<?>) activeConnection).getInnermostDelegate();
assertFalse(activeConnection.isClosed());
assertFalse(rawActiveConnection.isClosed());
// idle connection is in pool but closed
final Connection idleConnection = getConnection();
final Connection rawIdleConnection = ((DelegatingConnection<?>) idleConnection).getInnermostDelegate();
assertFalse(idleConnection.isClosed());
assertFalse(rawIdleConnection.isClosed());
// idle wrapper should be closed but raw connection should be open
idleConnection.close();
assertTrue(idleConnection.isClosed());
assertFalse(rawIdleConnection.isClosed());
ds.close();
// raw idle connection should now be closed
assertTrue(rawIdleConnection.isClosed());
// active connection should still be open
assertFalse(activeConnection.isClosed());
assertFalse(rawActiveConnection.isClosed());
// now close the active connection
activeConnection.close();
// both wrapper and raw active connection should be closed
assertTrue(activeConnection.isClosed());
assertTrue(rawActiveConnection.isClosed());
// Verify SQLException on getConnection after close
assertThrows(SQLException.class, this::getConnection);
// Redundant close is OK
ds.close();
}
@Test
void testConcurrentInitBorrow() throws Exception {
ds.setDriverClassName("org.apache.commons.dbcp2.TesterConnectionDelayDriver");
ds.setUrl("jdbc:apache:commons:testerConnectionDelayDriver:50");
ds.setInitialSize(8);
// Launch a request to trigger pool initialization
final TestThread testThread = new TestThread(1, 0);
final Thread t = new Thread(testThread);
t.start();
// Get another connection (should wait for pool init)
Thread.sleep(100); // Make sure t gets into init first
try (Connection conn = ds.getConnection()) {
// Pool should have at least 6 idle connections now
// Use underlying pool getNumIdle to avoid waiting for ds lock
assertTrue(ds.getConnectionPool().getNumIdle() > 5);
// Make sure t completes successfully
t.join();
assertFalse(testThread.failed());
}
ds.close();
}
/**
* JIRA: DBCP-444 Verify that invalidate does not return closed connection to the pool.
*/
@Test
void testConcurrentInvalidateBorrow() throws Exception {
ds.setDriverClassName("org.apache.commons.dbcp2.TesterConnRequestCountDriver");
ds.setUrl("jdbc:apache:commons:testerConnRequestCountDriver");
ds.setTestOnBorrow(true);
ds.setValidationQuery("SELECT DUMMY FROM DUAL");
ds.setMaxTotal(8);
ds.setLifo(true);
ds.setMaxWait(Duration.ofMillis(-1));
// Threads just borrow and return - validation will trigger close check
final TestThread testThread1 = new TestThread(1000, 0);
final Thread t1 = new Thread(testThread1);
t1.start();
final TestThread testThread2 = new TestThread(1000, 0);
final Thread t2 = new Thread(testThread1);
t2.start();
// Grab and invalidate connections
for (int i = 0; i < 1000; i++) {
final Connection conn = ds.getConnection();
ds.invalidateConnection(conn);
}
// Make sure borrow threads complete successfully
t1.join();
t2.join();
assertFalse(testThread1.failed());
assertFalse(testThread2.failed());
ds.close();
}
/**
* Test disabling MBean registration for Connection objects. JIRA: DBCP-585
*/
@Test
void testConnectionMBeansDisabled() throws Exception {
final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
// Unregister leftovers from other tests (TODO: worry about concurrent test execution)
final ObjectName commons = new ObjectName("org.apache.commons.*:*");
final Set<ObjectName> results = mbs.queryNames(commons, null);
for (final ObjectName result : results) {
mbs.unregisterMBean(result);
}
ds.setRegisterConnectionMBean(false); // Should disable Connection MBean registration
try (Connection conn = ds.getConnection()) { // Trigger initialization
// No Connection MBeans shall be registered
final ObjectName connections = new ObjectName("org.apache.commons.*:connection=*,*");
assertEquals(0, mbs.queryNames(connections, null).size());
}
}
/**
* JIRA: DBCP-547 Verify that ConnectionFactory interface in BasicDataSource.createConnectionFactory().
*/
@Test
void testCreateConnectionFactoryWithConnectionFactoryClassName() throws Exception {
Properties properties = new Properties();
// set ConnectionFactoryClassName
properties = new Properties();
properties.put("initialSize", "1");
properties.put("driverClassName", "org.apache.commons.dbcp2.TesterDriver");
properties.put("url", "jdbc:apache:commons:testdriver");
properties.put("username", "foo");
properties.put("password", "bar");
properties.put("connectionFactoryClassName", "org.apache.commons.dbcp2.TesterConnectionFactory");
try (BasicDataSource ds = BasicDataSourceFactory.createDataSource(properties)) {
try (Connection conn = ds.getConnection()) {
assertNotNull(conn);
}
}
}
/**
* JIRA: DBCP-547 Verify that ConnectionFactory interface in BasicDataSource.createConnectionFactory().
*/
@Test
void testCreateConnectionFactoryWithoutConnectionFactoryClassName() throws Exception {
// not set ConnectionFactoryClassName
final Properties properties = new Properties();
properties.put("initialSize", "1");
properties.put("driverClassName", "org.apache.commons.dbcp2.TesterDriver");
properties.put("url", "jdbc:apache:commons:testdriver");
properties.put("username", "foo");
properties.put("password", "bar");
try (BasicDataSource ds = BasicDataSourceFactory.createDataSource(properties)) {
try (Connection conn = ds.getConnection()) {
assertNotNull(conn);
}
}
}
/**
* JIRA: DBCP-342, DBCP-93 Verify that when errors occur during BasicDataSource initialization, GenericObjectPool Evictors are cleaned up.
*/
@Test
void testCreateDataSourceCleanupEvictor() throws Exception {
ds.close();
ds = null;
ds = createDataSource();
ds.setDriverClassName("org.apache.commons.dbcp2.TesterConnRequestCountDriver");
ds.setUrl("jdbc:apache:commons:testerConnRequestCountDriver");
ds.setValidationQuery("SELECT DUMMY FROM DUAL");
ds.setUsername("userName");
// Make password incorrect, so createDataSource will throw
ds.setPassword("wrong");
// Set timeBetweenEvictionRuns > 0, so evictor will be created
ds.setDurationBetweenEvictionRuns(Duration.ofMillis(100));
// Set min idle > 0, so evictor will try to make connection as many as idle count
ds.setMinIdle(2);
// Prevent concurrent execution of threads executing test subclasses
synchronized (TesterConnRequestCountDriver.class) {
TesterConnRequestCountDriver.initConnRequestCount();
// user request 10 times
for (int i = 0; i < 10; i++) {
try {
@SuppressWarnings("unused")
final DataSource ds2 = ds.createDataSource();
} catch (final SQLException e) {
// Ignore
}
}
// sleep 1000ms. evictor will be invoked 10 times if running.
Thread.sleep(1000);
// Make sure there have been no Evictor-generated requests (count should be 10, from requests above)
assertEquals(10, TesterConnRequestCountDriver.getConnectionRequestCount());
}
// make sure cleanup is complete
assertNull(ds.getConnectionPool());
}
/**
* JIRA DBCP-93: If an SQLException occurs after the GenericObjectPool is initialized in createDataSource, the evictor task is not cleaned up.
*/
@Test
void testCreateDataSourceCleanupThreads() throws Exception {
ds.close();
ds = null;
ds = createDataSource();
ds.setDriverClassName("org.apache.commons.dbcp2.TesterDriver");
ds.setUrl("jdbc:apache:commons:testdriver");
ds.setMaxTotal(getMaxTotal());
ds.setMaxWait(getMaxWaitDuration());
ds.setDefaultAutoCommit(Boolean.TRUE);
ds.setDefaultReadOnly(Boolean.FALSE);
ds.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
ds.setDefaultCatalog(CATALOG);
ds.setUsername("userName");
// Set timeBetweenEvictionRuns > 0, so evictor is created
ds.setDurationBetweenEvictionRuns(Duration.ofMillis(100));
// Make password incorrect, so createDataSource will throw
ds.setPassword("wrong");
ds.setValidationQuery("SELECT DUMMY FROM DUAL");
final int threadCount = Thread.activeCount();
for (int i = 0; i < 10; i++) {
try (Connection c = ds.getConnection()) {
} catch (final SQLException ex) {
// ignore
}
}
// Allow one extra thread for JRockit compatibility
assertTrue(Thread.activeCount() <= threadCount + 1);
}
@Test
void testDefaultCatalog() throws Exception {
final Connection[] c = new Connection[getMaxTotal()];
for (int i = 0; i < c.length; i++) {
c[i] = getConnection();
assertNotNull(c[i]);
assertEquals(CATALOG, c[i].getCatalog());
}
for (final Connection element : c) {
element.setCatalog("error");
element.close();
}
for (int i = 0; i < c.length; i++) {
c[i] = getConnection();
assertNotNull(c[i]);
assertEquals(CATALOG, c[i].getCatalog());
}
for (final Connection element : c) {
element.close();
}
}
@Test
void testDeprecatedAccessors() throws SQLException {
try (BasicDataSource bds = new BasicDataSource()) {
int i = 0;
//
i++;
bds.setDefaultQueryTimeout(i);
assertEquals(i, bds.getDefaultQueryTimeout());
assertEquals(Duration.ofSeconds(i), bds.getDefaultQueryTimeoutDuration());
//
i++;
bds.setMaxConnLifetimeMillis(i);
assertEquals(i, bds.getMaxConnLifetimeMillis());
assertEquals(Duration.ofMillis(i), bds.getMaxConnDuration());
//
i++;
bds.setMaxWaitMillis(i);
assertEquals(i, bds.getMaxWaitMillis());
assertEquals(Duration.ofMillis(i), bds.getMaxWaitDuration());
//
i++;
bds.setMinEvictableIdleTimeMillis(i);
assertEquals(i, bds.getMinEvictableIdleTimeMillis());
assertEquals(Duration.ofMillis(i), bds.getMinEvictableIdleDuration());
//
i++;
bds.setRemoveAbandonedTimeout(i);
assertEquals(i, bds.getRemoveAbandonedTimeout());
assertEquals(Duration.ofSeconds(i), bds.getRemoveAbandonedTimeoutDuration());
//
i++;
bds.setSoftMinEvictableIdleTimeMillis(i);
assertEquals(i, bds.getSoftMinEvictableIdleTimeMillis());
assertEquals(Duration.ofMillis(i), bds.getSoftMinEvictableIdleDuration());
//
i++;
bds.setTimeBetweenEvictionRunsMillis(i);
assertEquals(i, bds.getTimeBetweenEvictionRunsMillis());
assertEquals(Duration.ofMillis(i), bds.getDurationBetweenEvictionRuns());
//
i++;
bds.setValidationQueryTimeout(1);
assertEquals(1, bds.getValidationQueryTimeout());
assertEquals(Duration.ofSeconds(1), bds.getValidationQueryTimeoutDuration());
}
}
@Test
void testDisconnectionIgnoreSqlCodes() throws Exception {
final ArrayList<String> disconnectionIgnoreSqlCodes = new ArrayList<>();
disconnectionIgnoreSqlCodes.add("XXXX");
ds.setDisconnectionIgnoreSqlCodes(disconnectionIgnoreSqlCodes);
ds.setFastFailValidation(true);
try (Connection conn = ds.getConnection()) { // Triggers initialization - pcf creation
// Make sure factory got the properties
final PoolableConnectionFactory pcf = (PoolableConnectionFactory) ds.getConnectionPool().getFactory();
assertTrue(pcf.isFastFailValidation());
assertTrue(pcf.getDisconnectionIgnoreSqlCodes().contains("XXXX"));
assertEquals(1, pcf.getDisconnectionIgnoreSqlCodes().size());
}
}
/**
* JIRA: DBCP-437 Verify that BasicDataSource sets disconnect codes properties. Functionality is verified in pcf tests.
*/
@Test
void testDisconnectSqlCodes() throws Exception {
final ArrayList<String> disconnectionSqlCodes = new ArrayList<>();
disconnectionSqlCodes.add("XXX");
ds.setDisconnectionSqlCodes(disconnectionSqlCodes);
ds.setFastFailValidation(true);
try (Connection conn = ds.getConnection()) { // Triggers initialization - pcf creation
// Make sure factory got the properties
final PoolableConnectionFactory pcf = (PoolableConnectionFactory) ds.getConnectionPool().getFactory();
assertTrue(pcf.isFastFailValidation());
assertTrue(pcf.getDisconnectionSqlCodes().contains("XXX"));
assertEquals(1, pcf.getDisconnectionSqlCodes().size());
}
}
/**
* JIRA DBCP-333: Check that a custom class loader is used.
*
* @throws Exception
*/
@Test
void testDriverClassLoader() throws Exception {
try (Connection conn = getConnection()) {
final ClassLoader cl = ds.getDriverClassLoader();
assertNotNull(cl);
assertInstanceOf(TesterClassLoader.class, cl);
assertTrue(((TesterClassLoader) cl).didLoad(ds.getDriverClassName()));
}
}
@Test
void testEmptyInitConnectionSql() throws Exception {
// List
ds.setConnectionInitSqls(Arrays.asList("", " "));
assertNotNull(ds.getConnectionInitSqls());
assertEquals(0, ds.getConnectionInitSqls().size());
// null
ds.setConnectionInitSqls(null);
assertNotNull(ds.getConnectionInitSqls());
assertEquals(0, ds.getConnectionInitSqls().size());
// Collection
ds.setConnectionInitSqls((Collection<String>) Arrays.asList("", " "));
assertNotNull(ds.getConnectionInitSqls());
assertEquals(0, ds.getConnectionInitSqls().size());
}
@Test
void testEmptyValidationQuery() throws Exception {
assertNotNull(ds.getValidationQuery());
ds.setValidationQuery("");
assertNull(ds.getValidationQuery());
ds.setValidationQuery(" ");
assertNull(ds.getValidationQuery());
}
@Test
@Disabled
void testEvict() throws Exception {
final long delay = 1000;
ds.setInitialSize(10);
ds.setMaxIdle(10);
ds.setMaxTotal(10);
ds.setMinIdle(5);
ds.setNumTestsPerEvictionRun(3);
ds.setMinEvictableIdle(Duration.ofMillis(100));
ds.setDurationBetweenEvictionRuns(Duration.ofMillis(delay));
ds.setPoolPreparedStatements(true);
try (Connection conn = ds.getConnection()) {
// empty
}
final ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
while (Stream.of(threadBean.getThreadInfo(threadBean.getAllThreadIds())).anyMatch(t -> t.getThreadName().equals("commons-pool-evictor-thread"))) {
if (ds.getNumIdle() <= ds.getMinIdle()) {
break;
}
Thread.sleep(delay);
}
assertFalse(ds.getNumIdle() > ds.getMinIdle(),
() -> "EvictionTimer thread was destroyed with numIdle=" + ds.getNumIdle() + "(expected: less or equal than " + ds.getMinIdle() + ")");
}
@Test
void testInitialSize() throws Exception {
ds.setMaxTotal(20);
ds.setMaxIdle(20);
ds.setInitialSize(10);
try (Connection conn = getConnection()) {
assertNotNull(conn);
}
assertEquals(0, ds.getNumActive());
assertEquals(10, ds.getNumIdle());
}
/**
* JIRA: DBCP-482 Verify warning not logged if JMX MBean unregistered before close() called.
*/
@Test
void testInstanceNotFoundExceptionLogSuppressed() throws Exception {
final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
try (Connection c = ds.getConnection()) {
// nothing
}
final ObjectName objectName = new ObjectName(ds.getJmxName());
if (mbs.isRegistered(objectName)) {
mbs.unregisterMBean(objectName);
}
StackMessageLog.clear();
ds.close();
assertNull(StackMessageLog.popMessage());
assertNull(ds.getRegisteredJmxName());
}
/**
* Cycle through idle connections and verify that they are all valid.
* Assumes we are the only client of the pool.
*
* @throws Exception if an error occurs
*/
private void checkIdleValid() throws Exception {
final Set<Connection> idleConnections = new HashSet<>(); // idle connections
// Get idle connections by repeatedly making connection requests up to NumIdle
for (int i = 0; i < ds.getNumIdle(); i++) {
final Connection conn = ds.getConnection();
idleConnections.add(conn);
}
// Cycle through idle connections and verify that they are valid
for (final Connection conn : idleConnections) {
assertTrue(conn.isValid(2), "Connection should be valid");
conn.close();
}
}
/**
* Check that maxTotal and maxIdle are not exceeded
*
* @throws Exception
*/
private void checkLimits() throws Exception {
assertTrue(ds.getNumActive() + ds.getNumIdle() <= getMaxTotal(), "Total connections exceed maxTotal");
assertTrue(ds.getNumIdle() <= ds.getMaxIdle(), "Idle connections exceed maxIdle");
}
@Test
void testInvalidateConnection() throws Exception {
ds.setMaxTotal(2);
try (final Connection conn1 = ds.getConnection()) {
try (final Connection conn2 = ds.getConnection()) {
ds.invalidateConnection(conn1);
assertTrue(conn1.isClosed());
assertEquals(1, ds.getNumActive());
checkIdleValid();
checkLimits();
try (final Connection conn3 = ds.getConnection()) {
conn2.close();
conn3.close();
}
}
}
}
@Test
void testInvalidConnectionInitSqlCollection() {
ds.setConnectionInitSqls((Collection<String>) Arrays.asList("SELECT 1", "invalid"));
final SQLException e = assertThrows(SQLException.class, ds::getConnection);
assertTrue(e.toString().contains("invalid"));
}
@Test
void testInvalidConnectionInitSqlList() {
ds.setConnectionInitSqls(Arrays.asList("SELECT 1", "invalid"));
final SQLException e = assertThrows(SQLException.class, ds::getConnection);
assertTrue(e.toString().contains("invalid"));
}
@Test
void testInvalidValidationQuery() {
ds.setValidationQuery("invalid");
final SQLException e = assertThrows(SQLException.class, ds::getConnection);
assertTrue(e.toString().contains("invalid"));
}
// Bugzilla Bug 28251: Returning dead database connections to BasicDataSource
// isClosed() failure blocks returning a connection to the pool
@Test
void testIsClosedFailure() throws SQLException {
ds.setAccessToUnderlyingConnectionAllowed(true);
final Connection conn = ds.getConnection();
assertNotNull(conn);
assertEquals(1, ds.getNumActive());
// set an IO failure causing the isClosed method to fail
final TesterConnection tconn = (TesterConnection) ((DelegatingConnection<?>) conn).getInnermostDelegate();
tconn.setFailure(new IOException("network error"));
assertThrows(SQLException.class, () -> conn.close());
assertEquals(0, ds.getNumActive());
}
@Test
void testIsWrapperFor() throws Exception {
assertTrue(ds.isWrapperFor(BasicDataSource.class));
assertTrue(ds.isWrapperFor(AutoCloseable.class));
assertFalse(ds.isWrapperFor(String.class));
assertFalse(ds.isWrapperFor(null));
}
/**
* Make sure setting jmxName to null suppresses JMX registration of connection and statement pools. JIRA: DBCP-434
*/
@Test
void testJmxDisabled() throws Exception {
final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
// Unregister leftovers from other tests (TODO: worry about concurrent test execution)
final ObjectName commons = new ObjectName("org.apache.commons.*:*");
final Set<ObjectName> results = mbs.queryNames(commons, null);
for (final ObjectName result : results) {
mbs.unregisterMBean(result);
}
ds.setJmxName(null); // Should disable JMX for both connection and statement pools
ds.setPoolPreparedStatements(true);
try (Connection conn = ds.getConnection()) { // Trigger initialization
// Nothing should be registered
assertEquals(0, mbs.queryNames(commons, null).size());
}
}
/**
* Tests JIRA <a href="https://issues.apache.org/jira/browse/DBCP-562">DBCP-562</a>.
* <p>
* Make sure Password Attribute is not exported via JMXBean.
* </p>
*/
@Test
void testJmxDoesNotExposePassword() throws Exception {
final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
try (Connection c = ds.getConnection()) {
// nothing
}
final ObjectName objectName = new ObjectName(ds.getJmxName());
final MBeanAttributeInfo[] attributes = mbs.getMBeanInfo(objectName).getAttributes();
assertTrue(attributes != null && attributes.length > 0);
Arrays.asList(attributes).forEach(attrInfo -> assertFalse("password".equalsIgnoreCase(attrInfo.getName())));
assertThrows(AttributeNotFoundException.class, () -> mbs.getAttribute(objectName, "Password"));
}
@Test
void testManualConnectionEvict() throws Exception {
ds.setMinIdle(0);
ds.setMaxIdle(4);
ds.setMinEvictableIdle(Duration.ofMillis(10));
ds.setNumTestsPerEvictionRun(2);
try (Connection ds2 = ds.createDataSource().getConnection(); Connection ds3 = ds.createDataSource().getConnection()) {
assertEquals(0, ds.getNumIdle());
}
// Make sure MinEvictableIdleTimeMillis has elapsed
Thread.sleep(100);
// Ensure no connections evicted by eviction thread
assertEquals(2, ds.getNumIdle());
// Force Eviction
ds.evict();
// Ensure all connections evicted
assertEquals(0, ds.getNumIdle());
}
@Test
void testMaxConnLifetimeExceeded() throws Exception {
try {
StackMessageLog.lock();
ds.setMaxConn(Duration.ofMillis(100));
try (Connection conn = ds.getConnection()) {
assertEquals(1, ds.getNumActive());
Thread.sleep(500);
}
assertEquals(0, ds.getNumIdle());
final String message = StackMessageLog.popMessage();
Assertions.assertNotNull(message);
assertTrue(message.indexOf("exceeds the maximum permitted value") > 0);
} finally {
StackMessageLog.clear();
StackMessageLog.unLock();
}
}
@Test
void testMaxConnLifetimeExceededMutedLog() throws Exception {
try {
StackMessageLog.lock();
StackMessageLog.clear();
ds.setMaxConn(Duration.ofMillis(100));
ds.setLogExpiredConnections(false);
try (final Connection conn = ds.getConnection()) {
assertEquals(1, ds.getNumActive());
Thread.sleep(500);
}
assertEquals(0, ds.getNumIdle());
assertTrue(StackMessageLog.isEmpty(), StackMessageLog.getAll().toString());
} finally {
StackMessageLog.clear();
StackMessageLog.unLock();
}
}
/**
* Bugzilla Bug 29832: Broken behavior for BasicDataSource.setMaxTotal(0) MaxTotal == 0 should throw SQLException on getConnection. Results from Bug 29863
* in commons-pool.
*/
@Test
void testMaxTotalZero() throws Exception {
ds.setMaxTotal(0);
assertThrows(SQLException.class, ds::getConnection);
}
/**
* JIRA: DBCP-457 Verify that changes made to abandoned config are passed to the underlying pool.
*/
@Test
void testMutateAbandonedConfig() throws Exception {
final Properties properties = new Properties();
properties.put("initialSize", "1");
properties.put("driverClassName", "org.apache.commons.dbcp2.TesterDriver");
properties.put("url", "jdbc:apache:commons:testdriver");
properties.put("username", "foo");
properties.put("password", "bar");
try (BasicDataSource ds = BasicDataSourceFactory.createDataSource(properties)) {
final boolean original = ds.getConnectionPool().getLogAbandoned();
ds.setLogAbandoned(!original);
Assertions.assertNotEquals(original, ds.getConnectionPool().getLogAbandoned());
}
}
@Test
void testNoAccessToUnderlyingConnectionAllowed() throws Exception {
// default: false
assertFalse(ds.isAccessToUnderlyingConnectionAllowed());
try (Connection conn = getConnection()) {
Connection dconn = ((DelegatingConnection<?>) conn).getDelegate();
assertNull(dconn);
dconn = ((DelegatingConnection<?>) conn).getInnermostDelegate();
assertNull(dconn);
}
}
@Test
void testNoOverlapBetweenDisconnectionAndIgnoreSqlCodes() {
// Set disconnection SQL codes without overlap
final HashSet<String> disconnectionSqlCodes = new HashSet<>(Arrays.asList("XXX", "ZZZ"));
ds.setDisconnectionSqlCodes(disconnectionSqlCodes);
// Set ignore SQL codes without overlap
final HashSet<String> disconnectionIgnoreSqlCodes = new HashSet<>(Arrays.asList("YYY", "AAA"));
ds.setDisconnectionIgnoreSqlCodes(disconnectionIgnoreSqlCodes);
assertEquals(disconnectionSqlCodes, ds.getDisconnectionSqlCodes(), "Disconnection SQL codes should match the set values.");
assertEquals(disconnectionIgnoreSqlCodes, ds.getDisconnectionIgnoreSqlCodes(), "Disconnection Ignore SQL codes should match the set values.");
}
@Test
void testOverlapBetweenDisconnectionAndIgnoreSqlCodes() {
// Set initial disconnection SQL codes
final HashSet<String> disconnectionSqlCodes = new HashSet<>(Arrays.asList("XXX", "ZZZ"));
ds.setDisconnectionSqlCodes(disconnectionSqlCodes);
// Try setting ignore SQL codes with overlap
final HashSet<String> disconnectionIgnoreSqlCodes = new HashSet<>(Arrays.asList("YYY", "XXX"));
final IllegalArgumentException exception = assertThrows(IllegalArgumentException.class,
() -> ds.setDisconnectionIgnoreSqlCodes(disconnectionIgnoreSqlCodes));
assertEquals("[XXX] cannot be in both disconnectionSqlCodes and disconnectionIgnoreSqlCodes.", exception.getMessage());
}
/**
* Verifies correct handling of exceptions generated by the underlying pool as it closes connections in response to BDS#close. Exceptions have to be either
* swallowed by the underlying pool and logged, or propagated and wrapped.
*/
@Test
void testPoolCloseCheckedException() throws Exception {
ds.setAccessToUnderlyingConnectionAllowed(true); // Allow dirty tricks
final TesterConnection tc;
// Get an idle connection into the pool
try (Connection conn = ds.getConnection()) {
tc = (TesterConnection) ((DelegatingConnection<?>) conn).getInnermostDelegate();
}
// After returning the connection to the pool, bork it.
// Don't try this at home - bad violation of pool contract!
tc.setFailure(new SQLException("bang"));
// Now close Datasource, which will cause tc to be closed, triggering SQLE
// Pool 2.x swallows and logs exceptions on pool close. Below verifies that
// Either exceptions get logged or wrapped appropriately.
try {
StackMessageLog.lock();
StackMessageLog.clear();
ds.close();
// Exception must have been swallowed by the pool - verify it is logged
final String message = StackMessageLog.popMessage();
Assertions.assertNotNull(message);
assertTrue(message.indexOf("bang") > 0);
} catch (final SQLException ex) {
assertTrue(ex.getMessage().indexOf("Cannot close") > 0);
assertTrue(ex.getCause().getMessage().indexOf("bang") > 0);
} finally {
StackMessageLog.unLock();
}
}
@Test
void testPoolCloseRTE() throws Exception {
// RTE version of testPoolCloseCheckedException - see comments there.
ds.setAccessToUnderlyingConnectionAllowed(true);
final TesterConnection tc;
try (Connection conn = ds.getConnection()) {
tc = (TesterConnection) ((DelegatingConnection<?>) conn).getInnermostDelegate();
}
tc.setFailure(new IllegalStateException("boom"));
try {
StackMessageLog.lock();
StackMessageLog.clear();
ds.close();
final String message = StackMessageLog.popMessage();
Assertions.assertNotNull(message);
assertTrue(message.indexOf("boom") > 0);
} catch (final IllegalStateException ex) {
assertTrue(ex.getMessage().indexOf("boom") > 0); // RTE is not wrapped by BDS#close
} finally {
StackMessageLog.unLock();
}
}
@Override
@Test
public void testPooling() throws Exception {
// this also needs access to the underlying connection
ds.setAccessToUnderlyingConnectionAllowed(true);
super.testPooling();
}
/**
* Bugzilla Bug 29054: The BasicDataSource.setTestOnReturn(boolean) is not carried through to the GenericObjectPool variable _testOnReturn.
*/
@Test
void testPropertyTestOnReturn() throws Exception {
ds.setValidationQuery("select 1 from dual");
ds.setTestOnBorrow(false);
ds.setTestWhileIdle(false);
ds.setTestOnReturn(true);
try (Connection conn = ds.getConnection()) {
assertNotNull(conn);
assertFalse(ds.getConnectionPool().getTestOnBorrow());
assertFalse(ds.getConnectionPool().getTestWhileIdle());
assertTrue(ds.getConnectionPool().getTestOnReturn());
}
}
@Test
void testRestart() throws Exception {
ds.setMaxTotal(2);
ds.setDurationBetweenEvictionRuns(Duration.ofMillis(100));
ds.setNumTestsPerEvictionRun(2);
ds.setMinEvictableIdle(Duration.ofMinutes(1));
ds.setInitialSize(2);
ds.setDefaultCatalog("foo");
try (Connection conn1 = ds.getConnection()) {
Thread.sleep(200);
// Now set some property that will not have effect until restart
ds.setDefaultCatalog("bar");
ds.setInitialSize(1);
// restart will load new properties
ds.restart();
assertEquals("bar", ds.getDefaultCatalog());
assertEquals(1, ds.getInitialSize());
ds.getLogWriter(); // side effect is to init
assertEquals(0, ds.getNumActive());
assertEquals(1, ds.getNumIdle());
}
// verify old pool connection is not returned to pool
assertEquals(1, ds.getNumIdle());
ds.close();
}
/**
* Bugzilla Bug 29055: AutoCommit and ReadOnly The DaffodilDB driver throws an SQLException if trying to commit or rollback a readOnly connection.
*/
@Test
void testRollbackReadOnly() throws Exception {
ds.setDefaultReadOnly(Boolean.TRUE);
ds.setDefaultAutoCommit(Boolean.FALSE);
try (Connection conn = ds.getConnection()) {
assertNotNull(conn);
}
}
@Test
void testSetAutoCommitTrueOnClose() throws Exception {
ds.setAccessToUnderlyingConnectionAllowed(true);
ds.setDefaultAutoCommit(Boolean.FALSE);
final Connection dconn;
try (Connection conn = getConnection()) {
assertNotNull(conn);
assertFalse(conn.getAutoCommit());
dconn = ((DelegatingConnection<?>) conn).getInnermostDelegate();
assertNotNull(dconn);
assertFalse(dconn.getAutoCommit());
}
assertTrue(dconn.getAutoCommit());
}
@Test
void testSetProperties() throws Exception {
// normal
ds.setConnectionProperties("name1=value1;name2=value2;name3=value3");
assertEquals(3, ds.getConnectionProperties().size());
assertEquals("value1", ds.getConnectionProperties().getProperty("name1"));
assertEquals("value2", ds.getConnectionProperties().getProperty("name2"));
assertEquals("value3", ds.getConnectionProperties().getProperty("name3"));
// make sure all properties are replaced
ds.setConnectionProperties("name1=value1;name2=value2");
assertEquals(2, ds.getConnectionProperties().size());
assertEquals("value1", ds.getConnectionProperties().getProperty("name1"));
assertEquals("value2", ds.getConnectionProperties().getProperty("name2"));
assertFalse(ds.getConnectionProperties().containsKey("name3"));
// no value is empty string
ds.setConnectionProperties("name1=value1;name2");
assertEquals(2, ds.getConnectionProperties().size());
assertEquals("value1", ds.getConnectionProperties().getProperty("name1"));