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 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 | package Torello.HTML; import java.util.*; import java.util.regex.*; import java.util.stream.*; import java.util.function.*; import Torello.Java.StringParse; import Torello.Java.StrCmpr; import Torello.Java.StrFilter; import Torello.Java.Additional.EffectivelyFinal; import Torello.HTML.parse.HTMLRegEx; import Torello.HTML.NodeSearch.CSSStrException; import Torello.HTML.NodeSearch.TextComparitor; /** * Represents an HTML Element Tag, and is the flagship class of the Java-HTML Library. * * <EMBED CLASS="external-html" DATA-FILE-ID=TAG_NODE> * * <EMBED CLASS="external-html" DATA-FILE-ID=HTML_NODE_SUB_IMG> * * @see TextNode * @see CommentNode * @see HTMLNode */ @Torello.JavaDoc.JDHeaderBackgroundImg(EmbedTagFileID="HTML_NODE_SUBCLASS") public final class TagNode extends HTMLNode implements CharSequence, java.io.Serializable, Cloneable, Comparable<TagNode> { /** <EMBED CLASS="external-html" DATA-FILE-ID="SVUID"> */ public static final long serialVersionUID = 1; // ******************************************************************************************** // ******************************************************************************************** // NON-STATIC FIELDS // ******************************************************************************************** // ******************************************************************************************** /** <EMBED CLASS="external-html" DATA-FILE-ID=TAGNODE_TOK> */ public final String tok; /** <EMBED CLASS="external-html" DATA-FILE-ID=TAGNODE_IS_CLOSING> */ public final boolean isClosing; // ******************************************************************************************** // ******************************************************************************************** // Constructors // ******************************************************************************************** // ******************************************************************************************** /** * <EMBED CLASS='external-html' DATA-FILE-ID=TN_C_DESC_1> * * @param s Any valid HTML tag, for instance: {@code <H1>, <A HREF="somoe url">, * <DIV ID="some id">} etc... * * @throws MalformedTagNodeException If the passed {@code String} wasn't valid - meaning <I>it * did not match the regular-expression {@code parser}.</I> * * @throws HTMLTokException If the {@code String} found where the usual HTML token-element is * situated <I>is not a valid HTML element</I> then the {@code HTMLTokException} will be * thrown. * * @see HTMLTags#getTag_MEM_HEAP_CHECKOUT_COPY(String) */ public TagNode(String s) { super(s); // If the second character of the string is a forward-slash, this must be a closing-element // For Example: </SPAN>, </DIV>, </A>, etc... isClosing = s.charAt(1) == '/'; // This is the Element & Attribute Matcher used by the RegEx Parser. If this Matcher // doesn't find a match, the parameter 's' cannot be a valid HTML Element. NOTE: The // results of this matcher are also used to retrieve attribute-values, but here below, // its results are ignored. Matcher m = HTMLRegEx.P1.matcher(s); if (! m.find()) throw new MalformedTagNodeException( "The parser's regular-expression did not match the constructor-string.\n" + "The exact input-string was: [" + s + "]\n" + "NOTE: The parameter-string is included as a field (ex.str) to this Exception.", s ); // MINOR/MAJOR IMPROVEMENT... REUSE THE "ALLOCATED STRING TOKEN" from HTMLTag's class // THINK: Let the Garbage Collector take out as many duplicate-strings as is possible.. // AND SOONER. DECEMBER 2019: "Optimization" or ... "Improvement" String tokTEMP = m.group(1).toLowerCase(); if ((m.start() != 0) || (m.end() != s.length())) throw new MalformedTagNodeException( "The parser's regular-expression did not match the entire-string-length of the " + "string-parameter to this constructor: m.start()=" + m.start() + ", m.end()=" + m.end() + ".\nHowever, the length of the Input-Parameter String was " + '[' + s.length() + "]\nThe exact input-string was: [" + s + "]\nNOTE: The " + "parameter-string is included as a field (ex.str) to this Exception.", s ); // Get a copy of the 'tok' string that was already allocated on the heap; (OPTIMIZATON) // NOTE: There are already myriad strings for the '.str' field. // ALSO: Don't pay much attention to this line if it doesn't make sense... it's not // that important. If the HTML Token found was not a valid HTML5 token, this field // will be null. // Java 14+ has String.intern() - that's what this is.... this.tok = HTMLTags.getTag_MEM_HEAP_CHECKOUT_COPY(tokTEMP); // Now do the usual error check. if (this.tok == null) throw new HTMLTokException( "The HTML Tag / Token Element that is specified by the input string " + "[" + tokTEMP + "] is not a valid HTML Element Name.\n" + "The exact input-string was: [" + s + "]" ); } // USED-INTERNALLY - bypasses all checks. used when creating new HTML Element-Names // ONLY: class 'HTMLTags' via method 'addTag(...)' shall ever invoke this constructor. // NOTE: This only became necessary because of the MEM_COPY_HEAP optimization. This // optimization expects that there is already a TagNode with element 'tok' in // the TreeSet, which is always OK - except for the method that CREATES NEW HTML // TAGS... a.k.a. HTMLTags.addTag(String). TagNode(String token, TC openOrClosed) { super("<" + ((openOrClosed == TC.ClosingTags) ? "/" : "") + token + ">"); // ONLY CHANGE CASE HERE, NOT IN PREVIOUS-LINE. PAY ATTENTION. this.tok = token.toLowerCase(); this.isClosing = (openOrClosed == TC.ClosingTags) ? true : false; } /** * Convenience Constructor. * <BR />Invokes: {@link #TagNode(String, Properties, Iterable, SD, boolean)} * <BR />Passes: null to the Boolean / Key-Only Attributes {@code Iterable} */ public TagNode(String tok, Properties attributes, SD quotes, boolean addEndingForwardSlash) { this(tok, attributes, null /* keyOnlyAttributes */, quotes, addEndingForwardSlash); } /** * <EMBED CLASS='external-html' DATA-FILE-ID=TN_C_DESC_2> * * @param tok <EMBED CLASS='external-html' DATA-FILE-ID=TN_C_TOK> * @param attributes <EMBED CLASS='external-html' DATA-FILE-ID=TN_C_ATTRIBUTES> * @param keyOnlyAttributes <EMBED CLASS='external-html' DATA-FILE-ID=TN_C_KO_ATTRIBUTES> * @param quotes <EMBED CLASS='external-html' DATA-FILE-ID=TN_C_QUOTES> * @param addEndingForwardSlash <EMBED CLASS='external-html' DATA-FILE-ID=TN_C_AEFS> * * @throws InnerTagKeyException <EMBED CLASS="external-html" DATA-FILE-ID="ITKEYEXPROP"> * @throws QuotesException <EMBED CLASS="external-html" DATA-FILE-ID="QEX"> * @throws HTMLTokException if an invalid HTML 4 or 5 token is not present * <B>(check is {@code CASE_INSENSITIVE})</B> * * @see InnerTagKeyException#check(String, String) * @see QuotesException#check(String, SD, String) * @see #generateElementString(String, Properties, Iterable, SD, boolean) */ public TagNode( String tok, Properties attributes, Iterable<String> keyOnlyAttributes, SD quotes, boolean addEndingForwardSlash ) { this( generateElementString (tok, attributes, keyOnlyAttributes, quotes, addEndingForwardSlash)); } /** * This builds an HTML Element as a {@code String.} This {@code String} may be passed to the * standard HTML {@code TagNode} Constructor that accepts a {@code String} as input. * * @param tok <EMBED CLASS='external-html' DATA-FILE-ID=TN_C_TOK> * @param attributes <EMBED CLASS='external-html' DATA-FILE-ID=TN_C_ATTRIBUTES> * @param keyOnlyAttributes <EMBED CLASS='external-html' DATA-FILE-ID=TN_C_KO_ATTRIBUTES> * @param quotes <EMBED CLASS='external-html' DATA-FILE-ID=TN_C_QUOTES> * @param addEndingForwardSlash <EMBED CLASS='external-html' DATA-FILE-ID=TN_C_AEFS> * * @throws InnerTagKeyException <EMBED CLASS="external-html" DATA-FILE-ID="ITKEYEXPROP"> * @throws QuotesException <EMBED CLASS="external-html" DATA-FILE-ID="QEX"> * @throws HTMLTokException if an invalid HTML 4 or 5 token is not present * <B>{@code CASE_INSENSITIVE}</B> * * @return This method returns an HTML Element, as a {@code String}. * * @see HTMLTokException#check(String[]) * @see InnerTagKeyException#check(String, String) * @see QuotesException#check(String, SD, String) */ protected static String generateElementString( String tok, Properties attributes, Iterable<String> keyOnlyAttributes, SD quotes, boolean addEndingForwardSlash ) { String computedQuote = (quotes == null) ? "" : ("" + quotes.quote); HTMLTokException.check(tok); // The HTML Element is "built" using a StringBuilder StringBuilder sb = new StringBuilder(); sb.append("<" + tok); // If there are any Inner-Tag Key-Value pairs, insert them first. if ((attributes != null) && (attributes.size() > 0)) for (String key : attributes.stringPropertyNames()) { String value = attributes.getProperty(key); InnerTagKeyException.check(key, value); QuotesException.check( value, quotes, "parameter 'Properties' contains:\nkey:\t" + key + "\nvalue:\t" + value + "\n" ); sb.append(" " + key + '=' + computedQuote + value + computedQuote); } // If there are any Key-Only Inner-Tags (Boolean Attributes), insert them next. if (keyOnlyAttributes != null) for (String keyOnlyAttribute : keyOnlyAttributes) { InnerTagKeyException.check(keyOnlyAttribute); sb.append(" " + keyOnlyAttribute); } // Add a closing forward-slash sb.append(addEndingForwardSlash ? " />" : ">"); // Build the String, using the StringBuilder, and return the newly-constructed HTML Element return sb.toString(); } // ******************************************************************************************** // ******************************************************************************************** // isTag // ******************************************************************************************** // ******************************************************************************************** /** * This method identifies that {@code 'this'} instance of (abstract parent-class) * {@link HTMLNode} is, indeed, an instance of sub-class {@code TagNode}. * * <BR /><BR /><B CLASS=JDDescLabel>Final Method:</B> * * <BR />This method is final, and cannot be modified by sub-classes. * * @return This method shall always return <B>TRUE</B> It overrides the parent-class * {@code HTMLNode} method {@link #isTagNode()}, which always returns <B>FALSE</B>. */ @Override public final boolean isTagNode() { return true; } /** * <EMBED CLASS='external-html' DATA-FILE-ID=TN_IF_TN_DESC> * * <BR /><BR /><B CLASS=JDDescLabel>Final Method:</B> * * <BR />This method is final, and cannot be modified by sub-classes. * * @return <EMBED CLASS='external-html' DATA-FILE-ID=TN_IF_TN_RET> */ @Override public final TagNode ifTagNode() { return this; } /** * <EMBED CLASS='external-html' DATA-FILE-ID=TN_OPENTAG_PWA_DESC> * * <BR /><BR /><B CLASS=JDDescLabel>Final Method:</B> * * <BR />This method is final, and cannot be modified by sub-classes. * * @return <EMBED CLASS='external-html' DATA-FILE-ID=TN_OPENTAG_PWA_RET> */ @Override public final TagNode openTagPWA() { // Closing TagNode's simply may not have attributes if (this.isClosing) return null; // A TagNode whose '.str' field is not AT LEAST 5 characters LONGER than the length of the // HTML-Tag / Token, simply cannot have an attribute. // // NOTE: Below is the shortest possible HTML tag that could have an attribute-value pair. // COMPUTE: '<' + TOK.LENGTH + SPACE + 'c' + '=' + '>' if (this.str.length() < (this.tok.length() + 5)) return null; // This TagNode is an opening HTML tag (like <DIV ...>, rather than </DIV>), // and there are at least two additional characters after the token, such as: <DIV A...> // It is not guaranteed that this tag has attributes, but it is possibly - based on these /// optimization methods, and further investigation would have merit. return this; } /** * This is a loop-optimization method that makes finding opening {@code TagNode's} - <B>with * attribute-values</B> - quites a bit faster. All {@code HTMLNode} subclasses implement this * method, but only {@code TagNode} instances will ever return a non-null value. * * <BR /><BR /><B CLASS=JDDescLabel>Final Method:</B> * * <BR />This method is final, and cannot be modified by sub-classes. * * @return Returns null if and only if {@code 'this'} instance' {@link #isClosing} field is * false. When a non-null return-value is acheived, that value will always be {@code 'this'} * instance. */ @Override public final TagNode openTag() { return isClosing ? null : this; } /** * Receives a list of html-elements which the {@code this.tok} field must match. * This method returns <B>TRUE</B> if any match is found. * * <BR /><BR /><IMG SRC='doc-files/img/isTag.png' CLASS=JDIMG ALT='example'> * * @param possibleTags This non-null list of potential HTML tags. * @return <B>TRUE</B> If {@code this.tok} matches at least one of these tags. * @see #tok */ public boolean isTag(String... possibleTags) { for (String htmlTag : possibleTags) if (htmlTag.equalsIgnoreCase(this.tok)) return true; return false; } /** * Receives a list of html-elements which {@code this.tok} field <B>MAY NOT</B> match. * This method returns <B>FALSE</B> if any match is found. * * @param possibleTags This must be a non-null list of potential HTML tags. * * @return <B>FALSE</B> If {@code this.tok} matches any one of these tags, and <B>TRUE</B> * otherwise. * * @see #tok * @see #isTag(String[]) */ public boolean isTagExcept(String... possibleTags) { for (String htmlTag : possibleTags) if (htmlTag.equalsIgnoreCase(this.tok)) return false; return true; } /** * Receives two "criteria-specifier" parameters. This method shall return <B>TRUE</B> if: * * <BR /><BR /><UL CLASS="JDUL"> * <LI>Field {@code 'isClosing'} is equal-to / consistent-with {@code TC tagCriteria}</LI> * <LI>Field {@code 'tok'} is equal to at least one of the {@code 'possibleTags'}</LI> * </UL> * * <BR /><BR /><IMG SRC='doc-files/img/isTag2.png' CLASS=JDIMG ALT='example'> * * @param tagCriteria This ought to be either {@code 'TC.OpeningTags'} or * {@code TC.ClosingTags'}. This parameter specifies what {@code 'this'} instance of * {@code TagNode} is expected to contain, as {@code this.isClosing} field shall be compared * against it. * * @param possibleTags This is presumed to be a non-zero-length, and non-null-valued list of * html tokens. * * @return <B>TRUE</B> If {@code 'this'} matches the specified criteria, and <B>FALSE</B> * otherwise. * * @see TC * @see #isClosing * @see #tok */ public boolean isTag(TC tagCriteria, String... possibleTags) { // Requested an "OpeningTag" but this is a "ClosingTag" if ((tagCriteria == TC.OpeningTags) && this.isClosing) return false; // Requested a "ClosingTag" but this is an "OpeningTag" if ((tagCriteria == TC.ClosingTags) && ! this.isClosing) return false; for (int i=0; i < possibleTags.length; i++) if (this.tok.equalsIgnoreCase(possibleTags[i])) // Found a TOKEN match, return TRUE immediately return true; // None of the elements in 'possibleTags' equalled tn.tok return false; } /** * Receives a {@code TagNode} and then two "criteria-specifier" parameters. This method shall * return <B>FALSE</B> if: * * <BR /><BR /><UL CLASS="JDUL"> * <LI> Field {@code 'isClosing'} is <B><I>not</I></B> equal-to / * <B><I>not</I></B> consistent-with {@code TC tagCriteria}</LI> * <LI> Field {@code 'tok'} is <B><I>equal-to</I></B> any of the {@code 'possibleTags'}</LI> * </UL> * * @param tagCriteria tagCriteria This ought to be either {@code 'TC.OpeningTags'} or * {@code TC.ClosingTags'} This parameter specifies what {@code 'this'} instance of * {@code TagNode} is expected to contain, as {@code this.isClosing} field shall be compared * against it. * * @param possibleTags This is presumed to be a non-zero-length, and non-null-valued list of * html tokens. * * @return <B>TRUE</B> If this {@code TagNode 'n'} matches the specified criteria explained * above, and <B>FALSE</B> otherwise. * * @see TC * @see #tok * @see #isClosing */ public boolean isTagExcept(TC tagCriteria, String... possibleTags) { // Requested an "OpeningTag" but this is a "ClosingTag" if ((tagCriteria == TC.OpeningTags) && this.isClosing) return false; // Requested a "ClosingTag" but this is an "OpeningTag" if ((tagCriteria == TC.ClosingTags) && ! this.isClosing) return false; for (int i=0; i < possibleTags.length; i++) if (this.tok.equalsIgnoreCase(possibleTags[i])) // The Token of the input node was a match with one of the 'possibleTags' // Since this is "Except" - we must return 'false' return false; // None of the elements in 'possibleTags' equalled tn.tok // since this is "Except" - return 'true' return true; } // ******************************************************************************************** // ******************************************************************************************** // Main Method 'AV' // ******************************************************************************************** // ******************************************************************************************** /** * <EMBED CLASS="external-html" DATA-FILE-ID=TN_AV_DESC> * <EMBED CLASS="external-html" DATA-FILE-ID=TN_AV_DESC_EXAMPLE> * @param innerTagAttribute <EMBED CLASS="external-html" DATA-FILE-ID=TN_AV_ITA> * @return <EMBED CLASS="external-html" DATA-FILE-ID=TN_AV_RET> * @see #isClosing * @see #str * @see #tok * @see StringParse#ifQuotesStripQuotes(String) * @see AttrRegEx#KEY_VALUE_REGEX */ public String AV(String innerTagAttribute) { // All HTML element tags that start like: </DIV> with a front-slash. // They may not legally contain inner-tag attributes. if (this.isClosing) return null; // All HTML element tags that contain only <TOK> (TOK <==> Tag-Name) in their 'str' field // Specifically: '<', TOKEN, '>', (Where TOKEN is 'div', 'span', 'table', 'ul', etc...) // are TOO SHORT to have the attribute, so don't check... return null. if (this.str.length() < (3 + this.tok.length() + (innerTagAttribute = innerTagAttribute.trim()).length())) return null; // Matches "Attribute / Inner-Tag Key-Value" Pairs. Matcher m = AttrRegEx.KEY_VALUE_REGEX.matcher(this.str); // This loop iterates the KEY_VALUE PAIRS THAT HAVE BEEN FOUND. /// NOTE: The REGEX Matches on Key-Value Pairs. while (m.find()) // m.group(2) is the "KEY" of the Attribute KEY-VALUE Pair // m.group(3) is the "VALUE" of the Attribute. if (m.group(2).equalsIgnoreCase(innerTagAttribute)) return StringParse.ifQuotesStripQuotes(m.group(3)); // This means the attribute name provided to parameter 'innerTagAttribute' was not found. return null; } /** * <SPAN STYLE="color: red;"><B>OPT: Optimized</B></SPAN> * * <BR /><BR /> This is an "optimized" version of method {@link #AV(String)}. This method does * the exact same thing as {@code AV(...)}, but leaves out parameter-checking and * error-checking. This is used internally (repeatedly) by the NodeSearch Package Search Loops. * * @param innerTagAttribute This is the inner-tag / attribute <B STYLE="color: red;">name</B> * whose <B STYLE="color: red;">value</B> is hereby being requested. * * @return {@code String}-<B STYLE="color: red;">value</B> of this inner-tag / attribute. * * @see StringParse#ifQuotesStripQuotes(String) * @see #str * @see TagNode.AttrRegEx#KEY_VALUE_REGEX */ public String AVOPT(String innerTagAttribute) { // COPIED DIRECTLY FROM class TagNode, leaves off initial tests. // Matches "Attribute / Inner-Tag Key-Value" Pairs. Matcher m = AttrRegEx.KEY_VALUE_REGEX.matcher(this.str); // This loop iterates the KEY_VALUE PAIRS THAT HAVE BEEN FOUND. /// NOTE: The REGEX Matches on Key-Value Pairs. while (m.find()) // m.group(2) is the "KEY" of the Attribute KEY-VALUE Pair // m.group(3) is the "VALUE" of the Attribute. if (m.group(2).equalsIgnoreCase(innerTagAttribute)) return StringParse.ifQuotesStripQuotes(m.group(3)); // This means the attribute name provided to parameter 'innerTagAttribute' was not found. return null; } // ******************************************************************************************** // ******************************************************************************************** // Attribute Modify-Value methods // ******************************************************************************************** // ******************************************************************************************** /** * <EMBED CLASS="external-html" DATA-FILE-ID=TN_SET_AV_DESC> * @param attribute <EMBED CLASS="external-html" DATA-FILE-ID=TN_SET_AV_ATTR> * @param value Any valid attribute-<B STYLE="color: red;">value</B>. This parameter may not * be null, or a {@code NullPointerException} will throw. * @param quote <EMBED CLASS="external-html" DATA-FILE-ID=TN_SET_AV_QUOTE> * @throws InnerTagKeyException <EMBED CLASS="external-html" DATA-FILE-ID="ITKEYEX2"> * @throws QuotesException <EMBED CLASS="external-html" DATA-FILE-ID="QEX"> * @throws ClosingTagNodeException <EMBED CLASS="external-html" DATA-FILE-ID=CTNEX> * @throws HTMLTokException If an invalid HTML 4 or 5 token is not present * (<B>{@code CASE_INSENSITIVE}</B>). * @return <EMBED CLASS="external-html" DATA-FILE-ID=TN_SET_AV_RET> * @see ClosingTagNodeException#check(TagNode) * @see #generateElementString(String, Properties, Iterable, SD, boolean) * @see #setAV(Properties, SD) * @see #tok * @see #str * @see #isClosing */ public TagNode setAV(String attribute, String value, SD quote) { ClosingTagNodeException.check(this); if (attribute == null) throw new NullPointerException( "You have passed 'null' to the 'attribute' (attribute-name) String-parameter, " + "but this is not allowed here." ); if (value == null) throw new NullPointerException( "You have passed 'null' to the 'attribute' (attribute-value) String-parameter, " + "but this is not allowed here." ); // Retrieve all "Key-Only" (Boolean) Attributes from 'this' (the original) TagNode // Use Java Streams to filter out any that match the newly-added attribute key-value pair. // SAVE: Save the updated / shortened list to a List<String> List<String> prunedOriginalKeyOnlyAttributes = allKeyOnlyAttributes(true) .filter((String originalKeyOnlyAttribute) -> ! originalKeyOnlyAttribute.equalsIgnoreCase(attribute)) .collect(Collectors.toList()); // Retrieve all Inner-Tag Key-Value Pairs. Preserve the Case of the Attributes. Preserve // the Quotation-Marks. Properties p = allAV(true, true); String originalValueWithQuotes = null; String computedQuote = null; // NOTE, there should only be ONE instance of an attribute in an HTML element, but // malformed HTML happens all the time, so to keep this method safe, it checks // (and removes) the entire attribute-list for matches - not just the first found instance. for (String key : p.stringPropertyNames()) if (key.equalsIgnoreCase(attribute)) { Object temp = p.remove(key); if (temp instanceof String) originalValueWithQuotes = (String) temp; } // If the user does not wish to "change" the original quote choice, then find out what // the original-quote choice was... if ( (quote == null) && (originalValueWithQuotes != null) && (originalValueWithQuotes.length() >= 2) ) { char s = originalValueWithQuotes.charAt(0); char e = originalValueWithQuotes.charAt(originalValueWithQuotes.length() - 1); if ((s == e) && (s == '\'')) computedQuote = "" + SD.SingleQuotes.quote; else if ((s == e) && (s == '"')) computedQuote = "" + SD.DoubleQuotes.quote; else computedQuote = ""; } else if (quote == null) computedQuote = ""; else computedQuote = "" + quote.quote; p.put(attribute, computedQuote + value + computedQuote); return new TagNode( generateElementString( // Rather than using '.tok' here, preserve the case of the original HTML Element this.str.substring(1, 1 + tok.length()), p, prunedOriginalKeyOnlyAttributes, null /* SD */, this.str.endsWith("/>") )); } /** * This allows for inserting or updating multiple {@code TagNode} inner-tag * <B STYLE="color: red;">key-value</B> pairs with a single method invocation. * * @param attributes These are the new attribute <B STYLE="color: red;">key-value</B> pairs to * be inserted. * * @param defaultQuote This is the default quotation mark to use, if the {@code 'attribute'} * themselves do not already have quotations. * * <BR /><BR /><B><SPAN STYLE='color: red;'>IMPORTANT:</B></SPAN> If this value is used, then * none of the provided {@code Property}-<B STYLE="color: red;">values</B> of the input * {@code java.lang.Properties} instance should have quotes already. Each of these * new-<B STYLE="color: red;">values</B> will be wrapped in the quote that is provided as the * value to this parameter. * * <BR /><BR /><B><SPAN STYLE='color: red;'>HOWEVER:</B></SPAN> If this parameter is passed a * value of 'null', then no quotes will be added to the new <B STYLE="color: red;">keys</B> - * <I>unless the attribute being inserted is replacing a previous attribute that was already * present in the element.</I> In this case, the original quotation shall be used. If this * parameter receives 'null' and any of the new {@code Properties} were not already present in * the original ({@code 'this'}) element, then no quotation marks will be used, which may * throw a {@code QuotesException} if the attribute <B STYLE="color: red;">value</B> contains * any white-space. * * @throws InnerTagKeyException <EMBED CLASS="external-html" DATA-FILE-ID="ITKEYEXPROP"> * * @throws QuotesException if there are "quotes within quotes" problems, due to the * <B STYLE="color: red;">values</B> of the <B STYLE="color: red;">key-value</B> pairs. * * @throws HTMLTokException if an invalid HTML 4 or 5 token is not present * <B>({@code CASE_INSENSITIVE})</B> * * @throws ClosingTagNodeException <EMBED CLASS="external-html" DATA-FILE-ID=CTNEX> * * @return An HTML {@code TagNode} instance with updated {@code TagNode} information. * * <BR /><BR /><B><SPAN STYLE="color: red;">IMPORTANT:</SPAN></B> Because * <I>{@code TagNode's} are immutable</I> (since they are just wrapped-java-{@code String's}, * which are also immutable), it is important to remember that this method <I><B>does not * change the contents</B></I> of a {@code TagNode}, but rather <I><B>returns an entirely * new {@code TagNode}</I></B> as a result instead. * * @see ClosingTagNodeException#check(TagNode) * @see #setAV(String, String, SD) * @see #allKeyOnlyAttributes(boolean) * @see #tok * @see #str * @see #isClosing */ public TagNode setAV(Properties attributes, SD defaultQuote) { ClosingTagNodeException.check(this); // Check that this attributes has elements. if (attributes.size() == 0) throw new IllegalArgumentException( "You have passed an empty java.util.Properties instance to the " + "setAV(Properties, SD) method" ); // Retrieve all Inner-Tag Key-Value Pairs. // Preserve: the Case of the Attributes. // Preserve: the Quotation-Marks. Properties originalAttributes = allAV(true, true); // Retrieve all "Key-Only" (Boolean) attributes from the new / update attribute-list Set<String> newAttributeKeys = attributes.stringPropertyNames(); // Retrieve all "Key-Only" (Boolean) Attributes from 'this' (the original) TagNode // Use Java Streams to filter out all the ones that need to be clobbered by-virtue-of // the fact that they are present in the new / parameter-updated attribute key-value list. // SAVE: Save the updated / shortened list to a List<String> List<String> prunedOriginalKeyOnlyAttributes = allKeyOnlyAttributes(true) .filter((String originalKeyOnlyAttribute) -> { // Returns false when the original key-only attribute matches one of the // new attributes being inserted. Notice that a case-insensitive comparison // must be performed - to preserve case. for (String newKey : newAttributeKeys) if (newKey.equalsIgnoreCase(originalKeyOnlyAttribute)) return false; return true; }) .collect(Collectors.toList()); // NOTE: There is no need to check the validity of the new attributes. The TagNode // constructor that is invoked on the last line of this method will do a // validity-check on the attribute key-names provided to the 'attributes' // java.util.Properties instance passed to to this method. for (String newKey : newAttributeKeys) { String originalValueWithQuotes = null; String computedQuote = null; // NOTE, there should only be ONE instance of an attribute in an HTML element, but // malformed HTML happens all the time, so to keep this method safe, it checks (and // removes) the entire attribute-list for matches - not just the first found instance. for (String originalKey : originalAttributes.stringPropertyNames()) if (originalKey.equalsIgnoreCase(newKey)) { // Remove the original key-value inner-tag pair. Object temp = originalAttributes.remove(originalKey); if (temp instanceof String) originalValueWithQuotes = (String) temp; } // If the user does not wish to "change" the original quote choice, then find out what // the original-quote choice was... if ( (defaultQuote == null) && (originalValueWithQuotes != null) && (originalValueWithQuotes.length() >= 2) ) { char s = originalValueWithQuotes.charAt(0); char e = originalValueWithQuotes.charAt(originalValueWithQuotes.length() - 1); if ((s == e) && (s == '\'')) computedQuote = "" + SD.SingleQuotes.quote; else if ((s == e) && (s == '"')) computedQuote = "" + SD.DoubleQuotes.quote; else computedQuote = ""; } else if (defaultQuote == null) computedQuote = ""; else computedQuote = "" + defaultQuote.quote; // Insert the newly, updated key-value inner-tag pair. This 'Properties' will be // used to construct a new TagNode. originalAttributes.put(newKey, computedQuote + attributes.get(newKey) + computedQuote); } return new TagNode( generateElementString( // Rather than using '.tok' here, preserve the case of the original HTML Element this.str.substring(1, 1 + tok.length()), originalAttributes, prunedOriginalKeyOnlyAttributes, null /* SD */, this.str.endsWith("/>") )); } /** * This will append a substring to the attribute <B STYLE="color: red;">value</B> of an HTML * {@code TagNode}. * * This method can be very useful, for instance when dealing with CSS tags that are inserted * inside the HTML node itself. For example, in order to add a {@code 'color: red; * background: white;'} portion to the CSS {@code 'style'} tag of an HTML * {@code <TABLE STYLE="...">} element, without clobbering the {@code style}-information that * is already inside the element, using this method will achieve that. * * @param attribute The <B STYLE="color: red;">name</B> of the attribute to which the * <B STYLE="color: red;">value</B> must be appended. This parameter may not be null, or a * {@code NullPointerException} will throw. * * @param appendStr The {@code String} to be appended to the * attribute-<B STYLE="color: red;">value</B>. * * @param startOrEnd If this parameter is <B>TRUE</B> then the append-{@code String} will be * inserted at the beginning (before) whatever the current attribute-<B STYLE="color: red;"> * value</B> is. If this parameter is <B>FALSE</B> then the append-{@code String} will be * inserted at the end (after) the current attribute-<B STYLE="color: red;">value</B> * {@code String}. * * <BR /><BR /><B>NOTE:</B> If tag element currently does not posses this attribute, then the * <B STYLE="color: red;">attribute/value</B> pair will be created and inserted with its * <B STYLE="color: red;">value</B> set to the value of {@code 'appendStr'.} * * @param quote <EMBED CLASS='external-html' DATA-FILE-ID=TGND_QUOTE_EXPL> * * <BR /><BR />It is important to note that "appending" a {@code String} to an attribute's * <B STYLE='color: red;'>value</B> will often (but not always) mean that the new * attribute-<B STYLE='color: red;'>value</B> will have a space character. <B><I>If</I></B> * this parameter were passed null, <B><I>and if</I></B> the original tag had a value, but did * not use any quotes, <B><I>then</I></B> the attribute's ultimate inclusion into the tag would * generate invalid HTML, and the invocation of {@link #setAV(String, String, SD)} would * throw a {@link QuotesException}. * * @return Since all instances of {@code TagNode} are immutable, this method will not actually * alter the {@code TagNode} element, but rather create a new object reference that contains * the updated attribute. * * @see #AV(String) * @see #setAV(String, String, SD) * @see ClosingTagNodeException#check(TagNode) * * @throws ClosingTagNodeException <EMBED CLASS="external-html" DATA-FILE-ID=CTNEX> * * @throws QuotesException The <B><A HREF=#QUOTEEX>rules</A></B> for quotation usage apply * here too, and see that explanation for how how this exception could be thrown. */ public TagNode appendToAV(String attribute, String appendStr, boolean startOrEnd, SD quote) { ClosingTagNodeException.check(this); if (attribute == null) throw new NullPointerException( "You have passed 'null' to the 'attribute' (attribute-name) String-parameter, " + "but this is not allowed here." ); if (appendStr == null) throw new NullPointerException( "You have passed 'null' to the 'appendStr' (attribute-value-append-string) " + "String-parameter, but this is not allowed here." ); String curVal = AV(attribute); if (curVal == null) curVal = ""; // This decides whether to insert the "appendStr" before the current value-string, // or afterwards. This is based on the passed boolean-parameter 'startOrEnd' curVal = startOrEnd ? (appendStr + curVal) : (curVal + appendStr); // Reuse the 'setAV(String, String, SD)' method already defined in this class. return setAV(attribute, curVal, quote); } // ******************************************************************************************** // ******************************************************************************************** // Attribute Removal Operations // ******************************************************************************************** // ******************************************************************************************** /** * Convenience Method. * <BR />Invokes: {@link #removeAttributes(String[])} */ public TagNode remove(String attributeName) { return removeAttributes(attributeName); } /** * <EMBED CLASS="external-html" DATA-FILE-ID=TN_REM_ATTR_DESC> * @param attributes <EMBED CLASS="external-html" DATA-FILE-ID=TN_REM_ATTR_ATTR> * @return <EMBED CLASS="external-html" DATA-FILE-ID=TN_REM_ATTR_RET> * @throws ClosingTagNodeException <EMBED CLASS="external-html" DATA-FILE-ID=CTNEX> * @see ClosingTagNodeException#check(TagNode) * @see #tok * @see #isClosing * @see #str * @see #TagNode(String) * @see #generateElementString(String, Properties, Iterable, SD, boolean) */ public TagNode removeAttributes(String... attributes) { ClosingTagNodeException.check(this); // Retrieve all Inner-Tag Key-Value Pairs. Preserve the Case of the Attributes. Preserve // the Quotation-Marks. Properties originalAttributes = allAV(true, true); // Remove any attributes from the "Attributes Key-Value Properties Instance" which MATCH // the attribute names that have been EXPLICITLY REQUESTED FOR REMOVAL for (String key : originalAttributes.stringPropertyNames()) for (String attribute : attributes) if (key.equalsIgnoreCase(attribute)) originalAttributes.remove(key); // Retrieve all "Boolean Attributes" (key-no-value). Preserve the Case of these Attributes // Retain only the attributes in the 'filteredKeyOnlyAttributes' String-Array which have // PASSED THE FILTER OPERATION. The filter operation only returns TRUE if the // requested-attribute-list does not contain a copy of the Key-Only-Attribute // // NOTE: 'true' is passed as input to the 'allKeyOnlyAttributes(boolean)' method to request // that CASE be PRESERVED. Iterable<String> prunedKeyOnlyAttributes = allKeyOnlyAttributes(true) .filter((String attribute) -> { // Returns false when the original key-only attribute matches one of the attributes // that was requested to to be removed. Notice that a case-insensitive comparison // must be performed. for (String removeAttributes : attributes) if (removeAttributes.equalsIgnoreCase(attribute)) return false; return true; }) .collect(Collectors.toList()); return new TagNode( generateElementString( // Rather than using '.tok' here, preserve the case of the original HTML Element this.str.substring(1, 1 + tok.length()), originalAttributes, prunedKeyOnlyAttributes, /* SD */ null, this.str.endsWith("/>") )); } /** * {@code TagNode's} are immutable. And because of this, calling {@code removeAllAV()} is * actually the same as retrieving the standard, zero-attribute, pre-instantiated instance of * an HTML Element. Pre-instantiated <B><I>factory-instances</I></B> of {@code class TagNode} * for every HTML-Element are stored by {@code class HTMLTags} inside a {@code Hashtable.} * They can be retrieved in multiple ways, two of which are found in methods in this class. * * <BR /><BR /><B>Point of Interest:</B> Calling these three different methods will all return * <I>identical</I> {@code Object} references: * * <BR /><BR /> * * <UL CLASS="JDUL"> * <LI>{@code TagNode v1 = myTagNode.removeAllAV(); } </LI> * <LI>{@code TagNode v2 = TagNode.getInstance(myTagToken, openOrClosed); } </LI> * <LI>{@code TagNode v3 = HTMLTag.hasTag(myTagToken, openOrClosed); } </LI> * <LI><SPAN STYLE="color: red;">{@code assert((v1 == v2) && (v2 == v3)); }</SPAN></LI> * </UL> * * <BR /><BR /><IMG SRC='doc-files/img/removeAllAV.png' CLASS=JDIMG ALT='example'> * * @return An HTML {@code TagNode} instance with all inner attributes removed. * * <BR /><BR /><B>NOTE:</B> If this tag contains an "ending forward slash" that ending slash * will not be included in the output {@code TagNode.} * * <BR /><BR /><B><SPAN STYLE="color: red;">IMPORTANT:</SPAN></B> Because <I>{@code TagNode's} * are immutable</I> (since they are just wrapped-java-{@code String's}, which are also * immutable), it is important to remember that this method <I><B>does not change the * contents</B></I> of a {@code TagNode}, but rather <I><B>returns an entirely new * {@code TagNode}</I></B> as a result instead. * * @throws ClosingTagNodeException <EMBED CLASS="external-html" DATA-FILE-ID=CTNEX> * * @see ClosingTagNodeException#check(TagNode) * @see #getInstance(String, TC) * @see #str * @see #tok * @see TC#OpeningTags */ public TagNode removeAllAV() { ClosingTagNodeException.check(this); // NOTE: We *CANNOT* use the 'tok' field to instantiate the TagNode here, because the 'tok' // String-field is *ALWAYS* guaranteed to be in a lower-case format. The 'str' // String-field, however uses the original case that was found on the HTML Document by the // parser (or in the Constructor-Parameters that were passed to construct 'this' instance // of TagNode. return getInstance(this.str.substring(1, 1 + tok.length()), TC.OpeningTags); } // ******************************************************************************************** // Retrieve all attributes // ******************************************************************************************** /** * Convenience Method. * <BR />Invokes: {@link #allAV(boolean, boolean)} * <BR />Attribute-<B STYLE="color: red;">names</B> will be in lower-case. */ public Properties allAV() { return allAV(false, false); } /** * This will copy every attribute <B STYLE="color: red;">key-value</B> pair inside * {@code 'this'} HTML {@code TagNode} element into a {@code java.util.Properties} Hash-Table. * * <BR /><BR /><B>RETURN-VALUE NOTE:</B> This method shall not return any "Key-Only Attributes" * (a.k.a. "Boolean Attributes"). The most commonly used "Boolean Attribute" example is the * {@code 'HIDDEN'} key-word that is used to prevent the browser from displaying an HTML * Element. Inner-tags that represent attribute <B STYLE="color: red;">key-value</B> pairs are * the only attributes that may be included in the returned {@code 'Properties'} instance. * * <BR /><BR /><IMG SRC='doc-files/img/allAV.png' CLASS=JDIMG ALT="example"> * * @param keepQuotes If this parameter is passed <B>TRUE</B>, then any surrounding quotation * marks will be included for each the <B STYLE="color: red;">values</B> of each attribute * key-value pair. * * @param preserveKeysCase If this parameter is passed <B>TRUE</B>, then the method * {@code String.toLowerCase()} will not be invoked on any of the * <B STYLE="color: red;">keys</B> (attribute-names) of each inner-tag key-value pair. * * <EMBED CLASS="external-html" DATA-FILE-ID=TAGNODE_PRESERVE_C> * * @return This returns a list of each and every attribute-<B STYLE="color: red;">name</B> - * <I>and the associate <B STYLE="color: red;">value</B> of the attribute</I> - found in * {@code 'this' TagNode}. An instance of {@code class java.util.Properties} is used to store * the attribute <B STYLE="color: red;">key-value</B> pairs. * * <BR /><BR /><B>NOTE:</B> This method will <B>NOT</B> return any boolean, * <B STYLE="color: red;">key-only</B> attributes present in {@code 'this' TagNode}. * * <BR /><BR /><B>ALSO:</B> This method shall not return {@code 'null'}. If there do not * exist any Attribute-Value Pairs, or if {@code 'this'} node is a closing-element, then * an empty {@code 'Properties'} instance shall be returned. * * @see StringParse#ifQuotesStripQuotes(String) * @see AttrRegEx#KEY_VALUE_REGEX * @see #tok * @see #str */ public Properties allAV(boolean keepQuotes, boolean preserveKeysCase) { Properties ret = new Properties(); // NOTE: OPTIMIZED, "closing-versions" of the TagNode, and TagNode's whose 'str' field is // is only longer than the token, itself, by 3 or less characters cannot have // attributes. // CHARS: '<', TOKEN, SPACE, '>' // RET: In that case, just return an empty 'Properties' instance. if (isClosing || (str.length() <= (tok.length() + 3))) return ret; // This RegEx Matcher 'matches' against Attribute/InnerTag Key-Value Pairs. // m.group(1): UN-USED! (Includes Key, Equals-Sign, and Value). Not w/leading white-space // m.group(2): returns the 'key' portion of the key-value pair, before an '=' (equals-sign) // m.group(3): returns the 'value' portion of the key-value pair, after an '=' Matcher m = AttrRegEx.KEY_VALUE_REGEX.matcher(this.str); // MORE-CODE, but MORE-EFFICIENT (slightly) if (keepQuotes && preserveKeysCase) while (m.find()) ret.put(m.group(2), m.group(3)); else if (!keepQuotes && preserveKeysCase) while (m.find()) ret.put(m.group(2), StringParse.ifQuotesStripQuotes(m.group(3))); else if (keepQuotes && !preserveKeysCase) while (m.find()) ret.put(m.group(2).toLowerCase(), m.group(3)); else if (!keepQuotes && !preserveKeysCase) while (m.find()) ret.put(m.group(2).toLowerCase(), StringParse.ifQuotesStripQuotes(m.group(3))); return ret; } /** * Convenience Method. * <BR />Invokes: {@link #allAN(boolean, boolean)} * <BR />Attribute-<B STYLE="color: red;">names</B> will be in lower-case */ public Stream<String> allAN() { return allAN(false, false); } /** * This method will only return a list of attribute-<B STYLE="color: red;">names</B>. The * attribute-<B STYLE="color: red">values</B> shall <B>NOT</B> be included in the result. The * {@code String's} returned can have their "case-preserved" by passing <B>TRUE</B> to the * input boolean parameter {@code 'preserveKeysCase'}. * * @param preserveKeysCase If this is parameter receives <B>TRUE</B> then the case of the * attribute-<B STYLE="color: red;">names</B> shall be preserved. * * <EMBED CLASS="external-html" DATA-FILE-ID=TAGNODE_PRESERVE_C> * * @param includeKeyOnlyAttributes When this parameter receives <B>TRUE</B>, then any * "Boolean Attributes" or "Key-Only, No-Value-Assignment" Inner-Tags will <B>ALSO</B> be * included in the {@code Stream<String>} returned by this method. * * @return an instance of {@code Stream<String>} containing all * attribute-<B STYLE="color: red;">names</B> identified in {@code 'this'} instance of * {@code TagNode}. A {@code java.util.stream.Stream} is used because it's contents can easily * be converted to just about any data-type. * * <EMBED CLASS="external-html" DATA-FILE-ID=STRMCNVT> * * <BR /><B>NOTE:</B> This method shall never return {@code 'null'} - even if there are no * attribute <B STYLE="color: red;">key-value</B> pairs contained by {@code 'this' TagNode}. * If there are strictly zero attributes, an empty {@code Stream} shall be returned, instead. * * @see #allKeyOnlyAttributes(boolean) * @see #allAN() */ public Stream<String> allAN(boolean preserveKeysCase, boolean includeKeyOnlyAttributes) { // If there is NO ROOM in the "str" field for attributes, then there is now way attributes // could exist in this element. Return "empty" immediately. // // NOTE: OPTIMIZED, "closing-versions" of the TagNode, and TagNode's whose 'str' field // is only longer than the token, itself, by 3 or less characters cannot have // attributes. // // CHARS: '<', TOKEN, SPACE, '>' // RET: In that case, just return an empty Stream. if (isClosing || (str.length() <= (tok.length() + 3))) return Stream.empty(); // Use Java Streams. A String-Stream is easily converted to just about any data-type Stream.Builder<String> b = Stream.builder(); // This RegEx Matcher 'matches' against Attribute/InnerTag Key-Value Pairs. // m.group(2): returns the 'key' portion of the key-value pair, before an '=' (equals-sign) Matcher m = AttrRegEx.KEY_VALUE_REGEX.matcher(this.str); // Retrieve all of the keys of the attribute key-value pairs. while (m.find()) b.add(m.group(2)); // This Stream contains only keys that were once key-value pairs, if there are "key-only" // attributes, they have not been added yet. Stream<String> ret = b.build(); // Convert these to lower-case, (if requested) if (! preserveKeysCase) ret = ret.map((String attribute) -> attribute.toLowerCase()); // Now, add in all the "Key-Only" attributes (if there are any). Note, "preserve-case" // and "to lower case" are handled, already, in method "allKeyOnlyAttributes(boolean)" if (includeKeyOnlyAttributes) return Stream.concat(ret, allKeyOnlyAttributes(preserveKeysCase)); return ret; } // ******************************************************************************************** // ******************************************************************************************** // Key only attributes // ******************************************************************************************** // ******************************************************************************************** /** * <EMBED CLASS='external-html' DATA-FILE-ID=TN_ALL_KOA_DESC> * @param preserveKeysCase <EMBED CLASS='external-html' DATA-FILE-ID=TN_ALL_KOA_PKC> * <EMBED CLASS="external-html" DATA-FILE-ID=TAGNODE_PRESERVE_C> * @return <EMBED CLASS="external-html" DATA-FILE-ID=TN_ALL_KOA_RET> * <EMBED CLASS="external-html" DATA-FILE-ID=STRMCNVT> * @see #tok * @see #str */ public Stream<String> allKeyOnlyAttributes(boolean preserveKeysCase) { // NOTE: OPTIMIZED, "closing-versions" of the TagNode, and TagNode's whose 'str' // field is only longer than the token, itself, by 3 or less characters cannot have // attributes. In that case, just return an empty 'Stream' instance. int len = str.length(); if (isClosing || (len <= (tok.length() + 3))) return Stream.empty(); // Leaves off the opening 'token' and less-than '<' symbol (leaves off "<DIV " for example) // Also leave off the "ending-forward-slash" (if there is one) and ending '>' String s = str.substring(tok.length() + 2, len - ((str.charAt(len - 2) == '/') ? 2 : 1)); // if all lower-case is requested, do that here. if (! preserveKeysCase) s = s.toLowerCase(); // java.util.regex.Pattern.split(CharSequence) is sort of an "inverse reg-ex" in that it // returns all of the text that was present BETWEEN the matches // NOTE: This is the "opposite of the matches, themselves)" - a.k.a. all the stuff that was // left-out. Stream.Builder<String> b = Stream.builder(); // 'split' => inverse-matches (text between KEY-VALUE pairs) for (String unMatchedStr : AttrRegEx.KEY_VALUE_REGEX.split(s)) // Of that stuff, now do a white-space split for connected characters for (String keyWord : unMatchedStr.split("\\s+")) // Call String.trim() and String.length() if ((keyWord = keyWord.trim()).length() > 0) // Check for valid Attribute-Name's only if (AttrRegEx.ATTRIBUTE_KEY_REGEX_PRED.test(keyWord)) // ... put it in the return stream. // NOTE: This has the potential to slightly change the original HTML // It will "leave out any guck" that was in the Element b.add(keyWord); // Build the Stream<String>, and return; return b.build(); } /** * <EMBED CLASS='external-html' DATA-FILE-ID=TN_HAS_KOA_DESC> * <!-- @ExternalHTMLDocFiles({"@returns", "@desc", "keyOnlyAttribute", * "@IllegalArgumentException"}) --> * @param keyOnlyAttribute <EMBED CLASS='external-html' DATA-FILE-ID=TN_HAS_KOA_KOA> * @return <EMBED CLASS='external-html' DATA-FILE-ID=TN_HAS_KOA_RET> * @throws IllegalArgumentException <EMBED CLASS='external-html' DATA-FILE-ID=TN_HAS_KOA_IAEX> * @see AttrRegEx#KEY_VALUE_REGEX */ public boolean hasKeyOnlyAttribute(String keyOnlyAttribute) { // Closing TagNode's do not have attributes, return false immediately. if (this.isClosing) return false; // ONLY CHECKS FOR WHITE-SPACE, *NOT* VALIDITY... if (StringParse.hasWhiteSpace(keyOnlyAttribute)) throw new IllegalArgumentException( "The attribute you have passed [" + keyOnlyAttribute + "] has white-space, " + "This is not allowed here, because the search routine splits on whitespace, and " + "therefore a match would never be found." ); // NOTE: TagNode's whose 'str' field is only longer than the token, itself, by 3 or less // characters cannot have attributes. In that case, just return false. int len = str.length(); if (len <= (tok.length() + 3)) return false; // Leaves off the opening 'token' and less-than '<' symbol (leaves off "<DIV " for example) // Also leave off the "ending-forward-slash" (if there is one), and edning '>' String s = str.substring(tok.length() + 2, len - ((str.charAt(len - 2) == '/') ? 2 : 1)); // java.util.regex.Pattern.split(CharSequence) is sort of an "inverse reg-ex" in that it // returns all of the text that was present BETWEEN the matches // 'split' => inverse-matches (text between KEY-VALUE pairs) for (String unMatchedStr : AttrRegEx.KEY_VALUE_REGEX.split(s)) // Of that stuff, now do a white-space split for connected characters for (String keyWord : unMatchedStr.split("\\s+")) // trim, check-length... if ((keyWord = keyWord.trim()).length() > 0) if (keyOnlyAttribute.equalsIgnoreCase(keyWord)) return true; // Was not found, return false; return false; } // ******************************************************************************************** // ******************************************************************************************** // testAV // ******************************************************************************************** // ******************************************************************************************** /** * Convenience Method. * <BR />Invokes: {@link #testAV(String, Predicate)} * <BR />Passes: {@code String.equals(attributeValue)} as the test-{@code Predicate} */ public boolean testAV(String attributeName, String attributeValue) { return testAV(attributeName, (String s) -> s.equals(attributeValue)); } /** * Convenience Method. * <BR />Invokes: {@link #testAV(String, Predicate)} * <BR />Passes: {@code attributeValueTest.asPredicate()} */ public boolean testAV(String attributeName, Pattern attributeValueTest) { return testAV(attributeName, attributeValueTest.asPredicate()); } /** * Convenience Method. * <BR />Invokes: {@link #testAV(String, Predicate)} * <BR />Passes: {@link TextComparitor#test(String, String[])} as the test-{@code Predicate} */ public boolean testAV (String attributeName, TextComparitor attributeValueTester, String... compareStrs) { return testAV(attributeName, (String s) -> attributeValueTester.test(s, compareStrs)); } /** * Test the <B STYLE="color: red;">value</B> of the inner-tag named {@code 'attributeName'} * (if that attribute exists, and has a non-empty value) using a provided * {@code Predicate<String>}. * * <BR /><BR /><IMG SRC='doc-files/img/testAV1.png' CLASS=JDIMG ALT='example'> * * @param attributeName Any String will suffice - but only valid attribute * <B STYLE="color: red;">names</B> will match the internal regular-expression. * * <BR /><BR /><B>NOTE:</B> The validity of this parameter <I><B>is not</I></B> checked with * the HTML attribute-<B STYLE="color: red;">name</B> Regular-Expression exception checker. * * @param attributeValueTest Any {@code java.util.function.Predicate<String>} * * @return Method will return <B>TRUE</B> if and only if: * * <BR /><BR /><UL CLASS="JDUL"> * <LI> {@code 'this'} instance of {@code TagNode} has an inner-tag named * {@code 'attributeName'}. * <BR /><BR /> * </LI> * <LI> The results of the provided {@code String-Predicate}, when applied against the * <B STYLE="color: red">value</B> of the requested attribute, returns <B>TRUE</B>. * </LI> * </UL> * * @see AttrRegEx#KEY_VALUE_REGEX * @see #str * @see #isClosing * @see StringParse#ifQuotesStripQuotes(String) */ public boolean testAV(String attributeName, Predicate<String> attributeValueTest) { // Closing TagNode's (</DIV>, </A>) cannot attributes, or attribute-values if (isClosing) return false; // OPTIMIZATION: TagNode's whose String-length is less than this computed length // are simply too short to have the attribute named by the input parameter if (this.str.length() < (this.tok.length() + attributeName.length() + 4)) return false; // This Reg-Ex will allow us to iterate through each attribute key-value pair // contained / 'inside' this instance of TagNode. Matcher m = AttrRegEx.KEY_VALUE_REGEX.matcher(this.str); // Test each attribute key-value pair, and return the test results if an attribute // whose name matches 'attributeName' is found. while (m.find()) if (m.group(2).equalsIgnoreCase(attributeName)) return attributeValueTest.test (StringParse.ifQuotesStripQuotes(m.group(3))); // No attribute key-value pair was found whose 'key' matched input-parameter // 'attributeName' return false; } // ******************************************************************************************** // ******************************************************************************************** // has-attribute boolean-logic methods // ******************************************************************************************** // ******************************************************************************************** /** * Convenience Method. * <BR />Invokes: {@link #hasLogicOp(boolean, IntFunction, IntPredicate, String[])} * <BR />Passes: AND Boolean Logic */ public boolean hasAND(boolean checkAttributeStringsForErrors, String... attributes) { // First-Function: Tells the logic to *IGNORE* intermediate matches (returns NULL) // (This is *AND*, so wait until all attributes have been found, or at // the very least all tags in the element tested, and failed. // // Second-Function: At the End of the Loops, all Attributes have either been found, or // at least all attributes in 'this' tag have been tested. Note that the // first-function is only called on a MATCH, and tht 'AND' requires to // defer a response until all attributes have been tested.. Here, simply // RETURN WHETHER OR NOT the MATCH-COUNT equals the number of matches in // the user-provided String-array. return hasLogicOp( checkAttributeStringsForErrors, (int matchCount) -> null, (int matchCount) -> (matchCount == attributes.length), attributes ); } /** * Convenience Method. * <BR />Invokes: {@link #hasLogicOp(boolean, IntFunction, IntPredicate, String[])} * <BR />Passes: OR Boolean Logic * <!-- NOT USED NOW: * <BR /><BR /><IMG SRC='doc-files/img/hasOR.png' CLASS=JDIMG ALT="Example"> --> */ public boolean hasOR(boolean checkAttributeStringsForErrors, String... attributes) { // First-Function: Tells the logic to return TRUE on any match IMMEDIATELY // // Second-Function: At the End of the Loops, all Attributes have been tested. SINCE the // previous function returns on match immediately, AND SINCE this is an // OR, therefore FALSE must be returned (since there were no matches!) return hasLogicOp( checkAttributeStringsForErrors, (int matchCount) -> true, (int matchCount) -> false, attributes ); } /** * Convenience Method. * <BR />Invokes: {@link #hasLogicOp(boolean, IntFunction, IntPredicate, String[])} * <BR />Passes: NAND Boolean Logic */ public boolean hasNAND(boolean checkAttributeStringsForErrors, String... attributes) { // First-Function: Tells the logic to return FALSE on any match IMMEDIATELY // // Second-Function: At the End of the Loops, all Attributes have been tested. SINCE // the previous function returns on match immediately, AND SINCE this is // a NAND, therefore TRUE must be returned (since there were no matches!) return hasLogicOp( checkAttributeStringsForErrors, (int matchCount) -> false, (int matchCount) -> true, attributes ); } /** * Convenience Method. * <BR />Invokes: {@link #hasLogicOp(boolean, IntFunction, IntPredicate, String[])} * <BR />Passes: XOR Boolean Logic */ public boolean hasXOR(boolean checkAttributeStringsForErrors, String... attributes) { // First-Function: Tells the logic to IGNORE the FIRST MATCH, and any matches afterwards // should produce a FALSE result immediately // (XOR means ==> one-and-only-one) // // Second-Function: At the End of the Loops, all Attributes have been tested. Just // return whether or not the match-count is PRECISELY ONE. return hasLogicOp( checkAttributeStringsForErrors, (int matchCount) -> (matchCount == 1) ? null : false, (int matchCount) -> (matchCount == 1), attributes ); } /** * Provides the Logic for methods: * * <BR ><TABLE CLASS=BRIEFTABLE> * <TR><TH>Boolean Evaluation</TH><TH>Method</TH></TR> * <TR> * <TD>Checks that <B STYLE='color: red;'><I>all</I></B> Attributes are found</TD> * <TD>{@link #hasAND(boolean, String[])}</TD> * </TR> * <TR> * <TD>Checks that <B STYLE='color: red;'><I>at least one</I></B> Attribute matches</TD> * <TD>{@link #hasOR(boolean, String[])}</TD> * </TR> * <TR> * <TD>Checks that <B STYLE='color: red;'><I>precisely-one</I></B> Attribute is found</TD> * <TD>{@link #hasXOR(boolean, String[])}</TD> * </TR> * <TR> * <TD>Checks that <B STYLE='color: red;'><I>none</I></B> of the Attributes match</TD> * <TD>{@link #hasNAND(boolean, String[])}</TD> * </TR> * </TABLE> * * <BR /><IMG SRC='doc-files/img/hasAND.png' CLASS=JDIMG ALT="Example"> * * @param attributes This is a list of HTML Element Attribute-<B STYLE="color: red;">Names</B> * or "Inner Tags" as they are called in this Search and Scrape Package. * * @param checkAttributeStringsForErrors <EMBED CLASS="external-html" * DATA-FILE-ID=TAGNODE_HAS_BOOL> * * @return <B>TRUE</B> if at least one of these attribute-<B STYLE="color: red;">names</B> are * present in {@code 'this'} instance, and <B>FALSE</B> otherwise. * * <BR /><BR /><B>NOTE:</B> If this method is passed a zero-length {@code String}-array to the * {@code 'attributes'} parameter, this method shall exit immediately and return <B>FALSE</B>. * * @throws InnerTagKeyException If any of the {@code 'attributes'} are not valid HTML * attributes, <I><B>and</B></I> the user has passed <B>TRUE</B> to parameter * {@code checkAttributeStringsForErrors}. * * @throws NullPointerException If any of the {@code 'attributes'} are null. * * @throws ClosingTagNodeException <EMBED CLASS="external-html" DATA-FILE-ID="CTNEX"> * * @throws IllegalArgumentException If the {@code 'attributes'} parameter has length zero. * * @see InnerTagKeyException#check(String[]) * @see #AV(String) * @see AttrRegEx#KEY_VALUE_REGEX */ protected boolean hasLogicOp( boolean checkAttributeStringsForErrors, IntFunction<Boolean> onMatchFunction, IntPredicate reachedEndFunction, String... attributes ) { ClosingTagNodeException.check(this); // Keep a tally of how many of the input attributes are found int matchCount = 0; // Don't clobber the user's input attributes = attributes.clone(); // If no attributes are passed to 'attributes' parameter, throw exception. if (attributes.length == 0) throw new IllegalArgumentException ("Input variable-length String[] array parameter, 'attributes', has length zero."); // OPTIMIZATION: TagNode's whose String-length is less than this computed length // are simply too short to have any attribute-value pairs. // 4 (characters) are: '<', '>', ' ' and 'X' // SHORTEST POSSIBLE SUCH-ELEMENT: <DIV X> // // This TagNode doesn't have any attributes in it. // There is no need to check anything, so return FALSE immediately ("OR" fails) if (this.str.length() < (this.tok.length() + 4)) return false; if (checkAttributeStringsForErrors) InnerTagKeyException.check(attributes); // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** // Check the main key=value attributes // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** // Get all inner-tag key-value pairs. If even one of these is inside the 'attributes' // input-parameter string-array, Then we must return true, since this is OR Matcher keyValueInnerTags = AttrRegEx.KEY_VALUE_REGEX.matcher(this.str); while (keyValueInnerTags.find()) { // Retrieve the key of the key-value pair String innerTagKey = keyValueInnerTags.group(2); // Iterate every element of the String[] 'attributes' parameter SECOND_FROM_TOP: for (int i=0; i < attributes.length; i++) // No need to check attributes that have already been matched. // When an attribute matches, it's place in the array is set to null if (attributes[i] != null) // Does the latest keyOnlyInnerTag match one of the user-requested // attribute names? if (innerTagKey.equalsIgnoreCase(attributes[i])) { // NAND & OR will exit immediately on a match. XOR and AND // will return 'null' meaning they are not sure yet. Boolean whatToDo = onMatchFunction.apply(++matchCount); if (whatToDo != null) return whatToDo; // Increment the matchCounter, if this ever reaches the length // of the input array, there is no need to continue with the loop if (matchCount == attributes.length) return reachedEndFunction.test(matchCount); // There are still more matches to be found (not every element in // this array is null yet)... Keep Searching, but eliminated the // recently identified attribute from the list, because it has // already been found. attributes[i] = null; continue SECOND_FROM_TOP; } } // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** // Check the main key-only (Boolean) Attributes // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** // // Also check the "Boolean Attributes" also known as the "Key-Word Only Attributes" // Use the "Inverse Reg-Ex Matcher" (which matches all the strings that are "between" the // real matches) // substring eliminates the leading "<TOK ..." and the trailing '>' character // 2: '<' character *PLUS* the space (' ') character String strToSplit = this.str.substring( 2 + tok.length(), this.str.length() - ((str.charAt(this.str.length() - 2) == '/') ? 2 : 1) ).trim(); // 'split' => inverse-matches (text between KEY-VALUE pairs) for (String unMatchedStr : AttrRegEx.KEY_VALUE_REGEX.split(strToSplit)) // Of that stuff, now do a white-space split for connected characters SECOND_FROM_TOP: for (String keyOnlyInnerTag : unMatchedStr.split("\\s+")) // Just-In-Case, usually not necessary if ((keyOnlyInnerTag = keyOnlyInnerTag.trim()).length() > 0) // Iterate all the input-parameter String-array attributes for (int i=0; i < attributes.length; i++) // No need to check attributes that have already been matched. // When an attribute matches, it's place in the array is set to null if (attributes[i] != null) // Does the latest keyOnlyInnerTag match one of the user-requested // attribute names? if (keyOnlyInnerTag.equalsIgnoreCase(attributes[i])) { // NAND & OR will exit immediately on a match. XOR and AND // will return 'null' meaning they are not sure yet. Boolean whatToDo = onMatchFunction.apply(++matchCount); if (whatToDo != null) return whatToDo; // Increment the matchCounter, if this ever reaches the length // of the input array, there is no need to continue with the loop if (matchCount == attributes.length) return reachedEndFunction.test(matchCount); // There are still more matches to be found (not every element in // this array is null yet)... Keep Searching, but eliminated the // recently identified attribute from the list, because it has // already been found. attributes[i] = null; continue SECOND_FROM_TOP; } // Let them know how many matches there were return reachedEndFunction.test(matchCount); } // ******************************************************************************************** // ******************************************************************************************** // has methods - extended, variable attribute-names // ******************************************************************************************** // ******************************************************************************************** /** * Convenience Method. * <BR />Invokes: {@link #has(Predicate)} * <BR />Passes: {@code String.equalsIgnoreCase(attributeName)} as the test-{@code Predicate} */ public boolean has(String attributeName) { return has((String s) -> s.equalsIgnoreCase(attributeName)); } /** * Convenience Method. * <BR />Invokes: {@link #has(Predicate)} * <BR />Passes: {@code Pattern.asPredicate()} */ public boolean has(Pattern attributeNameRegExTest) { return has(attributeNameRegExTest.asPredicate()); } /** * Convenience Method. * <BR />Invokes: {@link #has(Predicate)} * <BR />Passes: {@link TextComparitor#test(String, String[])} as the test-{@code Predicate} */ public boolean has(TextComparitor tc, String... compareStrs) { return has((String s) -> tc.test(s, compareStrs)); } /** * <EMBED CLASS='external-html' DATA-FILE-ID=TN_HAS_DESC2> * <EMBED CLASS='external-html' DATA-FILE-ID=TAGNODE_HAS_NOTE> * @param attributeNameTest <EMBED CLASS='external-html' DATA-FILE-ID=TN_HAS_ANT> * @return <EMBED CLASS='external-html' DATA-FILE-ID=TN_HAS_RET2> * @see AttrRegEx#KEY_VALUE_REGEX * @see StrFilter */ public boolean has(Predicate<String> attributeNameTest) { // Closing HTML Elements may not have attribute-names or values. // Exit gracefully, and immediately. if (this.isClosing) return false; // OPTIMIZATION: TagNode's whose String-length is less than this computed length // are simply too short to have such an attribute-value pair. // 4 (characters) are: '<', '>', ' ' and 'X' // SHORTEST POSSIBLE SUCH-ELEMENT: <DIV X> if (this.str.length() < (this.tok.length() + 4)) return false; // Get all inner-tag key-value pairs. If any of them match with the 'attributeNameTest' // Predicate, return TRUE immediately. Matcher keyValueInnerTags = AttrRegEx.KEY_VALUE_REGEX.matcher(this.str); // the matcher.group(2) has the key (not the value) while (keyValueInnerTags.find()) if (attributeNameTest.test(keyValueInnerTags.group(2))) return true; // Also check the "Boolean Attributes" also known as the "Key-Word Only Attributes" // Use the "Inverse Reg-Ex Matcher" (which matches all the strings that are "between" the // real matches) // 'split' => inverse-matches (text between KEY-VALUE pairs) for (String unMatchedStr : AttrRegEx.KEY_VALUE_REGEX.split(this.str)) // Of that stuff, now do a white-space split for connected characters for (String keyOnlyInnerTag : unMatchedStr.split("\\s+")) // Just-In-Case, usually not necessary if ((keyOnlyInnerTag = keyOnlyInnerTag.trim()).length() > 0) if (attributeNameTest.test(keyOnlyInnerTag)) return true; // A match was not found in either the "key-value pairs", or the boolean "key-only list." return false; } // ******************************************************************************************** // ******************************************************************************************** // hasValue(...) methods // ******************************************************************************************** // ******************************************************************************************** /** * Convenience Method. * <BR />Invokes: {@link #hasValue(Predicate, boolean, boolean)} * <BR />Passes: {@code String.equals(attributeValue)} as the test-{@code Predicate} */ public Map.Entry<String, String> hasValue (String attributeValue, boolean retainQuotes, boolean preserveKeysCase) { return hasValue((String s) -> attributeValue.equals(s), retainQuotes, preserveKeysCase); } /** * Convenience Method. * <BR />Invokes: {@link #hasValue(Predicate, boolean, boolean)} * <BR />Passes: {@code attributeValueRegExTest.asPredicate()} */ public Map.Entry<String, String> hasValue (Pattern attributeValueRegExTest, boolean retainQuotes, boolean preserveKeysCase) { return hasValue(attributeValueRegExTest.asPredicate(), retainQuotes, preserveKeysCase); } /** * Convenience Method. * <BR />Invokes: {@link #hasValue(Predicate, boolean, boolean)} * <BR />Passes: {@link TextComparitor#test(String, String[])} as the test-{@code Predicate} */ public Map.Entry<String, String> hasValue( boolean retainQuotes, boolean preserveKeysCase, TextComparitor attributeValueTester, String... compareStrs ) { return hasValue( (String s) -> attributeValueTester.test(s, compareStrs), retainQuotes, preserveKeysCase ); } /** * <EMBED CLASS="external-html" DATA-FILE-ID=TN_HASVAL_DESC2> * <EMBED CLASS="external-html" DATA-FILE-ID=TN_HASVAL_DNOTE> * @param attributeValueTest <EMBED CLASS='external-html' DATA-FILE-ID=TN_HASVAL_AVT> * @param retainQuotes <EMBED CLASS='external-html' DATA-FILE-ID=TN_HASVAL_RQ> * @param preserveKeysCase * <EMBED CLASS="external-html" DATA-FILE-ID=TN_HASVAL_PKC> * <EMBED CLASS="external-html" DATA-FILE-ID=TAGNODE_PRESERVE_C> * @return <EMBED CLASS="external-html" DATA-FILE-ID=TN_HASVAL_RET2> * @see AttrRegEx#KEY_VALUE_REGEX * @see StrFilter */ public Map.Entry<String, String> hasValue (Predicate<String> attributeValueTest, boolean retainQuotes, boolean preserveKeysCase) { // Closing HTML Elements may not have attribute-names or values. // Exit gracefully, and immediately. if (this.isClosing) return null; // OPTIMIZATION: TagNode's whose String-length is less than this computed length // are simply too short to have such an attribute-value pair. // 5 (characters) are: '<', '>', ' ', 'X' and '=' // SHORTEST POSSIBLE SUCH-ELEMENT: <DIV X=> if (this.str.length() < (this.tok.length() + 5)) return null; // Get all inner-tag key-value pairs. If any are 'equal' to parameter attributeName, // return TRUE immediately. Matcher keyValueInnerTags = AttrRegEx.KEY_VALUE_REGEX.matcher(this.str); while (keyValueInnerTags.find()) { // Matcher.group(3) has the key's value, of the inner-tag key-value pair // (matcher.group(2) has the key's name) String foundAttributeValue = keyValueInnerTags.group(3); // The comparison must be performed on the version of the value that DOES NOT HAVE the // surrounding quotation-marks String foundAttributeValueNoQuotes = StringParse.ifQuotesStripQuotes(foundAttributeValue); // Matcher.group(3) has the key-value, make sure to remove quotation marks (if present) // before comparing. if (attributeValueTest.test(foundAttributeValueNoQuotes)) // matcher.group(2) has the key's name, not the value. This is returned via the // Map.Entry key return retainQuotes ? new AbstractMap.SimpleImmutableEntry<>( preserveKeysCase ? keyValueInnerTags.group(2) : keyValueInnerTags.group(2).toLowerCase(), foundAttributeValue ) : new AbstractMap.SimpleImmutableEntry<>( preserveKeysCase ? keyValueInnerTags.group(2) : keyValueInnerTags.group(2).toLowerCase(), foundAttributeValueNoQuotes ); } // No match was identified, return null. return null; } // ******************************************************************************************** // ******************************************************************************************** // getInstance() // ******************************************************************************************** // ******************************************************************************************** /** * <EMBED CLASS='external-html' DATA-FILE-ID=TN_GETINST_DESC> * @param tok Any valid HTML tag. * @param openOrClosed <EMBED CLASS='external-html' DATA-FILE-ID=TN_GETINST_OOC> * @return An instance of this class * * @throws IllegalArgumentException If parameter {@code TC openOrClose} is {@code null} or * {@code TC.Both} * * @throws HTMLTokException If the parameter {@code String tok} is not a valid HTML-tag * * @throws SingletonException If the token requested is a {@code singleton} (self-closing) tag, * but the Tag-Criteria {@code 'TC'} parameter is requesting a closing-version of the tag. * * @see HTMLTags#hasTag(String, TC) * @see HTMLTags#isSingleton(String) */ public static TagNode getInstance(String tok, TC openOrClosed) { if (openOrClosed == null) throw new NullPointerException("The value of openOrClosed cannot be null."); if (openOrClosed == TC.Both) throw new IllegalArgumentException("The value of openOrClosed cannot be TC.Both."); if (HTMLTags.isSingleton(tok) && (openOrClosed == TC.ClosingTags)) throw new SingletonException( "The value of openOrClosed is TC.ClosingTags, but unfortunately you have asked " + "for a [" + tok + "] HTML element, which is a singleton element, and therefore " + "cannot have a closing-tag instance." ); TagNode ret = HTMLTags.hasTag(tok, openOrClosed); if (ret == null) throw new HTMLTokException ("The HTML-Tag provided isn't valid!\ntok: " + tok + "\nTC: " + openOrClosed); return ret; } // ******************************************************************************************** // ******************************************************************************************** // Methods for "CSS Classes" // ******************************************************************************************** // ******************************************************************************************** /** * Convenience Method. * <BR />Invokes: {@link #cssClasses()} * <BR />Catches-Exception */ public Stream<String> cssClassesNOCSE() { try { return cssClasses(); } catch (CSSStrException e) { return Stream.empty(); } } /** * <EMBED CLASS="external-html" DATA-FILE-ID=TN_CSS_CL_DESC> * @return * <EMBED CLASS="external-html" DATA-FILE-ID=TN_CSS_CL_RET> * <EMBED CLASS="external-html" DATA-FILE-ID=STRMCNVT> * @throws CSSStrException <EMBED CLASS="external-html" DATA-FILE-ID=TN_CSS_CL_CSSSE> * @see #cssClasses() * @see #AV(String) * @see StringParse#WHITE_SPACE_REGEX * @see CSSStrException#check(Stream) */ public Stream<String> cssClasses() { // The CSS Class is just an attribute/inner-tag within an HTML Element. String classes = AV("class"); // IF the "class" attribute was not present, OR (after trimming) was empty, return // "empty stream" if ((classes == null) || ((classes = classes.trim()).length() == 0)) return Stream.empty(); // STEP 1: Split the string on white-space // STEP 2: Check each element of the output Stream using the "CSSStrException Checker" return CSSStrException.check(StringParse.WHITE_SPACE_REGEX.splitAsStream(classes)); } /** * <EMBED CLASS='external-html' DATA-FILE-ID=TN_SET_CSS_CL_DESC> * @param quote <EMBED CLASS='external-html' DATA-FILE-ID=TGND_QUOTE_EXPL> * @param appendOrClobber <EMBED CLASS='external-html' DATA-FILE-ID=TN_SET_CSS_CL_AOC> * @param cssClasses <EMBED CLASS='external-html' DATA-FILE-ID=TN_SET_CSS_CL_CCL> * @return <EMBED CLASS='external-html' DATA-FILE-ID=TN_SET_CSS_CL_RET> * @throws CSSStrException This exception shall throw if any of the {@code 'cssClasses'} in the * var-args {@code String...} parameter do not meet the HTML 5 CSS {@code Class} naming rules. * @throws ClosingTagNodeException <EMBED CLASS="external-html" DATA-FILE-ID=CTNEX> * @throws QuotesException <EMBED CLASS='external-html' DATA-FILE-ID=TN_SET_CSS_CL_QEX> * @see CSSStrException#check(String[]) * @see CSSStrException#VALID_CSS_CLASS_OR_NAME_TOKEN * @see #appendToAV(String, String, boolean, SD) * @see #setAV(String, String, SD) */ public TagNode setCSSClasses(SD quote, boolean appendOrClobber, String... cssClasses) { // Throw CSSStrException if any of the input strings are invalid CSS Class-Names. CSSStrException.check(cssClasses); // Build the CSS 'class' Attribute String. This will be inserted into the TagNode Element StringBuilder sb = new StringBuilder(); boolean first = true; for (String c : cssClasses) { sb.append((first ? "" : " ") + c.trim()); first=false; } return appendOrClobber ? appendToAV("class", " " + sb.toString(), false, quote) : setAV("class", sb.toString(), quote); } /** * <EMBED CLASS='external-html' DATA-FILE-ID=TN_APD_CSS_CL_DESC> * @param cssClass This is the CSS-{@code Class} name that is being inserted into * {@code 'this'} instance of {@code TagNode} * @param quote <EMBED CLASS='external-html' DATA-FILE-ID=TGND_QUOTE_EXPL> * @return A newly instantiated {@code TagNode} with updated CSS {@code Class} Name(s). * @throws CSSStrException <EMBED CLASS='external-html' DATA-FILE-ID=TN_APD_CSS_CL_CSSSE> * @throws ClosingTagNodeException <EMBED CLASS="external-html" DATA-FILE-ID=CTNEX> * @throws QuotesException <EMBED CLASS='external-html' DATA-FILE-ID=TN_APD_CSS_CL_QEX> * @see CSSStrException#check(String[]) * @see #setAV(String, String, SD) * @see #appendToAV(String, String, boolean, SD) */ public TagNode appendCSSClass(String cssClass, SD quote) { // Do a validity check on the class. If this is "problematic" due to use of specialized / // pre-processed CSS Class directives, use the general purpose "setAV(...)" method CSSStrException.check(cssClass); String curCSSClassSetting = AV("class"); // If there wasn't a CSS Class already defined, use "setAV(...)", // otherwise use "appendToAV(...)" if ((curCSSClassSetting == null) || (curCSSClassSetting.length() == 0)) return setAV("class", cssClass, quote); else return appendToAV("class", cssClass + ' ', true, quote); } // ******************************************************************************************** // ******************************************************************************************** // Methods for "CSS Style" // ******************************************************************************************** // ******************************************************************************************** /** * <EMBED CLASS="external-html" DATA-FILE-ID=TN_CSS_STYLE_DESC> * <EMBED CLASS="external-html" DATA-FILE-ID=TN_CSS_STYLE_DESCEX> * @return <EMBED CLASS="external-html" DATA-FILE-ID=TN_CSS_STYLE_RET> * @see AttrRegEx#CSS_INLINE_STYLE_REGEX * @see #AV(String) */ public Properties cssStyle() { Properties p = new Properties(); String styleStr = AV("style"); // Returns the complete attribute-value of "style" in the TagNode // There was no STYLE='...' attribute found, return empty Properties. if (styleStr == null) return p; // Standard String-trim routine styleStr = styleStr.trim(); if (styleStr.length() == 0) return p; // This reg-ex "iterates" over matches of strings that follow the (very basic) form: // declaration-name: declaration-string; // // Where the ":" (color), and ";" (semi-colon) are the only watched/monitored tokens. // See the reg-ex definition in "See Also" tag. Matcher m = AttrRegEx.CSS_INLINE_STYLE_REGEX.matcher(styleStr); // m.group(1): declaration-name (stuff before the ":") // m.group(2): declaration-string (stuff before the next ";", or end-of-string) // // For Example, if the style attribute-value was specified as: // STYLE="font-weight: bold; margin: 1em 1em 1em 2em; color: #0000FF" // // The returned Properties object would contain the string key-value pair elements: // "font-weight" -> "bold" // "margin" -> "1em 1em 1em 2em" // "color" -> "#0000FF" while (m.find()) p.put(m.group(1).toLowerCase(), m.group(2)); return p; } /** * <EMBED CLASS='external-html' DATA-FILE-ID=TN_SET_CSS_STY_DESC> * @param p <EMBED CLASS='external-html' DATA-FILE-ID=TN_SET_CSS_STY_P> * @param quote <EMBED CLASS='external-html' DATA-FILE-ID=TGND_QUOTE_EXPL> * @param appendOrClobber <EMBED CLASS='external-html' DATA-FILE-ID=TN_SET_CSS_STY_AOC> * @return <EMBED CLASS='external-html' DATA-FILE-ID=TN_SET_CSS_STY_RET> * @throws ClosingTagNodeException <EMBED CLASS="external-html" DATA-FILE-ID=CTNEX> * @throws CSSStrException If there is an invalid CSS Style Property Name. * @throws QuotesException If the style-element's quotation marks are incompatible with any * and all quotation marks employed by the style-element definitions. * @see CSSStrException#VALID_CSS_CLASS_OR_NAME_TOKEN * @see #appendToAV(String, String, boolean, SD) * @see #setAV(String, String, SD) */ public TagNode setCSSStyle(Properties p, SD quote, boolean appendOrClobber) { // this is used in the "exception constructor" below (which means, it might not be used). int counter = 0; // Follows the "FAIL-FAST" philosophy, and does not allow invalid CSS declaration-name // tokens. Use TagNode.setAV("style", ...), or TagNode.appendToAV("style", ...), to // bypass exception-check. for (String key : p.stringPropertyNames()) if (! CSSStrException.VALID_CSS_CLASS_OR_NAME_TOKEN_PRED.test(key)) { String[] keyArr = new String[p.size()]; throw new CSSStrException( "CSS Style Definition Property: [" + key + "] does not conform to the " + "valid, HTML 5, regular-expression for CSS Style Definitions Properties:\n[" + CSSStrException.VALID_CSS_CLASS_OR_NAME_TOKEN.pattern() + "].", // One minor "PRESUMPTION" that is the Iterator will return the elements of // Properties in the EXACT SAME ORDER on both creations / instantiations of the // iterator. Specifically: two invocations of method .iterator(), will return // the same-list of property-keys, in the same order, BOTH TIMES. Once for the // for-loop, and once for the exception message. This only matters if there is // an exception. p.stringPropertyNames().toArray(keyArr), ++counter ); } else ++counter; // Follows the "FAIL-FAST" philosophy, and does not allow "quotes-within-quote" problems // to occur. An attribute-value surrounded by single-quotes, cannot contain a // single-quote inside, and double-within-double. counter = 0; for (String key : p.stringPropertyNames()) if (StrCmpr.containsOR(p.get(key).toString(), ("" + quote.quote), ";")) { String[] keyArr = new String[p.size()]; throw new CSSStrException( "CSS Style Definition Property: [" + key + "], which maps to style-" + "definition property-value:\n[" + p.get(key) + "], contains either a " + "semi-colon ';' character, or the same quotation-mark specified: [" + quote.quote + "], and is therefore not a valid assignment for a CSS " + "Definition Property.", p .stringPropertyNames() .stream() .map((String propertyName) -> p.get(propertyName)) .toArray((int i) -> new String[i]), ++counter ); } else ++counter; // ERROR-CHECKING: FINISHED, NOW JUST BUILD THE ATTRIBUTE-VALUE STRING // (using StringBuilder), AND INSERT IT. StringBuilder sb = new StringBuilder(); for (String key : p.stringPropertyNames()) sb.append(key + ": " + p.get(key) + ";"); return appendOrClobber ? appendToAV("style", " " + sb.toString(), false, quote) : setAV("style", sb.toString(), quote); } // ******************************************************************************************** // ******************************************************************************************** // Methods for "CSS ID" // ******************************************************************************************** // ******************************************************************************************** /** * Convenience Method. * <BR />Invokes: {@link #AV(String)} * <BR />Passes: {@code String "id"}, the CSS-ID attribute-<B STYLE="color: red;">name</B> * <!-- RIDICULOUS: BR />BR />IMG SRC='doc-files/img/getID.png' CLASS=JDIMG ALT='example'> --> */ public String getID() { String id = AV("ID"); return (id == null) ? null : id.trim(); } /** * This merely sets the current CSS {@code 'ID'} Attribute <B STYLE="color: red;">Value</B>. * * @param id This is the new CSS {@code 'ID'} attribute-<B STYLE="color: red;">value</B> that * the user would like applied to {@code 'this'} instance of {@code TagNode}. * * @param quote <EMBED CLASS='external-html' DATA-FILE-ID=TGND_QUOTE_EXPL> * * @return Returns a new instance of {@code TagNode} that has an updated {@code 'ID'} * attribute-<B STYLE="color: red;">value</B>. * * @throws IllegalArgumentException This exception shall throw if an invalid * {@code String}-token has been passed to parameter {@code 'id'}. * * <BR /><BR /><B>BYPASS NOTE:</B> If the user would like to bypass this exception-check, for * instance because he / she is using a CSS Pre-Processor, then applying the general-purpose * method {@code TagNode.setAV("id", "some-new-id")} ought to suffice. This other method will * not apply validity checking, beyond scanning for the usual "quotes-within-quotes" problems, * which is always disallowed. * * @throws ClosingTagNodeException <EMBED CLASS="external-html" DATA-FILE-ID=CTNEX> * * @see CSSStrException#VALID_CSS_CLASS_OR_NAME_TOKEN * @see #setAV(String, String, SD) */ public TagNode setID(String id, SD quote) { if (! CSSStrException.VALID_CSS_CLASS_OR_NAME_TOKEN_PRED.test(id)) throw new IllegalArgumentException( "The id parameter provide: [" + id + "], does not conform to the standard CSS " + "Names.\nEither try using the generic TagNode.setAV(\"id\", yourNewId, quote); " + "method to bypass this check, or change the value passed to the 'id' parameter " + "here." ); return setAV("id", id.trim(), quote); } // ******************************************************************************************** // ******************************************************************************************** // Attributes that begin with "data-..." // ******************************************************************************************** // ******************************************************************************************** /** * Convenience Method. * <BR />Invokes: {@link #AV(String)} * <BR />Passes: {@code "data-"} prepended to parameter {@code 'dataName'} for the * attribute-<B STYLE='color:red'>name</B> */ public String dataAV(String dataName) { return AV("data-" + dataName); } /** * This method will remove any HTML <B STYLE="color: red;">'data'</B> Attributes - if there are * any present. "Data Inner-Tags" are simply the attributes inside of HTML Elements whose * <B STYLE="color: red;">names</B> begin with <B STYLE="color: red;">{@code "data-"}</B>. * * <BR /><BR />Since {@code class TagNode} is immutable, a new {@code TagNode} must be * instantiated, if any data-inner-tags are removed. If no data-attributes are removed, * {@code 'this'} instance {@code TagNode} shall be returned instead. * * @return This will return a newly constructed {@code 'TagNode'} instance, if there were any * "<B STYLE="color: red;">Data</B> Attributes" that were removed by request. If the original * {@code TagNode} has remained unchanged, a reference to {@code 'this'} shall be returned. * * @throws ClosingTagNodeException This exception throws if {@code 'this'} instance of * {@code TagNode} is a closing-version of the HTML Element. Closing HTML Elements may not * have data attributes, because they simply are not intended to contain <I>any</I> attributes. */ public TagNode removeDataAttributes() { // Because this method expects to modify the TagNode, this exception-check is necessary. ClosingTagNodeException.check(this); // Make sure to keep the quotes that were already used, we are removing attributes, and the // original attributes that aren't removed need to preserve their quotation marks. Properties p = this.allAV(true, true); Enumeration<Object> keys = p.keys(); int oldSize = p.size(); // Visit each Property Element, and remove any properties that have key-names which // begin with the word "data-" while (keys.hasMoreElements()) { String key = keys.nextElement().toString(); if (key.startsWith("data-")) p.remove(key); } // If any of properties were removed, we have to rebuild the TagNode, and replace it. // REMEMBER: 'null' is passed to the 'SD' parameter, because we preserved the original // quotes above. return (p.size() == oldSize) ? this : new TagNode(this.tok, p, null, this.str.endsWith("/>")); } /** * Convenience Method. * <BR />Invokes: {@link #getDataAV(boolean)} * <BR />Attribute-<B STYLE="color: red;">names</B> will be in lower-case */ public Properties getDataAV() { return getDataAV(false); } /** * This will retrieve and return any/all <B STYLE="color: red;">'data'</B> HTML Attributes. * "Data Inner-Tags" are simply the attributes inside of HTML Elements whose * <B STYLE="color: red;">names</B> begin with <B STYLE="color: red;">{@code "data-"}</B>. * * @param preserveKeysCase When this parameter is passed <B>TRUE</B>, the case of the attribute * <B STYLE="color: red;">names</B> in the returned {@code Properties} table will have been * preserved. When <B>FALSE</B> is passed, all {@code Properties} * <B STYLE="color: red">keys</B> shall have been converted to lower-case first. * * <EMBED CLASS="external-html" DATA-FILE-ID=TAGNODE_PRESERVE_C> * * @return This will return a {@code java.util.Properties} of all * <B STYLE="color: red;">data</B>-attributes which are found in {@code 'this'} HTML Element. * If no such attributes were found, 'null' shall not be returned by this method, but rather an * empty {@code Properties} instance will be provided, instead. * * @see TagNode#isClosing * @see TagNode#str * @see TagNode#tok * @see AttrRegEx#DATA_ATTRIBUTE_REGEX */ public Properties getDataAV(boolean preserveKeysCase) { Properties ret = new Properties(); // NOTE: OPTIMIZED, "closing-versions" of the TagNode, and TagNode's whose 'str' // field is only longer than the token, itself, by 3 or less characters cannot have // attributes.v In that case, just return an empty 'Properties' instance. if (isClosing || (str.length() <= (tok.length() + 3))) return ret; // This RegEx Matcher 'matches' against Attribute/InnerTag Key-Value Pairs // ONLY PAIRS WHOSE KEY BEGINS WITH "data-" WILL MATCH // // m.group(2): returns the 'key' portion of the key-value pair, before an '=' (equals-sign) // m.group(3): returns the 'value' portion of the key-value pair, after an '=' Matcher m = AttrRegEx.DATA_ATTRIBUTE_REGEX.matcher(this.str); // NOTE: HTML mandates attributes must be 'case-insensitive' to the attribute 'key-part' // (but not necessarily the 'value-part') // // HOWEVER: Java does not require anything for the 'Properties' class. // ALSO: Case is PRESERVED for the 'value-part' of the key-value pair. if (preserveKeysCase) while (m.find()) ret.put(m.group(2), StringParse.ifQuotesStripQuotes(m.group(3))); else while (m.find()) ret.put(m.group(2).toLowerCase(), StringParse.ifQuotesStripQuotes(m.group(3))); return ret; } /** * Convenience Method. * <BR />Invokes: {@link #getDataAN(boolean)} * <BR />Attribute-<B STYLE="color: red;">names</B> will be in lower-case */ public Stream<String> getDataAN() { return getDataAN(false); } /** * This method will only return a list of all data-attribute <B STYLE="color: red;">names</B>. * The data-attribute <B STYLE="color: red;">values</B> shall not be included in the result. * An HTML Element "data-attribute" is any attribute inside of an HTML {@code TagNode} whose * <B STYLE="color: red;">key-value</B> pair uses a <B STYLE="color: red;">key</B> that begins * with <B STYLE="color: red;">{@code "data-"}</B>... <I>It is that simple!</I> * * @param preserveKeysCase When this parameter is passed <B>TRUE</B>, the case of the attribute * <B STYLE="color: red;">names</B> that are returned by this method will have been * preserved. When <B>FALSE</B> is passed, they shall be converted to lower-case first. * * <EMBED CLASS="external-html" DATA-FILE-ID=TAGNODE_PRESERVE_C> * * @return Returns an instance of {@code Stream<String>}. The attribute * <B STYLE="color: red;">names</B> that are returned, are all converted to lower-case. * * <BR /><BR />A return type of {@code Stream<String>} is used. Please see the list below for * how to convert a {@code Stream} to another data-type. * * <EMBED CLASS="external-html" DATA-FILE-ID=STRMCNVT> * * <BR /><B>NOTE:</B> This method shall never return 'null' - even if there are no * <B STYLE="color: red;">data-</B>attribute <B STYLE="color: red;">key-value</B> pairs * contained by the {@code TagNode}. If there are strictly zero such attributes, * ({@code Stream.empty()}) shall be returned, instead. * * @see #str * @see #tok * @see AttrRegEx#DATA_ATTRIBUTE_REGEX */ public Stream<String> getDataAN(boolean preserveKeysCase) { // Java Stream's can be quickly and easily converted to any data-structure the user needs. Stream.Builder<String> b = Stream.builder(); // NOTE: OPTIMIZED, "closing-versions" of the TagNode, and TagNode's whose 'str' // field is only longer than the token, itself, by 3 or less characters cannot have // attributes. In that case, just return an empty 'Properties' instance. if (isClosing || (str.length() <= (tok.length() + 3))) return Stream.empty(); // This RegEx Matcher 'matches' against Attribute/InnerTag Key-Value Pairs // ONLY PAIRS WHOSE KEY BEGINS WITH "data-" WILL MATCH // m.group(2): returns the 'key' portion of the key-value pair, before an '=' (equals-sign). // m.group(3): returns the 'value' portion of the key-value pair, after an '=' Matcher m = AttrRegEx.DATA_ATTRIBUTE_REGEX.matcher(this.str); // NOTE: HTML mandates attributes must be 'case-insensitive' to the attribute 'key-part' // (but not necessarily the 'value-part') // HOWEVER: Java does not require anything for the 'Properties' class. // ALSO: Case is PRESERVED for the 'value-part' of the key-value pair. if (preserveKeysCase) while (m.find()) b.accept(m.group(2)); else while (m.find()) b.accept(m.group(2).toLowerCase()); return b.build(); } // ******************************************************************************************** // ******************************************************************************************** // Java Methods // ******************************************************************************************** // ******************************************************************************************** /** * This does a "longer version" of the parent {@code toString()} method. This is because it * also parses and prints inner-tag <B STYLE="color: red;">key-value</B> pairs. The ordinary * {@code public String toString()} method that is inherited from parent {@code class HTMLNode} * will just return the value of {@code class HTMLNode} field: {@code public final String str}. * * @return A String with the inner-tag <B STYLE="color: red;">key-value</B> pairs specified. * * <DIV CLASS="EXAMPLE">{@code * // The following code, would output the text below * TagNode tn = new TagNode("<BUTTON CLASS='MyButtons' ONCLICK='MyListener();'>"); * System.out.println(tn.toStringAV()); * * // Outputs the following Text: * * // TagNode.str: [<BUTTON class='MyButtons' onclick='MyListener();'>], TagNode.tok: [button], * // TagNode.isClosing: [false] * // CONTAINS a total of (2) attributes / inner-tag key-value pairs: * // (KEY, VALUE): [onclick], [MyListener();] * // (KEY, VALUE): [class], [MyButtons] * }</DIV> * * @see #allAV() * @see #tok * @see #isClosing * @see HTMLNode#toString() */ public String toStringAV() { StringBuilder sb = new StringBuilder(); // Basic information. This info is common to ALL instances of TagNode sb.append( "TagNode.str: [" + this.str + "], TagNode.tok: [" + this.tok + "], " + "TagNode.isClosing: [" + this.isClosing + "]\n" ); // Not all instances of TagNode will have attributes. Properties attributes = this.allAV(false, true); sb.append( "CONTAINS a total of (" + attributes.size() + ") attributes / inner-tag " + "key-value pairs" + (attributes.size() == 0 ? "." : ":") + "\n" ); // If there are inner-tags / attributes, then add them to the output-string, each on a // separate line. for (String key : attributes.stringPropertyNames()) sb.append("(KEY, VALUE):\t[" + key + "], [" + attributes.get(key) + "]\n"); // Build the string from the StringBuilder, and return it. return sb.toString(); } /** * Java's {@code interface Cloneable} requirements. This instantiates a new {@code TagNode} * with identical <SPAN STYLE="color: red;">{@code String str}</SPAN> fields, and also * identical <SPAN STYLE="color: red;">{@code boolean isClosing}</SPAN> and * <SPAN STYLE="color: red;">{@code String tok}</SPAN> fields. * * @return A new {@code TagNode} whose internal fields are identical to this one. */ public TagNode clone() { return new TagNode(str); } /** * This sorts by: * * <BR /><BR /><OL CLASS="JDOL"> * <LI> by {@code String 'tok'} fields character-order (ASCII-alphabetical). * <BR />The following {@code final String 'tok'} fields are ASCII ordered: * {@code 'a', 'button', 'canvas', 'div', 'em', 'figure' ...} * </LI> * <LI>then (if {@code 'tok'} fields are equal) by the {@code public final boolean 'isClosing'} * field. <BR />{@code TagNode's} that have a {@code 'isClosing'} set to <B>FALSE</B> come * before {@code TagNode's} whose {@code 'isClosing'} field is set to <B>TRUE</B> * </LI> * <LI> finally, if the {@code 'tok'} and {@code 'isClosing'} fields are equal, they are * sorted by <I>the integer-length of</I> {@code final String 'str'} field. * </LI> * </OL> * * @param n Any other {@code TagNode} to be compared to {@code 'this' TagNode} * * @return An integer that fulfils Java's * {@code interface Comparable<T> public boolean compareTo(T t)} method requirements. * * @see #tok * @see #isClosing * @see #str */ public int compareTo(TagNode n) { // Utilize the standard "String.compare(String)" method with the '.tok' string field. // All 'tok' fields are stored as lower-case strings. int compare1 = this.tok.compareTo(n.tok); // Comparison #1 will be non-zero if the two TagNode's being compared had different // .tok fields if (compare1 != 0) return compare1; // If the '.tok' fields were the same, use the 'isClosing' field for comparison instead. // This comparison will only be used if they are different. if (this.isClosing != n.isClosing) return (this.isClosing == false) ? -1 : 1; // Finally try using the entire element '.str' String field, instead. return this.str.length() - n.str.length(); } // ******************************************************************************************** // ******************************************************************************************** // UpperCase, LowerCase // ******************************************************************************************** // ******************************************************************************************** // public TagNode toUpperCase(boolean b) { return null; } // public TagNode toLowerCase(boolean b) { return null; } /** * Return a capitalized (upper-case) instance of the {@code String}-Contents of this * {@code TagNode}. * * <BR /><BR />The user has the option of capitalizing the Tag-Name only, or the Tag-Name * and the Attribute-<B STYLE='color: red;'>Name's</B>. * * <BR /><BR />White-space shall remain unchanged by this method. * * @param justTag_Or_TagAndAttributeNames When this parameter is passed {@code TRUE}, only the * Element-Name will be converted to Upper-Case. This is the {@link #tok} field of this * {@code TagNode}. * * <BR /><BR />If this parameter receives {@code FALSE}, then * <B STYLE='color: red;'><I>BOTH</I></B> the Tag-Name <B STYLE='color: red;'><I>AND</I></B> * the Attribute-Names are capitalized. * * <!-- * NOTE: THIS CODE BREAKS COMMAND 'javadoc', AND I DON'T KNOW WHY... * * <BR /><BR />The follwing example will (hopefully) elucidate the output of this method. * * <DIV CLASS=EXAMPLE>{@code * TagNode tn = new TagNode("<a href='http://some.url.com/Some/Case/Sensitive/DIR'>"); * * System.out.println(tn.toUpperCase(true)); * // Prints: "<A href='http://some.url.com/Some/Case/Sensitive/DIR'>" * // NOTE: Only the 'a' is upper-case, the 'href' attribute is still lower-case * * System.out.println(tn.toUpperCase(false)); * // Prints: "<A HREF='http://some.url.com/Some/Case/Sensitive/DIR'>" * // NOTE: The Tag-Name and all Attribute-Names are now upper-case. * // ALSO: The HREF-URL (an Attribute-Value) has remained unchanged. * }<DIV> * --> * * @return A capitalized version of {@code 'this'} instance. Only the Tag-Name, or the * Tag-Name and the Attribute-<B STYLE='color: red;'>Name's</B> will be capitalized. This * method will leave Attributte-<B STYLE='color: red;'>Values</B> unmodified. * * <BR /><BR />All spacing characters and (again) Attribute-<B STYLE='color: red;'>Values</B> * will remain unchanged. * * <BR /><BR /><B CLASS=JDDescLabel>'DATA-' ATTRIBUTES:</B> * * <BR />HTML {@code 'data-*'} Attributes are Inner-Tags that allow a programmer to pass * 'values', of one kind or another, that have a name to a Web-Browser or client. Since there * is the possibility that the 'name' provided is case-sensitive, this method will not alter the * name text that apears after the {@code 'data-'} portion of the * Attribute-<B STYLE='color: red;'>Name</B> for HTML Data-Attributes. */ public TagNode toUpperCase(boolean justTag_Or_TagAndAttributeNames) { if (justTag_Or_TagAndAttributeNames) return new TagNode( this.isClosing ? ("</" + this.tok.toUpperCase() + this.str.substring(2 + this.tok.length())) : ('<' + this.tok.toUpperCase() + this.str.substring(1 + this.tok.length())) ); StringBuilder sb = new StringBuilder(); Matcher m = AttrRegEx.KEY_VALUE_REGEX.matcher(this.str); sb.append(this.isClosing ? "</" : "<"); sb.append(this.tok.toUpperCase()); // Skip over the opening '<' and the Tag-Name int pos = this.tok.length() + 1; // If this was a "Closing Tag", remember to skip the opeing '/' if (this.isClosing) pos++; // Here, the Key-Value (Attribue-Name & Attribute-Value) pairs are iterated. Care is // taken to ensure that only the names (not the values) are modified. while (m.find()) { // Apppend white-space that occurs **BEFORE** the Name-Value Pair // // NOTE: The 'toUpperCase' here will catch any Attribute-Name-Only Attributes // (also known as "Boolean-Attributes") sb.append(this.str.substring(pos, m.start(2)).toUpperCase()); // Append the Attribute-Name, and make sure to Capitalize it. First this needs to be // retrieved, and (more importantly), do not capitalize the actual name-part of // "data-" Attributes, their case **COULD POSSIBLY** be important... (They are for the // EmbedTag Parameters Data-Attributes) String attrName = m.group(2).toUpperCase(); sb.append( StrCmpr.startsWithIgnoreCase(attrName, "data-") ? ("DATA-" + attrName.substring(5).toUpperCase()) : attrName.toUpperCase() ); // Append the Attribute-Value, and update the 'pos' variable to reflect where // in the String the current Match-Location ends... // // NOTE: m.end(2) and m.end() are the exact same values, since this regex's // group #2 ends at the very-end of the regex pattern. sb.append(this.str.substring(pos = m.end(2), pos)); } // ALWAYS: After the last match of a RegEx, remember to append any text that occurs // after the last match. This is also quite important in the HTML-Parser // not to forget this line. sb.append(this.str.substring(pos)); // Return the new TagNode return new TagNode(sb.toString()); } /** * Return a de-capitalized (Lower-case) instance of the {@code String}-Contents of this * {@code TagNode}. * * <BR /><BR />The user has the option of de-capitalizing the Tag-Name only, or the Tag-Name * and the Attribute-<B STYLE='color: red;'>Name's</B>. * * <BR /><BR />White-space shall remain unchanged by this method. * * @param justTag_Or_TagAndAttributeNames When this parameter is passed {@code TRUE}, only the * Element-Name will be converted to Lower-Case. (The '{@link #tok}'' field of this * {@code TagNode} is changed) * * <BR /><BR />If this parameter receives {@code FALSE}, then * <B STYLE='color: red;'><I>BOTH</I></B> the Tag-Name <B STYLE='color: red;'><I>AND</I></B> * the Attribute-Names are de-capitalized. * * <!-- * THIS BREAKS JAVADOC, FOR SOME ODD REASON... * * <BR /><BR />The follwing example will (hopefully) elucidate the output of this method. * * <DIV CLASS=EXAMPLE>{@code * TagNode tn = new TagNode("<DIV CLASS=MyMainClass1>"); * * System.out.println(tn.toLowerCase(true)); * // Prints: "<div CLASS=MyMainClass1>" * // NOTE: Only the 'div' is lower-case, the 'class' attribute is still upper-case * * System.out.println(tn.toLowerCase(false)); * // Prints: "<div class=MyMainClass1>" * // NOTE: The Tag-Name and all Attribute-Names are now lower-case. * // ALSO: The CSS-Class Name (an Attribute-Value) has remained unchanged. * }<DIV> * --> * * @return A lower-case version of {@code 'this'} instance. Only the Tag-Name, or the * Tag-Name and the Attribute-<B STYLE='color: red;'>Name's</B> will be de-capitalized. This * method will leave Attributte-<B STYLE='color: red;'>Values</B> unmodified. * * <BR /><BR />All spacing characters and (again) Attribute-<B STYLE='color: red;'>Values</B> * will remain unchanged. * * <BR /><BR /><B CLASS=JDDescLabel>'DATA-' ATTRIBUTES:</B> * * <BR />HTML {@code 'data-*'} Attributes are Inner-Tags that allow a programmer to pass * 'values', of one kind or another, that have a name to a Web-Browser or client. Since there * is the possibility that the 'name' provided is case-sensitive, this method will not alter the * name text that apears after the {@code 'data-'} portion of the * Attribute-<B STYLE='color: red;'>Name</B> for HTML Data-Attributes. */ public TagNode toLowerCase(boolean justTag_Or_TagAndAttributeNames) { if (justTag_Or_TagAndAttributeNames) return new TagNode( this.isClosing ? ("</" + this.tok.toLowerCase() + this.str.substring(2 + this.tok.length())) : ('<' + this.tok.toLowerCase() + this.str.substring(1 + this.tok.length())) ); StringBuilder sb = new StringBuilder(); Matcher m = AttrRegEx.KEY_VALUE_REGEX.matcher(this.str); sb.append(this.isClosing ? "</" : "<"); sb.append(this.tok.toLowerCase()); // Skip over the opening '<' and the Tag-Name int pos = this.tok.length() + 1; // If this was a "Closing Tag", remember to skip the opeing '/' if (this.isClosing) pos++; // Here, the Key-Value (Attribue-Name & Attribute-Value) pairs are iterated. Care is // taken to ensure that only the names (not the values) are modified. while (m.find()) { // Apppend white-space that occurs **BEFORE** the Name-Value Pair // // NOTE: The 'toLowerCase' here will catch any Attribute-Name-Only Attributes // (also known as "Boolean-Attributes") sb.append(this.str.substring(pos, m.start(2)).toLowerCase()); // Append the Attribute-Name, and make sure to De-Capitalize it. First this needs to // be retrieved, and (more importantly), do not modify the actual name-part of "data-" // Attributes, their case **COULD POSSIBLY** be important... (They are for the EmbedTag // Parameters Data-Attributes) String attrName = m.group(2).toLowerCase(); sb.append( StrCmpr.startsWithIgnoreCase(attrName, "data-") ? ("DATA-" + attrName.substring(5).toLowerCase()) : attrName.toLowerCase() ); // Append the Attribute-Value, and update the 'pos' variable to reflect where // in the String the current Match-Location ends... // // NOTE: m.end(2) and m.end() are the exact same values, since this regex's // group #2 ends at the very-end of the regex pattern. sb.append(this.str.substring(pos = m.end(2), pos)); } // ALWAYS: After the last match of a RegEx, remember to append any text that occurs // after the last match. This is also quite important in the HTML-Parser // not to forget this line. sb.append(this.str.substring(pos)); // Return the new TagNode return new TagNode(sb.toString()); } // ******************************************************************************************** // ******************************************************************************************** // Internally used Regular Expressions, (STATIC FIELDS INSIDE STATIC CLASS) // ******************************************************************************************** // ******************************************************************************************** /** * Regular-Expressions that are used by both the parsing class {@link HTMLPage}, and class * {@link TagNode} for searching HTML tags for attributes and even data. * * <BR /><BR /><EMBED CLASS="external-html" DATA-FILE-ID=TAGNODE_ATTR_REGEX> */ public static final class AttrRegEx { private AttrRegEx() { } /** * <EMBED CLASS="external-html" DATA-FILE-ID=TAGNODE_REGEX_KV> * @see TagNode#allAV(boolean, boolean) */ public static final Pattern KEY_VALUE_REGEX = Pattern.compile( "(?:\\s+?" + // mandatory leading white-space "(([\\w-]+?)=(" + // inner-tag name (a.k.a. 'key' or 'attribute-name') "'[^']*?'" + "|" + // inner-tag value using single-quotes ... 'OR' "\"[^\"]*?\"" + "|" + // inner-tag value using double-quotes ... 'OR' "[^\"'>\\s]*" + // inner-tag value without quotes ")))", Pattern.CASE_INSENSITIVE | Pattern.DOTALL ); /** * A {@code Predicate<String>} Regular-Expression. * @see #KEY_VALUE_REGEX */ public static final Predicate<String> KEY_VALUE_REGEX_PRED = KEY_VALUE_REGEX.asPredicate(); /** * <B CLASS=JDDescLabel>Legacy Regular Expression:</B> * * <BR />This RegEx was originall used by the method {@link #AV(String)}, but no longer is. * This isn't being deprecated because it still serves the purpose of showing how the HTML * Tags in this class are stored. * * <BR /><BR /><B CLASS=JDDescLabel>Capture Group:</B> * * <BR />This Regular-Expression has a single set of parenthesis <I>(and therefore only one * Capture-Group!)</I>. Notice that that group practically includes the entire RegEx - all * except the very first equals-sign located at the first character of the {@code String}. * * @see TagNode#AV(String) */ public static final Pattern QUOTES_AND_VALUE_REGEX = Pattern.compile( // Matches, for example: ='MyClass' or ="MyClass" or =MyClass "=(" + "\"[^\"]*?\"" + "|" + // inner-tag value using single-quotes ... 'OR' "'[^']*?'" + "|" + // inner-tag value using double-quotes ... 'OR' "[\\w-]+" + // inner-tag value without quotes ")", Pattern.DOTALL ); /** * A {@code Predicate<String>} Regular-Expression. * @see #QUOTES_AND_VALUE_REGEX */ public static final Predicate<String> QUOTES_AND_VALUE_REGEX_PRED = QUOTES_AND_VALUE_REGEX.asPredicate(); /** * This matches all valid attribute-<B STYLE="color: red;">keys</B> <I>(not values)</I> of * HTML Element <B STYLE="color: red;">key-value pairs</B>. * * <BR /><BR /><UL CLASS="JDUL"> * <LI> <B>PART-1:</B> {@code [A-Za-z_]} The first character must be a letter or the * underscore. * </LI> * <LI> <B>PART-2:</B> {@code [A-Za-z0-9_-]} All other characters must be alpha-numeric, * the dash {@code '-'}, or the underscore {@code '_'}. * </LI> * </UL> * * @see InnerTagKeyException#check(String[]) * @see #allKeyOnlyAttributes(boolean) */ public static final Pattern ATTRIBUTE_KEY_REGEX = Pattern.compile("^[A-Za-z_][A-Za-z0-9_-]*$"); /** * A {@code Predicate<String>} Regular-Expression. * @see #ATTRIBUTE_KEY_REGEX */ public static final Predicate<String> ATTRIBUTE_KEY_REGEX_PRED = ATTRIBUTE_KEY_REGEX.asPredicate(); /** * <EMBED CLASS="external-html" DATA-FILE-ID=TAGNODE_REGEX_DATA> * @see TagNode#getDataAN() * @see TagNode#getDataAV() */ public static final Pattern DATA_ATTRIBUTE_REGEX = Pattern.compile( // regex will match, for example: data-src="https://cdn.imgur.com/MyImage.jpg" "(?:\\s+?" + // mandatory leading white-space "(data-([\\w-]+?)=" + // data inner-tag name "(" + "'[^']*?'" + "|" + // inner-tag value using single-quotes ... 'OR' "\"[^\"]*?\"" + "|" + // inner-tag value using double-quotes ... 'OR "[^\"'>\\s]*" + // inner-tag value without quotes ")))", Pattern.CASE_INSENSITIVE | Pattern.DOTALL ); /** * A {@code Predicate<String>} Regular-Expression. * @see #DATA_ATTRIBUTE_REGEX */ public static final Predicate<String> DATA_ATTRIBUTE_REGEX_PRED = DATA_ATTRIBUTE_REGEX.asPredicate(); /** * <EMBED CLASS="external-html" DATA-FILE-ID=TAGNODE_REGEX_CSS> * @see TagNode#cssStyle() */ public static final Pattern CSS_INLINE_STYLE_REGEX = Pattern.compile( // regex will match, for example: font-weight: bold; // CSS Style Property Name - Must begin with letter or underscore "([_\\-a-zA-Z]+" + "[_\\-a-zA-Z0-9]*)" + // The ":" symbol between property-name and property-value "\\s*?" + ":" + "\\s*?" + // CSS Style Property Value "([^;]+?\\s*)" + // text after the "Name : Value" definition "(;|$|[\\w]+$)" ); /** * A {@code Predicate<String>} Regular-Expression. * @see #CSS_INLINE_STYLE_REGEX */ public static final Predicate<String> CSS_INLINE_STYLE_REGEX_PRED = CSS_INLINE_STYLE_REGEX.asPredicate(); } } |