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
|
/*
*
* Derby - Class org.apache.derbyTesting.junit.TestConfiguration
*
* 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.derbyTesting.junit;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.PrivilegedActionException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Properties;
import junit.extensions.TestSetup;
import junit.framework.Assert;
import junit.framework.Test;
import junit.framework.TestCase;
/**
* Class which holds information about the configuration of a Test.
*
* A configuration manages the pool of databases in use
* in <code>usedDbNames</code> property. One of those databases
* is supposed to be the default database. A new default database
* is added to the pool by <code>singleUseDatabaseDecorator</code> function.
* <br>
* Additional databases may be added by <code>additionalDatabaseDecorator</code>
* function. Each of the additional databases has its logical and physical name.
* Physical database name is automatically generated as 'singleUse/oneuseXX'
* where 'XX' is unique number. The logical database name is used to establish
* a connection to the database using
* a <code>TestConfiguration::openConnection(String logicalDatabaseName)</code>
* function.
* <br>
* The database files are supposed to be local and they will be
* removed by <code>DropDatabaseSetup</code>.
*
*/
public final class TestConfiguration {
/**
* Default values for configurations
*/
private final static String DEFAULT_DBNAME = "wombat";
private final static String DEFAULT_DBNAME_SQL = "dbsqlauth";
private final static String DEFAULT_USER_NAME = "APP";
private final static String DEFAULT_USER_PASSWORD = "APP";
private final static int DEFAULT_PORT = 1527;
private final static String DEFAULT_FRAMEWORK = "embedded";
private final static String DEFAULT_HOSTNAME = "localhost";
private static final int LOCKFILETIMEOUT = 300000; // 5 mins
/**
* Maximum number of ports used by Suites.All
* If this changes, this constant and the Wiki
* page at http://wiki.apache.org/db-derby/DerbyJUnitTesting
* need to be updated.
*/
private final static int MAX_PORTS_USED = 22;
/** This is the base port. This does NOT change EVER during the run of a suite.
* It is set using the property derby.tests.basePort and it is set to default when
* a property isn't used. */
private final static int basePort;
private static int lastAssignedPort;
private static final int bogusPort;
static {
String port = BaseTestCase.getSystemProperty("derby.tests.basePort");
if (port == null) {
lastAssignedPort = DEFAULT_PORT;
} else {
lastAssignedPort = Integer.parseInt(port);
}
basePort = lastAssignedPort;
bogusPort = ++lastAssignedPort;
}
private static int assignedPortCount = 2;
private FileOutputStream serverOutput;
/** Sleep for 1000 ms before pinging the network server (again) */
private static final int SLEEP_TIME = 1000;
/**
* Keys to use to look up values in properties files.
*/
private final static String KEY_DBNAME = "databaseName";
private final static String KEY_FRAMEWORK = "framework";
private final static String KEY_USER_PASSWORD = "password";
private final static String KEY_USER_NAME = "user";
private final static String KEY_HOSTNAME = "hostName";
private final static String KEY_PORT = "port";
private final static String KEY_VERBOSE = "derby.tests.debug";
private final static String KEY_LOGIN_TIMEOUT = "derby.tests.login.timeout";
private final static String KEY_TRACE = "derby.tests.trace";
public final static String KEY_OMIT_LUCENE = "derby.tests.omitLucene";
public final static String KEY_OMIT_JSON = "derby.tests.omitJson";
/**
* derby.tests.stopAfterFirstFail - debugging property to exit after
* first failure. Can be useful for debugging cascading failures or errors
* that lead to hang scenario.
*/
private final static String KEY_STOP_AFTER_FIRST_FAIL = "derby.tests.stopAfterFirstFail";
private final static String KEY_SSL = "ssl";
private final static String KEY_JMX_PORT = "jmxPort";
/**
* Simple count to provide a unique number for database
* names.
*/
private static int uniqueDB;
/** Repository of old/previous Derby releases available on the local system. */
private static ReleaseRepository releaseRepository;
/**
* Default configuration for standalone JUnit tests,
* an embedded configuration.
*/
private static final TestConfiguration JUNIT_CONFIG
= new TestConfiguration();
/**
* The default configuration.
*/
private static final TestConfiguration DEFAULT_CONFIG;
static {
DEFAULT_CONFIG = JUNIT_CONFIG;
final File dsh = new File("system");
BaseTestCase.setSystemProperty(
"derby.system.home", dsh.getAbsolutePath());
}
/**
* Current configuration is stored in a ThreadLocal to
* allow the potential for multiple tests to be running
* concurrently with different configurations.
*/
private static final ThreadLocal<TestConfiguration>
CURRENT_CONFIG = new ThreadLocal<TestConfiguration>() {
protected TestConfiguration initialValue() {
return DEFAULT_CONFIG;
}
};
/**
* Get this Thread's current configuraiton for running
* the tests.
* Note this call must only be used while a test is
* running, they make no sense when setting up a suite.
* A suite itself sets up which test configurations
* the fixtures will run in.
* @return TestConfiguration to use.
*/
public static TestConfiguration getCurrent() {
return (TestConfiguration) CURRENT_CONFIG.get();
}
/**
* Returns the release repository containing old Derby releases available
* on the local system.
* <p>
* <strong>NOTE</strong>: It is your responsibility to keep the repository
* up to date. This usually involves syncing the local Subversion repository
* of previous Derby releases with the master repository at Apache.
*
* @see ReleaseRepository
*/
public static synchronized ReleaseRepository getReleaseRepository() {
if (releaseRepository == null) {
try {
releaseRepository = ReleaseRepository.getInstance();
} catch (IOException ioe) {
BaseTestCase.printStackTrace(ioe);
Assert.fail("failed to initialize the release repository: " +
ioe.getMessage());
}
}
return releaseRepository;
}
/**
* WORK IN PROGRESS
* Set this Thread's current configuration for running tests.
* @param config Configuration to set it to.
*/
static void setCurrent(TestConfiguration config)
{
CURRENT_CONFIG.set(config);
}
/**
* Return a Test suite that contains all the test fixtures
* for the passed in class running in embedded and the
* default client server configuration.
* <BR>
* Each set of embedded and set of client server tests
* is decorated with a CleanDatabaseTestSetup.
* <BR>
* The client server configuration is setup using clientServerSuite
*/
public static Test defaultSuite(Class testClass)
{
return defaultSuite(testClass, true);
}
/**
* Does the work of "defaultSuite" as defined above. Takes
* a boolean argument to determine whether or not to "clean"
* the test database before each suite. If the resultant
* suite is going to be wrapped inside a TestSetup that creates
* database objects to be used throughout the tests, then the
* cleanDB parameter should be "false" to prevent cleanup of the
* database objects that TestSetup created. For example, see
* XMLBindingTest.suite().
*/
public static Test defaultSuite(Class testClass, boolean cleanDB)
{
final BaseTestSuite suite = new BaseTestSuite(suiteName(testClass));
if (cleanDB)
{
suite.addTest(new CleanDatabaseTestSetup(embeddedSuite(testClass)));
suite.addTest(new CleanDatabaseTestSetup(clientServerSuite(testClass)));
}
else
{
suite.addTest(embeddedSuite(testClass));
suite.addTest(clientServerSuite(testClass));
}
return (suite);
}
/**
* Equivalent to "defaultSuite" as defined above, but assumes a server
* has already been started.
* <BR>
* Does NOT decorate for running in embedded mode, only for running on
* the already started server.
* <BR>
* Return a Test suite that contains all the test fixtures
* for the passed in class running in client server configuration
* on an already started server.
* <BR>
* The set of client server tests
* is decorated with a CleanDatabaseTestSetup.
* <BR>
* The client server configuration is setup using clientExistingServerSuite
*/
public static Test defaultExistingServerSuite(Class testClass)
{
return defaultExistingServerSuite(testClass, true);
}
/**
* Does the work of "defaultExistingServerSuite" as defined above. Takes
* a boolean argument to determine whether or not to "clean"
* the test database before each suite. If the resultant
* suite is going to be wrapped inside a TestSetup that creates
* database objects to be used throughout the tests, then the
* cleanDB parameter should be "false" to prevent cleanup of the
* database objects that TestSetup created.
* <BR>
* Does NOT decorate for running in embedded mode, only for running on
* an already started server.
*/
public static Test defaultExistingServerSuite(Class testClass, boolean cleanDB)
{
final BaseTestSuite suite = new BaseTestSuite(suiteName(testClass));
if (cleanDB)
{
suite.addTest(new CleanDatabaseTestSetup(clientExistingServerSuite(testClass)));
}
else
{
suite.addTest(clientExistingServerSuite(testClass));
}
return (suite);
}
/**
* Return a Test suite that contains all the test fixtures
* for the passed in class running in client server configuration
* on an already started server on a given host and port number.
* <BR>
* Takes a boolean argument to determine whether or not to "clean"
* the test database before each suite. If the resultant
* suite is going to be wrapped inside a TestSetup that creates
* database objects to be used throughout the tests, then the
* cleanDB parameter should be "false" to prevent cleanup of the
* database objects that TestSetup created.
* <BR>
* Takes a String argument to specify which host the server runs on, and
* takes an int argument to specify the port number to use.
* <BR>
* Does NOT decorate for running in embedded mode, only for running on
* an already started server.
* <BR>
* The set of client server tests
* is decorated with a CleanDatabaseTestSetup.
* <BR>
* The client server configuration is setup using clientExistingServerSuite
*/
public static Test existingServerSuite(Class testClass,
boolean cleanDB,
String hostName,
int portNumber)
{
final BaseTestSuite suite = new BaseTestSuite(suiteName(testClass));
if (cleanDB)
{
suite.addTest(new CleanDatabaseTestSetup(
clientExistingServerSuite(testClass, hostName, portNumber)));
}
else
{
suite.addTest(clientExistingServerSuite(testClass, hostName, portNumber));
}
return (suite);
}
public static Test existingServerSuite(Class testClass,
boolean cleanDB,
String hostName,
int portNumber,
String dbPath)
{
final BaseTestSuite suite = new BaseTestSuite(suiteName(testClass));
if (cleanDB)
{
suite.addTest(new CleanDatabaseTestSetup(
clientExistingServerSuite(testClass, hostName, portNumber, dbPath)));
}
else
{
suite.addTest(clientExistingServerSuite(testClass, hostName, portNumber, dbPath));
}
return (suite);
}
/**
* Return a Test suite that contains all the test fixtures
* for the passed in class running in embedded and client-
* server *JDBC3* configurations.
* <BR>
* Each set of embedded and set of client server tests is
* decorated with a CleanDatabaseTestSetup.
* <BR>
*/
public static Test forceJDBC3Suite(Class testClass)
{
final BaseTestSuite suite = new BaseTestSuite(suiteName(testClass));
suite.addTest(
new CleanDatabaseTestSetup(
forceJDBC3Embedded(embeddedSuite(testClass))));
suite.addTest(
new CleanDatabaseTestSetup(
forceJDBC3NetClient(clientServerSuite(testClass))));
return (suite);
}
/**
* Generate a suite name from a class name, taking
* only the last element of the fully qualified class name.
*/
static String suiteName(Class testClass)
{
int lastDot = testClass.getName().lastIndexOf('.');
String suiteName = testClass.getName();
if (lastDot != -1)
suiteName = suiteName.substring(lastDot + 1, suiteName.length());
return suiteName;
}
/**
* Create a suite for the passed test class that includes
* all the default fixtures from the class.
*/
public static Test embeddedSuite(Class testClass)
{
return new BaseTestSuite(testClass,
suiteName(testClass)+":embedded");
}
/**
* Create a suite for the passed test class that includes
* all the default fixtures from the class, wrapped in
* a derbyClientServerDecorator.
*
*/
public static Test clientServerSuite(Class testClass)
{
return clientServerDecorator(bareClientServerSuite(testClass));
}
/**
* Create a suite for the passed test class that includes
* all the default fixtures from the class, wrapped in
* a derbyClientServerDecorator with alternative port.
*
*/
public static Test clientServerSuiteWithAlternativePort(Class testClass) {
return clientServerDecoratorWithAlternativePort(
bareClientServerSuite(testClass));
}
/**
* Equivalent to 'clientServerSuite' above, but assumes server is
* already running.
*
*/
public static Test clientExistingServerSuite(Class testClass)
{
// Will not start server and does not stop it when done.
return defaultExistingServerDecorator(bareClientServerSuite(testClass));
}
/**
* Create a suite for the passed test class that includes
* all the default fixtures from the class, wrapped in
* a existingServerDecorator.
* <BR>
* Equivalent to 'clientServerSuite' above, but assumes server is
* already running. Will also NOT shut down the server.
*
*/
public static Test clientExistingServerSuite(Class testClass, String hostName, int portNumber)
{
// Will not start server and does not stop it when done!.
return existingServerDecorator(bareClientServerSuite(testClass),
hostName, portNumber);
}
public static Test clientExistingServerSuite(Class testClass,
String hostName, int portNumber, String dbPath)
{
// Will not start server and does not stop it when done!.
return existingServerDecorator(bareClientServerSuite(testClass),
hostName, portNumber, dbPath);
}
/**
* Return a decorator for the passed in tests that sets the
* configuration for the client to be Derby's JDBC client
* and to start the network server at setUp.
* <BR>
* The database configuration (name etc.) is based upon
* the previous configuration.
* <BR>
* The previous TestConfiguration is restored at tearDown and
* the network server is shutdown.
* @param suite the suite to decorate
*/
public static Test clientServerDecorator(Test suite)
{
Test test = new NetworkServerTestSetup(suite, false);
return defaultServerDecorator(test);
}
/**
* Return a decorator for the passed in tests that sets the
* configuration for the client to be Derby's JDBC client
* and to start the network server at setUp.
* <BR>
* The database configuration (name etc.) is based upon
* the previous configuration.
* <BR>
* The previous TestConfiguration is restored at tearDown and
* the network server is shutdown.
* @param suite the suite to decorate
*/
public static Test clientServerDecoratorWithPort(Test suite, int port)
{
Test test = new NetworkServerTestSetup(suite, false);
return existingServerDecorator(test,"localhost",port);
}
/**
* Wrapper to use the alternative port number.
*/
public static Test clientServerDecoratorWithAlternativePort(Test suite) {
Test test = new NetworkServerTestSetup(suite, false);
return defaultServerDecoratorWithAlternativePort(test);
}
/**
* Decorate a test to use suite's default host and port,
* but assuming the server is already running.
*/
public static Test defaultExistingServerDecorator(Test test)
{
// As defaultServerDecorator but assuming
// server is already started.
// Need to have client
// and not running in J2ME (JSR169).
if (!(Derby.hasClient())
|| JDBC.vmSupportsJSR169())
{
return new BaseTestSuite(
"empty: no network server support in JSR169 " +
"(or derbyclient.jar missing).");
}
Test r =
new ServerSetup(test, DEFAULT_HOSTNAME, TestConfiguration.getCurrent().getPort());
((ServerSetup)r).setJDBCClient(JDBCClient.DERBYNETCLIENT);
return r;
}
/**
* Decorate a test to use suite's default host and port.
*/
public static Test defaultServerDecorator(Test test)
{
// Need to have network server and client and not
// running in J2ME (JSR169).
if (!supportsClientServer()) {
return new BaseTestSuite("empty: no network server support");
}
//
// This looks bogus to me. Shouldn't this get the hostname and port
// which are specific to this test run (perhaps overridden on the
// command line)?
//
return new ServerSetup(test, DEFAULT_HOSTNAME, TestConfiguration.getCurrent().getPort());
}
/**
* A variant of defaultServerDecorator allowing
* non-default hostname and portnumber.
*/
public static Test existingServerDecorator(Test test,
String hostName, int PortNumber)
{
// Need to have network server and client and not
// running in J2ME (JSR169).
if (!supportsClientServer()) {
return new BaseTestSuite("empty: no network server support");
}
Test r =
new ServerSetup(test, hostName, PortNumber);
((ServerSetup)r).setJDBCClient(JDBCClient.DERBYNETCLIENT);
return r;
}
/**
* A variant of defaultServerDecorator allowing
* non-default hostname, portnumber and database name.
*/
public static Test existingServerDecorator(Test test,
String hostName, int PortNumber, String dbPath)
{
// Need to have network server and client and not
// running in J2ME (JSR169).
if (!supportsClientServer()) {
return new BaseTestSuite("empty: no network server support");
}
Test r =
new ServerSetup(test, hostName, PortNumber);
((ServerSetup)r).setJDBCClient(JDBCClient.DERBYNETCLIENT);
((ServerSetup)r).setDbPath(dbPath);
return r;
}
/**
* Decorate a test to use suite's default host and Alternative port.
*/
public static Test defaultServerDecoratorWithAlternativePort(Test test) {
// Need to have network server and client and not
// running in J2ME (JSR169).
if (!supportsClientServer()) {
return new BaseTestSuite("empty: no network server support");
}
int port = getCurrent().getNextAvailablePort();
//
// This looks bogus to me. Shouldn't this get the hostname and port
// which are specific to this test run (perhaps overridden on the
// command line)?
//
return new ServerSetup(test, DEFAULT_HOSTNAME, port);
}
/**
* Check if client and server testing is supported in the test environment.
*/
private static boolean supportsClientServer() {
return JDBC.vmSupportsJDBC3() && Derby.hasClient() && Derby.hasServer();
}
/**
* Create a suite of test cases to run in a client/server environment. The
* returned test suite is not decorated with a ServerSetup.
*
* @param testClass the class from which to extract the test cases
* @return a test suite with all the test cases in {@code testClass}, or
* an empty test suite if client/server is not supported in the test
* environment
*/
private static Test bareClientServerSuite(Class testClass) {
BaseTestSuite suite =
new BaseTestSuite(suiteName(testClass) + ":client");
if (supportsClientServer()) {
suite.addTestSuite(testClass);
}
return suite;
}
/**
* Generate the unique database name for single use.
*/
public static synchronized String generateUniqueDatabaseName()
{
// Forward slash is ok, Derby treats database names
// as URLs and translates forward slash to the local
// separator.
String dbName = "singleUse/oneuse";
dbName = dbName.concat(Integer.toHexString(uniqueDB++));
return dbName;
}
/**
* Decorate a test to use a new database that is created upon the
* first connection request to the database and shutdown and deleted at
* tearDown. The configuration differs only from the current configuration
* by the list of used databases. The new database name
* is generated automatically as 'singleUse/oneuseXX' where 'XX' is
* the unique number. The generated database name is added at the end
* of <code>usedDbNames</code> and assigned as a default database name.
* This decorator expects the database file to be local so it
* can be removed.
* @param test Test to be decorated
* @return decorated test.
*/
public static TestSetup singleUseDatabaseDecorator(Test test)
{
String dbName = generateUniqueDatabaseName();
return new DatabaseChangeSetup(new DropDatabaseSetup(test, dbName), dbName, dbName, true);
}
/**
* Decorate a test to use a new database that is created upon the first
* connection request to the database and shutdown and deleted at
* tearDown. The configuration differs only from the current configuration
* by the list of used databases. The generated database name is added at
* the end of <code>usedDbNames</code> and assigned as a default database
* name. This decorator expects the database file to be local so it can be
* removed.
* @param test Test to be decorated
* @param dbName We sometimes need to know outside to be able to pass it on
* to other VMs/processes.
* @return decorated test.
*/
public static TestSetup singleUseDatabaseDecorator(Test test, String dbName)
{
return new DatabaseChangeSetup(
new DropDatabaseSetup(test, dbName), dbName, dbName, true);
}
/**
* Decorate a test to use a new database that is created upon the
* first connection request to the database and deleted at
* tearDown. In contrast to plain singleUseDatabaseDecorator, the
* database is expected to be shutdown by the test. The
* configuration differs only from the current configuration by
* the list of used databases. The new database name is generated
* automatically as 'singleUse/oneuseXX' where 'XX' is the unique
* number. The generated database name is added at the end of
* <code>usedDbNames</code> and assigned as a default database
* name. This decorator expects the database file to be local so
* it can be removed.
* @param test Test to be decorated
* @return decorated test.
*/
public static TestSetup singleUseDatabaseDecoratorNoShutdown(Test test)
{
String dbName = generateUniqueDatabaseName();
return new DatabaseChangeSetup(
new DropDatabaseSetup(test, dbName, false),
dbName, dbName, true);
}
/**
* Decorate a test to use a new database that is created upon the
* first connection request to the database and shutdown and deleted at
* tearDown. The configuration differs only from the current configuration
* by the list of used databases.
* The passed database name is mapped to the generated database
* name 'singleUse/oneuseXX' where 'XX' is the unique number.
* (by generateUniqueDatabaseName). The generated database name is added
* at the end of <code>usedDbNames</code>.
* This decorator expects the database file to be local so it
* can be removed.
* @param test Test to be decorated
* @param logicalDbName The logical database name. This name is used to identify
* the database in openConnection(String logicalDatabaseName) method calls.
* @return decorated test.
*/
public static DatabaseChangeSetup additionalDatabaseDecorator(Test test, String logicalDbName)
{
return new DatabaseChangeSetup(new DropDatabaseSetup(test, logicalDbName),
logicalDbName,
generateUniqueDatabaseName(),
false);
}
/**
* Similar to additionalDatabaseDecorator except the database will
* not be shutdown, only deleted. It is the responsibility of the
* test to shut it down.
*
* @param test Test to be decorated
* @param logicalDbName The logical database name. This name is
* used to identify the database in
* openConnection(String logicalDatabaseName)
* method calls.
* @return decorated test.
*/
public static DatabaseChangeSetup additionalDatabaseDecoratorNoShutdown(
Test test,
String logicalDbName)
{
return additionalDatabaseDecoratorNoShutdown( test, logicalDbName, false );
}
/**
* Similar to additionalDatabaseDecorator except the database will
* not be shutdown, only deleted. It is the responsibility of the
* test to shut it down.
*
* @param test Test to be decorated
* @param logicalDbName The logical database name. This name is
* used to identify the database in
* openConnection(String logicalDatabaseName)
* method calls.
* @param defaultDB True if the database should store its own name in its TestConfiguration.
* @return decorated test.
*/
public static DatabaseChangeSetup additionalDatabaseDecoratorNoShutdown
(
Test test,
String logicalDbName,
boolean defaultDB
)
{
return new DatabaseChangeSetup(
new DropDatabaseSetup(test, logicalDbName, false),
logicalDbName,
generateUniqueDatabaseName(),
defaultDB);
}
/**
* Similar to additionalDatabaseDecorator except the database will
* not be shutdown, only deleted. It is the responsibility of the
* test to shut it down.
*
* @param test Test to be decorated
* @param logicalDbName The logical database name. This name is
* used to identify the database in
* openConnection(String logicalDatabaseName)
* method calls.
* @param physicalDbName - Real database name on disk.
* @return decorated test.
*/
public static DatabaseChangeSetup additionalDatabaseDecoratorNoShutdown(
Test test,
String logicalDbName, String physicalDbName )
{
return new DatabaseChangeSetup(
new DropDatabaseSetup(test, logicalDbName, false),
logicalDbName,
physicalDbName,
false);
}
/**
* Decorate a test changing the default user name and password.
* Typically used along with DatabasePropertyTestSetup.builtinAuthentication.
* The tearDown method resets the default user and password value to
* their previous settings.
*
* @param test Test to decorate
* @param user New default user
* @param password New password
* @return decorated test
*
* @see DatabasePropertyTestSetup#builtinAuthentication(Test, String[], String)
*/
public static Test changeUserDecorator(Test test, String user, String password)
{
return new ChangeUserSetup(test, user, password);
}
/**
* Decorate a test to use the default database that has
* was created in SQL authorization mode.
* The tearDown reverts the configuration to the previous
* configuration.
*
* The database owner of this default SQL authorization mode
* database is TEST_DBO. This decorator sets the default user
* to be TEST_DBO.
*
* Tests can use this in conjunction with
* DatabasePropertyTestSetup.builtinAuthentication
* to set up BUILTIN authentication and changeUserDecorator
* to switch users. The database owner TEST_DBO must be included
* in the list of users provided to builtinAuthentication.
* This decorator must be the outer one in this mode.
* <code>
* test = DatabasePropertyTestSetup.builtinAuthentication(test,
new String[] {TEST_DBO,"U1","U2",},
"nh32ew");
test = TestConfiguration.sqlAuthorizationDecorator(test);
* </code>
* A utility version of sqlAuthorizationDecorator is provided
* that combines the two setups.
*
* @param test Test to be decorated
* @return decorated test.
*
* @see DatabasePropertyTestSetup#builtinAuthentication(Test, String[], String)
*/
public static Test sqlAuthorizationDecorator(Test test)
{
// Set the SQL authorization mode as a database property
// with a modified DatabasePropertyTestSetup that does not
// reset it.
final Properties sqlAuth = new Properties();
sqlAuth.setProperty("derby.database.sqlAuthorization", "true");
Test setSQLAuthMode = DatabasePropertyTestSetup.getNoTeardownInstance(
test, sqlAuth, true);
return changeUserDecorator(
new DatabaseChangeSetup(setSQLAuthMode, DEFAULT_DBNAME_SQL, DEFAULT_DBNAME_SQL, true),
DerbyConstants.TEST_DBO, "dummy"); // DRDA doesn't like empty pw
}
/**
* Same as sqlAuthorizationDecorator, except that the database is dropped
* at teardown and the test is responsible for shutting down the database.
*
* @param test Test to be decorated
* @return decorated test.
*
* @see TestConfiguration#sqlAuthorizationDecorator(Test test)
*/
public static Test sqlAuthorizationDecoratorSingleUse(Test test)
{
return sqlAuthorizationDecoratorSingleUse(
test, DEFAULT_DBNAME_SQL, false);
}
/**
* Same as sqlAuthorizationDecoratorSingleUse, except that you can name
* the database yourself, and you can choose whether or not the decorator
* should shut down the database before it attempts to drop it.
*
* @param test Test to be decorated
* @param dbName The name of the database to use in the test
* @param shutdownDatabase Whether or not to shut down the database
* before it is dropped
* @return decorated test.
*
* @see TestConfiguration#sqlAuthorizationDecorator(Test test)
*/
public static Test sqlAuthorizationDecoratorSingleUse(
Test test, String dbName, boolean shutdownDatabase)
{
// Set the SQL authorization mode as a database property
// with a modified DatabasePropertyTestSetup that does not
// reset it.
final Properties sqlAuth = new Properties();
sqlAuth.setProperty("derby.database.sqlAuthorization", "true");
Test setSQLAuthMode = DatabasePropertyTestSetup.getNoTeardownInstance(
test, sqlAuth, true);
setSQLAuthMode = new DropDatabaseSetup(
setSQLAuthMode, dbName, shutdownDatabase);
setSQLAuthMode = new DatabaseChangeSetup
( setSQLAuthMode, dbName, dbName, true );
return changeUserDecorator(setSQLAuthMode,
DerbyConstants.TEST_DBO,
"dummy"); // DRDA doesn't like empty pw
}
/**
* Utility version of sqlAuthorizationDecorator that also sets
* up authentication. A combination of
* DatabasePropertyTestSetup.builtinAuthentication wrapped in
* sqlAuthorizationDecorator.
* <BR>
* The database owner of this default SQL authorization mode
* database is TEST_DBO. This decorator sets the default user
* to be TEST_DBO.
* <BR>
* Assumption is that no authentication is enabled on the default
* SQL authorization database on entry.
*
* @param users Set of users excluding the database owner, that will
* be added by this decorator.
*/
public static Test sqlAuthorizationDecorator(Test test,
String[] users, String passwordToken)
{
String[] usersWithDBO = new String[users.length + 1];
usersWithDBO[0] = DerbyConstants.TEST_DBO;
System.arraycopy(users, 0, usersWithDBO, 1, users.length);
return sqlAuthorizationDecorator(
DatabasePropertyTestSetup.builtinAuthentication(test,
usersWithDBO, passwordToken));
}
/**
* Return a decorator that changes the configuration to obtain
* connections from a ConnectionPoolDataSource using
* <code>getPooledConnection().getConnection()</code>
* <p>
* Note that statement pooling is enabled in the data source and in all the
* connections created from it.
* <p>
* The tearDown reverts the configuration to the previous
* configuration.
*
* @param test the test/suite to decorate
* @return A test setup with the requested decorator.
*/
public static Test connectionCPDecorator(Test test)
{
if (JDBC.vmSupportsJDBC3()) {
return new ConnectorSetup(test,
"org.apache.derbyTesting.junit.ConnectionPoolDataSourceConnector");
} else {
return new BaseTestSuite("ConnectionPoolDataSource not supported");
}
}
/**
* Return a decorator that changes the configuration to obtain
* connections from an XADataSource using
* <code>
* getXAConnection().getConnection()
* </code>
* The connection is not connected to any global transaction,
* thus it is in local connection mode.
* The tearDown reverts the configuration to the previous
* configuration.
*/
public static Test connectionXADecorator(Test test)
{
if (JDBC.vmSupportsJDBC3()) {
return new ConnectorSetup(test,
"org.apache.derbyTesting.junit.XADataSourceConnector");
} else {
return new BaseTestSuite("XADataSource not supported");
}
}
/**
* Return a decorator that changes the configuration to obtain
* connections from a standard DataSource using
* <code>
* getConnection()
* </code>
* The tearDown reverts the configuration to the previous
* configuration.
*/
public static TestSetup connectionDSDecorator(Test test)
{
return new ConnectorSetup(test,
"org.apache.derbyTesting.junit.DataSourceConnector");
}
/**
* Returns a decorator that forces the JDBC 3 embedded client in
* a Java SE 6/JDBC 4 environment. The only difference is that
* the DataSource class names will be the "old" JDBC 3 versions
* and not the JDBC 4 specific ones.
* that
* @param test
*/
public static Test forceJDBC3Embedded(Test test)
{
if (JDBC.vmSupportsJDBC4()) {
test = new JDBCClientSetup(test, JDBCClient.EMBEDDED_30);
}
return test;
}
/**
* Returns a decorator that forces the JDBC 3 network client in
* a Java SE 6/JDBC 4 environment. The only difference is that
* the DataSource class names will be the "old" JDBC 3 versions
* and not the JDBC 4 specific ones.
*
* Assumption is that the received Test is an instance of ServerSetup,
* which is the decorator for client server tests. If that is not
* the case then this method is a no-op.
*
* @param test Test around which to wrap the JDBC 3 network client
* configuration.
*/
public static Test forceJDBC3NetClient(Test test)
{
if (JDBC.vmSupportsJDBC4() && (test instanceof ServerSetup))
((ServerSetup)test).setJDBCClient(JDBCClient.DERBYNETCLIENT_30);
return test;
}
/**
* Decorate a test changing the default ssl mode.
* The tearDown method resets the default user and password value to
* their previous settings.
*
* @param test Test to decorate
* @param ssl New ssl mode
* @return decorated test
*/
public static Test changeSSLDecorator(Test test, String ssl)
{
return new ChangeSSLSetup(test, ssl);
}
/**
* Default embedded configuration
*
*/
private TestConfiguration() {
// Check for possibly passed in DatabaseName
// this is used in OCRecoveryTest
String propDefDbName = getSystemProperties().getProperty(
"derby.tests.defaultDatabaseName");
if (propDefDbName != null)
this.defaultDbName = propDefDbName;
else
this.defaultDbName=DEFAULT_DBNAME;
usedDbNames.add(DEFAULT_DBNAME);
logicalDbMapping.put(DEFAULT_DBNAME, DEFAULT_DBNAME);
this.userName = DEFAULT_USER_NAME;
this.userPassword = DEFAULT_USER_PASSWORD;
this.connectionAttributes = new Properties();
this.hostName = DEFAULT_HOSTNAME;
this.port = basePort;
this.isVerbose = Boolean.valueOf(
getSystemProperties().getProperty(KEY_VERBOSE)).
booleanValue();
this.doTrace = Boolean.valueOf(
getSystemProperties().getProperty(KEY_TRACE)).
booleanValue();
this.stopAfterFirstFail = Boolean.valueOf(
getSystemProperties().getProperty(KEY_STOP_AFTER_FIRST_FAIL)).
booleanValue();
this.jdbcClient = JDBCClient.getDefaultEmbedded();
this.ssl = null;
this.jmxPort = getNextAvailablePort();
println("basePort=" + basePort + ", bogusPort=" + bogusPort +
", jmxPort=" + jmxPort);
url = createJDBCUrlWithDatabaseName(defaultDbName);
initConnector(null);
}
/**
* Obtain a new configuration identical to the passed one.
*/
TestConfiguration(TestConfiguration copy)
{
this.defaultDbName = copy.defaultDbName;
this.usedDbNames.addAll(copy.usedDbNames);
logicalDbMapping.putAll(copy.logicalDbMapping);
this.userName = copy.userName;
this.userPassword = copy.userPassword;
this.connectionAttributes = new Properties(copy.connectionAttributes);
this.isVerbose = copy.isVerbose;
this.doTrace = copy.doTrace;
this.port = copy.port;
this.jmxPort = copy.jmxPort;
this.jdbcClient = copy.jdbcClient;
this.hostName = copy.hostName;
this.ssl = copy.ssl;
this.url = copy.url;
initConnector(copy.connector);
}
TestConfiguration(TestConfiguration copy, JDBCClient client,
String hostName, int port)
{
this.defaultDbName = copy.defaultDbName;
this.usedDbNames.addAll(copy.usedDbNames);
logicalDbMapping.putAll(copy.logicalDbMapping);
this.userName = copy.userName;
this.userPassword = copy.userPassword;
this.connectionAttributes = new Properties(copy.connectionAttributes);
this.isVerbose = copy.isVerbose;
this.doTrace = copy.doTrace;
this.port = port;
this.jmxPort = copy.jmxPort;
if (bogusPort == port) {
throw new IllegalStateException(
"port cannot equal bogusPort: " + bogusPort);
}
this.jdbcClient = client;
this.hostName = hostName;
this.ssl = copy.ssl;
this.url = createJDBCUrlWithDatabaseName(defaultDbName);
initConnector(copy.connector);
}
TestConfiguration(TestConfiguration copy, JDBCClient client,
String hostName, int port, String dataBasePath)
{
this.defaultDbName = dataBasePath;
this.usedDbNames.addAll(copy.usedDbNames);
logicalDbMapping.putAll(copy.logicalDbMapping);
this.userName = copy.userName;
this.userPassword = copy.userPassword;
this.connectionAttributes = new Properties(copy.connectionAttributes);
this.isVerbose = copy.isVerbose;
this.doTrace = copy.doTrace;
this.port = port;
this.jmxPort = copy.jmxPort;
if (bogusPort == port) {
throw new IllegalStateException(
"port cannot equal bogusPort: " + bogusPort);
}
this.jdbcClient = client;
this.hostName = hostName;
this.ssl = copy.ssl;
this.url = createJDBCUrlWithDatabaseName(defaultDbName);
initConnector(copy.connector);
}
/**
* Obtain a new configuration identical to the passed in
* one except for the default user and password.
* @param copy Configuration to copy.
* @param user New default user
* @param password New default password.
*/
TestConfiguration(TestConfiguration copy, String user,
String password, String passwordToken)
{
this.defaultDbName = copy.defaultDbName;
this.usedDbNames.addAll(copy.usedDbNames);
logicalDbMapping.putAll(copy.logicalDbMapping);
this.userName = user;
this.userPassword = password;
this.passwordToken = passwordToken == null ?
copy.passwordToken : passwordToken;
this.connectionAttributes = new Properties(copy.connectionAttributes);
this.isVerbose = copy.isVerbose;
this.doTrace = copy.doTrace;
this.port = copy.port;
this.jmxPort = copy.jmxPort;
this.jdbcClient = copy.jdbcClient;
this.hostName = copy.hostName;
this.ssl = copy.ssl;
this.url = copy.url;
initConnector(copy.connector);
}
/**
* Obtains a new configuration identical to the passed in one, except for
* the default SSL mode.
* <p>
* The modes supported at the moment are <tt>basic</tt> and <tt>off</tt>.
* The mode <tt>peerAuthentication</tt> is not yet supported.
*
* @param copy configuration to copy
* @param ssl default SSL mode
*/
TestConfiguration(TestConfiguration copy, String ssl)
{
this(copy);
this.ssl = ssl;
}
/**
* Obtain a new configuration identical to the passed in
* one except for the database name. The passed database name
* is added at the end of the list of used databases.
* If the <code>defaulDb</code> parameter is <code>true</code>
* the new database name is used as a default database.
* @param copy Configuration to copy.
* @param dbName New database name
* @param defaultDb Indicates that the passed <code>dbName</code> is supposed
* to be used as the default database name.
*/
TestConfiguration(TestConfiguration copy, String logicalDbName,
String dbName, boolean defaultDb)
{
this.usedDbNames.addAll(copy.usedDbNames);
this.usedDbNames.add(dbName);
logicalDbMapping.putAll(copy.logicalDbMapping);
// Can not use the same logical name for different database.
// If this assert will make failures it might be safely removed
// since having more physical databases accessible throught the same
// logical database name will access only the last physical database
Assert.assertNull(logicalDbMapping.put(logicalDbName, dbName));
if (defaultDb) {
this.defaultDbName = dbName;
} else {
this.defaultDbName = copy.defaultDbName;
}
this.userName = copy.userName;
this.userPassword = copy.userPassword;
this.connectionAttributes = new Properties(copy.connectionAttributes);
this.isVerbose = copy.isVerbose;
this.doTrace = copy.doTrace;
this.port = copy.port;
this.jmxPort = copy.jmxPort;
this.jdbcClient = copy.jdbcClient;
this.hostName = copy.hostName;
this.ssl = copy.ssl;
this.url = createJDBCUrlWithDatabaseName(this.defaultDbName);
initConnector(copy.connector);
}
/**
* This constructor creates a TestConfiguration from a Properties object.
*
* @throws NumberFormatException if the port specification is not an integer.
*/
private TestConfiguration(Properties props)
throws NumberFormatException {
defaultDbName = props.getProperty(KEY_DBNAME, DEFAULT_DBNAME);
usedDbNames.add(defaultDbName);
logicalDbMapping.put(defaultDbName, defaultDbName);
userName = props.getProperty(KEY_USER_NAME, DEFAULT_USER_NAME);
userPassword = props.getProperty(KEY_USER_PASSWORD,
DEFAULT_USER_PASSWORD);
connectionAttributes = new Properties();
hostName = props.getProperty(KEY_HOSTNAME, DEFAULT_HOSTNAME);
isVerbose = Boolean.valueOf(props.getProperty(KEY_VERBOSE)).booleanValue();
doTrace = Boolean.valueOf(props.getProperty(KEY_TRACE)).booleanValue();
port = basePort;
jmxPort = getNextAvailablePort();
println("basePort=" + basePort + ", bogusPort=" + bogusPort +
", jmxPort=" + jmxPort);
ssl = props.getProperty(KEY_SSL);
String framework = props.getProperty(KEY_FRAMEWORK, DEFAULT_FRAMEWORK);
if ("DerbyNetClient".equals(framework)) {
jdbcClient = JDBCClient.DERBYNETCLIENT;
} else if ("DerbyNet".equals(framework)) {
jdbcClient = JDBCClient.DB2CLIENT;
} else {
jdbcClient = JDBCClient.getDefaultEmbedded();
}
url = createJDBCUrlWithDatabaseName(defaultDbName);
initConnector(null);
}
/**
* Create a copy of this configuration with some additional connection
* attributes.
*
* @param attrs the extra connection attributes
* @return a copy of the configuration with extra attributes
*/
TestConfiguration addConnectionAttributes(Properties attrs) {
TestConfiguration copy = new TestConfiguration(this);
Enumeration e = attrs.propertyNames();
while (e.hasMoreElements()) {
String key = (String) e.nextElement();
String val = attrs.getProperty(key);
copy.connectionAttributes.setProperty(key, val);
}
copy.initConnector(connector);
return copy;
}
/**
* Get the system properties in a privileged block.
*
* @return the system properties.
*/
public static final Properties getSystemProperties() {
// Fetch system properties in a privileged block.
return AccessController.doPrivileged(
new PrivilegedAction<Properties>() {
public Properties run() {
return System.getProperties();
}
});
}
/**
* Create JDBC connection url, including the name of the database.
*
* @return JDBC connection url, without attributes.
*/
private String createJDBCUrlWithDatabaseName(String name) {
if (JDBC.vmSupportsJDBC3())
{
String url;
if (jdbcClient.isEmbedded()) {
url = jdbcClient.getUrlBase();
} else {
url = jdbcClient.getUrlBase() + hostName + ":" + port + "/";
}
return url.concat(name);
}
// No DriverManager support so no URL support.
return null;
}
/**
* Initialize the connection factory.
* Defaults to the DriverManager implementation
* if running JDBC 2.0 or higher, otherwise a
* DataSource implementation for JSR 169.
*
*/
private void initConnector(Connector oldConnector)
{
if (oldConnector != null)
{
// Use the same type of connector as the
// configuration we are copying from.
try {
Class<?> clazz = Class.forName(oldConnector.getClass().getName());
connector = (Connector) clazz.getConstructor().newInstance();
} catch (Exception e) {
Assert.fail(e.getMessage());
}
}
else if (JDBC.vmSupportsJDBC3())
{
try {
Class<?> clazz = Class.forName("org.apache.derbyTesting.junit.DriverManagerConnector");
connector = (Connector) clazz.getConstructor().newInstance();
} catch (Exception e) {
Assert.fail(e.getMessage());
}
} else {
connector = new DataSourceConnector();
}
connector.setConfiguration(this);
try {
String loginTimeoutString = BaseTestCase.getSystemProperty( KEY_LOGIN_TIMEOUT );
if ( loginTimeoutString != null )
{
int loginTimeout = Integer.parseInt( loginTimeoutString );
connector.setLoginTimeout( loginTimeout );
}
}
catch (Exception e) { Assert.fail(e.getMessage()); }
}
/**
* Get configured JDBCClient object.
*
* @return JDBCClient
*/
public JDBCClient getJDBCClient() {
return jdbcClient;
}
/**
* <p>
* Return the jdbc url for connecting to the default database.
* </p>
*
* <p>
* The returned URL does not include the connection attributes. These must
* either be appended to the URL when connecting, or they must be passed
* as a {@code Properties} object to {@code DriverManager.getConnection()}.
* </p>
*
* @return JDBC url.
*/
public String getJDBCUrl() {
return url;
}
/**
* Return the jdbc url for a connecting to the database.
*
* @param databaseName name of database.
* @return JDBC connection url, including database name.
*/
public String getJDBCUrl(String databaseName) {
return createJDBCUrlWithDatabaseName(databaseName);
}
/**
* Return the default database name.
*
* @return default database name.
*/
public String getDefaultDatabaseName() {
return defaultDbName;
}
/**
* Return the physical name for a database
* given its logical name.
*
* @return Physical name of the database.
*/
public String getPhysicalDatabaseName(String logicalName) {
return (String) logicalDbMapping.get(logicalName);
}
/**
* Return the user name.
*
* @return user name.
*/
public String getUserName() {
return userName;
}
/**
* Return the user password.
*
* @return user password.
*/
public String getUserPassword() {
return userPassword;
}
/**
* Return the connection attributes to use in this configuration. The
* attributes won't contain user name or password. Use
* {@link #getUserName()} or {@link #getUserPassword()} instead to
* retrieve those attributes.
*
* @return connection attributes (never {@code null})
*/
public Properties getConnectionAttributes() {
return connectionAttributes;
}
/**
* Get a flat string representation of the connection attributes. To
* be used in the connectionAttributes property of a data source.
*
* @return all connection attributes concatenated ({@code null} if there
* are no attributes)
*/
String getConnectionAttributesString() {
StringBuffer sb = new StringBuffer();
Enumeration e = connectionAttributes.propertyNames();
boolean first = true;
while (e.hasMoreElements()) {
if (!first) {
sb.append(';');
}
String key = (String) e.nextElement();
sb.append(key);
sb.append('=');
sb.append(connectionAttributes.getProperty(key));
first = false;
}
if (first) {
// No connection attributes.
return null;
}
return sb.toString();
}
/**
* Return the host name for the network server.
*
* @return host name.
*/
public String getHostName() {
return hostName;
}
/**
* Return if the base port is default or not.
*
* @return true if base port is default.
*/
public static boolean isDefaultBasePort() {
return (basePort == DEFAULT_PORT);
}
public static int getBasePort() {
return basePort;
}
/**
* Get port number for network server.
*
* @return port number.
*/
public int getPort() {
return port;
}
/**
* Get the next available port. This method is multi-purposed.
* It can be used for alternative servers and also for JMX and replication.
*
* @return port number.
*/
public int getNextAvailablePort() {
/* We want to crash. If you are reading this, you have to increment
* the MAX_PORTS_USED constant and to edit the wiki page relative to
* concurrent test running */
if (assignedPortCount+1 > MAX_PORTS_USED) {
Assert.fail("Port "+(lastAssignedPort+1)+" exceeeds expected maximum. " +
"You may need to update TestConfiguration.MAX_PORTS_USED and "+
"the Wiki page at http://wiki.apache.org/db-derby/DerbyJUnitTesting "+
"if test runs now require more available ports");
}
int possiblePort = lastAssignedPort + 1;
assignedPortCount++;
lastAssignedPort = possiblePort;
return possiblePort;
}
/**
* Gets the value of the port number that may be used for "remote"
* JMX monitoring and management.
* @return the port number on which the JMX MBean server is listening for
* connections
*/
public int getJmxPort() {
return jmxPort;
}
/**
* Returns a port number where no Derby network servers are supposed to
* be running.
*
* @return A port number where no Derby network servers are started.
*/
public int getBogusPort() {
return bogusPort;
}
/**
* Get ssl mode for network server
*
* @return ssl mode
*/
public String getSsl() {
return ssl;
}
/**
* Open connection to the default database.
* If the database does not exist, it will be created.
* A default username and password will be used for the connection.
*
* @return connection to default database.
*/
public Connection openDefaultConnection()
throws SQLException {
return connector.openConnection();
}
/**
* Open connection to the default database.
* If the database does not exist, it will be created.
*
* @return connection to default database.
*/
Connection openDefaultConnection(String user, String password)
throws SQLException {
return connector.openConnection(user, password);
}
/**
* Open connection to the specified database.
* If the database does not exist, it will be created.
* A default username and password will be used for the connection.
* Requires that the test has been decorated with
* additionalDatabaseDecorator with the matching name.
* The physical database name may differ.
* @param logicalDatabaseName A logical database name as passed
* to <code>additionalDatabaseDecorator</code> function.
* @return connection to specified database.
*/
Connection openConnection(String logicalDatabaseName)
throws SQLException
{
return connector.openConnection( getAndVetPhysicalDatabaseName( logicalDatabaseName ) );
}
private String getAndVetPhysicalDatabaseName( String logicalDatabaseName )
throws SQLException
{
String databaseName = getPhysicalDatabaseName( logicalDatabaseName );
if ( usedDbNames.contains(databaseName) ) { return databaseName; }
else
{
throw new SQLException("Database name \"" + logicalDatabaseName
+ "\" is not in a list of used databases."
+ "Use method TestConfiguration.additionalDatabaseDecorator first.");
}
}
/**
* Open connection to the specified database using the supplied username and password.
* If the database does not exist, it will be created.
* Requires that the test has been decorated with
* additionalDatabaseDecorator with the matching name.
* The physical database name may differ.
* @param logicalDatabaseName A logical database name as passed
* to <code>additionalDatabaseDecorator</code> function.
* @return connection to specified database.
*/
public Connection openConnection( String logicalDatabaseName, String user, String password )
throws SQLException
{
return connector.openConnection
(
getAndVetPhysicalDatabaseName( logicalDatabaseName ),
user,
password
);
}
/**
* Open connection to the specified database using the supplied username and password.
* Treat the database name as a physical database name rather than as a logical name
* which needs to be mapped.
* If the database does not exist, it will be created.
* Requires that the test has been decorated with
* additionalDatabaseDecorator with the matching name.
* @param physicalDatabaseName The real database name to use.
* @param user name of user
* @param password password of user
* @param props extra properties to pass to the connection
* @return connection to specified database.
*/
public Connection openPhysicalConnection( String physicalDatabaseName, String user, String password, Properties props )
throws SQLException
{
return connector.openConnection
(
physicalDatabaseName,
user,
password,
props
);
}
/**
* Shutdown the database for this configuration
* assuming it is booted.
*
*/
public void shutdownDatabase()
{
try {
connector.shutDatabase();
Assert.fail("Database failed to shut down");
} catch (SQLException e) {
BaseJDBCTestCase.assertSQLState("Database shutdown", "08006", e);
}
}
/**
* Shutdown the engine for this configuration
* assuming it is booted.
* This method can only be called when the engine
* is running embedded in this JVM.
*
*/
public void shutdownEngine()
{
try {
connector.shutEngine(true);
Assert.fail("Engine failed to shut down");
} catch (SQLException e) {
BaseJDBCTestCase.assertSQLState("Engine shutdown", "XJ015", e);
}
}
/**
* Shutdown the engine for this configuration
* assuming it is booted.
* This method can only be called when the engine
* is running embedded in this JVM.
*
* @param deregisterDeriver if true, deregister the driver
*/
public void shutdownEngine(boolean deregisterDeriver)
{
try {
connector.shutEngine(deregisterDeriver);
Assert.fail("Engine failed to shut down");
} catch (SQLException e) {
BaseJDBCTestCase.assertSQLState("Engine shutdown", "XJ015", e);
}
}
/** Get the login timeout from the connector */
public int getLoginTimeout() throws SQLException
{
return connector.getLoginTimeout();
}
/**
* Set the login timeout for the connector.
* @param seconds the login timeout in seconds
* @throws SQLException if the timeout cannot be set
*/
public void setLoginTimeout(int seconds) throws SQLException {
connector.setLoginTimeout(seconds);
}
public void waitForShutdownComplete(String physicalDatabaseName) {
String path = getDatabasePath(physicalDatabaseName);
boolean lockfilepresent = true;
int timeout = LOCKFILETIMEOUT; // 5 mins
int totalsleep = 0;
File lockfile = new File (path + File.separatorChar + "db.lck");
File exlockfile = new File (path + File.separatorChar + "dbex.lck");
while (lockfilepresent) {
if (totalsleep >= timeout)
{
System.out.println("TestConfigruation.waitForShutdownComplete: " +
"been looping waiting for lock files to be deleted for at least 5 minutes, giving up");
break;
}
if (lockfile.exists() || exlockfile.exists())
{
// TODO: is it interesting to know whether db.lck or dbex.lck or both is still present?
try {
System.out.println("TestConfiguration.waitForShutdownComplete: " +
"db*.lck files not deleted after " + totalsleep + " ms.");
Thread.sleep(1000);
totalsleep=totalsleep+1000;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
else
lockfilepresent=false;
}
}
/**
* stops the Network server for this configuration.
*
*/
public void stopNetworkServer() {
try {
NetworkServerControlWrapper networkServer =
new NetworkServerControlWrapper();
networkServer.shutdown();
if (serverOutput != null) {
serverOutput.close();
}
} catch(Exception e) {
SQLException se = new SQLException("Error shutting down server");
se.initCause(e);
}
}
/**
* starts the Networs server for this configuration.
*
*/
public void startNetworkServer() throws SQLException
{
Exception failException = null;
try {
NetworkServerControlWrapper networkServer =
new NetworkServerControlWrapper();
serverOutput = AccessController.doPrivileged(
new PrivilegedAction<FileOutputStream>() {
public FileOutputStream run() {
File logs = new File("logs");
logs.mkdir();
File console = new File(logs, "serverConsoleOutput.log");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(console.getPath(), true);
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
return fos;
}
});
networkServer.start(new PrintWriter(serverOutput));
// Wait for the network server to start
boolean started = false;
int retries = 10; // Max retries = max seconds to wait
while (!started && retries > 0) {
try {
// Sleep 1 second and then ping the network server
Thread.sleep(SLEEP_TIME);
networkServer.ping();
// If ping does not throw an exception the server has started
started = true;
} catch(Exception e) {
retries--;
failException = e;
}
}
// Check if we got a reply on ping
if (!started) {
throw failException;
}
} catch (Exception e) {
SQLException se = new SQLException("Error starting network server");
se.initCause(failException);
throw se;
}
}
/**
* Set the verbosity, i.e., whether debug statements print.
*/
public void setVerbosity( boolean isChatty ) { isVerbose = isChatty; }
/**
* Set JUnit test method tracing.
*/
public void setTrace( boolean isChatty ) { doTrace = isChatty; }
/**
* Return verbose flag.
*
* @return verbose flag.
*/
public boolean isVerbose() {
return isVerbose;
}
/**
* Private method printing debug information to standard out if debugging
* is enabled.
* <p>
* <em>Note:</em> This method may direct output to a different location
* than the println method in <tt>BaseJDBCTestCase</tt>.
*/
private void println(CharSequence msg) {
if (isVerbose) {
System.out.println("DEBUG: {TC@" + hashCode() + "} " + msg);
}
}
/**
* Return JUnit test method trace flag.
*
* @return JUnit test method trace flag.
*/
public boolean doTrace() {
return doTrace;
}
public boolean stopAfterFirstFail() {
return stopAfterFirstFail;
}
/**
* <p>
* Return true if we classes are being loaded from jar files. For the time
* being, this simply tests that the JVMInfo class (common to the client and
* the server) comes out of a jar file.
* </p>
*/
public static boolean loadingFromJars()
{
return SecurityManagerSetup.isJars;
}
/**
* Returns true if this JUnit test being run by the old harness.
* Temp method to ease the switch over by allowing
* suites to alter their behaviour based upon the
* need to still run under the old harness.
*/
//public static boolean runningInDerbyHarness()
//{
// return runningInDerbyHarness;
//}
/**
* Get a folder already created where a test can
* write its failure information. The name of the folder,
* relative to ${user.dir} is:
* <BR>
* <code>
* fail/client/testclass/testname
* <code>
* <UL>
* <LI> client - value of JDBCClient.getName() for the test's configuration
* <LI> testclass - last element of the class name
* <LI> testname - value of test.getName()
* </UL>
*/
File getFailureFolder(TestCase test){
StringBuffer sb = new StringBuffer();
sb.append("fail");
sb.append(File.separatorChar);
sb.append(getJDBCClient().getName());
sb.append(File.separatorChar);
String className = test.getClass().getName();
int lastDot = className.lastIndexOf('.');
if (lastDot != -1)
className = className.substring(lastDot+1, className.length());
sb.append(className);
sb.append(File.separatorChar);
// DERBY-5620: Ensure valid file name.
char[] tmpName = test.getName().toCharArray();
for (int i=0; i < tmpName.length; i++) {
switch (tmpName[i]) {
case '-':
case '_':
continue;
default:
if (!Character.isLetterOrDigit(tmpName[i])) {
tmpName[i] = '_';
}
}
}
sb.append(tmpName);
String base = sb.toString().intern();
final File folder = new File(base);
// Create the folder
// TODO: Dump this configuration in some human readable format
synchronized (base) {
AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
public Boolean run() {
if (folder.exists()) {
// do something
}
return folder.mkdirs();
}
});
}
return folder;
}
/*
* Immutable data members in test configuration
*/
/** The default database name for tests. */
private final String defaultDbName;
/** Holds the names of all other databases used in a test to perform a proper cleanup.
* The <code>defaultDbName</code> is also contained here. */
private final ArrayList<String> usedDbNames = new ArrayList<String>();
/** Contains the mapping of logical database names to physical database names. */
private final HashMap<String, String> logicalDbMapping = new HashMap<String, String>();
private final String url;
private final String userName;
private final String userPassword;
private final int port;
private final String hostName;
private final JDBCClient jdbcClient;
private final int jmxPort;
private boolean isVerbose;
private boolean doTrace;
private boolean stopAfterFirstFail;
private String ssl;
/**
* Extra connection attributes. Not for user name and password, use the
* fields {@link #userName} and {@link #userPassword} for those attributes.
*/
private Properties connectionAttributes;
/**
* Password token used by the builtin authentication decorators.
* Default simple scheme is the password is a function
* of the user and a password token. password token
* is set by DatabasePropertyTestSetup.builtinAuthentication
*/
private String passwordToken = "";
/**
* Indirection for obtaining connections based upon
* this configuration.
*/
Connector connector;
/*
* SecurityManager related configuration.
*/
/**
* Install the default security manager setup,
* for the current configuration.
* @throws PrivilegedActionException
*/
boolean defaultSecurityManagerSetup() {
// Testing with the DB2 client has not been performed
// under the security manager since it's not part
// of Derby so no real interest in tracking down issues.
if (jdbcClient.isDB2Client()) {
SecurityManagerSetup.noSecurityManager();
return false;
} else {
if (SecurityManagerSetup.NO_POLICY.equals(
BaseTestCase.getSystemProperty("java.security.policy")))
{
// Explict setting of no security manager
return false;
}
SecurityManagerSetup.installSecurityManager();
return true;
}
}
/*
** BUILTIN password handling.
*/
/**
* Get the password that is a function of the user
* name and the passed in token.
*/
static final String getPassword(String user, String token)
{
return user.concat(token);
}
/**
* Get the password that is a function of the user
* name and the token for the current configuration.
*/
public final String getPassword(String user)
{
return getPassword(user, passwordToken);
}
public final String getDatabasePath(String physicalDatabaseName)
{
String dbName = physicalDatabaseName.replace('/', File.separatorChar);
String dsh = BaseTestCase.getSystemProperty("derby.system.home");
if (dsh == null) {
Assert.fail("not implemented");
} else {
dbName = dsh + File.separator + dbName;
}
return dbName;
}
}
|