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
|
// **********************************************************************
//
// Copyright (c) 2003-2009 ZeroC, Inc. All rights reserved.
//
// This copy of Ice is licensed to you under the terms described in the
// ICE_LICENSE file included in this distribution.
//
// **********************************************************************
#ifdef _WIN32
# include <IceUtil/Config.h>
#endif
#include <Operation.h>
#include <Current.h>
#include <Proxy.h>
#include <Types.h>
#include <Util.h>
#include <Ice/Communicator.h>
#include <Ice/IncomingAsync.h>
#include <Ice/Initialize.h>
#include <Ice/LocalException.h>
#include <Ice/Logger.h>
#include <Ice/ObjectAdapter.h>
#include <Ice/OutgoingAsync.h>
#include <Ice/Properties.h>
#include <Ice/Proxy.h>
#include <Slice/PythonUtil.h>
using namespace std;
using namespace IcePy;
using namespace Slice::Python;
namespace IcePy
{
//
// Information about an operation's parameter.
//
class ParamInfo : public UnmarshalCallback
{
public:
virtual void unmarshaled(PyObject*, PyObject*, void*);
Ice::StringSeq metaData;
TypeInfoPtr type;
};
typedef IceUtil::Handle<ParamInfo> ParamInfoPtr;
typedef vector<ParamInfoPtr> ParamInfoList;
//
// Encapsulates attributes of an operation.
//
class Operation : public IceUtil::Shared
{
public:
Operation(const char*, PyObject*, PyObject*, int, PyObject*, PyObject*, PyObject*, PyObject*, PyObject*);
void deprecate(const string&);
string name;
Ice::OperationMode mode;
Ice::OperationMode sendMode;
bool amd;
Ice::StringSeq metaData;
ParamInfoList inParams;
ParamInfoList outParams;
ParamInfoPtr returnType;
ExceptionInfoList exceptions;
string dispatchName;
bool sendsClasses;
bool returnsClasses;
private:
string _deprecateMessage;
static void convertParams(PyObject*, ParamInfoList&, bool&);
};
typedef IceUtil::Handle<Operation> OperationPtr;
//
// The base class for client-side invocations.
//
class Invocation : virtual public IceUtil::Shared
{
public:
Invocation(const Ice::ObjectPrx&);
virtual PyObject* invoke(PyObject*) = 0;
protected:
Ice::ObjectPrx _prx;
};
typedef IceUtil::Handle<Invocation> InvocationPtr;
//
// TypedInvocation uses the information in the given Operation to validate, marshal, and unmarshal
// parameters and exceptions.
//
class TypedInvocation : virtual public Invocation
{
public:
TypedInvocation(const Ice::ObjectPrx&, const OperationPtr&);
protected:
OperationPtr _op;
Ice::CommunicatorPtr _communicator;
bool prepareRequest(PyObject*, bool, vector<Ice::Byte>&);
PyObject* unmarshalResults(const pair<const Ice::Byte*, const Ice::Byte*>&);
PyObject* unmarshalException(const pair<const Ice::Byte*, const Ice::Byte*>&);
bool validateException(PyObject*) const;
void checkTwowayOnly(const Ice::ObjectPrx&) const;
};
//
// A synchronous typed invocation.
//
class SyncTypedInvocation : virtual public TypedInvocation
{
public:
SyncTypedInvocation(const Ice::ObjectPrx&, const OperationPtr&);
virtual PyObject* invoke(PyObject*);
};
//
// An asynchronous typed invocation.
//
class AsyncTypedInvocation : virtual public TypedInvocation, virtual public Ice::AMI_Array_Object_ice_invoke
{
public:
AsyncTypedInvocation(const Ice::ObjectPrx&, const OperationPtr&);
~AsyncTypedInvocation();
virtual PyObject* invoke(PyObject*);
virtual void ice_response(bool, const pair<const Ice::Byte*, const Ice::Byte*>&);
virtual void ice_exception(const Ice::Exception&);
protected:
void handleException(PyObject*);
PyObject* _callback;
};
//
// An asynchronous typed invocation with support for ice_sent.
//
class AsyncSentTypedInvocation : virtual public AsyncTypedInvocation, virtual public Ice::AMISentCallback
{
public:
AsyncSentTypedInvocation(const Ice::ObjectPrx&, const OperationPtr&);
virtual void ice_sent();
};
//
// A synchronous blobject invocation.
//
class SyncBlobjectInvocation : virtual public Invocation
{
public:
SyncBlobjectInvocation(const Ice::ObjectPrx&);
virtual PyObject* invoke(PyObject*);
};
//
// An asynchronous blobject invocation.
//
class AsyncBlobjectInvocation : virtual public Invocation, virtual public Ice::AMI_Array_Object_ice_invoke
{
public:
AsyncBlobjectInvocation(const Ice::ObjectPrx&);
~AsyncBlobjectInvocation();
virtual PyObject* invoke(PyObject*);
virtual void ice_response(bool, const pair<const Ice::Byte*, const Ice::Byte*>&);
virtual void ice_exception(const Ice::Exception&);
protected:
string _op;
PyObject* _callback;
void handleException(PyObject*);
};
//
// An asynchronous blobject invocation with support for ice_sent.
//
class AsyncSentBlobjectInvocation : virtual public AsyncBlobjectInvocation, virtual public Ice::AMISentCallback
{
public:
AsyncSentBlobjectInvocation(const Ice::ObjectPrx&);
virtual void ice_sent();
};
//
// The base class for server-side upcalls.
//
class Upcall : virtual public IceUtil::Shared
{
public:
virtual void dispatch(PyObject*, const pair<const Ice::Byte*, const Ice::Byte*>&, const Ice::Current&) = 0;
virtual void response(PyObject*) = 0;
virtual void exception(PyException&) = 0;
};
typedef IceUtil::Handle<Upcall> UpcallPtr;
//
// TypedInvocation uses the information in the given Operation to validate, marshal, and unmarshal
// parameters and exceptions.
//
class TypedUpcall : virtual public Upcall
{
public:
TypedUpcall(const OperationPtr&, const Ice::AMD_Array_Object_ice_invokePtr&, const Ice::CommunicatorPtr&);
virtual void dispatch(PyObject*, const pair<const Ice::Byte*, const Ice::Byte*>&, const Ice::Current&);
virtual void response(PyObject*);
virtual void exception(PyException&);
private:
bool validateException(PyObject*) const;
OperationPtr _op;
Ice::AMD_Array_Object_ice_invokePtr _callback;
Ice::CommunicatorPtr _communicator;
};
//
// Upcall for blobject servants.
//
class BlobjectUpcall : virtual public Upcall
{
public:
BlobjectUpcall(bool, const Ice::AMD_Array_Object_ice_invokePtr&);
virtual void dispatch(PyObject*, const pair<const Ice::Byte*, const Ice::Byte*>&, const Ice::Current&);
virtual void response(PyObject*);
virtual void exception(PyException&);
private:
bool _amd;
Ice::AMD_Array_Object_ice_invokePtr _callback;
};
//
// TypedServantWrapper uses the information in Operation to validate, marshal, and unmarshal
// parameters and exceptions.
//
class TypedServantWrapper : public ServantWrapper
{
public:
TypedServantWrapper(PyObject*);
virtual void ice_invoke_async(const Ice::AMD_Array_Object_ice_invokePtr&,
const pair<const Ice::Byte*, const Ice::Byte*>&,
const Ice::Current&);
private:
typedef map<string, OperationPtr> OperationMap;
OperationMap _operationMap;
OperationMap::iterator _lastOp;
};
//
// Encapsulates a blobject servant.
//
class BlobjectServantWrapper : public ServantWrapper
{
public:
BlobjectServantWrapper(PyObject*, bool);
virtual void ice_invoke_async(const Ice::AMD_Array_Object_ice_invokePtr&,
const pair<const Ice::Byte*, const Ice::Byte*>&,
const Ice::Current&);
private:
bool _amd;
};
struct OperationObject
{
PyObject_HEAD
OperationPtr* op;
};
struct AMDCallbackObject
{
PyObject_HEAD
UpcallPtr* upcall;
};
extern PyTypeObject OperationType;
extern PyTypeObject AMDCallbackType;
}
static OperationPtr
getOperation(PyObject* p)
{
assert(PyObject_IsInstance(p, reinterpret_cast<PyObject*>(&OperationType)) == 1);
OperationObject* obj = reinterpret_cast<OperationObject*>(p);
return *obj->op;
}
#ifdef WIN32
extern "C"
#endif
static OperationObject*
operationNew(PyObject* /*arg*/)
{
OperationObject* self = PyObject_New(OperationObject, &OperationType);
if(!self)
{
return 0;
}
self->op = 0;
return self;
}
#ifdef WIN32
extern "C"
#endif
static int
operationInit(OperationObject* self, PyObject* args, PyObject* /*kwds*/)
{
char* name;
PyObject* modeType = lookupType("Ice.OperationMode");
assert(modeType);
PyObject* mode;
PyObject* sendMode;
int amd;
PyObject* meta;
PyObject* inParams;
PyObject* outParams;
PyObject* returnType;
PyObject* exceptions;
if(!PyArg_ParseTuple(args, STRCAST("sO!O!iO!O!O!OO!"), &name, modeType, &mode, modeType, &sendMode, &amd,
&PyTuple_Type, &meta, &PyTuple_Type, &inParams, &PyTuple_Type, &outParams, &returnType,
&PyTuple_Type, &exceptions))
{
return -1;
}
OperationPtr op = new Operation(name, mode, sendMode, amd, meta, inParams, outParams, returnType, exceptions);
self->op = new OperationPtr(op);
return 0;
}
#ifdef WIN32
extern "C"
#endif
static void
operationDealloc(OperationObject* self)
{
delete self->op;
PyObject_Del(self);
}
#ifdef WIN32
extern "C"
#endif
static PyObject*
operationInvoke(OperationObject* self, PyObject* args)
{
PyObject* pyProxy;
PyObject* opArgs;
if(!PyArg_ParseTuple(args, STRCAST("O!O!"), &ProxyType, &pyProxy, &PyTuple_Type, &opArgs))
{
return 0;
}
Ice::ObjectPrx prx = getProxy(pyProxy);
assert(self->op);
InvocationPtr i = new SyncTypedInvocation(prx, *self->op);
return i->invoke(opArgs);
}
#ifdef WIN32
extern "C"
#endif
static PyObject*
operationInvokeAsync(OperationObject* self, PyObject* args)
{
PyObject* pyProxy;
PyObject* opArgs;
if(!PyArg_ParseTuple(args, STRCAST("O!O!"), &ProxyType, &pyProxy, &PyTuple_Type, &opArgs))
{
return 0;
}
Ice::ObjectPrx prx = getProxy(pyProxy);
assert(self->op);
//
// If the callback implements an ice_sent method, we create a wrapper that derives
// from AMISentCallback.
//
assert(PyTuple_GET_SIZE(opArgs) > 0);
PyObject* callback = PyTuple_GET_ITEM(opArgs, 0);
if(PyObject_HasAttrString(callback, STRCAST("ice_sent")))
{
InvocationPtr i = new AsyncSentTypedInvocation(prx, *self->op);
return i->invoke(opArgs);
}
else
{
InvocationPtr i = new AsyncTypedInvocation(prx, *self->op);
return i->invoke(opArgs);
}
}
#ifdef WIN32
extern "C"
#endif
static PyObject*
operationDeprecate(OperationObject* self, PyObject* args)
{
char* msg;
if(!PyArg_ParseTuple(args, STRCAST("s"), &msg))
{
return 0;
}
assert(self->op);
(*self->op)->deprecate(msg);
Py_INCREF(Py_None);
return Py_None;
}
#ifdef WIN32
extern "C"
#endif
static AMDCallbackObject*
amdCallbackNew(PyObject* /*arg*/)
{
AMDCallbackObject* self = PyObject_New(AMDCallbackObject, &AMDCallbackType);
if(!self)
{
return 0;
}
self->upcall = 0;
return self;
}
#ifdef WIN32
extern "C"
#endif
static void
amdCallbackDealloc(AMDCallbackObject* self)
{
delete self->upcall;
PyObject_Del(self);
}
#ifdef WIN32
extern "C"
#endif
static PyObject*
amdCallbackIceResponse(AMDCallbackObject* self, PyObject* args)
{
try
{
assert(self->upcall);
(*self->upcall)->response(args);
}
catch(...)
{
//
// No exceptions should propagate to Python.
//
assert(false);
}
Py_INCREF(Py_None);
return Py_None;
}
#ifdef WIN32
extern "C"
#endif
static PyObject*
amdCallbackIceException(AMDCallbackObject* self, PyObject* args)
{
PyObject* ex;
if(!PyArg_ParseTuple(args, STRCAST("O"), &ex))
{
return 0;
}
try
{
assert(self->upcall);
PyException pye(ex); // No traceback information available.
(*self->upcall)->exception(pye);
}
catch(...)
{
//
// No exceptions should propagate to Python.
//
assert(false);
}
Py_INCREF(Py_None);
return Py_None;
}
//
// ParamInfo implementation.
//
void
IcePy::ParamInfo::unmarshaled(PyObject* val, PyObject* target, void* closure)
{
assert(PyTuple_Check(target));
long i = reinterpret_cast<long>(closure);
PyTuple_SET_ITEM(target, i, val);
Py_INCREF(val); // PyTuple_SET_ITEM steals a reference.
}
//
// Operation implementation.
//
IcePy::Operation::Operation(const char* n, PyObject* m, PyObject* sm, int amdFlag, PyObject* meta,
PyObject* in, PyObject* out, PyObject* ret, PyObject* ex)
{
name = n;
//
// mode
//
PyObjectHandle modeValue = PyObject_GetAttrString(m, STRCAST("value"));
assert(PyInt_Check(modeValue.get()));
mode = (Ice::OperationMode)static_cast<int>(PyInt_AS_LONG(modeValue.get()));
//
// sendMode
//
PyObjectHandle sendModeValue = PyObject_GetAttrString(sm, STRCAST("value"));
assert(PyInt_Check(sendModeValue.get()));
sendMode = (Ice::OperationMode)static_cast<int>(PyInt_AS_LONG(sendModeValue.get()));
//
// amd
//
amd = amdFlag ? true : false;
if(amd)
{
dispatchName = fixIdent(name) + "_async";
}
else
{
dispatchName = fixIdent(name);
}
//
// metaData
//
#ifndef NDEBUG
bool b =
#endif
tupleToStringSeq(meta, metaData);
assert(b);
Py_ssize_t i, sz;
//
// inParams
//
convertParams(in, inParams, sendsClasses);
//
// outParams
//
convertParams(out, outParams, returnsClasses);
//
// returnType
//
if(ret != Py_None)
{
returnType = new ParamInfo;
returnType->type = getType(ret);
if(!returnsClasses)
{
returnsClasses = returnType->type->usesClasses();
}
}
//
// exceptions
//
sz = PyTuple_GET_SIZE(ex);
for(i = 0; i < sz; ++i)
{
exceptions.push_back(getException(PyTuple_GET_ITEM(ex, i)));
}
}
void
IcePy::Operation::deprecate(const string& msg)
{
if(!msg.empty())
{
_deprecateMessage = msg;
}
else
{
_deprecateMessage = "operation " + name + " is deprecated";
}
}
void
IcePy::Operation::convertParams(PyObject* p, ParamInfoList& params, bool& usesClasses)
{
usesClasses = false;
int sz = static_cast<int>(PyTuple_GET_SIZE(p));
for(int i = 0; i < sz; ++i)
{
PyObject* item = PyTuple_GET_ITEM(p, i);
assert(PyTuple_Check(item));
assert(PyTuple_GET_SIZE(item) == 2);
ParamInfoPtr param = new ParamInfo;
//
// metaData
//
PyObject* meta = PyTuple_GET_ITEM(item, 0);
assert(PyTuple_Check(meta));
#ifndef NDEBUG
bool b =
#endif
tupleToStringSeq(meta, param->metaData);
assert(b);
//
// type
//
param->type = getType(PyTuple_GET_ITEM(item, 1));
params.push_back(param);
if(!usesClasses)
{
usesClasses = param->type->usesClasses();
}
}
}
static PyMethodDef OperationMethods[] =
{
{ STRCAST("invoke"), reinterpret_cast<PyCFunction>(operationInvoke), METH_VARARGS,
PyDoc_STR(STRCAST("internal function")) },
{ STRCAST("invokeAsync"), reinterpret_cast<PyCFunction>(operationInvokeAsync), METH_VARARGS,
PyDoc_STR(STRCAST("internal function")) },
{ STRCAST("deprecate"), reinterpret_cast<PyCFunction>(operationDeprecate), METH_VARARGS,
PyDoc_STR(STRCAST("internal function")) },
{ 0, 0 } /* sentinel */
};
static PyMethodDef AMDCallbackMethods[] =
{
{ STRCAST("ice_response"), reinterpret_cast<PyCFunction>(amdCallbackIceResponse), METH_VARARGS,
PyDoc_STR(STRCAST("internal function")) },
{ STRCAST("ice_exception"), reinterpret_cast<PyCFunction>(amdCallbackIceException), METH_VARARGS,
PyDoc_STR(STRCAST("internal function")) },
{ 0, 0 } /* sentinel */
};
namespace IcePy
{
PyTypeObject OperationType =
{
/* The ob_type field must be initialized in the module init function
* to be portable to Windows without using C++. */
PyObject_HEAD_INIT(0)
0, /* ob_size */
STRCAST("IcePy.Operation"), /* tp_name */
sizeof(OperationObject), /* tp_basicsize */
0, /* tp_itemsize */
/* methods */
reinterpret_cast<destructor>(operationDealloc), /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_compare */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT, /* tp_flags */
0, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
OperationMethods, /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
reinterpret_cast<initproc>(operationInit), /* tp_init */
0, /* tp_alloc */
reinterpret_cast<newfunc>(operationNew), /* tp_new */
0, /* tp_free */
0, /* tp_is_gc */
};
PyTypeObject AMDCallbackType =
{
/* The ob_type field must be initialized in the module init function
* to be portable to Windows without using C++. */
PyObject_HEAD_INIT(0)
0, /* ob_size */
STRCAST("IcePy.AMDCallback"), /* tp_name */
sizeof(AMDCallbackObject), /* tp_basicsize */
0, /* tp_itemsize */
/* methods */
reinterpret_cast<destructor>(amdCallbackDealloc), /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_compare */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT, /* tp_flags */
0, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
AMDCallbackMethods, /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
0, /* tp_init */
0, /* tp_alloc */
reinterpret_cast<newfunc>(amdCallbackNew), /* tp_new */
0, /* tp_free */
0, /* tp_is_gc */
};
}
bool
IcePy::initOperation(PyObject* module)
{
if(PyType_Ready(&OperationType) < 0)
{
return false;
}
PyTypeObject* opType = &OperationType; // Necessary to prevent GCC's strict-alias warnings.
if(PyModule_AddObject(module, STRCAST("Operation"), reinterpret_cast<PyObject*>(opType)) < 0)
{
return false;
}
if(PyType_Ready(&AMDCallbackType) < 0)
{
return false;
}
PyTypeObject* cbType = &AMDCallbackType; // Necessary to prevent GCC's strict-alias warnings.
if(PyModule_AddObject(module, STRCAST("AMDCallback"), reinterpret_cast<PyObject*>(cbType)) < 0)
{
return false;
}
return true;
}
//
// Invocation
//
IcePy::Invocation::Invocation(const Ice::ObjectPrx& prx) :
_prx(prx)
{
}
//
// TypedInvocation
//
IcePy::TypedInvocation::TypedInvocation(const Ice::ObjectPrx& prx, const OperationPtr& op) :
Invocation(prx), _op(op), _communicator(prx->ice_getCommunicator())
{
}
bool
IcePy::TypedInvocation::prepareRequest(PyObject* args, bool async, vector<Ice::Byte>& bytes)
{
assert(PyTuple_Check(args));
//
// Validate the number of arguments.
//
Py_ssize_t argc = PyTuple_GET_SIZE(args);
Py_ssize_t paramCount = static_cast<Py_ssize_t>(_op->inParams.size());
if(argc != paramCount)
{
string fixedName = fixIdent(_op->name);
if(async)
{
fixedName += "_async";
}
PyErr_Format(PyExc_RuntimeError, STRCAST("%s expects %d in parameters"), fixedName.c_str(),
static_cast<int>(paramCount));
return false;
}
if(!_op->inParams.empty())
{
try
{
//
// Marshal the in parameters.
//
Ice::OutputStreamPtr os = Ice::createOutputStream(_communicator);
ObjectMap objectMap;
int i = 0;
for(ParamInfoList::iterator p = _op->inParams.begin(); p != _op->inParams.end(); ++p, ++i)
{
PyObject* arg = PyTuple_GET_ITEM(args, i);
if(!(*p)->type->validate(arg))
{
string opName;
if(async)
{
opName = fixIdent(_op->name) + "_async";
}
else
{
opName = fixIdent(_op->name);
}
PyErr_Format(PyExc_ValueError, STRCAST("invalid value for argument %d in operation `%s'"),
async ? i + 2 : i + 1, const_cast<char*>(opName.c_str()));
return false;
}
(*p)->type->marshal(arg, os, &objectMap, &(*p)->metaData);
}
if(_op->sendsClasses)
{
os->writePendingObjects();
}
os->finished(bytes);
}
catch(const AbortMarshaling&)
{
assert(PyErr_Occurred());
return false;
}
catch(const Ice::Exception& ex)
{
setPythonException(ex);
return false;
}
}
return true;
}
PyObject*
IcePy::TypedInvocation::unmarshalResults(const pair<const Ice::Byte*, const Ice::Byte*>& bytes)
{
Py_ssize_t i = _op->returnType ? 1 : 0;
Py_ssize_t numResults = static_cast<Py_ssize_t>(_op->outParams.size()) + i;
PyObjectHandle results = PyTuple_New(numResults);
if(results.get() && numResults > 0)
{
//
// Unmarshal the results. If there is more than one value to be returned, then return them
// in a tuple of the form (result, outParam1, ...). Otherwise just return the value.
//
Ice::InputStreamPtr is = Ice::createInputStream(_communicator, bytes);
for(ParamInfoList::iterator p = _op->outParams.begin(); p != _op->outParams.end(); ++p, ++i)
{
void* closure = reinterpret_cast<void*>(i);
(*p)->type->unmarshal(is, *p, results.get(), closure, &(*p)->metaData);
}
if(_op->returnType)
{
_op->returnType->type->unmarshal(is, _op->returnType, results.get(), 0, &_op->metaData);
}
if(_op->returnsClasses)
{
is->readPendingObjects();
}
}
return results.release();
}
PyObject*
IcePy::TypedInvocation::unmarshalException(const pair<const Ice::Byte*, const Ice::Byte*>& bytes)
{
int traceSlicing = -1;
Ice::InputStreamPtr is = Ice::createInputStream(_communicator, bytes);
is->readBool(); // usesClasses
string id = is->readString();
const string origId = id;
while(!id.empty())
{
ExceptionInfoPtr info = lookupExceptionInfo(id);
if(info)
{
PyObjectHandle ex = info->unmarshal(is);
if(info->usesClasses)
{
is->readPendingObjects();
}
if(validateException(ex.get()))
{
return ex.release();
}
else
{
PyException pye(ex.get()); // No traceback information available.
pye.raise();
}
}
else
{
if(traceSlicing == -1)
{
traceSlicing = _communicator->getProperties()->getPropertyAsInt("Ice.Trace.Slicing") > 0;
}
if(traceSlicing > 0)
{
_communicator->getLogger()->trace("Slicing", "unknown exception type `" + id + "'");
}
is->skipSlice(); // Slice off what we don't understand.
try
{
id = is->readString(); // Read type id for next slice.
}
catch(Ice::UnmarshalOutOfBoundsException& ex)
{
//
// When readString raises this exception it means we've seen the last slice,
// so we set the reason member to a more helpful message.
//
ex.reason = "unknown exception type `" + origId + "'";
throw;
}
}
}
//
// Getting here should be impossible: we can get here only if the
// sender has marshaled a sequence of type IDs, none of which we
// have a factory for. This means that sender and receiver disagree
// about the Slice definitions they use.
//
throw Ice::UnknownUserException(__FILE__, __LINE__, "unknown exception type `" + origId + "'");
}
bool
IcePy::TypedInvocation::validateException(PyObject* ex) const
{
for(ExceptionInfoList::const_iterator p = _op->exceptions.begin(); p != _op->exceptions.end(); ++p)
{
if(PyObject_IsInstance(ex, (*p)->pythonType.get()))
{
return true;
}
}
return false;
}
void
IcePy::TypedInvocation::checkTwowayOnly(const Ice::ObjectPrx& proxy) const
{
if((_op->returnType != 0 || !_op->outParams.empty()) && !proxy->ice_isTwoway())
{
Ice::TwowayOnlyException ex(__FILE__, __LINE__);
ex.operation = _op->name;
throw ex;
}
}
//
// SyncTypedInvocation
//
IcePy::SyncTypedInvocation::SyncTypedInvocation(const Ice::ObjectPrx& prx, const OperationPtr& op) :
Invocation(prx), TypedInvocation(prx, op)
{
}
PyObject*
IcePy::SyncTypedInvocation::invoke(PyObject* args)
{
assert(PyTuple_Check(args));
assert(PyTuple_GET_SIZE(args) == 2); // Format is ((params...), context|None)
PyObject* pyparams = PyTuple_GET_ITEM(args, 0);
assert(PyTuple_Check(pyparams));
PyObject* pyctx = PyTuple_GET_ITEM(args, 1);
//
// Marshal the input parameters to a byte sequence.
//
Ice::ByteSeq params;
if(!prepareRequest(pyparams, false, params))
{
return 0;
}
try
{
checkTwowayOnly(_prx);
//
// Invoke the operation.
//
vector<Ice::Byte> result;
bool status;
{
if(pyctx != Py_None)
{
Ice::Context ctx;
if(!PyDict_Check(pyctx))
{
PyErr_Format(PyExc_ValueError, STRCAST("context argument must be None or a dictionary"));
return 0;
}
if(!dictionaryToContext(pyctx, ctx))
{
return 0;
}
AllowThreads allowThreads; // Release Python's global interpreter lock during remote invocations.
status = _prx->ice_invoke(_op->name, _op->sendMode, params, result, ctx);
}
else
{
AllowThreads allowThreads; // Release Python's global interpreter lock during remote invocations.
status = _prx->ice_invoke(_op->name, _op->sendMode, params, result);
}
}
//
// Process the reply.
//
if(_prx->ice_isTwoway())
{
if(!status)
{
//
// Unmarshal a user exception.
//
pair<const Ice::Byte*, const Ice::Byte*> rb(0, 0);
if(!result.empty())
{
rb.first = &result[0];
rb.second = &result[0] + result.size();
}
PyObjectHandle ex = unmarshalException(rb);
//
// Set the Python exception.
//
setPythonException(ex.get());
return 0;
}
else if(_op->outParams.size() > 0 || _op->returnType)
{
//
// Unmarshal the results. If there is more than one value to be returned, then return them
// in a tuple of the form (result, outParam1, ...). Otherwise just return the value.
//
pair<const Ice::Byte*, const Ice::Byte*> rb(0, 0);
if(!result.empty())
{
rb.first = &result[0];
rb.second = &result[0] + result.size();
}
PyObjectHandle results = unmarshalResults(rb);
if(!results.get())
{
return 0;
}
if(PyTuple_GET_SIZE(results.get()) > 1)
{
return results.release();
}
else
{
PyObject* ret = PyTuple_GET_ITEM(results.get(), 0);
if(!ret)
{
return 0;
}
else
{
Py_INCREF(ret);
return ret;
}
}
}
}
}
catch(const AbortMarshaling&)
{
assert(PyErr_Occurred());
return 0;
}
catch(const Ice::Exception& ex)
{
setPythonException(ex);
return 0;
}
Py_INCREF(Py_None);
return Py_None;
}
//
// AsyncTypedInvocation
//
IcePy::AsyncTypedInvocation::AsyncTypedInvocation(const Ice::ObjectPrx& prx, const OperationPtr& op)
: Invocation(prx), TypedInvocation(prx, op), _callback(0)
{
}
IcePy::AsyncTypedInvocation::~AsyncTypedInvocation()
{
AdoptThread adoptThread; // Ensure the current thread is able to call into Python.
Py_XDECREF(_callback);
}
PyObject*
IcePy::AsyncTypedInvocation::invoke(PyObject* args)
{
assert(PyTuple_Check(args));
assert(PyTuple_GET_SIZE(args) == 3); // Format is (callback, (params...), context|None)
_callback = PyTuple_GET_ITEM(args, 0);
Py_INCREF(_callback);
PyObject* pyparams = PyTuple_GET_ITEM(args, 1);
assert(PyTuple_Check(pyparams));
PyObject* pyctx = PyTuple_GET_ITEM(args, 2);
//
// Marshal the input parameters to a byte sequence.
//
Ice::ByteSeq params;
if(!prepareRequest(pyparams, true, params))
{
return 0;
}
bool result = false;
try
{
checkTwowayOnly(_prx);
pair<const Ice::Byte*, const Ice::Byte*> pparams(0, 0);
if(!params.empty())
{
pparams.first = ¶ms[0];
pparams.second = ¶ms[0] + params.size();
}
//
// Invoke the operation asynchronously.
//
if(pyctx != Py_None)
{
Ice::Context ctx;
if(!PyDict_Check(pyctx))
{
PyErr_Format(PyExc_ValueError, STRCAST("context argument must be None or a dictionary"));
return 0;
}
if(!dictionaryToContext(pyctx, ctx))
{
return 0;
}
AllowThreads allowThreads; // Release Python's global interpreter lock during remote invocations.
result = _prx->ice_invoke_async(this, _op->name, _op->sendMode, pparams, ctx);
}
else
{
AllowThreads allowThreads; // Release Python's global interpreter lock during remote invocations.
result = _prx->ice_invoke_async(this, _op->name, _op->sendMode, pparams);
}
}
catch(const Ice::CommunicatorDestroyedException& ex)
{
//
// CommunicatorDestroyedException is the only exception that can propagate directly.
//
setPythonException(ex);
return 0;
}
catch(const Ice::Exception& ex)
{
PyObjectHandle exh = convertException(ex);
assert(exh.get());
handleException(exh.get());
}
PyRETURN_BOOL(result);
}
void
IcePy::AsyncTypedInvocation::ice_response(bool ok, const pair<const Ice::Byte*, const Ice::Byte*>& results)
{
AdoptThread adoptThread; // Ensure the current thread is able to call into Python.
try
{
if(ok)
{
//
// Unmarshal the results.
//
PyObjectHandle args;
try
{
args = unmarshalResults(results);
if(!args.get())
{
assert(PyErr_Occurred());
PyErr_Print();
return;
}
}
catch(const Ice::Exception& ex)
{
PyObjectHandle h = convertException(ex);
handleException(h.get());
return;
}
PyObjectHandle method = PyObject_GetAttrString(_callback, STRCAST("ice_response"));
if(!method.get())
{
ostringstream ostr;
ostr << "AMI callback object for operation `" << _op->name << "' does not define ice_response()";
string str = ostr.str();
PyErr_Warn(PyExc_RuntimeWarning, const_cast<char*>(str.c_str()));
}
else
{
PyObjectHandle tmp = PyObject_Call(method.get(), args.get(), 0);
if(PyErr_Occurred())
{
PyErr_Print();
}
}
}
else
{
PyObjectHandle ex = unmarshalException(results);
handleException(ex.get());
}
}
catch(const AbortMarshaling&)
{
assert(PyErr_Occurred());
PyErr_Print();
}
catch(const Ice::Exception& ex)
{
ostringstream ostr;
ostr << "Exception raised by AMI callback for operation `" << _op->name << "':" << ex;
string str = ostr.str();
PyErr_Warn(PyExc_RuntimeWarning, const_cast<char*>(str.c_str()));
}
}
void
IcePy::AsyncTypedInvocation::ice_exception(const Ice::Exception& ex)
{
AdoptThread adoptThread; // Ensure the current thread is able to call into Python.
PyObjectHandle exh = convertException(ex);
assert(exh.get());
handleException(exh.get());
}
void
IcePy::AsyncTypedInvocation::handleException(PyObject* ex)
{
PyObjectHandle method = PyObject_GetAttrString(_callback, STRCAST("ice_exception"));
if(!method.get())
{
ostringstream ostr;
ostr << "AMI callback object for operation `" << _op->name << "' does not define ice_exception()";
string str = ostr.str();
PyErr_Warn(PyExc_RuntimeWarning, const_cast<char*>(str.c_str()));
}
else
{
PyObjectHandle args = Py_BuildValue(STRCAST("(O)"), ex);
PyObjectHandle tmp = PyObject_Call(method.get(), args.get(), 0);
if(PyErr_Occurred())
{
PyErr_Print();
}
}
}
//
// AsyncSentTypedInvocation
//
IcePy::AsyncSentTypedInvocation::AsyncSentTypedInvocation(const Ice::ObjectPrx& prx, const OperationPtr& op)
: Invocation(prx), TypedInvocation(prx, op), AsyncTypedInvocation(prx, op)
{
}
void
IcePy::AsyncSentTypedInvocation::ice_sent()
{
AdoptThread adoptThread; // Ensure the current thread is able to call into Python.
PyObjectHandle method = PyObject_GetAttrString(_callback, STRCAST("ice_sent"));
if(!method.get())
{
ostringstream ostr;
ostr << "AMI callback object for operation `" << _op->name << "' does not define ice_sent()";
string str = ostr.str();
PyErr_Warn(PyExc_RuntimeWarning, const_cast<char*>(str.c_str()));
}
else
{
PyObjectHandle args = PyTuple_New(0);
PyObjectHandle tmp = PyObject_Call(method.get(), args.get(), 0);
if(PyErr_Occurred())
{
PyErr_Print();
}
}
}
//
// SyncBlobjectInvocation
//
IcePy::SyncBlobjectInvocation::SyncBlobjectInvocation(const Ice::ObjectPrx& prx)
: Invocation(prx)
{
}
PyObject*
IcePy::SyncBlobjectInvocation::invoke(PyObject* args)
{
char* operation;
PyObject* mode;
PyObject* inParams;
PyObject* operationModeType = lookupType("Ice.OperationMode");
PyObject* ctx = 0;
if(!PyArg_ParseTuple(args, STRCAST("sO!O!|O"), &operation, operationModeType, &mode, &PyBuffer_Type, &inParams,
&ctx))
{
return 0;
}
PyObjectHandle modeValue = PyObject_GetAttrString(mode, STRCAST("value"));
Ice::OperationMode sendMode = (Ice::OperationMode)static_cast<int>(PyInt_AS_LONG(modeValue.get()));
//
// Use the array API to avoid copying the data.
//
#if PY_VERSION_HEX < 0x02050000
const char* charBuf = 0;
#else
char* charBuf = 0;
#endif
Py_ssize_t sz = inParams->ob_type->tp_as_buffer->bf_getcharbuffer(inParams, 0, &charBuf);
const Ice::Byte* mem = reinterpret_cast<const Ice::Byte*>(charBuf);
pair<const ::Ice::Byte*, const ::Ice::Byte*> in(0, 0);
if(sz > 0)
{
in.first = mem;
in.second = mem + sz;
}
try
{
vector<Ice::Byte> out;
bool ok;
if(ctx == 0 || ctx == Py_None)
{
AllowThreads allowThreads; // Release Python's global interpreter lock during remote invocations.
ok = _prx->ice_invoke(operation, sendMode, in, out);
}
else
{
Ice::Context context;
if(!dictionaryToContext(ctx, context))
{
return 0;
}
AllowThreads allowThreads; // Release Python's global interpreter lock during remote invocations.
ok = _prx->ice_invoke(operation, sendMode, in, out, context);
}
//
// Prepare the result as a tuple of the bool and out param buffer.
//
PyObjectHandle result = PyTuple_New(2);
if(!result.get())
{
throwPythonException();
}
if(PyTuple_SET_ITEM(result.get(), 0, ok ? getTrue() : getFalse()) < 0)
{
throwPythonException();
}
//
// Create the output buffer and copy in the outParams.
//
PyObjectHandle ip = PyBuffer_New(out.size());
if(!ip.get())
{
throwPythonException();
}
if(!out.empty())
{
void* buf;
Py_ssize_t sz;
if(PyObject_AsWriteBuffer(ip.get(), &buf, &sz))
{
throwPythonException();
}
memcpy(buf, &out[0], sz);
}
if(PyTuple_SET_ITEM(result.get(), 1, ip.get()) < 0)
{
throwPythonException();
}
ip.release(); // PyTuple_SET_ITEM steals a reference.
return result.release();
}
catch(const Ice::Exception& ex)
{
setPythonException(ex);
return 0;
}
}
//
// AsyncBlobjectInvocation
//
IcePy::AsyncBlobjectInvocation::AsyncBlobjectInvocation(const Ice::ObjectPrx& prx)
: Invocation(prx), _callback(0)
{
}
IcePy::AsyncBlobjectInvocation::~AsyncBlobjectInvocation()
{
AdoptThread adoptThread; // Ensure the current thread is able to call into Python.
Py_XDECREF(_callback);
}
PyObject*
IcePy::AsyncBlobjectInvocation::invoke(PyObject* args)
{
char* operation;
PyObject* mode;
PyObject* inParams;
PyObject* operationModeType = lookupType("Ice.OperationMode");
PyObject* ctx = 0;
if(!PyArg_ParseTuple(args, STRCAST("OsO!O!|O"), &_callback, &operation, operationModeType, &mode,
&PyBuffer_Type, &inParams, &ctx))
{
return 0;
}
Py_INCREF(_callback);
_op = operation;
PyObjectHandle modeValue = PyObject_GetAttrString(mode, STRCAST("value"));
Ice::OperationMode sendMode = (Ice::OperationMode)static_cast<int>(PyInt_AS_LONG(modeValue.get()));
//
// Use the array API to avoid copying the data.
//
#if PY_VERSION_HEX < 0x02050000
const char* charBuf = 0;
#else
char* charBuf = 0;
#endif
Py_ssize_t sz = inParams->ob_type->tp_as_buffer->bf_getcharbuffer(inParams, 0, &charBuf);
const Ice::Byte* mem = reinterpret_cast<const Ice::Byte*>(charBuf);
pair<const ::Ice::Byte*, const ::Ice::Byte*> in(0, 0);
if(sz > 0)
{
in.first = mem;
in.second = mem + sz;
}
bool result = false;
try
{
if(ctx == 0 || ctx == Py_None)
{
AllowThreads allowThreads; // Release Python's global interpreter lock during remote invocations.
result = _prx->ice_invoke_async(this, operation, sendMode, in);
}
else
{
Ice::Context context;
if(!dictionaryToContext(ctx, context))
{
return 0;
}
AllowThreads allowThreads; // Release Python's global interpreter lock during remote invocations.
result = _prx->ice_invoke_async(this, operation, sendMode, in, context);
}
}
catch(const Ice::CommunicatorDestroyedException& ex)
{
//
// CommunicatorDestroyedException is the only exception that can propagate directly.
//
setPythonException(ex);
return 0;
}
catch(const Ice::Exception& ex)
{
PyObjectHandle exh = convertException(ex);
assert(exh.get());
handleException(exh.get());
}
PyRETURN_BOOL(result);
}
void
IcePy::AsyncBlobjectInvocation::ice_response(bool ok, const pair<const Ice::Byte*, const Ice::Byte*>& results)
{
AdoptThread adoptThread; // Ensure the current thread is able to call into Python.
try
{
//
// Prepare the args as a tuple of the bool and out param buffer.
//
PyObjectHandle args = PyTuple_New(2);
if(!args.get())
{
assert(PyErr_Occurred());
PyErr_Print();
return;
}
if(PyTuple_SET_ITEM(args.get(), 0, ok ? getTrue() : getFalse()) < 0)
{
assert(PyErr_Occurred());
PyErr_Print();
return;
}
//
// Create the output buffer and copy in the outParams.
//
PyObjectHandle ip = PyBuffer_New(results.second - results.first);
if(!ip.get())
{
assert(PyErr_Occurred());
PyErr_Print();
return;
}
void* buf;
Py_ssize_t sz;
if(PyObject_AsWriteBuffer(ip.get(), &buf, &sz))
{
assert(PyErr_Occurred());
PyErr_Print();
return;
}
assert(sz == results.second - results.first);
memcpy(buf, results.first, sz);
if(PyTuple_SET_ITEM(args.get(), 1, ip.get()) < 0)
{
assert(PyErr_Occurred());
PyErr_Print();
return;
}
ip.release(); // PyTuple_SET_ITEM steals a reference.
PyObjectHandle method = PyObject_GetAttrString(_callback, STRCAST("ice_response"));
if(!method.get())
{
ostringstream ostr;
ostr << "AMI callback object for operation `ice_invoke_async' does not define ice_response()";
string str = ostr.str();
PyErr_Warn(PyExc_RuntimeWarning, const_cast<char*>(str.c_str()));
}
else
{
PyObjectHandle tmp = PyObject_Call(method.get(), args.get(), 0);
if(PyErr_Occurred())
{
PyErr_Print();
}
}
}
catch(const Ice::Exception& ex)
{
ostringstream ostr;
ostr << "Exception raised by AMI callback for operation `ice_invoke_async':" << ex;
string str = ostr.str();
PyErr_Warn(PyExc_RuntimeWarning, const_cast<char*>(str.c_str()));
}
}
void
IcePy::AsyncBlobjectInvocation::ice_exception(const Ice::Exception& ex)
{
AdoptThread adoptThread; // Ensure the current thread is able to call into Python.
PyObjectHandle exh = convertException(ex);
assert(exh.get());
handleException(exh.get());
}
void
IcePy::AsyncBlobjectInvocation::handleException(PyObject* ex)
{
PyObjectHandle method = PyObject_GetAttrString(_callback, STRCAST("ice_exception"));
if(!method.get())
{
ostringstream ostr;
ostr << "AMI callback object for operation `" << _op << "' does not define ice_exception()";
string str = ostr.str();
PyErr_Warn(PyExc_RuntimeWarning, const_cast<char*>(str.c_str()));
}
else
{
PyObjectHandle args = Py_BuildValue(STRCAST("(O)"), ex);
PyObjectHandle tmp = PyObject_Call(method.get(), args.get(), 0);
if(PyErr_Occurred())
{
PyErr_Print();
}
}
}
//
// AsyncSentBlobjectInvocation
//
IcePy::AsyncSentBlobjectInvocation::AsyncSentBlobjectInvocation(const Ice::ObjectPrx& prx)
: Invocation(prx), AsyncBlobjectInvocation(prx)
{
}
void
IcePy::AsyncSentBlobjectInvocation::ice_sent()
{
AdoptThread adoptThread; // Ensure the current thread is able to call into Python.
PyObjectHandle method = PyObject_GetAttrString(_callback, STRCAST("ice_sent"));
if(!method.get())
{
ostringstream ostr;
ostr << "AMI callback object for ice_invoke_async does not define ice_sent()";
string str = ostr.str();
PyErr_Warn(PyExc_RuntimeWarning, const_cast<char*>(str.c_str()));
}
else
{
PyObjectHandle args = PyTuple_New(0);
PyObjectHandle tmp = PyObject_Call(method.get(), args.get(), 0);
if(PyErr_Occurred())
{
PyErr_Print();
}
}
}
//
// TypedUpcall
//
IcePy::TypedUpcall::TypedUpcall(const OperationPtr& op, const Ice::AMD_Array_Object_ice_invokePtr& callback,
const Ice::CommunicatorPtr& communicator) :
_op(op), _callback(callback), _communicator(communicator)
{
}
void
IcePy::TypedUpcall::dispatch(PyObject* servant, const pair<const Ice::Byte*, const Ice::Byte*>& inBytes,
const Ice::Current& current)
{
//
// Unmarshal the in parameters. We have to leave room in the arguments for a trailing
// Ice::Current object.
//
Py_ssize_t count = static_cast<Py_ssize_t>(_op->inParams.size()) + 1;
Py_ssize_t start = 0;
if(_op->amd)
{
++count; // Leave room for a leading AMD callback argument.
start = 1;
}
PyObjectHandle args = PyTuple_New(count);
if(!args.get())
{
throwPythonException();
}
if(!_op->inParams.empty())
{
Ice::InputStreamPtr is = Ice::createInputStream(_communicator, inBytes);
try
{
Py_ssize_t i = start;
for(ParamInfoList::iterator p = _op->inParams.begin(); p != _op->inParams.end(); ++p, ++i)
{
void* closure = reinterpret_cast<void*>(i);
(*p)->type->unmarshal(is, *p, args.get(), closure, &(*p)->metaData);
}
if(_op->sendsClasses)
{
is->readPendingObjects();
}
}
catch(const AbortMarshaling&)
{
throwPythonException();
}
}
//
// Create an object to represent Ice::Current. We need to append this to the argument tuple.
//
PyObjectHandle curr = createCurrent(current);
if(PyTuple_SET_ITEM(args.get(), PyTuple_GET_SIZE(args.get()) - 1, curr.get()) < 0)
{
throwPythonException();
}
curr.release(); // PyTuple_SET_ITEM steals a reference.
if(_op->amd)
{
//
// Create the callback object and pass it as the first argument.
//
AMDCallbackObject* obj = amdCallbackNew(0);
if(!obj)
{
throwPythonException();
}
obj->upcall = new UpcallPtr(this);
if(PyTuple_SET_ITEM(args.get(), 0, (PyObject*)obj) < 0) // PyTuple_SET_ITEM steals a reference.
{
Py_DECREF(obj);
throwPythonException();
}
}
//
// Dispatch the operation. Use _dispatchName here, not current.operation.
//
PyObjectHandle method = PyObject_GetAttrString(servant, const_cast<char*>(_op->dispatchName.c_str()));
if(!method.get())
{
ostringstream ostr;
ostr << "servant for identity " << _communicator->identityToString(current.id)
<< " does not define operation `" << _op->dispatchName << "'";
string str = ostr.str();
PyErr_Warn(PyExc_RuntimeWarning, const_cast<char*>(str.c_str()));
Ice::UnknownException ex(__FILE__, __LINE__);
ex.unknown = str;
throw ex;
}
PyObjectHandle result = PyObject_Call(method.get(), args.get(), 0);
//
// Check for exceptions.
//
if(PyErr_Occurred())
{
PyException ex; // Retrieve it before another Python API call clears it.
exception(ex);
return;
}
if(!_op->amd)
{
response(result.get());
}
}
void
IcePy::TypedUpcall::response(PyObject* args)
{
try
{
//
// Marshal the results. If there is more than one value to be returned, then they must be
// returned in a tuple of the form (result, outParam1, ...).
//
Ice::OutputStreamPtr os = Ice::createOutputStream(_communicator);
try
{
Py_ssize_t i = _op->returnType ? 1 : 0;
Py_ssize_t numResults = static_cast<Py_ssize_t>(_op->outParams.size()) + i;
if(numResults > 1)
{
if(!PyTuple_Check(args) || PyTuple_GET_SIZE(args) != numResults)
{
ostringstream ostr;
ostr << "operation `" << fixIdent(_op->name) << "' should return a tuple of length " << numResults;
string str = ostr.str();
PyErr_Warn(PyExc_RuntimeWarning, const_cast<char*>(str.c_str()));
throw Ice::MarshalException(__FILE__, __LINE__);
}
}
ObjectMap objectMap;
for(ParamInfoList::iterator p = _op->outParams.begin(); p != _op->outParams.end(); ++p, ++i)
{
PyObject* arg;
if(_op->amd || numResults > 1)
{
arg = PyTuple_GET_ITEM(args, i);
}
else
{
arg = args;
assert(_op->outParams.size() == 1);
}
if(!(*p)->type->validate(arg))
{
// TODO: Provide the parameter name instead?
ostringstream ostr;
ostr << "invalid value for out argument " << (i + 1) << " in operation `" << fixIdent(_op->name)
<< (_op->amd ? "_async" : "") << "'";
string str = ostr.str();
PyErr_Warn(PyExc_RuntimeWarning, const_cast<char*>(str.c_str()));
throw Ice::MarshalException(__FILE__, __LINE__);
}
(*p)->type->marshal(arg, os, &objectMap, &(*p)->metaData);
}
if(_op->returnType)
{
PyObject* res;
if(_op->amd || numResults > 1)
{
res = PyTuple_GET_ITEM(args, 0);
}
else
{
assert(_op->outParams.size() == 0);
res = args;
}
if(!_op->returnType->type->validate(res))
{
ostringstream ostr;
ostr << "invalid return value for operation `" << fixIdent(_op->name) << "'";
string str = ostr.str();
PyErr_Warn(PyExc_RuntimeWarning, const_cast<char*>(str.c_str()));
throw Ice::MarshalException(__FILE__, __LINE__);
}
_op->returnType->type->marshal(res, os, &objectMap, &_op->metaData);
}
if(_op->returnsClasses)
{
os->writePendingObjects();
}
Ice::ByteSeq bytes;
os->finished(bytes);
pair<const Ice::Byte*, const Ice::Byte*> ob(0, 0);
if(!bytes.empty())
{
ob.first = &bytes[0];
ob.second = &bytes[0] + bytes.size();
}
AllowThreads allowThreads; // Release Python's global interpreter lock during blocking calls.
_callback->ice_response(true, ob);
}
catch(const AbortMarshaling&)
{
throwPythonException();
}
}
catch(const Ice::Exception& ex)
{
AllowThreads allowThreads; // Release Python's global interpreter lock during blocking calls.
_callback->ice_exception(ex);
}
}
void
IcePy::TypedUpcall::exception(PyException& ex)
{
try
{
try
{
//
// A servant that calls sys.exit() will raise the SystemExit exception.
// This is normally caught by the interpreter, causing it to exit.
// However, we have no way to pass this exception to the interpreter,
// so we act on it directly.
//
ex.checkSystemExit();
PyObject* userExceptionType = lookupType("Ice.UserException");
if(PyObject_IsInstance(ex.ex.get(), userExceptionType))
{
//
// Get the exception's type and verify that it is legal to be thrown from this operation.
//
PyObjectHandle iceType = PyObject_GetAttrString(ex.ex.get(), STRCAST("ice_type"));
assert(iceType.get());
ExceptionInfoPtr info = ExceptionInfoPtr::dynamicCast(getException(iceType.get()));
assert(info);
if(!validateException(ex.ex.get()))
{
ex.raise(); // Raises UnknownUserException.
}
else
{
Ice::OutputStreamPtr os = Ice::createOutputStream(_communicator);
os->writeBool(info->usesClasses);
ObjectMap objectMap;
info->marshal(ex.ex.get(), os, &objectMap);
if(info->usesClasses)
{
os->writePendingObjects();
}
Ice::ByteSeq bytes;
os->finished(bytes);
pair<const Ice::Byte*, const Ice::Byte*> ob(0, 0);
if(!bytes.empty())
{
ob.first = &bytes[0];
ob.second = &bytes[0] + bytes.size();
}
AllowThreads allowThreads; // Release Python's global interpreter lock during blocking calls.
_callback->ice_response(false, ob);
}
}
else
{
ex.raise();
}
}
catch(const AbortMarshaling&)
{
throwPythonException();
}
}
catch(const Ice::Exception& ex)
{
AllowThreads allowThreads; // Release Python's global interpreter lock during blocking calls.
_callback->ice_exception(ex);
}
}
bool
IcePy::TypedUpcall::validateException(PyObject* ex) const
{
for(ExceptionInfoList::const_iterator p = _op->exceptions.begin(); p != _op->exceptions.end(); ++p)
{
if(PyObject_IsInstance(ex, (*p)->pythonType.get()))
{
return true;
}
}
return false;
}
//
// BlobjectUpcall
//
IcePy::BlobjectUpcall::BlobjectUpcall(bool amd, const Ice::AMD_Array_Object_ice_invokePtr& callback) :
_amd(amd), _callback(callback)
{
}
void
IcePy::BlobjectUpcall::dispatch(PyObject* servant, const pair<const Ice::Byte*, const Ice::Byte*>& inBytes,
const Ice::Current& current)
{
Ice::CommunicatorPtr communicator = current.adapter->getCommunicator();
Py_ssize_t count = 2; // First is the inParams, second is the Ice::Current object.
Py_ssize_t start = 0;
if(_amd)
{
++count; // Leave room for a leading AMD callback argument.
start = 1;
}
PyObjectHandle args = PyTuple_New(count);
if(!args.get())
{
throwPythonException();
}
//
// If using AMD we need to copy the bytes since the bytes may be
// accessed after this method is over, otherwise
// PyBuffer_FromMemory can be used which doesn't do a copy.
//
PyObjectHandle ip;
if(!_amd)
{
ip = PyBuffer_FromMemory((void*)inBytes.first, inBytes.second - inBytes.first);
if(!ip.get())
{
throwPythonException();
}
}
else
{
ip = PyBuffer_New(inBytes.second - inBytes.first);
if(!ip.get())
{
throwPythonException();
}
void* buf;
Py_ssize_t sz;
if(PyObject_AsWriteBuffer(ip.get(), &buf, &sz))
{
throwPythonException();
}
assert(sz == inBytes.second - inBytes.first);
memcpy(buf, inBytes.first, sz);
}
if(PyTuple_SET_ITEM(args.get(), start, ip.get()) < 0)
{
throwPythonException();
}
++start;
ip.release(); // PyTuple_SET_ITEM steals a reference.
//
// Create an object to represent Ice::Current. We need to append
// this to the argument tuple.
//
PyObjectHandle curr = createCurrent(current);
if(PyTuple_SET_ITEM(args.get(), start, curr.get()) < 0)
{
throwPythonException();
}
curr.release(); // PyTuple_SET_ITEM steals a reference.
string dispatchName = "ice_invoke";
if(_amd)
{
dispatchName += "_async";
//
// Create the callback object and pass it as the first argument.
//
AMDCallbackObject* obj = amdCallbackNew(0);
if(!obj)
{
throwPythonException();
}
obj->upcall = new UpcallPtr(this);
if(PyTuple_SET_ITEM(args.get(), 0, (PyObject*)obj) < 0) // PyTuple_SET_ITEM steals a reference.
{
Py_DECREF(obj);
throwPythonException();
}
}
//
// Dispatch the operation.
//
PyObjectHandle method = PyObject_GetAttrString(servant, const_cast<char*>(dispatchName.c_str()));
if(!method.get())
{
ostringstream ostr;
ostr << "servant for identity " << communicator->identityToString(current.id)
<< " does not define operation `" << dispatchName << "'";
string str = ostr.str();
PyErr_Warn(PyExc_RuntimeWarning, const_cast<char*>(str.c_str()));
Ice::UnknownException ex(__FILE__, __LINE__);
ex.unknown = str;
throw ex;
}
PyObjectHandle result = PyObject_Call(method.get(), args.get(), 0);
//
// Check for exceptions.
//
if(PyErr_Occurred())
{
PyException ex; // Retrieve it before another Python API call clears it.
exception(ex);
return;
}
if(!_amd)
{
response(result.get());
}
}
void
IcePy::BlobjectUpcall::response(PyObject* args)
{
//
// The return value is a tuple of (bool, PyBuffer).
//
if(!PyTuple_Check(args) || PyTuple_GET_SIZE(args) != 2)
{
ostringstream ostr;
string name = "ice_invoke";
if(_amd)
{
name += "_async";
}
ostr << "operation `" << name << "' should return a tuple of length 2";
string str = ostr.str();
PyErr_Warn(PyExc_RuntimeWarning, const_cast<char*>(str.c_str()));
throw Ice::MarshalException(__FILE__, __LINE__);
}
PyObject* arg = PyTuple_GET_ITEM(args, 0);
int isTrue = PyObject_IsTrue(arg);
arg = PyTuple_GET_ITEM(args, 1);
if(!PyBuffer_Check(arg))
{
ostringstream ostr;
ostr << "invalid return value for operation `ice_invoke'";
string str = ostr.str();
PyErr_Warn(PyExc_RuntimeWarning, const_cast<char*>(str.c_str()));
throw Ice::MarshalException(__FILE__, __LINE__);
}
#if PY_VERSION_HEX < 0x02050000
const char* charBuf = 0;
#else
char* charBuf = 0;
#endif
Py_ssize_t sz = arg->ob_type->tp_as_buffer->bf_getcharbuffer(arg, 0, &charBuf);
const Ice::Byte* mem = reinterpret_cast<const Ice::Byte*>(charBuf);
const pair<const ::Ice::Byte*, const ::Ice::Byte*> bytes(mem, mem + sz);
AllowThreads allowThreads; // Release Python's global interpreter lock during blocking calls.
_callback->ice_response(isTrue, bytes);
}
void
IcePy::BlobjectUpcall::exception(PyException& ex)
{
try
{
//
// A servant that calls sys.exit() will raise the SystemExit exception.
// This is normally caught by the interpreter, causing it to exit.
// However, we have no way to pass this exception to the interpreter,
// so we act on it directly.
//
ex.checkSystemExit();
ex.raise();
}
catch(const Ice::Exception& ex)
{
AllowThreads allowThreads; // Release Python's global interpreter lock during blocking calls.
_callback->ice_exception(ex);
}
}
PyObject*
IcePy::iceIsA(const Ice::ObjectPrx& prx, PyObject* args)
{
PyObject* objectType = lookupType("Ice.Object");
assert(objectType);
PyObjectHandle obj = PyObject_GetAttrString(objectType, "_op_ice_isA");
assert(obj.get());
OperationPtr op = getOperation(obj.get());
assert(op);
InvocationPtr i = new SyncTypedInvocation(prx, op);
return i->invoke(args);
}
PyObject*
IcePy::icePing(const Ice::ObjectPrx& prx, PyObject* args)
{
PyObject* objectType = lookupType("Ice.Object");
assert(objectType);
PyObjectHandle obj = PyObject_GetAttrString(objectType, "_op_ice_ping");
assert(obj.get());
OperationPtr op = getOperation(obj.get());
assert(op);
InvocationPtr i = new SyncTypedInvocation(prx, op);
return i->invoke(args);
}
PyObject*
IcePy::iceIds(const Ice::ObjectPrx& prx, PyObject* args)
{
PyObject* objectType = lookupType("Ice.Object");
assert(objectType);
PyObjectHandle obj = PyObject_GetAttrString(objectType, "_op_ice_ids");
assert(obj.get());
OperationPtr op = getOperation(obj.get());
assert(op);
InvocationPtr i = new SyncTypedInvocation(prx, op);
return i->invoke(args);
}
PyObject*
IcePy::iceId(const Ice::ObjectPrx& prx, PyObject* args)
{
PyObject* objectType = lookupType("Ice.Object");
assert(objectType);
PyObjectHandle obj = PyObject_GetAttrString(objectType, "_op_ice_id");
assert(obj.get());
OperationPtr op = getOperation(obj.get());
assert(op);
InvocationPtr i = new SyncTypedInvocation(prx, op);
return i->invoke(args);
}
PyObject*
IcePy::iceInvoke(const Ice::ObjectPrx& prx, PyObject* args)
{
InvocationPtr i = new SyncBlobjectInvocation(prx);
return i->invoke(args);
}
PyObject*
IcePy::iceInvokeAsync(const Ice::ObjectPrx& prx, PyObject* args)
{
//
// If the callback implements an ice_sent method, we create a wrapper that derives
// from AMISentCallback.
//
assert(PyTuple_GET_SIZE(args) > 0);
PyObject* callback = PyTuple_GET_ITEM(args, 0);
if(PyObject_HasAttrString(callback, STRCAST("ice_sent")))
{
InvocationPtr i = new AsyncSentBlobjectInvocation(prx);
return i->invoke(args);
}
else
{
InvocationPtr i = new AsyncBlobjectInvocation(prx);
return i->invoke(args);
}
}
//
// ServantWrapper implementation.
//
IcePy::ServantWrapper::ServantWrapper(PyObject* servant) :
_servant(servant)
{
Py_INCREF(_servant);
}
IcePy::ServantWrapper::~ServantWrapper()
{
AdoptThread adoptThread; // Ensure the current thread is able to call into Python.
Py_DECREF(_servant);
}
PyObject*
IcePy::ServantWrapper::getObject()
{
Py_INCREF(_servant);
return _servant;
}
//
// TypedServantWrapper implementation.
//
IcePy::TypedServantWrapper::TypedServantWrapper(PyObject* servant) :
ServantWrapper(servant), _lastOp(_operationMap.end())
{
}
void
IcePy::TypedServantWrapper::ice_invoke_async(const Ice::AMD_Array_Object_ice_invokePtr& cb,
const pair<const Ice::Byte*, const Ice::Byte*>& inParams,
const Ice::Current& current)
{
AdoptThread adoptThread; // Ensure the current thread is able to call into Python.
try
{
//
// Locate the Operation object. As an optimization we keep a reference
// to the most recent operation we've dispatched, so check that first.
//
OperationPtr op;
if(_lastOp != _operationMap.end() && _lastOp->first == current.operation)
{
op = _lastOp->second;
}
else
{
//
// Next check our cache of operations.
//
_lastOp = _operationMap.find(current.operation);
if(_lastOp == _operationMap.end())
{
//
// Look for the Operation object in the servant's type.
//
string attrName = "_op_" + current.operation;
PyObjectHandle h = PyObject_GetAttrString((PyObject*)_servant->ob_type,
const_cast<char*>(attrName.c_str()));
if(!h.get())
{
PyErr_Clear();
Ice::OperationNotExistException ex(__FILE__, __LINE__);
ex.id = current.id;
ex.facet = current.facet;
ex.operation = current.operation;
throw ex;
}
assert(PyObject_IsInstance(h.get(), reinterpret_cast<PyObject*>(&OperationType)) == 1);
OperationObject* obj = reinterpret_cast<OperationObject*>(h.get());
op = *obj->op;
_lastOp = _operationMap.insert(OperationMap::value_type(current.operation, op)).first;
}
else
{
op = _lastOp->second;
}
}
__checkMode(op->mode, current.mode);
UpcallPtr up = new TypedUpcall(op, cb, current.adapter->getCommunicator());
up->dispatch(_servant, inParams, current);
}
catch(const Ice::Exception& ex)
{
AllowThreads allowThreads; // Release Python's global interpreter lock during blocking calls.
cb->ice_exception(ex);
}
}
//
// BlobjectServantWrapper implementation.
//
IcePy::BlobjectServantWrapper::BlobjectServantWrapper(PyObject* servant, bool amd) :
ServantWrapper(servant), _amd(amd)
{
}
void
IcePy::BlobjectServantWrapper::ice_invoke_async(const Ice::AMD_Array_Object_ice_invokePtr& cb,
const pair<const Ice::Byte*, const Ice::Byte*>& inParams,
const Ice::Current& current)
{
AdoptThread adoptThread; // Ensure the current thread is able to call into Python.
try
{
UpcallPtr up = new BlobjectUpcall(_amd, cb);
up->dispatch(_servant, inParams, current);
}
catch(const Ice::Exception& ex)
{
AllowThreads allowThreads; // Release Python's global interpreter lock during blocking calls.
cb->ice_exception(ex);
}
}
IcePy::ServantWrapperPtr
IcePy::createServantWrapper(PyObject* servant)
{
ServantWrapperPtr wrapper;
PyObject* blobjectType = lookupType("Ice.Blobject");
PyObject* blobjectAsyncType = lookupType("Ice.BlobjectAsync");
if(PyObject_IsInstance(servant, blobjectType))
{
return new BlobjectServantWrapper(servant, false);
}
else if(PyObject_IsInstance(servant, blobjectAsyncType))
{
return new BlobjectServantWrapper(servant, true);
}
return new TypedServantWrapper(servant);
}
|