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 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270
|
/*
* 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
*
* http://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;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.lang.management.ManagementFactory;
import java.nio.charset.StandardCharsets;
import java.security.AccessController;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
import java.util.logging.Logger;
import javax.management.InstanceAlreadyExistsException;
import javax.management.JMException;
import javax.management.MBeanRegistration;
import javax.management.MBeanRegistrationException;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.NotCompliantMBeanException;
import javax.management.ObjectName;
import javax.sql.DataSource;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.apache.tomcat.dbcp.pool2.PooledObject;
import org.apache.tomcat.dbcp.pool2.impl.AbandonedConfig;
import org.apache.tomcat.dbcp.pool2.impl.BaseObjectPoolConfig;
import org.apache.tomcat.dbcp.pool2.impl.GenericKeyedObjectPoolConfig;
import org.apache.tomcat.dbcp.pool2.impl.GenericObjectPool;
import org.apache.tomcat.dbcp.pool2.impl.GenericObjectPoolConfig;
/**
* <p>Basic implementation of <code>javax.sql.DataSource</code> that is
* configured via JavaBeans properties. This is not the only way to
* combine the <em>commons-dbcp</em> and <em>commons-pool</em> packages,
* but provides a "one stop shopping" solution for basic requirements.</p>
*
* @author Glenn L. Nielsen
* @author Craig R. McClanahan
* @author Dirk Verbeeck
* @since 2.0
*/
public class BasicDataSource implements DataSource, BasicDataSourceMXBean, MBeanRegistration {
private static final Log log = LogFactory.getLog(BasicDataSource.class);
static {
// Attempt to prevent deadlocks - see DBCP - 272
DriverManager.getDrivers();
try {
// Load classes now to prevent AccessControlExceptions later
// A number of classes are loaded when getConnection() is called
// but the following classes are not loaded and therefore require
// explicit loading.
if (Utils.IS_SECURITY_ENABLED) {
ClassLoader loader = BasicDataSource.class.getClassLoader();
String dbcpPackageName = BasicDataSource.class.getPackage().getName();
loader.loadClass(dbcpPackageName + ".BasicDataSource$PaGetConnection");
loader.loadClass(dbcpPackageName + ".DelegatingCallableStatement");
loader.loadClass(dbcpPackageName + ".DelegatingDatabaseMetaData");
loader.loadClass(dbcpPackageName + ".DelegatingPreparedStatement");
loader.loadClass(dbcpPackageName + ".DelegatingResultSet");
loader.loadClass(dbcpPackageName + ".PoolableCallableStatement");
loader.loadClass(dbcpPackageName + ".PoolablePreparedStatement");
loader.loadClass(dbcpPackageName + ".PoolingConnection$StatementType");
loader.loadClass(dbcpPackageName + ".PStmtKey");
String poolPackageName = PooledObject.class.getPackage().getName();
loader.loadClass(poolPackageName + ".impl.LinkedBlockingDeque$Node");
loader.loadClass(poolPackageName + ".impl.GenericKeyedObjectPool$ObjectDeque");
}
} catch (ClassNotFoundException cnfe) {
throw new IllegalStateException("Unable to pre-load classes", cnfe);
}
}
// ------------------------------------------------------------- Properties
/**
* The default auto-commit state of connections created by this pool.
*/
private volatile Boolean defaultAutoCommit = null;
/**
* Returns the default auto-commit property.
*
* @return true if default auto-commit is enabled
*/
@Override
public Boolean getDefaultAutoCommit() {
return defaultAutoCommit;
}
/**
* <p>Sets default auto-commit state of connections returned by this
* datasource.</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: <code>getConnection, setLogwriter,
* setLoginTimeout, getLoginTimeout, getLogWriter.</code></p>
*
* @param defaultAutoCommit default auto-commit value
*/
public void setDefaultAutoCommit(Boolean defaultAutoCommit) {
this.defaultAutoCommit = defaultAutoCommit;
}
/**
* The default read-only state of connections created by this pool.
*/
private transient Boolean defaultReadOnly = null;
/**
* Returns the default readOnly property.
*
* @return true if connections are readOnly by default
*/
@Override
public Boolean getDefaultReadOnly() {
return defaultReadOnly;
}
/**
* <p>Sets defaultReadonly property.</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: <code>getConnection, setLogwriter,
* setLoginTimeout, getLoginTimeout, getLogWriter.</code></p>
*
* @param defaultReadOnly default read-only value
*/
public void setDefaultReadOnly(Boolean defaultReadOnly) {
this.defaultReadOnly = defaultReadOnly;
}
/**
* The default TransactionIsolation state of connections created by this pool.
*/
private volatile int defaultTransactionIsolation =
PoolableConnectionFactory.UNKNOWN_TRANSACTIONISOLATION;
/**
* Returns the default transaction isolation state of returned connections.
*
* @return the default value for transaction isolation state
* @see Connection#getTransactionIsolation
*/
@Override
public int getDefaultTransactionIsolation() {
return this.defaultTransactionIsolation;
}
/**
* <p>Sets the default transaction isolation state for returned
* connections.</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: <code>getConnection, setLogwriter,
* setLoginTimeout, getLoginTimeout, getLogWriter.</code></p>
*
* @param defaultTransactionIsolation the default transaction isolation
* state
* @see Connection#getTransactionIsolation
*/
public void setDefaultTransactionIsolation(int defaultTransactionIsolation) {
this.defaultTransactionIsolation = defaultTransactionIsolation;
}
private Integer defaultQueryTimeout = null;
/**
* Obtain the default query timeout that will be used for {@link java.sql.Statement Statement}s
* created from this connection. <code>null</code> means that the driver
* default will be used.
*/
public Integer getDefaultQueryTimeout() {
return defaultQueryTimeout;
}
/**
* Set the default query timeout that will be used for {@link java.sql.Statement Statement}s
* created from this connection. <code>null</code> means that the driver
* default will be used.
*/
public void setDefaultQueryTimeout(Integer defaultQueryTimeout) {
this.defaultQueryTimeout = defaultQueryTimeout;
}
/**
* The default "catalog" of connections created by this pool.
*/
private volatile String defaultCatalog = null;
/**
* Returns the default catalog.
*
* @return the default catalog
*/
@Override
public String getDefaultCatalog() {
return this.defaultCatalog;
}
/**
* <p>Sets the default catalog.</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: <code>getConnection, setLogwriter,
* setLoginTimeout, getLoginTimeout, getLogWriter.</code></p>
*
* @param defaultCatalog the default catalog
*/
public void setDefaultCatalog(String defaultCatalog) {
if (defaultCatalog != null && defaultCatalog.trim().length() > 0) {
this.defaultCatalog = defaultCatalog;
}
else {
this.defaultCatalog = null;
}
}
/**
* The property that controls if the pooled connections cache some state
* rather than query the database for current state to improve performance.
*/
private boolean cacheState = true;
/**
* Returns the state caching flag.
*
* @return the state caching flag
*/
@Override
public boolean getCacheState() {
return cacheState;
}
/**
* Sets the state caching flag.
*
* @param cacheState The new value for the state caching flag
*/
public void setCacheState(boolean cacheState) {
this.cacheState = cacheState;
}
/**
* The instance of the JDBC Driver to use.
*/
private Driver driver = null;
/**
* Returns the JDBC Driver that has been configured for use by this pool.
* <p>
* Note: This getter only returns the last value set by a call to
* {@link #setDriver(Driver)}. It does not return any driver instance that
* may have been created from the value set via
* {@link #setDriverClassName(String)}.
*
* @return the JDBC Driver that has been configured for use by this pool
*/
public synchronized Driver getDriver() {
return driver;
}
/**
* Sets the JDBC Driver instance to use for this pool.
* <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: <code>getConnection, setLogwriter,
* setLoginTimeout, getLoginTimeout, getLogWriter.</code></p>
*
* @param driver
*/
public synchronized void setDriver(Driver driver) {
this.driver = driver;
}
/**
* The fully qualified Java class name of the JDBC driver to be used.
*/
private String driverClassName = null;
/**
* Returns the jdbc driver class name.
* <p>
* Note: This getter only returns the last value set by a call to
* {@link #setDriverClassName(String)}. It does not return the class name of
* any driver that may have been set via {@link #setDriver(Driver)}.
*
* @return the jdbc driver class name
*/
@Override
public synchronized String getDriverClassName() {
return this.driverClassName;
}
/**
* <p>Sets the jdbc driver class name.</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: <code>getConnection, setLogwriter,
* setLoginTimeout, getLoginTimeout, getLogWriter.</code></p>
*
* @param driverClassName the class name of the jdbc driver
*/
public synchronized void setDriverClassName(String driverClassName) {
if (driverClassName != null && driverClassName.trim().length() > 0) {
this.driverClassName = driverClassName;
}
else {
this.driverClassName = null;
}
}
/**
* The class loader instance to use to load the JDBC driver. If not
* specified, {@link Class#forName(String)} is used to load the JDBC driver.
* If specified, {@link Class#forName(String, boolean, ClassLoader)} is
* used.
*/
private ClassLoader driverClassLoader = null;
/**
* Returns the class loader specified for loading the JDBC driver. Returns
* <code>null</code> if no class loader has been explicitly specified.
* <p>
* Note: This getter only returns the last value set by a call to
* {@link #setDriverClassLoader(ClassLoader)}. It does not return the class
* loader of any driver that may have been set via
* {@link #setDriver(Driver)}.
*/
public synchronized ClassLoader getDriverClassLoader() {
return this.driverClassLoader;
}
/**
* <p>Sets the class loader to be used to load the JDBC driver.</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: <code>getConnection, setLogwriter,
* setLoginTimeout, getLoginTimeout, getLogWriter.</code></p>
*
* @param driverClassLoader the class loader with which to load the JDBC
* driver
*/
public synchronized void setDriverClassLoader(
ClassLoader driverClassLoader) {
this.driverClassLoader = driverClassLoader;
}
/**
* True means that borrowObject returns the most recently used ("last in")
* connection in the pool (if there are idle connections available). False
* means that the pool behaves as a FIFO queue - connections are taken from
* the idle instance pool in the order that they are returned to the pool.
*/
private boolean lifo = BaseObjectPoolConfig.DEFAULT_LIFO;
/**
* Returns the LIFO property.
*
* @return true if connection pool behaves as a LIFO queue.
*/
@Override
public synchronized boolean getLifo() {
return this.lifo;
}
/**
* Sets the LIFO property. True means the pool behaves as a LIFO queue;
* false means FIFO.
*
* @param lifo the new value for the LIFO property
*
*/
public synchronized void setLifo(boolean lifo) {
this.lifo = lifo;
if (connectionPool != null) {
connectionPool.setLifo(lifo);
}
}
/**
* The maximum number of active connections that can be allocated from
* this pool at the same time, or negative for no limit.
*/
private int maxTotal = GenericObjectPoolConfig.DEFAULT_MAX_TOTAL;
/**
* <p>Returns the maximum number of active connections that can be
* allocated at the same time.
* </p>
* <p>A negative number means that there is no limit.</p>
*
* @return the maximum number of active connections
*/
@Override
public synchronized int getMaxTotal() {
return this.maxTotal;
}
/**
* Sets the maximum total number of idle and borrows connections that can be
* active at the same time. Use a negative value for no limit.
*
* @param maxTotal the new value for maxTotal
* @see #getMaxTotal()
*/
public synchronized void setMaxTotal(int maxTotal) {
this.maxTotal = maxTotal;
if (connectionPool != null) {
connectionPool.setMaxTotal(maxTotal);
}
}
/**
* The maximum number of connections that can remain idle in the
* pool, without extra ones being destroyed, or negative for no limit.
* If maxIdle is set too low on heavily loaded systems it is possible you
* will see connections being closed and almost immediately new connections
* being opened. This is a result of the active threads momentarily closing
* connections faster than they are opening them, causing the number of idle
* connections to rise above maxIdle. The best value for maxIdle for heavily
* loaded system will vary but the default is a good starting point.
*/
private int maxIdle = GenericObjectPoolConfig.DEFAULT_MAX_IDLE;
/**
* <p>Returns the maximum number of connections that can remain idle in the
* pool. Excess idle connections are destroyed on return to the pool.
* </p>
* <p>A negative value indicates that there is no limit</p>
*
* @return the maximum number of idle connections
*/
@Override
public synchronized int getMaxIdle() {
return this.maxIdle;
}
/**
* Sets the maximum number of connections that can remain idle in the
* pool. Excess idle connections are destroyed on return to the pool.
*
* @see #getMaxIdle()
* @param maxIdle the new value for maxIdle
*/
public synchronized void setMaxIdle(int maxIdle) {
this.maxIdle = maxIdle;
if (connectionPool != null) {
connectionPool.setMaxIdle(maxIdle);
}
}
/**
* The minimum number of active connections that can remain idle in the
* pool, without extra ones being created when the evictor runs, or 0 to create none.
* The pool attempts to ensure that minIdle connections are available when the idle object evictor
* runs. The value of this property has no effect unless {@link #timeBetweenEvictionRunsMillis}
* has a positive value.
*/
private int minIdle = GenericObjectPoolConfig.DEFAULT_MIN_IDLE;
/**
* Returns the minimum number of idle connections in the pool. The pool attempts
* to ensure that minIdle connections are available when the idle object evictor
* runs. The value of this property has no effect unless {@link #timeBetweenEvictionRunsMillis}
* has a positive value.
*
* @return the minimum number of idle connections
* @see GenericObjectPool#getMinIdle()
*/
@Override
public synchronized int getMinIdle() {
return this.minIdle;
}
/**
* Sets the minimum number of idle connections in the pool. The pool attempts
* to ensure that minIdle connections are available when the idle object evictor
* runs. The value of this property has no effect unless {@link #timeBetweenEvictionRunsMillis}
* has a positive value.
*
* @param minIdle the new value for minIdle
* @see GenericObjectPool#setMinIdle(int)
*/
public synchronized void setMinIdle(int minIdle) {
this.minIdle = minIdle;
if (connectionPool != null) {
connectionPool.setMinIdle(minIdle);
}
}
/**
* The initial number of connections that are created when the pool
* is started.
*/
private int initialSize = 0;
/**
* Returns the initial size of the connection pool.
*
* @return the number of connections created when the pool is initialized
*/
@Override
public synchronized int getInitialSize() {
return this.initialSize;
}
/**
* <p>Sets the initial size of the connection pool.</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: <code>getConnection, setLogwriter,
* setLoginTimeout, getLoginTimeout, getLogWriter.</code></p>
*
* @param initialSize the number of connections created when the pool
* is initialized
*/
public synchronized void setInitialSize(int initialSize) {
this.initialSize = initialSize;
}
/**
* The maximum number of milliseconds that the pool will wait (when there
* are no available connections) for a connection to be returned before
* throwing an exception, or <= 0 to wait indefinitely.
*/
private long maxWaitMillis =
BaseObjectPoolConfig.DEFAULT_MAX_WAIT_MILLIS;
/**
* Returns the maximum number of milliseconds that the pool will wait
* for a connection to be returned before throwing an exception. A value
* less than or equal to zero means the pool is set to wait indefinitely.
*
* @return the maxWaitMillis property value
*/
@Override
public synchronized long getMaxWaitMillis() {
return this.maxWaitMillis;
}
/**
* Sets the MaxWaitMillis property. Use -1 to make the pool wait
* indefinitely.
*
* @param maxWaitMillis the new value for MaxWaitMillis
* @see #getMaxWaitMillis()
*/
public synchronized void setMaxWaitMillis(long maxWaitMillis) {
this.maxWaitMillis = maxWaitMillis;
if (connectionPool != null) {
connectionPool.setMaxWaitMillis(maxWaitMillis);
}
}
/**
* Prepared statement pooling for this pool. When this property is set to <code>true</code>
* both PreparedStatements and CallableStatements are pooled.
*/
private boolean poolPreparedStatements = false;
/**
* Returns true if we are pooling statements.
*
* @return true if prepared and callable statements are pooled
*/
@Override
public synchronized boolean isPoolPreparedStatements() {
return this.poolPreparedStatements;
}
/**
* <p>Sets whether to pool statements or not.</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: <code>getConnection, setLogwriter,
* setLoginTimeout, getLoginTimeout, getLogWriter.</code></p>
*
* @param poolingStatements pooling on or off
*/
public synchronized void setPoolPreparedStatements(boolean poolingStatements) {
this.poolPreparedStatements = poolingStatements;
}
/**
* <p>The maximum number of open statements that can be allocated from
* the statement pool at the same time, or negative for no limit. Since
* a connection usually only uses one or two statements at a time, this is
* mostly used to help detect resource leaks.</p>
*
* <p>Note: As of version 1.3, CallableStatements (those produced by {@link Connection#prepareCall})
* are pooled along with PreparedStatements (produced by {@link Connection#prepareStatement})
* and <code>maxOpenPreparedStatements</code> limits the total number of prepared or callable statements
* that may be in use at a given time.</p>
*/
private int maxOpenPreparedStatements =
GenericKeyedObjectPoolConfig.DEFAULT_MAX_TOTAL;
/**
* Gets the value of the <code>maxOpenPreparedStatements</code> property.
*
* @return the maximum number of open statements
*/
@Override
public synchronized int getMaxOpenPreparedStatements() {
return this.maxOpenPreparedStatements;
}
/**
* <p>Sets the value of the <code>maxOpenPreparedStatements</code>
* property.</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: <code>getConnection, setLogwriter,
* setLoginTimeout, getLoginTimeout, getLogWriter.</code></p>
*
* @param maxOpenStatements the new maximum number of prepared statements
*/
public synchronized void setMaxOpenPreparedStatements(int maxOpenStatements) {
this.maxOpenPreparedStatements = maxOpenStatements;
}
/**
* The indication of whether objects will be validated as soon as they have
* been created by the pool. If the object fails to validate, the borrow
* operation that triggered the creation will fail.
*/
private boolean testOnCreate = false;
/**
* Returns the {@link #testOnCreate} property.
*
* @return true if objects are validated immediately after they are created
* by the pool
*
* @see #testOnCreate
*/
@Override
public synchronized boolean getTestOnCreate() {
return this.testOnCreate;
}
/**
* Sets the {@link #testOnCreate} property. This property determines
* whether or not the pool will validate objects immediately after they are
* created by the pool
*
* @param testOnCreate new value for testOnCreate property
*/
public synchronized void setTestOnCreate(boolean testOnCreate) {
this.testOnCreate = testOnCreate;
if (connectionPool != null) {
connectionPool.setTestOnCreate(testOnCreate);
}
}
/**
* The indication of whether objects will be validated before being
* borrowed from the pool. If the object fails to validate, it will be
* dropped from the pool, and we will attempt to borrow another.
*/
private boolean testOnBorrow = true;
/**
* Returns the {@link #testOnBorrow} property.
*
* @return true if objects are validated before being borrowed from the
* pool
*
* @see #testOnBorrow
*/
@Override
public synchronized boolean getTestOnBorrow() {
return this.testOnBorrow;
}
/**
* Sets the {@link #testOnBorrow} property. This property determines
* whether or not the pool will validate objects before they are borrowed
* from the pool.
*
* @param testOnBorrow new value for testOnBorrow property
*/
public synchronized void setTestOnBorrow(boolean testOnBorrow) {
this.testOnBorrow = testOnBorrow;
if (connectionPool != null) {
connectionPool.setTestOnBorrow(testOnBorrow);
}
}
/**
* The indication of whether objects will be validated before being
* returned to the pool.
*/
private boolean testOnReturn = false;
/**
* Returns the value of the {@link #testOnReturn} property.
*
* @return true if objects are validated before being returned to the
* pool
* @see #testOnReturn
*/
public synchronized boolean getTestOnReturn() {
return this.testOnReturn;
}
/**
* Sets the <code>testOnReturn</code> property. This property determines
* whether or not the pool will validate objects before they are returned
* to the pool.
*
* @param testOnReturn new value for testOnReturn property
*/
public synchronized void setTestOnReturn(boolean testOnReturn) {
this.testOnReturn = testOnReturn;
if (connectionPool != null) {
connectionPool.setTestOnReturn(testOnReturn);
}
}
/**
* The number of milliseconds to sleep between runs of the idle object
* evictor thread. When non-positive, no idle object evictor thread will
* be run.
*/
private long timeBetweenEvictionRunsMillis =
BaseObjectPoolConfig.DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS;
/**
* Returns the value of the {@link #timeBetweenEvictionRunsMillis}
* property.
*
* @return the time (in milliseconds) between evictor runs
* @see #timeBetweenEvictionRunsMillis
*/
@Override
public synchronized long getTimeBetweenEvictionRunsMillis() {
return this.timeBetweenEvictionRunsMillis;
}
/**
* Sets the {@link #timeBetweenEvictionRunsMillis} property.
*
* @param timeBetweenEvictionRunsMillis the new time between evictor runs
* @see #timeBetweenEvictionRunsMillis
*/
public synchronized void setTimeBetweenEvictionRunsMillis(long timeBetweenEvictionRunsMillis) {
this.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis;
if (connectionPool != null) {
connectionPool.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
}
}
/**
* The number of objects to examine during each run of the idle object
* evictor thread (if any).
*/
private int numTestsPerEvictionRun =
BaseObjectPoolConfig.DEFAULT_NUM_TESTS_PER_EVICTION_RUN;
/**
* Returns the value of the {@link #numTestsPerEvictionRun} property.
*
* @return the number of objects to examine during idle object evictor
* runs
* @see #numTestsPerEvictionRun
*/
@Override
public synchronized int getNumTestsPerEvictionRun() {
return this.numTestsPerEvictionRun;
}
/**
* Sets the value of the {@link #numTestsPerEvictionRun} property.
*
* @param numTestsPerEvictionRun the new {@link #numTestsPerEvictionRun}
* value
* @see #numTestsPerEvictionRun
*/
public synchronized void setNumTestsPerEvictionRun(int numTestsPerEvictionRun) {
this.numTestsPerEvictionRun = numTestsPerEvictionRun;
if (connectionPool != null) {
connectionPool.setNumTestsPerEvictionRun(numTestsPerEvictionRun);
}
}
/**
* The minimum amount of time an object may sit idle in the pool before it
* is eligible for eviction by the idle object evictor (if any).
*/
private long minEvictableIdleTimeMillis =
BaseObjectPoolConfig.DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS;
/**
* Returns the {@link #minEvictableIdleTimeMillis} property.
*
* @return the value of the {@link #minEvictableIdleTimeMillis} property
* @see #minEvictableIdleTimeMillis
*/
@Override
public synchronized long getMinEvictableIdleTimeMillis() {
return this.minEvictableIdleTimeMillis;
}
/**
* Sets the {@link #minEvictableIdleTimeMillis} property.
*
* @param minEvictableIdleTimeMillis the minimum amount of time an object
* may sit idle in the pool
* @see #minEvictableIdleTimeMillis
*/
public synchronized void setMinEvictableIdleTimeMillis(long minEvictableIdleTimeMillis) {
this.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis;
if (connectionPool != null) {
connectionPool.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
}
}
/**
* The minimum amount of time a connection may sit idle in the pool before
* it is eligible for eviction by the idle object evictor, with the extra
* condition that at least "minIdle" connections remain in the pool.
* Note that {@code minEvictableIdleTimeMillis} takes precedence over this
* parameter. See {@link #getSoftMinEvictableIdleTimeMillis()}.
*/
private long softMinEvictableIdleTimeMillis =
BaseObjectPoolConfig.DEFAULT_SOFT_MIN_EVICTABLE_IDLE_TIME_MILLIS;
/**
* Sets the minimum amount of time a connection may sit idle in the pool
* before it is eligible for eviction by the idle object evictor, with the
* extra condition that at least "minIdle" connections remain in the pool.
*
* @param softMinEvictableIdleTimeMillis minimum amount of time a
* connection may sit idle in the pool before it is eligible for eviction,
* assuming there are minIdle idle connections in the pool.
* @see #getSoftMinEvictableIdleTimeMillis
*/
public synchronized void setSoftMinEvictableIdleTimeMillis(long softMinEvictableIdleTimeMillis) {
this.softMinEvictableIdleTimeMillis = softMinEvictableIdleTimeMillis;
if (connectionPool != null) {
connectionPool.setSoftMinEvictableIdleTimeMillis(softMinEvictableIdleTimeMillis);
}
}
/**
* <p>Returns the minimum amount of time a connection may sit idle in the
* pool before it is eligible for eviction by the idle object evictor, with
* the extra condition that at least "minIdle" connections remain in the
* pool.</p>
*
* <p>When {@link #getMinEvictableIdleTimeMillis() miniEvictableIdleTimeMillis}
* is set to a positive value, miniEvictableIdleTimeMillis is examined
* first by the idle connection evictor - i.e. when idle connections are
* visited by the evictor, idle time is first compared against
* {@code minEvictableIdleTimeMillis} (without considering the number of idle
* connections in the pool) and then against
* {@code softMinEvictableIdleTimeMillis}, including the {@code minIdle},
* constraint.</p>
*
* @return minimum amount of time a connection may sit idle in the pool before
* it is eligible for eviction, assuming there are minIdle idle connections
* in the pool
*/
@Override
public synchronized long getSoftMinEvictableIdleTimeMillis() {
return softMinEvictableIdleTimeMillis;
}
private String evictionPolicyClassName =
BaseObjectPoolConfig.DEFAULT_EVICTION_POLICY_CLASS_NAME;
/**
* Gets the EvictionPolicy implementation in use with this connection pool.
*/
public synchronized String getEvictionPolicyClassName() {
return evictionPolicyClassName;
}
/**
* Sets the EvictionPolicy implementation to use with this connection pool.
*
* @param evictionPolicyClassName The fully qualified class name of the
* EvictionPolicy implementation
*/
public synchronized void setEvictionPolicyClassName(
String evictionPolicyClassName) {
if (connectionPool != null) {
connectionPool.setEvictionPolicyClassName(evictionPolicyClassName);
}
this.evictionPolicyClassName = evictionPolicyClassName;
}
/**
* The indication of whether objects will be validated by the idle object
* evictor (if any). If an object fails to validate, it will be dropped
* from the pool.
*/
private boolean testWhileIdle = false;
/**
* Returns the value of the {@link #testWhileIdle} property.
*
* @return true if objects examined by the idle object evictor are
* validated
* @see #testWhileIdle
*/
@Override
public synchronized boolean getTestWhileIdle() {
return this.testWhileIdle;
}
/**
* Sets the <code>testWhileIdle</code> property. This property determines
* whether or not the idle object evictor will validate connections.
*
* @param testWhileIdle new value for testWhileIdle property
*/
public synchronized void setTestWhileIdle(boolean testWhileIdle) {
this.testWhileIdle = testWhileIdle;
if (connectionPool != null) {
connectionPool.setTestWhileIdle(testWhileIdle);
}
}
/**
* [Read Only] The current number of active connections that have been
* allocated from this data source.
*
* @return the current number of active connections
*/
@Override
public synchronized int getNumActive() {
if (connectionPool != null) {
return connectionPool.getNumActive();
}
return 0;
}
/**
* [Read Only] The current number of idle connections that are waiting
* to be allocated from this data source.
*
* @return the current number of idle connections
*/
@Override
public synchronized int getNumIdle() {
if (connectionPool != null) {
return connectionPool.getNumIdle();
}
return 0;
}
/**
* The connection password to be passed to our JDBC driver to establish
* a connection.
*/
private volatile String password = null;
/**
* Returns the password passed to the JDBC driver to establish connections.
*
* @return the connection password
*/
@Override
public String getPassword() {
return this.password;
}
/**
* <p>Sets the {@link #password}.</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: <code>getConnection, setLogwriter,
* setLoginTimeout, getLoginTimeout, getLogWriter.</code></p>
*
* @param password new value for the password
*/
public void setPassword(String password) {
this.password = password;
}
/**
* The connection URL to be passed to our JDBC driver to establish
* a connection.
*/
private String url = null;
/**
* Returns the JDBC connection {@link #url} property.
*
* @return the {@link #url} passed to the JDBC driver to establish
* connections
*/
@Override
public synchronized String getUrl() {
return this.url;
}
/**
* <p>Sets the {@link #url}.</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: <code>getConnection, setLogwriter,
* setLoginTimeout, getLoginTimeout, getLogWriter.</code></p>
*
* @param url the new value for the JDBC connection url
*/
public synchronized void setUrl(String url) {
this.url = url;
}
/**
* The connection username to be passed to our JDBC driver to
* establish a connection.
*/
private String username = null;
/**
* Returns the JDBC connection {@link #username} property.
*
* @return the {@link #username} passed to the JDBC driver to establish
* connections
*/
@Override
public String getUsername() {
return this.username;
}
/**
* <p>Sets the {@link #username}.</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: <code>getConnection, setLogwriter,
* setLoginTimeout, getLoginTimeout, getLogWriter.</code></p>
*
* @param username the new value for the JDBC connection username
*/
public void setUsername(String username) {
this.username = username;
}
/**
* 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.
*/
private volatile String validationQuery = null;
/**
* Returns the validation query used to validate connections before
* returning them.
*
* @return the SQL validation query
* @see #validationQuery
*/
@Override
public String getValidationQuery() {
return this.validationQuery;
}
/**
* <p>Sets the {@link #validationQuery}.</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: <code>getConnection, setLogwriter,
* setLoginTimeout, getLoginTimeout, getLogWriter.</code></p>
*
* @param validationQuery the new value for the validation query
*/
public void setValidationQuery(String validationQuery) {
if (validationQuery != null && validationQuery.trim().length() > 0) {
this.validationQuery = validationQuery;
} else {
this.validationQuery = null;
}
}
/**
* Timeout in seconds before connection validation queries fail.
*/
private volatile int validationQueryTimeout = -1;
/**
* Returns the validation query timeout.
*
* @return the timeout in seconds before connection validation queries fail.
*/
@Override
public int getValidationQueryTimeout() {
return validationQueryTimeout;
}
/**
* Sets the validation query timeout, the amount of time, in seconds, that
* connection validation will wait for a response from the database when
* executing a validation query. Use a value less than or equal to 0 for
* no timeout.
* <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: <code>getConnection, setLogwriter,
* setLoginTimeout, getLoginTimeout, getLogWriter.</code></p>
*
* @param timeout new validation query timeout value in seconds
*/
public void setValidationQueryTimeout(int timeout) {
this.validationQueryTimeout = timeout;
}
/**
* These SQL statements run once after a Connection is created.
* <p>
* This property can be used for example to run ALTER SESSION SET
* NLS_SORT=XCYECH in an Oracle Database only once after connection
* creation.
* </p>
*/
private volatile List<String> connectionInitSqls;
/**
* Returns the list of SQL statements executed when a physical connection
* is first created. Returns an empty list if there are no initialization
* statements configured.
*
* @return initialization SQL statements
*/
public List<String> getConnectionInitSqls() {
List<String> result = connectionInitSqls;
if (result == null) {
return Collections.emptyList();
}
return result;
}
/**
* Provides the same data as {@link #getConnectionInitSqls()} but in an
* array so it is accessible via JMX.
*/
@Override
public String[] getConnectionInitSqlsAsArray() {
Collection<String> result = getConnectionInitSqls();
return result.toArray(new String[result.size()]);
}
/**
* Sets the list of SQL statements to be executed when a physical
* connection is first created.
* <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: <code>getConnection, setLogwriter,
* setLoginTimeout, getLoginTimeout, getLogWriter.</code></p>
*
* @param connectionInitSqls Collection of SQL statements to execute
* on connection creation
*/
public void setConnectionInitSqls(Collection<String> connectionInitSqls) {
if (connectionInitSqls != null && connectionInitSqls.size() > 0) {
ArrayList<String> newVal = null;
for (String s : connectionInitSqls) {
if (s != null && s.trim().length() > 0) {
if (newVal == null) {
newVal = new ArrayList<>();
}
newVal.add(s);
}
}
this.connectionInitSqls = newVal;
} else {
this.connectionInitSqls = null;
}
}
/**
* Controls access to the underlying connection.
*/
private boolean accessToUnderlyingConnectionAllowed = false;
/**
* Returns the value of the accessToUnderlyingConnectionAllowed property.
*
* @return true if access to the underlying connection is allowed, false
* otherwise.
*/
@Override
public synchronized boolean isAccessToUnderlyingConnectionAllowed() {
return this.accessToUnderlyingConnectionAllowed;
}
/**
* <p>Sets the value of the accessToUnderlyingConnectionAllowed property.
* It controls if the PoolGuard allows access to the underlying connection.
* (Default: false)</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: <code>getConnection, setLogwriter,
* setLoginTimeout, getLoginTimeout, getLogWriter.</code></p>
*
* @param allow Access to the underlying connection is granted when true.
*/
public synchronized void setAccessToUnderlyingConnectionAllowed(boolean allow) {
this.accessToUnderlyingConnectionAllowed = allow;
}
private long maxConnLifetimeMillis = -1;
/**
* Returns the maximum permitted lifetime of a connection in milliseconds. A
* value of zero or less indicates an infinite lifetime.
*/
@Override
public long getMaxConnLifetimeMillis() {
return 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: <code>getConnection, setLogwriter,
* setLoginTimeout, getLoginTimeout, getLogWriter.</code></p>
*/
public void setMaxConnLifetimeMillis(long maxConnLifetimeMillis) {
this.maxConnLifetimeMillis = maxConnLifetimeMillis;
}
private String jmxName = null;
/**
* Returns the JMX name that has been requested for this DataSource. If the
* requested name is not valid, an alternative may be chosen.
*/
public String getJmxName() {
return jmxName;
}
/**
* Sets the JMX name that has been requested for this DataSource. If the
* requested name is not valid, an alternative may be chosen. This
* DataSource will attempt to register itself using this name. If another
* component registers this DataSource with JMX and this name is valid this
* name will be used in preference to any specified by the other component.
*/
public void setJmxName(String jmxName) {
this.jmxName = jmxName;
}
private boolean enableAutoCommitOnReturn = true;
/**
* Returns the value of the flag that controls whether or not connections
* being returned to the pool will checked and configured with
* {@link Connection#setAutoCommit(boolean) Connection.setAutoCommit(true)}
* if the auto commit setting is {@code false} when the connection
* is returned. It is <code>true</code> by default.
*/
public boolean getEnableAutoCommitOnReturn() {
return enableAutoCommitOnReturn;
}
/**
* Sets the value of the flag that controls whether or not connections
* being returned to the pool will checked and configured with
* {@link Connection#setAutoCommit(boolean) Connection.setAutoCommit(true)}
* if the auto commit setting is {@code false} when the connection
* is returned. It is <code>true</code> by default.
*/
public void setEnableAutoCommitOnReturn(boolean enableAutoCommitOnReturn) {
this.enableAutoCommitOnReturn = enableAutoCommitOnReturn;
}
private boolean rollbackOnReturn = true;
/**
* Gets the current value of the flag that controls if a connection will be
* rolled back when it is returned to the pool if auto commit is not enabled
* and the connection is not read only.
*/
public boolean getRollbackOnReturn() {
return rollbackOnReturn;
}
/**
* Sets the flag that controls if a connection will be rolled back when it
* is returned to the pool if auto commit is not enabled and the connection
* is not read only.
*/
public void setRollbackOnReturn(boolean rollbackOnReturn) {
this.rollbackOnReturn = rollbackOnReturn;
}
// ----------------------------------------------------- Instance Variables
/**
* The object pool that internally manages our connections.
*/
private volatile GenericObjectPool<PoolableConnection> connectionPool = null;
protected GenericObjectPool<PoolableConnection> getConnectionPool() {
return connectionPool;
}
/**
* The connection properties that will be sent to our JDBC driver when
* establishing new connections. <strong>NOTE</strong> - The "user" and
* "password" properties will be passed explicitly, so they do not need
* to be included here.
*/
private Properties connectionProperties = new Properties();
// For unit testing
Properties getConnectionProperties() {
return connectionProperties;
}
/**
* The data source we will use to manage connections. This object should
* be acquired <strong>ONLY</strong> by calls to the
* <code>createDataSource()</code> method.
*/
private volatile DataSource dataSource = null;
/**
* The PrintWriter to which log messages should be directed.
*/
private volatile PrintWriter logWriter = new PrintWriter(new OutputStreamWriter(
System.out, StandardCharsets.UTF_8));
// ----------------------------------------------------- DataSource Methods
/**
* Create (if necessary) and return a connection to the database.
*
* @throws SQLException if a database access error occurs
* @return a database connection
*/
@Override
public Connection getConnection() throws SQLException {
if (Utils.IS_SECURITY_ENABLED) {
PrivilegedExceptionAction<Connection> action = new PaGetConnection();
try {
return AccessController.doPrivileged(action);
} catch (PrivilegedActionException e) {
Throwable cause = e.getCause();
if (cause instanceof SQLException) {
throw (SQLException) cause;
}
throw new SQLException(e);
}
}
return createDataSource().getConnection();
}
/**
* <strong>BasicDataSource does NOT support this method. </strong>
*
* @param user Database user on whose behalf the Connection
* is being made
* @param pass The database user's password
*
* @throws UnsupportedOperationException
* @throws SQLException if a database access error occurs
* @return nothing - always throws UnsupportedOperationException
*/
@Override
public Connection getConnection(String user, String pass) throws SQLException {
// This method isn't supported by the PoolingDataSource returned by
// the createDataSource
throw new UnsupportedOperationException("Not supported by BasicDataSource");
}
/**
* <strong>BasicDataSource does NOT support this method. </strong>
*
* <p>Returns the login timeout (in seconds) for connecting to the database.
* </p>
* <p>Calls {@link #createDataSource()}, so has the side effect
* of initializing the connection pool.</p>
*
* @throws SQLException if a database access error occurs
* @throws UnsupportedOperationException If the DataSource implementation
* does not support the login timeout feature.
* @return login timeout in seconds
*/
@Override
public int getLoginTimeout() throws SQLException {
// This method isn't supported by the PoolingDataSource returned by
// the createDataSource
throw new UnsupportedOperationException("Not supported by BasicDataSource");
}
/**
* <p>Returns the log writer being used by this data source.</p>
* <p>
* Calls {@link #createDataSource()}, so has the side effect
* of initializing the connection pool.</p>
*
* @throws SQLException if a database access error occurs
* @return log writer in use
*/
@Override
public PrintWriter getLogWriter() throws SQLException {
return createDataSource().getLogWriter();
}
/**
* <strong>BasicDataSource does NOT support this method. </strong>
*
* <p>Set the login timeout (in seconds) for connecting to the
* database.</p>
* <p>
* Calls {@link #createDataSource()}, so has the side effect
* of initializing the connection pool.</p>
*
* @param loginTimeout The new login timeout, or zero for no timeout
* @throws UnsupportedOperationException If the DataSource implementation
* does not support the login timeout feature.
* @throws SQLException if a database access error occurs
*/
@Override
public void setLoginTimeout(int loginTimeout) throws SQLException {
// This method isn't supported by the PoolingDataSource returned by
// the createDataSource
throw new UnsupportedOperationException("Not supported by BasicDataSource");
}
/**
* <p>Sets the log writer being used by this data source.</p>
* <p>
* Calls {@link #createDataSource()}, so has the side effect
* of initializing the connection pool.</p>
*
* @param logWriter The new log writer
* @throws SQLException if a database access error occurs
*/
@Override
public void setLogWriter(PrintWriter logWriter) throws SQLException {
createDataSource().setLogWriter(logWriter);
this.logWriter = logWriter;
}
private AbandonedConfig abandonedConfig;
/**
* <p>Flag to remove abandoned connections if they exceed the
* removeAbandonedTimeout when borrowObject is invoked.</p>
*
* <p>The default value is false.<p>
*
* <p>If set to true a connection is considered abandoned and eligible
* for removal if it has not been used for more than
* {@link #getRemoveAbandonedTimeout() removeAbandonedTimeout} seconds.</p>
*
* <p>Abandoned connections are identified and removed when
* {@link #getConnection()} is invoked and the following conditions hold
* <ul><li>{@link #getRemoveAbandonedOnBorrow()} or
* {@link #getRemoveAbandonedOnMaintenance()} = true</li>
* <li>{@link #getNumActive()} > {@link #getMaxTotal()} - 3 </li>
* <li>{@link #getNumIdle()} < 2 </li></ul></p>
*
* @see #getRemoveAbandonedTimeout()
*/
@Override
public boolean getRemoveAbandonedOnBorrow() {
if (abandonedConfig != null) {
return abandonedConfig.getRemoveAbandonedOnBorrow();
}
return false;
}
/**
* <p>Flag to remove abandoned connections if they exceed the
* removeAbandonedTimeout when borrowObject is invoked.</p>
*
* <p>If set to true a connection is considered abandoned and eligible
* for removal if it has been idle longer than the
* {@link #getRemoveAbandonedTimeout() removeAbandonedTimeout}.</p>
*
* <p>Setting this to true can recover db connections from poorly written
* applications which fail to close a connection.</p>
*
* @param removeAbandonedOnMaintenance true means abandoned connections will
* be removed when borrowObject is
* invoked
*/
public void setRemoveAbandonedOnMaintenance(
boolean removeAbandonedOnMaintenance) {
if (abandonedConfig == null) {
abandonedConfig = new AbandonedConfig();
}
abandonedConfig.setRemoveAbandonedOnMaintenance(
removeAbandonedOnMaintenance);
}
/**
* <p>Flag to remove abandoned connections if they exceed the
* removeAbandonedTimeout during pool maintenance.</p>
*
* <p>The default value is false.<p>
*
* <p>If set to true a connection is considered abandoned and eligible
* for removal if it has not been used for more than
* {@link #getRemoveAbandonedTimeout() removeAbandonedTimeout} seconds.</p>
*
* <p>Abandoned connections are identified and removed when
* {@link #getConnection()} is invoked and the following conditions hold
* <ul><li>{@link #getRemoveAbandonedOnBorrow()} or
* {@link #getRemoveAbandonedOnMaintenance()} = true</li>
* <li>{@link #getNumActive()} > {@link #getMaxTotal()} - 3 </li>
* <li>{@link #getNumIdle()} < 2 </li></ul></p>
*
* @see #getRemoveAbandonedTimeout()
*/
@Override
public boolean getRemoveAbandonedOnMaintenance() {
if (abandonedConfig != null) {
return abandonedConfig.getRemoveAbandonedOnMaintenance();
}
return false;
}
/**
* <p>Flag to remove abandoned connections if they exceed the
* removeAbandonedTimeout during pool maintenance.</p>
*
* <p>If set to true a connection is considered abandoned and eligible
* for removal if it has been idle longer than the
* {@link #getRemoveAbandonedTimeout() removeAbandonedTimeout}.</p>
*
* <p>Setting this to true can recover db connections from poorly written
* applications which fail to close a connection.</p>
*
* @param removeAbandonedOnBorrow true means abandoned connections will be
* removed during pool maintenance
*/
public void setRemoveAbandonedOnBorrow(boolean removeAbandonedOnBorrow) {
if (abandonedConfig == null) {
abandonedConfig = new AbandonedConfig();
}
abandonedConfig.setRemoveAbandonedOnBorrow(removeAbandonedOnBorrow);
}
/**
* <p>Timeout in seconds before an abandoned connection can be removed.</p>
*
* <p>Creating a Statement, PreparedStatement or CallableStatement or using
* one of these to execute a query (using one of the execute methods)
* resets the lastUsed property of the parent connection.</p>
*
* <p>Abandoned connection cleanup happens when
* <code><ul>
* <li>{@link #getRemoveAbandonedOnBorrow()} or
* {@link #getRemoveAbandonedOnMaintenance()} = true</li>
* <li>{@link #getNumIdle() numIdle} < 2</li>
* <li>{@link #getNumActive() numActive} > {@link #getMaxTotal() maxTotal} - 3</li>
* </ul></code></p>
*
* <p>The default value is 300 seconds.</p>
*/
@Override
public int getRemoveAbandonedTimeout() {
if (abandonedConfig != null) {
return abandonedConfig.getRemoveAbandonedTimeout();
}
return 300;
}
/**
* <p>Sets the timeout in seconds before an abandoned connection can be
* removed.</p>
*
* <p>Setting this property has no effect if
* {@link #getRemoveAbandonedOnBorrow()} and
* {@link #getRemoveAbandonedOnMaintenance()} are false.</p>
*
* @param removeAbandonedTimeout new abandoned timeout in seconds
* @see #getRemoveAbandonedTimeout()
* @see #getRemoveAbandonedOnBorrow()
* @see #getRemoveAbandonedOnMaintenance()
*/
public void setRemoveAbandonedTimeout(int removeAbandonedTimeout) {
if (abandonedConfig == null) {
abandonedConfig = new AbandonedConfig();
}
abandonedConfig.setRemoveAbandonedTimeout(removeAbandonedTimeout);
}
/**
* <p>Flag to log stack traces for application code which abandoned
* a Statement or Connection.
* </p>
* <p>Defaults to false.
* </p>
* <p>Logging of abandoned Statements and Connections adds overhead
* for every Connection open or new Statement because a stack
* trace has to be generated. </p>
*/
@Override
public boolean getLogAbandoned() {
if (abandonedConfig != null) {
return abandonedConfig.getLogAbandoned();
}
return false;
}
/**
* @param logAbandoned new logAbandoned property value
*/
public void setLogAbandoned(boolean logAbandoned) {
if (abandonedConfig == null) {
abandonedConfig = new AbandonedConfig();
}
abandonedConfig.setLogAbandoned(logAbandoned);
}
/**
* Gets the log writer to be used by this configuration to log
* information on abandoned objects.
*/
public PrintWriter getAbandonedLogWriter() {
if (abandonedConfig != null) {
return abandonedConfig.getLogWriter();
}
return null;
}
/**
* Sets the log writer to be used by this configuration to log
* information on abandoned objects.
*
* @param logWriter The new log writer
*/
public void setAbandonedLogWriter(PrintWriter logWriter) {
if (abandonedConfig == null) {
abandonedConfig = new AbandonedConfig();
}
abandonedConfig.setLogWriter(logWriter);
}
/**
* If the connection pool implements {@link org.apache.tomcat.dbcp.pool2.UsageTracking UsageTracking}, should the
* connection pool record a stack trace every time a method is called on a
* pooled connection and retain the most recent stack trace to aid debugging
* of abandoned connections?
*
* @return <code>true</code> if usage tracking is enabled
*/
@Override
public boolean getAbandonedUsageTracking() {
if (abandonedConfig != null) {
return abandonedConfig.getUseUsageTracking();
}
return false;
}
/**
* If the connection pool implements {@link org.apache.tomcat.dbcp.pool2.UsageTracking UsageTracking}, configure
* whether the connection pool should record a stack trace every time a
* method is called on a pooled connection and retain the most recent stack
* trace to aid debugging of abandoned connections.
*
* @param usageTracking A value of <code>true</code> will enable
* the recording of a stack trace on every use
* of a pooled connection
*/
public void setAbandonedUsageTracking(boolean usageTracking) {
if (abandonedConfig == null) {
abandonedConfig = new AbandonedConfig();
}
abandonedConfig.setUseUsageTracking(usageTracking);
}
// --------------------------------------------------------- Public Methods
/**
* Add a custom connection property to the set that will be passed to our
* JDBC driver. This <strong>MUST</strong> be called before the first
* connection is retrieved (along with all the other configuration
* property setters). Calls to this method after the connection pool
* has been initialized have no effect.
*
* @param name Name of the custom connection property
* @param value Value of the custom connection property
*/
public void addConnectionProperty(String name, String value) {
connectionProperties.put(name, value);
}
/**
* Remove a custom connection property.
*
* @param name Name of the custom connection property to remove
* @see #addConnectionProperty(String, String)
*/
public void removeConnectionProperty(String name) {
connectionProperties.remove(name);
}
/**
* Sets the connection properties passed to driver.connect(...).
*
* Format of the string must be [propertyName=property;]*
*
* NOTE - The "user" and "password" properties will be added
* explicitly, so they do not need to be included here.
*
* @param connectionProperties the connection properties used to
* create new connections
*/
public void setConnectionProperties(String connectionProperties) {
if (connectionProperties == null) {
throw new NullPointerException("connectionProperties is null");
}
String[] entries = connectionProperties.split(";");
Properties properties = new Properties();
for (String entry : entries) {
if (entry.length() > 0) {
int index = entry.indexOf('=');
if (index > 0) {
String name = entry.substring(0, index);
String value = entry.substring(index + 1);
properties.setProperty(name, value);
} else {
// no value is empty string which is how java.util.Properties works
properties.setProperty(entry, "");
}
}
}
this.connectionProperties = properties;
}
private boolean closed;
/**
* <p>Closes and releases all idle connections that are currently stored in the connection pool
* associated with this data source.</p>
*
* <p>Connections that are checked out to clients when this method is invoked are not affected.
* When client applications subsequently invoke {@link Connection#close()} to return
* these connections to the pool, the underlying JDBC connections are closed.</p>
*
* <p>Attempts to acquire connections using {@link #getConnection()} after this method has been
* invoked result in SQLExceptions.<p>
*
* <p>This method is idempotent - i.e., closing an already closed BasicDataSource has no effect
* and does not generate exceptions.</p>
*
* @throws SQLException if an error occurs closing idle connections
*/
public synchronized void close() throws SQLException {
if (registeredJmxName != null) {
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
try {
mbs.unregisterMBean(registeredJmxName);
} catch (JMException e) {
log.warn("Failed to unregister the JMX name: " + registeredJmxName, e);
} finally {
registeredJmxName = null;
}
}
closed = true;
GenericObjectPool<?> oldpool = connectionPool;
connectionPool = null;
dataSource = null;
try {
if (oldpool != null) {
oldpool.close();
}
} catch(RuntimeException e) {
throw e;
} catch(Exception e) {
throw new SQLException("Cannot close connection pool", e);
}
}
/**
* If true, this data source is closed and no more connections can be retrieved from this datasource.
* @return true, if the data source is closed; false otherwise
*/
@Override
public synchronized boolean isClosed() {
return closed;
}
@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
return false;
}
@Override
public <T> T unwrap(Class<T> iface) throws SQLException {
throw new SQLException("BasicDataSource is not a wrapper.");
}
@Override
public Logger getParentLogger() throws SQLFeatureNotSupportedException {
throw new SQLFeatureNotSupportedException();
}
// ------------------------------------------------------ Protected Methods
/**
* <p>Create (if necessary) and return the internal data source we are
* using to manage our connections.</p>
*
* @throws SQLException if the object pool cannot be created.
*/
protected DataSource createDataSource()
throws SQLException {
if (closed) {
throw new SQLException("Data source is closed");
}
// Return the pool if we have already created it
// This is double-checked locking. This is safe since dataSource is
// volatile and the code is targeted at Java 5 onwards.
if (dataSource != null) {
return dataSource;
}
synchronized (this) {
if (dataSource != null) {
return dataSource;
}
jmxRegister();
// create factory which returns raw physical connections
ConnectionFactory driverConnectionFactory = createConnectionFactory();
// Set up the poolable connection factory
boolean success = false;
PoolableConnectionFactory poolableConnectionFactory;
try {
poolableConnectionFactory = createPoolableConnectionFactory(
driverConnectionFactory);
poolableConnectionFactory.setPoolStatements(
poolPreparedStatements);
poolableConnectionFactory.setMaxOpenPrepatedStatements(
maxOpenPreparedStatements);
success = true;
} catch (SQLException se) {
throw se;
} catch (RuntimeException rte) {
throw rte;
} catch (Exception ex) {
throw new SQLException("Error creating connection factory", ex);
}
if (success) {
// create a pool for our connections
createConnectionPool(poolableConnectionFactory);
}
// Create the pooling data source to manage connections
success = false;
try {
dataSource = createDataSourceInstance();
dataSource.setLogWriter(logWriter);
success = true;
} catch (SQLException se) {
throw se;
} catch (RuntimeException rte) {
throw rte;
} catch (Exception ex) {
throw new SQLException("Error creating datasource", ex);
} finally {
if (!success) {
closeConnectionPool();
}
}
// If initialSize > 0, preload the pool
try {
for (int i = 0 ; i < initialSize ; i++) {
connectionPool.addObject();
}
} catch (Exception e) {
closeConnectionPool();
throw new SQLException("Error preloading the connection pool", e);
}
// If timeBetweenEvictionRunsMillis > 0, start the pool's evictor task
startPoolMaintenance();
return dataSource;
}
}
/**
* Creates a JDBC connection factory for this datasource. The JDBC driver
* is loaded using the following algorithm:
* <ol>
* <li>If a Driver instance has been specified via
* {@link #setDriver(Driver)} use it</li>
* <li>If no Driver instance was specified and {@link #driverClassName} is
* specified that class is loaded using the {@link ClassLoader} of this
* class or, if {@link #driverClassLoader} is set, {@link #driverClassName}
* is loaded with the specified {@link ClassLoader}.</li>
* <li>If {@link #driverClassName} is specified and the previous attempt
* fails, the class is loaded using the context class loader of the current
* thread.</li>
* <li>If a driver still isn't loaded one is loaded via the
* {@link DriverManager} using the specified {@link #url}.
* </ol>
* This method exists so subclasses can replace the implementation class.
*/
protected ConnectionFactory createConnectionFactory() throws SQLException {
// Load the JDBC driver class
Driver driverToUse = this.driver;
if (driverToUse == null) {
Class<?> driverFromCCL = null;
if (driverClassName != null) {
try {
try {
if (driverClassLoader == null) {
driverFromCCL = Class.forName(driverClassName);
} else {
driverFromCCL = Class.forName(
driverClassName, true, driverClassLoader);
}
} catch (ClassNotFoundException cnfe) {
driverFromCCL = Thread.currentThread(
).getContextClassLoader().loadClass(
driverClassName);
}
} catch (Exception t) {
String message = "Cannot load JDBC driver class '" +
driverClassName + "'";
logWriter.println(message);
t.printStackTrace(logWriter);
throw new SQLException(message, t);
}
}
try {
if (driverFromCCL == null) {
driverToUse = DriverManager.getDriver(url);
} else {
// Usage of DriverManager is not possible, as it does not
// respect the ContextClassLoader
// N.B. This cast may cause ClassCastException which is handled below
driverToUse = (Driver) driverFromCCL.newInstance();
if (!driverToUse.acceptsURL(url)) {
throw new SQLException("No suitable driver", "08001");
}
}
} catch (Exception t) {
String message = "Cannot create JDBC driver of class '" +
(driverClassName != null ? driverClassName : "") +
"' for connect URL '" + url + "'";
logWriter.println(message);
t.printStackTrace(logWriter);
throw new SQLException(message, t);
}
}
// Set up the driver connection factory we will use
String user = username;
if (user != null) {
connectionProperties.put("user", user);
} else {
log("DBCP DataSource configured without a 'username'");
}
String pwd = password;
if (pwd != null) {
connectionProperties.put("password", pwd);
} else {
log("DBCP DataSource configured without a 'password'");
}
ConnectionFactory driverConnectionFactory =
new DriverConnectionFactory(driverToUse, url, connectionProperties);
return driverConnectionFactory;
}
/**
* Creates a connection pool for this datasource. This method only exists
* so subclasses can replace the implementation class.
*
* This implementation configures all pool properties other than
* timeBetweenEvictionRunsMillis. Setting that property is deferred to
* {@link #startPoolMaintenance()}, since setting timeBetweenEvictionRunsMillis
* to a positive value causes {@link GenericObjectPool}'s eviction timer
* to be started.
*/
protected void createConnectionPool(PoolableConnectionFactory factory) {
// Create an object pool to contain our active connections
GenericObjectPoolConfig config = new GenericObjectPoolConfig();
updateJmxName(config);
GenericObjectPool<PoolableConnection> gop;
if (abandonedConfig != null &&
(abandonedConfig.getRemoveAbandonedOnBorrow() ||
abandonedConfig.getRemoveAbandonedOnMaintenance())) {
gop = new GenericObjectPool<>(factory, config, abandonedConfig);
}
else {
gop = new GenericObjectPool<>(factory, config);
}
gop.setMaxTotal(maxTotal);
gop.setMaxIdle(maxIdle);
gop.setMinIdle(minIdle);
gop.setMaxWaitMillis(maxWaitMillis);
gop.setTestOnCreate(testOnCreate);
gop.setTestOnBorrow(testOnBorrow);
gop.setTestOnReturn(testOnReturn);
gop.setNumTestsPerEvictionRun(numTestsPerEvictionRun);
gop.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
gop.setTestWhileIdle(testWhileIdle);
gop.setLifo(lifo);
gop.setSwallowedExceptionListener(new SwallowedExceptionLogger(log));
gop.setEvictionPolicyClassName(evictionPolicyClassName);
factory.setPool(gop);
connectionPool = gop;
}
/**
* Closes the connection pool, silently swallowing any exception that occurs.
*/
private void closeConnectionPool() {
GenericObjectPool<?> oldpool = connectionPool;
connectionPool = null;
try {
if (oldpool != null) {
oldpool.close();
}
} catch(Exception e) {
/* Ignore */
}
}
/**
* Starts the connection pool maintenance task, if configured.
*/
protected void startPoolMaintenance() {
if (connectionPool != null && timeBetweenEvictionRunsMillis > 0) {
connectionPool.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
}
}
/**
* Creates the actual data source instance. This method only exists so
* that subclasses can replace the implementation class.
*
* @throws SQLException if unable to create a datasource instance
*/
protected DataSource createDataSourceInstance() throws SQLException {
PoolingDataSource<PoolableConnection> pds = new PoolingDataSource<>(connectionPool);
pds.setAccessToUnderlyingConnectionAllowed(isAccessToUnderlyingConnectionAllowed());
return pds;
}
/**
* Creates the PoolableConnectionFactory and attaches it to the connection pool. This method only exists
* so subclasses can replace the default implementation.
*
* @param driverConnectionFactory JDBC connection factory
* @throws SQLException if an error occurs creating the PoolableConnectionFactory
*/
protected PoolableConnectionFactory createPoolableConnectionFactory(
ConnectionFactory driverConnectionFactory) throws SQLException {
PoolableConnectionFactory connectionFactory = null;
try {
connectionFactory = new PoolableConnectionFactory(driverConnectionFactory, registeredJmxName);
connectionFactory.setValidationQuery(validationQuery);
connectionFactory.setValidationQueryTimeout(validationQueryTimeout);
connectionFactory.setConnectionInitSql(connectionInitSqls);
connectionFactory.setDefaultReadOnly(defaultReadOnly);
connectionFactory.setDefaultAutoCommit(defaultAutoCommit);
connectionFactory.setDefaultTransactionIsolation(defaultTransactionIsolation);
connectionFactory.setDefaultCatalog(defaultCatalog);
connectionFactory.setCacheState(cacheState);
connectionFactory.setPoolStatements(poolPreparedStatements);
connectionFactory.setMaxOpenPrepatedStatements(maxOpenPreparedStatements);
connectionFactory.setMaxConnLifetimeMillis(maxConnLifetimeMillis);
connectionFactory.setRollbackOnReturn(getRollbackOnReturn());
connectionFactory.setEnableAutoCommitOnReturn(getEnableAutoCommitOnReturn());
connectionFactory.setDefaultQueryTimeout(getDefaultQueryTimeout());
validateConnectionFactory(connectionFactory);
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new SQLException("Cannot create PoolableConnectionFactory (" + e.getMessage() + ")", e);
}
return connectionFactory;
}
protected static void validateConnectionFactory(
PoolableConnectionFactory connectionFactory) throws Exception {
PoolableConnection conn = null;
PooledObject<PoolableConnection> p = null;
try {
p = connectionFactory.makeObject();
conn = p.getObject();
connectionFactory.activateObject(p);
connectionFactory.validateConnection(conn);
connectionFactory.passivateObject(p);
}
finally {
if (p != null) {
connectionFactory.destroyObject(p);
}
}
}
protected void log(String message) {
if (logWriter != null) {
logWriter.println(message);
}
}
/**
* Actual name under which this component has been registered.
*/
private ObjectName registeredJmxName = null;
private void jmxRegister() {
// Return immediately if this DataSource has already been registered
if (registeredJmxName != null) {
return;
}
// Return immediately if no JMX name has been specified
String requestedName = getJmxName();
if (requestedName == null) {
return;
}
ObjectName oname;
try {
oname = new ObjectName(requestedName);
} catch (MalformedObjectNameException e) {
log.warn("The requested JMX name [" + requestedName +
"] was not valid and will be ignored.");
return;
}
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
try {
mbs.registerMBean(this, oname);
} catch (InstanceAlreadyExistsException | MBeanRegistrationException
| NotCompliantMBeanException e) {
log.warn("Failed to complete JMX registration", e);
}
}
@Override
public ObjectName preRegister(MBeanServer server, ObjectName name) {
String requestedName = getJmxName();
if (requestedName != null) {
try {
registeredJmxName = new ObjectName(requestedName);
} catch (MalformedObjectNameException e) {
log.warn("The requested JMX name [" + requestedName +
"] was not valid and will be ignored.");
}
}
if (registeredJmxName == null) {
registeredJmxName = name;
}
return registeredJmxName;
}
@Override
public void postRegister(Boolean registrationDone) {
// NO-OP
}
@Override
public void preDeregister() throws Exception {
// NO-OP
}
@Override
public void postDeregister() {
// NO-OP
}
private void updateJmxName(GenericObjectPoolConfig config) {
if (registeredJmxName == null) {
return;
}
StringBuilder base = new StringBuilder(registeredJmxName.toString());
base.append(Constants.JMX_CONNECTION_POOL_BASE_EXT);
config.setJmxNameBase(base.toString());
config.setJmxNamePrefix(Constants.JMX_CONNECTION_POOL_PREFIX);
}
protected ObjectName getRegisteredJmxName() {
return registeredJmxName;
}
/**
* @since 2.0
*/
private class PaGetConnection implements PrivilegedExceptionAction<Connection> {
@Override
public Connection run() throws SQLException {
return createDataSource().getConnection();
}
}
}
|