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 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.jasper.compiler;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TimeZone;
import java.util.Vector;
import javax.el.MethodExpression;
import javax.el.ValueExpression;
import javax.servlet.jsp.tagext.TagAttributeInfo;
import javax.servlet.jsp.tagext.TagInfo;
import javax.servlet.jsp.tagext.TagVariableInfo;
import javax.servlet.jsp.tagext.VariableInfo;
import org.apache.jasper.Constants;
import org.apache.jasper.JasperException;
import org.apache.jasper.JspCompilationContext;
import org.apache.jasper.compiler.Node.NamedAttribute;
import org.apache.jasper.runtime.JspRuntimeLibrary;
import org.xml.sax.Attributes;
/**
* Generate Java source from Nodes
*
* @author Anil K. Vijendran
* @author Danno Ferrin
* @author Mandar Raje
* @author Rajiv Mordani
* @author Pierre Delisle
*
* Tomcat 4.1.x and Tomcat 5:
* @author Kin-man Chung
* @author Jan Luehe
* @author Shawn Bayern
* @author Mark Roth
* @author Denis Benoit
*
* Tomcat 6.x
* @author Jacob Hookom
* @author Remy Maucherat
*/
class Generator {
private static final Class<?>[] OBJECT_CLASS = { Object.class };
private static final String VAR_EXPRESSIONFACTORY =
System.getProperty("org.apache.jasper.compiler.Generator.VAR_EXPRESSIONFACTORY", "_el_expressionfactory");
private static final String VAR_INSTANCEMANAGER =
System.getProperty("org.apache.jasper.compiler.Generator.VAR_INSTANCEMANAGER", "_jsp_instancemanager");
private static final boolean POOL_TAGS_WITH_EXTENDS =
Boolean.getBoolean("org.apache.jasper.compiler.Generator.POOL_TAGS_WITH_EXTENDS");
/* System property that controls if the requirement to have the object
* used in jsp:getProperty action to be previously "introduced"
* to the JSP processor (see JSP.5.3) is enforced.
*/
private static final boolean STRICT_GET_PROPERTY = Boolean.valueOf(
System.getProperty(
"org.apache.jasper.compiler.Generator.STRICT_GET_PROPERTY",
"true")).booleanValue();
private final ServletWriter out;
private final ArrayList<GenBuffer> methodsBuffered;
private final FragmentHelperClass fragmentHelperClass;
private final ErrorDispatcher err;
private final BeanRepository beanInfo;
private final Set<String> varInfoNames;
private final JspCompilationContext ctxt;
private final boolean isPoolingEnabled;
private final boolean breakAtLF;
private String jspIdPrefix;
private int jspId;
private final PageInfo pageInfo;
private final Vector<String> tagHandlerPoolNames;
private GenBuffer charArrayBuffer;
private final DateFormat timestampFormat;
private final ELInterpreter elInterpreter;
/**
* @param s
* the input string
* @return quoted and escaped string, per Java rule
*/
static String quote(String s) {
if (s == null)
return "null";
return '"' + escape(s) + '"';
}
/**
* @param s
* the input string
* @return escaped string, per Java rule
*/
static String escape(String s) {
if (s == null)
return "";
StringBuilder b = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '"')
b.append('\\').append('"');
else if (c == '\\')
b.append('\\').append('\\');
else if (c == '\n')
b.append('\\').append('n');
else if (c == '\r')
b.append('\\').append('r');
else
b.append(c);
}
return b.toString();
}
/**
* Single quote and escape a character
*/
static String quote(char c) {
StringBuilder b = new StringBuilder();
b.append('\'');
if (c == '\'')
b.append('\\').append('\'');
else if (c == '\\')
b.append('\\').append('\\');
else if (c == '\n')
b.append('\\').append('n');
else if (c == '\r')
b.append('\\').append('r');
else
b.append(c);
b.append('\'');
return b.toString();
}
private String createJspId() {
if (this.jspIdPrefix == null) {
StringBuilder sb = new StringBuilder(32);
String name = ctxt.getServletJavaFileName();
sb.append("jsp_");
// Cast to long to avoid issue with Integer.MIN_VALUE
sb.append(Math.abs((long) name.hashCode()));
sb.append('_');
this.jspIdPrefix = sb.toString();
}
return this.jspIdPrefix + (this.jspId++);
}
/**
* Generates declarations. This includes "info" of the page directive, and
* scriptlet declarations.
*/
private void generateDeclarations(Node.Nodes page) throws JasperException {
class DeclarationVisitor extends Node.Visitor {
private boolean getServletInfoGenerated = false;
/*
* Generates getServletInfo() method that returns the value of the
* page directive's 'info' attribute, if present.
*
* The Validator has already ensured that if the translation unit
* contains more than one page directive with an 'info' attribute,
* their values match.
*/
@Override
public void visit(Node.PageDirective n) throws JasperException {
if (getServletInfoGenerated) {
return;
}
String info = n.getAttributeValue("info");
if (info == null)
return;
getServletInfoGenerated = true;
out.printil("public java.lang.String getServletInfo() {");
out.pushIndent();
out.printin("return ");
out.print(quote(info));
out.println(";");
out.popIndent();
out.printil("}");
out.println();
}
@Override
public void visit(Node.Declaration n) throws JasperException {
n.setBeginJavaLine(out.getJavaLine());
out.printMultiLn(n.getText());
out.println();
n.setEndJavaLine(out.getJavaLine());
}
// Custom Tags may contain declarations from tag plugins.
@Override
public void visit(Node.CustomTag n) throws JasperException {
if (n.useTagPlugin()) {
if (n.getAtSTag() != null) {
n.getAtSTag().visit(this);
}
visitBody(n);
if (n.getAtETag() != null) {
n.getAtETag().visit(this);
}
} else {
visitBody(n);
}
}
}
out.println();
page.visit(new DeclarationVisitor());
}
/**
* Compiles list of tag handler pool names.
*/
private void compileTagHandlerPoolList(Node.Nodes page)
throws JasperException {
class TagHandlerPoolVisitor extends Node.Visitor {
private final Vector<String> names;
/*
* Constructor
*
* @param v Vector of tag handler pool names to populate
*/
TagHandlerPoolVisitor(Vector<String> v) {
names = v;
}
/*
* Gets the name of the tag handler pool for the given custom tag
* and adds it to the list of tag handler pool names unless it is
* already contained in it.
*/
@Override
public void visit(Node.CustomTag n) throws JasperException {
if (!n.implementsSimpleTag()) {
String name = createTagHandlerPoolName(n.getPrefix(), n
.getLocalName(), n.getAttributes(),
n.getNamedAttributeNodes(), n.hasEmptyBody());
n.setTagHandlerPoolName(name);
if (!names.contains(name)) {
names.add(name);
}
}
visitBody(n);
}
/*
* Creates the name of the tag handler pool whose tag handlers may
* be (re)used to service this action.
*
* @return The name of the tag handler pool
*/
private String createTagHandlerPoolName(String prefix,
String shortName, Attributes attrs, Node.Nodes namedAttrs,
boolean hasEmptyBody) {
StringBuilder poolName = new StringBuilder(64);
poolName.append("_jspx_tagPool_").append(prefix).append('_')
.append(shortName);
if (attrs != null) {
String[] attrNames =
new String[attrs.getLength() + namedAttrs.size()];
for (int i = 0; i < attrNames.length; i++) {
attrNames[i] = attrs.getQName(i);
}
for (int i = 0; i < namedAttrs.size(); i++) {
attrNames[attrs.getLength() + i] =
((NamedAttribute) namedAttrs.getNode(i)).getQName();
}
Arrays.sort(attrNames, Collections.reverseOrder());
if (attrNames.length > 0) {
poolName.append('&');
}
for (int i = 0; i < attrNames.length; i++) {
poolName.append('_');
poolName.append(attrNames[i]);
}
}
if (hasEmptyBody) {
poolName.append("_nobody");
}
return JspUtil.makeJavaIdentifier(poolName.toString());
}
}
page.visit(new TagHandlerPoolVisitor(tagHandlerPoolNames));
}
private void declareTemporaryScriptingVars(Node.Nodes page)
throws JasperException {
class ScriptingVarVisitor extends Node.Visitor {
private final Vector<String> vars;
ScriptingVarVisitor() {
vars = new Vector<String>();
}
@Override
public void visit(Node.CustomTag n) throws JasperException {
// XXX - Actually there is no need to declare those
// "_jspx_" + varName + "_" + nestingLevel variables when we are
// inside a JspFragment.
if (n.getCustomNestingLevel() > 0) {
TagVariableInfo[] tagVarInfos = n.getTagVariableInfos();
VariableInfo[] varInfos = n.getVariableInfos();
if (varInfos.length > 0) {
for (int i = 0; i < varInfos.length; i++) {
String varName = varInfos[i].getVarName();
String tmpVarName = "_jspx_" + varName + "_"
+ n.getCustomNestingLevel();
if (!vars.contains(tmpVarName)) {
vars.add(tmpVarName);
out.printin(varInfos[i].getClassName());
out.print(" ");
out.print(tmpVarName);
out.print(" = ");
out.print(null);
out.println(";");
}
}
} else {
for (int i = 0; i < tagVarInfos.length; i++) {
String varName = tagVarInfos[i].getNameGiven();
if (varName == null) {
varName = n.getTagData().getAttributeString(
tagVarInfos[i].getNameFromAttribute());
} else if (tagVarInfos[i].getNameFromAttribute() != null) {
// alias
continue;
}
String tmpVarName = "_jspx_" + varName + "_"
+ n.getCustomNestingLevel();
if (!vars.contains(tmpVarName)) {
vars.add(tmpVarName);
out.printin(tagVarInfos[i].getClassName());
out.print(" ");
out.print(tmpVarName);
out.print(" = ");
out.print(null);
out.println(";");
}
}
}
}
visitBody(n);
}
}
page.visit(new ScriptingVarVisitor());
}
/**
* Generates the _jspInit() method for instantiating the tag handler pools.
* For tag file, _jspInit has to be invoked manually, and the ServletConfig
* object explicitly passed.
*
* In JSP 2.1, we also instantiate an ExpressionFactory
*/
private void generateInit() {
if (ctxt.isTagFile()) {
out.printil("private void _jspInit(javax.servlet.ServletConfig config) {");
} else {
out.printil("public void _jspInit() {");
}
out.pushIndent();
if (isPoolingEnabled) {
for (int i = 0; i < tagHandlerPoolNames.size(); i++) {
out.printin(tagHandlerPoolNames.elementAt(i));
out.print(" = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(");
if (ctxt.isTagFile()) {
out.print("config");
} else {
out.print("getServletConfig()");
}
out.println(");");
}
}
out.printin(VAR_EXPRESSIONFACTORY);
out.print(" = _jspxFactory.getJspApplicationContext(");
if (ctxt.isTagFile()) {
out.print("config");
} else {
out.print("getServletConfig()");
}
out.println(".getServletContext()).getExpressionFactory();");
out.printin(VAR_INSTANCEMANAGER);
out.print(" = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(");
if (ctxt.isTagFile()) {
out.print("config");
} else {
out.print("getServletConfig()");
}
out.println(");");
out.popIndent();
out.printil("}");
out.println();
}
/**
* Generates the _jspDestroy() method which is responsible for calling the
* release() method on every tag handler in any of the tag handler pools.
*/
private void generateDestroy() {
out.printil("public void _jspDestroy() {");
out.pushIndent();
if (isPoolingEnabled) {
for (int i = 0; i < tagHandlerPoolNames.size(); i++) {
out.printin(tagHandlerPoolNames.elementAt(i));
out.println(".release();");
}
}
out.popIndent();
out.printil("}");
out.println();
}
/**
* Generate preamble package name (shared by servlet and tag handler
* preamble generation)
*/
private void genPreamblePackage(String packageName) {
if (!"".equals(packageName) && packageName != null) {
out.printil("package " + packageName + ";");
out.println();
}
}
/**
* Generate preamble imports (shared by servlet and tag handler preamble
* generation)
*/
private void genPreambleImports() {
Iterator<String> iter = pageInfo.getImports().iterator();
while (iter.hasNext()) {
out.printin("import ");
out.print(iter.next());
out.println(";");
}
out.println();
}
/**
* Generation of static initializers in preamble. For example, dependent
* list, el function map, prefix map. (shared by servlet and tag handler
* preamble generation)
*/
private void genPreambleStaticInitializers() {
out.printil("private static final javax.servlet.jsp.JspFactory _jspxFactory =");
out.printil(" javax.servlet.jsp.JspFactory.getDefaultFactory();");
out.println();
// Static data for getDependants()
out.printil("private static java.util.Map<java.lang.String,java.lang.Long> _jspx_dependants;");
out.println();
Map<String,Long> dependants = pageInfo.getDependants();
Iterator<Entry<String,Long>> iter = dependants.entrySet().iterator();
if (!dependants.isEmpty()) {
out.printil("static {");
out.pushIndent();
out.printin("_jspx_dependants = new java.util.HashMap<java.lang.String,java.lang.Long>(");
out.print("" + dependants.size());
out.println(");");
while (iter.hasNext()) {
Entry<String,Long> entry = iter.next();
out.printin("_jspx_dependants.put(\"");
out.print(entry.getKey());
out.print("\", Long.valueOf(");
out.print(entry.getValue().toString());
out.println("L));");
}
out.popIndent();
out.printil("}");
out.println();
}
}
/**
* Declare tag handler pools (tags of the same type and with the same
* attribute set share the same tag handler pool) (shared by servlet and tag
* handler preamble generation)
*
* In JSP 2.1, we also scope an instance of ExpressionFactory
*/
private void genPreambleClassVariableDeclarations() {
if (isPoolingEnabled && !tagHandlerPoolNames.isEmpty()) {
for (int i = 0; i < tagHandlerPoolNames.size(); i++) {
out.printil("private org.apache.jasper.runtime.TagHandlerPool "
+ tagHandlerPoolNames.elementAt(i) + ";");
}
out.println();
}
out.printin("private javax.el.ExpressionFactory ");
out.print(VAR_EXPRESSIONFACTORY);
out.println(";");
out.printin("private org.apache.tomcat.InstanceManager ");
out.print(VAR_INSTANCEMANAGER);
out.println(";");
out.println();
}
/**
* Declare general-purpose methods (shared by servlet and tag handler
* preamble generation)
*/
private void genPreambleMethods() {
// Method used to get compile time file dependencies
out.printil("public java.util.Map<java.lang.String,java.lang.Long> getDependants() {");
out.pushIndent();
out.printil("return _jspx_dependants;");
out.popIndent();
out.printil("}");
out.println();
generateInit();
generateDestroy();
}
/**
* Generates the beginning of the static portion of the servlet.
*/
private void generatePreamble(Node.Nodes page) throws JasperException {
String servletPackageName = ctxt.getServletPackageName();
String servletClassName = ctxt.getServletClassName();
String serviceMethodName = Constants.SERVICE_METHOD_NAME;
// First the package name:
genPreamblePackage(servletPackageName);
// Generate imports
genPreambleImports();
// Generate class declaration
out.printin("public final class ");
out.print(servletClassName);
out.print(" extends ");
out.println(pageInfo.getExtends());
out.printin(" implements org.apache.jasper.runtime.JspSourceDependent");
if (!pageInfo.isThreadSafe()) {
out.println(",");
out.printin(" javax.servlet.SingleThreadModel");
}
out.println(" {");
out.pushIndent();
// Class body begins here
generateDeclarations(page);
// Static initializations here
genPreambleStaticInitializers();
// Class variable declarations
genPreambleClassVariableDeclarations();
// Methods here
genPreambleMethods();
// Now the service method
out.printin("public void ");
out.print(serviceMethodName);
out.println("(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response)");
out.println(" throws java.io.IOException, javax.servlet.ServletException {");
out.pushIndent();
out.println();
// Local variable declarations
out.printil("final javax.servlet.jsp.PageContext pageContext;");
if (pageInfo.isSession())
out.printil("javax.servlet.http.HttpSession session = null;");
if (pageInfo.isErrorPage()) {
out.printil("java.lang.Throwable exception = org.apache.jasper.runtime.JspRuntimeLibrary.getThrowable(request);");
out.printil("if (exception != null) {");
out.pushIndent();
out.printil("response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR);");
out.popIndent();
out.printil("}");
}
out.printil("final javax.servlet.ServletContext application;");
out.printil("final javax.servlet.ServletConfig config;");
out.printil("javax.servlet.jsp.JspWriter out = null;");
out.printil("final java.lang.Object page = this;");
out.printil("javax.servlet.jsp.JspWriter _jspx_out = null;");
out.printil("javax.servlet.jsp.PageContext _jspx_page_context = null;");
out.println();
declareTemporaryScriptingVars(page);
out.println();
out.printil("try {");
out.pushIndent();
out.printin("response.setContentType(");
out.print(quote(pageInfo.getContentType()));
out.println(");");
if (ctxt.getOptions().isXpoweredBy()) {
out.printil("response.addHeader(\"X-Powered-By\", \"JSP/2.1\");");
}
out.printil("pageContext = _jspxFactory.getPageContext(this, request, response,");
out.printin("\t\t\t");
out.print(quote(pageInfo.getErrorPage()));
out.print(", " + pageInfo.isSession());
out.print(", " + pageInfo.getBuffer());
out.print(", " + pageInfo.isAutoFlush());
out.println(");");
out.printil("_jspx_page_context = pageContext;");
out.printil("application = pageContext.getServletContext();");
out.printil("config = pageContext.getServletConfig();");
if (pageInfo.isSession())
out.printil("session = pageContext.getSession();");
out.printil("out = pageContext.getOut();");
out.printil("_jspx_out = out;");
out.println();
}
/**
* Generates an XML Prolog, which includes an XML declaration and an XML
* doctype declaration.
*/
private void generateXmlProlog(Node.Nodes page) {
/*
* An XML declaration is generated under the following conditions: -
* 'omit-xml-declaration' attribute of <jsp:output> action is set to
* "no" or "false" - JSP document without a <jsp:root>
*/
String omitXmlDecl = pageInfo.getOmitXmlDecl();
if ((omitXmlDecl != null && !JspUtil.booleanValue(omitXmlDecl))
|| (omitXmlDecl == null && page.getRoot().isXmlSyntax()
&& !pageInfo.hasJspRoot() && !ctxt.isTagFile())) {
String cType = pageInfo.getContentType();
String charSet = cType.substring(cType.indexOf("charset=") + 8);
out.printil("out.write(\"<?xml version=\\\"1.0\\\" encoding=\\\""
+ charSet + "\\\"?>\\n\");");
}
/*
* Output a DOCTYPE declaration if the doctype-root-element appears. If
* doctype-public appears: <!DOCTYPE name PUBLIC "doctypePublic"
* "doctypeSystem"> else <!DOCTYPE name SYSTEM "doctypeSystem" >
*/
String doctypeName = pageInfo.getDoctypeName();
if (doctypeName != null) {
String doctypePublic = pageInfo.getDoctypePublic();
String doctypeSystem = pageInfo.getDoctypeSystem();
out.printin("out.write(\"<!DOCTYPE ");
out.print(doctypeName);
if (doctypePublic == null) {
out.print(" SYSTEM \\\"");
} else {
out.print(" PUBLIC \\\"");
out.print(doctypePublic);
out.print("\\\" \\\"");
}
out.print(doctypeSystem);
out.println("\\\">\\n\");");
}
}
/**
* A visitor that generates codes for the elements in the page.
*/
class GenerateVisitor extends Node.Visitor {
/*
* Hashtable containing introspection information on tag handlers:
* <key>: tag prefix <value>: hashtable containing introspection on tag
* handlers: <key>: tag short name <value>: introspection info of tag
* handler for <prefix:shortName> tag
*/
private final Hashtable<String,Hashtable<String,TagHandlerInfo>> handlerInfos;
private final Hashtable<String,Integer> tagVarNumbers;
private String parent;
private boolean isSimpleTagParent; // Is parent a SimpleTag?
private String pushBodyCountVar;
private String simpleTagHandlerVar;
private boolean isSimpleTagHandler;
private boolean isFragment;
private final boolean isTagFile;
private ServletWriter out;
private final ArrayList<GenBuffer> methodsBuffered;
private final FragmentHelperClass fragmentHelperClass;
private int methodNesting;
private int charArrayCount;
private HashMap<String,String> textMap;
/**
* Constructor.
*/
public GenerateVisitor(boolean isTagFile, ServletWriter out,
ArrayList<GenBuffer> methodsBuffered,
FragmentHelperClass fragmentHelperClass) {
this.isTagFile = isTagFile;
this.out = out;
this.methodsBuffered = methodsBuffered;
this.fragmentHelperClass = fragmentHelperClass;
methodNesting = 0;
handlerInfos =
new Hashtable<String,Hashtable<String,TagHandlerInfo>>();
tagVarNumbers = new Hashtable<String,Integer>();
textMap = new HashMap<String,String>();
}
/**
* Returns an attribute value, optionally URL encoded. If the value is a
* runtime expression, the result is the expression itself, as a string.
* If the result is an EL expression, we insert a call to the
* interpreter. If the result is a Named Attribute we insert the
* generated variable name. Otherwise the result is a string literal,
* quoted and escaped.
*
* @param attr
* An JspAttribute object
* @param encode
* true if to be URL encoded
* @param expectedType
* the expected type for an EL evaluation (ignored for
* attributes that aren't EL expressions)
*/
private String attributeValue(Node.JspAttribute attr, boolean encode,
Class<?> expectedType, boolean isXml) {
String v = attr.getValue();
if (!attr.isNamedAttribute() && (v == null))
return "";
if (attr.isExpression()) {
if (encode) {
return "org.apache.jasper.runtime.JspRuntimeLibrary.URLEncode(String.valueOf("
+ v + "), request.getCharacterEncoding())";
}
return v;
} else if (attr.isELInterpreterInput()) {
v = elInterpreter.interpreterCall(ctxt, this.isTagFile, v,
expectedType, attr.getEL().getMapName(), isXml);
if (encode) {
return "org.apache.jasper.runtime.JspRuntimeLibrary.URLEncode("
+ v + ", request.getCharacterEncoding())";
}
return v;
} else if (attr.isNamedAttribute()) {
return attr.getNamedAttributeNode().getTemporaryVariableName();
} else {
if (encode) {
return "org.apache.jasper.runtime.JspRuntimeLibrary.URLEncode("
+ quote(v) + ", request.getCharacterEncoding())";
}
return quote(v);
}
}
/**
* Prints the attribute value specified in the param action, in the form
* of name=value string.
*
* @param n
* the parent node for the param action nodes.
*/
private void printParams(Node n, String pageParam, boolean literal)
throws JasperException {
class ParamVisitor extends Node.Visitor {
String separator;
ParamVisitor(String separator) {
this.separator = separator;
}
@Override
public void visit(Node.ParamAction n) throws JasperException {
out.print(" + ");
out.print(separator);
out.print(" + ");
out.print("org.apache.jasper.runtime.JspRuntimeLibrary."
+ "URLEncode(" + quote(n.getTextAttribute("name"))
+ ", request.getCharacterEncoding())");
out.print("+ \"=\" + ");
out.print(attributeValue(n.getValue(), true, String.class,
n.getRoot().isXmlSyntax()));
// The separator is '&' after the second use
separator = "\"&\"";
}
}
String sep;
if (literal) {
sep = pageParam.indexOf('?') > 0 ? "\"&\"" : "\"?\"";
} else {
sep = "((" + pageParam + ").indexOf('?')>0? '&': '?')";
}
if (n.getBody() != null) {
n.getBody().visit(new ParamVisitor(sep));
}
}
@Override
public void visit(Node.Expression n) throws JasperException {
n.setBeginJavaLine(out.getJavaLine());
out.printin("out.print(");
out.printMultiLn(n.getText());
out.println(");");
n.setEndJavaLine(out.getJavaLine());
}
@Override
public void visit(Node.Scriptlet n) throws JasperException {
n.setBeginJavaLine(out.getJavaLine());
out.printMultiLn(n.getText());
out.println();
n.setEndJavaLine(out.getJavaLine());
}
@Override
public void visit(Node.ELExpression n) throws JasperException {
n.setBeginJavaLine(out.getJavaLine());
if (!pageInfo.isELIgnored() && (n.getEL() != null)) {
out.printil("out.write("
+ elInterpreter.interpreterCall(ctxt, this.isTagFile,
n.getType() + "{" + n.getText() + "}",
String.class, n.getEL().getMapName(), false) +
");");
} else {
out.printil("out.write("
+ quote(n.getType() + "{" + n.getText() + "}") + ");");
}
n.setEndJavaLine(out.getJavaLine());
}
@Override
public void visit(Node.IncludeAction n) throws JasperException {
String flush = n.getTextAttribute("flush");
Node.JspAttribute page = n.getPage();
boolean isFlush = false; // default to false;
if ("true".equals(flush))
isFlush = true;
n.setBeginJavaLine(out.getJavaLine());
String pageParam;
if (page.isNamedAttribute()) {
// If the page for jsp:include was specified via
// jsp:attribute, first generate code to evaluate
// that body.
pageParam = generateNamedAttributeValue(page
.getNamedAttributeNode());
} else {
pageParam = attributeValue(page, false, String.class,
n.getRoot().isXmlSyntax());
}
// If any of the params have their values specified by
// jsp:attribute, prepare those values first.
Node jspBody = findJspBody(n);
if (jspBody != null) {
prepareParams(jspBody);
} else {
prepareParams(n);
}
out.printin("org.apache.jasper.runtime.JspRuntimeLibrary.include(request, response, "
+ pageParam);
printParams(n, pageParam, page.isLiteral());
out.println(", out, " + isFlush + ");");
n.setEndJavaLine(out.getJavaLine());
}
/**
* Scans through all child nodes of the given parent for <param>
* subelements. For each <param> element, if its value is specified via
* a Named Attribute (<jsp:attribute>), generate the code to evaluate
* those bodies first.
* <p>
* If parent is null, simply returns.
*/
private void prepareParams(Node parent) throws JasperException {
if (parent == null)
return;
Node.Nodes subelements = parent.getBody();
if (subelements != null) {
for (int i = 0; i < subelements.size(); i++) {
Node n = subelements.getNode(i);
if (n instanceof Node.ParamAction) {
Node.Nodes paramSubElements = n.getBody();
for (int j = 0; (paramSubElements != null)
&& (j < paramSubElements.size()); j++) {
Node m = paramSubElements.getNode(j);
if (m instanceof Node.NamedAttribute) {
generateNamedAttributeValue((Node.NamedAttribute) m);
}
}
}
}
}
}
/**
* Finds the <jsp:body> subelement of the given parent node. If not
* found, null is returned.
*/
private Node.JspBody findJspBody(Node parent) {
Node.JspBody result = null;
Node.Nodes subelements = parent.getBody();
for (int i = 0; (subelements != null) && (i < subelements.size()); i++) {
Node n = subelements.getNode(i);
if (n instanceof Node.JspBody) {
result = (Node.JspBody) n;
break;
}
}
return result;
}
@Override
public void visit(Node.ForwardAction n) throws JasperException {
Node.JspAttribute page = n.getPage();
n.setBeginJavaLine(out.getJavaLine());
out.printil("if (true) {"); // So that javac won't complain about
out.pushIndent(); // codes after "return"
String pageParam;
if (page.isNamedAttribute()) {
// If the page for jsp:forward was specified via
// jsp:attribute, first generate code to evaluate
// that body.
pageParam = generateNamedAttributeValue(page
.getNamedAttributeNode());
} else {
pageParam = attributeValue(page, false, String.class,
n.getRoot().isXmlSyntax());
}
// If any of the params have their values specified by
// jsp:attribute, prepare those values first.
Node jspBody = findJspBody(n);
if (jspBody != null) {
prepareParams(jspBody);
} else {
prepareParams(n);
}
out.printin("_jspx_page_context.forward(");
out.print(pageParam);
printParams(n, pageParam, page.isLiteral());
out.println(");");
if (isTagFile || isFragment) {
out.printil("throw new javax.servlet.jsp.SkipPageException();");
} else {
out.printil((methodNesting > 0) ? "return true;" : "return;");
}
out.popIndent();
out.printil("}");
n.setEndJavaLine(out.getJavaLine());
// XXX Not sure if we can eliminate dead codes after this.
}
@Override
public void visit(Node.GetProperty n) throws JasperException {
String name = n.getTextAttribute("name");
String property = n.getTextAttribute("property");
n.setBeginJavaLine(out.getJavaLine());
if (beanInfo.checkVariable(name)) {
// Bean is defined using useBean, introspect at compile time
Class<?> bean = beanInfo.getBeanType(name);
String beanName = bean.getCanonicalName();
java.lang.reflect.Method meth = JspRuntimeLibrary
.getReadMethod(bean, property);
String methodName = meth.getName();
out.printil("out.write(org.apache.jasper.runtime.JspRuntimeLibrary.toString("
+ "((("
+ beanName
+ ")_jspx_page_context.findAttribute("
+ "\""
+ name + "\"))." + methodName + "())));");
} else if (!STRICT_GET_PROPERTY || varInfoNames.contains(name)) {
// The object is a custom action with an associated
// VariableInfo entry for this name.
// Get the class name and then introspect at runtime.
out.printil("out.write(org.apache.jasper.runtime.JspRuntimeLibrary.toString"
+ "(org.apache.jasper.runtime.JspRuntimeLibrary.handleGetProperty"
+ "(_jspx_page_context.findAttribute(\""
+ name
+ "\"), \""
+ property
+ "\")));");
} else {
StringBuilder msg = new StringBuilder();
msg.append("file:");
msg.append(n.getStart());
msg.append(" jsp:getProperty for bean with name '");
msg.append(name);
msg.append(
"'. Name was not previously introduced as per JSP.5.3");
throw new JasperException(msg.toString());
}
n.setEndJavaLine(out.getJavaLine());
}
@Override
public void visit(Node.SetProperty n) throws JasperException {
String name = n.getTextAttribute("name");
String property = n.getTextAttribute("property");
String param = n.getTextAttribute("param");
Node.JspAttribute value = n.getValue();
n.setBeginJavaLine(out.getJavaLine());
if ("*".equals(property)) {
out.printil("org.apache.jasper.runtime.JspRuntimeLibrary.introspect("
+ "_jspx_page_context.findAttribute("
+ "\""
+ name + "\"), request);");
} else if (value == null) {
if (param == null)
param = property; // default to same as property
out.printil("org.apache.jasper.runtime.JspRuntimeLibrary.introspecthelper("
+ "_jspx_page_context.findAttribute(\""
+ name
+ "\"), \""
+ property
+ "\", request.getParameter(\""
+ param
+ "\"), "
+ "request, \""
+ param
+ "\", false);");
} else if (value.isExpression()) {
out.printil("org.apache.jasper.runtime.JspRuntimeLibrary.handleSetProperty("
+ "_jspx_page_context.findAttribute(\""
+ name
+ "\"), \"" + property + "\",");
out.print(attributeValue(value, false, null,
n.getRoot().isXmlSyntax()));
out.println(");");
} else if (value.isELInterpreterInput()) {
// We've got to resolve the very call to the interpreter
// at runtime since we don't know what type to expect
// in the general case; we thus can't hard-wire the call
// into the generated code. (XXX We could, however,
// optimize the case where the bean is exposed with
// <jsp:useBean>, much as the code here does for
// getProperty.)
// The following holds true for the arguments passed to
// JspRuntimeLibrary.handleSetPropertyExpression():
// - 'pageContext' is a VariableResolver.
// - 'this' (either the generated Servlet or the generated tag
// handler for Tag files) is a FunctionMapper.
out.printil("org.apache.jasper.runtime.JspRuntimeLibrary.handleSetPropertyExpression("
+ "_jspx_page_context.findAttribute(\""
+ name
+ "\"), \""
+ property
+ "\", "
+ quote(value.getValue())
+ ", "
+ "_jspx_page_context, "
+ value.getEL().getMapName() + ");");
} else if (value.isNamedAttribute()) {
// If the value for setProperty was specified via
// jsp:attribute, first generate code to evaluate
// that body.
String valueVarName = generateNamedAttributeValue(value
.getNamedAttributeNode());
out.printil("org.apache.jasper.runtime.JspRuntimeLibrary.introspecthelper("
+ "_jspx_page_context.findAttribute(\""
+ name
+ "\"), \""
+ property
+ "\", "
+ valueVarName
+ ", null, null, false);");
} else {
out.printin("org.apache.jasper.runtime.JspRuntimeLibrary.introspecthelper("
+ "_jspx_page_context.findAttribute(\""
+ name
+ "\"), \"" + property + "\", ");
out.print(attributeValue(value, false, null,
n.getRoot().isXmlSyntax()));
out.println(", null, null, false);");
}
n.setEndJavaLine(out.getJavaLine());
}
@Override
public void visit(Node.UseBean n) throws JasperException {
String name = n.getTextAttribute("id");
String scope = n.getTextAttribute("scope");
String klass = n.getTextAttribute("class");
String type = n.getTextAttribute("type");
Node.JspAttribute beanName = n.getBeanName();
// If "class" is specified, try an instantiation at compile time
boolean generateNew = false;
String canonicalName = null; // Canonical name for klass
if (klass != null) {
try {
Class<?> bean = ctxt.getClassLoader().loadClass(klass);
if (klass.indexOf('$') >= 0) {
// Obtain the canonical type name
canonicalName = bean.getCanonicalName();
} else {
canonicalName = klass;
}
int modifiers = bean.getModifiers();
if (!Modifier.isPublic(modifiers)
|| Modifier.isInterface(modifiers)
|| Modifier.isAbstract(modifiers)) {
throw new Exception("Invalid bean class modifier");
}
// Check that there is a 0 arg constructor
bean.getConstructor(new Class[] {});
// At compile time, we have determined that the bean class
// exists, with a public zero constructor, new() can be
// used for bean instantiation.
generateNew = true;
} catch (Exception e) {
// Cannot instantiate the specified class, either a
// compilation error or a runtime error will be raised,
// depending on a compiler flag.
if (ctxt.getOptions()
.getErrorOnUseBeanInvalidClassAttribute()) {
err.jspError(n, "jsp.error.invalid.bean", klass);
}
if (canonicalName == null) {
// Doing our best here to get a canonical name
// from the binary name, should work 99.99% of time.
canonicalName = klass.replace('$', '.');
}
}
if (type == null) {
// if type is unspecified, use "class" as type of bean
type = canonicalName;
}
}
// JSP.5.1, Sematics, para 1 - lock not required for request or
// page scope
String scopename = "javax.servlet.jsp.PageContext.PAGE_SCOPE"; // Default to page
String lock = null;
if ("request".equals(scope)) {
scopename = "javax.servlet.jsp.PageContext.REQUEST_SCOPE";
} else if ("session".equals(scope)) {
scopename = "javax.servlet.jsp.PageContext.SESSION_SCOPE";
lock = "session";
} else if ("application".equals(scope)) {
scopename = "javax.servlet.jsp.PageContext.APPLICATION_SCOPE";
lock = "application";
}
n.setBeginJavaLine(out.getJavaLine());
// Declare bean
out.printin(type);
out.print(' ');
out.print(name);
out.println(" = null;");
// Lock (if required) while getting or creating bean
if (lock != null) {
out.printin("synchronized (");
out.print(lock);
out.println(") {");
out.pushIndent();
}
// Locate bean from context
out.printin(name);
out.print(" = (");
out.print(type);
out.print(") _jspx_page_context.getAttribute(");
out.print(quote(name));
out.print(", ");
out.print(scopename);
out.println(");");
// Create bean
/*
* Check if bean is already there
*/
out.printin("if (");
out.print(name);
out.println(" == null){");
out.pushIndent();
if (klass == null && beanName == null) {
/*
* If both class name and beanName is not specified, the bean
* must be found locally, otherwise it's an error
*/
out.printin("throw new java.lang.InstantiationException(\"bean ");
out.print(name);
out.println(" not found within scope\");");
} else {
/*
* Instantiate the bean if it is not in the specified scope.
*/
if (!generateNew) {
String binaryName;
if (beanName != null) {
if (beanName.isNamedAttribute()) {
// If the value for beanName was specified via
// jsp:attribute, first generate code to evaluate
// that body.
binaryName = generateNamedAttributeValue(beanName
.getNamedAttributeNode());
} else {
binaryName = attributeValue(beanName, false,
String.class, n.getRoot().isXmlSyntax());
}
} else {
// Implies klass is not null
binaryName = quote(klass);
}
out.printil("try {");
out.pushIndent();
out.printin(name);
out.print(" = (");
out.print(type);
out.print(") java.beans.Beans.instantiate(");
out.print("this.getClass().getClassLoader(), ");
out.print(binaryName);
out.println(");");
out.popIndent();
/*
* Note: Beans.instantiate throws ClassNotFoundException if
* the bean class is abstract.
*/
out.printil("} catch (java.lang.ClassNotFoundException exc) {");
out.pushIndent();
out.printil("throw new InstantiationException(exc.getMessage());");
out.popIndent();
out.printil("} catch (java.lang.Exception exc) {");
out.pushIndent();
out.printin("throw new javax.servlet.ServletException(");
out.print("\"Cannot create bean of class \" + ");
out.print(binaryName);
out.println(", exc);");
out.popIndent();
out.printil("}"); // close of try
} else {
// Implies klass is not null
// Generate codes to instantiate the bean class
out.printin(name);
out.print(" = new ");
out.print(canonicalName);
out.println("();");
}
/*
* Set attribute for bean in the specified scope
*/
out.printin("_jspx_page_context.setAttribute(");
out.print(quote(name));
out.print(", ");
out.print(name);
out.print(", ");
out.print(scopename);
out.println(");");
// Only visit the body when bean is instantiated
visitBody(n);
}
out.popIndent();
out.printil("}");
// End of lock block
if (lock != null) {
out.popIndent();
out.printil("}");
}
n.setEndJavaLine(out.getJavaLine());
}
/**
* @return a string for the form 'attr = "value"'
*/
private String makeAttr(String attr, String value) {
if (value == null)
return "";
return " " + attr + "=\"" + value + '\"';
}
@Override
public void visit(Node.PlugIn n) throws JasperException {
/**
* A visitor to handle <jsp:param> in a plugin
*/
class ParamVisitor extends Node.Visitor {
private final boolean ie;
ParamVisitor(boolean ie) {
this.ie = ie;
}
@Override
public void visit(Node.ParamAction n) throws JasperException {
String name = n.getTextAttribute("name");
if (name.equalsIgnoreCase("object"))
name = "java_object";
else if (name.equalsIgnoreCase("type"))
name = "java_type";
n.setBeginJavaLine(out.getJavaLine());
// XXX - Fixed a bug here - value used to be output
// inline, which is only okay if value is not an EL
// expression. Also, key/value pairs for the
// embed tag were not being generated correctly.
// Double check that this is now the correct behavior.
if (ie) {
// We want something of the form
// out.println( "<param name=\"blah\"
// value=\"" + ... + "\">" );
out.printil("out.write( \"<param name=\\\"" +
escape(name) +
"\\\" value=\\\"\" + " +
attributeValue(n.getValue(), false,
String.class,
n.getRoot().isXmlSyntax()) +
" + \"\\\">\" );");
out.printil("out.write(\"\\n\");");
} else {
// We want something of the form
// out.print( " blah=\"" + ... + "\"" );
out.printil("out.write( \" " +
escape(name) +
"=\\\"\" + " +
attributeValue(n.getValue(), false,
String.class,
n.getRoot().isXmlSyntax()) +
" + \"\\\"\" );");
}
n.setEndJavaLine(out.getJavaLine());
}
}
String type = n.getTextAttribute("type");
String code = n.getTextAttribute("code");
String name = n.getTextAttribute("name");
Node.JspAttribute height = n.getHeight();
Node.JspAttribute width = n.getWidth();
String hspace = n.getTextAttribute("hspace");
String vspace = n.getTextAttribute("vspace");
String align = n.getTextAttribute("align");
String iepluginurl = n.getTextAttribute("iepluginurl");
String nspluginurl = n.getTextAttribute("nspluginurl");
String codebase = n.getTextAttribute("codebase");
String archive = n.getTextAttribute("archive");
String jreversion = n.getTextAttribute("jreversion");
String widthStr = null;
if (width != null) {
if (width.isNamedAttribute()) {
widthStr = generateNamedAttributeValue(width
.getNamedAttributeNode());
} else {
widthStr = attributeValue(width, false, String.class,
n.getRoot().isXmlSyntax());
}
}
String heightStr = null;
if (height != null) {
if (height.isNamedAttribute()) {
heightStr = generateNamedAttributeValue(height
.getNamedAttributeNode());
} else {
heightStr = attributeValue(height, false, String.class,
n.getRoot().isXmlSyntax());
}
}
if (iepluginurl == null)
iepluginurl = Constants.IE_PLUGIN_URL;
if (nspluginurl == null)
nspluginurl = Constants.NS_PLUGIN_URL;
n.setBeginJavaLine(out.getJavaLine());
// If any of the params have their values specified by
// jsp:attribute, prepare those values first.
// Look for a params node and prepare its param subelements:
Node.JspBody jspBody = findJspBody(n);
if (jspBody != null) {
Node.Nodes subelements = jspBody.getBody();
if (subelements != null) {
for (int i = 0; i < subelements.size(); i++) {
Node m = subelements.getNode(i);
if (m instanceof Node.ParamsAction) {
prepareParams(m);
break;
}
}
}
}
// XXX - Fixed a bug here - width and height can be set
// dynamically. Double-check if this generation is correct.
// IE style plugin
// <object ...>
// First compose the runtime output string
String s0 = "<object"
+ makeAttr("classid", ctxt.getOptions().getIeClassId())
+ makeAttr("name", name);
String s1 = "";
if (width != null) {
s1 = " + \" width=\\\"\" + " + widthStr + " + \"\\\"\"";
}
String s2 = "";
if (height != null) {
s2 = " + \" height=\\\"\" + " + heightStr + " + \"\\\"\"";
}
String s3 = makeAttr("hspace", hspace) + makeAttr("vspace", vspace)
+ makeAttr("align", align)
+ makeAttr("codebase", iepluginurl) + '>';
// Then print the output string to the java file
out.printil("out.write(" + quote(s0) + s1 + s2 + " + " + quote(s3)
+ ");");
out.printil("out.write(\"\\n\");");
// <param > for java_code
s0 = "<param name=\"java_code\"" + makeAttr("value", code) + '>';
out.printil("out.write(" + quote(s0) + ");");
out.printil("out.write(\"\\n\");");
// <param > for java_codebase
if (codebase != null) {
s0 = "<param name=\"java_codebase\""
+ makeAttr("value", codebase) + '>';
out.printil("out.write(" + quote(s0) + ");");
out.printil("out.write(\"\\n\");");
}
// <param > for java_archive
if (archive != null) {
s0 = "<param name=\"java_archive\""
+ makeAttr("value", archive) + '>';
out.printil("out.write(" + quote(s0) + ");");
out.printil("out.write(\"\\n\");");
}
// <param > for type
s0 = "<param name=\"type\""
+ makeAttr("value", "application/x-java-"
+ type
+ ((jreversion == null) ? "" : ";version="
+ jreversion)) + '>';
out.printil("out.write(" + quote(s0) + ");");
out.printil("out.write(\"\\n\");");
/*
* generate a <param> for each <jsp:param> in the plugin body
*/
if (n.getBody() != null)
n.getBody().visit(new ParamVisitor(true));
/*
* Netscape style plugin part
*/
out.printil("out.write(" + quote("<comment>") + ");");
out.printil("out.write(\"\\n\");");
s0 = "<EMBED"
+ makeAttr("type", "application/x-java-"
+ type
+ ((jreversion == null) ? "" : ";version="
+ jreversion)) + makeAttr("name", name);
// s1 and s2 are the same as before.
s3 = makeAttr("hspace", hspace) + makeAttr("vspace", vspace)
+ makeAttr("align", align)
+ makeAttr("pluginspage", nspluginurl)
+ makeAttr("java_code", code)
+ makeAttr("java_codebase", codebase)
+ makeAttr("java_archive", archive);
out.printil("out.write(" + quote(s0) + s1 + s2 + " + " + quote(s3)
+ ");");
/*
* Generate a 'attr = "value"' for each <jsp:param> in plugin body
*/
if (n.getBody() != null)
n.getBody().visit(new ParamVisitor(false));
out.printil("out.write(" + quote("/>") + ");");
out.printil("out.write(\"\\n\");");
out.printil("out.write(" + quote("<noembed>") + ");");
out.printil("out.write(\"\\n\");");
/*
* Fallback
*/
if (n.getBody() != null) {
visitBody(n);
out.printil("out.write(\"\\n\");");
}
out.printil("out.write(" + quote("</noembed>") + ");");
out.printil("out.write(\"\\n\");");
out.printil("out.write(" + quote("</comment>") + ");");
out.printil("out.write(\"\\n\");");
out.printil("out.write(" + quote("</object>") + ");");
out.printil("out.write(\"\\n\");");
n.setEndJavaLine(out.getJavaLine());
}
@Override
public void visit(Node.NamedAttribute n) throws JasperException {
// Don't visit body of this tag - we already did earlier.
}
@Override
public void visit(Node.CustomTag n) throws JasperException {
// Use plugin to generate more efficient code if there is one.
if (n.useTagPlugin()) {
generateTagPlugin(n);
return;
}
TagHandlerInfo handlerInfo = getTagHandlerInfo(n);
// Create variable names
String baseVar = createTagVarName(n.getQName(), n.getPrefix(), n
.getLocalName());
String tagEvalVar = "_jspx_eval_" + baseVar;
String tagHandlerVar = "_jspx_th_" + baseVar;
String tagPushBodyCountVar = "_jspx_push_body_count_" + baseVar;
// If the tag contains no scripting element, generate its codes
// to a method.
ServletWriter outSave = null;
Node.ChildInfo ci = n.getChildInfo();
if (ci.isScriptless() && !ci.hasScriptingVars()) {
// The tag handler and its body code can reside in a separate
// method if it is scriptless and does not have any scripting
// variable defined.
String tagMethod = "_jspx_meth_" + baseVar;
// Generate a call to this method
out.printin("if (");
out.print(tagMethod);
out.print("(");
if (parent != null) {
out.print(parent);
out.print(", ");
}
out.print("_jspx_page_context");
if (pushBodyCountVar != null) {
out.print(", ");
out.print(pushBodyCountVar);
}
out.println("))");
out.pushIndent();
out.printil((methodNesting > 0) ? "return true;" : "return;");
out.popIndent();
// Set up new buffer for the method
outSave = out;
/*
* For fragments, their bodies will be generated in fragment
* helper classes, and the Java line adjustments will be done
* there, hence they are set to null here to avoid double
* adjustments.
*/
GenBuffer genBuffer = new GenBuffer(n,
n.implementsSimpleTag() ? null : n.getBody());
methodsBuffered.add(genBuffer);
out = genBuffer.getOut();
methodNesting++;
// Generate code for method declaration
out.println();
out.pushIndent();
out.printin("private boolean ");
out.print(tagMethod);
out.print("(");
if (parent != null) {
out.print("javax.servlet.jsp.tagext.JspTag ");
out.print(parent);
out.print(", ");
}
out.print("javax.servlet.jsp.PageContext _jspx_page_context");
if (pushBodyCountVar != null) {
out.print(", int[] ");
out.print(pushBodyCountVar);
}
out.println(")");
out.printil(" throws java.lang.Throwable {");
out.pushIndent();
// Initialize local variables used in this method.
if (!isTagFile) {
out.printil("javax.servlet.jsp.PageContext pageContext = _jspx_page_context;");
}
out.printil("javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut();");
generateLocalVariables(out, n);
}
// Add the named objects to the list of 'introduced' names to enable
// a later test as per JSP.5.3
VariableInfo[] infos = n.getVariableInfos();
if (infos != null && infos.length > 0) {
for (int i = 0; i < infos.length; i++) {
VariableInfo info = infos[i];
if (info != null && info.getVarName() != null)
pageInfo.getVarInfoNames().add(info.getVarName());
}
}
TagVariableInfo[] tagInfos = n.getTagVariableInfos();
if (tagInfos != null && tagInfos.length > 0) {
for (int i = 0; i < tagInfos.length; i++) {
TagVariableInfo tagInfo = tagInfos[i];
if (tagInfo != null) {
String name = tagInfo.getNameGiven();
if (name == null) {
String nameFromAttribute =
tagInfo.getNameFromAttribute();
name = n.getAttributeValue(nameFromAttribute);
}
pageInfo.getVarInfoNames().add(name);
}
}
}
if (n.implementsSimpleTag()) {
generateCustomDoTag(n, handlerInfo, tagHandlerVar);
} else {
/*
* Classic tag handler: Generate code for start element, body,
* and end element
*/
generateCustomStart(n, handlerInfo, tagHandlerVar, tagEvalVar,
tagPushBodyCountVar);
// visit body
String tmpParent = parent;
parent = tagHandlerVar;
boolean isSimpleTagParentSave = isSimpleTagParent;
isSimpleTagParent = false;
String tmpPushBodyCountVar = null;
if (n.implementsTryCatchFinally()) {
tmpPushBodyCountVar = pushBodyCountVar;
pushBodyCountVar = tagPushBodyCountVar;
}
boolean tmpIsSimpleTagHandler = isSimpleTagHandler;
isSimpleTagHandler = false;
visitBody(n);
parent = tmpParent;
isSimpleTagParent = isSimpleTagParentSave;
if (n.implementsTryCatchFinally()) {
pushBodyCountVar = tmpPushBodyCountVar;
}
isSimpleTagHandler = tmpIsSimpleTagHandler;
generateCustomEnd(n, tagHandlerVar, tagEvalVar,
tagPushBodyCountVar);
}
if (ci.isScriptless() && !ci.hasScriptingVars()) {
// Generate end of method
if (methodNesting > 0) {
out.printil("return false;");
}
out.popIndent();
out.printil("}");
out.popIndent();
methodNesting--;
// restore previous writer
out = outSave;
}
}
private static final String DOUBLE_QUOTE = "\\\"";
@Override
public void visit(Node.UninterpretedTag n) throws JasperException {
n.setBeginJavaLine(out.getJavaLine());
/*
* Write begin tag
*/
out.printin("out.write(\"<");
out.print(n.getQName());
Attributes attrs = n.getNonTaglibXmlnsAttributes();
if (attrs != null) {
for (int i = 0; i < attrs.getLength(); i++) {
out.print(" ");
out.print(attrs.getQName(i));
out.print("=");
out.print(DOUBLE_QUOTE);
out.print(escape(attrs.getValue(i).replace("\"", """)));
out.print(DOUBLE_QUOTE);
}
}
attrs = n.getAttributes();
if (attrs != null) {
Node.JspAttribute[] jspAttrs = n.getJspAttributes();
for (int i = 0; i < attrs.getLength(); i++) {
out.print(" ");
out.print(attrs.getQName(i));
out.print("=");
if (jspAttrs[i].isELInterpreterInput()) {
out.print("\\\"\" + ");
String debug = attributeValue(jspAttrs[i], false,
String.class, n.getRoot().isXmlSyntax());
out.print(debug);
out.print(" + \"\\\"");
} else {
out.print(DOUBLE_QUOTE);
out.print(escape(jspAttrs[i].getValue().replace("\"", """)));
out.print(DOUBLE_QUOTE);
}
}
}
if (n.getBody() != null) {
out.println(">\");");
// Visit tag body
visitBody(n);
/*
* Write end tag
*/
out.printin("out.write(\"</");
out.print(n.getQName());
out.println(">\");");
} else {
out.println("/>\");");
}
n.setEndJavaLine(out.getJavaLine());
}
@Override
public void visit(Node.JspElement n) throws JasperException {
n.setBeginJavaLine(out.getJavaLine());
// Compute attribute value string for XML-style and named
// attributes
Hashtable<String,String> map = new Hashtable<String,String>();
Node.JspAttribute[] attrs = n.getJspAttributes();
for (int i = 0; attrs != null && i < attrs.length; i++) {
String value = null;
String nvp = null;
if (attrs[i].isNamedAttribute()) {
NamedAttribute attr = attrs[i].getNamedAttributeNode();
Node.JspAttribute omitAttr = attr.getOmit();
String omit;
if (omitAttr == null) {
omit = "false";
} else {
omit = attributeValue(omitAttr, false, boolean.class,
n.getRoot().isXmlSyntax());
if ("true".equals(omit)) {
continue;
}
}
value = generateNamedAttributeValue(
attrs[i].getNamedAttributeNode());
if ("false".equals(omit)) {
nvp = " + \" " + attrs[i].getName() + "=\\\"\" + " +
value + " + \"\\\"\"";
} else {
nvp = " + (java.lang.Boolean.valueOf(" + omit + ")?\"\":\" " +
attrs[i].getName() + "=\\\"\" + " + value +
" + \"\\\"\")";
}
} else {
value = attributeValue(attrs[i], false, Object.class,
n.getRoot().isXmlSyntax());
nvp = " + \" " + attrs[i].getName() + "=\\\"\" + " +
value + " + \"\\\"\"";
}
map.put(attrs[i].getName(), nvp);
}
// Write begin tag, using XML-style 'name' attribute as the
// element name
String elemName = attributeValue(n.getNameAttribute(), false,
String.class, n.getRoot().isXmlSyntax());
out.printin("out.write(\"<\"");
out.print(" + " + elemName);
// Write remaining attributes
Enumeration<String> enumeration = map.keys();
while (enumeration.hasMoreElements()) {
String attrName = enumeration.nextElement();
out.print(map.get(attrName));
}
// Does the <jsp:element> have nested tags other than
// <jsp:attribute>
boolean hasBody = false;
Node.Nodes subelements = n.getBody();
if (subelements != null) {
for (int i = 0; i < subelements.size(); i++) {
Node subelem = subelements.getNode(i);
if (!(subelem instanceof Node.NamedAttribute)) {
hasBody = true;
break;
}
}
}
if (hasBody) {
out.println(" + \">\");");
// Smap should not include the body
n.setEndJavaLine(out.getJavaLine());
// Visit tag body
visitBody(n);
// Write end tag
out.printin("out.write(\"</\"");
out.print(" + " + elemName);
out.println(" + \">\");");
} else {
out.println(" + \"/>\");");
n.setEndJavaLine(out.getJavaLine());
}
}
@Override
public void visit(Node.TemplateText n) throws JasperException {
String text = n.getText();
int textSize = text.length();
if (textSize == 0) {
return;
}
if (textSize <= 3) {
// Special case small text strings
n.setBeginJavaLine(out.getJavaLine());
int lineInc = 0;
for (int i = 0; i < textSize; i++) {
char ch = text.charAt(i);
out.printil("out.write(" + quote(ch) + ");");
if (i > 0) {
n.addSmap(lineInc);
}
if (ch == '\n') {
lineInc++;
}
}
n.setEndJavaLine(out.getJavaLine());
return;
}
if (ctxt.getOptions().genStringAsCharArray()) {
// Generate Strings as char arrays, for performance
ServletWriter caOut;
if (charArrayBuffer == null) {
charArrayBuffer = new GenBuffer();
caOut = charArrayBuffer.getOut();
caOut.pushIndent();
textMap = new HashMap<String,String>();
} else {
caOut = charArrayBuffer.getOut();
}
// UTF-8 is up to 4 bytes per character
// String constants are limited to 64k bytes
// Limit string constants here to 16k characters
int textIndex = 0;
int textLength = text.length();
while (textIndex < textLength) {
int len = 0;
if (textLength - textIndex > 16384) {
len = 16384;
} else {
len = textLength - textIndex;
}
String output = text.substring(textIndex, textIndex + len);
String charArrayName = textMap.get(output);
if (charArrayName == null) {
charArrayName = "_jspx_char_array_" + charArrayCount++;
textMap.put(output, charArrayName);
caOut.printin("static char[] ");
caOut.print(charArrayName);
caOut.print(" = ");
caOut.print(quote(output));
caOut.println(".toCharArray();");
}
n.setBeginJavaLine(out.getJavaLine());
out.printil("out.write(" + charArrayName + ");");
n.setEndJavaLine(out.getJavaLine());
textIndex = textIndex + len;
}
return;
}
n.setBeginJavaLine(out.getJavaLine());
out.printin();
StringBuilder sb = new StringBuilder("out.write(\"");
int initLength = sb.length();
int count = JspUtil.CHUNKSIZE;
int srcLine = 0; // relative to starting source line
for (int i = 0; i < text.length(); i++) {
char ch = text.charAt(i);
--count;
switch (ch) {
case '"':
sb.append('\\').append('\"');
break;
case '\\':
sb.append('\\').append('\\');
break;
case '\r':
sb.append('\\').append('r');
break;
case '\n':
sb.append('\\').append('n');
srcLine++;
if (breakAtLF || count < 0) {
// Generate an out.write() when see a '\n' in template
sb.append("\");");
out.println(sb.toString());
if (i < text.length() - 1) {
out.printin();
}
sb.setLength(initLength);
count = JspUtil.CHUNKSIZE;
}
// add a Smap for this line
n.addSmap(srcLine);
break;
case '\t': // Not sure we need this
sb.append('\\').append('t');
break;
default:
sb.append(ch);
}
}
if (sb.length() > initLength) {
sb.append("\");");
out.println(sb.toString());
}
n.setEndJavaLine(out.getJavaLine());
}
@Override
public void visit(Node.JspBody n) throws JasperException {
if (n.getBody() != null) {
if (isSimpleTagHandler) {
out.printin(simpleTagHandlerVar);
out.print(".setJspBody(");
generateJspFragment(n, simpleTagHandlerVar);
out.println(");");
} else {
visitBody(n);
}
}
}
@Override
public void visit(Node.InvokeAction n) throws JasperException {
n.setBeginJavaLine(out.getJavaLine());
// Copy virtual page scope of tag file to page scope of invoking
// page
out.printil("((org.apache.jasper.runtime.JspContextWrapper) this.jspContext).syncBeforeInvoke();");
String varReaderAttr = n.getTextAttribute("varReader");
String varAttr = n.getTextAttribute("var");
if (varReaderAttr != null || varAttr != null) {
out.printil("_jspx_sout = new java.io.StringWriter();");
} else {
out.printil("_jspx_sout = null;");
}
// Invoke fragment, unless fragment is null
out.printin("if (");
out.print(toGetterMethod(n.getTextAttribute("fragment")));
out.println(" != null) {");
out.pushIndent();
out.printin(toGetterMethod(n.getTextAttribute("fragment")));
out.println(".invoke(_jspx_sout);");
out.popIndent();
out.printil("}");
// Store varReader in appropriate scope
if (varReaderAttr != null || varAttr != null) {
String scopeName = n.getTextAttribute("scope");
out.printin("_jspx_page_context.setAttribute(");
if (varReaderAttr != null) {
out.print(quote(varReaderAttr));
out.print(", new java.io.StringReader(_jspx_sout.toString())");
} else {
out.print(quote(varAttr));
out.print(", _jspx_sout.toString()");
}
if (scopeName != null) {
out.print(", ");
out.print(getScopeConstant(scopeName));
}
out.println(");");
}
n.setEndJavaLine(out.getJavaLine());
}
@Override
public void visit(Node.DoBodyAction n) throws JasperException {
n.setBeginJavaLine(out.getJavaLine());
// Copy virtual page scope of tag file to page scope of invoking
// page
out.printil("((org.apache.jasper.runtime.JspContextWrapper) this.jspContext).syncBeforeInvoke();");
// Invoke body
String varReaderAttr = n.getTextAttribute("varReader");
String varAttr = n.getTextAttribute("var");
if (varReaderAttr != null || varAttr != null) {
out.printil("_jspx_sout = new java.io.StringWriter();");
} else {
out.printil("_jspx_sout = null;");
}
out.printil("if (getJspBody() != null)");
out.pushIndent();
out.printil("getJspBody().invoke(_jspx_sout);");
out.popIndent();
// Store varReader in appropriate scope
if (varReaderAttr != null || varAttr != null) {
String scopeName = n.getTextAttribute("scope");
out.printin("_jspx_page_context.setAttribute(");
if (varReaderAttr != null) {
out.print(quote(varReaderAttr));
out.print(", new java.io.StringReader(_jspx_sout.toString())");
} else {
out.print(quote(varAttr));
out.print(", _jspx_sout.toString()");
}
if (scopeName != null) {
out.print(", ");
out.print(getScopeConstant(scopeName));
}
out.println(");");
}
// Restore EL context
out.printil("jspContext.getELContext().putContext(javax.servlet.jsp.JspContext.class,getJspContext());");
n.setEndJavaLine(out.getJavaLine());
}
@Override
public void visit(Node.AttributeGenerator n) throws JasperException {
Node.CustomTag tag = n.getTag();
Node.JspAttribute[] attrs = tag.getJspAttributes();
for (int i = 0; attrs != null && i < attrs.length; i++) {
if (attrs[i].getName().equals(n.getName())) {
out.print(evaluateAttribute(getTagHandlerInfo(tag),
attrs[i], tag, null));
break;
}
}
}
private TagHandlerInfo getTagHandlerInfo(Node.CustomTag n)
throws JasperException {
Hashtable<String,TagHandlerInfo> handlerInfosByShortName =
handlerInfos.get(n.getPrefix());
if (handlerInfosByShortName == null) {
handlerInfosByShortName =
new Hashtable<String,TagHandlerInfo>();
handlerInfos.put(n.getPrefix(), handlerInfosByShortName);
}
TagHandlerInfo handlerInfo =
handlerInfosByShortName.get(n.getLocalName());
if (handlerInfo == null) {
handlerInfo = new TagHandlerInfo(n, n.getTagHandlerClass(), err);
handlerInfosByShortName.put(n.getLocalName(), handlerInfo);
}
return handlerInfo;
}
private void generateTagPlugin(Node.CustomTag n) throws JasperException {
if (n.getAtSTag() != null) {
n.getAtSTag().visit(this);
}
visitBody(n);
if (n.getAtETag() != null) {
n.getAtETag().visit(this);
}
}
private void generateCustomStart(Node.CustomTag n,
TagHandlerInfo handlerInfo, String tagHandlerVar,
String tagEvalVar, String tagPushBodyCountVar)
throws JasperException {
Class<?> tagHandlerClass =
handlerInfo.getTagHandlerClass();
out.printin("// ");
out.println(n.getQName());
n.setBeginJavaLine(out.getJavaLine());
// Declare AT_BEGIN scripting variables
declareScriptingVars(n, VariableInfo.AT_BEGIN);
saveScriptingVars(n, VariableInfo.AT_BEGIN);
String tagHandlerClassName = tagHandlerClass.getCanonicalName();
if (isPoolingEnabled && !(n.implementsJspIdConsumer())) {
out.printin(tagHandlerClassName);
out.print(" ");
out.print(tagHandlerVar);
out.print(" = ");
out.print("(");
out.print(tagHandlerClassName);
out.print(") ");
out.print(n.getTagHandlerPoolName());
out.print(".get(");
out.print(tagHandlerClassName);
out.println(".class);");
} else {
writeNewInstance(tagHandlerVar, tagHandlerClassName);
}
// includes setting the context
generateSetters(n, tagHandlerVar, handlerInfo, false);
// JspIdConsumer (after context has been set)
if (n.implementsJspIdConsumer()) {
out.printin(tagHandlerVar);
out.print(".setJspId(\"");
out.print(createJspId());
out.println("\");");
}
if (n.implementsTryCatchFinally()) {
out.printin("int[] ");
out.print(tagPushBodyCountVar);
out.println(" = new int[] { 0 };");
out.printil("try {");
out.pushIndent();
}
out.printin("int ");
out.print(tagEvalVar);
out.print(" = ");
out.print(tagHandlerVar);
out.println(".doStartTag();");
if (!n.implementsBodyTag()) {
// Synchronize AT_BEGIN scripting variables
syncScriptingVars(n, VariableInfo.AT_BEGIN);
}
if (!n.hasEmptyBody()) {
out.printin("if (");
out.print(tagEvalVar);
out.println(" != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {");
out.pushIndent();
// Declare NESTED scripting variables
declareScriptingVars(n, VariableInfo.NESTED);
saveScriptingVars(n, VariableInfo.NESTED);
if (n.implementsBodyTag()) {
out.printin("if (");
out.print(tagEvalVar);
out.println(" != javax.servlet.jsp.tagext.Tag.EVAL_BODY_INCLUDE) {");
// Assume EVAL_BODY_BUFFERED
out.pushIndent();
out.printil("out = _jspx_page_context.pushBody();");
if (n.implementsTryCatchFinally()) {
out.printin(tagPushBodyCountVar);
out.println("[0]++;");
} else if (pushBodyCountVar != null) {
out.printin(pushBodyCountVar);
out.println("[0]++;");
}
out.printin(tagHandlerVar);
out.println(".setBodyContent((javax.servlet.jsp.tagext.BodyContent) out);");
out.printin(tagHandlerVar);
out.println(".doInitBody();");
out.popIndent();
out.printil("}");
// Synchronize AT_BEGIN and NESTED scripting variables
syncScriptingVars(n, VariableInfo.AT_BEGIN);
syncScriptingVars(n, VariableInfo.NESTED);
} else {
// Synchronize NESTED scripting variables
syncScriptingVars(n, VariableInfo.NESTED);
}
if (n.implementsIterationTag()) {
out.printil("do {");
out.pushIndent();
}
}
// Map the Java lines that handles start of custom tags to the
// JSP line for this tag
n.setEndJavaLine(out.getJavaLine());
}
private void writeNewInstance(String tagHandlerVar, String tagHandlerClassName) {
if (Constants.USE_INSTANCE_MANAGER_FOR_TAGS) {
out.printin(tagHandlerClassName);
out.print(" ");
out.print(tagHandlerVar);
out.print(" = (");
out.print(tagHandlerClassName);
out.print(")");
out.print(VAR_INSTANCEMANAGER);
out.print(".newInstance(\"");
out.print(tagHandlerClassName);
out.println("\", this.getClass().getClassLoader());");
} else {
out.printin(tagHandlerClassName);
out.print(" ");
out.print(tagHandlerVar);
out.print(" = (");
out.print("new ");
out.print(tagHandlerClassName);
out.println("());");
out.printin(VAR_INSTANCEMANAGER);
out.print(".newInstance(");
out.print(tagHandlerVar);
out.println(");");
}
}
private void writeDestroyInstance(String tagHandlerVar) {
out.printin(VAR_INSTANCEMANAGER);
out.print(".destroyInstance(");
out.print(tagHandlerVar);
out.println(");");
}
private void generateCustomEnd(Node.CustomTag n, String tagHandlerVar,
String tagEvalVar, String tagPushBodyCountVar) {
if (!n.hasEmptyBody()) {
if (n.implementsIterationTag()) {
out.printin("int evalDoAfterBody = ");
out.print(tagHandlerVar);
out.println(".doAfterBody();");
// Synchronize AT_BEGIN and NESTED scripting variables
syncScriptingVars(n, VariableInfo.AT_BEGIN);
syncScriptingVars(n, VariableInfo.NESTED);
out.printil("if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)");
out.pushIndent();
out.printil("break;");
out.popIndent();
out.popIndent();
out.printil("} while (true);");
}
restoreScriptingVars(n, VariableInfo.NESTED);
if (n.implementsBodyTag()) {
out.printin("if (");
out.print(tagEvalVar);
out.println(" != javax.servlet.jsp.tagext.Tag.EVAL_BODY_INCLUDE) {");
out.pushIndent();
out.printil("out = _jspx_page_context.popBody();");
if (n.implementsTryCatchFinally()) {
out.printin(tagPushBodyCountVar);
out.println("[0]--;");
} else if (pushBodyCountVar != null) {
out.printin(pushBodyCountVar);
out.println("[0]--;");
}
out.popIndent();
out.printil("}");
}
out.popIndent(); // EVAL_BODY
out.printil("}");
}
out.printin("if (");
out.print(tagHandlerVar);
out.println(".doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {");
out.pushIndent();
if (!n.implementsTryCatchFinally()) {
if (isPoolingEnabled && !(n.implementsJspIdConsumer())) {
out.printin(n.getTagHandlerPoolName());
out.print(".reuse(");
out.print(tagHandlerVar);
out.println(");");
} else {
out.printin(tagHandlerVar);
out.println(".release();");
writeDestroyInstance(tagHandlerVar);
}
}
if (isTagFile || isFragment) {
out.printil("throw new javax.servlet.jsp.SkipPageException();");
} else {
out.printil((methodNesting > 0) ? "return true;" : "return;");
}
out.popIndent();
out.printil("}");
// Synchronize AT_BEGIN scripting variables
syncScriptingVars(n, VariableInfo.AT_BEGIN);
// TryCatchFinally
if (n.implementsTryCatchFinally()) {
out.popIndent(); // try
out.printil("} catch (java.lang.Throwable _jspx_exception) {");
out.pushIndent();
out.printin("while (");
out.print(tagPushBodyCountVar);
out.println("[0]-- > 0)");
out.pushIndent();
out.printil("out = _jspx_page_context.popBody();");
out.popIndent();
out.printin(tagHandlerVar);
out.println(".doCatch(_jspx_exception);");
out.popIndent();
out.printil("} finally {");
out.pushIndent();
out.printin(tagHandlerVar);
out.println(".doFinally();");
}
if (isPoolingEnabled && !(n.implementsJspIdConsumer())) {
out.printin(n.getTagHandlerPoolName());
out.print(".reuse(");
out.print(tagHandlerVar);
out.println(");");
} else {
out.printin(tagHandlerVar);
out.println(".release();");
writeDestroyInstance(tagHandlerVar);
}
if (n.implementsTryCatchFinally()) {
out.popIndent();
out.printil("}");
}
// Declare and synchronize AT_END scripting variables (must do this
// outside the try/catch/finally block)
declareScriptingVars(n, VariableInfo.AT_END);
syncScriptingVars(n, VariableInfo.AT_END);
restoreScriptingVars(n, VariableInfo.AT_BEGIN);
}
private void generateCustomDoTag(Node.CustomTag n,
TagHandlerInfo handlerInfo, String tagHandlerVar)
throws JasperException {
Class<?> tagHandlerClass =
handlerInfo.getTagHandlerClass();
n.setBeginJavaLine(out.getJavaLine());
out.printin("// ");
out.println(n.getQName());
// Declare AT_BEGIN scripting variables
declareScriptingVars(n, VariableInfo.AT_BEGIN);
saveScriptingVars(n, VariableInfo.AT_BEGIN);
String tagHandlerClassName = tagHandlerClass.getCanonicalName();
writeNewInstance(tagHandlerVar, tagHandlerClassName);
generateSetters(n, tagHandlerVar, handlerInfo, true);
// JspIdConsumer (after context has been set)
if (n.implementsJspIdConsumer()) {
out.printin(tagHandlerVar);
out.print(".setJspId(\"");
out.print(createJspId());
out.println("\");");
}
// Set the body
if (findJspBody(n) == null) {
/*
* Encapsulate body of custom tag invocation in JspFragment and
* pass it to tag handler's setJspBody(), unless tag body is
* empty
*/
if (!n.hasEmptyBody()) {
out.printin(tagHandlerVar);
out.print(".setJspBody(");
generateJspFragment(n, tagHandlerVar);
out.println(");");
}
} else {
/*
* Body of tag is the body of the <jsp:body> element. The visit
* method for that element is going to encapsulate that
* element's body in a JspFragment and pass it to the tag
* handler's setJspBody()
*/
String tmpTagHandlerVar = simpleTagHandlerVar;
simpleTagHandlerVar = tagHandlerVar;
boolean tmpIsSimpleTagHandler = isSimpleTagHandler;
isSimpleTagHandler = true;
visitBody(n);
simpleTagHandlerVar = tmpTagHandlerVar;
isSimpleTagHandler = tmpIsSimpleTagHandler;
}
out.printin(tagHandlerVar);
out.println(".doTag();");
restoreScriptingVars(n, VariableInfo.AT_BEGIN);
// Synchronize AT_BEGIN scripting variables
syncScriptingVars(n, VariableInfo.AT_BEGIN);
// Declare and synchronize AT_END scripting variables
declareScriptingVars(n, VariableInfo.AT_END);
syncScriptingVars(n, VariableInfo.AT_END);
// Resource injection
writeDestroyInstance(tagHandlerVar);
n.setEndJavaLine(out.getJavaLine());
}
private void declareScriptingVars(Node.CustomTag n, int scope) {
if (isFragment) {
// No need to declare Java variables, if we inside a
// JspFragment, because a fragment is always scriptless.
return;
}
List<Object> vec = n.getScriptingVars(scope);
if (vec != null) {
for (int i = 0; i < vec.size(); i++) {
Object elem = vec.get(i);
if (elem instanceof VariableInfo) {
VariableInfo varInfo = (VariableInfo) elem;
if (varInfo.getDeclare()) {
out.printin(varInfo.getClassName());
out.print(" ");
out.print(varInfo.getVarName());
out.println(" = null;");
}
} else {
TagVariableInfo tagVarInfo = (TagVariableInfo) elem;
if (tagVarInfo.getDeclare()) {
String varName = tagVarInfo.getNameGiven();
if (varName == null) {
varName = n.getTagData().getAttributeString(
tagVarInfo.getNameFromAttribute());
} else if (tagVarInfo.getNameFromAttribute() != null) {
// alias
continue;
}
out.printin(tagVarInfo.getClassName());
out.print(" ");
out.print(varName);
out.println(" = null;");
}
}
}
}
}
/*
* This method is called as part of the custom tag's start element.
*
* If the given custom tag has a custom nesting level greater than 0,
* save the current values of its scripting variables to temporary
* variables, so those values may be restored in the tag's end element.
* This way, the scripting variables may be synchronized by the given
* tag without affecting their original values.
*/
private void saveScriptingVars(Node.CustomTag n, int scope) {
if (n.getCustomNestingLevel() == 0) {
return;
}
if (isFragment) {
// No need to declare Java variables, if we inside a
// JspFragment, because a fragment is always scriptless.
// Thus, there is no need to save/ restore/ sync them.
// Note, that JspContextWrapper.syncFoo() methods will take
// care of saving/ restoring/ sync'ing of JspContext attributes.
return;
}
TagVariableInfo[] tagVarInfos = n.getTagVariableInfos();
VariableInfo[] varInfos = n.getVariableInfos();
if ((varInfos.length == 0) && (tagVarInfos.length == 0)) {
return;
}
List<Object> declaredVariables = n.getScriptingVars(scope);
if (varInfos.length > 0) {
for (int i = 0; i < varInfos.length; i++) {
if (varInfos[i].getScope() != scope)
continue;
// If the scripting variable has been declared, skip codes
// for saving and restoring it.
if (declaredVariables.contains(varInfos[i]))
continue;
String varName = varInfos[i].getVarName();
String tmpVarName = "_jspx_" + varName + "_"
+ n.getCustomNestingLevel();
out.printin(tmpVarName);
out.print(" = ");
out.print(varName);
out.println(";");
}
} else {
for (int i = 0; i < tagVarInfos.length; i++) {
if (tagVarInfos[i].getScope() != scope)
continue;
// If the scripting variable has been declared, skip codes
// for saving and restoring it.
if (declaredVariables.contains(tagVarInfos[i]))
continue;
String varName = tagVarInfos[i].getNameGiven();
if (varName == null) {
varName = n.getTagData().getAttributeString(
tagVarInfos[i].getNameFromAttribute());
} else if (tagVarInfos[i].getNameFromAttribute() != null) {
// alias
continue;
}
String tmpVarName = "_jspx_" + varName + "_"
+ n.getCustomNestingLevel();
out.printin(tmpVarName);
out.print(" = ");
out.print(varName);
out.println(";");
}
}
}
/*
* This method is called as part of the custom tag's end element.
*
* If the given custom tag has a custom nesting level greater than 0,
* restore its scripting variables to their original values that were
* saved in the tag's start element.
*/
private void restoreScriptingVars(Node.CustomTag n, int scope) {
if (n.getCustomNestingLevel() == 0) {
return;
}
if (isFragment) {
// No need to declare Java variables, if we inside a
// JspFragment, because a fragment is always scriptless.
// Thus, there is no need to save/ restore/ sync them.
// Note, that JspContextWrapper.syncFoo() methods will take
// care of saving/ restoring/ sync'ing of JspContext attributes.
return;
}
TagVariableInfo[] tagVarInfos = n.getTagVariableInfos();
VariableInfo[] varInfos = n.getVariableInfos();
if ((varInfos.length == 0) && (tagVarInfos.length == 0)) {
return;
}
List<Object> declaredVariables = n.getScriptingVars(scope);
if (varInfos.length > 0) {
for (int i = 0; i < varInfos.length; i++) {
if (varInfos[i].getScope() != scope)
continue;
// If the scripting variable has been declared, skip codes
// for saving and restoring it.
if (declaredVariables.contains(varInfos[i]))
continue;
String varName = varInfos[i].getVarName();
String tmpVarName = "_jspx_" + varName + "_"
+ n.getCustomNestingLevel();
out.printin(varName);
out.print(" = ");
out.print(tmpVarName);
out.println(";");
}
} else {
for (int i = 0; i < tagVarInfos.length; i++) {
if (tagVarInfos[i].getScope() != scope)
continue;
// If the scripting variable has been declared, skip codes
// for saving and restoring it.
if (declaredVariables.contains(tagVarInfos[i]))
continue;
String varName = tagVarInfos[i].getNameGiven();
if (varName == null) {
varName = n.getTagData().getAttributeString(
tagVarInfos[i].getNameFromAttribute());
} else if (tagVarInfos[i].getNameFromAttribute() != null) {
// alias
continue;
}
String tmpVarName = "_jspx_" + varName + "_"
+ n.getCustomNestingLevel();
out.printin(varName);
out.print(" = ");
out.print(tmpVarName);
out.println(";");
}
}
}
/*
* Synchronizes the scripting variables of the given custom tag for the
* given scope.
*/
private void syncScriptingVars(Node.CustomTag n, int scope) {
if (isFragment) {
// No need to declare Java variables, if we inside a
// JspFragment, because a fragment is always scriptless.
// Thus, there is no need to save/ restore/ sync them.
// Note, that JspContextWrapper.syncFoo() methods will take
// care of saving/ restoring/ sync'ing of JspContext attributes.
return;
}
TagVariableInfo[] tagVarInfos = n.getTagVariableInfos();
VariableInfo[] varInfos = n.getVariableInfos();
if ((varInfos.length == 0) && (tagVarInfos.length == 0)) {
return;
}
if (varInfos.length > 0) {
for (int i = 0; i < varInfos.length; i++) {
if (varInfos[i].getScope() == scope) {
out.printin(varInfos[i].getVarName());
out.print(" = (");
out.print(varInfos[i].getClassName());
out.print(") _jspx_page_context.findAttribute(");
out.print(quote(varInfos[i].getVarName()));
out.println(");");
}
}
} else {
for (int i = 0; i < tagVarInfos.length; i++) {
if (tagVarInfos[i].getScope() == scope) {
String name = tagVarInfos[i].getNameGiven();
if (name == null) {
name = n.getTagData().getAttributeString(
tagVarInfos[i].getNameFromAttribute());
} else if (tagVarInfos[i].getNameFromAttribute() != null) {
// alias
continue;
}
out.printin(name);
out.print(" = (");
out.print(tagVarInfos[i].getClassName());
out.print(") _jspx_page_context.findAttribute(");
out.print(quote(name));
out.println(");");
}
}
}
}
private String getJspContextVar() {
if (this.isTagFile) {
return "this.getJspContext()";
}
return "_jspx_page_context";
}
private String getExpressionFactoryVar() {
return VAR_EXPRESSIONFACTORY;
}
/*
* Creates a tag variable name by concatenating the given prefix and
* shortName and encoded to make the resultant string a valid Java
* Identifier.
*/
private String createTagVarName(String fullName, String prefix,
String shortName) {
String varName;
synchronized (tagVarNumbers) {
varName = prefix + "_" + shortName + "_";
if (tagVarNumbers.get(fullName) != null) {
Integer i = tagVarNumbers.get(fullName);
varName = varName + i.intValue();
tagVarNumbers.put(fullName,
Integer.valueOf(i.intValue() + 1));
} else {
tagVarNumbers.put(fullName, Integer.valueOf(1));
varName = varName + "0";
}
}
return JspUtil.makeJavaIdentifier(varName);
}
@SuppressWarnings("null")
private String evaluateAttribute(TagHandlerInfo handlerInfo,
Node.JspAttribute attr, Node.CustomTag n, String tagHandlerVar)
throws JasperException {
String attrValue = attr.getValue();
if (attrValue == null) {
if (attr.isNamedAttribute()) {
if (n.checkIfAttributeIsJspFragment(attr.getName())) {
// XXX - no need to generate temporary variable here
attrValue = generateNamedAttributeJspFragment(attr
.getNamedAttributeNode(), tagHandlerVar);
} else {
attrValue = generateNamedAttributeValue(attr
.getNamedAttributeNode());
}
} else {
return null;
}
}
String localName = attr.getLocalName();
Method m = null;
Class<?>[] c = null;
if (attr.isDynamic()) {
c = OBJECT_CLASS;
} else {
m = handlerInfo.getSetterMethod(localName);
if (m == null) {
err.jspError(n, "jsp.error.unable.to_find_method", attr
.getName());
}
c = m.getParameterTypes();
// XXX assert(c.length > 0)
}
if (attr.isExpression()) {
// Do nothing
} else if (attr.isNamedAttribute()) {
if (!n.checkIfAttributeIsJspFragment(attr.getName())
&& !attr.isDynamic()) {
attrValue = convertString(c[0], attrValue, localName,
handlerInfo.getPropertyEditorClass(localName), true);
}
} else if (attr.isELInterpreterInput()) {
// results buffer
StringBuilder sb = new StringBuilder(64);
TagAttributeInfo tai = attr.getTagAttributeInfo();
// generate elContext reference
sb.append(getJspContextVar());
sb.append(".getELContext()");
String elContext = sb.toString();
if (attr.getEL() != null && attr.getEL().getMapName() != null) {
sb.setLength(0);
sb.append("new org.apache.jasper.el.ELContextWrapper(");
sb.append(elContext);
sb.append(',');
sb.append(attr.getEL().getMapName());
sb.append(')');
elContext = sb.toString();
}
// reset buffer
sb.setLength(0);
// create our mark
sb.append(n.getStart().toString());
sb.append(" '");
sb.append(attrValue);
sb.append('\'');
String mark = sb.toString();
// reset buffer
sb.setLength(0);
// depending on type
if (attr.isDeferredInput()
|| ((tai != null) && ValueExpression.class.getName().equals(tai.getTypeName()))) {
sb.append("new org.apache.jasper.el.JspValueExpression(");
sb.append(quote(mark));
sb.append(',');
sb.append(getExpressionFactoryVar());
sb.append(".createValueExpression(");
if (attr.getEL() != null) { // optimize
sb.append(elContext);
sb.append(',');
}
sb.append(quote(attrValue));
sb.append(',');
sb.append(JspUtil.toJavaSourceTypeFromTld(attr.getExpectedTypeName()));
sb.append("))");
// should the expression be evaluated before passing to
// the setter?
boolean evaluate = false;
if (tai != null && tai.canBeRequestTime()) {
evaluate = true; // JSP.2.3.2
}
if (attr.isDeferredInput()) {
evaluate = false; // JSP.2.3.3
}
if (attr.isDeferredInput() && tai != null &&
tai.canBeRequestTime()) {
evaluate = !attrValue.contains("#{"); // JSP.2.3.5
}
if (evaluate) {
sb.append(".getValue(");
sb.append(getJspContextVar());
sb.append(".getELContext()");
sb.append(")");
}
attrValue = sb.toString();
} else if (attr.isDeferredMethodInput()
|| ((tai != null) && MethodExpression.class.getName().equals(tai.getTypeName()))) {
sb.append("new org.apache.jasper.el.JspMethodExpression(");
sb.append(quote(mark));
sb.append(',');
sb.append(getExpressionFactoryVar());
sb.append(".createMethodExpression(");
sb.append(elContext);
sb.append(',');
sb.append(quote(attrValue));
sb.append(',');
sb.append(JspUtil.toJavaSourceTypeFromTld(attr.getExpectedTypeName()));
sb.append(',');
sb.append("new java.lang.Class[] {");
String[] p = attr.getParameterTypeNames();
for (int i = 0; i < p.length; i++) {
sb.append(JspUtil.toJavaSourceTypeFromTld(p[i]));
sb.append(',');
}
if (p.length > 0) {
sb.setLength(sb.length() - 1);
}
sb.append("}))");
attrValue = sb.toString();
} else {
// run attrValue through the expression interpreter
String mapName = (attr.getEL() != null) ? attr.getEL()
.getMapName() : null;
attrValue = elInterpreter.interpreterCall(ctxt,
this.isTagFile, attrValue, c[0], mapName, false);
}
} else {
attrValue = convertString(c[0], attrValue, localName,
handlerInfo.getPropertyEditorClass(localName), false);
}
return attrValue;
}
/**
* Generate code to create a map for the alias variables
*
* @return the name of the map
*/
private String generateAliasMap(Node.CustomTag n,
String tagHandlerVar) {
TagVariableInfo[] tagVars = n.getTagVariableInfos();
String aliasMapVar = null;
boolean aliasSeen = false;
for (int i = 0; i < tagVars.length; i++) {
String nameFrom = tagVars[i].getNameFromAttribute();
if (nameFrom != null) {
String aliasedName = n.getAttributeValue(nameFrom);
if (aliasedName == null)
continue;
if (!aliasSeen) {
out.printin("java.util.HashMap ");
aliasMapVar = tagHandlerVar + "_aliasMap";
out.print(aliasMapVar);
out.println(" = new java.util.HashMap();");
aliasSeen = true;
}
out.printin(aliasMapVar);
out.print(".put(");
out.print(quote(tagVars[i].getNameGiven()));
out.print(", ");
out.print(quote(aliasedName));
out.println(");");
}
}
return aliasMapVar;
}
private void generateSetters(Node.CustomTag n, String tagHandlerVar,
TagHandlerInfo handlerInfo, boolean simpleTag)
throws JasperException {
// Set context
if (simpleTag) {
// Generate alias map
String aliasMapVar = null;
if (n.isTagFile()) {
aliasMapVar = generateAliasMap(n, tagHandlerVar);
}
out.printin(tagHandlerVar);
if (aliasMapVar == null) {
out.println(".setJspContext(_jspx_page_context);");
} else {
out.print(".setJspContext(_jspx_page_context, ");
out.print(aliasMapVar);
out.println(");");
}
} else {
out.printin(tagHandlerVar);
out.println(".setPageContext(_jspx_page_context);");
}
// Set parent
if (isTagFile && parent == null) {
out.printin(tagHandlerVar);
out.print(".setParent(");
out.print("new javax.servlet.jsp.tagext.TagAdapter(");
out.print("(javax.servlet.jsp.tagext.SimpleTag) this ));");
} else if (!simpleTag) {
out.printin(tagHandlerVar);
out.print(".setParent(");
if (parent != null) {
if (isSimpleTagParent) {
out.print("new javax.servlet.jsp.tagext.TagAdapter(");
out.print("(javax.servlet.jsp.tagext.SimpleTag) ");
out.print(parent);
out.println("));");
} else {
out.print("(javax.servlet.jsp.tagext.Tag) ");
out.print(parent);
out.println(");");
}
} else {
out.println("null);");
}
} else {
// The setParent() method need not be called if the value being
// passed is null, since SimpleTag instances are not reused
if (parent != null) {
out.printin(tagHandlerVar);
out.print(".setParent(");
out.print(parent);
out.println(");");
}
}
// need to handle deferred values and methods
Node.JspAttribute[] attrs = n.getJspAttributes();
for (int i = 0; attrs != null && i < attrs.length; i++) {
String attrValue = evaluateAttribute(handlerInfo, attrs[i], n,
tagHandlerVar);
Mark m = n.getStart();
out.printil("// "+m.getFile()+"("+m.getLineNumber()+","+m.getColumnNumber()+") "+ attrs[i].getTagAttributeInfo());
if (attrs[i].isDynamic()) {
out.printin(tagHandlerVar);
out.print(".");
out.print("setDynamicAttribute(");
String uri = attrs[i].getURI();
if ("".equals(uri) || (uri == null)) {
out.print("null");
} else {
out.print("\"" + attrs[i].getURI() + "\"");
}
out.print(", \"");
out.print(attrs[i].getLocalName());
out.print("\", ");
out.print(attrValue);
out.println(");");
} else {
out.printin(tagHandlerVar);
out.print(".");
out.print(handlerInfo.getSetterMethod(
attrs[i].getLocalName()).getName());
out.print("(");
out.print(attrValue);
out.println(");");
}
}
}
/*
* @param c The target class to which to coerce the given string @param
* s The string value @param attrName The name of the attribute whose
* value is being supplied @param propEditorClass The property editor
* for the given attribute @param isNamedAttribute true if the given
* attribute is a named attribute (that is, specified using the
* jsp:attribute standard action), and false otherwise
*/
private String convertString(Class<?> c, String s, String attrName,
Class<?> propEditorClass, boolean isNamedAttribute) {
String quoted = s;
if (!isNamedAttribute) {
quoted = quote(s);
}
if (propEditorClass != null) {
String className = c.getCanonicalName();
return "("
+ className
+ ")org.apache.jasper.runtime.JspRuntimeLibrary.getValueFromBeanInfoPropertyEditor("
+ className + ".class, \"" + attrName + "\", " + quoted
+ ", " + propEditorClass.getCanonicalName() + ".class)";
} else if (c == String.class) {
return quoted;
} else if (c == boolean.class) {
return JspUtil.coerceToPrimitiveBoolean(s, isNamedAttribute);
} else if (c == Boolean.class) {
return JspUtil.coerceToBoolean(s, isNamedAttribute);
} else if (c == byte.class) {
return JspUtil.coerceToPrimitiveByte(s, isNamedAttribute);
} else if (c == Byte.class) {
return JspUtil.coerceToByte(s, isNamedAttribute);
} else if (c == char.class) {
return JspUtil.coerceToChar(s, isNamedAttribute);
} else if (c == Character.class) {
return JspUtil.coerceToCharacter(s, isNamedAttribute);
} else if (c == double.class) {
return JspUtil.coerceToPrimitiveDouble(s, isNamedAttribute);
} else if (c == Double.class) {
return JspUtil.coerceToDouble(s, isNamedAttribute);
} else if (c == float.class) {
return JspUtil.coerceToPrimitiveFloat(s, isNamedAttribute);
} else if (c == Float.class) {
return JspUtil.coerceToFloat(s, isNamedAttribute);
} else if (c == int.class) {
return JspUtil.coerceToInt(s, isNamedAttribute);
} else if (c == Integer.class) {
return JspUtil.coerceToInteger(s, isNamedAttribute);
} else if (c == short.class) {
return JspUtil.coerceToPrimitiveShort(s, isNamedAttribute);
} else if (c == Short.class) {
return JspUtil.coerceToShort(s, isNamedAttribute);
} else if (c == long.class) {
return JspUtil.coerceToPrimitiveLong(s, isNamedAttribute);
} else if (c == Long.class) {
return JspUtil.coerceToLong(s, isNamedAttribute);
} else if (c == Object.class) {
return quoted;
} else {
String className = c.getCanonicalName();
return "("
+ className
+ ")org.apache.jasper.runtime.JspRuntimeLibrary.getValueFromPropertyEditorManager("
+ className + ".class, \"" + attrName + "\", " + quoted
+ ")";
}
}
/*
* Converts the scope string representation, whose possible values are
* "page", "request", "session", and "application", to the corresponding
* scope constant.
*/
private String getScopeConstant(String scope) {
String scopeName = "javax.servlet.jsp.PageContext.PAGE_SCOPE"; // Default to page
if ("request".equals(scope)) {
scopeName = "javax.servlet.jsp.PageContext.REQUEST_SCOPE";
} else if ("session".equals(scope)) {
scopeName = "javax.servlet.jsp.PageContext.SESSION_SCOPE";
} else if ("application".equals(scope)) {
scopeName = "javax.servlet.jsp.PageContext.APPLICATION_SCOPE";
}
return scopeName;
}
/**
* Generates anonymous JspFragment inner class which is passed as an
* argument to SimpleTag.setJspBody().
*/
private void generateJspFragment(Node n, String tagHandlerVar)
throws JasperException {
// XXX - A possible optimization here would be to check to see
// if the only child of the parent node is TemplateText. If so,
// we know there won't be any parameters, etc, so we can
// generate a low-overhead JspFragment that just echoes its
// body. The implementation of this fragment can come from
// the org.apache.jasper.runtime package as a support class.
FragmentHelperClass.Fragment fragment = fragmentHelperClass
.openFragment(n, methodNesting);
ServletWriter outSave = out;
out = fragment.getGenBuffer().getOut();
String tmpParent = parent;
parent = "_jspx_parent";
boolean isSimpleTagParentSave = isSimpleTagParent;
isSimpleTagParent = true;
boolean tmpIsFragment = isFragment;
isFragment = true;
String pushBodyCountVarSave = pushBodyCountVar;
if (pushBodyCountVar != null) {
// Use a fixed name for push body count, to simplify code gen
pushBodyCountVar = "_jspx_push_body_count";
}
visitBody(n);
out = outSave;
parent = tmpParent;
isSimpleTagParent = isSimpleTagParentSave;
isFragment = tmpIsFragment;
pushBodyCountVar = pushBodyCountVarSave;
fragmentHelperClass.closeFragment(fragment, methodNesting);
// XXX - Need to change pageContext to jspContext if
// we're not in a place where pageContext is defined (e.g.
// in a fragment or in a tag file.
out.print("new " + fragmentHelperClass.getClassName() + "( "
+ fragment.getId() + ", _jspx_page_context, "
+ tagHandlerVar + ", " + pushBodyCountVar + ")");
}
/**
* Generate the code required to obtain the runtime value of the given
* named attribute.
*
* @return The name of the temporary variable the result is stored in.
*/
public String generateNamedAttributeValue(Node.NamedAttribute n)
throws JasperException {
String varName = n.getTemporaryVariableName();
// If the only body element for this named attribute node is
// template text, we need not generate an extra call to
// pushBody and popBody. Maybe we can further optimize
// here by getting rid of the temporary variable, but in
// reality it looks like javac does this for us.
Node.Nodes body = n.getBody();
if (body != null) {
boolean templateTextOptimization = false;
if (body.size() == 1) {
Node bodyElement = body.getNode(0);
if (bodyElement instanceof Node.TemplateText) {
templateTextOptimization = true;
out.printil("java.lang.String "
+ varName
+ " = "
+ quote(((Node.TemplateText) bodyElement)
.getText()) + ";");
}
}
// XXX - Another possible optimization would be for
// lone EL expressions (no need to pushBody here either).
if (!templateTextOptimization) {
out.printil("out = _jspx_page_context.pushBody();");
visitBody(n);
out.printil("java.lang.String " + varName + " = "
+ "((javax.servlet.jsp.tagext.BodyContent)"
+ "out).getString();");
out.printil("out = _jspx_page_context.popBody();");
}
} else {
// Empty body must be treated as ""
out.printil("java.lang.String " + varName + " = \"\";");
}
return varName;
}
/**
* Similar to generateNamedAttributeValue, but create a JspFragment
* instead.
*
* @param n
* The parent node of the named attribute
* @param tagHandlerVar
* The variable the tag handler is stored in, so the fragment
* knows its parent tag.
* @return The name of the temporary variable the fragment is stored in.
*/
public String generateNamedAttributeJspFragment(Node.NamedAttribute n,
String tagHandlerVar) throws JasperException {
String varName = n.getTemporaryVariableName();
out.printin("javax.servlet.jsp.tagext.JspFragment " + varName
+ " = ");
generateJspFragment(n, tagHandlerVar);
out.println(";");
return varName;
}
}
private static void generateLocalVariables(ServletWriter out, Node n)
throws JasperException {
Node.ChildInfo ci;
if (n instanceof Node.CustomTag) {
ci = ((Node.CustomTag) n).getChildInfo();
} else if (n instanceof Node.JspBody) {
ci = ((Node.JspBody) n).getChildInfo();
} else if (n instanceof Node.NamedAttribute) {
ci = ((Node.NamedAttribute) n).getChildInfo();
} else {
// Cannot access err since this method is static, but at
// least flag an error.
throw new JasperException("Unexpected Node Type");
// err.getString(
// "jsp.error.internal.unexpected_node_type" ) );
}
if (ci.hasUseBean()) {
out.printil("javax.servlet.http.HttpSession session = _jspx_page_context.getSession();");
out.printil("javax.servlet.ServletContext application = _jspx_page_context.getServletContext();");
}
if (ci.hasUseBean() || ci.hasIncludeAction() || ci.hasSetProperty()
|| ci.hasParamAction()) {
out.printil("javax.servlet.http.HttpServletRequest request = (javax.servlet.http.HttpServletRequest)_jspx_page_context.getRequest();");
}
if (ci.hasIncludeAction()) {
out.printil("javax.servlet.http.HttpServletResponse response = (javax.servlet.http.HttpServletResponse)_jspx_page_context.getResponse();");
}
}
/**
* Common part of postamble, shared by both servlets and tag files.
*/
private void genCommonPostamble() {
// Append any methods that were generated in the buffer.
for (int i = 0; i < methodsBuffered.size(); i++) {
GenBuffer methodBuffer = methodsBuffered.get(i);
methodBuffer.adjustJavaLines(out.getJavaLine() - 1);
out.printMultiLn(methodBuffer.toString());
}
// Append the helper class
if (fragmentHelperClass.isUsed()) {
fragmentHelperClass.generatePostamble();
fragmentHelperClass.adjustJavaLines(out.getJavaLine() - 1);
out.printMultiLn(fragmentHelperClass.toString());
}
// Append char array declarations
if (charArrayBuffer != null) {
out.printMultiLn(charArrayBuffer.toString());
}
// Close the class definition
out.popIndent();
out.printil("}");
}
/**
* Generates the ending part of the static portion of the servlet.
*/
private void generatePostamble() {
out.popIndent();
out.printil("} catch (java.lang.Throwable t) {");
out.pushIndent();
out.printil("if (!(t instanceof javax.servlet.jsp.SkipPageException)){");
out.pushIndent();
out.printil("out = _jspx_out;");
out.printil("if (out != null && out.getBufferSize() != 0)");
out.pushIndent();
out.printil("try {");
out.pushIndent();
out.printil("if (response.isCommitted()) {");
out.pushIndent();
out.printil("out.flush();");
out.popIndent();
out.printil("} else {");
out.pushIndent();
out.printil("out.clearBuffer();");
out.popIndent();
out.printil("}");
out.popIndent();
out.printil("} catch (java.io.IOException e) {}");
out.popIndent();
out.printil("if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);");
out.printil("else throw new ServletException(t);");
out.popIndent();
out.printil("}");
out.popIndent();
out.printil("} finally {");
out.pushIndent();
out.printil("_jspxFactory.releasePageContext(_jspx_page_context);");
out.popIndent();
out.printil("}");
// Close the service method
out.popIndent();
out.printil("}");
// Generated methods, helper classes, etc.
genCommonPostamble();
}
/**
* Constructor.
*/
Generator(ServletWriter out, Compiler compiler) throws JasperException {
this.out = out;
methodsBuffered = new ArrayList<GenBuffer>();
charArrayBuffer = null;
err = compiler.getErrorDispatcher();
ctxt = compiler.getCompilationContext();
fragmentHelperClass = new FragmentHelperClass("Helper");
pageInfo = compiler.getPageInfo();
ELInterpreter elInterpreter = null;
try {
elInterpreter = ELInterpreterFactory.getELInterpreter(
compiler.getCompilationContext().getServletContext());
} catch (Exception e) {
err.jspError("jsp.error.el_interpreter_class.instantiation",
e.getMessage());
}
this.elInterpreter = elInterpreter;
/*
* Temporary hack. If a JSP page uses the "extends" attribute of the
* page directive, the _jspInit() method of the generated servlet class
* will not be called (it is only called for those generated servlets
* that extend HttpJspBase, the default), causing the tag handler pools
* not to be initialized and resulting in a NPE. The JSP spec needs to
* clarify whether containers can override init() and destroy(). For
* now, we just disable tag pooling for pages that use "extends".
*/
if (pageInfo.getExtends(false) == null || POOL_TAGS_WITH_EXTENDS) {
isPoolingEnabled = ctxt.getOptions().isPoolingEnabled();
} else {
isPoolingEnabled = false;
}
beanInfo = pageInfo.getBeanRepository();
varInfoNames = pageInfo.getVarInfoNames();
breakAtLF = ctxt.getOptions().getMappedFile();
if (isPoolingEnabled) {
tagHandlerPoolNames = new Vector<String>();
} else {
tagHandlerPoolNames = null;
}
timestampFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
timestampFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
}
/**
* The main entry for Generator.
*
* @param out
* The servlet output writer
* @param compiler
* The compiler
* @param page
* The input page
*/
public static void generate(ServletWriter out, Compiler compiler,
Node.Nodes page) throws JasperException {
Generator gen = new Generator(out, compiler);
if (gen.isPoolingEnabled) {
gen.compileTagHandlerPoolList(page);
}
gen.generateCommentHeader();
if (gen.ctxt.isTagFile()) {
JasperTagInfo tagInfo = (JasperTagInfo) gen.ctxt.getTagInfo();
gen.generateTagHandlerPreamble(tagInfo, page);
if (gen.ctxt.isPrototypeMode()) {
return;
}
gen.generateXmlProlog(page);
gen.fragmentHelperClass.generatePreamble();
page.visit(gen.new GenerateVisitor(gen.ctxt.isTagFile(), out,
gen.methodsBuffered, gen.fragmentHelperClass));
gen.generateTagHandlerPostamble(tagInfo);
} else {
gen.generatePreamble(page);
gen.generateXmlProlog(page);
gen.fragmentHelperClass.generatePreamble();
page.visit(gen.new GenerateVisitor(gen.ctxt.isTagFile(), out,
gen.methodsBuffered, gen.fragmentHelperClass));
gen.generatePostamble();
}
}
private void generateCommentHeader() {
out.println("/*");
out.println(" * Generated by the Jasper component of Apache Tomcat");
out.println(" * Version: " + ctxt.getServletContext().getServerInfo());
out.println(" * Generated at: " + timestampFormat.format(new Date()) +
" UTC");
out.println(" * Note: The last modified time of this file was set to");
out.println(" * the last modified time of the source file after");
out.println(" * generation to assist with modification tracking.");
out.println(" */");
}
/*
* Generates tag handler preamble.
*/
private void generateTagHandlerPreamble(JasperTagInfo tagInfo,
Node.Nodes tag) throws JasperException {
// Generate package declaration
String className = tagInfo.getTagClassName();
int lastIndex = className.lastIndexOf('.');
if (lastIndex != -1) {
String pkgName = className.substring(0, lastIndex);
genPreamblePackage(pkgName);
className = className.substring(lastIndex + 1);
}
// Generate imports
genPreambleImports();
// Generate class declaration
out.printin("public final class ");
out.println(className);
out.printil(" extends javax.servlet.jsp.tagext.SimpleTagSupport");
out.printin(" implements org.apache.jasper.runtime.JspSourceDependent");
if (tagInfo.hasDynamicAttributes()) {
out.println(",");
out.printin(" javax.servlet.jsp.tagext.DynamicAttributes");
}
out.println(" {");
out.println();
out.pushIndent();
/*
* Class body begins here
*/
generateDeclarations(tag);
// Static initializations here
genPreambleStaticInitializers();
out.printil("private javax.servlet.jsp.JspContext jspContext;");
// Declare writer used for storing result of fragment/body invocation
// if 'varReader' or 'var' attribute is specified
out.printil("private java.io.Writer _jspx_sout;");
// Class variable declarations
genPreambleClassVariableDeclarations();
generateSetJspContext(tagInfo);
// Tag-handler specific declarations
generateTagHandlerAttributes(tagInfo);
if (tagInfo.hasDynamicAttributes())
generateSetDynamicAttribute();
// Methods here
genPreambleMethods();
// Now the doTag() method
out.printil("public void doTag() throws javax.servlet.jsp.JspException, java.io.IOException {");
if (ctxt.isPrototypeMode()) {
out.printil("}");
out.popIndent();
out.printil("}");
return;
}
out.pushIndent();
/*
* According to the spec, 'pageContext' must not be made available as an
* implicit object in tag files. Declare _jspx_page_context, so we can
* share the code generator with JSPs.
*/
out.printil("javax.servlet.jsp.PageContext _jspx_page_context = (javax.servlet.jsp.PageContext)jspContext;");
// Declare implicit objects.
out.printil("javax.servlet.http.HttpServletRequest request = "
+ "(javax.servlet.http.HttpServletRequest) _jspx_page_context.getRequest();");
out.printil("javax.servlet.http.HttpServletResponse response = "
+ "(javax.servlet.http.HttpServletResponse) _jspx_page_context.getResponse();");
out.printil("javax.servlet.http.HttpSession session = _jspx_page_context.getSession();");
out.printil("javax.servlet.ServletContext application = _jspx_page_context.getServletContext();");
out.printil("javax.servlet.ServletConfig config = _jspx_page_context.getServletConfig();");
out.printil("javax.servlet.jsp.JspWriter out = jspContext.getOut();");
out.printil("_jspInit(config);");
// set current JspContext on ELContext
out.printil("jspContext.getELContext().putContext(javax.servlet.jsp.JspContext.class,jspContext);");
generatePageScopedVariables(tagInfo);
declareTemporaryScriptingVars(tag);
out.println();
out.printil("try {");
out.pushIndent();
}
private void generateTagHandlerPostamble(TagInfo tagInfo) {
out.popIndent();
// Have to catch Throwable because a classic tag handler
// helper method is declared to throw Throwable.
out.printil("} catch( java.lang.Throwable t ) {");
out.pushIndent();
out.printil("if( t instanceof javax.servlet.jsp.SkipPageException )");
out.printil(" throw (javax.servlet.jsp.SkipPageException) t;");
out.printil("if( t instanceof java.io.IOException )");
out.printil(" throw (java.io.IOException) t;");
out.printil("if( t instanceof java.lang.IllegalStateException )");
out.printil(" throw (java.lang.IllegalStateException) t;");
out.printil("if( t instanceof javax.servlet.jsp.JspException )");
out.printil(" throw (javax.servlet.jsp.JspException) t;");
out.printil("throw new javax.servlet.jsp.JspException(t);");
out.popIndent();
out.printil("} finally {");
out.pushIndent();
// handle restoring VariableMapper
TagAttributeInfo[] attrInfos = tagInfo.getAttributes();
for (int i = 0; i < attrInfos.length; i++) {
if (attrInfos[i].isDeferredMethod() || attrInfos[i].isDeferredValue()) {
out.printin("_el_variablemapper.setVariable(");
out.print(quote(attrInfos[i].getName()));
out.print(",_el_ve");
out.print(i);
out.println(");");
}
}
// restore nested JspContext on ELContext
out.printil("jspContext.getELContext().putContext(javax.servlet.jsp.JspContext.class,super.getJspContext());");
out.printil("((org.apache.jasper.runtime.JspContextWrapper) jspContext).syncEndTagFile();");
if (isPoolingEnabled && !tagHandlerPoolNames.isEmpty()) {
out.printil("_jspDestroy();");
}
out.popIndent();
out.printil("}");
// Close the doTag method
out.popIndent();
out.printil("}");
// Generated methods, helper classes, etc.
genCommonPostamble();
}
/**
* Generates declarations for tag handler attributes, and defines the getter
* and setter methods for each.
*/
private void generateTagHandlerAttributes(TagInfo tagInfo) {
if (tagInfo.hasDynamicAttributes()) {
out.printil("private java.util.HashMap _jspx_dynamic_attrs = new java.util.HashMap();");
}
// Declare attributes
TagAttributeInfo[] attrInfos = tagInfo.getAttributes();
for (int i = 0; i < attrInfos.length; i++) {
out.printin("private ");
if (attrInfos[i].isFragment()) {
out.print("javax.servlet.jsp.tagext.JspFragment ");
} else {
out.print(JspUtil.toJavaSourceType(attrInfos[i].getTypeName()));
out.print(" ");
}
out.print(JspUtil.makeJavaIdentifierForAttribute(
attrInfos[i].getName()));
out.println(";");
}
out.println();
// Define attribute getter and setter methods
for (int i = 0; i < attrInfos.length; i++) {
String javaName =
JspUtil.makeJavaIdentifierForAttribute(attrInfos[i].getName());
// getter method
out.printin("public ");
if (attrInfos[i].isFragment()) {
out.print("javax.servlet.jsp.tagext.JspFragment ");
} else {
out.print(JspUtil.toJavaSourceType(attrInfos[i].getTypeName()));
out.print(" ");
}
out.print(toGetterMethod(attrInfos[i].getName()));
out.println(" {");
out.pushIndent();
out.printin("return this.");
out.print(javaName);
out.println(";");
out.popIndent();
out.printil("}");
out.println();
// setter method
out.printin("public void ");
out.print(toSetterMethodName(attrInfos[i].getName()));
if (attrInfos[i].isFragment()) {
out.print("(javax.servlet.jsp.tagext.JspFragment ");
} else {
out.print("(");
out.print(JspUtil.toJavaSourceType(attrInfos[i].getTypeName()));
out.print(" ");
}
out.print(javaName);
out.println(") {");
out.pushIndent();
out.printin("this.");
out.print(javaName);
out.print(" = ");
out.print(javaName);
out.println(";");
if (ctxt.isTagFile()) {
// Tag files should also set jspContext attributes
out.printin("jspContext.setAttribute(\"");
out.print(attrInfos[i].getName());
out.print("\", ");
out.print(javaName);
out.println(");");
}
out.popIndent();
out.printil("}");
out.println();
}
}
/*
* Generate setter for JspContext so we can create a wrapper and store both
* the original and the wrapper. We need the wrapper to mask the page
* context from the tag file and simulate a fresh page context. We need the
* original to do things like sync AT_BEGIN and AT_END scripting variables.
*/
private void generateSetJspContext(TagInfo tagInfo) {
boolean nestedSeen = false;
boolean atBeginSeen = false;
boolean atEndSeen = false;
// Determine if there are any aliases
boolean aliasSeen = false;
TagVariableInfo[] tagVars = tagInfo.getTagVariableInfos();
for (int i = 0; i < tagVars.length; i++) {
if (tagVars[i].getNameFromAttribute() != null
&& tagVars[i].getNameGiven() != null) {
aliasSeen = true;
break;
}
}
if (aliasSeen) {
out.printil("public void setJspContext(javax.servlet.jsp.JspContext ctx, java.util.Map aliasMap) {");
} else {
out.printil("public void setJspContext(javax.servlet.jsp.JspContext ctx) {");
}
out.pushIndent();
out.printil("super.setJspContext(ctx);");
out.printil("java.util.ArrayList _jspx_nested = null;");
out.printil("java.util.ArrayList _jspx_at_begin = null;");
out.printil("java.util.ArrayList _jspx_at_end = null;");
for (int i = 0; i < tagVars.length; i++) {
switch (tagVars[i].getScope()) {
case VariableInfo.NESTED:
if (!nestedSeen) {
out.printil("_jspx_nested = new java.util.ArrayList();");
nestedSeen = true;
}
out.printin("_jspx_nested.add(");
break;
case VariableInfo.AT_BEGIN:
if (!atBeginSeen) {
out.printil("_jspx_at_begin = new java.util.ArrayList();");
atBeginSeen = true;
}
out.printin("_jspx_at_begin.add(");
break;
case VariableInfo.AT_END:
if (!atEndSeen) {
out.printil("_jspx_at_end = new java.util.ArrayList();");
atEndSeen = true;
}
out.printin("_jspx_at_end.add(");
break;
} // switch
out.print(quote(tagVars[i].getNameGiven()));
out.println(");");
}
if (aliasSeen) {
out.printil("this.jspContext = new org.apache.jasper.runtime.JspContextWrapper(ctx, _jspx_nested, _jspx_at_begin, _jspx_at_end, aliasMap);");
} else {
out.printil("this.jspContext = new org.apache.jasper.runtime.JspContextWrapper(ctx, _jspx_nested, _jspx_at_begin, _jspx_at_end, null);");
}
out.popIndent();
out.printil("}");
out.println();
out.printil("public javax.servlet.jsp.JspContext getJspContext() {");
out.pushIndent();
out.printil("return this.jspContext;");
out.popIndent();
out.printil("}");
}
/*
* Generates implementation of
* javax.servlet.jsp.tagext.DynamicAttributes.setDynamicAttribute() method,
* which saves each dynamic attribute that is passed in so that a scoped
* variable can later be created for it.
*/
public void generateSetDynamicAttribute() {
out.printil("public void setDynamicAttribute(java.lang.String uri, java.lang.String localName, java.lang.Object value) throws javax.servlet.jsp.JspException {");
out.pushIndent();
/*
* According to the spec, only dynamic attributes with no uri are to be
* present in the Map; all other dynamic attributes are ignored.
*/
out.printil("if (uri == null)");
out.pushIndent();
out.printil("_jspx_dynamic_attrs.put(localName, value);");
out.popIndent();
out.popIndent();
out.printil("}");
}
/*
* Creates a page-scoped variable for each declared tag attribute. Also, if
* the tag accepts dynamic attributes, a page-scoped variable is made
* available for each dynamic attribute that was passed in.
*/
private void generatePageScopedVariables(JasperTagInfo tagInfo) {
// "normal" attributes
TagAttributeInfo[] attrInfos = tagInfo.getAttributes();
boolean variableMapperVar = false;
for (int i = 0; i < attrInfos.length; i++) {
String attrName = attrInfos[i].getName();
// handle assigning deferred vars to VariableMapper, storing
// previous values under '_el_ve[i]' for later re-assignment
if (attrInfos[i].isDeferredValue() || attrInfos[i].isDeferredMethod()) {
// we need to scope the modified VariableMapper for consistency and performance
if (!variableMapperVar) {
out.printil("javax.el.VariableMapper _el_variablemapper = jspContext.getELContext().getVariableMapper();");
variableMapperVar = true;
}
out.printin("javax.el.ValueExpression _el_ve");
out.print(i);
out.print(" = _el_variablemapper.setVariable(");
out.print(quote(attrName));
out.print(',');
if (attrInfos[i].isDeferredMethod()) {
out.print(VAR_EXPRESSIONFACTORY);
out.print(".createValueExpression(");
out.print(toGetterMethod(attrName));
out.print(",javax.el.MethodExpression.class)");
} else {
out.print(toGetterMethod(attrName));
}
out.println(");");
} else {
out.printil("if( " + toGetterMethod(attrName) + " != null ) ");
out.pushIndent();
out.printin("_jspx_page_context.setAttribute(");
out.print(quote(attrName));
out.print(", ");
out.print(toGetterMethod(attrName));
out.println(");");
out.popIndent();
}
}
// Expose the Map containing dynamic attributes as a page-scoped var
if (tagInfo.hasDynamicAttributes()) {
out.printin("_jspx_page_context.setAttribute(\"");
out.print(tagInfo.getDynamicAttributesMapName());
out.print("\", _jspx_dynamic_attrs);");
}
}
/*
* Generates the getter method for the given attribute name.
*/
private String toGetterMethod(String attrName) {
char[] attrChars = attrName.toCharArray();
attrChars[0] = Character.toUpperCase(attrChars[0]);
return "get" + new String(attrChars) + "()";
}
/*
* Generates the setter method name for the given attribute name.
*/
private String toSetterMethodName(String attrName) {
char[] attrChars = attrName.toCharArray();
attrChars[0] = Character.toUpperCase(attrChars[0]);
return "set" + new String(attrChars);
}
/**
* Class storing the result of introspecting a custom tag handler.
*/
private static class TagHandlerInfo {
private Hashtable<String, Method> methodMaps;
private Hashtable<String, Class<?>> propertyEditorMaps;
private Class<?> tagHandlerClass;
/**
* Constructor.
*
* @param n
* The custom tag whose tag handler class is to be
* introspected
* @param tagHandlerClass
* Tag handler class
* @param err
* Error dispatcher
*/
TagHandlerInfo(Node n, Class<?> tagHandlerClass,
ErrorDispatcher err) throws JasperException {
this.tagHandlerClass = tagHandlerClass;
this.methodMaps = new Hashtable<String, Method>();
this.propertyEditorMaps = new Hashtable<String, Class<?>>();
try {
BeanInfo tagClassInfo = Introspector
.getBeanInfo(tagHandlerClass);
PropertyDescriptor[] pd = tagClassInfo.getPropertyDescriptors();
for (int i = 0; i < pd.length; i++) {
/*
* FIXME: should probably be checking for things like
* pageContext, bodyContent, and parent here -akv
*/
if (pd[i].getWriteMethod() != null) {
methodMaps.put(pd[i].getName(), pd[i].getWriteMethod());
}
if (pd[i].getPropertyEditorClass() != null)
propertyEditorMaps.put(pd[i].getName(), pd[i]
.getPropertyEditorClass());
}
} catch (IntrospectionException ie) {
err.jspError(n, ie, "jsp.error.introspect.taghandler",
tagHandlerClass.getName());
}
}
/**
* XXX
*/
public Method getSetterMethod(String attrName) {
return methodMaps.get(attrName);
}
/**
* XXX
*/
public Class<?> getPropertyEditorClass(String attrName) {
return propertyEditorMaps.get(attrName);
}
/**
* XXX
*/
public Class<?> getTagHandlerClass() {
return tagHandlerClass;
}
}
/**
* A class for generating codes to a buffer. Included here are some support
* for tracking source to Java lines mapping.
*/
private static class GenBuffer {
/*
* For a CustomTag, the codes that are generated at the beginning of the
* tag may not be in the same buffer as those for the body of the tag.
* Two fields are used here to keep this straight. For codes that do not
* corresponds to any JSP lines, they should be null.
*/
private Node node;
private Node.Nodes body;
private java.io.CharArrayWriter charWriter;
protected ServletWriter out;
GenBuffer() {
this(null, null);
}
GenBuffer(Node n, Node.Nodes b) {
node = n;
body = b;
if (body != null) {
body.setGeneratedInBuffer(true);
}
charWriter = new java.io.CharArrayWriter();
out = new ServletWriter(new java.io.PrintWriter(charWriter));
}
public ServletWriter getOut() {
return out;
}
@Override
public String toString() {
return charWriter.toString();
}
/**
* Adjust the Java Lines. This is necessary because the Java lines
* stored with the nodes are relative the beginning of this buffer and
* need to be adjusted when this buffer is inserted into the source.
*/
public void adjustJavaLines(final int offset) {
if (node != null) {
adjustJavaLine(node, offset);
}
if (body != null) {
try {
body.visit(new Node.Visitor() {
@Override
public void doVisit(Node n) {
adjustJavaLine(n, offset);
}
@Override
public void visit(Node.CustomTag n)
throws JasperException {
Node.Nodes b = n.getBody();
if (b != null && !b.isGeneratedInBuffer()) {
// Don't adjust lines for the nested tags that
// are also generated in buffers, because the
// adjustments will be done elsewhere.
b.visit(this);
}
}
});
} catch (JasperException ex) {
// Ignore
}
}
}
private static void adjustJavaLine(Node n, int offset) {
if (n.getBeginJavaLine() > 0) {
n.setBeginJavaLine(n.getBeginJavaLine() + offset);
n.setEndJavaLine(n.getEndJavaLine() + offset);
}
}
}
/**
* Keeps track of the generated Fragment Helper Class
*/
private static class FragmentHelperClass {
private static class Fragment {
private GenBuffer genBuffer;
private int id;
public Fragment(int id, Node node) {
this.id = id;
genBuffer = new GenBuffer(null, node.getBody());
}
public GenBuffer getGenBuffer() {
return this.genBuffer;
}
public int getId() {
return this.id;
}
}
// True if the helper class should be generated.
private boolean used = false;
private ArrayList<Fragment> fragments = new ArrayList<Fragment>();
private String className;
// Buffer for entire helper class
private GenBuffer classBuffer = new GenBuffer();
public FragmentHelperClass(String className) {
this.className = className;
}
public String getClassName() {
return this.className;
}
public boolean isUsed() {
return this.used;
}
public void generatePreamble() {
ServletWriter out = this.classBuffer.getOut();
out.println();
out.pushIndent();
// Note: cannot be static, as we need to reference things like
// _jspx_meth_*
out.printil("private class " + className);
out.printil(" extends "
+ "org.apache.jasper.runtime.JspFragmentHelper");
out.printil("{");
out.pushIndent();
out.printil("private javax.servlet.jsp.tagext.JspTag _jspx_parent;");
out.printil("private int[] _jspx_push_body_count;");
out.println();
out.printil("public " + className
+ "( int discriminator, javax.servlet.jsp.JspContext jspContext, "
+ "javax.servlet.jsp.tagext.JspTag _jspx_parent, "
+ "int[] _jspx_push_body_count ) {");
out.pushIndent();
out.printil("super( discriminator, jspContext, _jspx_parent );");
out.printil("this._jspx_parent = _jspx_parent;");
out.printil("this._jspx_push_body_count = _jspx_push_body_count;");
out.popIndent();
out.printil("}");
}
public Fragment openFragment(Node parent, int methodNesting)
throws JasperException {
Fragment result = new Fragment(fragments.size(), parent);
fragments.add(result);
this.used = true;
parent.setInnerClassName(className);
ServletWriter out = result.getGenBuffer().getOut();
out.pushIndent();
out.pushIndent();
// XXX - Returns boolean because if a tag is invoked from
// within this fragment, the Generator sometimes might
// generate code like "return true". This is ignored for now,
// meaning only the fragment is skipped. The JSR-152
// expert group is currently discussing what to do in this case.
// See comment in closeFragment()
if (methodNesting > 0) {
out.printin("public boolean invoke");
} else {
out.printin("public void invoke");
}
out.println(result.getId() + "( " + "javax.servlet.jsp.JspWriter out ) ");
out.pushIndent();
// Note: Throwable required because methods like _jspx_meth_*
// throw Throwable.
out.printil("throws java.lang.Throwable");
out.popIndent();
out.printil("{");
out.pushIndent();
generateLocalVariables(out, parent);
return result;
}
public void closeFragment(Fragment fragment, int methodNesting) {
ServletWriter out = fragment.getGenBuffer().getOut();
// XXX - See comment in openFragment()
if (methodNesting > 0) {
out.printil("return false;");
} else {
out.printil("return;");
}
out.popIndent();
out.printil("}");
}
public void generatePostamble() {
ServletWriter out = this.classBuffer.getOut();
// Generate all fragment methods:
for (int i = 0; i < fragments.size(); i++) {
Fragment fragment = fragments.get(i);
fragment.getGenBuffer().adjustJavaLines(out.getJavaLine() - 1);
out.printMultiLn(fragment.getGenBuffer().toString());
}
// Generate postamble:
out.printil("public void invoke( java.io.Writer writer )");
out.pushIndent();
out.printil("throws javax.servlet.jsp.JspException");
out.popIndent();
out.printil("{");
out.pushIndent();
out.printil("javax.servlet.jsp.JspWriter out = null;");
out.printil("if( writer != null ) {");
out.pushIndent();
out.printil("out = this.jspContext.pushBody(writer);");
out.popIndent();
out.printil("} else {");
out.pushIndent();
out.printil("out = this.jspContext.getOut();");
out.popIndent();
out.printil("}");
out.printil("try {");
out.pushIndent();
out.printil("Object _jspx_saved_JspContext = this.jspContext.getELContext().getContext(javax.servlet.jsp.JspContext.class);");
out.printil("this.jspContext.getELContext().putContext(javax.servlet.jsp.JspContext.class,this.jspContext);");
out.printil("switch( this.discriminator ) {");
out.pushIndent();
for (int i = 0; i < fragments.size(); i++) {
out.printil("case " + i + ":");
out.pushIndent();
out.printil("invoke" + i + "( out );");
out.printil("break;");
out.popIndent();
}
out.popIndent();
out.printil("}"); // switch
// restore nested JspContext on ELContext
out.printil("jspContext.getELContext().putContext(javax.servlet.jsp.JspContext.class,_jspx_saved_JspContext);");
out.popIndent();
out.printil("}"); // try
out.printil("catch( java.lang.Throwable e ) {");
out.pushIndent();
out.printil("if (e instanceof javax.servlet.jsp.SkipPageException)");
out.printil(" throw (javax.servlet.jsp.SkipPageException) e;");
out.printil("throw new javax.servlet.jsp.JspException( e );");
out.popIndent();
out.printil("}"); // catch
out.printil("finally {");
out.pushIndent();
out.printil("if( writer != null ) {");
out.pushIndent();
out.printil("this.jspContext.popBody();");
out.popIndent();
out.printil("}");
out.popIndent();
out.printil("}"); // finally
out.popIndent();
out.printil("}"); // invoke method
out.popIndent();
out.printil("}"); // helper class
out.popIndent();
}
@Override
public String toString() {
return classBuffer.toString();
}
public void adjustJavaLines(int offset) {
for (int i = 0; i < fragments.size(); i++) {
Fragment fragment = fragments.get(i);
fragment.getGenBuffer().adjustJavaLines(offset);
}
}
}
}
|