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 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336
|
/*******************************************************************************
* Copyright (c) 1998, 2015 Oracle and/or its affiliates, IBM Corporation. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
* 10/15/2010-2.2 Guy Pelletier
* - 322008: Improve usability of additional criteria applied to queries at the session/EM
* 06/30/2011-2.3.1 Guy Pelletier
* - 341940: Add disable/enable allowing native queries
* 09/09/2011-2.3.1 Guy Pelletier
* - 356197: Add new VPD type to MultitenantType
* 09/14/2011-2.3.1 Guy Pelletier
* - 357533: Allow DDL queries to execute even when Multitenant entities are part of the PU
* 05/14/2012-2.4 Guy Pelletier
* - 376603: Provide for table per tenant support for multitenant applications
* 08/11/2012-2.5 Guy Pelletier
* - 393867: Named queries do not work when using EM level Table Per Tenant Multitenancy.
* 11/29/2012-2.5 Guy Pelletier
* - 395406: Fix nightly static weave test errors
* 08/11/2014-2.5 Rick Curtis
* - 440594: Tolerate invalid NamedQuery at EntityManager creation.
* 09/03/2015 - Will Dazey
* - 456067 : Added support for defining query timeout units
******************************************************************************/
package org.eclipse.persistence.internal.sessions;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.reflect.Constructor;
import java.security.AccessController;
import java.security.PrivilegedActionException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
import java.util.concurrent.TimeUnit;
import org.eclipse.persistence.config.PersistenceUnitProperties;
import org.eclipse.persistence.config.ReferenceMode;
import org.eclipse.persistence.descriptors.ClassDescriptor;
import org.eclipse.persistence.descriptors.DescriptorEvent;
import org.eclipse.persistence.descriptors.DescriptorQueryManager;
import org.eclipse.persistence.descriptors.TablePerMultitenantPolicy;
import org.eclipse.persistence.descriptors.invalidation.CacheInvalidationPolicy;
import org.eclipse.persistence.descriptors.partitioning.PartitioningPolicy;
import org.eclipse.persistence.exceptions.ConcurrencyException;
import org.eclipse.persistence.exceptions.DatabaseException;
import org.eclipse.persistence.exceptions.EclipseLinkException;
import org.eclipse.persistence.exceptions.ExceptionHandler;
import org.eclipse.persistence.exceptions.IntegrityChecker;
import org.eclipse.persistence.exceptions.IntegrityException;
import org.eclipse.persistence.exceptions.OptimisticLockException;
import org.eclipse.persistence.exceptions.QueryException;
import org.eclipse.persistence.exceptions.ValidationException;
import org.eclipse.persistence.expressions.Expression;
import org.eclipse.persistence.history.AsOfClause;
import org.eclipse.persistence.indirection.ValueHolderInterface;
import org.eclipse.persistence.internal.core.sessions.CoreAbstractSession;
import org.eclipse.persistence.internal.databaseaccess.Accessor;
import org.eclipse.persistence.internal.databaseaccess.Platform;
import org.eclipse.persistence.internal.descriptors.ObjectBuilder;
import org.eclipse.persistence.internal.helper.ConcurrencyManager;
import org.eclipse.persistence.internal.helper.Helper;
import org.eclipse.persistence.internal.helper.QueryCounter;
import org.eclipse.persistence.internal.helper.linkedlist.ExposedNodeLinkedList;
import org.eclipse.persistence.internal.history.HistoricalSession;
import org.eclipse.persistence.internal.identitymaps.CacheKey;
import org.eclipse.persistence.internal.identitymaps.IdentityMapManager;
import org.eclipse.persistence.internal.indirection.DatabaseValueHolder;
import org.eclipse.persistence.internal.indirection.ProtectedValueHolder;
import org.eclipse.persistence.internal.indirection.ProxyIndirectionPolicy;
import org.eclipse.persistence.internal.localization.ExceptionLocalization;
import org.eclipse.persistence.internal.queries.JoinedAttributeManager;
import org.eclipse.persistence.internal.security.PrivilegedAccessHelper;
import org.eclipse.persistence.internal.security.PrivilegedClassForName;
import org.eclipse.persistence.internal.security.PrivilegedGetConstructorFor;
import org.eclipse.persistence.internal.security.PrivilegedInvokeConstructor;
import org.eclipse.persistence.internal.security.PrivilegedNewInstanceFromClass;
import org.eclipse.persistence.internal.sequencing.Sequencing;
import org.eclipse.persistence.internal.sessions.cdi.DisabledEntityListenerInjectionManager;
import org.eclipse.persistence.internal.sessions.cdi.EntityListenerInjectionManager;
import org.eclipse.persistence.logging.DefaultSessionLog;
import org.eclipse.persistence.logging.SessionLog;
import org.eclipse.persistence.logging.SessionLogEntry;
import org.eclipse.persistence.mappings.ForeignReferenceMapping;
import org.eclipse.persistence.mappings.foundation.AbstractTransformationMapping;
import org.eclipse.persistence.platform.database.DatabasePlatform;
import org.eclipse.persistence.platform.server.ServerPlatform;
import org.eclipse.persistence.queries.AttributeGroup;
import org.eclipse.persistence.queries.Call;
import org.eclipse.persistence.queries.DataModifyQuery;
import org.eclipse.persistence.queries.DataReadQuery;
import org.eclipse.persistence.queries.DatabaseQuery;
import org.eclipse.persistence.queries.DeleteObjectQuery;
import org.eclipse.persistence.queries.DoesExistQuery;
import org.eclipse.persistence.queries.InsertObjectQuery;
import org.eclipse.persistence.queries.JPAQueryBuilder;
import org.eclipse.persistence.queries.JPQLCall;
import org.eclipse.persistence.queries.ObjectBuildingQuery;
import org.eclipse.persistence.queries.ObjectLevelReadQuery;
import org.eclipse.persistence.queries.ReadAllQuery;
import org.eclipse.persistence.queries.ReadObjectQuery;
import org.eclipse.persistence.queries.SQLCall;
import org.eclipse.persistence.queries.UpdateObjectQuery;
import org.eclipse.persistence.queries.WriteObjectQuery;
import org.eclipse.persistence.sessions.CopyGroup;
import org.eclipse.persistence.sessions.DatabaseLogin;
import org.eclipse.persistence.sessions.ExternalTransactionController;
import org.eclipse.persistence.sessions.Login;
import org.eclipse.persistence.sessions.ObjectCopyingPolicy;
import org.eclipse.persistence.sessions.Project;
import org.eclipse.persistence.sessions.SessionEventManager;
import org.eclipse.persistence.sessions.SessionProfiler;
import org.eclipse.persistence.sessions.coordination.Command;
import org.eclipse.persistence.sessions.coordination.CommandManager;
import org.eclipse.persistence.sessions.coordination.CommandProcessor;
import org.eclipse.persistence.sessions.coordination.MetadataRefreshListener;
import org.eclipse.persistence.sessions.serializers.Serializer;
/**
* Implementation of org.eclipse.persistence.sessions.Session
* The public interface should be used.
* @see org.eclipse.persistence.sessions.Session
*
* <p>
* <b>Purpose</b>: Define the interface and common protocol of an EclipseLink compliant session.
* <p>
* <b>Description</b>: The session is the primary interface into EclipseLink,
* the application should do all of its reading and writing of objects through the session.
* The session also manages transactions and units of work. Normally the session
* is passed and used by the application controller objects. Controller objects normally
* sit behind the GUI and perform the business processes required for the application,
* they should perform all explicit database access and database access should be avoided from
* the domain object model. Do not use a globally accessible session instance, doing so does
* not allow for multiple sessions. Multiple sessions may required when performing things like
* data migration or multiple database access, as well the unit of work feature requires the usage
* of multiple session instances. Although session is abstract, any users of its subclasses
* should only cast the variables to Session to allow usage of any of its subclasses.
* <p>
* <b>Responsibilities</b>:
* <ul>
* <li> Connecting/disconnecting.
* <li> Reading and writing objects.
* <li> Transaction and unit of work support.
* <li> Identity maps and caching.
* </ul>
* @see DatabaseSessionImpl
*/
public abstract class AbstractSession extends CoreAbstractSession<ClassDescriptor, Login, Platform, Project, SessionEventManager> implements org.eclipse.persistence.sessions.Session, CommandProcessor, java.io.Serializable, java.lang.Cloneable {
/** ExceptionHandler handles database exceptions. */
transient protected ExceptionHandler exceptionHandler;
/** IntegrityChecker catch all the descriptor Exceptions. */
transient protected IntegrityChecker integrityChecker;
/** The project stores configuration information, such as the descriptors and login. */
transient protected Project project;
/** Ensure mutual exclusion of the session's transaction state across multiple threads.*/
transient protected ConcurrencyManager transactionMutex;
/** Manages the live object cache.*/
protected IdentityMapAccessor identityMapAccessor;
/** If Transactions were externally started */
protected boolean wasJTSTransactionInternallyStarted;
/** The connection to the data store. */
transient protected Collection<Accessor> accessors;
/** Allow the datasource platform to be cached. */
transient protected Platform platform;
/** Stores predefine reusable queries.*/
transient protected Map<String, List<DatabaseQuery>> queries;
/**
* Stores predefined reusable AttributeGroups.
*/
protected Map<String, AttributeGroup> attributeGroups;
/** Stores predefined not yet parsed JPQL queries.*/
protected boolean jpaQueriesProcessed = false;
/** Resolves referential integrity on commits. */
transient protected CommitManager commitManager;
/** Tool that log performance information. */
transient protected SessionProfiler profiler;
/** Support being owned by a session broker. */
transient protected AbstractSession broker;
/** Used to identify a session when using the session broker. */
protected String name;
/** Keep track of active units of work. */
transient protected int numberOfActiveUnitsOfWork;
/**
* This collection will be used to store those objects that are currently locked
* for the clone process. It should be populated with an EclipseLinkIdentityHashMap
*/
protected Map objectsLockedForClone;
/** Destination for logged messages and SQL. */
transient protected SessionLog sessionLog;
/** When logging the name of the session is typed: class name + system hashcode. */
transient protected String logSessionString;
/** Stores the event listeners for this session. */
transient protected SessionEventManager eventManager;
/** Allow for user defined properties. */
protected Map<Object, Object> properties;
/** Delegate that handles synchronizing a UnitOfWork with an external transaction. */
transient protected ExternalTransactionController externalTransactionController;
/** Last descriptor accessed, use to optimize descriptor lookup. */
transient protected ClassDescriptor lastDescriptorAccessed;
/** PERF: cache descriptors from project. */
transient protected Map<Class, ClassDescriptor> descriptors;
/** PERF: cache table per tenant descriptors needing to be initialized per EM */
transient protected List<ClassDescriptor> tablePerTenantDescriptors;
/** PERF: cache table per tenant queries needing to be initialized per EM */
transient protected List<DatabaseQuery> tablePerTenantQueries;
// bug 3078039: move EJBQL alias > descriptor map from Session to Project (MWN)
/** Used to determine If a session is in a Broker or not */
protected boolean isInBroker;
/**
* Used to connect this session to EclipseLink cluster for distributed command
*/
transient protected CommandManager commandManager;
/**
* PERF: Cache the write-lock check to avoid cost of checking in every register/clone.
*/
protected boolean shouldCheckWriteLock;
/**
* Determined whether changes should be propagated to an EclipseLink cluster
*/
protected boolean shouldPropagateChanges;
/** Used to determine If a session is in a profile or not */
protected boolean isInProfile;
/** PERF: Quick check if logging is OFF entirely. */
protected boolean isLoggingOff;
/** PERF: Allow for finalizers to be enabled, currently enables client-session finalize. */
protected boolean isFinalizersEnabled;
/** List of active command threads. */
transient protected ExposedNodeLinkedList activeCommandThreads;
/**
* Indicates whether the session is synchronized.
* In case external transaction controller is used isSynchronized==true means
* the session's jta connection will be freed during external transaction callback.
*/
protected boolean isSynchronized;
/**
* Stores the default reference mode that a UnitOfWork will use when referencing
* managed objects.
* @see org.eclipse.persistence.config.ReferenceMode
*/
protected ReferenceMode defaultReferenceMode;
/**
* Default pessimistic lock timeout value.
*/
protected Integer pessimisticLockTimeoutDefault;
protected int queryTimeoutDefault;
protected TimeUnit queryTimeoutUnitDefault;
/** Allow a session to enable concurrent processing. */
protected boolean isConcurrent;
/**
* This map will hold onto class to static metamodel class references from JPA.
*/
protected Map<String, String> staticMetamodelClasses;
/** temporarily holds a list of events that must be fired after the current operation completes.
* Initialy created for postClone events.
*/
protected List<DescriptorEvent> deferredEvents;
/** records that the UOW is executing deferred events. Events could cause operations to occur that may attempt to restart the event execution. This must be avoided*/
protected boolean isExecutingEvents;
/** Allow queries to be targeted at specific connection pools. */
protected PartitioningPolicy partitioningPolicy;
/** the MetadataRefreshListener is used with RCM to force a refresh of the metadata used within EntityManagerFactoryWrappers */
protected MetadataRefreshListener metadatalistener;
/** Stores the set of multitenant context properties this session requires **/
protected Set<String> multitenantContextProperties;
/** Store the query builder used to parse JPQL. */
transient protected JPAQueryBuilder queryBuilder;
/** Set the Serializer to use by default for serialization. */
transient protected Serializer serializer;
/** Allow CDI injection of entity listeners **/
transient protected EntityListenerInjectionManager entityListenerInjectionManager;
/**
* Indicates whether ObjectLevelReadQuery should by default use ResultSet Access optimization.
* Optimization specified by the session is ignored if incompatible with other query settings.
*/
protected boolean shouldOptimizeResultSetAccess;
/**
* Indicates whether Session creation should tolerate an invalid NamedQuery. If true, an exception
* will be thrown on .createNamedQuery(..) rather than at init time.
*/
protected boolean tolerateInvalidJPQL = false;
/**
* INTERNAL:
* Create and return a new session.
* This should only be called if the database login information is not know at the time of creation.
* Normally it is better to call the constructor that takes the login information as an argument
* so that the session can initialize itself to the platform information given in the login.
*/
protected AbstractSession() {
this.name = "";
this.queryTimeoutUnitDefault = DescriptorQueryManager.DefaultTimeoutUnit;
initializeIdentityMapAccessor();
// PERF - move to lazy init (3286091)
}
/**
* INTERNAL:
* Create a blank session, used for proxy session.
*/
protected AbstractSession(int nothing) {
}
/**
* PUBLIC:
* Create and return a new session.
* By giving the login information on creation this allows the session to initialize itself
* to the platform given in the login. This constructor does not return a connected session.
* To connect the session to the database login() must be sent to it. The login(userName, password)
* method may also be used to connect the session, this allows for the user name and password
* to be given at login but for the other database information to be provided when the session is created.
*/
public AbstractSession(Login login) {
this(new org.eclipse.persistence.sessions.Project(login));
}
/**
* PUBLIC:
* Create and return a new session.
* This constructor does not return a connected session.
* To connect the session to the database login() must be sent to it. The login(userName, password)
* method may also be used to connect the session, this allows for the user name and password
* to be given at login but for the other database information to be provided when the session is created.
*/
public AbstractSession(org.eclipse.persistence.sessions.Project project) {
this();
this.project = project;
if (project.getDatasourceLogin() == null) {
throw ValidationException.projectLoginIsNull(this);
}
// add the Project's queries as session queries
for (DatabaseQuery query : project.getQueries()) {
addQuery(query.getName(), query);
}
}
/**
* Return the Serializer to use by default for serialization.
*/
public Serializer getSerializer() {
return serializer;
}
/**
* Set the Serializer to use by default for serialization.
*/
public void setSerializer(Serializer serializer) {
this.serializer = serializer;
}
/**
* INTERNAL
* Return the query builder used to parser JPQL.
*/
public JPAQueryBuilder getQueryBuilder() {
if (this.queryBuilder == null) {
AbstractSession parent = getParent();
if (parent != null) {
this.queryBuilder = parent.getQueryBuilder();
} else {
this.queryBuilder = buildDefaultQueryBuilder();
}
}
return this.queryBuilder;
}
/**
* INTERNAL
* Set the query builder used to parser JPQL.
*/
public void setQueryBuilder(JPAQueryBuilder queryBuilder) {
this.queryBuilder = queryBuilder;
}
/**
* INTERNAL
* Build the JPQL builder based on session properties.
*/
protected JPAQueryBuilder buildDefaultQueryBuilder() {
String queryBuilderClassName = (String)getProperty(PersistenceUnitProperties.JPQL_PARSER);
if (queryBuilderClassName == null) {
queryBuilderClassName = "org.eclipse.persistence.internal.jpa.jpql.HermesParser";
//queryBuilderClassName = "org.eclipse.persistence.queries.ANTLRQueryBuilder";
}
String validation = (String)getProperty(PersistenceUnitProperties.JPQL_VALIDATION);
JPAQueryBuilder builder = null;
try {
Class parserClass = null;
// use class.forName() to avoid loading parser classes for JAXB
// Use Class.forName not thread class loader to avoid class loader issues.
if (PrivilegedAccessHelper.shouldUsePrivilegedAccess()){
try {
parserClass = AccessController.doPrivileged(new PrivilegedClassForName(queryBuilderClassName));
} catch (PrivilegedActionException exception) {
}
} else {
parserClass = PrivilegedAccessHelper.getClassForName(queryBuilderClassName);
}
if (PrivilegedAccessHelper.shouldUsePrivilegedAccess()) {
try {
builder = (JPAQueryBuilder)AccessController.doPrivileged(new PrivilegedNewInstanceFromClass(parserClass));
} catch (PrivilegedActionException exception) {
}
} else {
builder = (JPAQueryBuilder)PrivilegedAccessHelper.newInstanceFromClass(parserClass);
}
} catch (Exception e) {
throw new IllegalStateException("Could not load the JPQL parser class." /* TODO: Localize string */, e);
}
if (validation != null) {
builder.setValidationLevel(validation);
}
return builder;
}
/**
* INTERNAL:
* PERF: Used for quick turning logging ON/OFF entirely.
* @param loggingOff Logging is turned off when <code>true</code>
* and turned on when <code>false</code>.
*/
public void setLoggingOff(final boolean loggingOff) {
isLoggingOff = loggingOff;
}
/**
* INTERNAL:
* PERF: Used for quick check if logging is OFF entirely.
*/
public boolean isLoggingOff() {
return isLoggingOff;
}
/**
* INTERNAL:
* Called by a sessions queries to obtain individual query ids.
* CR #2698903
*/
public long getNextQueryId() {
return QueryCounter.getCount();
}
/**
* INTERNAL:
* Return a unit of work for this session not registered with the JTS transaction.
*/
public UnitOfWorkImpl acquireNonSynchronizedUnitOfWork() {
return acquireNonSynchronizedUnitOfWork(null);
}
/**
* INTERNAL:
* Return a unit of work for this session not registered with the JTS transaction.
*/
public UnitOfWorkImpl acquireNonSynchronizedUnitOfWork(ReferenceMode referenceMode) {
setNumberOfActiveUnitsOfWork(getNumberOfActiveUnitsOfWork() + 1);
UnitOfWorkImpl unitOfWork = new UnitOfWorkImpl(this, referenceMode);
if (shouldLog(SessionLog.FINER, SessionLog.TRANSACTION)) {
log(SessionLog.FINER, SessionLog.TRANSACTION, "acquire_unit_of_work_with_argument", String.valueOf(System.identityHashCode(unitOfWork)));
}
return unitOfWork;
}
/**
* INTERNAL:
* Constructs a HistoricalSession given a valid AsOfClause.
*/
public org.eclipse.persistence.sessions.Session acquireHistoricalSession(AsOfClause clause) throws ValidationException {
if ((clause == null) || (clause.getValue() == null)) {
throw ValidationException.cannotAcquireHistoricalSession();
}
if (!getProject().hasGenericHistorySupport() && !hasBroker() && ((getPlatform() == null) || !getPlatform().isOracle())) {
throw ValidationException.historicalSessionOnlySupportedOnOracle();
}
return new HistoricalSession(this, clause);
}
/**
* PUBLIC:
* Return a unit of work for this session.
* The unit of work is an object level transaction that allows
* a group of changes to be applied as a unit.
*
* @see UnitOfWorkImpl
*/
public UnitOfWorkImpl acquireUnitOfWork() {
UnitOfWorkImpl unitOfWork = acquireNonSynchronizedUnitOfWork(getDefaultReferenceMode());
unitOfWork.registerWithTransactionIfRequired();
return unitOfWork;
}
/**
* PUBLIC:
* Return a repeatable write unit of work for this session.
* A repeatable write unit of work allows multiple writeChanges (flushes).
*
* @see RepeatableWriteUnitOfWork
*/
public RepeatableWriteUnitOfWork acquireRepeatableWriteUnitOfWork(ReferenceMode referenceMode) {
return new RepeatableWriteUnitOfWork(this, referenceMode);
}
/**
* PUBLIC:
* Return a unit of work for this session.
* The unit of work is an object level transaction that allows
* a group of changes to be applied as a unit.
*
* @see UnitOfWorkImpl
* @param referenceMode The reference type the UOW should use internally when
* referencing Working clones. Setting this to WEAK means the UOW will use
* weak references to reference clones that support active object change
* tracking and hard references for deferred change tracked objects.
* Setting to FORCE_WEAK means that all objects will be referenced by weak
* references and if the application no longer references the clone the
* clone may be garbage collected. If the clone
* has uncommitted changes then those changes will be lost.
*/
public UnitOfWorkImpl acquireUnitOfWork(ReferenceMode referenceMode) {
UnitOfWorkImpl unitOfWork = acquireNonSynchronizedUnitOfWork(referenceMode);
unitOfWork.registerWithTransactionIfRequired();
return unitOfWork;
}
/**
* PUBLIC:
* Add an alias for the descriptor
*/
public void addAlias(String alias, ClassDescriptor descriptor) {
project.addAlias(alias, descriptor);
}
/**
* INTERNAL:
* Return all pre-defined not yet parsed EJBQL queries.
*/
public void addJPAQuery(DatabaseQuery query) {
getProject().addJPAQuery(query);
}
/**
* INTERNAL:
* Return all pre-defined not yet parsed EJBQL multitenant queries.
*/
public void addJPATablePerTenantQuery(DatabaseQuery query) {
getProject().addJPATablePerTenantQuery(query);
}
/**
* PUBLIC:
* Return a set of multitenant context properties this session
*/
public void addMultitenantContextProperty(String contextProperty) {
getMultitenantContextProperties().add(contextProperty);
}
/**
* INTERNAL:
* Add the query to the session queries.
*/
protected synchronized void addQuery(DatabaseQuery query, boolean nameMustBeUnique) {
Vector queriesByName = (Vector)getQueries().get(query.getName());
if (queriesByName == null) {
// lazily create Vector in Hashtable.
queriesByName = org.eclipse.persistence.internal.helper.NonSynchronizedVector.newInstance();
getQueries().put(query.getName(), queriesByName);
}
if (nameMustBeUnique){ // JPA addNamedQuery
if (queriesByName.size() <= 1){
queriesByName.clear();
}else{
throw new IllegalStateException(ExceptionLocalization.buildMessage("argument_keyed_named_query_with_JPA", new Object[]{query.getName()}));
}
}else{
// Check that we do not already have a query that matched it
for (Iterator enumtr = queriesByName.iterator(); enumtr.hasNext();) {
DatabaseQuery existingQuery = (DatabaseQuery)enumtr.next();
if (Helper.areTypesAssignable(query.getArgumentTypes(), existingQuery.getArgumentTypes())) {
throw ValidationException.existingQueryTypeConflict(query, existingQuery);
}
}
}
queriesByName.add(query);
}
/**
* PUBLIC:
* Add the query to the session queries with the given name.
* This allows for common queries to be pre-defined, reused and executed by name.
*/
public void addQuery(String name, DatabaseQuery query) {
query.setName(name);
addQuery(query, false);
}
/**
* PUBLIC:
* Add the query to the session queries with the given name.
* This allows for common queries to be pre-defined, reused and executed by name.
*/
public void addQuery(String name, DatabaseQuery query, boolean replace) {
query.setName(name);
addQuery(query, replace);
}
/**
* INTERNAL:
* Add a metamodel class to model class reference.
*/
public void addStaticMetamodelClass(String modelClassName, String metamodelClassName) {
if (staticMetamodelClasses == null) {
staticMetamodelClasses = new HashMap<String, String>();
}
staticMetamodelClasses.put(modelClassName, metamodelClassName);
}
/**
* INTERNAL:
* Add a descriptor that is uses a table per tenant multitenant policy.
*/
protected void addTablePerTenantDescriptor(ClassDescriptor descriptor) {
getTablePerTenantDescriptors().add(descriptor);
}
/**
* INTERNAL:
* Add a query that queries a table per tenant entity
*/
protected void addTablePerTenantQuery(DatabaseQuery query) {
getTablePerTenantQueries().add(query);
}
/**
* INTERNAL:
* Called by beginTransaction() to start a transaction.
* This starts a real database transaction.
* Allows retry if the connection is dead.
*/
protected void basicBeginTransaction() throws DatabaseException {
Collection<Accessor> accessors = getAccessors();
if (accessors == null) {
return;
}
Accessor failedAccessor = null;
try {
for (Accessor accessor : accessors) {
failedAccessor = accessor;
basicBeginTransaction(accessor);
}
} catch (RuntimeException exception) {
// If begin failed, rollback ones already started.
for (Accessor accessor : accessors) {
if (accessor == failedAccessor) {
break;
}
try {
accessor.rollbackTransaction(this);
} catch (RuntimeException ignore) { }
}
throw exception;
}
}
/**
* INTERNAL:
* Called by beginTransaction() to start a transaction.
* This starts a real database transaction.
* Allows retry if the connection is dead.
*/
protected void basicBeginTransaction(Accessor accessor) throws DatabaseException {
try {
accessor.beginTransaction(this);
} catch (DatabaseException databaseException) {
// Retry if the failure was communication based? (i.e. timeout, database down, can no longer ping)
if ((!getDatasourceLogin().shouldUseExternalTransactionController()) && databaseException.isCommunicationFailure()) {
DatabaseException exceptionToThrow = databaseException;
Object[] args = new Object[1];
args[0] = databaseException;
log(SessionLog.INFO, SessionLog.TRANSACTION, "communication_failure_attempting_begintransaction_retry", args, null);
// Attempt to reconnect connection.
exceptionToThrow = retryTransaction(accessor, databaseException, 0, this);
if (exceptionToThrow == null) {
// Retry was a success.
return;
}
handleException(exceptionToThrow);
} else {
handleException(databaseException);
}
} catch (RuntimeException exception) {
handleException(exception);
}
}
/**
* INTERNAL:
* A begin transaction failed.
* Re-connect and retry the begin transaction.
*/
public DatabaseException retryTransaction(Accessor accessor, DatabaseException databaseException, int retryCount, AbstractSession executionSession) {
DatabaseException exceptionToThrow = databaseException;
// Attempt to reconnect connection.
int count = getLogin().getQueryRetryAttemptCount();
while (retryCount < count) {
try {
// if database session then re-establish
// connection
// else the session will just get a new
// connection from the pool
accessor.reestablishConnection(this);
accessor.beginTransaction(this);
return null;
} catch (DatabaseException newException) {
// Need to use last exception, as may not be a communication exception.
exceptionToThrow = newException;
// failed to get connection because of
// database error.
++retryCount;
try {
// Give the failover time to recover.
Thread.currentThread().sleep(getLogin().getDelayBetweenConnectionAttempts());
Object[] args = new Object[1];
args[0] = databaseException;
log(SessionLog.INFO, SessionLog.TRANSACTION, "communication_failure_attempting_begintransaction_retry", args, null);
} catch (InterruptedException intEx) {
break;
}
}
}
return exceptionToThrow;
}
/**
* INTERNAL:
* Called in the end of beforeCompletion of external transaction synchronization listener.
* Close the managed sql connection corresponding to the external transaction,
* if applicable releases accessor.
*/
public void releaseJTSConnection() {
}
/**
* INTERNAL:
* Called by commitTransaction() to commit a transaction.
* This commits the active transaction.
*/
protected void basicCommitTransaction() throws DatabaseException {
Collection<Accessor> accessors = getAccessors();
if (accessors == null) {
return;
}
try {
for (Accessor accessor : accessors) {
accessor.commitTransaction(this);
}
} catch (RuntimeException exception) {
// Leave transaction uncommitted as rollback should be called.
handleException(exception);
}
}
/**
* INTERNAL:
* Called by rollbackTransaction() to rollback a transaction.
* This rolls back the active transaction.
*/
protected void basicRollbackTransaction() throws DatabaseException {
Collection<Accessor> accessors = getAccessors();
if (accessors == null) {
return;
}
RuntimeException exception = null;
for (Accessor accessor : accessors) {
try {
accessor.rollbackTransaction(this);
} catch (RuntimeException failure) {
exception = failure;
}
}
if (exception != null) {
handleException(exception);
}
}
/**
* INTERNAL:
* Attempts to begin an external transaction.
* Returns true only in one case -
* external transaction has been internally started during this method call:
* wasJTSTransactionInternallyStarted()==false in the beginning of this method and
* wasJTSTransactionInternallyStarted()==true in the end of this method.
*/
public boolean beginExternalTransaction() {
boolean externalTransactionHasBegun = false;
if (hasExternalTransactionController() && !wasJTSTransactionInternallyStarted()) {
try {
getExternalTransactionController().beginTransaction(this);
} catch (RuntimeException exception) {
handleException(exception);
}
if (wasJTSTransactionInternallyStarted()) {
externalTransactionHasBegun = true;
log(SessionLog.FINER, SessionLog.TRANSACTION, "external_transaction_has_begun_internally");
}
}
return externalTransactionHasBegun;
}
/**
* PUBLIC:
* Begin a transaction on the database.
* This allows a group of database modification to be committed or rolled back as a unit.
* All writes/deletes will be sent to the database be will not be visible to other users until commit.
* Although databases do not allow nested transaction,
* EclipseLink supports nesting through only committing to the database on the outer commit.
*
* @exception DatabaseException if the database connection is lost or the begin is rejected.
* @exception ConcurrencyException if this session's transaction is acquired by another thread and a timeout occurs.
*
* @see #isInTransaction()
*/
public void beginTransaction() throws DatabaseException, ConcurrencyException {
ConcurrencyManager mutex = getTransactionMutex();
// If there is no db transaction in progress
// beginExternalTransaction() starts an external transaction -
// provided externalTransactionController is used, and there is
// no active external transaction - so we have to start one internally.
if (!mutex.isAcquired()) {
beginExternalTransaction();
}
// For unit of work and client session multi threading is allowed as they are a context,
// this is required for JTS/RMI/CORBA/EJB stuff where the server thread can be different across calls.
if (isClientSession()) {
mutex.setActiveThread(Thread.currentThread());
}
// Ensure mutual exclusion and call subclass specific begin.
mutex.acquire();
if (!mutex.isNested()) {
if (this.eventManager != null) {
this.eventManager.preBeginTransaction();
}
basicBeginTransaction();
if (this.eventManager != null) {
this.eventManager.postBeginTransaction();
}
}
}
/**
* Check to see if the descriptor of a superclass can be used to describe this class
*
* @param Class
* @return ClassDescriptor
*/
protected ClassDescriptor checkHierarchyForDescriptor(Class theClass){
return getDescriptor(theClass.getSuperclass());
}
/**
* allow the entity listener injection manager to clean itself up.
*/
public void cleanUpEntityListenerInjectionManager(){
if (entityListenerInjectionManager != null){
entityListenerInjectionManager.cleanUp(this);
}
}
/**
* PUBLIC:
* clear the integrityChecker. IntegrityChecker holds all the ClassDescriptor Exceptions.
*/
public void clearIntegrityChecker() {
setIntegrityChecker(null);
}
/**
* INTERNAL:
* Clear the the lastDescriptorAccessed cache.
*/
public void clearLastDescriptorAccessed() {
this.lastDescriptorAccessed = null;
}
/**
* INTERNAL:
* Clear the the descriptors cache.
*/
public void clearDescriptors() {
this.descriptors = null;
}
/**
* PUBLIC:
* Clear the profiler, this will end the current profile operation.
*/
public void clearProfile() {
setProfiler(null);
}
/**
* INTERNAL:
* Clones the descriptor
*/
public Object clone() {
// An alternative to this process should be found
try {
return super.clone();
} catch (Exception exception) {
return null;
}
}
/**
* INTERNAL:
* Attempts to commit the running internally started external transaction.
* Returns true only in one case -
* external transaction has been internally committed during this method call:
* wasJTSTransactionInternallyStarted()==true in the beginning of this method and
* wasJTSTransactionInternallyStarted()==false in the end of this method.
*/
public boolean commitExternalTransaction() {
boolean externalTransactionHasCommitted = false;
if (hasExternalTransactionController() && wasJTSTransactionInternallyStarted()) {
try {
getExternalTransactionController().commitTransaction(this);
} catch (RuntimeException exception) {
handleException(exception);
}
if (!wasJTSTransactionInternallyStarted()) {
externalTransactionHasCommitted = true;
log(SessionLog.FINER, SessionLog.TRANSACTION, "external_transaction_has_committed_internally");
}
}
return externalTransactionHasCommitted;
}
/**
* PUBLIC:
* Commit the active database transaction.
* This allows a group of database modification to be committed or rolled back as a unit.
* All writes/deletes will be sent to the database be will not be visible to other users until commit.
* Although databases do not allow nested transaction,
* EclipseLink supports nesting through only committing to the database on the outer commit.
*
* @exception DatabaseException most databases validate changes as they are done,
* normally errors do not occur on commit unless the disk fails or the connection is lost.
* @exception ConcurrencyException if this session is not within a transaction.
*/
public void commitTransaction() throws DatabaseException, ConcurrencyException {
ConcurrencyManager mutex = getTransactionMutex();
// Release mutex and call subclass specific commit.
if (!mutex.isNested()) {
if (this.eventManager != null) {
this.eventManager.preCommitTransaction();
}
basicCommitTransaction();
if (this.eventManager != null) {
this.eventManager.postCommitTransaction();
}
}
// This MUST not be in a try catch or finally as if the commit failed the transaction is still open.
mutex.release();
// If there is no db transaction in progress
// if there is an active external transaction
// which was started internally - it should be committed internally, too.
if (!mutex.isAcquired()) {
commitExternalTransaction();
}
}
/**
* INTERNAL:
* Return if the two object match completely.
* This checks the objects attributes and their private parts.
*/
public boolean compareObjects(Object firstObject, Object secondObject) {
if ((firstObject == null) && (secondObject == null)) {
return true;
}
if ((firstObject == null) || (secondObject == null)) {
return false;
}
if (!(firstObject.getClass().equals(secondObject.getClass()))) {
return false;
}
ObjectBuilder builder = getDescriptor(firstObject.getClass()).getObjectBuilder();
return builder.compareObjects(builder.unwrapObject(firstObject, this), builder.unwrapObject(secondObject, this), this);
}
/**
* TESTING:
* Return true if the object do not match.
* This checks the objects attributes and their private parts.
*/
public boolean compareObjectsDontMatch(Object firstObject, Object secondObject) {
return !this.compareObjects(firstObject, secondObject);
}
/**
* PUBLIC:
* Return true if the pre-defined query is defined on the session.
*/
public boolean containsQuery(String queryName) {
return getQueries().containsKey(queryName);
}
/**
* PUBLIC:
* Return a complete copy of the object or of collection of objects.
* In case of collection all members should be either entities of the same type
* or have a common inheritance hierarchy mapped root class.
* This can be used to obtain a scratch copy of an object,
* or for templatizing an existing object into another new object.
* The object and all of its privately owned parts will be copied.
*
* @see #copy(Object, AttributeGroup)
*/
public Object copy(Object originalObjectOrObjects) {
return copy(originalObjectOrObjects, new CopyGroup());
}
/**
* PUBLIC:
* Return a complete copy of the object or of collection of objects.
* In case of collection all members should be either entities of the same type
* or have a common inheritance hierarchy mapped root class.
* This can be used to obtain a scratch copy of an object,
* or for templatizing an existing object into another new object.
* If there are no attributes in the group
* then the object and all of its privately owned parts will be copied.
* Otherwise only the attributes included into the group will be copied.
*/
public Object copy(Object originalObjectOrObjects, AttributeGroup group) {
if (originalObjectOrObjects == null) {
return null;
}
CopyGroup copyGroup = group.toCopyGroup();
copyGroup.setSession(this);
if(originalObjectOrObjects instanceof Collection) {
// it's a collection - make sure all elements use the same instance of CopyGroup.
Collection originalCollection = (Collection)originalObjectOrObjects;
Collection copies;
if(originalCollection instanceof List) {
copies = new ArrayList();
} else {
copies = new HashSet();
}
Iterator it = originalCollection.iterator();
while(it.hasNext()) {
copies.add(copyInternal(it.next(), copyGroup));
}
return copies;
}
// it's not a collection
return copyInternal(originalObjectOrObjects, copyGroup);
}
/**
* INTERNAL:
*/
public Object copyInternal(Object originalObject, CopyGroup copyGroup) {
if (originalObject == null) {
return null;
}
ClassDescriptor descriptor = getDescriptor(originalObject);
if (descriptor == null) {
return originalObject;
}
return descriptor.getObjectBuilder().copyObject(originalObject, copyGroup);
}
/**
* PUBLIC:
* Return a complete copy of the object.
* This can be used to obtain a scratch copy of an object,
* or for templatizing an existing object into another new object.
* The object and all of its privately owned parts will be copied, the object's primary key will be reset to null.
*
* @see #copyObject(Object, ObjectCopyingPolicy)
* @deprecated since EclipseLink 2.1, replaced by copy(Object)
* @see #copy(Object)
*/
public Object copyObject(Object original) {
CopyGroup copyGroup = new CopyGroup();
copyGroup.setShouldResetPrimaryKey(true);
return copy(original, copyGroup);
}
/**
* PUBLIC:
* Return a complete copy of the object.
* This can be used to obtain a scratch copy of an object,
* or for templatizing an existing object into another new object.
* The object copying policy allow for the depth, and reseting of the primary key to null, to be specified.
* @deprecated since EclipseLink 2.1, replaced by copy(Object, AttributeGroup)
* @see #copy(Object, AttributeGroup)
*/
public Object copyObject(Object original, ObjectCopyingPolicy policy) {
return copy(original, policy);
}
/**
* INTERNAL:
* Copy the read only classes from the unit of work
*
* Added Nov 8, 2000 JED for Patch 2.5.1.8
* Ref: Prs 24502
*/
public Vector copyReadOnlyClasses() {
return getDefaultReadOnlyClasses();
}
public DatabaseValueHolder createCloneQueryValueHolder(ValueHolderInterface attributeValue, Object clone, AbstractRecord row, ForeignReferenceMapping mapping) {
return new ProtectedValueHolder(attributeValue, mapping, this);
}
public DatabaseValueHolder createCloneTransformationValueHolder(ValueHolderInterface attributeValue, Object original, Object clone, AbstractTransformationMapping mapping) {
return new ProtectedValueHolder(attributeValue, mapping, this);
}
public EntityListenerInjectionManager createEntityListenerInjectionManager(Object beanManager){
try{
if (PrivilegedAccessHelper.shouldUsePrivilegedAccess()){
Class elim = AccessController.doPrivileged(new PrivilegedClassForName(EntityListenerInjectionManager.DEFAULT_CDI_INJECTION_MANAGER, true, getLoader()));
Constructor constructor = AccessController.doPrivileged(new PrivilegedGetConstructorFor(elim, new Class[] {String.class}, false));
return (EntityListenerInjectionManager) AccessController.doPrivileged(new PrivilegedInvokeConstructor(constructor, new Object[] {beanManager}));
} else {
Class elim = org.eclipse.persistence.internal.security.PrivilegedAccessHelper.getClassForName(EntityListenerInjectionManager.DEFAULT_CDI_INJECTION_MANAGER, true, getLoader());
Constructor constructor = PrivilegedAccessHelper.getConstructorFor(elim, new Class[] {Object.class}, false);
return (EntityListenerInjectionManager) PrivilegedAccessHelper.invokeConstructor(constructor, new Object[] {beanManager});
}
} catch (Exception e){
logThrowable(SessionLog.FINEST, SessionLog.JPA, e);
}
return new DisabledEntityListenerInjectionManager();
}
/**
* INTERNAL:
* This method is similar to getAndCloneCacheKeyFromParent. It purpose is to get protected cache data from the shared cache and
* build/return a protected instance.
*/
public Object createProtectedInstanceFromCachedData(Object cached, Integer refreshCascade, ClassDescriptor descriptor){
CacheKey localCacheKey = getIdentityMapAccessorInstance().getCacheKeyForObject(cached);
if (localCacheKey != null && localCacheKey.getObject() != null){
return localCacheKey.getObject();
}
boolean identityMapLocked = this.shouldCheckWriteLock && getParent().getIdentityMapAccessorInstance().acquireWriteLock();
boolean rootOfCloneRecursion = false;
CacheKey cacheKey = getParent().getIdentityMapAccessorInstance().getCacheKeyForObject(cached);
try{
Object key = null;
Object lockValue = null;
long readTime = 0;
if (cacheKey != null){
if (identityMapLocked) {
checkAndRefreshInvalidObject(cached, cacheKey, descriptor);
} else {
// Check if we have locked all required objects already.
if (this.objectsLockedForClone == null) {
// PERF: If a simple object just acquire a simple read-lock.
if (descriptor.shouldAcquireCascadedLocks()) {
this.objectsLockedForClone = getParent().getIdentityMapAccessorInstance().getWriteLockManager().acquireLocksForClone(cached, descriptor, cacheKey, this);
} else {
checkAndRefreshInvalidObject(cached, cacheKey, descriptor);
cacheKey.acquireReadLock();
}
rootOfCloneRecursion = true;
}
}
key = cacheKey.getKey();
lockValue = cacheKey.getWriteLockValue();
readTime = cacheKey.getReadTime();
}
if (descriptor.hasInheritance()){
descriptor = this.getClassDescriptor(cached.getClass());
}
ObjectBuilder builder = descriptor.getObjectBuilder();
Object workingClone = builder.instantiateWorkingCopyClone(cached, this);
// PERF: Cache the primary key if implements PersistenceEntity.
builder.populateAttributesForClone(cached, cacheKey, workingClone, refreshCascade, this);
getIdentityMapAccessorInstance().putInIdentityMap(workingClone, key, lockValue, readTime, descriptor);
return workingClone;
}finally{
if (rootOfCloneRecursion){
if (this.objectsLockedForClone == null && cacheKey != null) {
cacheKey.releaseReadLock();
} else {
for (Iterator iterator = this.objectsLockedForClone.values().iterator(); iterator.hasNext();) {
((CacheKey)iterator.next()).releaseReadLock();
}
this.objectsLockedForClone = null;
}
executeDeferredEvents();
}
}
}
/**
* INTERNAL:
* Check if the object is invalid and refresh it.
* This is used to ensure that no invalid objects are registered.
*/
public void checkAndRefreshInvalidObject(Object object, CacheKey cacheKey, ClassDescriptor descriptor) {
if (isConsideredInvalid(object, cacheKey, descriptor)) {
ReadObjectQuery query = new ReadObjectQuery();
query.setReferenceClass(object.getClass());
query.setSelectionId(cacheKey.getKey());
query.refreshIdentityMapResult();
query.setIsExecutionClone(true);
this.executeQuery(query);
}
}
/**
* INTERNAL:
* Check if the object is invalid and *should* be refreshed.
* This is used to ensure that no invalid objects are cloned.
*/
public boolean isConsideredInvalid(Object object, CacheKey cacheKey, ClassDescriptor descriptor) {
if (cacheKey.getObject() != null) {
CacheInvalidationPolicy cachePolicy = descriptor.getCacheInvalidationPolicy();
// BUG#6671556 refresh invalid objects when accessed in the unit of work.
return (cachePolicy.shouldRefreshInvalidObjectsOnClone() && cachePolicy.isInvalidated(cacheKey));
}
return false;
}
/**
* INTERNAL:
* Add an event to the deferred list. Events will be fired after the operation completes
*/
public void deferEvent(DescriptorEvent event){
if (this.deferredEvents == null){
this.deferredEvents = new ArrayList<DescriptorEvent>();
}
this.deferredEvents.add(event);
}
/**
* PUBLIC:
* delete all of the objects and all of their privately owned parts in the database.
* The allows for a group of objects to be deleted as a unit.
* The objects will be deleted through a single transactions.
*
* @exception DatabaseException if an error occurs on the database,
* these include constraint violations, security violations and general database errors.
* @exception OptimisticLockException if the object's descriptor is using optimistic locking and
* the object has been updated or deleted by another user since it was last read.
*/
public void deleteAllObjects(Collection domainObjects) throws DatabaseException, OptimisticLockException {
for (Iterator objectsEnum = domainObjects.iterator(); objectsEnum.hasNext();) {
deleteObject(objectsEnum.next());
}
}
/**
* PUBLIC:
* delete all of the objects and all of their privately owned parts in the database.
* The allows for a group of objects to be deleted as a unit.
* The objects will be deleted through a single transactions.
*
* @exception DatabaseException if an error occurs on the database,
* these include constraint violations, security violations and general database errors.
* @exception OptimisticLockException if the object's descriptor is using optimistic locking and
* the object has been updated or deleted by another user since it was last read.
*/
@Deprecated
public void deleteAllObjects(Vector domainObjects) throws DatabaseException, OptimisticLockException {
for (Enumeration objectsEnum = domainObjects.elements(); objectsEnum.hasMoreElements();) {
deleteObject(objectsEnum.nextElement());
}
}
/**
* PUBLIC:
* Delete the object and all of its privately owned parts from the database.
* The delete operation can be customized through using a delete query.
*
* @exception DatabaseException if an error occurs on the database,
* these include constraint violations, security violations and general database errors.
* An database error is not raised if the object is already deleted or no rows are effected.
* @exception OptimisticLockException if the object's descriptor is using optimistic locking and
* the object has been updated or deleted by another user since it was last read.
*
* @see DeleteObjectQuery
*/
public Object deleteObject(Object domainObject) throws DatabaseException, OptimisticLockException {
DeleteObjectQuery query = new DeleteObjectQuery();
query.setObject(domainObject);
query.setIsExecutionClone(true);
return executeQuery(query);
}
/**
* PUBLIC:
* Return if the object exists on the database or not.
* This always checks existence on the database.
*/
public boolean doesObjectExist(Object object) throws DatabaseException {
DoesExistQuery query = new DoesExistQuery();
query.setObject(object);
query.checkDatabaseForDoesExist();
query.setIsExecutionClone(true);
return ((Boolean)executeQuery(query)).booleanValue();
}
/**
* PUBLIC:
* Turn off logging
*/
public void dontLogMessages() {
setLogLevel(SessionLog.OFF);
}
/**
* INTERNAL:
* End the operation timing.
*/
public void endOperationProfile(String operationName) {
if (this.isInProfile) {
getProfiler().endOperationProfile(operationName);
}
}
/**
* INTERNAL:
* End the operation timing.
*/
public void endOperationProfile(String operationName, DatabaseQuery query, int weight) {
if (this.isInProfile) {
getProfiler().endOperationProfile(operationName, query, weight);
}
}
/**
* INTERNAL:
* Updates the value of SessionProfiler state
*/
public void updateProfile(String operationName, Object value) {
if (this.isInProfile) {
getProfiler().update(operationName, value);
}
}
/**
* INTERNAL:
* Set the table per tenant. This should be called per client session after
* the start of a transaction. From JPA this method is called on the entity
* manager by setting the multitenant table per tenant property.
*/
public void updateTablePerTenantDescriptors(String property, Object value) {
// When all the table per tenant descriptors are set, we should initialize them.
boolean shouldInitializeDescriptors = hasTablePerTenantDescriptors();
for (ClassDescriptor descriptor : getTablePerTenantDescriptors()) {
TablePerMultitenantPolicy policy = (TablePerMultitenantPolicy) descriptor.getMultitenantPolicy();
if ((! policy.hasContextTenant()) && policy.usesContextProperty(property)) {
policy.setContextTenant((String) value);
}
shouldInitializeDescriptors = shouldInitializeDescriptors && policy.hasContextTenant();
}
if (shouldInitializeDescriptors) {
// Now that the correct tables are set on all table per tenant
// descriptors, we can go through the initialization phases safely.
try {
// First initialize basic properties (things that do not depend on anything else)
for (ClassDescriptor descriptor : tablePerTenantDescriptors) {
descriptor.preInitialize(this);
}
// Second initialize basic mappings
for (ClassDescriptor descriptor : tablePerTenantDescriptors) {
descriptor.initialize(this);
}
// Third initialize child dependencies
for (ClassDescriptor descriptor : tablePerTenantDescriptors) {
descriptor.postInitialize(this);
}
if (getIntegrityChecker().hasErrors()) {
handleSevere(new IntegrityException(getIntegrityChecker()));
}
} finally {
clearIntegrityChecker();
}
getCommitManager().initializeCommitOrder();
// If we have table per tenant queries, initialize and add them now
// once all the descriptors have been initialized.
if (hasTablePerTenantQueries()) {
for (DatabaseQuery query : getTablePerTenantQueries()) {
processJPAQuery(query);
}
}
}
}
/**
* INTERNAL:
* Updates the count of SessionProfiler event
*/
public void incrementProfile(String operationName) {
if (this.isInProfile) {
getProfiler().occurred(operationName, this);
}
}
/**
* INTERNAL:
* Updates the count of SessionProfiler event
*/
public void incrementProfile(String operationName, DatabaseQuery query) {
if (this.isInProfile) {
getProfiler().occurred(operationName, query, this);
}
}
/**
* INTERNAL:
* Causes any deferred events to be fired. Called after operation completes
*/
public void executeDeferredEvents(){
if (!this.isExecutingEvents && this.deferredEvents != null) {
this.isExecutingEvents = true;
try {
for (int i = 0; i < this.deferredEvents.size(); ++i) {
// the size is checked every time here because the list may grow
DescriptorEvent event = this.deferredEvents.get(i);
event.getDescriptor().getEventManager().executeEvent(event);
}
this.deferredEvents.clear();
} finally {
this.isExecutingEvents = false;
}
}
}
/**
* INTERNAL:
* Overridden by subclasses that do more than just execute the call.
* Executes the call directly on this session and does not check which
* session it should have executed on.
*/
public Object executeCall(Call call, AbstractRecord translationRow, DatabaseQuery query) throws DatabaseException {
if (query.getAccessors() == null) {
query.setAccessors(getAccessors());
}
try {
return basicExecuteCall(call, translationRow, query);
} finally {
if (call.isFinished()) {
query.setAccessors(null);
}
}
}
/**
* INTERNAL:
* Release (if required) connection after call.
* @param query
* @return
*/
public void releaseConnectionAfterCall(DatabaseQuery query) {
}
/**
* PUBLIC:
* Execute the call on the database.
* The row count is returned.
* The call can be a stored procedure call, SQL call or other type of call.
* <p>Example:
* <p>session.executeNonSelectingCall(new SQLCall("Delete from Employee");
*
* @see #executeSelectingCall(Call)
*/
public int executeNonSelectingCall(Call call) throws DatabaseException {
DataModifyQuery query = new DataModifyQuery();
query.setIsExecutionClone(true);
query.setCall(call);
Integer value = (Integer)executeQuery(query);
if (value == null) {
return 0;
} else {
return value.intValue();
}
}
/**
* PUBLIC:
* Execute the sql on the database.
* <p>Example:
* <p>session.executeNonSelectingSQL("Delete from Employee");
* @see #executeNonSelectingCall(Call)
* Warning: Allowing an unverified SQL string to be passed into this
* method makes your application vulnerable to SQL injection attacks.
*/
public void executeNonSelectingSQL(String sqlString) throws DatabaseException {
executeNonSelectingCall(new SQLCall(sqlString));
}
/**
* PUBLIC:
* Execute the pre-defined query by name and return the result.
* Queries can be pre-defined and named to allow for their reuse.
*
* @see #addQuery(String, DatabaseQuery)
*/
public Object executeQuery(String queryName) throws DatabaseException {
DatabaseQuery query = getQuery(queryName);
if (query == null) {
throw QueryException.queryNotDefined(queryName);
}
return executeQuery(query);
}
/**
* PUBLIC:
* Execute the pre-defined query by name and return the result.
* Queries can be pre-defined and named to allow for their reuse.
* The class is the descriptor in which the query was pre-defined.
*
* @see DescriptorQueryManager#addQuery(String, DatabaseQuery)
*/
public Object executeQuery(String queryName, Class domainClass) throws DatabaseException {
ClassDescriptor descriptor = getDescriptor(domainClass);
if (descriptor == null) {
throw QueryException.descriptorIsMissingForNamedQuery(domainClass, queryName);
}
DatabaseQuery query = descriptor.getQueryManager().getQuery(queryName);
if (query == null) {
throw QueryException.queryNotDefined(queryName, domainClass);
}
return executeQuery(query);
}
/**
* PUBLIC:
* Execute the pre-defined query by name and return the result.
* Queries can be pre-defined and named to allow for their reuse.
* The class is the descriptor in which the query was pre-defined.
*
* @see DescriptorQueryManager#addQuery(String, DatabaseQuery)
*/
public Object executeQuery(String queryName, Class domainClass, Object arg1) throws DatabaseException {
Vector argumentValues = new Vector();
argumentValues.addElement(arg1);
return executeQuery(queryName, domainClass, argumentValues);
}
/**
* PUBLIC:
* Execute the pre-defined query by name and return the result.
* Queries can be pre-defined and named to allow for their reuse.
* The class is the descriptor in which the query was pre-defined.
*
* @see DescriptorQueryManager#addQuery(String, DatabaseQuery)
*/
public Object executeQuery(String queryName, Class domainClass, Object arg1, Object arg2) throws DatabaseException {
Vector argumentValues = new Vector();
argumentValues.addElement(arg1);
argumentValues.addElement(arg2);
return executeQuery(queryName, domainClass, argumentValues);
}
/**
* PUBLIC:
* Execute the pre-defined query by name and return the result.
* Queries can be pre-defined and named to allow for their reuse.
* The class is the descriptor in which the query was pre-defined.
*
* @see DescriptorQueryManager#addQuery(String, DatabaseQuery)
*/
public Object executeQuery(String queryName, Class domainClass, Object arg1, Object arg2, Object arg3) throws DatabaseException {
Vector argumentValues = new Vector();
argumentValues.addElement(arg1);
argumentValues.addElement(arg2);
argumentValues.addElement(arg3);
return executeQuery(queryName, domainClass, argumentValues);
}
/**
* PUBLIC:
* Execute the pre-defined query by name and return the result.
* Queries can be pre-defined and named to allow for their reuse.
* The class is the descriptor in which the query was pre-defined.
*
* @see DescriptorQueryManager#addQuery(String, DatabaseQuery)
*/
public Object executeQuery(String queryName, Class domainClass, List argumentValues) throws DatabaseException {
if (argumentValues instanceof Vector) {
return executeQuery(queryName, domainClass, (Vector)argumentValues);
} else {
return executeQuery(queryName, domainClass, new Vector(argumentValues));
}
}
/**
* PUBLIC:
* Execute the pre-defined query by name and return the result.
* Queries can be pre-defined and named to allow for their reuse.
* The class is the descriptor in which the query was pre-defined.
*
* @see DescriptorQueryManager#addQuery(String, DatabaseQuery)
*/
public Object executeQuery(String queryName, Class domainClass, Vector argumentValues) throws DatabaseException {
ClassDescriptor descriptor = getDescriptor(domainClass);
if (descriptor == null) {
throw QueryException.descriptorIsMissingForNamedQuery(domainClass, queryName);
}
DatabaseQuery query = descriptor.getQueryManager().getQuery(queryName, argumentValues);
if (query == null) {
throw QueryException.queryNotDefined(queryName, domainClass);
}
return executeQuery(query, argumentValues);
}
/**
* PUBLIC:
* Execute the pre-defined query by name and return the result.
* Queries can be pre-defined and named to allow for their reuse.
*
* @see #addQuery(String, DatabaseQuery)
*/
public Object executeQuery(String queryName, Object arg1) throws DatabaseException {
Vector argumentValues = new Vector();
argumentValues.addElement(arg1);
return executeQuery(queryName, argumentValues);
}
/**
* PUBLIC:
* Execute the pre-defined query by name and return the result.
* Queries can be pre-defined and named to allow for their reuse.
*
* @see #addQuery(String, DatabaseQuery)
*/
public Object executeQuery(String queryName, Object arg1, Object arg2) throws DatabaseException {
Vector argumentValues = new Vector();
argumentValues.addElement(arg1);
argumentValues.addElement(arg2);
return executeQuery(queryName, argumentValues);
}
/**
* PUBLIC:
* Execute the pre-defined query by name and return the result.
* Queries can be pre-defined and named to allow for their reuse.
*
* @see #addQuery(String, DatabaseQuery)
*/
public Object executeQuery(String queryName, Object arg1, Object arg2, Object arg3) throws DatabaseException {
Vector argumentValues = new Vector();
argumentValues.addElement(arg1);
argumentValues.addElement(arg2);
argumentValues.addElement(arg3);
return executeQuery(queryName, argumentValues);
}
/**
* PUBLIC:
* Execute the pre-defined query by name and return the result.
* Queries can be pre-defined and named to allow for their reuse.
*
* @see #addQuery(String, DatabaseQuery)
*/
public Object executeQuery(String queryName, List argumentValues) throws DatabaseException {
if (argumentValues instanceof Vector) {
return executeQuery(queryName, (Vector)argumentValues);
} else {
return executeQuery(queryName, new Vector(argumentValues));
}
}
/**
* PUBLIC:
* Execute the pre-defined query by name and return the result.
* Queries can be pre-defined and named to allow for their reuse.
*
* @see #addQuery(String, DatabaseQuery)
*/
public Object executeQuery(String queryName, Vector argumentValues) throws DatabaseException {
DatabaseQuery query = getQuery(queryName, argumentValues);
if (query == null) {
throw QueryException.queryNotDefined(queryName);
}
return executeQuery(query, argumentValues);
}
/**
* PUBLIC:
* Execute the database query.
* A query is a database operation such as reading or writing.
* The query allows for the operation to be customized for such things as,
* performance, depth, caching, etc.
*
* @see DatabaseQuery
*/
public Object executeQuery(DatabaseQuery query) throws DatabaseException {
return executeQuery(query, EmptyRecord.getEmptyRecord());
}
/**
* PUBLIC:
* Return the results from executing the database query.
* The query arguments are passed in as a List of argument values in the same order as the query arguments.
*/
public Object executeQuery(DatabaseQuery query, List argumentValues) throws DatabaseException {
if (query == null) {
throw QueryException.queryNotDefined();
}
AbstractRecord row = query.rowFromArguments(argumentValues, this);
return executeQuery(query, row);
}
/**
* INTERNAL:
* Return the results from executing the database query.
* the arguments should be a database row with raw data values.
*/
public Object executeQuery(DatabaseQuery query, AbstractRecord row) throws DatabaseException {
if (hasBroker()) {
if (!((query.isDataModifyQuery() || query.isDataReadQuery()) && (query.getSessionName() == null))) {
return getBroker().executeQuery(query, row);
}
}
if (query == null) {
throw QueryException.queryNotDefined();
}
// Check for disabled native queries.
if (query.isUserDefinedSQLCall() && query.isSQLCallQuery() && ! query.isJPQLCallQuery()) {
if (! query.shouldAllowNativeSQLQuery(getProject().allowNativeSQLQueries())) {
// If the session/project says no to SQL queries and the database
// query doesn't ask to bypass this decision then throw an exception.
throw QueryException.nativeSQLQueriesAreDisabled(query);
}
}
//CR#2272
log(SessionLog.FINEST, SessionLog.QUERY, "execute_query", query);
//Make a call to the internal method with a retry count of 0. This will
//initiate a retry call stack if required and supported. The separation between the
//calling stack and the target method is made because the target method may call itself
//recursively.
return this.executeQuery(query, row, 0);
}
/**
* INTERNAL:
* Return the results from executing the database query.
* the arguments should be a database row with raw data values.
*/
public Object executeQuery(DatabaseQuery query, AbstractRecord row, int retryCount) throws DatabaseException {
try {
if (this.eventManager != null) {
this.eventManager.preExecuteQuery(query);
}
Object result;
if (isInProfile()) {
result = getProfiler().profileExecutionOfQuery(query, row, this);
} else {
result = internalExecuteQuery(query, row);
}
if (this.eventManager != null) {
this.eventManager.postExecuteQuery(query, result);
}
return result;
} catch (RuntimeException exception) {
if (exception instanceof QueryException) {
QueryException queryException = (QueryException)exception;
if (queryException.getQuery() == null) {
queryException.setQuery(query);
}
if (queryException.getQueryArgumentsRecord() == null) {
queryException.setQueryArguments(row);
}
if (queryException.getSession() == null) {
queryException.setSession(this);
}
} else if (exception instanceof DatabaseException) {
DatabaseException databaseException = (DatabaseException)exception;
if (databaseException.getQuery() == null) {
databaseException.setQuery(query);
}
if (databaseException.getQueryArgumentsRecord() == null) {
databaseException.setQueryArguments(row);
}
if (databaseException.getSession() == null) {
databaseException.setSession(this);
}
//if this query is a read query outside of a transaction then we may be able to retry the query
if (!isInTransaction() && query.isReadQuery()) {
final int count = getLogin().getQueryRetryAttemptCount();
//was the failure communication based? (ie timeout)
if (databaseException.isCommunicationFailure() && retryCount < count) {
Object[] args = new Object[1];
args[0] = databaseException;
log(SessionLog.INFO, SessionLog.QUERY, "communication_failure_attempting_query_retry", args, null);
Object result = retryQuery(query, row, databaseException, retryCount, this);
if (result instanceof DatabaseException) {
exception = (DatabaseException)result;
} else {
return result;
}
}
}
}
return handleException(exception);
}
}
/**
* INTERNAL:
* A query execution failed due to an invalid query.
* Re-connect and retry the query.
*/
public Object retryQuery(DatabaseQuery query, AbstractRecord row, DatabaseException databaseException, int retryCount, AbstractSession executionSession) {
DatabaseException exception = databaseException;
//retry
if (retryCount <= getLogin().getQueryRetryAttemptCount()) {
try {
// attempt to reconnect for a certain number of times.
// servers may take some time to recover.
++retryCount;
try {
//passing the retry count will prevent a runaway retry where
// we can acquire connections but are unable to execute any queries
if (retryCount > 1) {
// We are retrying more than once lets wait to give connection time to restart.
//Give the failover time to recover.
Thread.currentThread().sleep(getLogin().getDelayBetweenConnectionAttempts());
}
return executionSession.executeQuery(query, row, retryCount);
} catch (DatabaseException newException){
//replace original exception with last exception thrown
//this exception could be a data based exception as opposed
//to a connection exception that needs to go back to the customer.
exception = newException;
}
} catch (InterruptedException ex) {
//Ignore interrupted exception.
}
}
return exception;
}
/**
* PUBLIC:
* Execute the call on the database and return the result.
* The call must return a value, if no value is return executeNonSelectCall must be used.
* The call can be a stored procedure call, SQL call or other type of call.
* A vector of database rows is returned, database row implements Java 2 Map which should be used to access the data.
* <p>Example:
* <p>session.executeSelectingCall(new SQLCall("Select * from Employee");
*
* @see #executeNonSelectingCall(Call)
*/
public Vector executeSelectingCall(Call call) throws DatabaseException {
DataReadQuery query = new DataReadQuery();
query.setCall(call);
query.setIsExecutionClone(true);
return (Vector)executeQuery(query);
}
/**
* PUBLIC:
* Execute the sql on the database and return the result.
* It must return a value, if no value is return executeNonSelectingSQL must be used.
* A vector of database rows is returned, database row implements Java 2 Map which should be used to access the data.
* Warning: Allowing an unverified SQL string to be passed into this
* method makes your application vulnerable to SQL injection attacks.
* <p>Example:
* <p>session.executeSelectingCall("Select * from Employee");
*
* @see #executeSelectingCall(Call)
*/
public Vector executeSQL(String sqlString) throws DatabaseException {
return executeSelectingCall(new SQLCall(sqlString));
}
/**
* INTERNAL:
* This should normally not be used, most sessions do not have a single accessor.
* ServerSession has a set of connection pools.
* ClientSession only has an accessor during a transaction.
* SessionBroker has multiple accessors.
* getAccessors() should be used to support partitioning.
* To maintain backward compatibility, and to support certain cases that required a default accessor,
* this returns the first accessor.
*/
public Accessor getAccessor() {
Collection<Accessor> accessors = getAccessors();
if ((accessors == null) || accessors.isEmpty()) {
return null;
}
if (accessors instanceof List) {
return ((List<Accessor>)accessors).get(0);
}
return accessors.iterator().next();
}
/**
* INTERNAL:
* This should normally not be used, most sessions do not have specific accessors.
* ServerSession has a set of connection pools.
* ClientSession only has an accessor during a transaction.
* SessionBroker has multiple accessors.
* getAccessors() is used to support partitioning.
* If the accessor is null, this lazy initializes one for backwardcompatibility with DatabaseSession.
*/
public Collection<Accessor> getAccessors() {
if ((this.accessors == null) && (this.project != null) && (this.project.getDatasourceLogin() != null)) {
synchronized (this) {
if ((this.accessors == null) && (this.project != null) && (this.project.getDatasourceLogin() != null)) {
// PERF: lazy init, not always required.
List<Accessor> newAccessors = new ArrayList(1);
newAccessors.add(this.project.getDatasourceLogin().buildAccessor());
this.accessors = newAccessors;
}
}
}
return this.accessors;
}
/**
* INTERNAL:
* Return the connections to use for the query execution.
*/
public Collection<Accessor> getAccessors(Call call, AbstractRecord translationRow, DatabaseQuery query) {
// Check for partitioning.
Collection<Accessor> accessors = null;
if (query.getPartitioningPolicy() != null) {
accessors = query.getPartitioningPolicy().getConnectionsForQuery(this, query, translationRow);
if (accessors != null) {
return accessors;
}
}
ClassDescriptor descriptor = query.getDescriptor();
if ((descriptor != null) && (descriptor.getPartitioningPolicy() != null)) {
accessors = descriptor.getPartitioningPolicy().getConnectionsForQuery(this, query, translationRow);
if (accessors != null) {
return accessors;
}
}
if (this.partitioningPolicy != null) {
accessors = this.partitioningPolicy.getConnectionsForQuery(this, query, translationRow);
if (accessors != null) {
return accessors;
}
}
return accessors;
}
/**
* INTERNAL:
* Execute the call on each accessors and merge the results.
*/
public Object basicExecuteCall(Call call, AbstractRecord translationRow, DatabaseQuery query) throws DatabaseException {
Object result = null;
if (query.getAccessors().size() == 1) {
result = query.getAccessor().executeCall(call, translationRow, this);
} else {
RuntimeException exception = null;
// Replication or partitioning may require execution on multiple connections.
for (Accessor accessor : query.getAccessors()) {
Object object = null;
try {
object = accessor.executeCall(call, translationRow, this);
} catch (RuntimeException failed) {
// Catch any exceptions to allow execution on each connections.
// This is used to have DDL run on every database even if one db fails because table already exists.
if (exception == null) {
exception = failed;
}
}
if (call.isOneRowReturned()) {
// If one row is desired, then break on first hit.
if (object != null) {
result = object;
break;
}
} else if (call.isNothingReturned()) {
// If no return ensure row count is consistent, 0 if any 0, otherwise first number.
if (result == null) {
result = object;
} else {
if (object instanceof Integer) {
if (((Integer)result).intValue() != 0) {
if (((Integer)object).intValue() != 0) {
result = object;
}
}
}
}
} else {
// Either a set of rows (union), or cursor (return).
if (result == null) {
result = object;
} else {
if (object instanceof List) {
((List)result).addAll((List)object);
} else {
break; // Not sure what to do, so break (if a cursor, don't only want to open one cursor.
}
}
}
}
if (exception != null) {
throw exception;
}
}
return result;
}
/**
* INTERNAL:
*/
public ExposedNodeLinkedList getActiveCommandThreads() {
if (activeCommandThreads == null) {
activeCommandThreads = new ExposedNodeLinkedList();
}
return activeCommandThreads;
}
/**
* PUBLIC:
* Return the active session for the current active external (JTS) transaction.
* This should only be used with JTS and will return the session if no external transaction exists.
*/
public org.eclipse.persistence.sessions.Session getActiveSession() {
org.eclipse.persistence.sessions.Session activeSession = getActiveUnitOfWork();
if (activeSession == null) {
activeSession = this;
}
return activeSession;
}
/**
* PUBLIC:
* Return the active unit of work for the current active external (JTS) transaction.
* This should only be used with JTS and will return null if no external transaction exists.
*/
public org.eclipse.persistence.sessions.UnitOfWork getActiveUnitOfWork() {
if (hasExternalTransactionController()) {
return getExternalTransactionController().getActiveUnitOfWork();
}
/* Steven Vo: CR# 2517
Get from the server session since the external transaction controller could be
null out from the client session by TL WebLogic 5.1 to provide non-jts transaction
operations
*/
if (isClientSession()) {
return ((org.eclipse.persistence.sessions.server.ClientSession)this).getParent().getActiveUnitOfWork();
}
return null;
}
/**
* INTERNAL:
* Returns the alias descriptors Map.
*/
public Map getAliasDescriptors() {
return project.getAliasDescriptors();
}
/**
* ADVANCED:
* Answers the past time this session is as of. Indicates whether or not this
* is a special historical session where all objects are read relative to a
* particular point in time.
* @return An immutable object representation of the past time.
* <code>null</code> if no clause set, or this a regular session.
* @see #acquireHistoricalSession(org.eclipse.persistence.history.AsOfClause)
*/
public AsOfClause getAsOfClause() {
return null;
}
/**
* INTERNAL:
* Allow the session to be used from a session broker.
*/
public AbstractSession getBroker() {
return broker;
}
/**
* INTERNAL:
* The session that this query is executed against when not in transaction.
* The session containing the shared identity map.
* <p>
* In most cases this is the root ServerSession or DatabaseSession.
* <p>
* In cases where objects are not to be cached in the global identity map
* an alternate session may be returned:
* <ul>
* <li>A ClientSession if in transaction
* <li>An isolated ClientSession or HistoricalSession
* <li>A registered session of a root SessionBroker
* </ul>
*/
public AbstractSession getRootSession(DatabaseQuery query) {
ClassDescriptor descriptor = null;
if (query != null){
descriptor = query.getDescriptor();
}
return getParentIdentityMapSession(descriptor, true, true);
}
/**
* INTERNAL:
* Gets the parent session.
*/
public AbstractSession getParent() {
return null;
}
/**
* INTERNAL:
* Gets the next link in the chain of sessions followed by a query's check
* early return, the chain of sessions with identity maps all the way up to
* the root session.
*/
public AbstractSession getParentIdentityMapSession(DatabaseQuery query) {
ClassDescriptor descriptor = null;
if (query != null){
descriptor = query.getDescriptor();
}
return getParentIdentityMapSession(descriptor, false, false);
}
/**
* INTERNAL:
* Gets the next link in the chain of sessions followed by a query's check
* early return, the chain of sessions with identity maps all the way up to
* the root session.
* <p>
* Used for session broker which delegates to registered sessions, or UnitOfWork
* which checks parent identity map also.
* @param canReturnSelf true when method calls itself. If the path
* starting at <code>this</code> is acceptable. Sometimes true if want to
* move to the first valid session, i.e. executing on ClientSession when really
* should be on ServerSession.
* @param terminalOnly return the session we will execute the call on, not
* the next step towards it.
* @return this if there is no next link in the chain
*/
public AbstractSession getParentIdentityMapSession(DatabaseQuery query, boolean canReturnSelf, boolean terminalOnly) {
ClassDescriptor descriptor = null;
if (query != null){
descriptor = query.getDescriptor();
}
return getParentIdentityMapSession(descriptor, canReturnSelf, terminalOnly);
}
/**
* INTERNAL:
* Returns the appropriate IdentityMap session for this descriptor. Sessions can be
* chained and each session can have its own Cache/IdentityMap. Entities can be stored
* at different levels based on Cache Isolation. This method will return the correct Session
* for a particular Entity class based on the Isolation Level and the attributes provided.
* <p>
* @param canReturnSelf true when method calls itself. If the path
* starting at <code>this</code> is acceptable. Sometimes true if want to
* move to the first valid session, i.e. executing on ClientSession when really
* should be on ServerSession.
* @param terminalOnly return the last session in the chain where the Enitity is stored.
* @return Session with the required IdentityMap
*/
public AbstractSession getParentIdentityMapSession(ClassDescriptor descriptor, boolean canReturnSelf, boolean terminalOnly) {
return this;
}
/**
* INTERNAL:
* Returns the default pessimistic lock timeout value.
*/
public Integer getPessimisticLockTimeoutDefault() {
return pessimisticLockTimeoutDefault;
}
/**
* PUBLIC:
* Return the default query timeout for this session.
* This timeout will apply to any queries that do not have a timeout set,
* and that do not have a default timeout defined in their descriptor.
*/
public int getQueryTimeoutDefault() {
return queryTimeoutDefault;
}
public TimeUnit getQueryTimeoutUnitDefault() {
return queryTimeoutUnitDefault;
}
public EntityListenerInjectionManager getEntityListenerInjectionManager() {
if (entityListenerInjectionManager == null){
entityListenerInjectionManager = createEntityListenerInjectionManager(this.getProperty(PersistenceUnitProperties.CDI_BEANMANAGER));
}
return entityListenerInjectionManager;
}
/**
* INTERNAL:
* Gets the session which this query will be executed on.
* Generally will be called immediately before the call is translated,
* which is immediately before session.executeCall.
* <p>
* Since the execution session also knows the correct datasource platform
* to execute on, it is often used in the mappings where the platform is
* needed for type conversion, or where calls are translated.
* <p>
* Is also the session with the accessor. Will return a ClientSession if
* it is in transaction and has a write connection.
* @return a session with a live accessor
* @param query may store session name or reference class for brokers case
*/
public AbstractSession getExecutionSession(DatabaseQuery query) {
return this;
}
/**
* INTERNAL:
* Return if the commit manager has been set.
*/
public boolean hasCommitManager() {
return commitManager != null;
}
/**
* INTERNAL:
* The commit manager is used to resolve referential integrity on commits of multiple objects.
* All brokered sessions share the same commit manager.
*/
public CommitManager getCommitManager() {
if (hasBroker()) {
return getBroker().getCommitManager();
}
// PERF: lazy init, not always required, not required for client sessions
if (commitManager == null) {
commitManager = new CommitManager(this);
}
return commitManager;
}
/**
* INTERNAL:
* Returns the set of read-only classes that gets assigned to each newly created UnitOfWork.
*
* @see org.eclipse.persistence.sessions.Project#setDefaultReadOnlyClasses(Vector)
*/
public Vector getDefaultReadOnlyClasses() {
//Bug#3911318 All brokered sessions share the same DefaultReadOnlyClasses.
if (hasBroker()) {
return getBroker().getDefaultReadOnlyClasses();
}
return getProject().getDefaultReadOnlyClasses();
}
/**
* ADVANCED:
* Return the descriptor specified for the class.
* If the class does not have a descriptor but implements an interface that is also implemented
* by one of the classes stored in the map, that descriptor will be stored under the
* new class. If a descriptor does not exist for the Class parameter, null is returned.
* If the passed Class parameter is null, then null will be returned.
*/
public ClassDescriptor getClassDescriptor(Class theClass) {
if (theClass == null) {
return null;
}
return getDescriptor(theClass);
}
/**
* ADVANCED:
* Return the descriptor specified for the object's class.
* If a descriptor does not exist for the Object parameter, null is returned.
* If the passed Object parameter is null, then null will be returned.
*/
public ClassDescriptor getClassDescriptor(Object domainObject) {
if (domainObject == null) {
return null;
}
return getDescriptor(domainObject);
}
/**
* PUBLIC:
* Return the descriptor for the alias.
* UnitOfWork delegates this to the parent
*/
public ClassDescriptor getClassDescriptorForAlias(String alias) {
return project.getDescriptorForAlias(alias);
}
/**
* ADVANCED:
* Return the descriptor specified for the class.
* If the class does not have a descriptor but implements an interface that is also implemented
* by one of the classes stored in the map, that descriptor will be stored under the
* new class. If the passed Class is null, null will be returned.
*/
public ClassDescriptor getDescriptor(Class theClass) {
if (theClass == null) {
return null;
}
// Optimize descriptor lookup through caching the last one accessed.
ClassDescriptor descriptor = this.lastDescriptorAccessed;
if ((descriptor != null) && (descriptor.getJavaClass() == theClass)) {
return descriptor;
}
if (this.descriptors != null) {
descriptor = this.descriptors.get(theClass);
} else {
descriptor = this.project.getDescriptors().get(theClass);
}
if (descriptor == null) {
if (hasBroker()) {
// Also check the broker
descriptor = getBroker().getDescriptor(theClass);
}
if (descriptor == null) {
// Allow for an event listener to lazy register the descriptor for a class.
if (this.eventManager != null) {
this.eventManager.missingDescriptor(theClass);
}
descriptor = getDescriptors().get(theClass);
if (descriptor == null) {
// This allows for the correct descriptor to be found if the class implements an interface,
// or extends a class that a descriptor is registered for.
// This is used by EJB to find the descriptor for a stub and remote to unwrap it,
// and by inheritance to allow for subclasses that have no additional state to not require a descriptor.
if (!theClass.isInterface()) {
Class[] interfaces = theClass.getInterfaces();
for (int index = 0; index < interfaces.length; ++index) {
Class interfaceClass = interfaces[index];
descriptor = getDescriptor(interfaceClass);
if (descriptor != null) {
getDescriptors().put(interfaceClass, descriptor);
break;
}
}
if (descriptor == null ) {
descriptor = checkHierarchyForDescriptor(theClass);
}
}
}
}
}
// Cache for optimization.
this.lastDescriptorAccessed = descriptor;
return descriptor;
}
/**
* ADVANCED:
* Return the descriptor specified for the object's class.
* If the passed Object is null, null will be returned.
*/
public ClassDescriptor getDescriptor(Object domainObject) {
if (domainObject == null) {
return null;
}
//Bug#3947714 Check and trigger the proxy here
if (this.project.hasProxyIndirection()) {
return getDescriptor(ProxyIndirectionPolicy.getValueFromProxy(domainObject).getClass());
}
return getDescriptor(domainObject.getClass());
}
/**
* PUBLIC:
* Return the descriptor for the alias.
* @param alias The descriptor alias.
* @param The descriptor for the alias or {@code null} if no descriptor was found.
*/
@Override
public ClassDescriptor getDescriptorForAlias(final String alias) {
// If we have a descriptors list return our sessions descriptor and
// not that of the project since we may be dealing with a multitenant
// descriptor which will have been initialized locally on the session.
// The project descriptor will be not initialized.
final ClassDescriptor desc = project.getDescriptorForAlias(alias);
if (desc != null && desc.hasMultitenantPolicy() && this.descriptors != null) {
return this.descriptors.get(desc.getJavaClass());
} else {
return desc;
}
}
/**
* ADVANCED:
* Return all registered descriptors.
*/
@Override
public Map<Class, ClassDescriptor> getDescriptors() {
return this.project.getDescriptors();
}
/**
* INTERNAL:
* Return if an event manager has been set.
*/
public boolean hasEventManager() {
return eventManager != null;
}
/**
* PUBLIC:
* Return the event manager.
* The event manager can be used to register for various session events.
*/
public SessionEventManager getEventManager() {
if (eventManager == null) {
synchronized (this) {
if (eventManager == null) {
// PERF: lazy init.
eventManager = new SessionEventManager(this);
}
}
}
return eventManager;
}
/**
* INTERNAL:
* Return a string which represents my ExceptionHandler's class
* Added for F2104: Properties.xml
* - gn
*/
public String getExceptionHandlerClass() {
String className = null;
try {
className = getExceptionHandler().getClass().getName();
} catch (Exception exception) {
return null;
}
return className;
}
/**
* PUBLIC:
* Return the ExceptionHandler.Exception handler can catch errors that occur on queries or during database access.
*/
public ExceptionHandler getExceptionHandler() {
return exceptionHandler;
}
/**
* PUBLIC:
* Used for JTS integration. If your application requires to have JTS control transactions instead of EclipseLink an
* external transaction controller must be specified.
* EclipseLink provides JTS controllers for several JTS implementations including JTS 1.0, Weblogic 5.1 and WebSphere 3.0.
*
* @see org.eclipse.persistence.transaction.JTATransactionController
*/
public ExternalTransactionController getExternalTransactionController() {
return externalTransactionController;
}
/**
* PUBLIC:
* The IdentityMapAccessor is the preferred way of accessing IdentityMap funcitons
* This will return an object which implements an interface which exposes all public
* IdentityMap functions.
*/
public org.eclipse.persistence.sessions.IdentityMapAccessor getIdentityMapAccessor() {
return identityMapAccessor;
}
/**
* INTERNAL:
* Return the internally available IdentityMapAccessor instance.
*/
public org.eclipse.persistence.internal.sessions.IdentityMapAccessor getIdentityMapAccessorInstance() {
return identityMapAccessor;
}
/**
* PUBLIC:
* Returns the integrityChecker.IntegrityChecker holds all the ClassDescriptor Exceptions.
*/
public IntegrityChecker getIntegrityChecker() {
// BUG# 2700595 - Lazily create an IntegrityChecker if one has not already been created.
if (integrityChecker == null) {
integrityChecker = new IntegrityChecker();
}
return integrityChecker;
}
/**
* ADVANCED:
* Return all pre-defined not yet parsed JPQL queries.
*/
public List<DatabaseQuery> getJPAQueries() {
return getProject().getJPAQueries();
}
/**
* ADVANCED:
* Return all pre-defined not yet parsed JPQL queries.
*/
public List<DatabaseQuery> getJPATablePerTenantQueries() {
return getProject().getJPATablePerTenantQueries();
}
/**
* PUBLIC:
* Return the writer to which an accessor writes logged messages and SQL.
* If not set, this reference defaults to a writer on System.out.
* To enable logging, logMessages must be turned on.
*
* @see #logMessages()
*/
public Writer getLog() {
return getSessionLog().getWriter();
}
/**
* INTERNAL:
* Return the name of the session: class name + system hashcode.
* <p>
* This should be the implementation of toString(), and also the
* value should be calculated in the constructor for it is used all the
* time. However everything is lazily initialized now and the value is
* transient for the system hashcode could vary?
*/
public String getLogSessionString() {
if (logSessionString == null) {
StringWriter writer = new StringWriter();
writer.write(getSessionTypeString());
writer.write("(");
writer.write(String.valueOf(System.identityHashCode(this)));
writer.write(")");
logSessionString = writer.toString();
}
return logSessionString;
}
/**
* INTERNAL:
* Returns the type of session, its class.
* <p>
* Override to hide from the user when they are using an internal subclass
* of a known class.
* <p>
* A user does not need to know that their UnitOfWork is a
* non-deferred UnitOfWork, or that their ClientSession is an
* IsolatedClientSession.
*/
public String getSessionTypeString() {
return Helper.getShortClassName(getClass());
}
/**
* INTERNAL:
* Return the static metamodel class associated with the given model class
* if available. Callers must handle null.
*/
public String getStaticMetamodelClass(String modelClassName) {
if (staticMetamodelClasses != null) {
return staticMetamodelClasses.get(modelClassName);
}
return null;
}
/**
* OBSOLETE:
* Return the login, the login holds any database connection information given.
* This has been replaced by getDatasourceLogin to make use of the Login interface
* to support non-relational datasources,
* if DatabaseLogin API is required it will need to be cast.
*/
public DatabaseLogin getLogin() {
try {
return (DatabaseLogin)getDatasourceLogin();
} catch (ClassCastException wrongType) {
throw ValidationException.notSupportedForDatasource();
}
}
/**
* PUBLIC:
* Return the login, the login holds any database connection information given.
* This return the Login interface and may need to be cast to the datasource specific implementation.
*/
public Login getDatasourceLogin() {
if (this.project == null) {
return null;
}
return this.project.getDatasourceLogin();
}
/**
* INTERNAL:
* Return the mapped superclass descriptor if one exists for the given
* class name. Must check any broker as well.
*/
public ClassDescriptor getMappedSuperclass(String className) {
ClassDescriptor desc = getProject().getMappedSuperclass(className);
if (desc == null && hasBroker()) {
getBroker().getMappedSuperclass(className);
}
return desc;
}
/**
* PUBLIC:
* Return a set of multitenant context properties this session
*/
public Set<String> getMultitenantContextProperties() {
if (this.multitenantContextProperties == null) {
this.multitenantContextProperties = new HashSet<String>();
}
return this.multitenantContextProperties;
}
/**
* PUBLIC:
* Return the name of the session.
* This is used with the session broker, or to give the session a more meaningful name.
*/
public String getName() {
return name;
}
/**
* ADVANCED:
* Return the sequnce number from the database
*/
public Number getNextSequenceNumberValue(Class domainClass) {
return (Number)getSequencing().getNextValue(domainClass);
}
/**
* INTERNAL:
* Return the number of units of work connected.
*/
public int getNumberOfActiveUnitsOfWork() {
return numberOfActiveUnitsOfWork;
}
/**
* INTERNAL:
* For use within the merge process this method will get an object from the shared
* cache using a readlock. If a readlock is unavailable then the merge manager will be
* transitioned to deferred locks and a deferred lock will be used.
*/
protected CacheKey getCacheKeyFromTargetSessionForMerge(Object implementation, ObjectBuilder builder, ClassDescriptor descriptor, MergeManager mergeManager){
Object original = null;
Object primaryKey = builder.extractPrimaryKeyFromObject(implementation, this, true);
if (primaryKey == null) {
return null;
}
CacheKey cacheKey = null;
if (mergeManager == null){
cacheKey = getIdentityMapAccessorInstance().getCacheKeyForObject(primaryKey, implementation.getClass(), descriptor, true);
if (cacheKey != null){
cacheKey.checkReadLock();
}
return cacheKey;
}
cacheKey = getIdentityMapAccessorInstance().getCacheKeyForObject(primaryKey, implementation.getClass(), descriptor, true);
if (cacheKey != null) {
if (cacheKey.acquireReadLockNoWait()) {
original = cacheKey.getObject();
cacheKey.releaseReadLock();
} else {
if (!mergeManager.isTransitionedToDeferredLocks()) {
getIdentityMapAccessorInstance().getWriteLockManager().transitionToDeferredLocks(mergeManager);
}
cacheKey.acquireDeferredLock();
original = cacheKey.getObject();
if (original == null) {
synchronized (cacheKey) {
if (cacheKey.isAcquired()) {
try {
cacheKey.wait();
} catch (InterruptedException e) {
//ignore and return
}
}
original = cacheKey.getObject();
}
}
cacheKey.releaseDeferredLock();
}
}
return cacheKey;
}
/**
* INTERNAL:
* Return the database platform currently connected to.
* The platform is used for database specific behavior.
* NOTE: this must only be used for relational specific usage,
* it will fail for non-relational datasources.
*/
public DatabasePlatform getPlatform() {
// PERF: Cache the platform.
if (platform == null) {
platform = getDatasourceLogin().getPlatform();
}
return (DatabasePlatform)platform;
}
/**
* INTERNAL:
* Return the class loader for the session's application.
* This loader should be able to load any application or EclipseLink class.
*/
public ClassLoader getLoader() {
return getDatasourcePlatform().getConversionManager().getLoader();
}
/**
* INTERNAL:
* Return the database platform currently connected to.
* The platform is used for database specific behavior.
*/
@Override
public Platform getDatasourcePlatform() {
// PERF: Cache the platform.
if (platform == null) {
platform = getDatasourceLogin().getDatasourcePlatform();
}
return platform;
}
/**
* INTERNAL:
* Marked internal as this is not customer API but helper methods for
* accessing the server platform from within EclipseLink's other sessions types
* (ie not DatabaseSession)
*/
public ServerPlatform getServerPlatform() {
return null;
}
/**
* INTERNAL:
* Return the database platform currently connected to
* for specified class.
* The platform is used for database specific behavior.
*/
@Override
public Platform getPlatform(Class domainClass) {
// PERF: Cache the platform.
if (platform == null) {
platform = getDatasourcePlatform();
}
return platform;
}
/**
* PUBLIC:
* Return the profiler.
* The profiler is a tool that can be used to determine performance bottlenecks.
* The profiler can be queries to print summaries and configure for logging purposes.
*/
public SessionProfiler getProfiler() {
return profiler;
}
/**
* PUBLIC:
* Return the project, the project holds configuartion information including the descriptors.
*/
public org.eclipse.persistence.sessions.Project getProject() {
return project;
}
/**
* ADVANCED:
* Allow for user defined properties.
*/
public Map getProperties() {
if (properties == null) {
properties = new HashMap(5);
}
return properties;
}
/**
* INTERNAL:
* Allow to check for user defined properties.
*/
public boolean hasProperties() {
return ((properties != null) && !properties.isEmpty());
}
/**
* INTERNAL:
* Return list of table per tenant multitenant descriptors.
*/
public boolean hasTablePerTenantDescriptors() {
return (tablePerTenantDescriptors != null && ! tablePerTenantDescriptors.isEmpty());
}
/**
* INTERNAL:
* Return a list of table per tenant multitenant queries.
*/
public boolean hasTablePerTenantQueries() {
return (tablePerTenantQueries != null && ! tablePerTenantQueries.isEmpty());
}
/**
* ADVANCED:
* Returns the user defined property.
*/
public Object getProperty(String name) {
if(this.properties==null){
return null;
}
return getProperties().get(name);
}
/**
* ADVANCED:
* Return all pre-defined queries.
*/
public Map<String, List<DatabaseQuery>> getQueries() {
// PERF: lazy init, not normally required.
if (queries == null) {
queries = new HashMap(5);
}
return queries;
}
/**
* ADVANCED:
* Return an attribute group of a particular name.
*/
/**
* ADVANCED
* Return all predefined attribute groups
*/
public Map<String, AttributeGroup> getAttributeGroups(){
if (this.attributeGroups == null){
this.attributeGroups = new HashMap<String, AttributeGroup>(5);
}
return this.attributeGroups;
}
/**
* INTERNAL:
* Return the pre-defined queries in this session.
* A single vector containing all the queries is returned.
*
* @see #getQueries()
*/
public List<DatabaseQuery> getAllQueries() {
Vector allQueries = new Vector();
for (Iterator vectors = getQueries().values().iterator(); vectors.hasNext();) {
allQueries.addAll((Vector)vectors.next());
}
return allQueries;
}
/**
* PUBLIC:
* Return the query from the session pre-defined queries with the given name.
* This allows for common queries to be pre-defined, reused and executed by name.
*/
public DatabaseQuery getQuery(String name) {
return getQuery(name, null);
}
/**
* PUBLIC:
* Return the query from the session pre-defined queries with the given name and argument types.
* This allows for common queries to be pre-defined, reused and executed by name.
* This method should be used if the Session has multiple queries with the same name but
* different arguments.
*
* @see #getQuery(String)
*/
public DatabaseQuery getQuery(String name, List arguments) {
if (arguments instanceof Vector) {
return getQuery(name, (Vector)arguments);
} else {
return getQuery(name, new Vector(arguments));
}
}
/**
* PUBLIC:
* Return the query from the session pre-defined queries with the given name and argument types.
* This allows for common queries to be pre-defined, reused and executed by name.
* This method should be used if the Session has multiple queries with the same name but
* different arguments.
*
* @see #getQuery(String)
*/
public DatabaseQuery getQuery(String name, Vector arguments) {
return getQuery(name, arguments, true);
}
/**
* INTERNAL:
* Return the query from the session pre-defined queries with the given name and argument types.
* This allows for common queries to be pre-defined, reused and executed by name.
* This method should be used if the Session has multiple queries with the same name but
* different arguments.
*
* @parameter shouldSearchParent indicates whether parent should be searched if query not found.
* @see #getQuery(String, arguments)
*/
public DatabaseQuery getQuery(String name, Vector arguments, boolean shouldSearchParent) {
Vector queries = (Vector)getQueries().get(name);
if ((queries != null) && !queries.isEmpty()) {
// Short circuit the simple, most common case of only one query.
if (queries.size() == 1) {
return (DatabaseQuery)queries.firstElement();
}
// CR#3754; Predrag; mar 19/2002;
// We allow multiple named queries with the same name but
// different argument set; we can have only one query with
// no arguments; Vector queries is not sorted;
// When asked for the query with no parameters the
// old version did return the first query - wrong:
// return (DatabaseQuery) queries.firstElement();
int argumentTypesSize = 0;
if (arguments != null) {
argumentTypesSize = arguments.size();
}
Vector argumentTypes = new Vector(argumentTypesSize);
for (int i = 0; i < argumentTypesSize; i++) {
argumentTypes.addElement(arguments.elementAt(i).getClass());
}
for (Enumeration queriesEnum = queries.elements(); queriesEnum.hasMoreElements();) {
DatabaseQuery query = (DatabaseQuery)queriesEnum.nextElement();
if (Helper.areTypesAssignable(argumentTypes, query.getArgumentTypes())) {
return query;
}
}
}
if(shouldSearchParent) {
AbstractSession parent = getParent();
if(parent != null) {
return parent.getQuery(name, arguments, true);
}
}
return null;
}
/**
* Returns an AttributeGroup by name
*/
/**
* INTERNAL:
* Return the Sequencing object used by the session.
*/
public Sequencing getSequencing() {
return null;
}
/**
* INTERNAL:
* Return the session to be used for the class.
* Used for compatibility with the session broker.
*/
public AbstractSession getSessionForClass(Class domainClass) {
if (hasBroker()) {
return getBroker().getSessionForClass(domainClass);
}
return this;
}
/**
* INTERNAL:
* Return the session by name.
* Used for compatibility with the session broker.
*/
public AbstractSession getSessionForName(String name) throws ValidationException {
if (hasBroker()) {
return getBroker().getSessionForName(name);
}
return this;
}
/**
* PUBLIC:
* Return the session log to which an accessor logs messages and SQL.
* If not set, this will default to a session log on a writer on System.out.
* To enable logging, logMessages must be turned on.
*
* @see #logMessages()
*/
public SessionLog getSessionLog() {
if (sessionLog == null) {
setSessionLog(new DefaultSessionLog());
}
return sessionLog;
}
/**
* INTERNAL:
* Return list of table per tenant multitenant descriptors.
*/
public List<ClassDescriptor> getTablePerTenantDescriptors() {
if (tablePerTenantDescriptors == null) {
tablePerTenantDescriptors = new ArrayList<ClassDescriptor>();
}
return tablePerTenantDescriptors;
}
/**
* INTERNAL:
* Return list of table per tenant multitenant descriptors.
*/
public List<DatabaseQuery> getTablePerTenantQueries() {
if (tablePerTenantQueries == null) {
tablePerTenantQueries = new ArrayList<DatabaseQuery>();
}
return tablePerTenantQueries;
}
/**
* INTERNAL:
* The transaction mutex ensure mutual exclusion on transaction across multiple threads.
*/
public ConcurrencyManager getTransactionMutex() {
// PERF: not always required, defer.
if (transactionMutex == null) {
synchronized (this) {
if (transactionMutex == null) {
transactionMutex = new ConcurrencyManager();
}
}
}
return transactionMutex;
}
/**
* PUBLIC:
* Allow any WARNING level exceptions that occur within EclipseLink to be logged and handled by the exception handler.
*/
public Object handleException(RuntimeException exception) throws RuntimeException {
if ((exception instanceof EclipseLinkException)) {
EclipseLinkException eclipseLinkException = (EclipseLinkException)exception;
if (eclipseLinkException.getSession() == null) {
eclipseLinkException.setSession(this);
}
//Bug#3559280 Avoid logging an exception twice
if (!eclipseLinkException.hasBeenLogged()) {
logThrowable(SessionLog.WARNING, null, exception);
eclipseLinkException.setHasBeenLogged(true);
}
} else {
logThrowable(SessionLog.WARNING, null, exception);
}
if (hasExceptionHandler()) {
if (this.broker != null && this.broker.hasExceptionHandler()) {
try {
return getExceptionHandler().handleException(exception);
} catch (RuntimeException ex) {
// handle the original exception
return this.broker.getExceptionHandler().handleException(exception);
}
} else {
return getExceptionHandler().handleException(exception);
}
} else {
if (this.broker != null && this.broker.hasExceptionHandler()) {
return this.broker.getExceptionHandler().handleException(exception);
} else {
throw exception;
}
}
}
/**
* INTERNAL:
* Allow the session to be used from a session broker.
*/
public boolean hasBroker() {
return broker != null;
}
/**
* ADVANCED:
* Return true if a descriptor exists for the given class.
*/
public boolean hasDescriptor(Class theClass) {
if (theClass == null) {
return false;
}
return getDescriptors().get(theClass) != null;
}
/**
* PUBLIC:
* Return if an exception handler is present.
*/
public boolean hasExceptionHandler() {
if (exceptionHandler == null) {
return false;
}
return true;
}
/**
* PUBLIC:
* Used for JTA integration. If your application requires to have JTA control transactions instead of EclipseLink an
* external transaction controler must be specified. EclipseLink provides JTA controlers for JTA 1.0 and application
* servers.
* @see org.eclipse.persistence.transaction.JTATransactionController
*/
public boolean hasExternalTransactionController() {
return externalTransactionController != null;
}
/**
* INTERNAL:
* Set up the IdentityMapManager. This method allows subclasses of Session to override
* the default IdentityMapManager functionality.
*/
public void initializeIdentityMapAccessor() {
this.identityMapAccessor = new org.eclipse.persistence.internal.sessions.IdentityMapAccessor(this, new IdentityMapManager(this));
}
/**
* PUBLIC:
* Insert the object and all of its privately owned parts into the database.
* Insert should only be used if the application knows that the object is new,
* otherwise writeObject should be used.
* The insert operation can be customized through using an insert query.
*
* @exception DatabaseException if an error occurs on the database,
* these include constraint violations, security violations and general database errors.
*
* @see InsertObjectQuery
* @see #writeObject(Object)
*/
public Object insertObject(Object domainObject) throws DatabaseException {
InsertObjectQuery query = new InsertObjectQuery();
query.setObject(domainObject);
query.setIsExecutionClone(true);
return executeQuery(query);
}
/**
* INTERNAL:
* Return the results from exeucting the database query.
* The arguments should be a database row with raw data values.
* This method is provided to allow subclasses to change the default querying behavior.
* All querying goes through this method.
*/
public Object internalExecuteQuery(DatabaseQuery query, AbstractRecord databaseRow) throws DatabaseException {
return query.execute(this, databaseRow);
}
/**
* INTERNAL:
* Returns true if the session is a session Broker.
*/
public boolean isBroker() {
return false;
}
/**
* INTERNAL:
* Returns true if the session is in a session Broker.
*/
public boolean isInBroker() {
return isInBroker;
}
/**
* PUBLIC:
* Return if the class is defined as read-only.
*/
public boolean isClassReadOnly(Class theClass) {
ClassDescriptor descriptor = getDescriptor(theClass);
return isClassReadOnly(theClass, descriptor);
}
/**
* INTERNAL:
* Return if the class is defined as read-only.
* PERF: Pass descriptor to avoid re-lookup.
*/
public boolean isClassReadOnly(Class theClass, ClassDescriptor descriptor) {
if ((descriptor != null) && descriptor.shouldBeReadOnly()) {
return true;
}
if (theClass != null) {
return getDefaultReadOnlyClasses().contains(theClass);
}
return false;
}
/**
* PUBLIC:
* Return if this session is a client session.
*/
public boolean isClientSession() {
return false;
}
/**
* PUBLIC:
* Return if this session is an isolated client session.
*/
public boolean isIsolatedClientSession() {
return false;
}
/**
* PUBLIC:
* Return if this session is an exclusive isolated client session.
*/
public boolean isExclusiveIsolatedClientSession() {
return false;
}
/**
* PUBLIC:
* Return if this session is connected to the database.
*/
public boolean isConnected() {
if (getAccessor() == null) {
return false;
}
return getAccessor().isConnected();
}
/**
* PUBLIC:
* Return if this session is a database session.
*/
public boolean isDatabaseSession() {
return false;
}
/**
* PUBLIC:
* Return if this session is a distributed session.
*/
public boolean isDistributedSession() {
return false;
}
/**
* PUBLIC:
* Return if a profiler is being used.
*/
public boolean isInProfile() {
return isInProfile;
}
/**
* PUBLIC:
* Allow for user deactive a profiler
*/
public void setIsInProfile(boolean inProfile) {
this.isInProfile = inProfile;
}
/**
* INTERNAL:
* Set if this session is contained in a SessionBroker.
*/
public void setIsInBroker(boolean isInBroker) {
this.isInBroker = isInBroker;
}
/**
* PUBLIC:
* Return if this session's decendants should use finalizers.
* The allows certain finalizers such as in ClientSession to be enabled.
* These are disable by default for performance reasons.
*/
public boolean isFinalizersEnabled() {
return isFinalizersEnabled;
}
/**
* INTERNAL:
* Register a finalizer to release this session.
*/
public void registerFinalizer() {
// Ensure the finalizer is referenced until the session is gc'd.
setProperty("finalizer", new SessionFinalizer(this));
}
/**
* INTERNAL:
* Return if this session is a historical session.
*/
public boolean isHistoricalSession() {
return false;
}
/**
* PUBLIC:
* Set if this session's decendants should use finalizers.
* The allows certain finalizers such as in ClientSession to be enabled.
* These are disable by default for performance reasons.
*/
public void setIsFinalizersEnabled(boolean isFinalizersEnabled) {
this.isFinalizersEnabled = isFinalizersEnabled;
}
/**
* PUBLIC:
* Return if the session is currently in the progress of a database transaction.
* Because nested transactions are allowed check if the transaction mutex has been aquired.
*/
public boolean isInTransaction() {
return this.transactionMutex != null && this.transactionMutex.isAcquired();
}
/**
* INTERNAL:
* used to see if JPA Queries have been processed during initialization
*/
public boolean isJPAQueriesProcessed(){
return this.jpaQueriesProcessed;
}
/**
* PUBLIC:
* Returns true if Protected Entities should be built within this session
*/
public boolean isProtectedSession(){
return true;
}
/**
* PUBLIC:
* Return if this session is remote.
*/
public boolean isRemoteSession() {
return false;
}
/**
* PUBLIC:
* Return if this session is a unit of work.
*/
public boolean isRemoteUnitOfWork() {
return false;
}
/**
* PUBLIC:
* Return if this session is a server session.
*/
public boolean isServerSession() {
return false;
}
/**
* PUBLIC:
* Return if this session is a session broker.
*/
public boolean isSessionBroker() {
return false;
}
/**
* INTERNAL:
* Return if this session is synchronized.
*/
public boolean isSynchronized() {
return isSynchronized;
}
/**
* PUBLIC:
* Return if this session is a unit of work.
*/
public boolean isUnitOfWork() {
return false;
}
/**
* ADVANCED:
* Extract and return the primary key from the object.
*/
public Object getId(Object domainObject) throws ValidationException {
ClassDescriptor descriptor = getDescriptor(domainObject);
return keyFromObject(domainObject, descriptor);
}
/**
* ADVANCED:
* Extract and return the primary key from the object.
* @deprecated since EclipseLink 2.1, replaced by getId(Object)
* @see #getId(Object)
*/
@Deprecated
public Vector keyFromObject(Object domainObject) throws ValidationException {
ClassDescriptor descriptor = getDescriptor(domainObject);
return (Vector)keyFromObject(domainObject, descriptor);
}
/**
* ADVANCED:
* Extract and return the primary key from the object.
*/
public Object keyFromObject(Object domainObject, ClassDescriptor descriptor) throws ValidationException {
if (descriptor == null) {
throw ValidationException.missingDescriptor(domainObject.getClass().getName());
}
Object implemention = descriptor.getObjectBuilder().unwrapObject(domainObject, this);
if (implemention == null) {
return null;
}
return descriptor.getObjectBuilder().extractPrimaryKeyFromObject(implemention, this);
}
/**
* PUBLIC:
* Log the log entry.
*/
public void log(SessionLogEntry entry) {
if (this.isLoggingOff) {
return;
}
if (shouldLog(entry.getLevel(), entry.getNameSpace())) {
if (entry.getSession() == null) {// Used for proxy session.
entry.setSession(this);
}
getSessionLog().log(entry);
}
}
/**
* Log a untranslated message to the EclipseLink log at FINER level.
*/
public void logMessage(String message) {
if (this.isLoggingOff) {
return;
}
log(SessionLog.FINER, SessionLog.MISC, message, (Object[])null, null, false);
}
/**
* INTERNAL:
* A call back to do session specific preparation of a query.
* <p>
* The call back occurs soon before we clone the query for execution,
* meaning that if this method needs to clone the query then the caller will
* determine that it doesn't need to clone the query itself.
*/
public DatabaseQuery prepareDatabaseQuery(DatabaseQuery query) {
if (!isUnitOfWork() && query.isObjectLevelReadQuery()) {
return ((ObjectLevelReadQuery)query).prepareOutsideUnitOfWork(this);
} else {
return query;
}
}
/**
* PUBLIC:
* Read all of the instances of the class from the database.
* This operation can be customized through using a ReadAllQuery,
* or through also passing in a selection criteria.
*
* @see ReadAllQuery
* @see #readAllObjects(Class, Expression)
*/
public Vector readAllObjects(Class domainClass) throws DatabaseException {
ReadAllQuery query = new ReadAllQuery();
query.setIsExecutionClone(true);
query.setReferenceClass(domainClass);
return (Vector)executeQuery(query);
}
/**
* PUBLIC:
* Read all of the instances of the class from the database return through execution the SQL string.
* The SQL string must be a valid SQL select statement or selecting stored procedure call.
* This operation can be customized through using a ReadAllQuery.
* Warning: Allowing an unverified SQL string to be passed into this
* method makes your application vulnerable to SQL injection attacks.
*
* @see ReadAllQuery
*/
public Vector readAllObjects(Class domainClass, String sqlString) throws DatabaseException {
ReadAllQuery query = new ReadAllQuery();
query.setReferenceClass(domainClass);
query.setSQLString(sqlString);
query.setIsExecutionClone(true);
return (Vector)executeQuery(query);
}
/**
* PUBLIC:
* Read all the instances of the class from the database returned through execution the Call string.
* The Call can be an SQLCall or JPQLCall.
*
* example: session.readAllObjects(Employee.class, new SQLCall("SELECT * FROM EMPLOYEE"));
* @see Call
*/
public Vector readAllObjects(Class referenceClass, Call aCall) throws DatabaseException {
ReadAllQuery raq = new ReadAllQuery();
raq.setReferenceClass(referenceClass);
raq.setCall(aCall);
raq.setIsExecutionClone(true);
return (Vector)executeQuery(raq);
}
/**
* PUBLIC:
* Read all of the instances of the class from the database matching the given expression.
* This operation can be customized through using a ReadAllQuery.
*
* @see ReadAllQuery
*/
public Vector readAllObjects(Class domainClass, Expression expression) throws DatabaseException {
ReadAllQuery query = new ReadAllQuery();
query.setReferenceClass(domainClass);
query.setSelectionCriteria(expression);
query.setIsExecutionClone(true);
return (Vector)executeQuery(query);
}
/**
* PUBLIC:
* Read the first instance of the class from the database.
* This operation can be customized through using a ReadObjectQuery,
* or through also passing in a selection criteria.
*
* @see ReadObjectQuery
* @see #readAllObjects(Class, Expression)
*/
public Object readObject(Class domainClass) throws DatabaseException {
ReadObjectQuery query = new ReadObjectQuery();
query.setReferenceClass(domainClass);
query.setIsExecutionClone(true);
return executeQuery(query);
}
/**
* PUBLIC:
* Read the first instance of the class from the database return through execution the SQL string.
* The SQL string must be a valid SQL select statement or selecting stored procedure call.
* This operation can be customized through using a ReadObjectQuery.
* Warning: Allowing an unverified SQL string to be passed into this
* method makes your application vulnerable to SQL injection attacks.
*
* @see ReadObjectQuery
*/
public Object readObject(Class domainClass, String sqlString) throws DatabaseException {
ReadObjectQuery query = new ReadObjectQuery();
query.setReferenceClass(domainClass);
query.setSQLString(sqlString);
query.setIsExecutionClone(true);
return executeQuery(query);
}
/**
* PUBLIC:
* Read the first instance of the class from the database returned through execution the Call string.
* The Call can be an SQLCall or JPQLCall.
*
* example: session.readObject(Employee.class, new SQLCall("SELECT * FROM EMPLOYEE"));
* @see SQLCall
* @see JPQLCall
*/
public Object readObject(Class domainClass, Call aCall) throws DatabaseException {
ReadObjectQuery query = new ReadObjectQuery();
query.setReferenceClass(domainClass);
query.setCall(aCall);
query.setIsExecutionClone(true);
return executeQuery(query);
}
/**
* PUBLIC:
* Read the first instance of the class from the database matching the given expression.
* This operation can be customized through using a ReadObjectQuery.
*
* @see ReadObjectQuery
*/
public Object readObject(Class domainClass, Expression expression) throws DatabaseException {
ReadObjectQuery query = new ReadObjectQuery();
query.setReferenceClass(domainClass);
query.setSelectionCriteria(expression);
query.setIsExecutionClone(true);
return executeQuery(query);
}
/**
* PUBLIC:
* Use the example object to consruct a read object query by the objects primary key.
* This will read the object from the database with the same primary key as the object
* or null if no object is found.
*/
public Object readObject(Object object) throws DatabaseException {
ReadObjectQuery query = new ReadObjectQuery();
query.setSelectionObject(object);
query.setIsExecutionClone(true);
return executeQuery(query);
}
/**
* PUBLIC:
* Refresh the attributes of the object and of all of its private parts from the database.
* The object will be pessimisticly locked on the database for the duration of the transaction.
* If the object is already locked this method will wait until the lock is released.
* A no wait option is available through setting the lock mode.
* @see #refreshAndLockObject(Object, lockMode)
*/
public Object refreshAndLockObject(Object object) throws DatabaseException {
return refreshAndLockObject(object, ObjectBuildingQuery.LOCK);
}
/**
* PUBLIC:
* Refresh the attributes of the object and of all of its private parts from the database.
* The object will be pessimisticly locked on the database for the duration of the transaction.
* <p>Lock Modes: ObjectBuildingQuery.NO_LOCK, LOCK, LOCK_NOWAIT
*/
public Object refreshAndLockObject(Object object, short lockMode) throws DatabaseException {
ReadObjectQuery query = new ReadObjectQuery();
query.setSelectionObject(object);
query.refreshIdentityMapResult();
query.cascadePrivateParts();
query.setLockMode(lockMode);
query.setIsExecutionClone(true);
return executeQuery(query);
}
/**
* PUBLIC:
* Refresh the attributes of the object and of all of its private parts from the database.
* This can be used to ensure the object is up to date with the database.
* Caution should be used when using this to make sure the application has no un commited
* changes to the object.
*/
public Object refreshObject(Object object) throws DatabaseException {
return refreshAndLockObject(object, ObjectBuildingQuery.NO_LOCK);
}
/**
* PUBLIC:
* Release the session.
* This does nothing by default, but allows for other sessions such as the ClientSession to do something.
*/
public void release() {
}
/**
* INTERNAL:
* Release the unit of work, if lazy release the connection.
*/
public void releaseUnitOfWork(UnitOfWorkImpl unitOfWork) {
// Nothing is required by default, allow subclasses to do cleanup.
setNumberOfActiveUnitsOfWork(getNumberOfActiveUnitsOfWork() - 1);
}
/**
* PUBLIC:
* Remove the user defined property.
*/
public void removeProperty(String property) {
getProperties().remove(property);
}
/**
* PUBLIC:
* Remove all queries with the given queryName regardless of the argument types.
*
* @see #removeQuery(String, Vector)
*/
public void removeQuery(String queryName) {
getQueries().remove(queryName);
}
/**
* PUBLIC:
* Remove the specific query with the given queryName and argumentTypes.
*/
public void removeQuery(String queryName, Vector argumentTypes) {
Vector queries = (Vector)getQueries().get(queryName);
if (queries == null) {
return;
} else {
DatabaseQuery query = null;
for (Enumeration enumtr = queries.elements(); enumtr.hasMoreElements();) {
query = (DatabaseQuery)enumtr.nextElement();
if (Helper.areTypesAssignable(argumentTypes, query.getArgumentTypes())) {
break;
}
}
if (query != null) {
queries.remove(query);
}
}
}
/**
* PROTECTED:
* Attempts to rollback the running internally started external transaction.
* Returns true only in one case -
* extenal transaction has been internally rolled back during this method call:
* wasJTSTransactionInternallyStarted()==true in the beginning of this method and
* wasJTSTransactionInternallyStarted()==false in the end of this method.
*/
protected boolean rollbackExternalTransaction() {
boolean externalTransactionHasRolledBack = false;
if (hasExternalTransactionController() && wasJTSTransactionInternallyStarted()) {
try {
getExternalTransactionController().rollbackTransaction(this);
} catch (RuntimeException exception) {
handleException(exception);
}
if (!wasJTSTransactionInternallyStarted()) {
externalTransactionHasRolledBack = true;
log(SessionLog.FINER, SessionLog.TRANSACTION, "external_transaction_has_rolled_back_internally");
}
}
return externalTransactionHasRolledBack;
}
/**
* PUBLIC:
* Rollback the active database transaction.
* This allows a group of database modification to be commited or rolledback as a unit.
* All writes/deletes will be sent to the database be will not be visible to other users until commit.
* Although databases do not allow nested transaction,
* EclipseLink supports nesting through only committing to the database on the outer commit.
*
* @exception DatabaseException if the database connection is lost or the rollback fails.
* @exception ConcurrencyException if this session is not within a transaction.
*/
public void rollbackTransaction() throws DatabaseException, ConcurrencyException {
ConcurrencyManager mutex = getTransactionMutex();
// Ensure release of mutex and call subclass specific release.
try {
if (!mutex.isNested()) {
if (this.eventManager != null) {
this.eventManager.preRollbackTransaction();
}
basicRollbackTransaction();
if (this.eventManager != null) {
this.eventManager.postRollbackTransaction();
}
}
} finally {
mutex.release();
// If there is no db transaction in progress
// if there is an active external transaction
// which was started internally - it should be rolled back internally, too.
if (!mutex.isAcquired()) {
rollbackExternalTransaction();
}
}
}
/**
* INTERNAL:
* Set the accessor.
*/
public void setAccessor(Accessor accessor) {
this.accessors = new ArrayList(1);
this.accessors.add(accessor);
}
/**
* INTERNAL:
* Allow the session to be used from a session broker.
*/
public void setBroker(AbstractSession broker) {
this.broker = broker;
}
/**
* INTERNAL:
* The commit manager is used to resolve referncial integrity on commits of multiple objects.
*/
public void setCommitManager(CommitManager commitManager) {
this.commitManager = commitManager;
}
public void setEntityListenerInjectionManager(
EntityListenerInjectionManager entityListenerInjectionManager) {
this.entityListenerInjectionManager = entityListenerInjectionManager;
}
/**
* INTERNAL:
* Set the event manager.
* The event manager can be used to register for various session events.
*/
public void setEventManager(SessionEventManager eventManager) {
this.eventManager = eventManager;
if (eventManager != null) {
this.eventManager.setSession(this);
}
}
/**
* PUBLIC:
* Set the exceptionHandler.
* Exception handler can catch errors that occur on queries or during database access.
*/
public void setExceptionHandler(ExceptionHandler exceptionHandler) {
this.exceptionHandler = exceptionHandler;
}
/**
* Used for JTS integration internally by ServerPlatform.
*/
public void setExternalTransactionController(ExternalTransactionController externalTransactionController) {
this.externalTransactionController = externalTransactionController;
if (externalTransactionController == null) {
return;
}
if (!hasBroker()) {
externalTransactionController.setSession(this);
}
}
/**
* PUBLIC:
* set the integrityChecker. IntegrityChecker holds all the ClassDescriptor Exceptions.
*/
public void setIntegrityChecker(IntegrityChecker integrityChecker) {
this.integrityChecker = integrityChecker;
}
/**
* INTERNAL:
* used to set if JPA Queries have been processed during initialization
*/
public void setJPAQueriesProcessed(boolean jpaQueriesProcessed){
this.jpaQueriesProcessed = jpaQueriesProcessed;
}
/**
* PUBLIC:
* Set the writer to which an accessor writes logged messages and SQL.
* If not set, this reference defaults to a writer on System.out.
* To enable logging logMessages() is used.
*
* @see #logMessages()
*/
public void setLog(Writer log) {
getSessionLog().setWriter(log);
}
/**
* PUBLIC:
* Set the login.
*/
public void setLogin(DatabaseLogin login) {
setDatasourceLogin(login);
}
/**
* PUBLIC:
* Set the login.
*/
public void setLogin(Login login) {
setDatasourceLogin(login);
}
/**
* PUBLIC:
* Set the login.
*/
public void setDatasourceLogin(Login login) {
getProject().setDatasourceLogin(login);
this.platform = null;
}
/**
* PUBLIC:
* Set the name of the session.
* This is used with the session broker.
*/
public void setName(String name) {
this.name = name;
}
protected void setNumberOfActiveUnitsOfWork(int numberOfActiveUnitsOfWork) {
this.numberOfActiveUnitsOfWork = numberOfActiveUnitsOfWork;
}
/**
* PUBLIC:
* Set the default pessimistic lock timeout value. This value will be used
* to set the WAIT clause of a SQL SELECT FOR UPDATE statement. It defines
* how long EcliseLink should wait for a lock on the database row before
* aborting.
*/
public void setPessimisticLockTimeoutDefault(Integer pessimisticLockTimeoutDefault) {
this.pessimisticLockTimeoutDefault = pessimisticLockTimeoutDefault;
}
/**
* PUBLIC:
* Set the default query timeout for this session.
* This timeout will apply to any queries that do not have a timeout set,
* and that do not have a default timeout defined in their descriptor.
*/
public void setQueryTimeoutDefault(int queryTimeoutDefault) {
this.queryTimeoutDefault = queryTimeoutDefault;
}
@Override
public void setQueryTimeoutUnitDefault(TimeUnit queryTimeoutUnitDefault) {
this.queryTimeoutUnitDefault = queryTimeoutUnitDefault;
}
/**
* PUBLIC:
* Set the profiler for the session.
* This allows for performance operations to be profiled.
*/
public void setProfiler(SessionProfiler profiler) {
this.profiler = profiler;
if (profiler != null) {
profiler.setSession(this);
setIsInProfile(getProfiler().getProfileWeight() != SessionProfiler.NONE);
// Clear cached flag that bypasses the profiler check.
getIdentityMapAccessorInstance().getIdentityMapManager().checkIsCacheAccessPreCheckRequired();
} else {
setIsInProfile(false);
}
}
/**
* INTERNAL:
* Set the project, the project holds configuration information including the descriptors.
*/
public void setProject(org.eclipse.persistence.sessions.Project project) {
this.project = project;
}
/**
* INTERNAL:
* Set the user defined properties by shallow copying the propertiesMap.
* @param propertiesMap
*/
public void setProperties(Map<Object, Object> propertiesMap) {
if (null == propertiesMap) {
// Keep current behavior and set properties map to null
properties = propertiesMap;
} else {
/*
* Bug# 219097 Clone as (HashMap) possible immutable maps to avoid
* an UnsupportedOperationException on a later put() We do not know
* the key:value type values at design time. putAll() is not
* synchronized. We clone all maps whether immutable or not.
*/
properties = new HashMap();
// Shallow copy all internal key:value pairs - a null propertiesMap will throw a NPE
properties.putAll(propertiesMap);
}
}
/**
* PUBLIC: Allow for user defined properties.
*/
public void setProperty(String propertyName, Object propertyValue) {
getProperties().put(propertyName, propertyValue);
}
/**
* INTERNAL:
* Set the named queries.
*/
public void setQueries(Map<String, List<DatabaseQuery>> queries) {
this.queries = queries;
}
/**
* PUBLIC:
* Set the session log to which an accessor logs messages and SQL.
* If not set, this will default to a session log on a writer on System.out.
* To enable logging, log level can not be OFF.
* Also set a backpointer to this session in SessionLog.
*
* @see #logMessage(String)
*/
public void setSessionLog(SessionLog sessionLog) {
this.isLoggingOff = false;
this.sessionLog = sessionLog;
if ((sessionLog != null) && (sessionLog.getSession() == null)) {
sessionLog.setSession(this);
}
}
/**
* INTERNAL:
* Set isSynchronized flag to indicate that this session is synchronized.
* This method should only be called by setSynchronized methods of derived classes.
*/
public void setSynchronized(boolean synched) {
isSynchronized = synched;
}
protected void setTransactionMutex(ConcurrencyManager transactionMutex) {
this.transactionMutex = transactionMutex;
}
/**
* INTERNAL:
* Return if a JTS transaction was started by the session.
* The session will start a JTS transaction if a unit of work or transaction is begun without a JTS transaction present.
*/
public void setWasJTSTransactionInternallyStarted(boolean wasJTSTransactionInternallyStarted) {
this.wasJTSTransactionInternallyStarted = wasJTSTransactionInternallyStarted;
}
/**
* PUBLIC:
* Return if logging is enabled (false if log level is OFF)
*/
public boolean shouldLogMessages() {
if (this.isLoggingOff) {
return false;
}
if (getLogLevel(null) == SessionLog.OFF) {
return false;
} else {
return true;
}
}
/**
* INTERNAL:
* Start the operation timing.
*/
public void startOperationProfile(String operationName) {
if (this.isInProfile) {
getProfiler().startOperationProfile(operationName);
}
}
/**
* INTERNAL:
* Start the operation timing.
*/
public void startOperationProfile(String operationName, DatabaseQuery query, int weight) {
if (this.isInProfile) {
getProfiler().startOperationProfile(operationName, query, weight);
}
}
/**
* Print the connection status with the session.
*/
public String toString() {
StringWriter writer = new StringWriter();
writer.write(getSessionTypeString() + "(" + Helper.cr() + "\t" + getAccessor() + Helper.cr() + "\t" + getDatasourcePlatform() + ")");
return writer.toString();
}
/**
* INTERNAL:
* Unwrap the object if required.
* This is used for the wrapper policy support and EJB.
*/
public Object unwrapObject(Object proxy) {
return getDescriptor(proxy).getObjectBuilder().unwrapObject(proxy, this);
}
/**
* PUBLIC:
* Update the object and all of its privately owned parts in the database.
* Update should only be used if the application knows that the object is new,
* otherwise writeObject should be used.
* The update operation can be customized through using an update query.
*
* @exception DatabaseException if an error occurs on the database,
* these include constraint violations, security violations and general database errors.
* @exception OptimisticLockException if the object's descriptor is using optimistic locking and
* the object has been updated or deleted by another user since it was last read.
*
* @see UpdateObjectQuery
* @see #writeObject(Object)
*/
public Object updateObject(Object domainObject) throws DatabaseException, OptimisticLockException {
UpdateObjectQuery query = new UpdateObjectQuery();
query.setObject(domainObject);
query.setIsExecutionClone(true);
return executeQuery(query);
}
/**
* ADVANCED:
* This can be used to help debugging an object identity problem.
* An object identity problem is when an object in the cache references an object not in the cache.
* This method will validate that all cached objects are in a correct state.
*/
public void validateCache() {
getIdentityMapAccessorInstance().validateCache();
}
/**
* INTERNAL:
* This method will be used to update the query with any settings required
* For this session. It can also be used to validate execution.
*/
public void validateQuery(DatabaseQuery query) {
// a no-op for this class
}
/**
* TESTING:
* This is used by testing code to ensure that a deletion was successful.
*/
public boolean verifyDelete(Object domainObject) {
ObjectBuilder builder = getDescriptor(domainObject).getObjectBuilder();
Object implementation = builder.unwrapObject(domainObject, this);
return builder.verifyDelete(implementation, this);
}
/**
* INTERNAL:
* Return if a JTS transaction was started by the session.
* The session will start a JTS transaction if a unit of work or transaction is begun without a JTS transaction present.
*/
public boolean wasJTSTransactionInternallyStarted() {
return wasJTSTransactionInternallyStarted;
}
/**
* INTERNAL:
* Wrap the object if required.
* This is used for the wrapper policy support and EJB.
*/
public Object wrapObject(Object implementation) {
return getDescriptor(implementation).getObjectBuilder().wrapObject(implementation, this);
}
/**
* INTERNAL:
* Write all of the objects and all of their privately owned parts in the database.
* The allows for a group of new objects to be commited as a unit.
* The objects will be commited through a single transactions and any
* foreign keys/circular references between the objects will be resolved.
*/
protected void writeAllObjectsWithChangeSet(UnitOfWorkChangeSet uowChangeSet) throws DatabaseException, OptimisticLockException {
getCommitManager().commitAllObjectsWithChangeSet(uowChangeSet);
}
/**
* PUBLIC:
* Write the object and all of its privately owned parts in the database.
* Write will determine if an insert or an update should be done,
* it may go to the database to determine this (by default will check the identity map).
* The write operation can be customized through using an write query.
*
* @exception DatabaseException if an error occurs on the database,
* these include constraint violations, security violations and general database errors.
* @exception OptimisticLockException if the object's descriptor is using optimistic locking and
* the object has been updated or deleted by another user since it was last read.
*
* @see WriteObjectQuery
* @see #insertObject(Object)
* @see #updateObject(Object)
*/
public Object writeObject(Object domainObject) throws DatabaseException, OptimisticLockException {
WriteObjectQuery query = new WriteObjectQuery();
query.setObject(domainObject);
query.setIsExecutionClone(true);
return executeQuery(query);
}
/**
* INTERNAL:
* This method notifies the accessor that a particular sets of writes has
* completed. This notification can be used for such thing as flushing the
* batch mechanism
*/
public void writesCompleted() {
if (getAccessors() == null) {
return;
}
for (Accessor accessor : getAccessors()) {
accessor.writesCompleted(this);
}
}
/**
* INTERNAL:
* RemoteCommandManager method. This is a required method in order
* to implement the CommandProcessor interface.
* Process the remote command from the RCM. The command may have come from
* any remote session or application. Since this is a EclipseLink session we can
* always assume that the object that we receive here will be a Command object.
*/
public void processCommand(Object command) {
((Command)command).executeWithSession(this);
}
/**
* INTERNAL:
* Process the JPA named queries into EclipseLink Session queries. This
* method is called after descriptor initialization.
* Temporarily made public for ODI. Should not be used elsewhere.
*/
public void processJPAQueries() {
if (! jpaQueriesProcessed) {
// Process the JPA queries that do not query table per tenant entities.
for (DatabaseQuery jpaQuery : getJPAQueries()) {
processJPAQuery(jpaQuery);
}
// Process the JPA queries that query table per tenant entities. At
// the EMF level, these queries will be initialized and added right
// away. At the EM level we must defer their initialization to each
// individual client session.
for (DatabaseQuery jpaQuery : getJPATablePerTenantQueries()) {
boolean processQuery = true;
for (ClassDescriptor descriptor : jpaQuery.getDescriptors()) {
// If the descriptor is not fully initialized then we can
// not initialize the query and must isolate it to be
// initialized and stored per client session (EM).
if (! descriptor.isFullyInitialized()) {
processQuery = false;
break;
}
}
if (processQuery) {
processJPAQuery(jpaQuery);
} else {
addTablePerTenantQuery(jpaQuery);
}
}
jpaQueriesProcessed = true;
}
}
/**
* INTERNAL:
* Process the JPA named query into an EclipseLink Session query. This
* method is called after descriptor initialization.
*/
protected void processJPAQuery(DatabaseQuery jpaQuery) {
// This is a hack, to allow the core Session to initialize JPA queries, without have a dependency on JPA.
// They need to be initialized after login, as the database platform must be known.
try {
jpaQuery.prepareInternal(this);
} catch (RuntimeException re) {
// If jpql-tolerate-error==true, any problems will be ignored at query prep time and the runtime will
// continue chugging along. The invalid query will be left in place so that an exception
// will be thrown at runtime if a user attempts to use it.
if (!tolerateInvalidJPQL) {
throw re;
}
}
DatabaseQuery databaseQuery = (DatabaseQuery) jpaQuery.getProperty("databasequery");
databaseQuery = (databaseQuery == null) ? jpaQuery : databaseQuery;
addQuery(databaseQuery, false); // this should be true but for backward compatibility it
// is set to false.
}
/**
* PUBLIC:
* Return the CommandManager that allows this session to act as a
* CommandProcessor and receive or propagate commands from/to the
* EclipseLink cluster.
*
* @see CommandManager
* @return The CommandManager instance that controls the remote command
* service for this session
*/
public CommandManager getCommandManager() {
return commandManager;
}
/**
* ADVANCED:
* Set the CommandManager that allows this session to act as a
* CommandProcessor and receive or propagate commands from/to the
* EclipseLink cluster.
*
* @see CommandManager
* @param mgr The CommandManager instance to control the remote command
* service for this session
*/
public void setCommandManager(CommandManager mgr) {
commandManager = mgr;
}
/**
* PUBLIC:
* Return whether changes should be propagated to other sessions or applications
* in a EclipseLink cluster through the Remote Command Manager mechanism. In order for
* this to occur the CommandManager must be set.
*
* @see #setCommandManager(CommandManager)
* @return True if propagation is set to occur, false if not
*/
public boolean shouldPropagateChanges() {
return shouldPropagateChanges;
}
/**
* ADVANCED:
* Set whether changes should be propagated to other sessions or applications
* in a EclipseLink cluster through the Remote Command Manager mechanism. In order for
* this to occur the CommandManager must be set.
*
* @see #setCommandManager(CommandManager)
* @param choice If true (and the CommandManager is set) then propagation will occur
*/
public void setShouldPropagateChanges(boolean choice) {
shouldPropagateChanges = choice;
}
/**
* INTERNAL:
* RemoteCommandManager method. This is a required method in order
* to implement the CommandProcessor interface.
* Return true if a message at the specified log level would be logged given the
* log level setting of this session. This can be used by the CommandManager to
* know whether it should even bother to create the localized strings and call
* the logMessage method, or if it would only find that the message would not be
* logged because the session level does not permit logging. The log level passed
* in will be one of the constants LOG_ERROR, LOG_WARNING, LOG_INFO, and LOG_DEBUG
* defined in the CommandProcessor interface.
*/
public boolean shouldLogMessages(int logLevel) {
if (this.isLoggingOff) {
return false;
}
if (LOG_ERROR == logLevel) {
return getLogLevel(SessionLog.PROPAGATION) <= SessionLog.SEVERE;
}
if (LOG_WARNING == logLevel) {
return getLogLevel(SessionLog.PROPAGATION) <= SessionLog.WARNING;
}
if (LOG_INFO == logLevel) {
return getLogLevel(SessionLog.PROPAGATION) <= SessionLog.FINER;
}
if (LOG_DEBUG == logLevel) {
return getLogLevel(SessionLog.PROPAGATION) <= SessionLog.FINEST;
}
return false;
}
/**
* INTERNAL:
* RemoteCommandManager method. This is a required method in order
* to implement the CommandProcessor interface.
* Log the specified message string at the specified level if it should be logged
* given the log level setting in this session. The log level passed in will be one
* of the constants LOG_ERROR, LOG_WARNING, LOG_INFO, and LOG_DEBUG defined in the
* CommandProcessor interface.
*/
public void logMessage(int logLevel, String message) {
if (this.isLoggingOff) {
return;
}
if (shouldLogMessages(logLevel)) {
int level;
switch (logLevel) {
case CommandProcessor.LOG_ERROR:
level = SessionLog.SEVERE;
break;
case CommandProcessor.LOG_WARNING:
level = SessionLog.WARNING;
break;
case CommandProcessor.LOG_INFO:
level = SessionLog.FINER;
break;
case CommandProcessor.LOG_DEBUG:
level = SessionLog.FINEST;
break;
default:
level = SessionLog.ALL;
;
}
log(level, SessionLog.PROPAGATION, message, null, null, false);
}
}
/**
* PUBLIC:
* <p>
* Return the log level
* </p><p>
*
* @return the log level
* </p><p>
* @param category the string representation of a EclipseLink category, e.g. "sql", "transaction" ...
* </p>
*/
public int getLogLevel(String category) {
return getSessionLog().getLevel(category);
}
/**
* PUBLIC:
* <p>
* Return the log level
* </p><p>
* @return the log level
* </p>
*/
public int getLogLevel() {
return getSessionLog().getLevel();
}
/**
* PUBLIC:
* <p>
* Set the log level
* </p><p>
*
* @param level the new log level
* </p>
*/
public void setLogLevel(int level) {
this.isLoggingOff = false;
getSessionLog().setLevel(level);
}
/**
* PUBLIC:
* Return true if SQL logging should log visible bind parameters. If the
* shouldDisplayData is not set, check the session log level and return
* true for a level greater than CONFIG.
*/
public boolean shouldDisplayData() {
return getSessionLog().shouldDisplayData();
}
/**
* PUBLIC:
* <p>
* Check if a message of the given level would actually be logged.
* </p><p>
*
* @return true if the given message level will be logged
* </p><p>
* @param level the log request level
* @param category the string representation of a EclipseLink category
* </p>
*/
public boolean shouldLog(int Level, String category) {
if (this.isLoggingOff) {
return false;
}
return getSessionLog().shouldLog(Level, category);
}
/**
* PUBLIC:
* <p>
* Log a message with level and category that needs to be translated.
* </p><p>
*
* @param level the log request level value
* </p><p>
* @param message the string message
* </p><p>
* @param category the string representation of a EclipseLink category.
* </p>
*/
public void log(int level, String category, String message) {
if (this.isLoggingOff) {
return;
}
if (!shouldLog(level, category)) {
return;
}
log(level, category, message, (Object[])null);
}
/**
* PUBLIC:
* <p>
* Log a message with level, category and a parameter that needs to be translated.
* </p><p>
*
* @param level the log request level value
* </p><p>
* @param message the string message
* </p><p>
* @param category the string representation of a EclipseLink category.
* </p><p>
* @param param a parameter of the message
* </p>
*/
public void log(int level, String category, String message, Object param) {
if (this.isLoggingOff) {
return;
}
if (!shouldLog(level, category)) {
return;
}
log(level, category, message, new Object[] { param });
}
/**
* PUBLIC:
* <p>
* Log a message with level, category and two parameters that needs to be translated.
* </p><p>
*
* @param level the log request level value
* </p><p>
* @param message the string message
* </p><p>
* @param category the string representation of a EclipseLink category.
* </p><p>
* @param param1 a parameter of the message
* </p><p>
* @param param2 second parameter of the message
* </p>
*/
public void log(int level, String category, String message, Object param1, Object param2) {
if (this.isLoggingOff) {
return;
}
if (!shouldLog(level, category)) {
return;
}
log(level, category, message, new Object[] { param1, param2 });
}
/**
* PUBLIC:
* <p>
* Log a message with level, category and three parameters that needs to be translated.
* </p><p>
*
* @param level the log request level value
* </p><p>
* @param message the string message
* </p><p>
* @param category the string representation of a EclipseLink category.
* </p><p>
* @param param1 a parameter of the message
* </p><p>
* @param param2 second parameter of the message
* </p><p>
* @param param3 third parameter of the message
* </p>
*/
public void log(int level, String category, String message, Object param1, Object param2, Object param3) {
if (this.isLoggingOff) {
return;
}
if (!shouldLog(level, category)) {
return;
}
log(level, category, message, new Object[] { param1, param2, param3 });
}
/**
* PUBLIC:
* <p>
* Log a message with level, category and an array of parameters that needs to be translated.
* </p><p>
*
* @param level the log request level value
* </p><p>
* @param message the string message
* </p><p>
* @param category the string representation of a EclipseLink category.
* </p><p>
* @param params array of parameters to the message
* </p>
*/
public void log(int level, String category, String message, Object[] params) {
if (this.isLoggingOff) {
return;
}
log(level, category, message, params, null);
}
/**
* PUBLIC:
* <p>
* Log a message with level, category, parameters and accessor that needs to be translated.
* </p><p>
*
* @param level the log request level value
* </p><p>
* @param message the string message
* </p><p>
* @param params array of parameters to the message
* </p><p>
* @param accessor the connection that generated the log entry
* </p><p>
* @param category the string representation of a EclipseLink category.
* </p>
*/
public void log(int level, String category, String message, Object[] params, Accessor accessor) {
if (this.isLoggingOff) {
return;
}
log(level, category, message, params, accessor, true);
}
/**
* PUBLIC:
* <p>
* Log a message with level, category, parameters and accessor. shouldTranslate determines if the message needs to be translated.
* </p><p>
*
* @param level the log request level value
* </p><p>
* @param message the string message
* </p><p>
* @param params array of parameters to the message
* </p><p>
* @param accessor the connection that generated the log entry
* </p><p>
* @param category the string representation of a EclipseLink category.
* </p><p>
* @param shouldTranslate true if the message needs to be translated.
* </p>
*/
public void log(int level, String category, String message, Object[] params, Accessor accessor, boolean shouldTranslate) {
if (this.isLoggingOff) {
return;
}
if (shouldLog(level, category)) {
startOperationProfile(SessionProfiler.Logging);
log(new SessionLogEntry(level, category, this, message, params, accessor, shouldTranslate));
endOperationProfile(SessionProfiler.Logging);
}
}
/**
* PUBLIC:
* <p>
* Log a message with level, parameters and accessor that needs to be translated.
* </p><p>
*
* @param level the log request level value
* </p><p>
* @param message the string message
* </p><p>
* @param params array of parameters to the message
* </p><p>
* @param accessor the connection that generated the log entry
* </p>
* @deprecated since 2.6 replaced by log with category, log(int, String, String, Object[], Accessor)
*/
@Deprecated
public void log(int level, String message, Object[] params, Accessor accessor) {
if (this.isLoggingOff) {
return;
}
log(level, message, params, accessor, true);
}
/**
* PUBLIC:
* <p>
* Log a message with level, parameters and accessor. shouldTranslate determines if the message needs to be translated.
* </p><p>
*
* @param level the log request level value
* </p><p>
* @param message the string message
* </p><p>
* @param params array of parameters to the message
* </p><p>
* @param accessor the connection that generated the log entry
* </p><p>
* @param shouldTranslate true if the message needs to be translated.
* </p>
* @deprecated since 2.6 replaced by log with category, log(int, String, String, Object[], Accessor, boolean)
*/
@Deprecated
public void log(int level, String message, Object[] params, Accessor accessor, boolean shouldTranslate) {
if (this.isLoggingOff) {
return;
}
if (shouldLog(level, null)) {
startOperationProfile(SessionProfiler.Logging);
log(new SessionLogEntry(level, this, message, params, accessor, shouldTranslate));
endOperationProfile(SessionProfiler.Logging);
}
}
/**
* PUBLIC:
* <p>
* Log a throwable with level and category.
* </p><p>
*
* @param level the log request level value
* </p><p>
* @param category the string representation of a EclipseLink category.
* </p><p>
* @param throwable a Throwable
* </p>
*/
public void logThrowable(int level, String category, Throwable throwable) {
if (this.isLoggingOff) {
return;
}
// Must not create the log if not logging as is a performance issue.
if (shouldLog(level, category)) {
startOperationProfile(SessionProfiler.Logging);
log(new SessionLogEntry(this, level, category, throwable));
endOperationProfile(SessionProfiler.Logging);
}
}
/**
* PUBLIC:
* <p>
* This method is called when a severe level message needs to be logged.
* The message will be translated
* </p><p>
*
* @param message the message key
* </p>
*/
public void severe(String message, String category) {
if (this.isLoggingOff) {
return;
}
log(SessionLog.SEVERE, category, message);
}
/**
* PUBLIC:
* <p>
* This method is called when a warning level message needs to be logged.
* The message will be translated
* </p><p>
*
* @param message the message key
* </p>
*/
public void warning(String message, String category) {
if (this.isLoggingOff) {
return;
}
log(SessionLog.WARNING, category, message);
}
/**
* PUBLIC:
* <p>
* This method is called when a info level message needs to be logged.
* The message will be translated
* </p><p>
*
* @param message the message key
* </p>
*/
public void info(String message, String category) {
if (this.isLoggingOff) {
return;
}
log(SessionLog.INFO, category, message);
}
/**
* PUBLIC:
* <p>
* This method is called when a config level message needs to be logged.
* The message will be translated
* </p><p>
*
* @param message the message key
* </p>
*/
public void config(String message, String category) {
if (this.isLoggingOff) {
return;
}
log(SessionLog.CONFIG, category, message);
}
/**
* PUBLIC:
* <p>
* This method is called when a fine level message needs to be logged.
* The message will be translated
* </p><p>
*
* @param message the message key
* </p>
*/
public void fine(String message, String category) {
if (this.isLoggingOff) {
return;
}
log(SessionLog.FINE, category, message);
}
/**
* PUBLIC:
* <p>
* This method is called when a finer level message needs to be logged.
* The message will be translated
* </p><p>
*
* @param message the message key
* </p>
*/
public void finer(String message, String category) {
if (this.isLoggingOff) {
return;
}
log(SessionLog.FINER, category, message);
}
/**
* PUBLIC:
* <p>
* This method is called when a finest level message needs to be logged.
* The message will be translated
* </p><p>
*
* @param message the message key
* </p>
*/
public void finest(String message, String category) {
if (this.isLoggingOff) {
return;
}
log(SessionLog.FINEST, category, message);
}
/**
* PUBLIC:
* Allow any SEVERE level exceptions that occur within EclipseLink to be logged and handled by the exception handler.
*/
public Object handleSevere(RuntimeException exception) throws RuntimeException {
logThrowable(SessionLog.SEVERE, null, exception);
if (hasExceptionHandler()) {
return getExceptionHandler().handleException(exception);
} else {
throw exception;
}
}
/**
* INTERNAL:
*/
public void releaseReadConnection(Accessor connection) {
//bug 4668234 -- used to only release connections on server sessions but should always release
//do nothing -- overidden in UnitOfWork,ClientSession and ServerSession
}
/**
* INTERNAL:
* Copies descriptors cached on the Project.
* Used after Project.descriptors has been reset by addDescriptor(s) when the session is connected.
*/
public void copyDescriptorsFromProject() {
this.descriptors = getDescriptors();
}
/**
* INTERNAL:
* This method will be used to copy all EclipseLink named queries defined in descriptors into the session.
* @param allowSameQueryNameDiffArgsCopyToSession if the value is true, it allow
* multiple queries of the same name but different arguments to be copied to the session.
*/
public void copyDescriptorNamedQueries(boolean allowSameQueryNameDiffArgsCopyToSession) {
for (ClassDescriptor descriptor : getProject().getOrderedDescriptors()) {
Map queries = descriptor.getQueryManager().getQueries();
if ((queries != null) && (queries.size() > 0)) {
for (Iterator keyValueItr = queries.entrySet().iterator(); keyValueItr.hasNext();){
Map.Entry entry = (Map.Entry) keyValueItr.next();
Vector thisQueries = (Vector)entry.getValue();
if ((thisQueries != null) && (thisQueries.size() > 0)){
for( Iterator thisQueriesItr=thisQueries.iterator();thisQueriesItr.hasNext();){
DatabaseQuery queryToBeAdded = (DatabaseQuery)thisQueriesItr.next();
if (allowSameQueryNameDiffArgsCopyToSession){
addQuery(queryToBeAdded, false);
} else {
if (getQuery(queryToBeAdded.getName()) == null){
addQuery(queryToBeAdded, false);
} else {
log(SessionLog.WARNING, SessionLog.PROPERTIES, "descriptor_named_query_cannot_be_added", new Object[]{queryToBeAdded,queryToBeAdded.getName(),queryToBeAdded.getArgumentTypes()});
}
}
}
}
}
}
}
}
/**
* INTERNAL:
* This method rises appropriate for the session event(s)
* right after connection is acquired.
*/
public void postAcquireConnection(Accessor accessor) {
if (getProject().hasVPDIdentifier(this)) {
if (getPlatform().supportsVPD()) {
DatabaseQuery query = getPlatform().getVPDSetIdentifierQuery(getProject().getVPDIdentifier());
List argValues = new ArrayList();
query.addArgument(getProject().getVPDIdentifier());
argValues.add(getProperty(getProject().getVPDIdentifier()));
executeQuery(query, argValues);
} else {
throw ValidationException.vpdNotSupported(getPlatform().getClass().getName());
}
}
if (this.eventManager != null) {
this.eventManager.postAcquireConnection(accessor);
}
}
/**
* INTERNAL:
* This method rises appropriate for the session event(s)
* right before the connection is released.
*/
public void preReleaseConnection(Accessor accessor) {
if (getProject().hasVPDIdentifier(this)) {
if (getPlatform().supportsVPD()) {
DatabaseQuery query = getPlatform().getVPDClearIdentifierQuery(getProject().getVPDIdentifier());
List argValues = new ArrayList();
query.addArgument(getProject().getVPDIdentifier());
argValues.add(getProperty(getProject().getVPDIdentifier()));
executeQuery(query, argValues);
} else {
throw ValidationException.vpdNotSupported(getPlatform().getClass().getName());
}
}
if (this.eventManager != null) {
this.eventManager.preReleaseConnection(accessor);
}
}
/**
* INTERNAL:
* Execute the call on the database. Calling this method will bypass a
* global setting to disallow native SQL queries. (set by default when
* one Entity is marked as multitenant)
*
* The row count is returned.
*
* The call can be a stored procedure call, SQL call or other type of call.
*
* <p>Example:
* <p>session.executeNonSelectingCall(new SQLCall("Delete from Employee"), true);
*
* @see #priviledgedExecuteSelectingCall(Call)
*/
public int priviledgedExecuteNonSelectingCall(Call call) throws DatabaseException {
DataModifyQuery query = new DataModifyQuery();
query.setAllowNativeSQLQuery(true);
query.setIsExecutionClone(true);
query.setCall(call);
Integer value = (Integer)executeQuery(query);
if (value == null) {
return 0;
} else {
return value.intValue();
}
}
/**
* INTERNAL:
* Execute the call on the database and return the result. Calling this
* method will bypass a global setting to disallow native SQL queries. (set
* by default when one Entity is marked as multitenant)
*
* The call must return a value, if no value is return executeNonSelectCall
* must be used.
*
* The call can be a stored procedure call, SQL call or other type of call.
*
* A vector of database rows is returned, database row implements Java 2 Map
* which should be used to access the data.
*
* <p>Example:
* <p>session.executeSelectingCall(new SQLCall("Select * from Employee");
*
* @see #priviledgedExecuteNonSelectingCall(Call)
*/
public Vector priviledgedExecuteSelectingCall(Call call) throws DatabaseException {
DataReadQuery query = new DataReadQuery();
query.setAllowNativeSQLQuery(true);
query.setCall(call);
query.setIsExecutionClone(true);
return (Vector)executeQuery(query);
}
/**
* INTERNAL:
* This method is called in case externalConnectionPooling is used.
* If returns true, accessor used by the session keeps its
* connection open until released by the session.
*/
public boolean isExclusiveConnectionRequired() {
return false;
}
/**
* Stores the default Session wide reference mode that a UnitOfWork will use when referencing
* managed objects.
* @see org.eclipse.persistence.config.ReferenceMode
*/
public ReferenceMode getDefaultReferenceMode() {
return defaultReferenceMode;
}
/**
* Stores the default Session wide reference mode that a UnitOfWork will use when referencing
* managed objects.
* @see org.eclipse.persistence.config.ReferenceMode
*/
public void setDefaultReferenceMode(ReferenceMode defaultReferenceMode) {
this.defaultReferenceMode = defaultReferenceMode;
}
/**
* This method will load the passed object or collection of objects using the passed AttributeGroup.
* In case of collection all members should be either objects of the same mapped type
* or have a common inheritance hierarchy mapped root class.
* The AttributeGroup should correspond to the object type.
*
* @param objectOrCollection
*/
public void load(Object objectOrCollection, AttributeGroup group) {
if (objectOrCollection == null || group == null) {
return;
}
if (objectOrCollection instanceof Collection) {
Iterator iterator = ((Collection)objectOrCollection).iterator();
while (iterator.hasNext()) {
Object object = iterator.next();
load(object, group, getClassDescriptor(object.getClass()), false);
}
} else {
ClassDescriptor concreteDescriptor = getClassDescriptor(objectOrCollection.getClass());
load(objectOrCollection, group, concreteDescriptor, false);
}
}
/**
* This method will load the passed object or collection of objects using the passed AttributeGroup.
* In case of collection all members should be either objects of the same mapped type
* or have a common inheritance hierarchy mapped root class.
* The AttributeGroup should correspond to the object type.
*
* @param objectOrCollection
*/
public void load(Object objectOrCollection, AttributeGroup group, ClassDescriptor referenceDescriptor, boolean fromFetchGroup) {
if (objectOrCollection == null || group == null) {
return;
}
if (objectOrCollection instanceof Collection) {
Iterator iterator = ((Collection)objectOrCollection).iterator();
while (iterator.hasNext()) {
load(iterator.next(), group, referenceDescriptor, fromFetchGroup);
}
} else {
ClassDescriptor concreteDescriptor = referenceDescriptor;
if (concreteDescriptor.hasInheritance() && !objectOrCollection.getClass().equals(concreteDescriptor.getJavaClass())){
concreteDescriptor = concreteDescriptor.getInheritancePolicy().getDescriptor(objectOrCollection.getClass());
}
AttributeGroup concreteGroup = group.findGroup(concreteDescriptor);
concreteDescriptor.getObjectBuilder().load(objectOrCollection, concreteGroup, this, fromFetchGroup);
}
}
public CacheKey retrieveCacheKey(Object primaryKey, ClassDescriptor concreteDescriptor, JoinedAttributeManager joinManager, ObjectBuildingQuery query){
CacheKey cacheKey;
//lock the object in the IM
// PERF: Only use deferred locking if required.
// CR#3876308 If joining is used, deferred locks are still required.
if (query.requiresDeferredLocks()) {
cacheKey = this.getIdentityMapAccessorInstance().acquireDeferredLock(primaryKey, concreteDescriptor.getJavaClass(), concreteDescriptor, query.isCacheCheckComplete() || query.shouldRetrieveBypassCache());
if (cacheKey.getActiveThread() != Thread.currentThread()) {
int counter = 0;
while ((cacheKey.getObject() == null) && (counter < 1000)) {
//must release lock here to prevent acquiring multiple deferred locks but only
//releasing one at the end of the build object call.
//bug 5156075
cacheKey.releaseDeferredLock();
//sleep and try again if we are not the owner of the lock for CR 2317
// prevents us from modifying a cache key that another thread has locked.
try {
Thread.sleep(10);
} catch (InterruptedException exception) {
}
cacheKey = this.getIdentityMapAccessorInstance().acquireDeferredLock(primaryKey, concreteDescriptor.getJavaClass(), concreteDescriptor, query.isCacheCheckComplete() || query.shouldRetrieveBypassCache());
if (cacheKey.getActiveThread() == Thread.currentThread()) {
break;
}
counter++;
}
if (counter == 1000) {
throw ConcurrencyException.maxTriesLockOnBuildObjectExceded(cacheKey.getActiveThread(), Thread.currentThread());
}
}
} else {
cacheKey = this.getIdentityMapAccessorInstance().acquireLock(primaryKey, concreteDescriptor.getJavaClass(), concreteDescriptor, query.isCacheCheckComplete() || query.shouldRetrieveBypassCache());
}
return cacheKey;
}
/**
* PUBLIC:
* Return the session's partitioning policy.
*/
public PartitioningPolicy getPartitioningPolicy() {
return partitioningPolicy;
}
/**
* PUBLIC:
* Set the session's partitioning policy.
* A PartitioningPolicy is used to partition, load-balance or replicate data across multiple difference databases
* or across a database cluster such as Oracle RAC.
* Partitioning can provide improved scalability by allowing multiple database machines to service requests.
*/
public void setPartitioningPolicy(PartitioningPolicy partitioningPolicy) {
this.partitioningPolicy = partitioningPolicy;
}
/**
* INTERNAL:
* This currently only used by JPA with RCM to force a refresh of the metadata used within EntityManagerFactoryWrappers
*/
public MetadataRefreshListener getRefreshMetadataListener() {
return metadatalistener;
}
public void setRefreshMetadataListener(MetadataRefreshListener metadatalistener) {
this.metadatalistener = metadatalistener;
}
/**
* ADVANCED:
* Return if the session enables concurrent processing.
* Concurrent processing allow certain processing to be done on seperate threads.
* This can result in improved performance.
* This will use the session's server platform's thread pool.
*/
public boolean isConcurrent() {
return this.isConcurrent;
}
/**
* ADVANCED:
* Set if the session enables concurrent processing.
* Concurrent processing allow certain processing to be done on seperate threads.
* This can result in improved performance.
* This will use the session's server platform's thread pool.
*/
public void setIsConcurrent(boolean isConcurrent) {
this.isConcurrent = isConcurrent;
}
/**
* ADVANCED:
* Set to indicate whether ObjectLevelReadQuery should by default use ResultSet Access optimization.
* If not set then parent's flag is used, is none set then ObjectLevelReadQuery.isResultSetAccessOptimizedQueryDefault is used.
* If the optimization specified by the session is ignored if incompatible with other query settings.
*/
public void setShouldOptimizeResultSetAccess(boolean shouldOptimizeResultSetAccess) {
this.shouldOptimizeResultSetAccess = shouldOptimizeResultSetAccess;
}
/**
* ADVANCED:
* Indicates whether ObjectLevelReadQuery should by default use ResultSet Access optimization.
* Optimization specified by the session is ignored if incompatible with other query settings.
*/
public boolean shouldOptimizeResultSetAccess() {
return this.shouldOptimizeResultSetAccess;
}
/**
* ADVANCED: Indicates whether an invalid NamedQuery will be tolerated at init time.
*
* Default is false.
*/
public void setTolerateInvalidJPQL(boolean b) {
this.tolerateInvalidJPQL = b;
}
/**
* ADVANCED: Indicates whether an invalid NamedQuery will be tolerated at init time.
*
* Default is false.
*/
public boolean shouldTolerateInvalidJPQL() {
return this.tolerateInvalidJPQL;
}
}
|