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 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320
|
/*
* 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.util.descriptor.web;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collection;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
import jakarta.servlet.DispatcherType;
import jakarta.servlet.ServletContext;
import jakarta.servlet.SessionTrackingMode;
import jakarta.servlet.descriptor.JspConfigDescriptor;
import jakarta.servlet.descriptor.JspPropertyGroupDescriptor;
import jakarta.servlet.descriptor.TaglibDescriptor;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.apache.tomcat.util.buf.B2CConverter;
import org.apache.tomcat.util.buf.UDecoder;
import org.apache.tomcat.util.descriptor.XmlIdentifiers;
import org.apache.tomcat.util.digester.DocumentProperties;
import org.apache.tomcat.util.res.StringManager;
import org.apache.tomcat.util.security.Escape;
/**
* Representation of common elements of web.xml and web-fragment.xml. Provides a repository for parsed data before the
* elements are merged. Validation is spread between multiple classes: The digester checks for structural correctness
* (e.g. single login-config) This class checks for invalid duplicates (e.g. filter/servlet names) StandardContext will
* check validity of values (e.g. URL formats etc)
*/
public class WebXml extends XmlEncodingBase implements DocumentProperties.Charset {
protected static final String ORDER_OTHERS = "org.apache.catalina.order.others";
private static final StringManager sm = StringManager.getManager(Constants.PACKAGE_NAME);
private final Log log = LogFactory.getLog(WebXml.class); // must not be static
/**
* Global defaults are overridable but Servlets and Servlet mappings need to be unique. Duplicates normally trigger
* an error. This flag indicates if newly added Servlet elements are marked as overridable.
*/
private boolean overridable = false;
public boolean isOverridable() {
return overridable;
}
public void setOverridable(boolean overridable) {
this.overridable = overridable;
}
/*
* Ideally, fragment names will be unique. If they are not, Tomcat needs to know as the action that the
* specification requires (see 8.2.2 1.e and 2.c) varies depending on the ordering method used.
*/
private final List<String> duplicates = new ArrayList<>();
public boolean isDuplicated() {
return !duplicates.isEmpty();
}
public void addDuplicate(String duplicate) {
this.duplicates.add(duplicate);
}
public List<String> getDuplicates() {
return new ArrayList<>(this.duplicates);
}
/**
* web.xml only elements Absolute Ordering
*/
private Set<String> absoluteOrdering = null;
public void createAbsoluteOrdering() {
if (absoluteOrdering == null) {
absoluteOrdering = new LinkedHashSet<>();
}
}
public void addAbsoluteOrdering(String fragmentName) {
createAbsoluteOrdering();
absoluteOrdering.add(fragmentName);
}
public void addAbsoluteOrderingOthers() {
createAbsoluteOrdering();
absoluteOrdering.add(ORDER_OTHERS);
}
public Set<String> getAbsoluteOrdering() {
return absoluteOrdering;
}
/**
* web-fragment.xml only elements Relative ordering
*/
private final Set<String> after = new LinkedHashSet<>();
public void addAfterOrdering(String fragmentName) {
after.add(fragmentName);
}
public void addAfterOrderingOthers() {
if (before.contains(ORDER_OTHERS)) {
throw new IllegalArgumentException(sm.getString("webXml.multipleOther"));
}
after.add(ORDER_OTHERS);
}
public Set<String> getAfterOrdering() {
return after;
}
private final Set<String> before = new LinkedHashSet<>();
public void addBeforeOrdering(String fragmentName) {
before.add(fragmentName);
}
public void addBeforeOrderingOthers() {
if (after.contains(ORDER_OTHERS)) {
throw new IllegalArgumentException(sm.getString("webXml.multipleOther"));
}
before.add(ORDER_OTHERS);
}
public Set<String> getBeforeOrdering() {
return before;
}
// Common elements and attributes
// Required attribute of web-app element
public String getVersion() {
StringBuilder sb = new StringBuilder(3);
sb.append(majorVersion);
sb.append('.');
sb.append(minorVersion);
return sb.toString();
}
/**
* Set the version for this web.xml file
*
* @param version Values of <code>null</code> will be ignored
*/
public void setVersion(String version) {
if (version == null) {
return;
}
switch (version) {
case "2.4":
majorVersion = 2;
minorVersion = 4;
break;
case "2.5":
majorVersion = 2;
minorVersion = 5;
break;
case "3.0":
majorVersion = 3;
minorVersion = 0;
break;
case "3.1":
majorVersion = 3;
minorVersion = 1;
break;
case "4.0":
majorVersion = 4;
minorVersion = 0;
break;
case "5.0":
majorVersion = 5;
minorVersion = 0;
break;
case "6.0":
majorVersion = 6;
minorVersion = 0;
break;
case "6.1":
majorVersion = 6;
minorVersion = 1;
break;
default:
log.warn(sm.getString("webXml.version.unknown", version));
}
}
// Optional publicId attribute
private String publicId = null;
public String getPublicId() {
return publicId;
}
public void setPublicId(String publicId) {
// Update major and minor version
if (publicId == null) {
return;
}
switch (publicId) {
case XmlIdentifiers.WEB_22_PUBLIC:
majorVersion = 2;
minorVersion = 2;
this.publicId = publicId;
break;
case XmlIdentifiers.WEB_23_PUBLIC:
majorVersion = 2;
minorVersion = 3;
this.publicId = publicId;
break;
default:
log.warn(sm.getString("webXml.unrecognisedPublicId", publicId));
break;
}
}
// Optional metadata-complete attribute
private boolean metadataComplete = false;
public boolean isMetadataComplete() {
return metadataComplete;
}
public void setMetadataComplete(boolean metadataComplete) {
this.metadataComplete = metadataComplete;
}
// Optional name element
private String name = null;
public String getName() {
return name;
}
public void setName(String name) {
if (ORDER_OTHERS.equalsIgnoreCase(name)) {
// This is unusual. This name will be ignored. Log the fact.
log.warn(sm.getString("webXml.reservedName", name));
} else {
this.name = name;
}
}
// Derived major and minor version attributes
private int majorVersion = 6;
private int minorVersion = 0;
public int getMajorVersion() {
return majorVersion;
}
public int getMinorVersion() {
return minorVersion;
}
// web-app elements
// TODO: Ignored elements:
// - description
// - icon
// display-name - TODO should support multiple with language
private String displayName = null;
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
// distributable
private boolean distributable = false;
public boolean isDistributable() {
return distributable;
}
public void setDistributable(boolean distributable) {
this.distributable = distributable;
}
// deny-uncovered-http-methods
private boolean denyUncoveredHttpMethods = false;
public boolean getDenyUncoveredHttpMethods() {
return denyUncoveredHttpMethods;
}
public void setDenyUncoveredHttpMethods(boolean denyUncoveredHttpMethods) {
this.denyUncoveredHttpMethods = denyUncoveredHttpMethods;
}
// context-param
// TODO: description (multiple with language) is ignored
private final Map<String,String> contextParams = new HashMap<>();
public void addContextParam(String param, String value) {
contextParams.put(param, value);
}
public Map<String,String> getContextParams() {
return contextParams;
}
// filter
// TODO: Should support multiple description elements with language
// TODO: Should support multiple display-name elements with language
// TODO: Should support multiple icon elements
// TODO: Description for init-param is ignored
private final Map<String,FilterDef> filters = new LinkedHashMap<>();
public void addFilter(FilterDef filter) {
if (filters.containsKey(filter.getFilterName())) {
// Filter names must be unique within a web(-fragment).xml
throw new IllegalArgumentException(sm.getString("webXml.duplicateFilter", filter.getFilterName()));
}
filters.put(filter.getFilterName(), filter);
}
public Map<String,FilterDef> getFilters() {
return filters;
}
// filter-mapping
private final Set<FilterMap> filterMaps = new LinkedHashSet<>();
private final Set<String> filterMappingNames = new HashSet<>();
public void addFilterMapping(FilterMap filterMap) {
filterMap.setCharset(getCharset());
filterMaps.add(filterMap);
filterMappingNames.add(filterMap.getFilterName());
}
public Set<FilterMap> getFilterMappings() {
return filterMaps;
}
// listener
// TODO: description (multiple with language) is ignored
// TODO: display-name (multiple with language) is ignored
// TODO: icon (multiple) is ignored
private final Set<String> listeners = new LinkedHashSet<>();
public void addListener(String className) {
listeners.add(className);
}
public Set<String> getListeners() {
return listeners;
}
// servlet
// TODO: description (multiple with language) is ignored
// TODO: display-name (multiple with language) is ignored
// TODO: icon (multiple) is ignored
// TODO: init-param/description (multiple with language) is ignored
// TODO: security-role-ref/description (multiple with language) is ignored
private final Map<String,ServletDef> servlets = new HashMap<>();
public void addServlet(ServletDef servletDef) {
servlets.put(servletDef.getServletName(), servletDef);
if (overridable) {
servletDef.setOverridable(true);
}
}
public Map<String,ServletDef> getServlets() {
return servlets;
}
// servlet-mapping
// Note: URLPatterns from web.xml may be URL encoded
// (https://svn.apache.org/r285186)
private final Map<String,String> servletMappings = new HashMap<>();
private final Set<String> servletMappingNames = new HashSet<>();
public void addServletMapping(String urlPattern, String servletName) {
addServletMappingDecoded(UDecoder.URLDecode(urlPattern, getCharset()), servletName);
}
public void addServletMappingDecoded(String urlPattern, String servletName) {
String oldServletName = servletMappings.put(urlPattern, servletName);
if (oldServletName != null) {
// Duplicate mapping. As per clarification from the Servlet EG,
// deployment should fail.
throw new IllegalArgumentException(
sm.getString("webXml.duplicateServletMapping", oldServletName, servletName, urlPattern));
}
servletMappingNames.add(servletName);
}
public Map<String,String> getServletMappings() {
return servletMappings;
}
// session-config
// Digester will check there is only one of these
private SessionConfig sessionConfig = new SessionConfig();
public void setSessionConfig(SessionConfig sessionConfig) {
this.sessionConfig = sessionConfig;
}
public SessionConfig getSessionConfig() {
return sessionConfig;
}
// mime-mapping
private final Map<String,String> mimeMappings = new HashMap<>();
public void addMimeMapping(String extension, String mimeType) {
mimeMappings.put(extension, mimeType);
}
public Map<String,String> getMimeMappings() {
return mimeMappings;
}
// welcome-file-list merge control
private boolean replaceWelcomeFiles = false;
private boolean alwaysAddWelcomeFiles = true;
/**
* When merging/parsing web.xml files into this web.xml should the current set be completely replaced?
*
* @param replaceWelcomeFiles <code>true</code> to replace welcome files rather than add to the list
*/
public void setReplaceWelcomeFiles(boolean replaceWelcomeFiles) {
this.replaceWelcomeFiles = replaceWelcomeFiles;
}
/**
* When merging from this web.xml, should the welcome files be added to the target web.xml even if it already
* contains welcome file definitions.
*
* @param alwaysAddWelcomeFiles <code>true</code> to add welcome files
*/
public void setAlwaysAddWelcomeFiles(boolean alwaysAddWelcomeFiles) {
this.alwaysAddWelcomeFiles = alwaysAddWelcomeFiles;
}
// welcome-file-list
private final Set<String> welcomeFiles = new LinkedHashSet<>();
public void addWelcomeFile(String welcomeFile) {
if (replaceWelcomeFiles) {
welcomeFiles.clear();
replaceWelcomeFiles = false;
}
welcomeFiles.add(welcomeFile);
}
public Set<String> getWelcomeFiles() {
return welcomeFiles;
}
// error-page
private final Map<String,ErrorPage> errorPages = new HashMap<>();
public void addErrorPage(ErrorPage errorPage) {
errorPage.setCharset(getCharset());
errorPages.put(errorPage.getName(), errorPage);
}
public Map<String,ErrorPage> getErrorPages() {
return errorPages;
}
// Digester will check there is only one jsp-config
// jsp-config/taglib or taglib (2.3 and earlier)
private final Map<String,String> taglibs = new HashMap<>();
public void addTaglib(String uri, String location) {
if (taglibs.containsKey(uri)) {
// Taglib URIs must be unique within a web(-fragment).xml
throw new IllegalArgumentException(sm.getString("webXml.duplicateTaglibUri", uri));
}
taglibs.put(uri, location);
}
public Map<String,String> getTaglibs() {
return taglibs;
}
// jsp-config/jsp-property-group
private final Set<JspPropertyGroup> jspPropertyGroups = new LinkedHashSet<>();
public void addJspPropertyGroup(JspPropertyGroup propertyGroup) {
propertyGroup.setCharset(getCharset());
jspPropertyGroups.add(propertyGroup);
}
public Set<JspPropertyGroup> getJspPropertyGroups() {
return jspPropertyGroups;
}
// security-constraint
// TODO: Should support multiple display-name elements with language
// TODO: Should support multiple description elements with language
private final Set<SecurityConstraint> securityConstraints = new HashSet<>();
public void addSecurityConstraint(SecurityConstraint securityConstraint) {
securityConstraint.setCharset(getCharset());
securityConstraints.add(securityConstraint);
}
public Set<SecurityConstraint> getSecurityConstraints() {
return securityConstraints;
}
// login-config
// Digester will check there is only one of these
private LoginConfig loginConfig = null;
public void setLoginConfig(LoginConfig loginConfig) {
loginConfig.setCharset(getCharset());
this.loginConfig = loginConfig;
}
public LoginConfig getLoginConfig() {
return loginConfig;
}
// security-role
// TODO: description (multiple with language) is ignored
private final Set<String> securityRoles = new HashSet<>();
public void addSecurityRole(String securityRole) {
securityRoles.add(securityRole);
}
public Set<String> getSecurityRoles() {
return securityRoles;
}
// env-entry
// TODO: Should support multiple description elements with language
private final Map<String,ContextEnvironment> envEntries = new HashMap<>();
public void addEnvEntry(ContextEnvironment envEntry) {
if (envEntries.containsKey(envEntry.getName())) {
// env-entry names must be unique within a web(-fragment).xml
throw new IllegalArgumentException(sm.getString("webXml.duplicateEnvEntry", envEntry.getName()));
}
envEntries.put(envEntry.getName(), envEntry);
}
public Map<String,ContextEnvironment> getEnvEntries() {
return envEntries;
}
// ejb-ref
// TODO: Should support multiple description elements with language
private final Map<String,ContextEjb> ejbRefs = new HashMap<>();
public void addEjbRef(ContextEjb ejbRef) {
ejbRefs.put(ejbRef.getName(), ejbRef);
}
public Map<String,ContextEjb> getEjbRefs() {
return ejbRefs;
}
// ejb-local-ref
// TODO: Should support multiple description elements with language
private final Map<String,ContextLocalEjb> ejbLocalRefs = new HashMap<>();
public void addEjbLocalRef(ContextLocalEjb ejbLocalRef) {
ejbLocalRefs.put(ejbLocalRef.getName(), ejbLocalRef);
}
public Map<String,ContextLocalEjb> getEjbLocalRefs() {
return ejbLocalRefs;
}
// service-ref
// TODO: Should support multiple description elements with language
// TODO: Should support multiple display-names elements with language
// TODO: Should support multiple icon elements ???
private final Map<String,ContextService> serviceRefs = new HashMap<>();
public void addServiceRef(ContextService serviceRef) {
serviceRefs.put(serviceRef.getName(), serviceRef);
}
public Map<String,ContextService> getServiceRefs() {
return serviceRefs;
}
// resource-ref
// TODO: Should support multiple description elements with language
private final Map<String,ContextResource> resourceRefs = new HashMap<>();
public void addResourceRef(ContextResource resourceRef) {
if (resourceRefs.containsKey(resourceRef.getName())) {
// resource-ref names must be unique within a web(-fragment).xml
throw new IllegalArgumentException(sm.getString("webXml.duplicateResourceRef", resourceRef.getName()));
}
resourceRefs.put(resourceRef.getName(), resourceRef);
}
public Map<String,ContextResource> getResourceRefs() {
return resourceRefs;
}
// resource-env-ref
// TODO: Should support multiple description elements with language
private final Map<String,ContextResourceEnvRef> resourceEnvRefs = new HashMap<>();
public void addResourceEnvRef(ContextResourceEnvRef resourceEnvRef) {
if (resourceEnvRefs.containsKey(resourceEnvRef.getName())) {
// resource-env-ref names must be unique within a web(-fragment).xml
throw new IllegalArgumentException(
sm.getString("webXml.duplicateResourceEnvRef", resourceEnvRef.getName()));
}
resourceEnvRefs.put(resourceEnvRef.getName(), resourceEnvRef);
}
public Map<String,ContextResourceEnvRef> getResourceEnvRefs() {
return resourceEnvRefs;
}
// message-destination-ref
// TODO: Should support multiple description elements with language
private final Map<String,MessageDestinationRef> messageDestinationRefs = new HashMap<>();
public void addMessageDestinationRef(MessageDestinationRef messageDestinationRef) {
if (messageDestinationRefs.containsKey(messageDestinationRef.getName())) {
// message-destination-ref names must be unique within a
// web(-fragment).xml
throw new IllegalArgumentException(
sm.getString("webXml.duplicateMessageDestinationRef", messageDestinationRef.getName()));
}
messageDestinationRefs.put(messageDestinationRef.getName(), messageDestinationRef);
}
public Map<String,MessageDestinationRef> getMessageDestinationRefs() {
return messageDestinationRefs;
}
// message-destination
// TODO: Should support multiple description elements with language
// TODO: Should support multiple display-names elements with language
// TODO: Should support multiple icon elements ???
private final Map<String,MessageDestination> messageDestinations = new HashMap<>();
public void addMessageDestination(MessageDestination messageDestination) {
if (messageDestinations.containsKey(messageDestination.getName())) {
// message-destination names must be unique within a
// web(-fragment).xml
throw new IllegalArgumentException(
sm.getString("webXml.duplicateMessageDestination", messageDestination.getName()));
}
messageDestinations.put(messageDestination.getName(), messageDestination);
}
public Map<String,MessageDestination> getMessageDestinations() {
return messageDestinations;
}
// locale-encoding-mapping-list
private final Map<String,String> localeEncodingMappings = new HashMap<>();
public void addLocaleEncodingMapping(String locale, String encoding) {
localeEncodingMappings.put(locale, encoding);
}
public Map<String,String> getLocaleEncodingMappings() {
return localeEncodingMappings;
}
// post-construct elements
private final Map<String,String> postConstructMethods = new HashMap<>();
public void addPostConstructMethods(String clazz, String method) {
if (!postConstructMethods.containsKey(clazz)) {
postConstructMethods.put(clazz, method);
}
}
public Map<String,String> getPostConstructMethods() {
return postConstructMethods;
}
// pre-destroy elements
private final Map<String,String> preDestroyMethods = new HashMap<>();
public void addPreDestroyMethods(String clazz, String method) {
if (!preDestroyMethods.containsKey(clazz)) {
preDestroyMethods.put(clazz, method);
}
}
public Map<String,String> getPreDestroyMethods() {
return preDestroyMethods;
}
public JspConfigDescriptor getJspConfigDescriptor() {
if (jspPropertyGroups.isEmpty() && taglibs.isEmpty()) {
return null;
}
Collection<JspPropertyGroupDescriptor> descriptors = new ArrayList<>(jspPropertyGroups.size());
for (JspPropertyGroup jspPropertyGroup : jspPropertyGroups) {
JspPropertyGroupDescriptor descriptor = new JspPropertyGroupDescriptorImpl(jspPropertyGroup);
descriptors.add(descriptor);
}
Collection<TaglibDescriptor> tlds = new HashSet<>(taglibs.size());
for (Entry<String,String> entry : taglibs.entrySet()) {
TaglibDescriptor descriptor = new TaglibDescriptorImpl(entry.getValue(), entry.getKey());
tlds.add(descriptor);
}
return new JspConfigDescriptorImpl(descriptors, tlds);
}
private String requestCharacterEncoding;
public String getRequestCharacterEncoding() {
return requestCharacterEncoding;
}
public void setRequestCharacterEncoding(String requestCharacterEncoding) {
if (requestCharacterEncoding != null) {
try {
B2CConverter.getCharset(requestCharacterEncoding);
} catch (UnsupportedEncodingException e) {
throw new IllegalArgumentException(e);
}
}
this.requestCharacterEncoding = requestCharacterEncoding;
}
private String responseCharacterEncoding;
public String getResponseCharacterEncoding() {
return responseCharacterEncoding;
}
public void setResponseCharacterEncoding(String responseCharacterEncoding) {
if (responseCharacterEncoding != null) {
try {
B2CConverter.getCharset(responseCharacterEncoding);
} catch (UnsupportedEncodingException e) {
throw new IllegalArgumentException(e);
}
}
this.responseCharacterEncoding = responseCharacterEncoding;
}
// Attributes not defined in web.xml or web-fragment.xml
// URL of JAR / exploded JAR for this web-fragment
private URL uRL = null;
public void setURL(URL url) {
this.uRL = url;
}
public URL getURL() {
return uRL;
}
// Name of jar file
private String jarName = null;
public void setJarName(String jarName) {
this.jarName = jarName;
}
public String getJarName() {
return jarName;
}
// Is this JAR part of the application or is it a container JAR? Assume it
// is.
private boolean webappJar = true;
public void setWebappJar(boolean webappJar) {
this.webappJar = webappJar;
}
public boolean getWebappJar() {
return webappJar;
}
// Does this web application delegate first for class loading?
private boolean delegate = false;
public boolean getDelegate() {
return delegate;
}
public void setDelegate(boolean delegate) {
this.delegate = delegate;
}
@Override
public String toString() {
StringBuilder buf = new StringBuilder(32);
buf.append("Name: ");
buf.append(getName());
buf.append(", URL: ");
buf.append(getURL());
return buf.toString();
}
private static final String INDENT2 = " ";
private static final String INDENT4 = " ";
private static final String INDENT6 = " ";
/**
* Generate a web.xml in String form that matches the representation stored in this object.
*
* @return The complete contents of web.xml as a String
*/
public String toXml() {
StringBuilder sb = new StringBuilder(2048);
// TODO - Various, icon, description etc elements are skipped - mainly
// because they are ignored when web.xml is parsed - see above
// NOTE - Elements need to be written in the order defined in the 2.3
// DTD else validation of the merged web.xml will fail
// NOTE - Some elements need to be skipped based on the version of the
// specification being used. Version is validated and starts at
// 2.2. The version tests used in this method take advantage of
// this.
// Declaration
sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
// Root element
if (publicId != null) {
sb.append("<!DOCTYPE web-app PUBLIC\n");
sb.append(" \"");
sb.append(publicId);
sb.append("\"\n");
sb.append(" \"");
if (XmlIdentifiers.WEB_22_PUBLIC.equals(publicId)) {
sb.append(XmlIdentifiers.WEB_22_SYSTEM);
} else {
sb.append(XmlIdentifiers.WEB_23_SYSTEM);
}
sb.append("\">\n");
sb.append("<web-app>");
} else {
String javaeeNamespace = null;
String webXmlSchemaLocation = null;
String version = getVersion();
if ("2.4".equals(version)) {
javaeeNamespace = XmlIdentifiers.JAVAEE_1_4_NS;
webXmlSchemaLocation = XmlIdentifiers.WEB_24_XSD;
} else if ("2.5".equals(version)) {
javaeeNamespace = XmlIdentifiers.JAVAEE_5_NS;
webXmlSchemaLocation = XmlIdentifiers.WEB_25_XSD;
} else if ("3.0".equals(version)) {
javaeeNamespace = XmlIdentifiers.JAVAEE_6_NS;
webXmlSchemaLocation = XmlIdentifiers.WEB_30_XSD;
} else if ("3.1".equals(version)) {
javaeeNamespace = XmlIdentifiers.JAVAEE_7_NS;
webXmlSchemaLocation = XmlIdentifiers.WEB_31_XSD;
} else if ("4.0".equals(version)) {
javaeeNamespace = XmlIdentifiers.JAVAEE_8_NS;
webXmlSchemaLocation = XmlIdentifiers.WEB_40_XSD;
} else if ("5.0".equals(version)) {
javaeeNamespace = XmlIdentifiers.JAKARTAEE_9_NS;
webXmlSchemaLocation = XmlIdentifiers.WEB_50_XSD;
} else if ("6.0".equals(version)) {
javaeeNamespace = XmlIdentifiers.JAKARTAEE_10_NS;
webXmlSchemaLocation = XmlIdentifiers.WEB_60_XSD;
} else if ("6.1".equals(version)) {
javaeeNamespace = XmlIdentifiers.JAKARTAEE_11_NS;
webXmlSchemaLocation = XmlIdentifiers.WEB_61_XSD;
}
sb.append("<web-app xmlns=\"");
sb.append(javaeeNamespace);
sb.append("\"\n");
sb.append(" xmlns:xsi=");
sb.append("\"http://www.w3.org/2001/XMLSchema-instance\"\n");
sb.append(" xsi:schemaLocation=\"");
sb.append(javaeeNamespace);
sb.append(' ');
sb.append(webXmlSchemaLocation);
sb.append("\"\n");
sb.append(" version=\"");
sb.append(getVersion());
sb.append("\"");
if ("2.4".equals(version)) {
sb.append(">\n\n");
} else {
sb.append("\n metadata-complete=\"true\">\n\n");
}
}
appendElement(sb, INDENT2, "display-name", displayName);
if (isDistributable()) {
sb.append(" <distributable/>\n\n");
}
for (Map.Entry<String,String> entry : contextParams.entrySet()) {
sb.append(" <context-param>\n");
appendElement(sb, INDENT4, "param-name", entry.getKey());
appendElement(sb, INDENT4, "param-value", entry.getValue());
sb.append(" </context-param>\n");
}
sb.append('\n');
// Filters were introduced in Servlet 2.3
if (getMajorVersion() > 2 || getMinorVersion() > 2) {
for (Map.Entry<String,FilterDef> entry : filters.entrySet()) {
FilterDef filterDef = entry.getValue();
sb.append(" <filter>\n");
appendElement(sb, INDENT4, "description", filterDef.getDescription());
appendElement(sb, INDENT4, "display-name", filterDef.getDisplayName());
appendElement(sb, INDENT4, "filter-name", filterDef.getFilterName());
appendElement(sb, INDENT4, "filter-class", filterDef.getFilterClass());
// Async support was introduced for Servlet 3.0 onwards
if (getMajorVersion() != 2) {
appendElement(sb, INDENT4, "async-supported", filterDef.getAsyncSupported());
}
for (Map.Entry<String,String> param : filterDef.getParameterMap().entrySet()) {
sb.append(" <init-param>\n");
appendElement(sb, INDENT6, "param-name", param.getKey());
appendElement(sb, INDENT6, "param-value", param.getValue());
sb.append(" </init-param>\n");
}
sb.append(" </filter>\n");
}
sb.append('\n');
for (FilterMap filterMap : filterMaps) {
sb.append(" <filter-mapping>\n");
appendElement(sb, INDENT4, "filter-name", filterMap.getFilterName());
if (filterMap.getMatchAllServletNames()) {
sb.append(" <servlet-name>*</servlet-name>\n");
} else {
for (String servletName : filterMap.getServletNames()) {
appendElement(sb, INDENT4, "servlet-name", servletName);
}
}
if (filterMap.getMatchAllUrlPatterns()) {
sb.append(" <url-pattern>*</url-pattern>\n");
} else {
for (String urlPattern : filterMap.getURLPatterns()) {
appendElement(sb, INDENT4, "url-pattern", encodeUrl(urlPattern));
}
}
// dispatcher was added in Servlet 2.4
if (getMajorVersion() > 2 || getMinorVersion() > 3) {
for (String dispatcher : filterMap.getDispatcherNames()) {
if (getMajorVersion() == 2 && DispatcherType.ASYNC.name().equals(dispatcher)) {
continue;
}
appendElement(sb, INDENT4, "dispatcher", dispatcher);
}
}
sb.append(" </filter-mapping>\n");
}
sb.append('\n');
}
// Listeners were introduced in Servlet 2.3
if (getMajorVersion() > 2 || getMinorVersion() > 2) {
for (String listener : listeners) {
sb.append(" <listener>\n");
appendElement(sb, INDENT4, "listener-class", listener);
sb.append(" </listener>\n");
}
sb.append('\n');
}
for (Map.Entry<String,ServletDef> entry : servlets.entrySet()) {
ServletDef servletDef = entry.getValue();
sb.append(" <servlet>\n");
appendElement(sb, INDENT4, "description", servletDef.getDescription());
appendElement(sb, INDENT4, "display-name", servletDef.getDisplayName());
appendElement(sb, INDENT4, "servlet-name", entry.getKey());
appendElement(sb, INDENT4, "servlet-class", servletDef.getServletClass());
appendElement(sb, INDENT4, "jsp-file", servletDef.getJspFile());
for (Map.Entry<String,String> param : servletDef.getParameterMap().entrySet()) {
sb.append(" <init-param>\n");
appendElement(sb, INDENT6, "param-name", param.getKey());
appendElement(sb, INDENT6, "param-value", param.getValue());
sb.append(" </init-param>\n");
}
appendElement(sb, INDENT4, "load-on-startup", servletDef.getLoadOnStartup());
appendElement(sb, INDENT4, "enabled", servletDef.getEnabled());
// Async support was introduced for Servlet 3.0 onwards
if (getMajorVersion() != 2) {
appendElement(sb, INDENT4, "async-supported", servletDef.getAsyncSupported());
}
// servlet/run-as was introduced in Servlet 2.3
if (getMajorVersion() > 2 || getMinorVersion() > 2) {
if (servletDef.getRunAs() != null) {
sb.append(" <run-as>\n");
appendElement(sb, INDENT6, "role-name", servletDef.getRunAs());
sb.append(" </run-as>\n");
}
}
for (SecurityRoleRef roleRef : servletDef.getSecurityRoleRefs()) {
sb.append(" <security-role-ref>\n");
appendElement(sb, INDENT6, "role-name", roleRef.getName());
appendElement(sb, INDENT6, "role-link", roleRef.getLink());
sb.append(" </security-role-ref>\n");
}
// multipart-config was added in Servlet 3.0
if (getMajorVersion() != 2) {
MultipartDef multipartDef = servletDef.getMultipartDef();
if (multipartDef != null) {
sb.append(" <multipart-config>\n");
appendElement(sb, INDENT6, "location", multipartDef.getLocation());
appendElement(sb, INDENT6, "max-file-size", multipartDef.getMaxFileSize());
appendElement(sb, INDENT6, "max-request-size", multipartDef.getMaxRequestSize());
appendElement(sb, INDENT6, "file-size-threshold", multipartDef.getFileSizeThreshold());
sb.append(" </multipart-config>\n");
}
}
sb.append(" </servlet>\n");
}
sb.append('\n');
for (Map.Entry<String,String> entry : servletMappings.entrySet()) {
sb.append(" <servlet-mapping>\n");
appendElement(sb, INDENT4, "servlet-name", entry.getValue());
appendElement(sb, INDENT4, "url-pattern", encodeUrl(entry.getKey()));
sb.append(" </servlet-mapping>\n");
}
sb.append('\n');
if (sessionConfig != null) {
sb.append(" <session-config>\n");
appendElement(sb, INDENT4, "session-timeout", sessionConfig.getSessionTimeout());
if (majorVersion >= 3) {
sb.append(" <cookie-config>\n");
appendElement(sb, INDENT6, "name", sessionConfig.getCookieName());
appendElement(sb, INDENT6, "domain", sessionConfig.getCookieDomain());
appendElement(sb, INDENT6, "path", sessionConfig.getCookiePath());
appendElement(sb, INDENT6, "comment", sessionConfig.getCookieComment());
appendElement(sb, INDENT6, "http-only", sessionConfig.getCookieHttpOnly());
appendElement(sb, INDENT6, "secure", sessionConfig.getCookieSecure());
appendElement(sb, INDENT6, "max-age", sessionConfig.getCookieMaxAge());
sb.append(" </cookie-config>\n");
for (SessionTrackingMode stm : sessionConfig.getSessionTrackingModes()) {
appendElement(sb, INDENT4, "tracking-mode", stm.name());
}
}
sb.append(" </session-config>\n\n");
}
for (Map.Entry<String,String> entry : mimeMappings.entrySet()) {
sb.append(" <mime-mapping>\n");
appendElement(sb, INDENT4, "extension", entry.getKey());
appendElement(sb, INDENT4, "mime-type", entry.getValue());
sb.append(" </mime-mapping>\n");
}
sb.append('\n');
if (!welcomeFiles.isEmpty()) {
sb.append(" <welcome-file-list>\n");
for (String welcomeFile : welcomeFiles) {
appendElement(sb, INDENT4, "welcome-file", welcomeFile);
}
sb.append(" </welcome-file-list>\n\n");
}
for (ErrorPage errorPage : errorPages.values()) {
String exceptionType = errorPage.getExceptionType();
int errorCode = errorPage.getErrorCode();
if (exceptionType == null && errorCode == 0 && getMajorVersion() == 2) {
// Default error pages are only supported from 3.0 onwards
continue;
}
sb.append(" <error-page>\n");
if (errorPage.getExceptionType() != null) {
appendElement(sb, INDENT4, "exception-type", exceptionType);
} else if (errorPage.getErrorCode() > 0) {
appendElement(sb, INDENT4, "error-code", Integer.toString(errorCode));
}
appendElement(sb, INDENT4, "location", errorPage.getLocation());
sb.append(" </error-page>\n");
}
sb.append('\n');
// jsp-config was added in Servlet 2.4. Prior to that, tag-libs was used
// directly and jsp-property-group did not exist
if (!taglibs.isEmpty() || !jspPropertyGroups.isEmpty()) {
if (getMajorVersion() > 2 || getMinorVersion() > 3) {
sb.append(" <jsp-config>\n");
}
for (Map.Entry<String,String> entry : taglibs.entrySet()) {
sb.append(" <taglib>\n");
appendElement(sb, INDENT6, "taglib-uri", entry.getKey());
appendElement(sb, INDENT6, "taglib-location", entry.getValue());
sb.append(" </taglib>\n");
}
if (getMajorVersion() > 2 || getMinorVersion() > 3) {
for (JspPropertyGroup jpg : jspPropertyGroups) {
sb.append(" <jsp-property-group>\n");
for (String urlPattern : jpg.getUrlPatterns()) {
appendElement(sb, INDENT6, "url-pattern", encodeUrl(urlPattern));
}
appendElement(sb, INDENT6, "el-ignored", jpg.getElIgnored());
appendElement(sb, INDENT6, "page-encoding", jpg.getPageEncoding());
appendElement(sb, INDENT6, "scripting-invalid", jpg.getScriptingInvalid());
appendElement(sb, INDENT6, "is-xml", jpg.getIsXml());
for (String prelude : jpg.getIncludePreludes()) {
appendElement(sb, INDENT6, "include-prelude", prelude);
}
for (String coda : jpg.getIncludeCodas()) {
appendElement(sb, INDENT6, "include-coda", coda);
}
appendElement(sb, INDENT6, "deferred-syntax-allowed-as-literal", jpg.getDeferredSyntax());
appendElement(sb, INDENT6, "trim-directive-whitespaces", jpg.getTrimWhitespace());
appendElement(sb, INDENT6, "default-content-type", jpg.getDefaultContentType());
appendElement(sb, INDENT6, "buffer", jpg.getBuffer());
appendElement(sb, INDENT6, "error-on-undeclared-namespace", jpg.getErrorOnUndeclaredNamespace());
sb.append(" </jsp-property-group>\n");
}
sb.append(" </jsp-config>\n\n");
}
}
// resource-env-ref was introduced in Servlet 2.3
if (getMajorVersion() > 2 || getMinorVersion() > 2) {
for (ContextResourceEnvRef resourceEnvRef : resourceEnvRefs.values()) {
sb.append(" <resource-env-ref>\n");
appendElement(sb, INDENT4, "description", resourceEnvRef.getDescription());
appendElement(sb, INDENT4, "resource-env-ref-name", resourceEnvRef.getName());
appendElement(sb, INDENT4, "resource-env-ref-type", resourceEnvRef.getType());
appendElement(sb, INDENT4, "mapped-name", resourceEnvRef.getProperty("mappedName"));
for (InjectionTarget target : resourceEnvRef.getInjectionTargets()) {
sb.append(" <injection-target>\n");
appendElement(sb, INDENT6, "injection-target-class", target.getTargetClass());
appendElement(sb, INDENT6, "injection-target-name", target.getTargetName());
sb.append(" </injection-target>\n");
}
appendElement(sb, INDENT4, "lookup-name", resourceEnvRef.getLookupName());
sb.append(" </resource-env-ref>\n");
}
sb.append('\n');
}
for (ContextResource resourceRef : resourceRefs.values()) {
sb.append(" <resource-ref>\n");
appendElement(sb, INDENT4, "description", resourceRef.getDescription());
appendElement(sb, INDENT4, "res-ref-name", resourceRef.getName());
appendElement(sb, INDENT4, "res-type", resourceRef.getType());
appendElement(sb, INDENT4, "res-auth", resourceRef.getAuth());
// resource-ref/res-sharing-scope was introduced in Servlet 2.3
if (getMajorVersion() > 2 || getMinorVersion() > 2) {
appendElement(sb, INDENT4, "res-sharing-scope", resourceRef.getScope());
}
appendElement(sb, INDENT4, "mapped-name", resourceRef.getProperty("mappedName"));
for (InjectionTarget target : resourceRef.getInjectionTargets()) {
sb.append(" <injection-target>\n");
appendElement(sb, INDENT6, "injection-target-class", target.getTargetClass());
appendElement(sb, INDENT6, "injection-target-name", target.getTargetName());
sb.append(" </injection-target>\n");
}
appendElement(sb, INDENT4, "lookup-name", resourceRef.getLookupName());
sb.append(" </resource-ref>\n");
}
sb.append('\n');
for (SecurityConstraint constraint : securityConstraints) {
sb.append(" <security-constraint>\n");
// security-constraint/display-name was introduced in Servlet 2.3
if (getMajorVersion() > 2 || getMinorVersion() > 2) {
appendElement(sb, INDENT4, "display-name", constraint.getDisplayName());
}
for (SecurityCollection collection : constraint.findCollections()) {
sb.append(" <web-resource-collection>\n");
appendElement(sb, INDENT6, "web-resource-name", collection.getName());
appendElement(sb, INDENT6, "description", collection.getDescription());
for (String urlPattern : collection.findPatterns()) {
appendElement(sb, INDENT6, "url-pattern", encodeUrl(urlPattern));
}
for (String method : collection.findMethods()) {
appendElement(sb, INDENT6, "http-method", method);
}
for (String method : collection.findOmittedMethods()) {
appendElement(sb, INDENT6, "http-method-omission", method);
}
sb.append(" </web-resource-collection>\n");
}
if (constraint.findAuthRoles().length > 0) {
sb.append(" <auth-constraint>\n");
for (String role : constraint.findAuthRoles()) {
appendElement(sb, INDENT6, "role-name", role);
}
sb.append(" </auth-constraint>\n");
}
if (constraint.getUserConstraint() != null) {
sb.append(" <user-data-constraint>\n");
appendElement(sb, INDENT6, "transport-guarantee", constraint.getUserConstraint());
sb.append(" </user-data-constraint>\n");
}
sb.append(" </security-constraint>\n");
}
sb.append('\n');
if (loginConfig != null) {
sb.append(" <login-config>\n");
appendElement(sb, INDENT4, "auth-method", loginConfig.getAuthMethod());
appendElement(sb, INDENT4, "realm-name", loginConfig.getRealmName());
if (loginConfig.getErrorPage() != null || loginConfig.getLoginPage() != null) {
sb.append(" <form-login-config>\n");
appendElement(sb, INDENT6, "form-login-page", loginConfig.getLoginPage());
appendElement(sb, INDENT6, "form-error-page", loginConfig.getErrorPage());
sb.append(" </form-login-config>\n");
}
sb.append(" </login-config>\n\n");
}
for (String roleName : securityRoles) {
sb.append(" <security-role>\n");
appendElement(sb, INDENT4, "role-name", roleName);
sb.append(" </security-role>\n");
}
for (ContextEnvironment envEntry : envEntries.values()) {
sb.append(" <env-entry>\n");
appendElement(sb, INDENT4, "description", envEntry.getDescription());
appendElement(sb, INDENT4, "env-entry-name", envEntry.getName());
appendElement(sb, INDENT4, "env-entry-type", envEntry.getType());
appendElement(sb, INDENT4, "env-entry-value", envEntry.getValue());
appendElement(sb, INDENT4, "mapped-name", envEntry.getProperty("mappedName"));
for (InjectionTarget target : envEntry.getInjectionTargets()) {
sb.append(" <injection-target>\n");
appendElement(sb, INDENT6, "injection-target-class", target.getTargetClass());
appendElement(sb, INDENT6, "injection-target-name", target.getTargetName());
sb.append(" </injection-target>\n");
}
appendElement(sb, INDENT4, "lookup-name", envEntry.getLookupName());
sb.append(" </env-entry>\n");
}
sb.append('\n');
for (ContextEjb ejbRef : ejbRefs.values()) {
sb.append(" <ejb-ref>\n");
appendElement(sb, INDENT4, "description", ejbRef.getDescription());
appendElement(sb, INDENT4, "ejb-ref-name", ejbRef.getName());
appendElement(sb, INDENT4, "ejb-ref-type", ejbRef.getType());
appendElement(sb, INDENT4, "home", ejbRef.getHome());
appendElement(sb, INDENT4, "remote", ejbRef.getRemote());
appendElement(sb, INDENT4, "ejb-link", ejbRef.getLink());
appendElement(sb, INDENT4, "mapped-name", ejbRef.getProperty("mappedName"));
for (InjectionTarget target : ejbRef.getInjectionTargets()) {
sb.append(" <injection-target>\n");
appendElement(sb, INDENT6, "injection-target-class", target.getTargetClass());
appendElement(sb, INDENT6, "injection-target-name", target.getTargetName());
sb.append(" </injection-target>\n");
}
appendElement(sb, INDENT4, "lookup-name", ejbRef.getLookupName());
sb.append(" </ejb-ref>\n");
}
sb.append('\n');
// ejb-local-ref was introduced in Servlet 2.3
if (getMajorVersion() > 2 || getMinorVersion() > 2) {
for (ContextLocalEjb ejbLocalRef : ejbLocalRefs.values()) {
sb.append(" <ejb-local-ref>\n");
appendElement(sb, INDENT4, "description", ejbLocalRef.getDescription());
appendElement(sb, INDENT4, "ejb-ref-name", ejbLocalRef.getName());
appendElement(sb, INDENT4, "ejb-ref-type", ejbLocalRef.getType());
appendElement(sb, INDENT4, "local-home", ejbLocalRef.getHome());
appendElement(sb, INDENT4, "local", ejbLocalRef.getLocal());
appendElement(sb, INDENT4, "ejb-link", ejbLocalRef.getLink());
appendElement(sb, INDENT4, "mapped-name", ejbLocalRef.getProperty("mappedName"));
for (InjectionTarget target : ejbLocalRef.getInjectionTargets()) {
sb.append(" <injection-target>\n");
appendElement(sb, INDENT6, "injection-target-class", target.getTargetClass());
appendElement(sb, INDENT6, "injection-target-name", target.getTargetName());
sb.append(" </injection-target>\n");
}
appendElement(sb, INDENT4, "lookup-name", ejbLocalRef.getLookupName());
sb.append(" </ejb-local-ref>\n");
}
sb.append('\n');
}
// service-ref was introduced in Servlet 2.4
if (getMajorVersion() > 2 || getMinorVersion() > 3) {
for (ContextService serviceRef : serviceRefs.values()) {
sb.append(" <service-ref>\n");
appendElement(sb, INDENT4, "description", serviceRef.getDescription());
appendElement(sb, INDENT4, "display-name", serviceRef.getDisplayname());
appendElement(sb, INDENT4, "service-ref-name", serviceRef.getName());
appendElement(sb, INDENT4, "service-interface", serviceRef.getInterface());
appendElement(sb, INDENT4, "service-ref-type", serviceRef.getType());
appendElement(sb, INDENT4, "wsdl-file", serviceRef.getWsdlfile());
appendElement(sb, INDENT4, "jaxrpc-mapping-file", serviceRef.getJaxrpcmappingfile());
String qname = serviceRef.getServiceqnameNamespaceURI();
if (qname != null) {
qname = qname + ":";
}
qname = qname + serviceRef.getServiceqnameLocalpart();
appendElement(sb, INDENT4, "service-qname", qname);
Iterator<String> endpointIter = serviceRef.getServiceendpoints();
while (endpointIter.hasNext()) {
String endpoint = endpointIter.next();
sb.append(" <port-component-ref>\n");
appendElement(sb, INDENT6, "service-endpoint-interface", endpoint);
appendElement(sb, INDENT6, "port-component-link", serviceRef.getProperty(endpoint));
sb.append(" </port-component-ref>\n");
}
Iterator<String> handlerIter = serviceRef.getHandlers();
while (handlerIter.hasNext()) {
String handler = handlerIter.next();
sb.append(" <handler>\n");
ContextHandler ch = serviceRef.getHandler(handler);
appendElement(sb, INDENT6, "handler-name", ch.getName());
appendElement(sb, INDENT6, "handler-class", ch.getHandlerclass());
sb.append(" </handler>\n");
}
// TODO handler-chains
appendElement(sb, INDENT4, "mapped-name", serviceRef.getProperty("mappedName"));
for (InjectionTarget target : serviceRef.getInjectionTargets()) {
sb.append(" <injection-target>\n");
appendElement(sb, INDENT6, "injection-target-class", target.getTargetClass());
appendElement(sb, INDENT6, "injection-target-name", target.getTargetName());
sb.append(" </injection-target>\n");
}
appendElement(sb, INDENT4, "lookup-name", serviceRef.getLookupName());
sb.append(" </service-ref>\n");
}
sb.append('\n');
}
if (!postConstructMethods.isEmpty()) {
for (Entry<String,String> entry : postConstructMethods.entrySet()) {
sb.append(" <post-construct>\n");
appendElement(sb, INDENT4, "lifecycle-callback-class", entry.getKey());
appendElement(sb, INDENT4, "lifecycle-callback-method", entry.getValue());
sb.append(" </post-construct>\n");
}
sb.append('\n');
}
if (!preDestroyMethods.isEmpty()) {
for (Entry<String,String> entry : preDestroyMethods.entrySet()) {
sb.append(" <pre-destroy>\n");
appendElement(sb, INDENT4, "lifecycle-callback-class", entry.getKey());
appendElement(sb, INDENT4, "lifecycle-callback-method", entry.getValue());
sb.append(" </pre-destroy>\n");
}
sb.append('\n');
}
// message-destination-ref, message-destination were introduced in
// Servlet 2.4
if (getMajorVersion() > 2 || getMinorVersion() > 3) {
for (MessageDestinationRef mdr : messageDestinationRefs.values()) {
sb.append(" <message-destination-ref>\n");
appendElement(sb, INDENT4, "description", mdr.getDescription());
appendElement(sb, INDENT4, "message-destination-ref-name", mdr.getName());
appendElement(sb, INDENT4, "message-destination-type", mdr.getType());
appendElement(sb, INDENT4, "message-destination-usage", mdr.getUsage());
appendElement(sb, INDENT4, "message-destination-link", mdr.getLink());
appendElement(sb, INDENT4, "mapped-name", mdr.getProperty("mappedName"));
for (InjectionTarget target : mdr.getInjectionTargets()) {
sb.append(" <injection-target>\n");
appendElement(sb, INDENT6, "injection-target-class", target.getTargetClass());
appendElement(sb, INDENT6, "injection-target-name", target.getTargetName());
sb.append(" </injection-target>\n");
}
appendElement(sb, INDENT4, "lookup-name", mdr.getLookupName());
sb.append(" </message-destination-ref>\n");
}
sb.append('\n');
for (MessageDestination md : messageDestinations.values()) {
sb.append(" <message-destination>\n");
appendElement(sb, INDENT4, "description", md.getDescription());
appendElement(sb, INDENT4, "display-name", md.getDisplayName());
appendElement(sb, INDENT4, "message-destination-name", md.getName());
appendElement(sb, INDENT4, "mapped-name", md.getProperty("mappedName"));
appendElement(sb, INDENT4, "lookup-name", md.getLookupName());
sb.append(" </message-destination>\n");
}
sb.append('\n');
}
// locale-encoding-mapping-list was introduced in Servlet 2.4
if (getMajorVersion() > 2 || getMinorVersion() > 3) {
if (!localeEncodingMappings.isEmpty()) {
sb.append(" <locale-encoding-mapping-list>\n");
for (Map.Entry<String,String> entry : localeEncodingMappings.entrySet()) {
sb.append(" <locale-encoding-mapping>\n");
appendElement(sb, INDENT6, "locale", entry.getKey());
appendElement(sb, INDENT6, "encoding", entry.getValue());
sb.append(" </locale-encoding-mapping>\n");
}
sb.append(" </locale-encoding-mapping-list>\n");
sb.append("\n");
}
}
// deny-uncovered-http-methods was introduced in Servlet 3.1
if (getMajorVersion() > 3 || (getMajorVersion() == 3 && getMinorVersion() > 0)) {
if (denyUncoveredHttpMethods) {
sb.append(" <deny-uncovered-http-methods/>");
sb.append("\n");
}
}
// request-encoding and response-encoding was introduced in Servlet 4.0
if (getMajorVersion() >= 4) {
appendElement(sb, INDENT2, "request-character-encoding", requestCharacterEncoding);
appendElement(sb, INDENT2, "response-character-encoding", responseCharacterEncoding);
}
sb.append("</web-app>");
return sb.toString();
}
private String encodeUrl(String input) {
return URLEncoder.encode(input, StandardCharsets.UTF_8);
}
private static void appendElement(StringBuilder sb, String indent, String elementName, String value) {
if (value == null) {
return;
}
if (value.isEmpty()) {
sb.append(indent);
sb.append('<');
sb.append(elementName);
sb.append("/>\n");
} else {
sb.append(indent);
sb.append('<');
sb.append(elementName);
sb.append('>');
sb.append(Escape.xml(value));
sb.append("</");
sb.append(elementName);
sb.append(">\n");
}
}
private static void appendElement(StringBuilder sb, String indent, String elementName, Object value) {
if (value == null) {
return;
}
appendElement(sb, indent, elementName, value.toString());
}
/**
* Merge the supplied web fragments into this main web.xml.
*
* @param fragments The fragments to merge in
*
* @return <code>true</code> if merge is successful, else <code>false</code>
*/
public boolean merge(Set<WebXml> fragments) {
// As far as possible, process in alphabetical order so it is easy to
// check everything is present
// Merge rules vary from element to element. See SRV.8.2.3
WebXml temp = new WebXml();
for (WebXml fragment : fragments) {
if (!mergeMap(fragment.getContextParams(), contextParams, temp.getContextParams(), fragment,
"Context Parameter")) {
return false;
}
}
contextParams.putAll(temp.getContextParams());
if (displayName == null) {
for (WebXml fragment : fragments) {
String value = fragment.getDisplayName();
if (value != null) {
if (temp.getDisplayName() == null) {
temp.setDisplayName(value);
} else {
log.error(
sm.getString("webXml.mergeConflictDisplayName", fragment.getName(), fragment.getURL()));
return false;
}
}
}
displayName = temp.getDisplayName();
}
// Note: Not permitted in fragments, but we also use fragments for
// per-Host and global defaults so they may appear there
if (!denyUncoveredHttpMethods) {
for (WebXml fragment : fragments) {
if (fragment.getDenyUncoveredHttpMethods()) {
denyUncoveredHttpMethods = true;
break;
}
}
}
if (requestCharacterEncoding == null) {
for (WebXml fragment : fragments) {
if (fragment.getRequestCharacterEncoding() != null) {
requestCharacterEncoding = fragment.getRequestCharacterEncoding();
}
}
}
if (responseCharacterEncoding == null) {
for (WebXml fragment : fragments) {
if (fragment.getResponseCharacterEncoding() != null) {
responseCharacterEncoding = fragment.getResponseCharacterEncoding();
}
}
}
if (distributable) {
for (WebXml fragment : fragments) {
if (!fragment.isDistributable()) {
distributable = false;
break;
}
}
}
for (WebXml fragment : fragments) {
if (!mergeResourceMap(fragment.getEjbLocalRefs(), ejbLocalRefs, temp.getEjbLocalRefs(), fragment)) {
return false;
}
}
ejbLocalRefs.putAll(temp.getEjbLocalRefs());
for (WebXml fragment : fragments) {
if (!mergeResourceMap(fragment.getEjbRefs(), ejbRefs, temp.getEjbRefs(), fragment)) {
return false;
}
}
ejbRefs.putAll(temp.getEjbRefs());
for (WebXml fragment : fragments) {
if (!mergeResourceMap(fragment.getEnvEntries(), envEntries, temp.getEnvEntries(), fragment)) {
return false;
}
}
envEntries.putAll(temp.getEnvEntries());
for (WebXml fragment : fragments) {
if (!mergeMap(fragment.getErrorPages(), errorPages, temp.getErrorPages(), fragment, "Error Page")) {
return false;
}
}
errorPages.putAll(temp.getErrorPages());
// As per 'clarification' from the Servlet EG, filter definitions in the
// main web.xml override those in fragments and those in fragments
// override those in annotations
List<FilterMap> filterMapsToAdd = new ArrayList<>();
for (WebXml fragment : fragments) {
for (FilterMap filterMap : fragment.getFilterMappings()) {
if (!filterMappingNames.contains(filterMap.getFilterName())) {
filterMapsToAdd.add(filterMap);
}
}
}
for (FilterMap filterMap : filterMapsToAdd) {
// Additive
addFilterMapping(filterMap);
}
for (WebXml fragment : fragments) {
for (Map.Entry<String,FilterDef> entry : fragment.getFilters().entrySet()) {
if (filters.containsKey(entry.getKey())) {
mergeFilter(entry.getValue(), filters.get(entry.getKey()), false);
} else {
if (temp.getFilters().containsKey(entry.getKey())) {
if (!(mergeFilter(entry.getValue(), temp.getFilters().get(entry.getKey()), true))) {
log.error(sm.getString("webXml.mergeConflictFilter", entry.getKey(), fragment.getName(),
fragment.getURL()));
return false;
}
} else {
temp.getFilters().put(entry.getKey(), entry.getValue());
}
}
}
}
filters.putAll(temp.getFilters());
for (WebXml fragment : fragments) {
for (JspPropertyGroup jspPropertyGroup : fragment.getJspPropertyGroups()) {
// Always additive
addJspPropertyGroup(jspPropertyGroup);
}
}
for (WebXml fragment : fragments) {
for (String listener : fragment.getListeners()) {
// Always additive
addListener(listener);
}
}
for (WebXml fragment : fragments) {
if (!mergeMap(fragment.getLocaleEncodingMappings(), localeEncodingMappings,
temp.getLocaleEncodingMappings(), fragment, "Locale Encoding Mapping")) {
return false;
}
}
localeEncodingMappings.putAll(temp.getLocaleEncodingMappings());
if (getLoginConfig() == null) {
LoginConfig tempLoginConfig = null;
for (WebXml fragment : fragments) {
LoginConfig fragmentLoginConfig = fragment.loginConfig;
if (fragmentLoginConfig != null) {
if (tempLoginConfig == null || fragmentLoginConfig.equals(tempLoginConfig)) {
tempLoginConfig = fragmentLoginConfig;
} else {
log.error(
sm.getString("webXml.mergeConflictLoginConfig", fragment.getName(), fragment.getURL()));
}
}
}
loginConfig = tempLoginConfig;
}
for (WebXml fragment : fragments) {
if (!mergeResourceMap(fragment.getMessageDestinationRefs(), messageDestinationRefs,
temp.getMessageDestinationRefs(), fragment)) {
return false;
}
}
messageDestinationRefs.putAll(temp.getMessageDestinationRefs());
for (WebXml fragment : fragments) {
if (!mergeResourceMap(fragment.getMessageDestinations(), messageDestinations, temp.getMessageDestinations(),
fragment)) {
return false;
}
}
messageDestinations.putAll(temp.getMessageDestinations());
for (WebXml fragment : fragments) {
if (!mergeMap(fragment.getMimeMappings(), mimeMappings, temp.getMimeMappings(), fragment, "Mime Mapping")) {
return false;
}
}
mimeMappings.putAll(temp.getMimeMappings());
for (WebXml fragment : fragments) {
if (!mergeResourceMap(fragment.getResourceEnvRefs(), resourceEnvRefs, temp.getResourceEnvRefs(),
fragment)) {
return false;
}
}
resourceEnvRefs.putAll(temp.getResourceEnvRefs());
for (WebXml fragment : fragments) {
if (!mergeResourceMap(fragment.getResourceRefs(), resourceRefs, temp.getResourceRefs(), fragment)) {
return false;
}
}
resourceRefs.putAll(temp.getResourceRefs());
for (WebXml fragment : fragments) {
for (SecurityConstraint constraint : fragment.getSecurityConstraints()) {
// Always additive
addSecurityConstraint(constraint);
}
}
for (WebXml fragment : fragments) {
for (String role : fragment.getSecurityRoles()) {
// Always additive
addSecurityRole(role);
}
}
for (WebXml fragment : fragments) {
if (!mergeResourceMap(fragment.getServiceRefs(), serviceRefs, temp.getServiceRefs(), fragment)) {
return false;
}
}
serviceRefs.putAll(temp.getServiceRefs());
// As per 'clarification' from the Servlet EG, servlet definitions and
// mappings in the main web.xml override those in fragments and those in
// fragments override those in annotations
// Skip servlet definitions and mappings from fragments that are
// defined in web.xml
List<Map.Entry<String,String>> servletMappingsToAdd = new ArrayList<>();
for (WebXml fragment : fragments) {
for (Map.Entry<String,String> servletMap : fragment.getServletMappings().entrySet()) {
if (!servletMappingNames.contains(servletMap.getValue()) &&
!servletMappings.containsKey(servletMap.getKey())) {
servletMappingsToAdd.add(servletMap);
}
}
}
// Add fragment mappings
for (Map.Entry<String,String> mapping : servletMappingsToAdd) {
addServletMappingDecoded(mapping.getKey(), mapping.getValue());
}
for (WebXml fragment : fragments) {
for (Map.Entry<String,ServletDef> entry : fragment.getServlets().entrySet()) {
if (servlets.containsKey(entry.getKey())) {
mergeServlet(entry.getValue(), servlets.get(entry.getKey()), false);
} else {
if (temp.getServlets().containsKey(entry.getKey())) {
if (!(mergeServlet(entry.getValue(), temp.getServlets().get(entry.getKey()), true))) {
log.error(sm.getString("webXml.mergeConflictServlet", entry.getKey(), fragment.getName(),
fragment.getURL()));
return false;
}
} else {
temp.getServlets().put(entry.getKey(), entry.getValue());
}
}
}
}
servlets.putAll(temp.getServlets());
if (sessionConfig.getSessionTimeout() == null) {
for (WebXml fragment : fragments) {
Integer value = fragment.getSessionConfig().getSessionTimeout();
if (value != null) {
if (temp.getSessionConfig().getSessionTimeout() == null) {
temp.getSessionConfig().setSessionTimeout(value.toString());
} else if (value.equals(temp.getSessionConfig().getSessionTimeout())) {
// Fragments use same value - no conflict
} else {
log.error(sm.getString("webXml.mergeConflictSessionTimeout", fragment.getName(),
fragment.getURL()));
return false;
}
}
}
if (temp.getSessionConfig().getSessionTimeout() != null) {
sessionConfig.setSessionTimeout(temp.getSessionConfig().getSessionTimeout().toString());
}
}
if (sessionConfig.getCookieName() == null) {
for (WebXml fragment : fragments) {
String value = fragment.getSessionConfig().getCookieName();
if (value != null) {
if (temp.getSessionConfig().getCookieName() == null) {
temp.getSessionConfig().setCookieName(value);
} else if (value.equals(temp.getSessionConfig().getCookieName())) {
// Fragments use same value - no conflict
} else {
log.error(sm.getString("webXml.mergeConflictSessionCookieName", fragment.getName(),
fragment.getURL()));
return false;
}
}
}
sessionConfig.setCookieName(temp.getSessionConfig().getCookieName());
}
Map<String,String> mainAttributes = getSessionConfig().getCookieAttributes();
Map<String,String> mergedFragmentAttributes = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
for (WebXml fragment : fragments) {
for (Map.Entry<String,String> attribute : fragment.getSessionConfig().getCookieAttributes().entrySet()) {
// Skip any attribute in a fragment that is defined in the main web.xml
if (!mainAttributes.containsKey(attribute.getKey())) {
if (mergedFragmentAttributes.containsKey(attribute.getKey())) {
// Attribute has already been seen.
// If values are the same, NO-OP. If they are different
// trigger a merge error
if (!mergedFragmentAttributes.get(attribute.getKey()).equals(attribute.getValue())) {
log.error(sm.getString("webXml.mergeConflictSessionCookieAttributes", fragment.getName(),
fragment.getURL()));
return false;
}
} else {
// First time this attribute has been seen. Add it.
mergedFragmentAttributes.put(attribute.getKey(), attribute.getValue());
}
}
}
}
mainAttributes.putAll(mergedFragmentAttributes);
if (sessionConfig.getSessionTrackingModes().isEmpty()) {
for (WebXml fragment : fragments) {
EnumSet<SessionTrackingMode> value = fragment.getSessionConfig().getSessionTrackingModes();
if (!value.isEmpty()) {
if (temp.getSessionConfig().getSessionTrackingModes().isEmpty()) {
temp.getSessionConfig().getSessionTrackingModes().addAll(value);
} else if (value.equals(temp.getSessionConfig().getSessionTrackingModes())) {
// Fragments use same value - no conflict
} else {
log.error(sm.getString("webXml.mergeConflictSessionTrackingMode", fragment.getName(),
fragment.getURL()));
return false;
}
}
}
sessionConfig.getSessionTrackingModes().addAll(temp.getSessionConfig().getSessionTrackingModes());
}
for (WebXml fragment : fragments) {
if (!mergeMap(fragment.getTaglibs(), taglibs, temp.getTaglibs(), fragment, "Taglibs")) {
return false;
}
}
taglibs.putAll(temp.getTaglibs());
for (WebXml fragment : fragments) {
if (fragment.alwaysAddWelcomeFiles || welcomeFiles.isEmpty()) {
for (String welcomeFile : fragment.getWelcomeFiles()) {
addWelcomeFile(welcomeFile);
}
}
}
if (postConstructMethods.isEmpty()) {
for (WebXml fragment : fragments) {
if (!mergeLifecycleCallback(fragment.getPostConstructMethods(), temp.getPostConstructMethods(),
fragment, "Post Construct Methods")) {
return false;
}
}
postConstructMethods.putAll(temp.getPostConstructMethods());
}
if (preDestroyMethods.isEmpty()) {
for (WebXml fragment : fragments) {
if (!mergeLifecycleCallback(fragment.getPreDestroyMethods(), temp.getPreDestroyMethods(), fragment,
"Pre Destroy Methods")) {
return false;
}
}
preDestroyMethods.putAll(temp.getPreDestroyMethods());
}
return true;
}
private <T extends ResourceBase> boolean mergeResourceMap(Map<String,T> fragmentResources,
Map<String,T> mainResources, Map<String,T> tempResources, WebXml fragment) {
for (T resource : fragmentResources.values()) {
String resourceName = resource.getName();
if (mainResources.containsKey(resourceName)) {
mainResources.get(resourceName).getInjectionTargets().addAll(resource.getInjectionTargets());
} else {
// Not defined in main web.xml
T existingResource = tempResources.get(resourceName);
if (existingResource != null) {
if (!existingResource.equals(resource)) {
log.error(sm.getString("webXml.mergeConflictResource", resourceName, fragment.getName(),
fragment.getURL()));
return false;
}
} else {
tempResources.put(resourceName, resource);
}
}
}
return true;
}
private <T> boolean mergeMap(Map<String,T> fragmentMap, Map<String,T> mainMap, Map<String,T> tempMap,
WebXml fragment, String mapName) {
for (Entry<String,T> entry : fragmentMap.entrySet()) {
final String key = entry.getKey();
if (!mainMap.containsKey(key)) {
// Not defined in main web.xml
T value = entry.getValue();
if (tempMap.containsKey(key)) {
if (value != null && !value.equals(tempMap.get(key))) {
log.error(sm.getString("webXml.mergeConflictString", mapName, key, fragment.getName(),
fragment.getURL()));
return false;
}
} else {
tempMap.put(key, value);
}
}
}
return true;
}
private static boolean mergeFilter(FilterDef src, FilterDef dest, boolean failOnConflict) {
if (dest.getAsyncSupported() == null) {
dest.setAsyncSupported(src.getAsyncSupported());
} else if (src.getAsyncSupported() != null) {
if (failOnConflict && !src.getAsyncSupported().equals(dest.getAsyncSupported())) {
return false;
}
}
if (dest.getFilterClass() == null) {
dest.setFilterClass(src.getFilterClass());
} else if (src.getFilterClass() != null) {
if (failOnConflict && !src.getFilterClass().equals(dest.getFilterClass())) {
return false;
}
}
for (Map.Entry<String,String> srcEntry : src.getParameterMap().entrySet()) {
if (dest.getParameterMap().containsKey(srcEntry.getKey())) {
if (failOnConflict && !dest.getParameterMap().get(srcEntry.getKey()).equals(srcEntry.getValue())) {
return false;
}
} else {
dest.addInitParameter(srcEntry.getKey(), srcEntry.getValue());
}
}
return true;
}
private static boolean mergeServlet(ServletDef src, ServletDef dest, boolean failOnConflict) {
// These tests should be unnecessary...
if (dest.getServletClass() != null && dest.getJspFile() != null) {
return false;
}
if (src.getServletClass() != null && src.getJspFile() != null) {
return false;
}
if (dest.getServletClass() == null && dest.getJspFile() == null) {
dest.setServletClass(src.getServletClass());
dest.setJspFile(src.getJspFile());
} else if (failOnConflict) {
if (src.getServletClass() != null &&
(dest.getJspFile() != null || !src.getServletClass().equals(dest.getServletClass()))) {
return false;
}
if (src.getJspFile() != null &&
(dest.getServletClass() != null || !src.getJspFile().equals(dest.getJspFile()))) {
return false;
}
}
// Additive
for (SecurityRoleRef securityRoleRef : src.getSecurityRoleRefs()) {
dest.addSecurityRoleRef(securityRoleRef);
}
if (dest.getLoadOnStartup() == null) {
if (src.getLoadOnStartup() != null) {
dest.setLoadOnStartup(src.getLoadOnStartup().toString());
}
} else if (src.getLoadOnStartup() != null) {
if (failOnConflict && !src.getLoadOnStartup().equals(dest.getLoadOnStartup())) {
return false;
}
}
if (dest.getEnabled() == null) {
if (src.getEnabled() != null) {
dest.setEnabled(src.getEnabled().toString());
}
} else if (src.getEnabled() != null) {
if (failOnConflict && !src.getEnabled().equals(dest.getEnabled())) {
return false;
}
}
for (Map.Entry<String,String> srcEntry : src.getParameterMap().entrySet()) {
if (dest.getParameterMap().containsKey(srcEntry.getKey())) {
if (failOnConflict && !dest.getParameterMap().get(srcEntry.getKey()).equals(srcEntry.getValue())) {
return false;
}
} else {
dest.addInitParameter(srcEntry.getKey(), srcEntry.getValue());
}
}
if (dest.getMultipartDef() == null) {
dest.setMultipartDef(src.getMultipartDef());
} else if (src.getMultipartDef() != null) {
return mergeMultipartDef(src.getMultipartDef(), dest.getMultipartDef(), failOnConflict);
}
if (dest.getAsyncSupported() == null) {
if (src.getAsyncSupported() != null) {
dest.setAsyncSupported(src.getAsyncSupported().toString());
}
} else if (src.getAsyncSupported() != null) {
return !failOnConflict || src.getAsyncSupported().equals(dest.getAsyncSupported());
}
return true;
}
private static boolean mergeMultipartDef(MultipartDef src, MultipartDef dest, boolean failOnConflict) {
if (dest.getLocation() == null) {
dest.setLocation(src.getLocation());
} else if (src.getLocation() != null) {
if (failOnConflict && !src.getLocation().equals(dest.getLocation())) {
return false;
}
}
if (dest.getFileSizeThreshold() == null) {
dest.setFileSizeThreshold(src.getFileSizeThreshold());
} else if (src.getFileSizeThreshold() != null) {
if (failOnConflict && !src.getFileSizeThreshold().equals(dest.getFileSizeThreshold())) {
return false;
}
}
if (dest.getMaxFileSize() == null) {
dest.setMaxFileSize(src.getMaxFileSize());
} else if (src.getMaxFileSize() != null) {
if (failOnConflict && !src.getMaxFileSize().equals(dest.getMaxFileSize())) {
return false;
}
}
if (dest.getMaxRequestSize() == null) {
dest.setMaxRequestSize(src.getMaxRequestSize());
} else if (src.getMaxRequestSize() != null) {
return !failOnConflict || src.getMaxRequestSize().equals(dest.getMaxRequestSize());
}
return true;
}
private boolean mergeLifecycleCallback(Map<String,String> fragmentMap, Map<String,String> tempMap, WebXml fragment,
String mapName) {
for (Entry<String,String> entry : fragmentMap.entrySet()) {
final String key = entry.getKey();
final String value = entry.getValue();
if (tempMap.containsKey(key)) {
if (value != null && !value.equals(tempMap.get(key))) {
log.error(sm.getString("webXml.mergeConflictString", mapName, key, fragment.getName(),
fragment.getURL()));
return false;
}
} else {
tempMap.put(key, value);
}
}
return true;
}
/**
* Generates the sub-set of the web-fragment.xml files to be processed in the order that the fragments must be
* processed as per the rules in the Servlet spec.
*
* @param application The application web.xml file
* @param fragments The map of fragment names to web fragments
* @param servletContext The servlet context the fragments are associated with
*
* @return Ordered list of web-fragment.xml files to process
*/
public static Set<WebXml> orderWebFragments(WebXml application, Map<String,WebXml> fragments,
ServletContext servletContext) {
return application.orderWebFragments(fragments, servletContext);
}
private Set<WebXml> orderWebFragments(Map<String,WebXml> fragments, ServletContext servletContext) {
Set<WebXml> orderedFragments = new LinkedHashSet<>();
boolean absoluteOrdering = getAbsoluteOrdering() != null;
boolean orderingPresent = false;
if (absoluteOrdering) {
orderingPresent = true;
// Only those fragments listed should be processed
Set<String> requestedOrder = getAbsoluteOrdering();
for (String requestedName : requestedOrder) {
if (ORDER_OTHERS.equals(requestedName)) {
// Add all fragments not named explicitly at this point
for (Entry<String,WebXml> entry : fragments.entrySet()) {
if (!requestedOrder.contains(entry.getKey())) {
WebXml fragment = entry.getValue();
if (fragment != null) {
orderedFragments.add(fragment);
}
}
}
} else {
WebXml fragment = fragments.get(requestedName);
if (fragment != null) {
orderedFragments.add(fragment);
} else {
log.warn(sm.getString("webXml.wrongFragmentName", requestedName));
}
}
}
} else {
// Stage 0. Check there were no fragments with duplicate names
for (WebXml fragment : fragments.values()) {
if (fragment.isDuplicated()) {
List<String> duplicates = fragment.getDuplicates();
duplicates.add(0, fragment.getURL().toString());
throw new IllegalArgumentException(
sm.getString("webXml.duplicateFragment", fragment.getName(), duplicates));
}
}
// Stage 1. Make all dependencies bidirectional - this makes the
// next stage simpler.
for (WebXml fragment : fragments.values()) {
Iterator<String> before = fragment.getBeforeOrdering().iterator();
while (before.hasNext()) {
orderingPresent = true;
String beforeEntry = before.next();
if (!beforeEntry.equals(ORDER_OTHERS)) {
WebXml beforeFragment = fragments.get(beforeEntry);
if (beforeFragment == null) {
before.remove();
} else {
beforeFragment.addAfterOrdering(fragment.getName());
}
}
}
Iterator<String> after = fragment.getAfterOrdering().iterator();
while (after.hasNext()) {
orderingPresent = true;
String afterEntry = after.next();
if (!afterEntry.equals(ORDER_OTHERS)) {
WebXml afterFragment = fragments.get(afterEntry);
if (afterFragment == null) {
after.remove();
} else {
afterFragment.addBeforeOrdering(fragment.getName());
}
}
}
}
// Stage 2. Make all fragments that are implicitly before/after
// others explicitly so. This is iterative so the next
// stage doesn't have to be.
for (WebXml fragment : fragments.values()) {
if (fragment.getBeforeOrdering().contains(ORDER_OTHERS)) {
makeBeforeOthersExplicit(fragment.getAfterOrdering(), fragments);
}
if (fragment.getAfterOrdering().contains(ORDER_OTHERS)) {
makeAfterOthersExplicit(fragment.getBeforeOrdering(), fragments);
}
}
// Stage 3. Separate into three groups
Set<WebXml> beforeSet = new HashSet<>();
Set<WebXml> othersSet = new HashSet<>();
Set<WebXml> afterSet = new HashSet<>();
for (WebXml fragment : fragments.values()) {
if (fragment.getBeforeOrdering().contains(ORDER_OTHERS)) {
beforeSet.add(fragment);
fragment.getBeforeOrdering().remove(ORDER_OTHERS);
} else if (fragment.getAfterOrdering().contains(ORDER_OTHERS)) {
afterSet.add(fragment);
fragment.getAfterOrdering().remove(ORDER_OTHERS);
} else {
othersSet.add(fragment);
}
}
// Stage 4. Decouple the groups so the ordering requirements for
// each fragment in the group only refer to other fragments
// in the group. Ordering requirements outside the group
// will be handled by processing the groups in order.
// Note: Only after ordering requirements are considered.
// This is OK because of the processing in stage 1.
decoupleOtherGroups(beforeSet);
decoupleOtherGroups(othersSet);
decoupleOtherGroups(afterSet);
// Stage 5. Order each group
// Note: Only after ordering requirements are considered.
// This is OK because of the processing in stage 1.
orderFragments(orderedFragments, beforeSet);
orderFragments(orderedFragments, othersSet);
orderFragments(orderedFragments, afterSet);
}
// Container fragments are always included
Set<WebXml> containerFragments = new LinkedHashSet<>();
// Find all the container fragments and remove any present from the
// ordered list
for (WebXml fragment : fragments.values()) {
if (!fragment.getWebappJar()) {
containerFragments.add(fragment);
orderedFragments.remove(fragment);
}
}
// Avoid NPE when unit testing
if (servletContext != null) {
// Publish the ordered fragments. The app does not need to know
// about container fragments
List<String> orderedJarFileNames = null;
if (orderingPresent) {
orderedJarFileNames = new ArrayList<>();
for (WebXml fragment : orderedFragments) {
orderedJarFileNames.add(fragment.getJarName());
}
}
servletContext.setAttribute(ServletContext.ORDERED_LIBS, orderedJarFileNames);
}
// The remainder of the processing needs to know about container
// fragments
if (!containerFragments.isEmpty()) {
Set<WebXml> result = new LinkedHashSet<>();
if (containerFragments.iterator().next().getDelegate()) {
result.addAll(containerFragments);
result.addAll(orderedFragments);
} else {
result.addAll(orderedFragments);
result.addAll(containerFragments);
}
return result;
} else {
return orderedFragments;
}
}
private static void decoupleOtherGroups(Set<WebXml> group) {
Set<String> names = new HashSet<>();
for (WebXml fragment : group) {
names.add(fragment.getName());
}
for (WebXml fragment : group) {
fragment.getAfterOrdering().removeIf(entry -> !names.contains(entry));
}
}
private static void orderFragments(Set<WebXml> orderedFragments, Set<WebXml> unordered) {
Set<WebXml> addedThisRound = new HashSet<>();
Set<WebXml> addedLastRound = new HashSet<>();
while (!unordered.isEmpty()) {
Iterator<WebXml> source = unordered.iterator();
while (source.hasNext()) {
WebXml fragment = source.next();
for (WebXml toRemove : addedLastRound) {
fragment.getAfterOrdering().remove(toRemove.getName());
}
if (fragment.getAfterOrdering().isEmpty()) {
addedThisRound.add(fragment);
orderedFragments.add(fragment);
source.remove();
}
}
if (addedThisRound.isEmpty()) {
// Circular
throw new IllegalArgumentException(sm.getString("webXml.mergeConflictOrder"));
}
addedLastRound.clear();
addedLastRound.addAll(addedThisRound);
addedThisRound.clear();
}
}
private static void makeBeforeOthersExplicit(Set<String> beforeOrdering, Map<String,WebXml> fragments) {
for (String before : beforeOrdering) {
if (!before.equals(ORDER_OTHERS)) {
WebXml webXml = fragments.get(before);
if (!webXml.getBeforeOrdering().contains(ORDER_OTHERS)) {
webXml.addBeforeOrderingOthers();
makeBeforeOthersExplicit(webXml.getAfterOrdering(), fragments);
}
}
}
}
private static void makeAfterOthersExplicit(Set<String> afterOrdering, Map<String,WebXml> fragments) {
for (String after : afterOrdering) {
if (!after.equals(ORDER_OTHERS)) {
WebXml webXml = fragments.get(after);
if (!webXml.getAfterOrdering().contains(ORDER_OTHERS)) {
webXml.addAfterOrderingOthers();
makeAfterOthersExplicit(webXml.getBeforeOrdering(), fragments);
}
}
}
}
}
|