File size: 167,685 Bytes
02eb4ab |
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 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 |
classname,id,original_code,num_file,num_line,Programming Language
emailgenerator,./ProjectTest/Java/emailgenerator.java,"// emailgenerator/EmailApp.java
package projecttest.emailgenerator;
import com.sun.security.jgss.GSSUtil;
import java.sql.SQLOutput;
import java.util.Scanner;
public class EmailApp {
public static void main(String[] args) {
System.out.println(""Generate Organization's Email ==>"");
Scanner sc=new Scanner(System.in);
// String x=sc.nextLine();
System.out.println(""Generating the email..."");
System.out.println(""Enter firstname :"");
String first=sc.nextLine();
System.out.println(""Enter Lastname :"");
String second=sc.nextLine();
Email em=new Email(first,second);
while(true) {
System.out.println(""1 : Information "");
System.out.println(""2 : Change Email"");
System.out.println(""3 : Change Password"");
System.out.println(""4 : Disclose Password"");
System.out.println(""5 : Exit"");
System.out.println(""Enter operation code :"");
int a = sc.nextInt();
switch (a) {
case 1:
System.out.println(em.showInfo());
break;
case 2:
System.out.println(""Enter alternate email prefix :"");
sc.nextLine();
String alt = sc.nextLine();
em.setEmail(alt+""@drngpit.ac.in"");
break;
case 3:
System.out.println(""Enter the verification code :"");
sc.nextLine();
String s = sc.nextLine();
if (s.equals(em.getVcode())) {
System.out.println(""Enter alternate password :"");
String p = sc.nextLine();
em.setPassword(p);
} else {
System.out.println(""Please Enter valid verification code !!!"");
}
System.out.println(""Password updated successfully !!!"");
break;
case 4:
System.out.println(""Password disclose warning !!!"");
System.out.println(""Enter the verification code :"");
sc.nextLine();
String s1 = sc.nextLine();
if (s1.equals(em.getVcode())) {
System.out.println(""Your password : "" + em.getPassword());
} else {
System.out.println(""Please Enter valid verification code !!!"");
}
case 5:
System.out.println(""Have a great day ahead ! BYE "");
return ;
}
}
}
}
// emailgenerator/Email.java
package projecttest.emailgenerator;
import java.util.Scanner;
public class Email {
private String firstName;
private String lastName;
private String password;
private String department;
private String email;
private int defaultPasswordLength=8;
private int codelen=5;
private String Vcode;
private String company=""drngpit.ac.in"";
private String name;
public Email(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
System.out.println(""Kindly ! Enter department for email creation dear ""+this.firstName+"" ""+this.lastName);
//dept
this.department=setDepartment();
System.out.println(""Department:""+department);
//pass
this.password=randomPass(defaultPasswordLength);
System.out.println(""New Password :""+password);
//clipping name as one
this.name=firstName+lastName;
//verification code
this.Vcode=vcode(codelen);
System.out.println(""Your verification code : ""+Vcode);
//Binding
email=name.toLowerCase()+"".""+department+""@""+company;
System.out.println(""Official mail :""+email);
}
private String setDepartment(){
System.out.println(""Enter the department Id\nSales : 1\nDevelopment : 2\nAccounting : 3"");
Scanner in=new Scanner(System.in);
int dep=in.nextInt();
if(dep==1){
return ""sales"";
}
else if(dep==2){
return""dev"";
}
else if(dep==3){
return ""acc"";
}
return"""";
}
private String randomPass(int length){
String password=""ABCEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%"";
char[]pass=new char[length];
for(int i=0;i<length;i++){
int rand=(int)(Math.random()*password.length());
pass[i]=password.charAt(rand);
}
return new String(pass);
}
private String vcode(int codelen){
String samcode=""1234567890"";
char[]code=new char[codelen];
for(int i=0;i<codelen;i++){
int c=(int)(Math.random()*samcode.length());
code[i]=samcode.charAt(c);
}
return new String(code);
}
public void setPassword(String password) {
this.password = password;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword(){
return password;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getVcode() {
return Vcode;
}
public String getDept(String dep){
if(dep.equals(""dev"")){
return ""Developers"";
}
else if(dep.equals(""acc"")){
return ""Accounts"";
}
else if(dep.equals(""sales"")){
return ""Sales"";
}
return """";
}
public String showInfo(){
return ""Name : ""+name+""\nOfficial email : ""+email+""\nDepartment : ""+getDept(department);
}
}
",2,194,Java
heap,./ProjectTest/Java/heap.java,"// heap/LeftistHeap.java
package projecttest.heap;
import java.util.ArrayList;
/*
* This is a leftist heap that follows the same operations as a
* binary min heap, but may be unbalanced at times and follows a
* leftist property, in which the left side is more heavy on the
* right based on the null-path length (npl) values.
*
* Source: https://iq.opengenus.org/leftist-heap/
*
*/
public class LeftistHeap {
private class Node {
private int element, npl;
private Node left, right;
// Node constructor setting the data element and left/right pointers to null
private Node(int element) {
this.element = element;
left = right = null;
npl = 0;
}
}
private Node root;
// Constructor
public LeftistHeap() {
root = null;
}
// Checks if heap is empty
public boolean isEmpty() {
return root == null;
}
// Resets structure to initial state
public void clear() {
// We will put head is null
root = null;
}
// Merge function that merges the contents of another leftist heap with the
// current one
public void merge(LeftistHeap h1) {
// If the present function is rhs then we ignore the merge
root = merge(root, h1.root);
h1.root = null;
}
// Function merge with two Nodes a and b
public Node merge(Node a, Node b) {
if (a == null) return b;
if (b == null) return a;
// Violates leftist property, so must do a swap
if (a.element > b.element) {
Node temp = a;
a = b;
b = temp;
}
// Now we call the function merge to merge a and b
a.right = merge(a.right, b);
// Violates leftist property so must swap here
if (a.left == null) {
a.left = a.right;
a.right = null;
} else {
if (a.left.npl < a.right.npl) {
Node temp = a.left;
a.left = a.right;
a.right = temp;
}
a.npl = a.right.npl + 1;
}
return a;
}
// Function insert. Uses the merge function to add the data
public void insert(int a) {
root = merge(new Node(a), root);
}
// Returns and removes the minimum element in the heap
public int extract_min() {
// If is empty return -1
if (isEmpty()) return -1;
int min = root.element;
root = merge(root.left, root.right);
return min;
}
// Function returning a list of an in order traversal of the data structure
public ArrayList<Integer> in_order() {
ArrayList<Integer> lst = new ArrayList<>();
in_order_aux(root, lst);
return new ArrayList<>(lst);
}
// Auxiliary function for in_order
private void in_order_aux(Node n, ArrayList<Integer> lst) {
if (n == null) return;
in_order_aux(n.left, lst);
lst.add(n.element);
in_order_aux(n.right, lst);
}
}
// heap/FibonacciHeap.java
package projecttest.heap;
public class FibonacciHeap {
private static final double GOLDEN_RATIO = (1 + Math.sqrt(5)) / 2;
private HeapNode min;
private static int totalLinks = 0;
private static int totalCuts = 0;
private int numOfTrees = 0;
private int numOfHeapNodes = 0;
private int markedHeapNoodesCounter = 0;
/*
* a constructor for an empty Heap
* set the min to be null
*/
public FibonacciHeap() {
this.min = null;
}
/*
* a constructor for a Heap with one element
* set the min to be the HeapNode with the given key
* @pre key>=0
* @post empty == false
*/
public FibonacciHeap(int key) {
this.min = new HeapNode(key);
this.numOfTrees++;
this.numOfHeapNodes++;
}
/*
* check if the heap is empty
* $ret == true - if the tree is empty
*/
public boolean empty() {
return (this.min == null);
}
/**
* Creates a node (of type HeapNode) which contains the given key, and inserts it into the heap.
*
* @pre key>=0
* @post (numOfnodes = = $prev numOfnodes + 1)
* @post empty == false
* $ret = the HeapNode we inserted
*/
public HeapNode insert(int key) {
HeapNode toInsert = new HeapNode(key); // creates the node
if (this.empty()) {
this.min = toInsert;
} else { // tree is not empty
min.setNext(toInsert);
this.updateMin(toInsert);
}
this.numOfHeapNodes++;
this.numOfTrees++;
return toInsert;
}
/**
* Delete the node containing the minimum key in the heap
* updates new min
*
* @post (numOfnodes = = $prev numOfnodes - 1)
*/
public void deleteMin() {
if (this.empty()) {
return;
}
if (this.numOfHeapNodes == 1) { // if there is only one tree
this.min = null;
this.numOfTrees--;
this.numOfHeapNodes--;
return;
}
// change all children's parent to null//
if (this.min.child != null) { // min has a child
HeapNode child = this.min.child;
HeapNode tmpChild = child;
child.parent = null;
while (child.next != tmpChild) {
child = child.next;
child.parent = null;
}
}
// delete the node//
if (this.numOfTrees > 1) {
(this.min.prev).next = this.min.next;
(this.min.next).prev = this.min.prev;
if (this.min.child != null) {
(this.min.prev).setNext(this.min.child);
}
} else { // this.numOfTrees = 1
this.min = this.min.child;
}
this.numOfHeapNodes--;
this.successiveLink(this.min.getNext());
}
/**
* Return the node of the heap whose key is minimal.
* $ret == null if (empty==true)
*/
public HeapNode findMin() {
return this.min;
}
/**
* Meld the heap with heap2
*
* @pre heap2 != null
* @post (numOfnodes = = $prev numOfnodes + heap2.numOfnodes)
*/
public void meld(FibonacciHeap heap2) {
if (heap2.empty()) {
return;
}
if (this.empty()) {
this.min = heap2.min;
} else {
this.min.setNext(heap2.min);
this.updateMin(heap2.min);
}
this.numOfTrees += heap2.numOfTrees;
this.numOfHeapNodes += heap2.numOfHeapNodes;
}
/**
* Return the number of elements in the heap
* $ret == 0 if heap is empty
*/
public int size() {
return this.numOfHeapNodes;
}
/**
* Return a counters array, where the value of the i-th index is the number of trees with rank i
* in the heap. returns an empty array for an empty heap
*/
public int[] countersRep() {
if (this.empty()) {
return new int[0]; /// return an empty array
}
int[] rankArray = new int[(int) Math.floor(Math.log(this.size()) / Math.log(GOLDEN_RATIO)) + 1]; // creates the array
rankArray[this.min.rank]++;
HeapNode curr = this.min.next;
while (curr != this.min) {
rankArray[curr.rank]++;
curr = curr.next;
}
return rankArray;
}
/**
* Deletes the node x from the heap (using decreaseKey(x) to -1)
*
* @pre heap contains x
* @post (numOfnodes = = $prev numOfnodes - 1)
*/
public void delete(HeapNode x) {
this.decreaseKey(x, x.getKey() + 1); // change key to be the minimal (-1)
this.deleteMin(); // delete it
}
/**
* The function decreases the key of the node x by delta.
*
* @pre x.key >= delta (we don't realize it when calling from delete())
* @pre heap contains x
*/
private void decreaseKey(HeapNode x, int delta) {
int newKey = x.getKey() - delta;
x.key = newKey;
if (x.isRoot()) { // no parent to x
this.updateMin(x);
return;
}
if (x.getKey() >= x.parent.getKey()) {
return;
} // we don't need to cut
HeapNode prevParent = x.parent;
this.cut(x);
this.cascadingCuts(prevParent);
}
/**
* returns the current potential of the heap, which is:
* Potential = #trees + 2*#markedNodes
*/
public int potential() {
return numOfTrees + (2 * markedHeapNoodesCounter);
}
/**
* This static function returns the total number of link operations made during the run-time of
* the program. A link operation is the operation which gets as input two trees of the same
* rank, and generates a tree of rank bigger by one.
*/
public static int totalLinks() {
return totalLinks;
}
/**
* This static function returns the total number of cut operations made during the run-time of
* the program. A cut operation is the operation which disconnects a subtree from its parent
* (during decreaseKey/delete methods).
*/
public static int totalCuts() {
return totalCuts;
}
/*
* updates the min of the heap (if needed)
* @pre this.min == @param (posMin) if and only if (posMin.key < this.min.key)
*/
private void updateMin(HeapNode posMin) {
if (posMin.getKey() < this.min.getKey()) {
this.min = posMin;
}
}
/*
* Recursively ""runs"" all the way up from @param (curr) and mark the nodes.
* stop the recursion if we had arrived to a marked node or to a root.
* if we arrived to a marked node, we cut it and continue recursively.
* called after a node was cut.
* @post (numOfnodes == $prev numOfnodes)
*/
private void cascadingCuts(HeapNode curr) {
if (!curr.isMarked()) { // stop the recursion
curr.mark();
if (!curr.isRoot()) this.markedHeapNoodesCounter++;
} else {
if (curr.isRoot()) {
return;
}
HeapNode prevParent = curr.parent;
this.cut(curr);
this.cascadingCuts(prevParent);
}
}
/*
* cut a node (and his ""subtree"") from his origin tree and connect it to the heap as a new tree.
* called after a node was cut.
* @post (numOfnodes == $prev numOfnodes)
*/
private void cut(HeapNode curr) {
curr.parent.rank--;
if (curr.marked) {
this.markedHeapNoodesCounter--;
curr.marked = false;
}
if (curr.parent.child == curr) { // we should change the parent's child
if (curr.next == curr) { // curr do not have brothers
curr.parent.child = null;
} else { // curr have brothers
curr.parent.child = curr.next;
}
}
curr.prev.next = curr.next;
curr.next.prev = curr.prev;
curr.next = curr;
curr.prev = curr;
curr.parent = null;
this.min.setNext(curr);
this.updateMin(curr);
this.numOfTrees++;
totalCuts++;
}
/*
*
*/
private void successiveLink(HeapNode curr) {
HeapNode[] buckets = this.toBuckets(curr);
this.min = this.fromBuckets(buckets);
}
/*
*
*/
private HeapNode[] toBuckets(HeapNode curr) {
HeapNode[] buckets = new HeapNode[(int) Math.floor(Math.log(this.size()) / Math.log(GOLDEN_RATIO)) + 1];
curr.prev.next = null;
HeapNode tmpCurr;
while (curr != null) {
tmpCurr = curr;
curr = curr.next;
tmpCurr.next = tmpCurr;
tmpCurr.prev = tmpCurr;
while (buckets[tmpCurr.rank] != null) {
tmpCurr = this.link(tmpCurr, buckets[tmpCurr.rank]);
buckets[tmpCurr.rank - 1] = null;
}
buckets[tmpCurr.rank] = tmpCurr;
}
return buckets;
}
/*
*
*/
private HeapNode fromBuckets(HeapNode[] buckets) {
HeapNode tmpMin = null;
this.numOfTrees = 0;
for (int i = 0; i < buckets.length; i++) {
if (buckets[i] != null) {
this.numOfTrees++;
if (tmpMin == null) {
tmpMin = buckets[i];
tmpMin.next = tmpMin;
tmpMin.prev = tmpMin;
} else {
tmpMin.setNext(buckets[i]);
if (buckets[i].getKey() < tmpMin.getKey()) {
tmpMin = buckets[i];
}
}
}
}
return tmpMin;
}
/*
* link between two nodes (and their trees)
* defines the smaller node to be the parent
*/
private HeapNode link(HeapNode c1, HeapNode c2) {
if (c1.getKey() > c2.getKey()) {
HeapNode c3 = c1;
c1 = c2;
c2 = c3;
}
if (c1.child == null) {
c1.child = c2;
} else {
c1.child.setNext(c2);
}
c2.parent = c1;
c1.rank++;
totalLinks++;
return c1;
}
/**
* public class HeapNode
* each HeapNode belongs to a heap (Inner class)
*/
public class HeapNode {
public int key;
private int rank;
private boolean marked;
private HeapNode child;
private HeapNode next;
private HeapNode prev;
private HeapNode parent;
/*
* a constructor for a heapNode withe key @param (key)
* prev == next == this
* parent == child == null
*/
public HeapNode(int key) {
this.key = key;
this.marked = false;
this.next = this;
this.prev = this;
}
/*
* returns the key of the node.
*/
public int getKey() {
return this.key;
}
/*
* checks whether the node is marked
* $ret = true if one child has been cut
*/
private boolean isMarked() {
return this.marked;
}
/*
* mark a node (after a child was cut)
* @inv root.mark() == false.
*/
private void mark() {
if (this.isRoot()) {
return;
} // check if the node is a root
this.marked = true;
}
/*
* add the node @param (newNext) to be between this and this.next
* works fine also if @param (newNext) does not ""stands"" alone
*/
private void setNext(HeapNode newNext) {
HeapNode tmpNext = this.next;
this.next = newNext;
this.next.prev.next = tmpNext;
tmpNext.prev = newNext.prev;
this.next.prev = this;
}
/*
* returns the next node to this node
*/
private HeapNode getNext() {
return this.next;
}
/*
* check if the node is a root
* root definition - this.parent == null (uppest in his tree)
*/
private boolean isRoot() {
return (this.parent == null);
}
}
}
// heap/HeapPerformanceTest.java
package projecttest.heap;
import java.util.HashMap;
import java.util.Random;
import java.util.ArrayList;
public class HeapPerformanceTest {
private final int numElements;
public HeapPerformanceTest(int numElements) {
this.numElements = numElements;
}
public HashMap<String, Long> test() {
// Number of elements to test
// Create heaps for insertion and deletion tests
FibonacciHeap fibonacciHeap = new FibonacciHeap();
LeftistHeap leftistHeap = new LeftistHeap();
HashMap<String, Long> ret = new HashMap<>();
// Insertion test
long startTime = System.currentTimeMillis();
for (int i = 0; i < numElements; i++) {
fibonacciHeap.insert(new Random().nextInt());
}
long endTime = System.currentTimeMillis();
ret.put(""Fibonacci Heap Insertion Time"", endTime - startTime);
startTime = System.currentTimeMillis();
for (int i = 0; i < numElements; i++) {
leftistHeap.insert(new Random().nextInt());
}
endTime = System.currentTimeMillis();
ret.put(""Leftist Heap Insertion Time"", endTime - startTime);
// Deletion test
startTime = System.currentTimeMillis();
while (!fibonacciHeap.empty()) {
fibonacciHeap.deleteMin();
}
endTime = System.currentTimeMillis();
ret.put(""Fibonacci Heap Deletion Time"", endTime - startTime);
startTime = System.currentTimeMillis();
while (!leftistHeap.isEmpty()) {
leftistHeap.extract_min();
}
endTime = System.currentTimeMillis();
ret.put(""Leftist Heap Deletion Time"", endTime - startTime);
// Merge test
FibonacciHeap fibonacciHeap1 = new FibonacciHeap();
FibonacciHeap fibonacciHeap2 = new FibonacciHeap();
LeftistHeap leftistHeap1 = new LeftistHeap();
LeftistHeap leftistHeap2 = new LeftistHeap();
// Populate the heaps for merge test
for (int i = 0; i < numElements / 2; i++) {
fibonacciHeap1.insert(new Random().nextInt());
fibonacciHeap2.insert(new Random().nextInt());
leftistHeap1.insert(new Random().nextInt());
leftistHeap2.insert(new Random().nextInt());
}
// Merge performance test
startTime = System.currentTimeMillis();
fibonacciHeap1.meld(fibonacciHeap2);
endTime = System.currentTimeMillis();
ret.put(""Fibonacci Heap Merge Time"", endTime - startTime);
startTime = System.currentTimeMillis();
leftistHeap1.merge(leftistHeap2);
endTime = System.currentTimeMillis();
ret.put(""Leftist Heap Merge Time"", endTime - startTime);
return ret;
}
public static void main(String[] args){
int numElements = Integer.parseInt(args[0]);
HeapPerformanceTest t = new HeapPerformanceTest(numElements);
HashMap<String, Long> ret = t.test();
for (String key : ret.keySet()) {
System.out.println(key + "": "" + ret.get(key) + ""ms"");
}
}
}
",3,629,Java
servlet,./ProjectTest/Java/servlet.java,"// servlet/registration.java
package projecttest.servlet;
import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class registration extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setContentType(""text/html"");
PrintWriter out = response.getWriter();
String f=request.getParameter(""fname"");
String c=request.getParameter(""cardno"");
String cn=request.getParameter(""cono"");
String ad=request.getParameter(""add"");
String dob=request.getParameter(""dob"");
String email=request.getParameter(""email"");
String pin=request.getParameter(""pin"");
try
{
Class.forName(""com.mysql.jdbc.Driver"");
Connection con=(Connection) DriverManager.getConnection(""jdbc:mysql://localhost:3306/votingdb"",""Vaishnavi"",""Nelavetla@537"");
PreparedStatement ps=con.prepareStatement(""insert into register values(?,?,?,?,?,?,?)"");
ps.setString(1,f);
ps.setString(2,c);
ps.setString(3,cn);
ps.setString(4,ad);
ps.setString(5,dob);
ps.setString(6,email);
ps.setString(7,pin);
int i=ps.executeUpdate();
if(i>0)
{
out.print(""Successfully your account has been created...PLEASE LOGIN"");
RequestDispatcher rd=request.getRequestDispatcher(""loginpage.html"");
rd.include(request,response);
}
else
{
out.print(""Failed account creation try again"");
RequestDispatcher rd=request.getRequestDispatcher(""registration.html"");
rd.include(request,response);
}
}
catch (Exception e2) {
out.print(""Invalid , Failed account creation try again ""+e2);
RequestDispatcher rd=request.getRequestDispatcher(""registration.html"");
rd.include(request,response);
}
out.close();
}
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
doPost(request, response);
}
}
// servlet/loginpage.java
package projecttest.servlet;
import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class loginpage extends HttpServlet {
private static final long serialVersionUID = 1L;
final static Connection con=DBUtilR.getDBConnection();
static PreparedStatement ps = null;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
PrintWriter out = response.getWriter();
String card=request.getParameter(""cardno"");
Integer pin=Integer.parseInt(request.getParameter(""pin""));
try {
if(check(card,pin))
{
out.print(""Successful Login...You Can Vote Now"");
RequestDispatcher rd=request.getRequestDispatcher(""vote.html"");
rd.include(request,response);
}
else {
out.print(""Sorry username or password error , Make new account"");
RequestDispatcher rd=request.getRequestDispatcher(""registration.html"");
rd.include(request,response);
}
}
catch (SQLException e) {
e.printStackTrace();
}
}
static boolean check(String card,Integer pin) throws SQLException
{
boolean r=false;
ps=con.prepareStatement(""Select * from register where cardno=? and pin=?"");
ps.setString(1,card);
ps.setInt(2,pin);
ResultSet rs=ps.executeQuery();
r=rs.next();
return r;
}
static boolean checkvote(String card) throws SQLException
{
boolean r=false;
ps=con.prepareStatement(""Select * from vote where cardno=?"");
ps.setString(1,card);
ResultSet rs=ps.executeQuery();
r=rs.next();
return r;
}
}
// servlet/againvote.java
package projecttest.servlet;
import java.io.IOException;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
public class againvote extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
doGet(request, response);
}
}
// servlet/thankyou.java
package projecttest.servlet;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
public class thankyou extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
}
}
// servlet/DBUtilR.java
package projecttest.servlet;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBUtilR {
static Connection conn = null;
static
{
try {
Class.forName(""com.mysql.jdbc.Driver"");
conn = DriverManager.getConnection(""jdbc:mysql://localhost:3306/votingdb"", ""Vaishnavi"", ""Nelavetla@537"");
if(!conn.isClosed()) {
System.out.println(""Connection established"");
}
} catch (ClassNotFoundException | SQLException e) {
System.out.println(""Error in DBUtilFile"");
e.printStackTrace();
}
}
public static Connection getDBConnection() {
// TODO Auto-generated method stub
return conn;
}
}
// servlet/vote.java
package projecttest.servlet;
import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLIntegrityConstraintViolationException;
public class vote extends HttpServlet {
private static final long serialVersionUID = 1L;
final static Connection con=DBUtilR.getDBConnection();
static PreparedStatement ps = null;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setContentType(""text/html"");
PrintWriter out = response.getWriter();
String f=request.getParameter(""cardno"");
String l=request.getParameter(""party"");
try
{
Class.forName(""com.mysql.jdbc.Driver"");
Connection con=(Connection) DriverManager.getConnection(""jdbc:mysql://localhost:3306/votingdb"",""Vaishnavi"",""Nelavetla@537"");
if(checkLogin(f))
{
ps=con.prepareStatement(""insert into vote values(?,?)"");
ps.setString(1,f);
ps.setString(2,l);
int i=ps.executeUpdate();
if(i>0)
{
out.print(""Your Vote has been submitted successfully..."");
RequestDispatcher rd=request.getRequestDispatcher(""thankyou.html"");
rd.include(request,response);
}
else
{
out.print(""Failed to submit vote, try again"");
RequestDispatcher rd=request.getRequestDispatcher(""vote.html"");
rd.include(request,response);
}
}
else
{
out.print(""Please enter correct card number"");
RequestDispatcher rd=request.getRequestDispatcher(""vote.html"");
rd.include(request,response);
}
}
catch (SQLIntegrityConstraintViolationException e2) {
out.print(""Please select any party"");
RequestDispatcher rd=request.getRequestDispatcher(""vote.html"");
rd.include(request,response);
}
catch(Exception e)
{
out.print("" "" +e);
RequestDispatcher rd=request.getRequestDispatcher(""vote.html"");
rd.include(request,response);
}
out.close();
}
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
static boolean checkLogin(String card) throws SQLException
{
boolean r=false;
ps=con.prepareStatement(""Select * from register where cardno = ?"");
ps.setString(1,card);
ResultSet rs=ps.executeQuery();
r=rs.next();
return r;
}
}
",6,308,Java
libraryApp,./ProjectTest/Java/libraryApp.java,"// libraryApp/Book.java
package projecttest.libraryApp;
public class Book {
private int isbn;
private String title;
private String author;
private String genre;
private int quantity;
private int checkedOut;
private int checkedIn;
//Constructor for book object
public Book(int isbn, String title, String author, String genre, int quantity, int checkedOut) {
this.isbn = isbn;
this.title = title;
this.author = author;
this.genre = genre;
this.quantity = quantity;
this.checkedOut = checkedOut;
this.checkedIn = quantity-checkedOut;
}
public int getCheckedIn() {
return checkedIn;
}
public void setCheckedIn(int checkedIn) {
this.checkedIn = checkedIn;
}
public void setIsbn(int isbn) {
this.isbn = isbn;
}
public void setTitle(String title) {
this.title = title;
}
public void setAuthor(String author) {
this.author = author;
}
public void setGenre(String genre) {
this.genre = genre;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public void setCheckedOut(int checkedOut) {
this.checkedOut = checkedOut;
}
//Getter Methods
public int getIsbn() {
return isbn;
}
public String getTitle() {
return title;
}
public String getAuthor() {
return author;
}
public String getGenre() {
return genre;
}
public int getQuantity() {
return quantity;
}
public int getCheckedOut() {
return checkedOut;
}
}
// libraryApp/LibraryApp.java
package projecttest.libraryApp;
public class LibraryApp {
BookRepository repo = new BookRepository();
public void findByTitle(String title) {
repo.searchByTitle(title);
return;
}
public void findByISBN(int isbn) {
repo.searchByISBN(isbn);
return;
}
public boolean findByGenre(String genre) {
if(repo.searchByGenre(genre))
return true;
else
return false;
}
public int findISBN(int isbn) {
return repo.searchISBN(isbn);
}
public boolean withdrawBook(int isbn) {
return repo.getBook(isbn);
}
public boolean depositBook(int isbn) {
return repo.submitBook(isbn);
}
public void getStatus(int isbn) {
repo.bookStatus(isbn);
}
}
// libraryApp/Main.java
package projecttest.libraryApp;
import java.util.Scanner;
public class Main{
static Scanner scan = new Scanner(System.in);
static LibraryApp app = new LibraryApp();
public static void main(String[] args) {
int userChoice=0;
System.out.println(""-----Welcome to the Library!-----\n"");
do{
System.out.println(""\n-----------------------------------"");
System.out.println(""1. Search book by Title keyword."");
System.out.println(""2. Search book by ISBN number."");
System.out.println(""3. Search book by Genre."");
System.out.println(""4. Book Check In"");
System.out.println(""5. Book Check Out"");
System.out.println(""6. Exit from the library."");
System.out.println(""-----------------------------------"");
System.out.print(""\nChoose any option: "");
userChoice = scan.nextInt();
scan.nextLine();
switch(userChoice){
case 1:
System.out.print(""Enter the Title of Book: "");
app.findByTitle(scan.nextLine());
break;
case 2:
System.out.println(""Enter ISBN number: "");
app.findByISBN(scan.nextInt());
break;
case 3:
System.out.println(""Enter Genre: "");
app.findByGenre(scan.nextLine());
break;
case 4:
checkIn();
break;
case 5:
checkOut();
break;
case 6:
System.out.println(""\nThanks for visiting. \nSee you again."");
break;
default:
System.out.println(""\nInvalid Choice!"");
}
}while(userChoice!=6);
}
//Checking book In
private static void checkIn() {
System.out.println(""Enter Book's ISBN number : "");
int isbnNum = scan.nextInt();
getStatus(isbnNum);
int bookAvailable = app.findISBN(isbnNum);
if(bookAvailable==1) {
System.out.println(isbnNum);
app.withdrawBook(isbnNum);
System.out.println(""Book CheckIn successful."");
getStatus(isbnNum);
}
else
System.out.printf(""Book with %d ISBN number not Found in inventory."",isbnNum);
}
//Checking book Out
private static void checkOut() {
System.out.println(""\nEnter Book's ISBN number : "");
int isbnNum = scan.nextInt();
int bookAvailable = app.findISBN(isbnNum);
if(bookAvailable==1) {
if(app.depositBook(isbnNum))
System.out.println(""Book CheckOut successful."");
else
System.out.println(""No Space for more Books."");
}
else
System.out.printf(""Book with %d ISBN number not Found in inventory."",isbnNum);
}
private static void getStatus(int isbn) {
app.getStatus(isbn);
}
}
// libraryApp/BookRepository.java
package projecttest.libraryApp;
import java.util.ArrayList;
public class BookRepository {
private ArrayList<Book> books = new ArrayList<>();
private int booksFound = 0;
//Constructor to initialize books
public BookRepository(){
books.add(new Book(253910,""Pride and Prejudice C"", ""Jane Austen"", ""Love"",10,7));
books.add(new Book(391520,""Programming in ANSI C"", ""E. Balagurusamy"", ""Educational"",15,10));
books.add(new Book(715332,""Shrimad Bhagavad Gita"", ""Krishna Dvaipayana"", ""Motivational"",20,18));
books.add(new Book(935141,""Java: The Complete Reference"", ""Herbert Schildt"", ""Educational"",12,9));
books.add(new Book(459901,""It"", ""Stephan King"", ""Horror"",7,5));
books.add(new Book(855141,""Disneyland"", ""Mickey & Minnie"", ""Love"",10,3));
}
//Searching books by Title Keyword
public void searchByTitle(String title) {
booksFound = 0;
for(Book book : books) {
String bookTitle = book.getTitle();
if(bookTitle.toLowerCase().contains(title.toLowerCase())) {
bookDetails(book);
booksFound++;
}
}
System.out.printf(""\n%d Book%s Found.\n"",booksFound,booksFound>1?""s"":"""");
return;
}
//Searching books by ISBN Number
public void searchByISBN(int isbn) {
booksFound = 0;
for(Book book : books) {
if(book.getIsbn()==isbn) {
bookDetails(book);
booksFound++;
break;
}
}
System.out.printf(""\n%d Book%s Found.\n"",booksFound,booksFound>1?""s"":"""");
return;
}
//Searching books by Genre
public boolean searchByGenre(String genre){
booksFound = 0;
for(Book book : books) {
String bookGenre = book.getGenre();
if(bookGenre.toLowerCase().equals(genre.toLowerCase())) {
bookDetails(book);
booksFound++;
}
}
System.out.printf(""\n%d Book%s Found.\n"",booksFound,booksFound>1?""s"":"""");
if(booksFound>0)
return true;
else
return false;
}
// Display Book Details
public void bookDetails(Book book) {
System.out.println(""\n+> Book details: \n"");
System.out.println(""\tTitle: ""+book.getTitle()+""\n\tAuthor: ""+ book.getAuthor()+""\n\tGenre: ""+book.getGenre()+""\n\tISBN: ""+book.getIsbn()+""\n\tQuantity: ""+book.getQuantity()+""\n\tChecked Out: ""+String.valueOf(book.getCheckedOut())+""\n\tAvailable: ""+String.valueOf(book.getQuantity()-book.getCheckedOut()));
}
//Searching for ISBN number for checkIn and checkOut
public int searchISBN(int isbn) {
for(Book book:books)
if(book.getIsbn()==isbn)
return 1;
return 0;
}
//withdrawing book
public boolean getBook(int isbn) {
for(Book book: books) {
if(book.getIsbn()==isbn) {
if((book.getQuantity()-book.getCheckedOut())>0) {
book.setCheckedOut(book.getCheckedOut()+1);
return true;
}
}
}
return false;
}
//submitting book
public boolean submitBook(int isbn) {
for(Book book: books) {
if(book.getQuantity()>book.getCheckedIn()) {
book.setCheckedOut(book.getCheckedOut()-1);
return true;
}
}
return false;
}
//Showing status of book
public void bookStatus(int isbn) {
for(Book book: books) {
if(book.getIsbn()==isbn) {
bookDetails(book);
break;
}
}
}
}
",4,340,Java
libraryManagement,./ProjectTest/Java/libraryManagement.java,"// libraryManagement/LibFunctions.java
package projecttest.libraryManagement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Scanner;
public class LibFunctions {
public static void callIssueMenu() {
System.out.println(""Reached inside issue book menu"");
Member m = new Member();
Book b = new Book();
Scanner sc = new Scanner(System.in);
int addStatus = 0;
while (addStatus == 0) {
try {
System.out.println(""Enter the member id "");
m.setMemberId(Integer.parseInt(sc.nextLine().toString()));
System.out.println(""Enter the isbn code "");
b.setIsbnCode(sc.nextLine().toString());
issueBook(m, b);
addStatus = 1;
} catch (Exception e) {
addStatus = 0;
}
}
}
public static void issueBook(Member m, Book b) {
Connection conn = LibUtil.getConnection();
try {
Statement stmt = conn.createStatement();
ResultSet rs = null;
String qry = ""select m.member_id, b.isbn_code, mbr.rec_id from members m,books b,member_book_record mbr\n""
+ ""where m.member_id= "" + m.getMemberId() + "" \n""
+ ""and b.isbn_code = '"" + b.getIsbnCode() + ""' \n""
+ ""and m.member_id=mbr.member_id\n""
+ ""and b.isbn_code=mbr.isbn_code and mbr.dor is null "";
rs=stmt.executeQuery(qry);
if (rs.next()) {
System.out.println(""The book is already issued and cannot be issued again"");
} else {
int k = stmt.executeUpdate(""insert into member_book_record values(lib_seq.nextval,"" + m.getMemberId() + "",'"" + b.getIsbnCode() + ""',sysdate,null)"");
if(k > 0){
k = stmt.executeUpdate(""update books set units_available= (units_available-1) where isbn_code = '""+ b.getIsbnCode() +""' "");
conn.commit();
System.out.println(""The book is issued successfully"");
}else{
conn.rollback();
}
}
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void callReturnMenu() {
System.out.println(""Reached inside return book menu"");
Member m = new Member();
Book b = new Book();
Scanner sc = new Scanner(System.in);
int addStatus = 0;
while (addStatus == 0) {
try {
System.out.println(""Enter the member id "");
m.setMemberId(Integer.parseInt(sc.nextLine().toString()));
System.out.println(""Enter the isbn code "");
b.setIsbnCode(sc.nextLine().toString());
returnBook(m, b);
addStatus = 1;
} catch (Exception e) {
addStatus = 0;
}
}
}
public static void returnBook(Member m, Book b) {
Connection conn = LibUtil.getConnection();
try {
Statement stmt = conn.createStatement();
ResultSet rs = null;
String qry = ""select m.member_id, b.isbn_code, mbr.rec_id from members m,books b,member_book_record mbr\n""
+ ""where m.member_id= "" + m.getMemberId() + "" \n""
+ ""and b.isbn_code = '"" + b.getIsbnCode() + ""' \n""
+ ""and m.member_id=mbr.member_id\n""
+ ""and b.isbn_code=mbr.isbn_code and mbr.dor is null "";
rs=stmt.executeQuery(qry);
if (rs.next()) {
Integer recId= rs.getInt(3);
System.out.println(""The book is already issued and starting the process to return "");
int k = stmt.executeUpdate(""update books set units_available= (units_available+1) where isbn_code = '""+ b.getIsbnCode() +""' "");
if(k > 0){
k = stmt.executeUpdate(""update member_book_record set dor= sysdate where rec_id = ""+ recId +"" "");
conn.commit();
System.out.println(""The book is returned successfully"");
}else{
conn.rollback();
}
} else{
System.out.println(""This book is not issued for the user"");
}
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
// libraryManagement/Member.java
package projecttest.libraryManagement;
import java.sql.Date;
/**
*
* @author testuser
*/
public class Member {
private Integer memberId;
private String memberName;
private Date dateOfJoining;
public Member() {
}
public Member(Integer memberId, String memberName, Date dateOfJoining) {
this.memberId = memberId;
this.memberName = memberName;
this.dateOfJoining = dateOfJoining;
}
public Date getDateOfJoining() {
return dateOfJoining;
}
public void setDateOfJoining(Date dateOfJoining) {
this.dateOfJoining = dateOfJoining;
}
public Integer getMemberId() {
return memberId;
}
public void setMemberId(Integer memberId) {
this.memberId = memberId;
}
public String getMemberName() {
return memberName;
}
public void setMemberName(String memberName) {
this.memberName = memberName;
}
}
// libraryManagement/Book.java
package projecttest.libraryManagement;
/**
*
* @author testuser
*/
public class Book {
private String isbnCode;
private String bookName;
private String bookDesc;
private String authorName;
private String subjectName;
private Integer unitsAvailable;
public Book(){
}
public Book(String isbnCode, String bookName, String bookDesc, String authorName, String subjectName, Integer unitsAvailable) {
this.isbnCode = isbnCode;
this.bookName = bookName;
this.bookDesc = bookDesc;
this.authorName = authorName;
this.subjectName = subjectName;
this.unitsAvailable = unitsAvailable;
}
public Integer getUnitsAvailable() {
return unitsAvailable;
}
public void setUnitsAvailable(Integer unitsAvailable) {
this.unitsAvailable = unitsAvailable;
}
public String getIsbnCode() {
return isbnCode;
}
public void setIsbnCode(String isbnCode) {
this.isbnCode = isbnCode;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public String getBookDesc() {
return bookDesc;
}
public void setBookDesc(String bookDesc) {
this.bookDesc = bookDesc;
}
public String getAuthorName() {
return authorName;
}
public void setAuthorName(String authorName) {
this.authorName = authorName;
}
public String getSubjectName() {
return subjectName;
}
public void setSubjectName(String subjectName) {
this.subjectName = subjectName;
}
}
// libraryManagement/UserMenu.java
package projecttest.libraryManagement;
import java.util.Scanner;
/**
*
* @author testuser
*/
public class UserMenu {
public static void main(String[] args) {
String input="""";
Scanner sc = new Scanner(System.in);
while(input != ""5""){
System.out.println(""---------------------------------------------------------"");
System.out.println(""---------------------------------------------------------"");
System.out.println(""---------------------------------------------------------"");
System.out.println(""Select the following options"");
System.out.println(""Enter 1 for adding a book"");
System.out.println(""Enter 2 for adding a member"");
System.out.println(""Enter 3 for issuing a book "");
System.out.println(""Enter 4 for returning a book "");
System.out.println(""Enter 5 to exit"");
input = processUserInput(sc.nextLine().toString());
}
}
public static String processUserInput(String in) {
String retVal=""5"";
switch(in){
case ""1"":
System.out.println(""---------------------------------------------------------"");
System.out.println(""You have selected option 1 to add a book"");
AddBookMenu.addBookMenu();
return ""1"";
case ""2"":
System.out.println(""---------------------------------------------------------"");
System.out.println(""You have selected option 2 to add a member"");
AddMemberMenu.addMemberMenu();
return ""2"";
case ""3"":
System.out.println(""---------------------------------------------------------"");
System.out.println(""You have selected option 3 to issue a book"");
LibFunctions.callIssueMenu();
return ""3"";
case ""4"":
System.out.println(""---------------------------------------------------------"");
System.out.println(""You have selected option 4 to return a book"");
LibFunctions.callReturnMenu();
return ""4"";
default:
System.out.println(""---------------------------------------------------------"");
System.out.println(""Thanks for working on this!!"");
return ""5"";
}
}
}
// libraryManagement/LibUtil.java
package projecttest.libraryManagement;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author testuser
*/
public class LibUtil {
public static Connection getConnection() {
Connection conn = null;
try {
Properties prop = new Properties();
FileInputStream in = new FileInputStream(""src/DBProperties"");
prop.load(in);
String driverName= prop.getProperty(""DBDriver"");
Class.forName(driverName);
String dbName,user,password;
dbName= prop.getProperty(""DBName"");
user = prop.getProperty(""User"");
password= prop.getProperty(""Password"");
conn= DriverManager.getConnection(dbName, user, password);
return conn;
} catch (Exception e) {
}
return conn;
}
}
// libraryManagement/AddMemberMenu.java
package projecttest.libraryManagement;
import java.sql.Connection;
import java.sql.Statement;
import java.util.Scanner;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author testuser
*/
public class AddMemberMenu {
public static void addMemberMenu() {
System.out.println(""Reached the add member menu"");
Member m = new Member();
Scanner sc = new Scanner(System.in);
int addStatus = 0;
while (addStatus == 0) {
try {
System.out.println(""Enter the member id "");
m.setMemberId(Integer.parseInt(sc.nextLine().toString()));
System.out.println(""Enter the member name"");
m.setMemberName(sc.nextLine().toString());
addMember(m);
addStatus = 1;
} catch (Exception e) {
addStatus=0;
}
}
}
public static void addMember(Member m) {
System.out.println(""Reached inside add member for member ""+m.getMemberId());
Connection conn = LibUtil.getConnection();
try {
Statement stmt = conn.createStatement();
int k = stmt.executeUpdate(""insert into members values (""+m.getMemberId()+"",'""+m.getMemberName()+""',sysdate)"");
if(k>0){
System.out.println(""Added Member successfully"");
conn.commit();
}else{
conn.rollback();
}
conn.close();
} catch (Exception e) {
}
}
}
// libraryManagement/AddBookMenu.java
package projecttest.libraryManagement;
import java.sql.Connection;
import java.sql.Statement;
import java.util.Scanner;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author testuser
*/
public class AddBookMenu {
public static void addBookMenu() {
System.out.println(""Reached the add book menu"");
Book b = new Book();
Scanner sc = new Scanner(System.in);
int addStatus = 0;
while (addStatus == 0) {
try {
System.out.println(""Enter the isbn code"");
b.setIsbnCode(sc.nextLine().toString());
System.out.println(""Enter the book name"");
b.setBookName(sc.nextLine().toString());
System.out.println(""Enter the book desc"");
b.setBookDesc(sc.nextLine().toString());
System.out.println(""Enter the author name"");
b.setAuthorName(sc.nextLine().toString());
System.out.println(""Enter the subject "");
b.setSubjectName(sc.nextLine().toString());
System.out.println(""Enter the units available"");
b.setUnitsAvailable(Integer.parseInt(sc.nextLine().toString()));
addBook(b);
addStatus = 1;
} catch (Exception e) {
addStatus=0;
}
}
}
public static void addBook(Book b) {
System.out.println(""Reached inside addBook for book ""+b.getIsbnCode());
Connection conn = LibUtil.getConnection();
try {
Statement stmt = conn.createStatement();
int k = stmt.executeUpdate(""insert into books values ('""+b.getIsbnCode()+""','""+b.getBookName()+""','""+b.getBookDesc()+""',""
+ ""'""+b.getAuthorName()+""','""+b.getSubjectName()+""',""+b.getUnitsAvailable()+"")"");
if(k>0){
System.out.println(""Added Book successfully"");
conn.commit();
}else{
conn.rollback();
}
conn.close();
} catch (Exception e) {
}
}
}
",7,483,Java
SimpleChat,./ProjectTest/Java/SimpleChat.java,"// SimpleChat/Server.java
package projecttest.SimpleChat;
import java.io.*;
import java.net.*;
import java.util.*;
class VerySimpleChatServer {
ArrayList clientOutputStreams;
public class ClientHandler implements Runnable {
BufferedReader reader;
Socket sock;
public ClientHandler(Socket clientSocket) {
try {
sock = clientSocket;
InputStreamReader isReader = new InputStreamReader(sock.getInputStream());
reader = new BufferedReader(isReader);
} catch (Exception ex) {
ex.printStackTrace();
}
} // close constructor
public void run() {
String message;
try {
while ((message = reader.readLine()) != null) {
System.out.println(""read "" + message);
tellEveryone(message);
} // close while
} catch (Exception ex) {
ex.printStackTrace();
}
} // close run
}
// close inner class
public static void main(String[] args) {
new VerySimpleChatServer().go();
}
public void go() {
clientOutputStreams = new ArrayList();
try {
ServerSocket serverSock = new ServerSocket(5000);
while (true) {
Socket clientSocket = serverSock.accept();
PrintWriter writer = new PrintWriter(clientSocket.getOutputStream());
clientOutputStreams.add(writer);
Thread t = new Thread(new ClientHandler(clientSocket));
t.start();
System.out.println(""got a connection"");
}
} catch (Exception ex) {
ex.printStackTrace();
}
} // close go
public void tellEveryone(String message) {
Iterator it = clientOutputStreams.iterator();
while (it.hasNext()) {
try {
PrintWriter writer = (PrintWriter) it.next();
writer.println(message);
writer.flush();
} catch (Exception ex) {
ex.printStackTrace();
}
} // end while
} // close tellEveryone
} // close class
// SimpleChat/Client.java
package projecttest.SimpleChat;
import java.io.*;
import java.net.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Client {
JTextArea incoming;
JTextField outgoing;
BufferedReader reader;
PrintWriter writer;
Socket sock;
public static void main(String[] args) {
Client client = new Client();
client.go();
}
public void go() {
JFrame frame = new JFrame(""Ludicrously Simple Chat Client"");
JPanel mainPanel = new JPanel();
incoming = new JTextArea(15, 50);
incoming.setLineWrap(true);
incoming.setWrapStyleWord(true);
incoming.setEditable(false);
JScrollPane qScroller = new JScrollPane(incoming);
qScroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
qScroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
outgoing = new JTextField(20);
JButton sendButton = new JButton(""Send"");
sendButton.addActionListener(new SendButtonListener());
mainPanel.add(qScroller);
mainPanel.add(outgoing);
mainPanel.add(sendButton);
setUpNetworking();
Thread readerThread = new Thread(new IncomingReader());
readerThread.start();
frame.getContentPane().add(BorderLayout.CENTER, mainPanel);
frame.setSize(400, 500);
frame.setVisible(true);
}
private void setUpNetworking() {
try {
sock = new Socket(""192.168.5.16"", 5000);
InputStreamReader streamReader = new InputStreamReader(sock.getInputStream());
reader = new BufferedReader(streamReader);
writer = new PrintWriter(sock.getOutputStream());
System.out.println(""networking established"");
} catch (IOException ex) {
ex.printStackTrace();
}
} // close setUpNetworking
public class SendButtonListener implements ActionListener {
public void actionPerformed(ActionEvent ev) {
try {
writer.println(outgoing.getText());
writer.flush();
} catch (Exception ex) {
ex.printStackTrace();
}
outgoing.setText("""");
outgoing.requestFocus();
}
} // close inner class
public class IncomingReader implements Runnable {
public void run() {
String message;
try {
while ((message = reader.readLine()) != null) {
System.out.println(""read "" + message);
incoming.append(message + ""\n"");
} // close while
} catch (Exception ex) {
ex.printStackTrace();
}
} // close run
}
}
",2,170,Java
springmicrometerundertow,./ProjectTest/Java/springmicrometerundertow.java,"// springmicrometerundertow/SpringMicrometerUndertowApplication.java
package projecttest.springmicrometerundertow;
import io.micrometer.core.instrument.MeterRegistry;
import io.undertow.server.HandlerWrapper;
import io.undertow.server.handlers.MetricsHandler;
import io.undertow.servlet.api.MetricsCollector;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.actuate.autoconfigure.metrics.MeterRegistryCustomizer;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.embedded.undertow.UndertowDeploymentInfoCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class SpringMicrometerUndertowApplication {
public static void main(String[] args) {
SpringApplication.run(SpringMicrometerUndertowApplication.class, args);
}
@Bean
UndertowDeploymentInfoCustomizer undertowDeploymentInfoCustomizer(UndertowMetricsHandlerWrapper undertowMetricsHandlerWrapper) {
return deploymentInfo -> deploymentInfo.addOuterHandlerChainWrapper(undertowMetricsHandlerWrapper);
//return deploymentInfo -> deploymentInfo.addOuterHandlerChainWrapper(MetricsHandler.WRAPPER);
}
@Bean
MeterRegistryCustomizer<MeterRegistry> micrometerMeterRegistryCustomizer(@Value(""${spring.application.name}"") String applicationName) {
return registry -> registry.config().commonTags(""application.name"", applicationName);
}
@GetMapping(value = ""/hello"", produces = MediaType.APPLICATION_JSON_VALUE)
public String hello(@RequestParam(name = ""name"", required = true) String name) {
return ""Hello "" + name + ""!"";
}
}
// springmicrometerundertow/UndertowMeterBinder.java
package projecttest.springmicrometerundertow;
import io.micrometer.core.instrument.FunctionCounter;
import io.micrometer.core.instrument.FunctionTimer;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.TimeGauge;
import io.micrometer.core.instrument.binder.MeterBinder;
import io.undertow.server.handlers.MetricsHandler;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;
import java.util.function.ToDoubleFunction;
import java.util.function.ToLongFunction;
@Component
public class UndertowMeterBinder implements ApplicationListener<ApplicationReadyEvent> {
private final UndertowMetricsHandlerWrapper undertowMetricsHandlerWrapper;
public UndertowMeterBinder(UndertowMetricsHandlerWrapper undertowMetricsHandlerWrapper) {
this.undertowMetricsHandlerWrapper = undertowMetricsHandlerWrapper;
}
@Override
public void onApplicationEvent(ApplicationReadyEvent applicationReadyEvent) {
bindTo(applicationReadyEvent.getApplicationContext().getBean(MeterRegistry.class));
}
public void bindTo(MeterRegistry meterRegistry) {
bind(meterRegistry, undertowMetricsHandlerWrapper.getMetricsHandler());
}
public void bind(MeterRegistry registry, MetricsHandler metricsHandler) {
bindTimer(registry, ""undertow.requests"", ""Number of requests"", metricsHandler,
m -> m.getMetrics().getTotalRequests(), m2 -> m2.getMetrics().getMinRequestTime());
bindTimeGauge(registry, ""undertow.request.time.max"", ""The longest request duration in time"", metricsHandler,
m -> m.getMetrics().getMaxRequestTime());
bindTimeGauge(registry, ""undertow.request.time.min"", ""The shortest request duration in time"", metricsHandler,
m -> m.getMetrics().getMinRequestTime());
bindCounter(registry, ""undertow.request.errors"", ""Total number of error requests "", metricsHandler,
m -> m.getMetrics().getTotalErrors());
}
private void bindTimer(MeterRegistry registry, String name, String desc, MetricsHandler metricsHandler,
ToLongFunction<MetricsHandler> countFunc, ToDoubleFunction<MetricsHandler> consumer) {
FunctionTimer.builder(name, metricsHandler, countFunc, consumer, TimeUnit.MILLISECONDS)
.description(desc).register(registry);
}
private void bindTimeGauge(MeterRegistry registry, String name, String desc, MetricsHandler metricResult,
ToDoubleFunction<MetricsHandler> consumer) {
TimeGauge.builder(name, metricResult, TimeUnit.MILLISECONDS, consumer).description(desc)
.register(registry);
}
private void bindCounter(MeterRegistry registry, String name, String desc, MetricsHandler metricsHandler,
ToDoubleFunction<MetricsHandler> consumer) {
FunctionCounter.builder(name, metricsHandler, consumer).description(desc)
.register(registry);
}
}
// springmicrometerundertow/UndertowMetricsHandlerWrapper.java
package projecttest.springmicrometerundertow;
import io.undertow.server.HandlerWrapper;
import io.undertow.server.HttpHandler;
import io.undertow.server.handlers.MetricsHandler;
import org.springframework.stereotype.Component;
@Component
public class UndertowMetricsHandlerWrapper implements HandlerWrapper {
private MetricsHandler metricsHandler;
@Override
public HttpHandler wrap(HttpHandler handler) {
metricsHandler = new MetricsHandler(handler);
return metricsHandler;
}
public MetricsHandler getMetricsHandler() {
return metricsHandler;
}
}
",3,130,Java
logrequestresponseundertow,./ProjectTest/Java/logrequestresponseundertow.java,"// logrequestresponseundertow/Song.java
package projecttest.logrequestresponseundertow;
import lombok.*;
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Song {
private Long id;
private String name;
private String author;
}
// logrequestresponseundertow/Application.java
package projecttest.logrequestresponseundertow;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.embedded.undertow.UndertowServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import io.undertow.server.handlers.RequestDumpingHandler;
import lombok.extern.log4j.Log4j2;
@SpringBootApplication
@Log4j2
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
public UndertowServletWebServerFactory undertowServletWebServerFactory() {
UndertowServletWebServerFactory factory = new UndertowServletWebServerFactory();
factory.addDeploymentInfoCustomizers(deploymentInfo ->
deploymentInfo.addInitialHandlerChainWrapper(handler -> {
return new RequestDumpingHandler(handler);
}));
return factory;
}
@Bean
public UndertowServletWebServerFactory UndertowServletWebServerFactory() {
UndertowServletWebServerFactory UndertowServletWebServerFactory = new UndertowServletWebServerFactory();
UndertowServletWebServerFactory.addDeploymentInfoCustomizers(deploymentInfo -> deploymentInfo.addInitialHandlerChainWrapper(handler -> {
return new RequestDumpingHandler(handler);
}));
return UndertowServletWebServerFactory;
}
}
// logrequestresponseundertow/SongController.java
package projecttest.logrequestresponseundertow;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import org.springframework.web.bind.annotation.*;
@RestController
public class SongController {
@PostMapping(""/songs"")
public Song createSong(@RequestBody Song song) {
song.setId(new Random().nextLong());
return song;
}
@GetMapping(""/songs"")
public List<Song> getSongs() {
List<Song> songs = new ArrayList<>();
songs.add(Song.builder().id(1L).name(""name1"").author(""author2"").build());
songs.add(Song.builder().id(2L).name(""name2"").author(""author2"").build());
return songs;
}
}
",3,85,Java
Train,./ProjectTest/Java/Train.java,"// Train/Driver.java
package projecttest.Train;
public class Driver
{
/**
* This testdriver wil test the difrent methods from train and trainstation
*/
public static void test() {
Train t1 = new Train(""Aarhus"", ""Berlin"", 999);
Train t2 = new Train(""Herning"", ""Copenhagen"", 42);
Train t3 = new Train(""Aarhus"", ""Herning"", 66);
Train t4 = new Train(""Odense"", ""Herning"", 177);
Train t5 = new Train(""Aarhus"", ""Copenhagen"", 122);
System.out.println(""Opgave 3:"");
System.out.println(""*******************"");
System.out.println(t1);
System.out.println(t2);
System.out.println(t3);
System.out.println(t4);
System.out.println(t5);
System.out.println(""*******************"");
System.out.println("""");
TrainStation ts = new TrainStation(""Herning"");
ts.addTrain(t1);
ts.addTrain(t2);
ts.addTrain(t3);
ts.addTrain(t4);
ts.addTrain(t5);
System.out.println(""Opgave 8:"");
System.out.println(""*******************"");
System.out.println(""No. of trains going from or to Herning:"");
System.out.println(ts.connectingTrains());
System.out.println(""*******************"");
System.out.println("""");
System.out.println(""Opgave 9:"");
System.out.println(""*******************"");
System.out.println(""The cheapest train going to Copenhagen is going:"");
System.out.println(ts.cheapTrainTo(""Copenhagen""));
System.out.println(""*******************"");
System.out.println("""");
System.out.println(""Opgave 10:"");
System.out.println(""*******************"");
ts.printTrainStation();
System.out.println(""*******************"");
System.out.println("""");
System.out.println(""Opgave 11:"");
System.out.println(""*******************"");
System.out.println(""Trains going from Aarhus to Herning:"");
for(Train t : ts.trainsFrom(""Aarhus"")) {
System.out.println(t);
}
System.out.println(""*******************"");
System.out.println("""");
System.out.println(""Opgave 12:"");
System.out.println(""*******************"");
System.out.println(""The cheapest train going from herning to Copenhagen:"");
System.out.println(ts.cheapTrain(""Copenhagen""));
System.out.println(""*******************"");
System.out.println("""");
}
}
// Train/TrainStation.java
package projecttest.Train;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.Comparator;
public class TrainStation
{
private String city;
private ArrayList<Train> trains;
public TrainStation(String city)
{
this.city = city;
trains = new ArrayList<Train>();
}
/**
* this method adds trains tot the ArrayList trains
*/
public void addTrain(Train t) {
trains.add(t);
}
/**
* Method will return the number of trains that starts or ends in the
* city of the Trainstation
*/
public int connectingTrains() {
int result = 0;
for(Train t : trains) {
if(city.equals(t.getDeparture()) || city.equals(t.getDestiantion())) {
result ++;
}
}
return result;
}
/**
* This method returns the chepest train go to a spesific destination
*/
public Train cheapTrainTo(String destination) {
Train result = null;
for(Train t : trains) {
if(destination.equals(t.getDestiantion())) {
if(result == null || result.getPrice() > t.getPrice()) {
result = t;
}
}
}
return result;
}
/**
* This method prints out all trains in the ArrayList trains
* in sorted order after the departurs in alphabeticly order
* if they have the same departures then it wil sort after price
* from lovest til highest
*/
public void printTrainStation() {
Collections.sort(trains);
System.out.println(""The trainstaion in "" + city + "" has following trains:"");
for(Train t : trains) {
System.out.println(t);
}
}
/**
* This method will return all trains that starts in a given place
* going to the Trainstations city.
*/
public List<Train> trainsFrom(String departure) {
return trains.stream()
.filter(t -> t.getDeparture().equals(departure) && t.getDestiantion().equals(city))
.collect(Collectors.toList());
}
/**
* This method returns the cheapest train strating in the Trainstations
* city, and ends in a given destination
*/
public Train cheapTrain(String destination) {
return trains.stream()
.filter(t -> t.getDeparture().equals(city) && t.getDestiantion().equals(destination))
.min(Comparator.comparing(t -> t.getPrice()))
.orElse(null);
}
}
// Train/Train.java
package projecttest.Train;
import java.util.Collections;
public class Train implements Comparable<Train>
{
private String departure;
private String destination;
private int price;
public Train(String departure, String destination, int price)
{
this.departure = departure;
this.destination = destination;
this.price = price;
}
/**
* A method to get the departure
*/
public String getDeparture() {
return departure;
}
/**
* A method to get the destiantion
*/
public String getDestiantion() {
return destination;
}
/**
* A method to get grice
*/
public int getPrice() {
return price;
}
/**
* This method will format a String of the given way
*/
public String toString() {
return ""From "" + departure + "" to "" + destination + "" for "" + price + "" DKK"";
}
/**
* This method sorts departures alphabeticly, if they have the same
* departures then it wil sort after price from lovest til highest
*/
public int compareTo(Train other) {
if(!departure.equals(other.departure)) {
return departure.compareTo(other.departure);
} else
{
return price - other.price;
}
}
}
",3,216,Java
bankingApplication,./ProjectTest/Java/bankingApplication.java,"// bankingApplication/bankManagement.java
package projecttest.bankingApplication;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLIntegrityConstraintViolationException;
import java.sql.Statement;
public class bankManagement { // these class provides all
// bank method
private static final int NULL = 0;
static Connection con = connection.getConnection();
static String sql = """";
public static boolean
createAccount(String name,
int passCode) // create account function
{
try {
// validation
if (name == """" || passCode == NULL) {
System.out.println(""All Field Required!"");
return false;
}
// query
Statement st = con.createStatement();
sql = ""INSERT INTO customer(cname,balance,pass_code) values('""
+ name + ""',1000,"" + passCode + "")"";
// Execution
if (st.executeUpdate(sql) == 1) {
System.out.println(name
+ "", Now You Login!"");
return true;
}
// return
}
catch (SQLIntegrityConstraintViolationException e) {
System.out.println(""Username Not Available!"");
}
catch (Exception e) {
e.printStackTrace();
}
return false;
}
public static boolean
loginAccount(String name, int passCode) // login method
{
try {
// validation
if (name == """" || passCode == NULL) {
System.out.println(""All Field Required!"");
return false;
}
// query
sql = ""select * from customer where cname='""
+ name + ""' and pass_code="" + passCode;
PreparedStatement st
= con.prepareStatement(sql);
ResultSet rs = st.executeQuery();
// Execution
BufferedReader sc = new BufferedReader(
new InputStreamReader(System.in));
if (rs.next()) {
// after login menu driven interface method
int ch = 5;
int amt = 0;
int senderAc = rs.getInt(""ac_no"");
;
int receiveAc;
while (true) {
try {
System.out.println(
""Hallo, ""
+ rs.getString(""cname""));
System.out.println(
""1)Transfer Money"");
System.out.println(""2)View Balance"");
System.out.println(""5)LogOut"");
System.out.print(""Enter Choice:"");
ch = Integer.parseInt(
sc.readLine());
if (ch == 1) {
System.out.print(
""Enter Receiver A/c No:"");
receiveAc = Integer.parseInt(
sc.readLine());
System.out.print(
""Enter Amount:"");
amt = Integer.parseInt(
sc.readLine());
if (bankManagement
.transferMoney(
senderAc, receiveAc,
amt)) {
System.out.println(
""MSG : Money Sent Successfully!\n"");
}
else {
System.out.println(
""ERR : Failed!\n"");
}
}
else if (ch == 2) {
bankManagement.getBalance(
senderAc);
}
else if (ch == 5) {
break;
}
else {
System.out.println(
""Err : Enter Valid input!\n"");
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
else {
return false;
}
// return
return true;
}
catch (SQLIntegrityConstraintViolationException e) {
System.out.println(""Username Not Available!"");
}
catch (Exception e) {
e.printStackTrace();
}
return false;
}
public static void
getBalance(int acNo) // fetch balance method
{
try {
// query
sql = ""select * from customer where ac_no=""
+ acNo;
PreparedStatement st
= con.prepareStatement(sql);
ResultSet rs = st.executeQuery(sql);
System.out.println(
""-----------------------------------------------------------"");
System.out.printf(""%12s %10s %10s\n"",
""Account No"", ""Name"",
""Balance"");
// Execution
while (rs.next()) {
System.out.printf(""%12d %10s %10d.00\n"",
rs.getInt(""ac_no""),
rs.getString(""cname""),
rs.getInt(""balance""));
}
System.out.println(
""-----------------------------------------------------------\n"");
}
catch (Exception e) {
e.printStackTrace();
}
}
public static boolean transferMoney(int sender_ac,
int reveiver_ac,
int amount)
throws SQLException // transfer money method
{
// validation
if (reveiver_ac == NULL || amount == NULL) {
System.out.println(""All Field Required!"");
return false;
}
try {
con.setAutoCommit(false);
sql = ""select * from customer where ac_no=""
+ sender_ac;
PreparedStatement ps
= con.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
if (rs.getInt(""balance"") < amount) {
System.out.println(
""Insufficient Balance!"");
return false;
}
}
Statement st = con.createStatement();
// debit
con.setSavepoint();
sql = ""update customer set balance=balance-""
+ amount + "" where ac_no="" + sender_ac;
if (st.executeUpdate(sql) == 1) {
System.out.println(""Amount Debited!"");
}
// credit
sql = ""update customer set balance=balance+""
+ amount + "" where ac_no="" + reveiver_ac;
st.executeUpdate(sql);
con.commit();
return true;
}
catch (Exception e) {
e.printStackTrace();
con.rollback();
}
// return
return false;
}
}
// bankingApplication/connection.java
package projecttest.bankingApplication;
import java.sql.Connection;
import java.sql.DriverManager;
// Global connection Class
public class connection {
static Connection con; // Global Connection Object
public static Connection getConnection()
{
try {
String mysqlJDBCDriver
= ""com.mysql.cj.jdbc.Driver""; //jdbc driver
String url
= ""jdbc:mysql://localhost:3306/mydata""; //mysql url
String user = ""root""; //mysql username
String pass = ""Pritesh4@""; //mysql passcode
Class.forName(mysqlJDBCDriver);
con = DriverManager.getConnection(url, user,
pass);
}
catch (Exception e) {
System.out.println(""Connection Failed!"");
}
return con;
}
}
// bankingApplication/bank.java
package projecttest.bankingApplication;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class bank {
public static void main(String args[]) //main class of bank
throws IOException
{
BufferedReader sc = new BufferedReader(
new InputStreamReader(System.in));
String name = """";
int pass_code;
int ac_no;
int ch;
while (true) {
System.out.println(
""\n ->|| Welcome to InBank ||<- \n"");
System.out.println(""1)Create Account"");
System.out.println(""2)Login Account"");
try {
System.out.print(""\n Enter Input:""); //user input
ch = Integer.parseInt(sc.readLine());
switch (ch) {
case 1:
try {
System.out.print(
""Enter Unique UserName:"");
name = sc.readLine();
System.out.print(
""Enter New Password:"");
pass_code = Integer.parseInt(
sc.readLine());
if (bankManagement.createAccount(
name, pass_code)) {
System.out.println(
""MSG : Account Created Successfully!\n"");
}
else {
System.out.println(
""ERR : Account Creation Failed!\n"");
}
}
catch (Exception e) {
System.out.println(
"" ERR : Enter Valid Data::Insertion Failed!\n"");
}
break;
case 2:
try {
System.out.print(
""Enter UserName:"");
name = sc.readLine();
System.out.print(
""Enter Password:"");
pass_code = Integer.parseInt(
sc.readLine());
if (bankManagement.loginAccount(
name, pass_code)) {
System.out.println(
""MSG : Logout Successfully!\n"");
}
else {
System.out.println(
""ERR : login Failed!\n"");
}
}
catch (Exception e) {
System.out.println(
"" ERR : Enter Valid Data::Login Failed!\n"");
}
break;
default:
System.out.println(""Invalid Entry!\n"");
}
if (ch == 5) {
System.out.println(
""Exited Successfully!\n\n Thank You :)"");
break;
}
}
catch (Exception e) {
System.out.println(""Enter Valid Entry!"");
}
}
sc.close();
}
}
",3,357,Java
springuploads3,./ProjectTest/Java/springuploads3.java,"// springuploads3/service/StorageService.java
package projecttest.springuploads3.service;
import org.springframework.web.multipart.MultipartFile;
import projecttest.springuploads3.service.model.DownloadedResource;
public interface StorageService {
String upload(MultipartFile multipartFile);
DownloadedResource download(String id);
}
// springuploads3/service/model/DownloadedResource.java
package projecttest.springuploads3.service.model;
import lombok.Builder;
import lombok.Data;
import java.io.InputStream;
@Data
@Builder
public class DownloadedResource {
private String id;
private String fileName;
private Long contentLength;
private InputStream inputStream;
}
// springuploads3/service/S3StorageService.java
package projecttest.springuploads3.service;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.S3Object;
import projecttest.springuploads3.service.model.DownloadedResource;
import lombok.SneakyThrows;
@Service
public class S3StorageService implements StorageService {
private static final String FILE_EXTENSION = ""fileExtension"";
private final AmazonS3 amazonS3;
private final String bucketName;
public S3StorageService(AmazonS3 amazonS3, @Value(""${aws.s3.bucket-name}"") String bucketName) {
this.amazonS3 = amazonS3;
this.bucketName = bucketName;
initializeBucket();
}
@SneakyThrows
@Override
public String upload(MultipartFile multipartFile) {
String key = RandomStringUtils.randomAlphanumeric(50);
amazonS3.putObject(bucketName, key, multipartFile.getInputStream(), extractObjectMetadata(multipartFile));
return key;
}
@Override
public DownloadedResource download(String id) {
S3Object s3Object = amazonS3.getObject(bucketName, id);
String filename = id + ""."" + s3Object.getObjectMetadata().getUserMetadata().get(FILE_EXTENSION);
Long contentLength = s3Object.getObjectMetadata().getContentLength();
return DownloadedResource.builder().id(id).fileName(filename).contentLength(contentLength).inputStream(s3Object.getObjectContent())
.build();
}
private ObjectMetadata extractObjectMetadata(MultipartFile file) {
ObjectMetadata objectMetadata = new ObjectMetadata();
objectMetadata.setContentLength(file.getSize());
objectMetadata.setContentType(file.getContentType());
objectMetadata.getUserMetadata().put(FILE_EXTENSION, FilenameUtils.getExtension(file.getOriginalFilename()));
return objectMetadata;
}
private void initializeBucket() {
if (!amazonS3.doesBucketExistV2(bucketName)) {
amazonS3.createBucket(bucketName);
}
}
}
// springuploads3/controller/FileUploadController.java
package projecttest.springuploads3.controller;
import projecttest.springuploads3.service.StorageService;
import lombok.extern.log4j.Log4j2;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
@Controller
@Log4j2
public class FileUploadController {
private final StorageService storageService;
public FileUploadController(StorageService storageService) {
this.storageService = storageService;
}
@PostMapping(value = ""/upload"", produces = ""application/json"")
public ResponseEntity<String> upload(@RequestParam(""file"") MultipartFile file) {
String key = storageService.upload(file);
return new ResponseEntity<>(key, HttpStatus.OK);
}
}
// springuploads3/controller/FileDownloadController.java
package projecttest.springuploads3.controller;
import projecttest.springuploads3.service.model.DownloadedResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import projecttest.springuploads3.service.StorageService;
import lombok.extern.log4j.Log4j2;
@Controller
@Log4j2
public class FileDownloadController {
private final StorageService storageService;
public FileDownloadController(StorageService storageService) {
this.storageService = storageService;
}
@GetMapping(""/download"")
public ResponseEntity<Resource> download(String id) {
DownloadedResource downloadedResource = storageService.download(id);
return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION, ""attachment; filename="" + downloadedResource.getFileName())
.contentLength(downloadedResource.getContentLength()).contentType(MediaType.APPLICATION_OCTET_STREAM)
.body(new InputStreamResource(downloadedResource.getInputStream()));
}
}
// springuploads3/SpringUploadS3Application.java
package projecttest.springuploads3;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringUploadS3Application {
public static void main(String[] args) {
SpringApplication.run(SpringUploadS3Application.class, args);
}
}
// springuploads3/configuration/S3ClientConfiguration.java
package projecttest.springuploads3.configuration;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.amazonaws.client.builder.AwsClientBuilder;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
@Configuration
public class S3ClientConfiguration {
@Value(""${aws.s3.endpoint-url}"")
private String endpointUrl;
@Bean
AmazonS3 amazonS3() {
AwsClientBuilder.EndpointConfiguration endpointConfiguration = new AwsClientBuilder.EndpointConfiguration(endpointUrl,
Regions.US_EAST_1.getName());
return AmazonS3ClientBuilder.standard().withEndpointConfiguration(endpointConfiguration).withPathStyleAccessEnabled(true).build();
}
}
",7,192,Java
CalculatorOOPS,./ProjectTest/Java/CalculatorOOPS.java,"// CalculatorOOPS/Divide.java
package projecttest.CalculatorOOPS;
public class Divide implements Operate {
@Override
public Double getResult(Double... numbers){
Double div = numbers[0];
for(int i=1;i< numbers.length;i++){
div /= numbers[i];
}
return div;
}
}
// CalculatorOOPS/Modulus.java
package projecttest.CalculatorOOPS;
public class Modulus implements Operate{
@Override
public Double getResult(Double... numbers){
Double mod = numbers[0];
for (int i = 1; i < numbers.length; i++) {
mod %= numbers[i];
}
return mod;
}
}
// CalculatorOOPS/ReadInput.java
package projecttest.CalculatorOOPS;
import java.util.Scanner;
public class ReadInput {
public static String read(){
Scanner scanner = new Scanner(System.in);
System.out.println(""Input Expression Example: 4*3/2"");
String inputLine = scanner.nextLine();
scanner.close();
return inputLine;
}
}
// CalculatorOOPS/Operate.java
package projecttest.CalculatorOOPS;
public interface Operate {
Double getResult(Double... numbers);
}
// CalculatorOOPS/Add.java
package projecttest.CalculatorOOPS;
public class Add implements Operate{
@Override
public Double getResult(Double... numbers){
Double sum = 0.0;
for(Double num: numbers){
sum += num;
}
return sum;
}
}
// CalculatorOOPS/Sub.java
package projecttest.CalculatorOOPS;
public class Sub implements Operate{
@Override
public Double getResult(Double... numbers){
Double sub = numbers[0];
for(int i=1;i< numbers.length;i++){
sub -= numbers[i];
}
return sub;
}
}
// CalculatorOOPS/Multiply.java
package projecttest.CalculatorOOPS;
public class Multiply implements Operate {
@Override
public Double getResult(Double... numbers){
Double mul = 1.0;
for(Double num: numbers){
mul *= num;
}
return mul;
}
}
// CalculatorOOPS/Calculator.java
package projecttest.CalculatorOOPS;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Objects;
import java.util.Queue;
public class Calculator {
public static void main(String[] args){
final String inputExp = ReadInput.read();
Queue<String> operations;
Queue<String> numbers;
String[] numbersArr = inputExp.split(""[-+*/%]"");
// String[] operArr = inputExp.split(""[0-9]+"");
String[] operArr = inputExp.split(""\\d+"");
numbers = new LinkedList<>(Arrays.asList(numbersArr));
operations = new LinkedList<>(Arrays.asList(operArr));
Double res = Double.parseDouble(Objects.requireNonNull(numbers.poll()));
while(!numbers.isEmpty()){
String opr = operations.poll();
Operate operate;
switch(Objects.requireNonNull(opr)){
case ""+"":
operate = new Add();
break;
case ""-"":
operate = new Sub();
break;
case ""*"":
operate = new Multiply();
break;
case ""/"":
operate = new Divide();
break;
case ""%"":
operate = new Modulus();
break;
default:
continue;
}
Double num = Double.parseDouble(Objects.requireNonNull(numbers.poll()));
res = operate.getResult(res, num);
}
System.out.println(res);
}
}
",8,138,Java
passwordGenerator,./ProjectTest/Java/passwordGenerator.java,"// passwordGenerator/GeneratorTest.java
package projecttest.passwordGenerator;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
class GeneratorTest {
private final Password password= new Password(""Secret"");
private final Alphabet firstAlphabet = new Alphabet(true,false,false,false);
private final Alphabet secondAlphabet = new Alphabet(false,true,true,true);
private final Generator generator = new Generator(true,false,false,false);
// private final Password generatedPassword = generator.GeneratePassword(4);
@Test
void test1() {
assertEquals(""Secret"", password.toString());
}
@Test
void test2() {
assertEquals(firstAlphabet.getAlphabet(), Alphabet.UPPERCASE_LETTERS);
}
@Test
void test3() {
assertEquals(secondAlphabet.getAlphabet(), Alphabet.LOWERCASE_LETTERS + Alphabet.NUMBERS + Alphabet.SYMBOLS);
}
@Test
void test4() {
assertEquals(generator.alphabet.getAlphabet(), Alphabet.UPPERCASE_LETTERS);
}
@Test
void test5() {
assertEquals(generator.alphabet.getAlphabet().length(), 26);
}
}
// passwordGenerator/Main.java
package projecttest.passwordGenerator;
import java.util.Scanner;
public class Main {
public static final Scanner keyboard = new Scanner(System.in);
public static void main(String[] args) {
Generator generator = new Generator(keyboard);
generator.mainLoop();
keyboard.close();
}
}
// passwordGenerator/Generator.java
package projecttest.passwordGenerator;
import java.util.Objects;
import java.util.Scanner;
public class Generator {
Alphabet alphabet;
public static Scanner keyboard;
public Generator(Scanner scanner) {
keyboard = scanner;
}
public Generator(boolean IncludeUpper, boolean IncludeLower, boolean IncludeNum, boolean IncludeSym) {
alphabet = new Alphabet(IncludeUpper, IncludeLower, IncludeNum, IncludeSym);
}
public void mainLoop() {
System.out.println(""Welcome to Ziz Password Services :)"");
printMenu();
String userOption = ""-1"";
while (!userOption.equals(""4"")) {
userOption = keyboard.next();
switch (userOption) {
case ""1"": {
requestPassword();
printMenu();
}
case ""2"": {
checkPassword();
printMenu();
}
case ""3"": {
printUsefulInfo();
printMenu();
}
case ""4"": printQuitMessage();
default: {
System.out.println();
System.out.println(""Kindly select one of the available commands"");
printMenu();
}
}
}
}
private Password GeneratePassword(int length) {
final StringBuilder pass = new StringBuilder("""");
final int alphabetLength = alphabet.getAlphabet().length();
int max = alphabetLength - 1;
int min = 0;
int range = max - min + 1;
for (int i = 0; i < length; i++) {
int index = (int) (Math.random() * range) + min;
pass.append(alphabet.getAlphabet().charAt(index));
}
return new Password(pass.toString());
}
private void printUsefulInfo() {
System.out.println();
System.out.println(""Use a minimum password length of 8 or more characters if permitted"");
System.out.println(""Include lowercase and uppercase alphabetic characters, numbers and symbols if permitted"");
System.out.println(""Generate passwords randomly where feasible"");
System.out.println(""Avoid using the same password twice (e.g., across multiple user accounts and/or software systems)"");
System.out.println(""Avoid character repetition, keyboard patterns, dictionary words, letter or number sequences,"" +
""\nusernames, relative or pet names, romantic links (current or past) "" +
""and biographical information (e.g., ID numbers, ancestors' names or dates)."");
System.out.println(""Avoid using information that the user's colleagues and/or "" +
""acquaintances might know to be associated with the user"");
System.out.println(""Do not use passwords which consist wholly of any simple combination of the aforementioned weak components"");
}
private void requestPassword() {
boolean IncludeUpper = false;
boolean IncludeLower = false;
boolean IncludeNum = false;
boolean IncludeSym = false;
boolean correctParams = false;
System.out.println();
System.out.println(""Hello, welcome to the Password Generator :) answer""
+ "" the following questions by Yes or No \n"");
do {
System.out.println(""Do you want Lowercase letters \""abcd...\"" to be used? "");
String input = keyboard.nextLine();
if (isInclude(input)) IncludeLower = true;
System.out.println(""Do you want Uppercase letters \""ABCD...\"" to be used? "");
input = keyboard.nextLine();
if (isInclude(input)) IncludeUpper = true;
System.out.println(""Do you want Numbers \""1234...\"" to be used? "");
input = keyboard.nextLine();
if (isInclude(input)) IncludeNum = true;
System.out.println(""Do you want Symbols \""!@#$...\"" to be used? "");
input = keyboard.nextLine();
if (isInclude(input)) IncludeSym = true;
//No Pool Selected
if (!IncludeUpper && !IncludeLower && !IncludeNum && !IncludeSym) {
System.out.println(""You have selected no characters to generate your "" +
""password at least one of your answers should be Yes"");
correctParams = true;
}
System.out.println(""Great! Now enter the length of the password"");
int length = keyboard.nextInt();
final Generator generator = new Generator(IncludeUpper, IncludeLower, IncludeNum, IncludeSym);
final Password password = generator.GeneratePassword(length);
System.err.println(""Your generated password -> "" + password);
} while (correctParams);
}
private boolean isInclude(String Input) {
if (Input.equalsIgnoreCase(""yes"")) {
return true;
} else {
if (!Input.equalsIgnoreCase(""no"")) {
PasswordRequestError();
}
return false;
}
}
private void PasswordRequestError() {
System.out.println(""You have entered something incorrect let's go over it again \n"");
}
private void checkPassword() {
String input;
final Scanner in = new Scanner(System.in);
System.out.print(""\nEnter your password:"");
input = in.nextLine();
final Password p = new Password(input);
System.out.println(p.calculateScore());
in.close();
}
private void printMenu() {
System.out.println();
System.out.println(""Enter 1 - Password Generator"");
System.out.println(""Enter 2 - Password Strength Check"");
System.out.println(""Enter 3 - Useful Information"");
System.out.println(""Enter 4 - Quit"");
System.out.print(""Choice:"");
}
private void printQuitMessage() {
System.out.println(""Closing the program bye bye!"");
}
}
// passwordGenerator/Alphabet.java
package projecttest.passwordGenerator;
public class Alphabet {
public static final String UPPERCASE_LETTERS = ""ABCDEFGHIJKLMNOPQRSTUVWXYZ"";
public static final String LOWERCASE_LETTERS = ""abcdefghijklmnopqrstuvwxyz"";
public static final String NUMBERS = ""1234567890"";
public static final String SYMBOLS = ""!@#$%^&*()-_=+\\/~?"";
private final StringBuilder pool;
public Alphabet(boolean uppercaseIncluded, boolean lowercaseIncluded, boolean numbersIncluded, boolean specialCharactersIncluded) {
pool = new StringBuilder();
if (uppercaseIncluded) pool.append(UPPERCASE_LETTERS);
if (lowercaseIncluded) pool.append(LOWERCASE_LETTERS);
if (numbersIncluded) pool.append(NUMBERS);
if (specialCharactersIncluded) pool.append(SYMBOLS);
}
public String getAlphabet() {
return pool.toString();
}
}
// passwordGenerator/Password.java
package projecttest.passwordGenerator;
public class Password {
String Value;
int Length;
public Password(String s) {
Value = s;
Length = s.length();
}
public int CharType(char C) {
int val;
// Char is Uppercase Letter
if ((int) C >= 65 && (int) C <= 90)
val = 1;
// Char is Lowercase Letter
else if ((int) C >= 97 && (int) C <= 122) {
val = 2;
}
// Char is Digit
else if ((int) C >= 60 && (int) C <= 71) {
val = 3;
}
// Char is Symbol
else {
val = 4;
}
return val;
}
public int PasswordStrength() {
String s = this.Value;
boolean UsedUpper = false;
boolean UsedLower = false;
boolean UsedNum = false;
boolean UsedSym = false;
int type;
int Score = 0;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
type = CharType(c);
if (type == 1) UsedUpper = true;
if (type == 2) UsedLower = true;
if (type == 3) UsedNum = true;
if (type == 4) UsedSym = true;
}
if (UsedUpper) Score += 1;
if (UsedLower) Score += 1;
if (UsedNum) Score += 1;
if (UsedSym) Score += 1;
if (s.length() >= 8) Score += 1;
if (s.length() >= 16) Score += 1;
return Score;
}
public String calculateScore() {
int Score = this.PasswordStrength();
if (Score == 6) {
return ""This is a very good password :D check the Useful Information section to make sure it satisfies the guidelines"";
} else if (Score >= 4) {
return ""This is a good password :) but you can still do better"";
} else if (Score >= 3) {
return ""This is a medium password :/ try making it better"";
} else {
return ""This is a weak password :( definitely find a new one"";
}
}
@Override
public String toString() {
return Value;
}
}
",5,344,Java
springdatamongowithcluster,./ProjectTest/Java/springdatamongowithcluster.java,"// springdatamongowithcluster/SpringDataMongoWithClusterApplication.java
package projecttest.springdatamongowithcluster;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import lombok.extern.log4j.Log4j2;
@SpringBootApplication
@Log4j2
public class SpringDataMongoWithClusterApplication implements CommandLineRunner {
@Autowired
MongoTemplate mongoTemplate;
public static void main(String[] args) {
SpringApplication.run(SpringDataMongoWithClusterApplication.class, args);
}
@Override
public void run(String... args) {
mongoTemplate.dropCollection(Car.class);
mongoTemplate.save(Car.builder().name(""Tesla Model S"").build());
mongoTemplate.save(Car.builder().name(""Tesla Model 3"").build());
log.info(""-------------------------------"");
log.info(""Cards found: "" + mongoTemplate.count(new Query(), Car.class));
log.info(""-------------------------------"");
}
}
// springdatamongowithcluster/Car.java
package projecttest.springdatamongowithcluster;
import org.springframework.data.annotation.Id;
import lombok.Builder;
@Builder
public class Car {
@Id
private String id;
private String name;
}
",2,51,Java
idcenter,./ProjectTest/Java/idcenter.java,"// idcenter/IdWorker.java
package projecttest.idcenter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
/**
* from https://github.com/twitter/snowflake/blob/master/src/main/scala/com/twitter/service/snowflake/IdWorker.scala
*
* @author adyliu ([email protected])
* @since 1.0
*/
public class IdWorker {
private final long workerId;
private final long datacenterId;
private final long idepoch;
private static final long workerIdBits = 5L;
private static final long datacenterIdBits = 5L;
private static final long maxWorkerId = -1L ^ (-1L << workerIdBits);
private static final long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);
private static final long sequenceBits = 12L;
private static final long workerIdShift = sequenceBits;
private static final long datacenterIdShift = sequenceBits + workerIdBits;
private static final long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;
private static final long sequenceMask = -1L ^ (-1L << sequenceBits);
private long lastTimestamp = -1L;
private long sequence;
private static final Random r = new Random();
public IdWorker() {
this(1344322705519L);
}
public IdWorker(long idepoch) {
this(r.nextInt((int) maxWorkerId), r.nextInt((int) maxDatacenterId), 0, idepoch);
}
public IdWorker(long workerId, long datacenterId, long sequence) {
this(workerId, datacenterId, sequence, 1344322705519L);
}
//
public IdWorker(long workerId, long datacenterId, long sequence, long idepoch) {
this.workerId = workerId;
this.datacenterId = datacenterId;
this.sequence = sequence;
this.idepoch = idepoch;
if (workerId < 0 || workerId > maxWorkerId) {
throw new IllegalArgumentException(""workerId is illegal: "" + workerId);
}
if (datacenterId < 0 || datacenterId > maxDatacenterId) {
throw new IllegalArgumentException(""datacenterId is illegal: "" + workerId);
}
if (idepoch >= System.currentTimeMillis()) {
throw new IllegalArgumentException(""idepoch is illegal: "" + idepoch);
}
}
public long getDatacenterId() {
return datacenterId;
}
public long getWorkerId() {
return workerId;
}
public long getTime() {
return System.currentTimeMillis();
}
public long getId() {
long id = nextId();
return id;
}
private synchronized long nextId() {
long timestamp = timeGen();
if (timestamp < lastTimestamp) {
throw new IllegalStateException(""Clock moved backwards."");
}
if (lastTimestamp == timestamp) {
sequence = (sequence + 1) & sequenceMask;
if (sequence == 0) {
timestamp = tilNextMillis(lastTimestamp);
}
} else {
sequence = 0;
}
lastTimestamp = timestamp;
long id = ((timestamp - idepoch) << timestampLeftShift)//
| (datacenterId << datacenterIdShift)//
| (workerId << workerIdShift)//
| sequence;
return id;
}
/**
* get the timestamp (millis second) of id
* @param id the nextId
* @return the timestamp of id
*/
public long getIdTimestamp(long id) {
return idepoch + (id >> timestampLeftShift);
}
private long tilNextMillis(long lastTimestamp) {
long timestamp = timeGen();
while (timestamp <= lastTimestamp) {
timestamp = timeGen();
}
return timestamp;
}
private long timeGen() {
return System.currentTimeMillis();
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder(""IdWorker{"");
sb.append(""workerId="").append(workerId);
sb.append("", datacenterId="").append(datacenterId);
sb.append("", idepoch="").append(idepoch);
sb.append("", lastTimestamp="").append(lastTimestamp);
sb.append("", sequence="").append(sequence);
sb.append('}');
return sb.toString();
}
}
// idcenter/Base62.java
package projecttest.idcenter;
/**
* A Base62 method
*
* @author adyliu ([email protected])
* @since 1.0
*/
public class Base62 {
private static final String baseDigits = ""0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"";
private static final int BASE = baseDigits.length();
private static final char[] digitsChar = baseDigits.toCharArray();
private static final int FAST_SIZE = 'z';
private static final int[] digitsIndex = new int[FAST_SIZE + 1];
static {
for (int i = 0; i < FAST_SIZE; i++) {
digitsIndex[i] = -1;
}
//
for (int i = 0; i < BASE; i++) {
digitsIndex[digitsChar[i]] = i;
}
}
public static long decode(String s) {
long result = 0L;
long multiplier = 1;
for (int pos = s.length() - 1; pos >= 0; pos--) {
int index = getIndex(s, pos);
result += index * multiplier;
multiplier *= BASE;
}
return result;
}
public static String encode(long number) {
if (number < 0) throw new IllegalArgumentException(""Number(Base62) must be positive: "" + number);
if (number == 0) return ""0"";
StringBuilder buf = new StringBuilder();
while (number != 0) {
buf.append(digitsChar[(int) (number % BASE)]);
number /= BASE;
}
return buf.reverse().toString();
}
private static int getIndex(String s, int pos) {
char c = s.charAt(pos);
if (c > FAST_SIZE) {
throw new IllegalArgumentException(""Unknow character for Base62: "" + s);
}
int index = digitsIndex[c];
if (index == -1) {
throw new IllegalArgumentException(""Unknow character for Base62: "" + s);
}
return index;
}
}
// idcenter/Main.java
package projecttest.idcenter;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
if (args.length != 3) {
System.err.println(""Usage: java -jar idcenter.jar <subcommand> <num> <output>"");
System.err.println(""Subcommands\nidworker: Sequential ID Creation\nsidworker: Timestamp-based ID Creation"");
return;
}
String subcommand = args[0];
int num = Integer.parseInt(args[1]);
String output = args[2];
if (subcommand.equals(""idworker"")) {
final long idepo = System.currentTimeMillis() - 3600 * 1000L;
IdWorker iw = new IdWorker(1, 1, 0, idepo);
IdWorker iw2 = new IdWorker(idepo);
try (BufferedWriter writer = new BufferedWriter(new FileWriter(output))) {
for (int i = 0; i < num; i++) {
long id = iw.getId();
long idTimeStamp = iw.getIdTimestamp(id);
long id2 = iw2.getId();
long idTimeStamp2 = iw2.getIdTimestamp(id2);
writer.write(""IdWorker1: "" + id + "", timestamp: "" + idTimeStamp + ""\n"");
writer.write(""IdWorker2: "" + id2 + "", timestamp: "" + idTimeStamp2 + ""\n"");
}
} catch (IOException e) {
e.printStackTrace();
}
} else if (subcommand.equals(""sidworker"")) {
try (BufferedWriter writer = new BufferedWriter(new FileWriter(output))) {
for (int i = 0; i < num; i++) {
long sid = SidWorker.nextSid();
writer.write(""SidWorker: "" + sid + ""\n"");
}
} catch (IOException e) {
e.printStackTrace();
}
} else {
System.err.println(""Usage: java -jar idcenter.jar <subcommand> <num> <output>"");
System.err.println(""Subcommands\nidworker: Sequential ID Creation\nsidworker: Timestamp-based ID Creation"");
}
}
}
// idcenter/SidWorker.java
package projecttest.idcenter;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* generator of 19 bits number with timestamp
*
* @author adyliu ([email protected])
* @since 2016-06-28
*/
public class SidWorker {
private static long lastTimestamp = -1L;
private static int sequence = 0;
private static final long MAX_SEQUENCE = 100;
private static final SimpleDateFormat format = new SimpleDateFormat(""yyyyMMddHHmmssSSS"");
/**
* 19 bits number with timestamp (20160628175532000002)
*
* @return 19 bits number with timestamp
*/
public static synchronized long nextSid() {
long now = timeGen();
if (now == lastTimestamp) {
if (sequence++ > MAX_SEQUENCE) {
now = tilNextMillis(lastTimestamp);
sequence = 0;
}
} else {
sequence = 0;
}
lastTimestamp = now;
//
return 100L * Long.parseLong(format.format(new Date(now))) + sequence;
}
private static long tilNextMillis(long lastTimestamp) {
long timestamp = timeGen();
while (timestamp <= lastTimestamp) {
timestamp = timeGen();
}
return timestamp;
}
private static long timeGen() {
return System.currentTimeMillis();
}
}
",4,295,Java
PongGame,./ProjectTest/Java/PongGame.java,"// PongGame/Score.java
package projecttest.PongGame;
import java.awt.*;
public class Score extends Rectangle{
static int GAME_WIDTH;
static int GAME_HEIGHT;
int player1;
int player2;
Score(int GAME_WIDTH, int GAME_HEIGHT){
Score.GAME_WIDTH = GAME_WIDTH;
Score.GAME_HEIGHT=GAME_HEIGHT;
}
public void draw(Graphics g){
g.setColor(Color.white);
g.setFont(new Font(""Consolas"", Font.PLAIN,60));
g.drawLine(GAME_WIDTH/2,0,GAME_WIDTH/2,GAME_HEIGHT);
g.drawString(String.valueOf(player1/10)+String.valueOf(player1%10), (GAME_WIDTH/2)-85, 50);
g.drawString(String.valueOf(player2/10)+String.valueOf(player2%10), (GAME_WIDTH/2)+20, 50);
}
}
// PongGame/GameFrame.java
package projecttest.PongGame;
import java.awt.*;
import javax.swing.*;
public class GameFrame extends JFrame{
GamePanel panel;
GameFrame(){
panel = new GamePanel();
this.add(panel);
this.setTitle(""Pong Game"");
this.setResizable(false);
this.setBackground(Color.black);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
this.setVisible(true);
this.setLocationRelativeTo(null);
}
}
// PongGame/Paddle.java
package projecttest.PongGame;
import java.awt.*;
import java.awt.event.*;
public class Paddle extends Rectangle{
int id;
int yVelocity;
int speed=10;
Paddle(int x, int y, int PADDLE_WIDTH, int PADDLE_HEIGHT, int id){
super(x,y,PADDLE_WIDTH,PADDLE_HEIGHT);
this.id=id;
}
public void keyPressed(KeyEvent e){
switch (id){
case 1:
if(e.getKeyCode()==KeyEvent.VK_W){
setYDirection(-speed);
move();
}
if(e.getKeyCode()==KeyEvent.VK_S){
setYDirection(speed);
move();
}
break;
case 2:
if(e.getKeyCode()==KeyEvent.VK_UP){
setYDirection(-speed);
move();
}
if(e.getKeyCode()==KeyEvent.VK_DOWN){
setYDirection(speed);
move();
}
break;
}
}
public void keyReleased(KeyEvent e){
switch (id){
case 1:
if(e.getKeyCode()==KeyEvent.VK_W){
setYDirection(0);
move();
}
if(e.getKeyCode()==KeyEvent.VK_S){
setYDirection(0);
move();
}
break;
case 2:
if(e.getKeyCode()==KeyEvent.VK_UP){
setYDirection(0);
move();
}
if(e.getKeyCode()==KeyEvent.VK_DOWN){
setYDirection(0);
move();
}
break;
}
}
public void setYDirection(int yDirection){
yVelocity = yDirection;
}
public void move(){
y=y+yVelocity;
}
public void draw(Graphics g){
if (id==1)
g.setColor(Color.BLUE);
else
g.setColor(Color.red);
g.fillRect(x, y, width, height);
}
}
// PongGame/PongGame.java
package projecttest.PongGame;
public class PongGame {
public static void main(String[] args) {
GameFrame frame = new GameFrame();
}
}
// PongGame/Ball.java
package projecttest.PongGame;
import java.awt.*;
import java.util.*;
public class Ball extends Rectangle{
Random random;
int xVelocity;
int yVelocity;
int initialSpeed = 4 ;
Ball(int x, int y, int width, int height){
super(x, y, width, height);
random = new Random();
int randomXDirection = random.nextInt(2);
if(randomXDirection==0)
randomXDirection--;
setXDirection(randomXDirection*initialSpeed);
int randomYDirection = random.nextInt(2);
if(randomYDirection==0)
randomYDirection--;
setXDirection(randomYDirection*initialSpeed);
}
public void setXDirection(int randomXDirection){
xVelocity = randomXDirection;
}
public void setYDirection(int randomYDirection){
yVelocity=randomYDirection;
}
public void move(){
x+=xVelocity;
y+=yVelocity;
}
public void draw(Graphics g){
g.setColor(Color.white);
g.fillOval(x, y, height, width);
}
}
// PongGame/GamePanel.java
package projecttest.PongGame;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
public class GamePanel extends JPanel implements Runnable{
static final int GAME_WIDTH = 1000;
static final int GAME_HEIGHT = (int)(GAME_WIDTH * (0.5555));
static final Dimension SCREEN_SIZE = new Dimension(GAME_WIDTH,GAME_HEIGHT);
static final int BALL_DIAMETER = 20;
static final int PADDLE_WIDTH = 25;
static final int PADDLE_HEIGHT = 100;
Thread gameThread;
Image image;
Graphics graphics;
Random random;
Paddle paddle1;
Paddle paddle2;
Ball ball;
Score score;
GamePanel(){
newPaddles();
newBall();
score = new Score(GAME_WIDTH,GAME_HEIGHT);
this.setFocusable(true);
this.addKeyListener(new AL());
this.setPreferredSize(SCREEN_SIZE);
gameThread = new Thread(this);
gameThread.start();
}
public void newBall() {
random = new Random();
ball = new Ball((GAME_WIDTH/2)-(BALL_DIAMETER/2),random.nextInt(GAME_HEIGHT-BALL_DIAMETER),BALL_DIAMETER,BALL_DIAMETER);
}
public void newPaddles() {
paddle1 = new Paddle(0,(GAME_HEIGHT/2)-(PADDLE_HEIGHT/2),PADDLE_WIDTH,PADDLE_HEIGHT,1);
paddle2 = new Paddle(GAME_WIDTH-PADDLE_WIDTH,(GAME_HEIGHT/2)-(PADDLE_HEIGHT/2),PADDLE_WIDTH,PADDLE_HEIGHT,2);
}
public void paint(Graphics g) {
image = createImage(getWidth(),getHeight());
graphics = image.getGraphics();
draw(graphics);
g.drawImage(image,0,0,this);
}
public void draw(Graphics g) {
paddle1.draw(g);
paddle2.draw(g);
ball.draw(g);
score.draw(g);
Toolkit.getDefaultToolkit().sync(); // I forgot to add this line of code in the video, it helps with the animation
}
public void move() {
paddle1.move();
paddle2.move();
ball.move();
}
public void checkCollision() {
//bounce ball off top & bottom window edges
if(ball.y <=0) {
ball.setYDirection(-ball.yVelocity);
}
if(ball.y >= GAME_HEIGHT-BALL_DIAMETER) {
ball.setYDirection(-ball.yVelocity);
}
//bounce ball off paddles
if(ball.intersects(paddle1)) {
ball.xVelocity = Math.abs(ball.xVelocity);
ball.xVelocity++; //optional for more difficulty
if(ball.yVelocity>0)
ball.yVelocity++; //optional for more difficulty
else
ball.yVelocity--;
ball.setXDirection(ball.xVelocity);
ball.setYDirection(ball.yVelocity);
}
if(ball.intersects(paddle2)) {
ball.xVelocity = Math.abs(ball.xVelocity);
ball.xVelocity++; //optional for more difficulty
if(ball.yVelocity>0)
ball.yVelocity++; //optional for more difficulty
else
ball.yVelocity--;
ball.setXDirection(-ball.xVelocity);
ball.setYDirection(ball.yVelocity);
}
//stops paddles at window edges
if(paddle1.y<=0)
paddle1.y=0;
if(paddle1.y >= (GAME_HEIGHT-PADDLE_HEIGHT))
paddle1.y = GAME_HEIGHT-PADDLE_HEIGHT;
if(paddle2.y<=0)
paddle2.y=0;
if(paddle2.y >= (GAME_HEIGHT-PADDLE_HEIGHT))
paddle2.y = GAME_HEIGHT-PADDLE_HEIGHT;
//give a player 1 point and creates new paddles & ball
if(ball.x <=0) {
score.player2++;
newPaddles();
newBall();
System.out.println(""Player 2: ""+score.player2);
}
if(ball.x >= GAME_WIDTH-BALL_DIAMETER) {
score.player1++;
newPaddles();
newBall();
System.out.println(""Player 1: ""+score.player1);
}
}
public void run() {
//game loop
long lastTime = System.nanoTime();
double amountOfTicks =60.0;
double ns = 1000000000 / amountOfTicks;
double delta = 0;
while(true) {
long now = System.nanoTime();
delta += (now -lastTime)/ns;
lastTime = now;
if(delta >=1) {
move();
checkCollision();
repaint();
delta--;
}
}
}
public class AL extends KeyAdapter{
public void keyPressed(KeyEvent e) {
paddle1.keyPressed(e);
paddle2.keyPressed(e);
}
public void keyReleased(KeyEvent e) {
paddle1.keyReleased(e);
paddle2.keyReleased(e);
}
}
}
",6,321,Java
Actor_relationship_game,./ProjectTest/Java/Actor_relationship_game.java,"// Actor_relationship_game/GraphCreation.java
package projecttest.Actor_relationship_game;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
public class GraphCreation {
private final TMDBApi tmdbApi;
private final ActorGraph actorGraph;
public GraphCreation() {
this.tmdbApi = new TMDBApi();
this.actorGraph = new ActorGraph();
}
public void createGraph(String fileName) throws IOException {
populateGraphWithActors();
saveGraphToFile(fileName);
}
private void populateGraphWithActors() throws IOException {
String popularActorsJson = tmdbApi.searchPopularActors();
JsonArray actorsArray = JsonParser.parseString(popularActorsJson)
.getAsJsonObject().getAsJsonArray(""results"");
for (JsonElement actorElement : actorsArray) {
processActorElement(actorElement);
}
}
private void processActorElement(JsonElement actorElement) throws IOException {
JsonObject actorObject = actorElement.getAsJsonObject();
String actorId = actorObject.get(""id"").getAsString();
String actorName = actorObject.get(""name"").getAsString();
Actor actor = new Actor(actorId, actorName);
actorGraph.addActor(actor);
populateGraphWithMoviesForActor(actorId);
}
private void populateGraphWithMoviesForActor(String actorId) throws IOException {
String moviesJson = tmdbApi.getMoviesByActorId(actorId);
JsonArray moviesArray = JsonParser.parseString(moviesJson)
.getAsJsonObject().getAsJsonArray(""cast"");
for (JsonElement movieElement : moviesArray) {
processMovieElement(movieElement, actorId);
}
}
private void processMovieElement(JsonElement movieElement, String actorId) {
JsonObject movieObject = movieElement.getAsJsonObject();
String movieId = movieObject.get(""id"").getAsString();
String movieTitle = movieObject.get(""title"").getAsString();
Movie movie = new Movie(movieId, movieTitle);
actorGraph.addMovie(movie);
actorGraph.addActorToMovie(actorId, movieId);
}
private void saveGraphToFile(String fileName) throws IOException {
try (FileOutputStream fileOut = new FileOutputStream(fileName);
ObjectOutputStream out = new ObjectOutputStream(fileOut)) {
out.writeObject(actorGraph);
System.out.println(""Serialized data is saved in ""+fileName);
}
}
public static void main(String[] args) {
try {
String fileName = args[0];
new GraphCreation().createGraph(fileName);
} catch (IOException e) {
e.printStackTrace();
}
}
}
// Actor_relationship_game/Actor.java
package projecttest.Actor_relationship_game;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
public class Actor implements Serializable{
private static final long serialVersionUID=1L;
private String id;
private String name;
private Set<String> movieIds; // Store movie IDs
public Actor(String id, String name) {
this.id = id;
this.name = name;
this.movieIds = new HashSet<>();
}
// Getters and setters
public Set<String> getMovieIds() {
return movieIds;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public void setId(String id) {
this.id = id;
}
public void setMovieIds(Set<String> movieIds) {
this.movieIds = movieIds;
}
public void setName(String name) {
this.name = name;
}
}
// Actor_relationship_game/ActorGraph.java
package projecttest.Actor_relationship_game;
import java.io.Serializable;
import java.util.*;
public class ActorGraph implements Serializable {
private static final long serialVersionUID=1L;
private Map<String, Actor> actors;
private Map<String, Movie> movies;
private Map<String, String> nameToIdMap;
private Map<String, String> idToNameMap;
public ActorGraph() {
this.actors = new HashMap<>();
this.movies = new HashMap<>();
this.nameToIdMap = new HashMap<>();
this.idToNameMap = new HashMap<>();
}
// getters
public Map<String, Actor> getActors() {
return actors;
}
public Map<String, Movie> getMovies() {
return movies;
}
public Map<String, String> getIdToNameMap() {
return idToNameMap;
}
public Map<String, String> getNameToIdMap() {
return nameToIdMap;
}
public static long getSerialVersionUID() {
return serialVersionUID;
}
// Methods
public void addActor(Actor actor) {
actors.putIfAbsent(actor.getId(), actor);
nameToIdMap.put(actor.getName(), actor.getId());
idToNameMap.put(actor.getId(), actor.getName());
}
public void addMovie(Movie movie) {
movies.putIfAbsent(movie.getId(), movie);
}
public String getActorIdByName(String name) {
return nameToIdMap.get(name);
}
public String getActorNameById(String id) {
return idToNameMap.get(id);
}
public List<String> getAllActorNames() {
return new ArrayList<>(nameToIdMap.keySet());
}
/**
* This connects an actor to a movie.
* It's useful for building the graph based on TMDB API data.
*/
public void addActorToMovie(String actorId, String movieId) {
if (actors.containsKey(actorId) && movies.containsKey(movieId)) {
Actor actor = actors.get(actorId);
Movie movie = movies.get(movieId);
actor.getMovieIds().add(movieId);
movie.getActorIds().add(actorId);
}
}
/**
* Implements BFS to find the shortest path from startActorId to endActorId.
* It uses a queue for BFS and a map (visited) to track the visited actors and their previous actor in the path.
*/
public List<Map.Entry<String, String>> findConnectionWithPath(String startActorId, String endActorId) {
if (!actors.containsKey(startActorId) || !actors.containsKey(endActorId)) {
return Collections.emptyList();
}
Queue<String> queue = new LinkedList<>();
Map<String, String> visited = new HashMap<>();
Map<String, String> previousMovie = new HashMap<>();
queue.add(startActorId);
visited.put(startActorId, null);
while (!queue.isEmpty()) {
String currentActorId = queue.poll();
Actor currentActor = actors.get(currentActorId);
for (String movieId : currentActor.getMovieIds()) {
Movie movie = movies.get(movieId);
for (String coActorId : movie.getActorIds()) {
if (!visited.containsKey(coActorId)) {
visited.put(coActorId, currentActorId);
previousMovie.put(coActorId, movieId);
queue.add(coActorId);
if (coActorId.equals(endActorId)) {
return buildPath(visited, previousMovie, endActorId);
}
}
}
}
}
return Collections.emptyList();
}
/**
* Helper method to construct the path from the endActorId back to the startActorId using the visited map.
*/
private List<Map.Entry<String, String>> buildPath(Map<String, String> visited, Map<String, String> previousMovie, String endActorId) {
LinkedList<Map.Entry<String, String>> path = new LinkedList<>();
String current = endActorId;
while (current != null) {
String movieId = previousMovie.get(current);
String movieName = (movieId != null) ? movies.get(movieId).getTitle() : ""Start"";
path.addFirst(new AbstractMap.SimpleEntry<>(idToNameMap.get(current), movieName));
current = visited.get(current);
}
return path;
}
}
// Actor_relationship_game/TMDBApi.java
package projecttest.Actor_relationship_game;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import java.io.IOException;
public class TMDBApi {
private final OkHttpClient client;
private final String apiKey = System.getenv(""TMDB_API_KEY""); // get API Key from environmental variable
public TMDBApi() {
this.client = new OkHttpClient();
}
public String getMoviesByActorId(String actorId) throws IOException {
String url = ""https://api.themoviedb.org/3/person/"" + actorId + ""/movie_credits?api_key="" + apiKey;
Request request = new Request.Builder().url(url).build();
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) {
throw new IOException(""Unexpected code "" + response);
}
return response.body().string();
}
}
public String searchPopularActors() throws IOException {
String url = ""https://api.themoviedb.org/3/person/popular?api_key="" + apiKey;
Request request = new Request.Builder().url(url).build();
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) {
throw new IOException(""Unexpected code "" + response);
}
return response.body().string();
}
}
}
// Actor_relationship_game/Movie.java
package projecttest.Actor_relationship_game;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
public class Movie implements Serializable {
private static final long serialVersionUID=1L;
private String id;
private String title;
private Set<String> actorIds; // Store actor IDs
public Movie(String id, String title) {
this.id = id;
this.title = title;
this.actorIds = new HashSet<>();
}
// Getters and setters
public String getId() {
return id;
}
public Set<String> getActorIds() {
return actorIds;
}
public String getTitle() {
return title;
}
public void setId(String id) {
this.id = id;
}
public void setActorIds(Set<String> actorIds) {
this.actorIds = actorIds;
}
public void setTitle(String title) {
this.title = title;
}
}
// Actor_relationship_game/ActorGraphUtil.java
package projecttest.Actor_relationship_game;
import java.io.*;
import java.util.List;
public class ActorGraphUtil {
public static void main(String[] args) {
String graphPath = args[0];
String filePath = args[1];
ActorGraph actorGraph = loadGraph(graphPath);
if (actorGraph != null) {
List<String> actorNames = actorGraph.getAllActorNames();
writeActorsToFile(actorNames, filePath);
System.out.println(""Actors list has been saved to "" + filePath);
} else {
System.out.println(""Failed to load the graph."");
}
}
protected static ActorGraph loadGraph(String graphPath) {
try (FileInputStream fileIn = new FileInputStream(graphPath);
ObjectInputStream in = new ObjectInputStream(fileIn)) {
return (ActorGraph) in.readObject();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
protected static void writeActorsToFile(List<String> actorNames, String fileName) {
try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName))) {
for (String name : actorNames) {
writer.write(name);
writer.newLine();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
// Actor_relationship_game/GameplayInterface.java
package projecttest.Actor_relationship_game;
import java.io.*;
import java.util.*;
import java.util.List;
public class GameplayInterface {
private ActorGraph actorGraph;
public void setActorGraph(ActorGraph actorGraph) {
this.actorGraph = actorGraph;
}
public void loadGraph(String fileName) {
try (FileInputStream fileIn = new FileInputStream(fileName);
ObjectInputStream in = new ObjectInputStream(fileIn)) {
actorGraph = (ActorGraph) in.readObject();
System.out.println(""Graph successfully loaded."");
} catch (Exception e) {
e.printStackTrace();
}
}
public void findConnections(List<String[]> actorPairs, String outputFilePath) {
try (PrintWriter writer = new PrintWriter(new FileWriter(outputFilePath))) {
for (String[] pair : actorPairs) {
if (pair.length != 2) {
System.out.println(""Invalid actor pair. Skipping."");
continue;
}
String actor1Name = pair[0];
String actor2Name = pair[1];
// Assuming getActorIdByName is a method in ActorGraph that returns the actor's ID given a name
String actor1Id = actorGraph.getActorIdByName(actor1Name);
String actor2Id = actorGraph.getActorIdByName(actor2Name);
if (actor1Id == null || actor2Id == null) {
writer.println(""One or both actors not found in the graph."");
continue;
}
List<Map.Entry<String, String>> connectionPath = actorGraph.findConnectionWithPath(actor1Id, actor2Id);
if (connectionPath.isEmpty()) {
writer.println(""==================================================="");
writer.println(""No connection found between "" + actor1Name + "" and "" + actor2Name + ""."");
writer.println(""==================================================="");
writer.println();
} else {
writer.println(""==================================================="");
writer.println(""Connection Number between "" + actor1Name + "" and "" + actor2Name + "":"" + (connectionPath.size() - 1));
writer.println(""Connection path between "" + actor1Name + "" and "" + actor2Name + "":"");
for (int i = 0; i < connectionPath.size(); i++) {
Map.Entry<String, String> step = connectionPath.get(i);
writer.println((i + 1) + "". "" + step.getKey() + "": "" + step.getValue());
}
writer.println(""==================================================="");
writer.println();
}
}
} catch (IOException e){
e.printStackTrace();
}
}
private static List<String> readActorsFromFile(String fileName) {
List<String> actors = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
String line;
while ((line = reader.readLine()) != null) {
actors.add(line.trim());
}
} catch (IOException e) {
e.printStackTrace();
}
return actors;
}
private static List<String[]> generateAllActorPairs(String fileName) {
List<String> actors = readActorsFromFile(fileName);
List<String[]> pairs = new ArrayList<>();
for (int i = 0; i < actors.size(); i++) {
for (int j = i + 1; j < actors.size(); j++) {
pairs.add(new String[]{actors.get(i), actors.get(j)});
}
}
return pairs;
}
public static void main(String[] args) {
String graphPath = args[0];
String actorPath = args[1];
String filePath = args[2];
GameplayInterface gameplay = new GameplayInterface();
gameplay.loadGraph(graphPath);
List<String[]> actorPairs = generateAllActorPairs(actorPath);
gameplay.findConnections(actorPairs,filePath);
}
}
",7,479,Java
springreactivenonreactive,./ProjectTest/Java/springreactivenonreactive.java,"// springreactivenonreactive/repository/NonReactiveRepository.java
package projecttest.springreactivenonreactive.repository;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
import projecttest.springreactivenonreactive.model.Message;
@Repository
public interface NonReactiveRepository extends MongoRepository<Message, String> {
}
// springreactivenonreactive/repository/ReactiveRepository.java
package projecttest.springreactivenonreactive.repository;
import org.springframework.data.mongodb.repository.ReactiveMongoRepository;
import org.springframework.stereotype.Repository;
import projecttest.springreactivenonreactive.model.Message;
@Repository
public interface ReactiveRepository extends ReactiveMongoRepository<Message, String> {
}
// springreactivenonreactive/model/Message.java
package projecttest.springreactivenonreactive.model;
import java.util.Date;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
@Document(collection = ""messages"")
@Getter
@Setter
@NoArgsConstructor
@ToString
public class Message {
@Id
private String id;
@NotBlank
private String content;
@NotNull
private Date createdAt = new Date();
}
// springreactivenonreactive/controller/WebFluxController.java
package projecttest.springreactivenonreactive.controller;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import projecttest.springreactivenonreactive.model.Message;
import projecttest.springreactivenonreactive.repository.ReactiveRepository;
import reactor.core.publisher.Mono;
@RestController
public class WebFluxController {
@Autowired
ReactiveRepository reactiveRepository;
@RequestMapping(""/webflux/{id}"")
public Mono<Message> findByIdReactive(@PathVariable(value = ""id"") String id) {
return reactiveRepository.findById(id);
}
@PostMapping(""/webflux"")
public Mono<Message> postReactive(@Valid @RequestBody Message message) {
return reactiveRepository.save(message);
}
@DeleteMapping(""/webflux"")
public Mono<Void> deleteAllReactive() {
return reactiveRepository.deleteAll();
}
}
// springreactivenonreactive/controller/MVCSyncController.java
package projecttest.springreactivenonreactive.controller;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import projecttest.springreactivenonreactive.model.Message;
import projecttest.springreactivenonreactive.repository.NonReactiveRepository;
@RestController
public class MVCSyncController {
@Autowired
NonReactiveRepository nonReactiveRepository;
@RequestMapping(""/mvcsync/{id}"")
public Message findById(@PathVariable(value = ""id"") String id) {
return nonReactiveRepository.findById(id).orElse(null);
}
@PostMapping(""/mvcsync"")
public Message post(@Valid @RequestBody Message message) {
return nonReactiveRepository.save(message);
}
}
// springreactivenonreactive/controller/MVCAsyncController.java
package projecttest.springreactivenonreactive.controller;
import java.util.concurrent.CompletableFuture;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import projecttest.springreactivenonreactive.model.Message;
import projecttest.springreactivenonreactive.repository.NonReactiveRepository;
@RestController
public class MVCAsyncController {
@Autowired
NonReactiveRepository nonReactiveRepository;
@RequestMapping(""/mvcasync/{id}"")
public CompletableFuture<Message> findById(@PathVariable(value = ""id"") String id) {
return CompletableFuture.supplyAsync(() -> nonReactiveRepository.findById(id).orElse(null));
}
@PostMapping(""/mvcasync"")
public CompletableFuture<Message> post(@Valid @RequestBody Message message) {
return CompletableFuture.supplyAsync(() -> nonReactiveRepository.save(message));
}
}
// springreactivenonreactive/SpringMvcVsWebfluxApplication.java
package projecttest.springreactivenonreactive;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringMvcVsWebfluxApplication {
public static void main(String[] args) {
SpringApplication.run(SpringMvcVsWebfluxApplication.class, args);
}
}
",7,170,Java
redis,./ProjectTest/Java/redis.java,"// redis/RedisConfigurationBuilder.java
package projecttest.redis;
import org.apache.ibatis.cache.CacheException;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Map;
import java.util.Properties;
/**
* Converter from the Config to a proper {@link RedisConfig}.
*
* @author Eduardo Macarron
*/
final class RedisConfigurationBuilder {
/**
* This class instance.
*/
private static final RedisConfigurationBuilder INSTANCE = new RedisConfigurationBuilder();
protected static final String SYSTEM_PROPERTY_REDIS_PROPERTIES_FILENAME = ""redis.properties.filename"";
protected static final String REDIS_RESOURCE = ""redis.properties"";
/**
* Hidden constructor, this class can't be instantiated.
*/
private RedisConfigurationBuilder() {
}
/**
* Return this class instance.
*
* @return this class instance.
*/
public static RedisConfigurationBuilder getInstance() {
return INSTANCE;
}
/**
* Parses the Config and builds a new {@link RedisConfig}.
*
* @return the converted {@link RedisConfig}.
*/
public RedisConfig parseConfiguration() {
return parseConfiguration(getClass().getClassLoader());
}
/**
* Parses the Config and builds a new {@link RedisConfig}.
*
* @param the {@link ClassLoader} used to load the {@code memcached.properties} file in classpath.
* @return the converted {@link RedisConfig}.
*/
public RedisConfig parseConfiguration(ClassLoader classLoader) {
Properties config = new Properties();
String redisPropertiesFilename = System.getProperty(SYSTEM_PROPERTY_REDIS_PROPERTIES_FILENAME, REDIS_RESOURCE);
try (InputStream input = classLoader.getResourceAsStream(redisPropertiesFilename)) {
if (input != null) {
config.load(input);
}
} catch (IOException e) {
throw new RuntimeException(
""An error occurred while reading classpath property '"" + redisPropertiesFilename + ""', see nested exceptions"",
e);
}
RedisConfig jedisConfig = new RedisConfig();
setConfigProperties(config, jedisConfig);
return jedisConfig;
}
private void setConfigProperties(Properties properties, RedisConfig jedisConfig) {
if (properties != null) {
MetaObject metaCache = SystemMetaObject.forObject(jedisConfig);
for (Map.Entry<Object, Object> entry : properties.entrySet()) {
String name = (String) entry.getKey();
// All prefix of 'redis.' on property values
if (name != null && name.startsWith(""redis."")) {
name = name.substring(6);
} else {
// Skip non prefixed properties
continue;
}
String value = (String) entry.getValue();
if (""serializer"".equals(name)) {
if (""kryo"".equalsIgnoreCase(value)) {
jedisConfig.setSerializer(KryoSerializer.INSTANCE);
} else if (!""jdk"".equalsIgnoreCase(value)) {
// Custom serializer is not supported yet.
throw new CacheException(""Unknown serializer: '"" + value + ""'"");
}
} else if (Arrays.asList(""sslSocketFactory"", ""sslParameters"", ""hostnameVerifier"").contains(name)) {
setInstance(metaCache, name, value);
} else if (metaCache.hasSetter(name)) {
Class<?> type = metaCache.getSetterType(name);
if (String.class == type) {
metaCache.setValue(name, value);
} else if (int.class == type || Integer.class == type) {
metaCache.setValue(name, Integer.valueOf(value));
} else if (long.class == type || Long.class == type) {
metaCache.setValue(name, Long.valueOf(value));
} else if (short.class == type || Short.class == type) {
metaCache.setValue(name, Short.valueOf(value));
} else if (byte.class == type || Byte.class == type) {
metaCache.setValue(name, Byte.valueOf(value));
} else if (float.class == type || Float.class == type) {
metaCache.setValue(name, Float.valueOf(value));
} else if (boolean.class == type || Boolean.class == type) {
metaCache.setValue(name, Boolean.valueOf(value));
} else if (double.class == type || Double.class == type) {
metaCache.setValue(name, Double.valueOf(value));
} else {
throw new CacheException(""Unsupported property type: '"" + name + ""' of type "" + type);
}
}
}
}
}
protected void setInstance(MetaObject metaCache, String name, String value) {
if (value == null || value.isEmpty()) {
return;
}
Object instance;
try {
Class<?> clazz = Resources.classForName(value);
instance = clazz.getDeclaredConstructor().newInstance();
} catch (Exception e) {
throw new CacheException(""Could not instantiate class: '"" + value + ""'."", e);
}
metaCache.setValue(name, instance);
}
}
// redis/KryoSerializer.java
package projecttest.redis;
import com.esotericsoftware.kryo.kryo5.Kryo;
import com.esotericsoftware.kryo.kryo5.io.Input;
import com.esotericsoftware.kryo.kryo5.io.Output;
import java.util.Arrays;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
/**
* SerializeUtil with Kryo, which is faster and less space consuming.
*
* @author Lei Jiang([email protected])
*/
public enum KryoSerializer implements Serializer {
// Enum singleton, which is preferred approach since Java 1.5
INSTANCE;
/**
* kryo is thread-unsafe, use ThreadLocal.
*/
private ThreadLocal<Kryo> kryos = ThreadLocal.withInitial(Kryo::new);
/**
* Classes which can not resolved by default kryo serializer, which occurs very
* rare(https://github.com/EsotericSoftware/kryo#using-standard-java-serialization) For these classes, we will use
* fallbackSerializer(use JDKSerializer now) to resolve.
*/
private Set<Class<?>> unnormalClassSet;
/**
* Hash codes of unnormal bytes which can not resolved by default kryo serializer, which will be resolved by
* fallbackSerializer
*/
private Set<Integer> unnormalBytesHashCodeSet;
private Serializer fallbackSerializer;
private KryoSerializer() {
unnormalClassSet = ConcurrentHashMap.newKeySet();
unnormalBytesHashCodeSet = ConcurrentHashMap.newKeySet();
fallbackSerializer = JDKSerializer.INSTANCE;// use JDKSerializer as fallback
}
@Override
public byte[] serialize(Object object) {
if (unnormalClassSet.contains(object.getClass())) {
// For unnormal class
return fallbackSerializer.serialize(object);
}
/**
* In the following cases: 1. This class occurs for the first time. 2. This class have occurred and can be resolved
* by default kryo serializer
*/
try (Output output = new Output(200, -1)) {
kryos.get().writeClassAndObject(output, object);
return output.toBytes();
} catch (Exception e) {
// For unnormal class occurred for the first time, exception will be thrown
unnormalClassSet.add(object.getClass());
return fallbackSerializer.serialize(object);// use fallback Serializer to resolve
}
}
@Override
public Object unserialize(byte[] bytes) {
if (bytes == null) {
return null;
}
int hashCode = Arrays.hashCode(bytes);
if (unnormalBytesHashCodeSet.contains(hashCode)) {
// For unnormal bytes
return fallbackSerializer.unserialize(bytes);
}
/**
* In the following cases: 1. This bytes occurs for the first time. 2. This bytes have occurred and can be resolved
* by default kryo serializer
*/
try (Input input = new Input()) {
input.setBuffer(bytes);
return kryos.get().readClassAndObject(input);
} catch (Exception e) {
// For unnormal bytes occurred for the first time, exception will be thrown
unnormalBytesHashCodeSet.add(hashCode);
return fallbackSerializer.unserialize(bytes);// use fallback Serializer to resolve
}
}
}
// redis/Serializer.java
package projecttest.redis;
public interface Serializer {
/**
* Serialize method
*
* @param object
*
* @return serialized bytes
*/
byte[] serialize(Object object);
/**
* Unserialize method
*
* @param bytes
*
* @return unserialized object
*/
Object unserialize(byte[] bytes);
}
// redis/Main.java
package projecttest.redis;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author 11293
*/
public class Main {
private static final String DEFAULT_ID = ""REDIS"";
private static RedisCache cache = new RedisCache(DEFAULT_ID);
public static void main(String[] args) throws IOException {
if (args.length != 2) {
System.err.println(""Error: Two arguments required, the first is the path to the input file, and the second is the path to the output file."");
System.exit(1);
}
String inputFile = args[0];
String outputFile = args[1];
List<String> lines = Files.readAllLines(Paths.get(inputFile));
Map<String, String> localCache = new HashMap<>();
for (String line : lines) {
String[] parts = line.split(""\\s+"");
if (parts.length == 2) {
String key = parts[0];
String value = parts[1];
cache.putObject(key, value);
localCache.put(key, value);
}
}
try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(outputFile))) {
for (String line : lines) {
String[] parts = line.split(""\\s+"");
if (parts.length == 2) {
String key = parts[0];
String value = (String) cache.getObject(key);
assert value.equals(localCache.get(key));
writer.write(key + "" "" + value);
writer.newLine();
}
}
}
}
}
// redis/JDKSerializer.java
package projecttest.redis;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import org.apache.ibatis.cache.CacheException;
public enum JDKSerializer implements Serializer {
// Enum singleton, which is preferred approach since Java 1.5
INSTANCE;
private JDKSerializer() {
// prevent instantiation
}
@Override
public byte[] serialize(Object object) {
try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos)) {
oos.writeObject(object);
return baos.toByteArray();
} catch (Exception e) {
throw new CacheException(e);
}
}
@Override
public Object unserialize(byte[] bytes) {
if (bytes == null) {
return null;
}
try (ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bais)) {
return ois.readObject();
} catch (Exception e) {
throw new CacheException(e);
}
}
}
// redis/RedisCallback.java
package projecttest.redis;
import redis.clients.jedis.Jedis;
public interface RedisCallback {
Object doWithRedis(Jedis jedis);
}
// redis/RedisCache.java
package projecttest.redis;
import org.apache.ibatis.cache.Cache;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
/**
* Cache adapter for Redis.
*
* @author Eduardo Macarron
*/
public final class RedisCache implements Cache {
private final ReadWriteLock readWriteLock = new DummyReadWriteLock();
private String id;
private static JedisPool pool;
private final RedisConfig redisConfig;
private Integer timeout;
public RedisCache(final String id) {
if (id == null) {
throw new IllegalArgumentException(""Cache instances require an ID"");
}
this.id = id;
redisConfig = RedisConfigurationBuilder.getInstance().parseConfiguration();
pool = new JedisPool(redisConfig, redisConfig.getHost(), redisConfig.getPort(), redisConfig.getConnectionTimeout(),
redisConfig.getSoTimeout(), redisConfig.getPassword(), redisConfig.getDatabase(), redisConfig.getClientName(),
redisConfig.isSsl(), redisConfig.getSslSocketFactory(), redisConfig.getSslParameters(),
redisConfig.getHostnameVerifier());
}
private Object execute(RedisCallback callback) {
Jedis jedis = pool.getResource();
try {
return callback.doWithRedis(jedis);
} finally {
jedis.close();
}
}
@Override
public String getId() {
return this.id;
}
@Override
public int getSize() {
return (Integer) execute(jedis -> {
Map<byte[], byte[]> result = jedis.hgetAll(id.getBytes());
return result.size();
});
}
@Override
public void putObject(final Object key, final Object value) {
execute(jedis -> {
final byte[] idBytes = id.getBytes();
jedis.hset(idBytes, key.toString().getBytes(), redisConfig.getSerializer().serialize(value));
if (timeout != null && jedis.ttl(idBytes) == -1) {
jedis.expire(idBytes, timeout);
}
return null;
});
}
@Override
public Object getObject(final Object key) {
return execute(
jedis -> redisConfig.getSerializer().unserialize(jedis.hget(id.getBytes(), key.toString().getBytes())));
}
@Override
public Object removeObject(final Object key) {
return execute(jedis -> jedis.hdel(id, key.toString()));
}
@Override
public void clear() {
execute(jedis -> {
jedis.del(id);
return null;
});
}
@Override
public ReadWriteLock getReadWriteLock() {
return readWriteLock;
}
@Override
public String toString() {
return ""Redis {"" + id + ""}"";
}
public void setTimeout(Integer timeout) {
this.timeout = timeout;
}
}
// redis/DummyReadWriteLock.java
package projecttest.redis;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
/**
* @author Iwao AVE!
*/
class DummyReadWriteLock implements ReadWriteLock {
private Lock lock = new DummyLock();
@Override
public Lock readLock() {
return lock;
}
@Override
public Lock writeLock() {
return lock;
}
static class DummyLock implements Lock {
@Override
public void lock() {
// Not implemented
}
@Override
public void lockInterruptibly() throws InterruptedException {
// Not implemented
}
@Override
public boolean tryLock() {
return true;
}
@Override
public boolean tryLock(long paramLong, TimeUnit paramTimeUnit) throws InterruptedException {
return true;
}
@Override
public void unlock() {
// Not implemented
}
@Override
public Condition newCondition() {
return null;
}
}
}
// redis/RedisConfig.java
package projecttest.redis;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.Protocol;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLParameters;
import javax.net.ssl.SSLSocketFactory;
public class RedisConfig extends JedisPoolConfig {
private String host = Protocol.DEFAULT_HOST;
private int port = Protocol.DEFAULT_PORT;
private int connectionTimeout = Protocol.DEFAULT_TIMEOUT;
private int soTimeout = Protocol.DEFAULT_TIMEOUT;
private String password;
private int database = Protocol.DEFAULT_DATABASE;
private String clientName;
private boolean ssl;
private SSLSocketFactory sslSocketFactory;
private SSLParameters sslParameters;
private HostnameVerifier hostnameVerifier;
private Serializer serializer = JDKSerializer.INSTANCE;
public boolean isSsl() {
return ssl;
}
public void setSsl(boolean ssl) {
this.ssl = ssl;
}
public SSLSocketFactory getSslSocketFactory() {
return sslSocketFactory;
}
public void setSslSocketFactory(SSLSocketFactory sslSocketFactory) {
this.sslSocketFactory = sslSocketFactory;
}
public SSLParameters getSslParameters() {
return sslParameters;
}
public void setSslParameters(SSLParameters sslParameters) {
this.sslParameters = sslParameters;
}
public HostnameVerifier getHostnameVerifier() {
return hostnameVerifier;
}
public void setHostnameVerifier(HostnameVerifier hostnameVerifier) {
this.hostnameVerifier = hostnameVerifier;
}
public String getHost() {
return host;
}
public void setHost(String host) {
if (host == null || host.isEmpty()) {
host = Protocol.DEFAULT_HOST;
}
this.host = host;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
if (password == null || password.isEmpty()) {
password = null;
}
this.password = password;
}
public int getDatabase() {
return database;
}
public void setDatabase(int database) {
this.database = database;
}
public String getClientName() {
return clientName;
}
public void setClientName(String clientName) {
if (clientName == null || clientName.isEmpty()) {
clientName = null;
}
this.clientName = clientName;
}
public int getConnectionTimeout() {
return connectionTimeout;
}
public void setConnectionTimeout(int connectionTimeout) {
this.connectionTimeout = connectionTimeout;
}
public int getSoTimeout() {
return soTimeout;
}
public void setSoTimeout(int soTimeout) {
this.soTimeout = soTimeout;
}
public Serializer getSerializer() {
return serializer;
}
public void setSerializer(Serializer serializer) {
this.serializer = serializer;
}
}
",9,651,Java
|