/usr/lib/python2.7/dist-packages/ZSI/TC.py is in python-zsi 2.1~a1-4.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 | # $Header$
'''General typecodes.
'''
from ZSI import _copyright, _children, _child_elements, \
_floattypes, _stringtypes, _seqtypes, _find_attr, _find_attrNS, _find_attrNodeNS, \
_find_arraytype, _find_default_namespace, _find_href, _find_encstyle, \
_resolve_prefix, _find_xsi_attr, _find_type, \
_find_xmlns_prefix, _get_element_nsuri_name, _get_idstr, \
_Node, EvaluateException, UNICODE_ENCODING, \
_valid_encoding, ParseException
from ZSI.wstools.Namespaces import SCHEMA, SOAP
from ZSI.wstools.Utility import SplitQName
from ZSI.wstools.c14n import Canonicalize
from ZSI.wstools.logging import getLogger as _GetLogger
import re, types, time, copy
from base64 import decodestring as b64decode, encodestring as b64encode
from urllib import unquote as urldecode, quote as urlencode
from binascii import unhexlify as hexdecode, hexlify as hexencode
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
_is_xsd_or_soap_ns = lambda ns: ns in [
SCHEMA.XSD3, SOAP.ENC, SCHEMA.XSD1, SCHEMA.XSD2, ]
_find_nil = lambda E: _find_xsi_attr(E, "null") or _find_xsi_attr(E, "nil")
def _get_xsitype(pyclass):
'''returns the xsi:type as a tuple, coupled with ZSI.schema
'''
if hasattr(pyclass,'type') and type(pyclass.type) in _seqtypes:
return pyclass.type
elif hasattr(pyclass,'type') and hasattr(pyclass, 'schema'):
return (pyclass.schema, pyclass.type)
return (None,None)
# value returned when xsi:nil="true"
Nilled = None
UNBOUNDED = 'unbounded'
class TypeCode:
'''The parent class for all parseable SOAP types.
Class data:
typechecks -- do init-time type checking if non-zero
Class data subclasses may define:
tag -- global element declaration
type -- global type definition
parselist -- list of valid SOAP types for this class, as
(uri,name) tuples, where a uri of None means "all the XML
Schema namespaces"
errorlist -- parselist in a human-readable form; will be
generated if/when needed
seriallist -- list of Python types or user-defined classes
that this typecode can serialize.
logger -- logger instance for this class.
'''
tag = None
type = (None,None)
typechecks = True
attribute_typecode_dict = None
logger = _GetLogger('ZSI.TC.TypeCode')
def __init__(self, pname=None, aname=None, minOccurs=1,
maxOccurs=1, nillable=False, typed=True, unique=True,
pyclass=None, attrs_aname='_attrs', **kw):
'''Baseclass initialization.
Instance data (and usually keyword arg)
pname -- the parameter name (localname).
nspname -- the namespace for the parameter;
None to ignore the namespace
typed -- output xsi:type attribute
unique -- data item is not aliased (no href/id needed)
minOccurs -- min occurances
maxOccurs -- max occurances
nillable -- is item nillable?
attrs_aname -- This is variable name to dictionary of attributes
encoded -- encoded namespaceURI (specify if use is encoded)
'''
if type(pname) in _seqtypes:
self.nspname, self.pname = pname
else:
self.nspname, self.pname = None, pname
if self.pname:
self.pname = str(self.pname).split(':')[-1]
self.aname = aname or self.pname
self.minOccurs = minOccurs
self.maxOccurs = maxOccurs
self.nillable = nillable
self.typed = typed
self.unique = unique
self.attrs_aname = attrs_aname
self.pyclass = pyclass
# Need this stuff for rpc/encoded.
encoded = kw.get('encoded')
if encoded is not None:
self.nspname = kw['encoded']
def parse(self, elt, ps):
'''
Parameters:
elt -- the DOM element being parsed
ps -- the ParsedSoap object.
'''
raise EvaluateException("Unimplemented evaluation", ps.Backtrace(elt))
def serialize(self, elt, sw, pyobj, name=None, orig=None, **kw):
'''
Parameters:
elt -- the current DOMWrapper element
sw -- soapWriter object
pyobj -- python object to serialize
'''
raise EvaluateException("Unimplemented evaluation", sw.Backtrace(elt))
def text_to_data(self, text, elt, ps):
'''convert text into typecode specific data.
Parameters:
text -- text content
elt -- the DOM element being parsed
ps -- the ParsedSoap object.
'''
raise EvaluateException("Unimplemented evaluation", ps.Backtrace(elt))
def serialize_as_nil(self, elt):
'''
Parameters:
elt -- the current DOMWrapper element
'''
elt.setAttributeNS(SCHEMA.XSI3, 'nil', '1')
def SimpleHREF(self, elt, ps, tag):
'''Simple HREF for non-string and non-struct and non-array.
Parameters:
elt -- the DOM element being parsed
ps -- the ParsedSoap object.
tag --
'''
if len(_children(elt)): return elt
href = _find_href(elt)
if not href:
if self.minOccurs is 0: return None
raise EvaluateException('Required' + tag + ' missing',
ps.Backtrace(elt))
return ps.FindLocalHREF(href, elt, 0)
def get_parse_and_errorlist(self):
"""Get the parselist and human-readable version, errorlist is returned,
because it is used in error messages.
"""
d = self.__class__.__dict__
parselist = d.get('parselist')
errorlist = d.get('errorlist')
if parselist and not errorlist:
errorlist = []
for t in parselist:
if t[1] not in errorlist: errorlist.append(t[1])
errorlist = ' or '.join(errorlist)
d['errorlist'] = errorlist
return (parselist, errorlist)
def checkname(self, elt, ps):
'''See if the name and type of the "elt" element is what we're
looking for. Return the element's type.
Parameters:
elt -- the DOM element being parsed
ps -- the ParsedSoap object.
'''
parselist,errorlist = self.get_parse_and_errorlist()
ns, name = _get_element_nsuri_name(elt)
if ns == SOAP.ENC:
# Element is in SOAP namespace, so the name is a type.
if parselist and \
(None, name) not in parselist and (ns, name) not in parselist:
raise EvaluateException(
'Element mismatch (got %s wanted %s) (SOAP encoding namespace)' % \
(name, errorlist), ps.Backtrace(elt))
return (ns, name)
# Not a type, check name matches.
if self.nspname and ns != self.nspname:
raise EvaluateException('Element NS mismatch (got %s wanted %s)' % \
(ns, self.nspname), ps.Backtrace(elt))
if self.pname and name != self.pname:
raise EvaluateException('Element Name mismatch (got %s wanted %s)' % \
(name, self.pname), ps.Backtrace(elt))
return self.checktype(elt, ps)
def checktype(self, elt, ps):
'''See if the type of the "elt" element is what we're looking for.
Return the element's type.
Parameters:
elt -- the DOM element being parsed
ps -- the ParsedSoap object.
'''
typeName = _find_type(elt)
if typeName is None or typeName == "":
return (None,None)
# Parse the QNAME.
prefix,typeName = SplitQName(typeName)
uri = ps.GetElementNSdict(elt).get(prefix)
if uri is None:
raise EvaluateException('Malformed type attribute (bad NS)',
ps.Backtrace(elt))
#typeName = list[1]
parselist,errorlist = self.get_parse_and_errorlist()
if not parselist or \
(uri,typeName) in parselist or \
(_is_xsd_or_soap_ns(uri) and (None,typeName) in parselist):
return (uri,typeName)
raise EvaluateException(
'Type mismatch (%s namespace) (got %s wanted %s)' % \
(uri, typeName, errorlist), ps.Backtrace(elt))
def name_match(self, elt):
'''Simple boolean test to see if we match the element name.
Parameters:
elt -- the DOM element being parsed
'''
return self.pname == elt.localName and \
self.nspname in [None, '', elt.namespaceURI]
def nilled(self, elt, ps):
'''Is the element NIL, and is that okay?
Parameters:
elt -- the DOM element being parsed
ps -- the ParsedSoap object.
'''
if _find_nil(elt) not in [ "true", "1"]: return False
if self.nillable is False:
raise EvaluateException('Non-nillable element is NIL',
ps.Backtrace(elt))
return True
def simple_value(self, elt, ps, mixed=False):
'''Get the value of the simple content of this element.
Parameters:
elt -- the DOM element being parsed
ps -- the ParsedSoap object.
mixed -- ignore element content, optional text node
'''
if not _valid_encoding(elt):
raise EvaluateException('Invalid encoding', ps.Backtrace(elt))
c = _children(elt)
if mixed is False:
if len(c) == 0:
raise EvaluateException('Value missing', ps.Backtrace(elt))
for c_elt in c:
if c_elt.nodeType == _Node.ELEMENT_NODE:
raise EvaluateException('Sub-elements in value',
ps.Backtrace(c_elt))
# It *seems* to be consensus that ignoring comments and
# concatenating the text nodes is the right thing to do.
return ''.join([E.nodeValue for E in c
if E.nodeType
in [ _Node.TEXT_NODE, _Node.CDATA_SECTION_NODE ]])
def parse_attributes(self, elt, ps):
'''find all attributes specified in the attribute_typecode_dict in
current element tag, if an attribute is found set it in the
self.attributes dictionary. Default to putting in String.
Parameters:
elt -- the DOM element being parsed
ps -- the ParsedSoap object.
'''
if self.attribute_typecode_dict is None:
return
attributes = {}
for attr,what in self.attribute_typecode_dict.items():
namespaceURI,localName = None,attr
if type(attr) in _seqtypes:
namespaceURI,localName = attr
value = _find_attrNodeNS(elt, namespaceURI, localName)
self.logger.debug("Parsed Attribute (%s,%s) -- %s",
namespaceURI, localName, value)
# For Now just set it w/o any type interpretation.
if value is None: continue
attributes[attr] = what.text_to_data(value, elt, ps)
return attributes
def set_attributes(self, el, pyobj):
'''Instance data attributes contains a dictionary
of keys (namespaceURI,localName) and attribute values.
These values can be self-describing (typecode), or use
attribute_typecode_dict to determine serialization.
Paramters:
el -- MessageInterface representing the element
pyobj --
'''
if not hasattr(pyobj, self.attrs_aname):
return
if not isinstance(getattr(pyobj, self.attrs_aname), dict):
raise TypeError,\
'pyobj.%s must be a dictionary of names and values'\
% self.attrs_aname
for attr, value in getattr(pyobj, self.attrs_aname).items():
namespaceURI,localName = None, attr
if type(attr) in _seqtypes:
namespaceURI, localName = attr
what = None
if getattr(self, 'attribute_typecode_dict', None) is not None:
what = self.attribute_typecode_dict.get(attr)
if what is None and namespaceURI is None:
what = self.attribute_typecode_dict.get(localName)
# allow derived type
if hasattr(value, 'typecode') and not isinstance(what, AnyType):
if what is not None and not isinstance(value.typecode, what):
raise EvaluateException, \
'self-describing attribute must subclass %s'\
%what.__class__
what = value.typecode
self.logger.debug("attribute create -- %s", value)
if isinstance(what, QName):
what.set_prefix(el, value)
#format the data
if what is None:
value = str(value)
else:
value = what.get_formatted_content(value)
el.setAttributeNS(namespaceURI, localName, value)
def set_attribute_xsi_type(self, el, **kw):
'''if typed, set the xsi:type attribute
Paramters:
el -- MessageInterface representing the element
'''
if kw.get('typed', self.typed):
namespaceURI,typeName = kw.get('type', _get_xsitype(self))
if namespaceURI and typeName:
self.logger.debug("attribute: (%s, %s)", namespaceURI, typeName)
el.setAttributeType(namespaceURI, typeName)
def set_attribute_href(self, el, objid):
'''set href attribute
Paramters:
el -- MessageInterface representing the element
objid -- ID type, unique id
'''
el.setAttributeNS(None, 'href', "#%s" %objid)
def set_attribute_id(self, el, objid):
'''set id attribute
Paramters:
el -- MessageInterface representing the element
objid -- ID type, unique id
'''
if self.unique is False:
el.setAttributeNS(None, 'id', "%s" %objid)
def get_name(self, name, objid):
'''
Paramters:
name -- element tag
objid -- ID type, unique id
'''
if type(name) is tuple:
return name
ns = self.nspname
n = name or self.pname or ('E' + objid)
return ns,n
def has_attributes(self):
'''Return True if Attributes are declared outside
the scope of SOAP ('root', 'id', 'href'), and some
attributes automatically handled (xmlns, xsi:type).
'''
if self.attribute_typecode_dict is None: return False
return len(self.attribute_typecode_dict) > 0
class SimpleType(TypeCode):
'''SimpleType -- consist exclusively of a tag, attributes, and a value
class attributes:
empty_content -- value representing an empty element.
'''
empty_content = None
logger = _GetLogger('ZSI.TC.SimpleType')
def parse(self, elt, ps):
self.checkname(elt, ps)
if len(_children(elt)) == 0:
href = _find_href(elt)
if not href:
if self.nilled(elt, ps) is False:
# No content, no HREF, not NIL: empty string
return self.text_to_data(self.empty_content, elt, ps)
# No content, no HREF, and is NIL...
if self.nillable is True:
return Nilled
raise EvaluateException('Requiredstring missing',
ps.Backtrace(elt))
if href[0] != '#':
return ps.ResolveHREF(href, self)
elt = ps.FindLocalHREF(href, elt)
self.checktype(elt, ps)
if self.nilled(elt, ps): return Nilled
if len(_children(elt)) == 0:
v = self.empty_content
else:
v = self.simple_value(elt, ps)
else:
v = self.simple_value(elt, ps)
pyobj = self.text_to_data(v, elt, ps)
# parse all attributes contained in attribute_typecode_dict
# (user-defined attributes), the values (if not None) will
# be keyed in self.attributes dictionary.
if self.attribute_typecode_dict is not None:
attributes = self.parse_attributes(elt, ps)
if attributes:
setattr(pyobj, self.attrs_aname, attributes)
return pyobj
def get_formatted_content(self, pyobj):
raise NotImplementedError, 'method get_formatted_content is not implemented'
def serialize_text_node(self, elt, sw, pyobj):
'''Serialize without an element node.
'''
textNode = None
if pyobj is not None:
text = self.get_formatted_content(pyobj)
if type(text) not in _stringtypes:
raise TypeError, 'pyobj must be a formatted string'
textNode = elt.createAppendTextNode(text)
return textNode
def serialize(self, elt, sw, pyobj, name=None, orig=None, **kw):
'''Handles the start and end tags, and attributes. callout
to get_formatted_content to get the textNode value.
Parameters:
elt -- ElementProxy/DOM element
sw -- SoapWriter instance
pyobj -- processed content
KeyWord Parameters:
name -- substitute name, (nspname,name) or name
orig --
'''
objid = _get_idstr(pyobj)
ns,n = self.get_name(name, objid)
# nillable
el = elt.createAppendElement(ns, n)
if self.nillable is True and pyobj is Nilled:
self.serialize_as_nil(el)
return None
# other attributes
self.set_attributes(el, pyobj)
# soap href attribute
unique = self.unique or kw.get('unique', False)
if unique is False and sw.Known(orig or pyobj):
self.set_attribute_href(el, objid)
return None
# xsi:type attribute
if kw.get('typed', self.typed) is True:
self.set_attribute_xsi_type(el, **kw)
# soap id attribute
if self.unique is False:
self.set_attribute_id(el, objid)
#Content, <empty tag/>c
self.serialize_text_node(el, sw, pyobj)
return el
class Any(TypeCode):
'''When the type isn't defined in the schema, but must be specified
in the incoming operation.
parsemap -- a type to class mapping (updated by descendants), for
parsing
serialmap -- same, for (outgoing) serialization
'''
logger = _GetLogger('ZSI.TC.Any')
parsemap, serialmap = {}, {}
def __init__(self, pname=None, aslist=False, minOccurs=0, unique=False, **kw):
TypeCode.__init__(self, pname, minOccurs=minOccurs, unique=unique, **kw)
self.aslist = aslist
self.kwargs = dict(aslist=aslist, unique=unique)
self.kwargs.update(kw)
# input arg v should be a list of tuples (name, value).
def listify(self, v):
if self.aslist: return [ k for j,k in v ]
return dict(v)
def parse_into_dict_or_list(self, elt, ps):
c = _child_elements(elt)
count = len(c)
v = []
if count == 0:
href = _find_href(elt)
if not href: return v
elt = ps.FindLocalHREF(href, elt)
self.checktype(elt, ps)
c = _child_elements(elt)
count = len(c)
if count == 0: return self.listify(v)
if self.nilled(elt, ps): return Nilled
for c_elt in c:
v.append((str(c_elt.localName), self.__class__(**self.kwargs).parse(c_elt, ps)))
return self.listify(v)
def parse(self, elt, ps):
(ns,type) = self.checkname(elt, ps)
if not type and self.nilled(elt, ps): return Nilled
if len(_children(elt)) == 0:
href = _find_href(elt)
if not href:
if self.minOccurs < 1:
if _is_xsd_or_soap_ns(ns):
parser = Any.parsemap.get((None,type))
if parser: return parser.parse(elt, ps)
if ((ns,type) == (SOAP.ENC,'Array') or
(_find_arraytype(elt) or '').endswith('[0]')):
return []
return None
raise EvaluateException('Required Any missing',
ps.Backtrace(elt))
elt = ps.FindLocalHREF(href, elt)
(ns,type) = self.checktype(elt, ps)
if not type and elt.namespaceURI == SOAP.ENC:
ns,type = SOAP.ENC, elt.localName
if not type or (ns,type) == (SOAP.ENC,'Array'):
if self.aslist or _find_arraytype(elt):
return [ self.__class__(**self.kwargs).parse(e, ps)
for e in _child_elements(elt) ]
if len(_child_elements(elt)) == 0:
#raise EvaluateException("Any cannot parse untyped element",
# ps.Backtrace(elt))
return self.simple_value(elt, ps)
return self.parse_into_dict_or_list(elt, ps)
parser = Any.parsemap.get((ns,type))
if not parser and _is_xsd_or_soap_ns(ns):
parser = Any.parsemap.get((None,type))
if not parser:
raise EvaluateException('''Any can't parse element''',
ps.Backtrace(elt))
return parser.parse(elt, ps)
def get_formatted_content(self, pyobj):
tc = type(pyobj)
if tc == types.InstanceType:
tc = pyobj.__class__
if hasattr(pyobj, 'typecode'):
#serializer = pyobj.typecode.serialmap.get(tc)
serializer = pyobj.typecode
else:
serializer = Any.serialmap.get(tc)
if not serializer:
tc = (types.ClassType, pyobj.__class__.__name__)
serializer = Any.serialmap.get(tc)
else:
serializer = Any.serialmap.get(tc)
if not serializer and isinstance(pyobj, time.struct_time):
from ZSI.TCtimes import gDateTime
serializer = gDateTime()
if serializer:
return serializer.get_formatted_content(pyobj)
raise EvaluateException, 'Failed to find serializer for pyobj %s' %pyobj
def serialize(self, elt, sw, pyobj, name=None, **kw):
if hasattr(pyobj, 'typecode') and pyobj.typecode is not self:
pyobj.typecode.serialize(elt, sw, pyobj, **kw)
return
objid = _get_idstr(pyobj)
ns,n = self.get_name(name, objid)
kw.setdefault('typed', self.typed)
tc = type(pyobj)
self.logger.debug('Any serialize -- %s', tc)
if tc in _seqtypes:
if self.aslist:
array = elt.createAppendElement(ns, n)
array.setAttributeType(SOAP.ENC, "Array")
array.setAttributeNS(self.nspname, 'SOAP-ENC:arrayType',
"xsd:anyType[" + str(len(pyobj)) + "]" )
for o in pyobj:
#TODO maybe this should take **self.kwargs...
serializer = getattr(o, 'typecode', Any(**self.kwargs))
serializer.serialize(array, sw, o, name='element', **kw)
else:
struct = elt.createAppendElement(ns, n)
for o in pyobj:
#TODO maybe this should take **self.kwargs...
serializer = getattr(o, 'typecode', Any(**self.kwargs))
serializer.serialize(struct, sw, o, **kw)
return
kw['name'] = (ns,n)
if tc == types.DictType:
el = elt.createAppendElement(ns, n)
parentNspname = self.nspname # temporarily clear nspname for dict elements
self.nspname = None
for o,m in pyobj.items():
if type(o) != types.StringType and type(o) != types.UnicodeType:
raise Exception, 'Dictionary implementation requires keys to be of type string (or unicode).' %pyobj
kw['name'] = o
kw.setdefault('typed', True)
self.serialize(el, sw, m, **kw)
# restore nspname
self.nspname = parentNspname
return
if tc == types.InstanceType:
tc = pyobj.__class__
if hasattr(pyobj, 'typecode'):
#serializer = pyobj.typecode.serialmap.get(tc)
serializer = pyobj.typecode
else:
serializer = Any.serialmap.get(tc)
if not serializer:
tc = (types.ClassType, pyobj.__class__.__name__)
serializer = Any.serialmap.get(tc)
else:
serializer = Any.serialmap.get(tc)
if not serializer and isinstance(pyobj, time.struct_time):
from ZSI.TCtimes import gDateTime
serializer = gDateTime()
if not serializer:
# Last-chance; serialize instances as dictionary
if pyobj is None:
self.serialize_as_nil(elt.createAppendElement(ns, n))
elif type(pyobj) != types.InstanceType:
raise EvaluateException('''Any can't serialize ''' + \
repr(pyobj))
else:
self.serialize(elt, sw, pyobj.__dict__, **kw)
else:
# Try to make the element name self-describing
tag = getattr(serializer, 'tag', None)
if self.pname is not None:
#serializer.nspname = self.nspname
#serializer.pname = self.pname
if "typed" not in kw:
kw['typed'] = False
elif tag:
if tag.find(':') == -1: tag = 'SOAP-ENC:' + tag
kw['name'] = tag
kw['typed'] = False
serializer.unique = self.unique
serializer.serialize(elt, sw, pyobj, **kw)
# Reset TypeCode
#serializer.nspname = None
#serializer.pname = None
class String(SimpleType):
'''A string type.
'''
empty_content = ''
parselist = [ (None,'string') ]
seriallist = [ types.StringType, types.UnicodeType ]
type = (SCHEMA.XSD3, 'string')
logger = _GetLogger('ZSI.TC.String')
def __init__(self, pname=None, strip=True, **kw):
TypeCode.__init__(self, pname, **kw)
if kw.has_key('resolver'): self.resolver = kw['resolver']
self.strip = strip
def text_to_data(self, text, elt, ps):
'''convert text into typecode specific data.
Encode all strings as UTF-8, which will be type 'str'
not 'unicode'
'''
if self.strip: text = text.strip()
if self.pyclass is not None:
return self.pyclass(text.encode(UNICODE_ENCODING))
return text.encode(UNICODE_ENCODING)
def get_formatted_content(self, pyobj):
if type(pyobj) not in _stringtypes:
pyobj = str(pyobj)
if type(pyobj) == unicode:
return pyobj.encode(UNICODE_ENCODING)
return pyobj
class URI(String):
'''A URI.
Class data:
reserved -- urllib.quote will escape all reserved characters
regardless of whether they are used for the reserved purpose.
'''
parselist = [ (None,'anyURI'),(SCHEMA.XSD3, 'anyURI')]
type = (SCHEMA.XSD3, 'anyURI')
logger = _GetLogger('ZSI.TC.URI')
reserved = ";/?:@&=+$,"
def text_to_data(self, text, elt, ps):
'''text --> typecode specific data.
'''
return String.text_to_data(self, urldecode(text), elt, ps)
def get_formatted_content(self, pyobj):
'''typecode data --> text
'''
u = urlencode(pyobj, self.reserved)
return String.get_formatted_content(self,
u)
class QName(String):
'''A QName type
'''
parselist = [ (None,'QName') ]
type = (SCHEMA.XSD3, 'QName')
logger = _GetLogger('ZSI.TC.QName')
def __init__(self, pname=None, strip=1, **kw):
String.__init__(self, pname, strip, **kw)
self.prefix = None
def get_formatted_content(self, pyobj):
value = pyobj
if isinstance(pyobj, tuple):
namespaceURI,localName = pyobj
if self.prefix is not None:
value = "%s:%s" %(self.prefix,localName)
return String.get_formatted_content(self, value)
def set_prefix(self, elt, pyobj):
'''use this method to set the prefix of the QName,
method looks in DOM to find prefix or set new prefix.
This method must be called before get_formatted_content.
'''
if isinstance(pyobj, tuple):
namespaceURI,localName = pyobj
self.prefix = elt.getPrefix(namespaceURI)
def text_to_data(self, text, elt, ps):
'''convert text into typecode specific data.
'''
prefix,localName = SplitQName(text)
nsdict = ps.GetElementNSdict(elt)
prefix = prefix or ''
try:
namespaceURI = nsdict[prefix]
except KeyError, ex:
raise EvaluateException('cannot resolve prefix(%s)'%prefix,
ps.Backtrace(elt))
v = (namespaceURI,localName)
if self.pyclass is not None:
return self.pyclass(v)
return v
def serialize_text_node(self, elt, sw, pyobj):
'''Serialize without an element node.
'''
self.set_prefix(elt, pyobj)
return String.serialize_text_node(self, elt, sw, pyobj)
class Token(String):
'''an xsd:token type
'''
parselist = [ (None, 'token') ]
type = (SCHEMA.XSD3, 'token')
logger = _GetLogger('ZSI.TC.Token')
class Base64String(String):
'''A Base64 encoded string.
'''
parselist = [ (None,'base64Binary'), (SOAP.ENC, 'base64') ]
type = (SOAP.ENC, 'base64')
logger = _GetLogger('ZSI.TC.Base64String')
def text_to_data(self, text, elt, ps):
'''convert text into typecode specific data.
'''
val = b64decode(text.replace(' ', '').replace('\n','').replace('\r',''))
if self.pyclass is not None:
return self.pyclass(val)
return val
def get_formatted_content(self, pyobj):
pyobj = '\n' + b64encode(pyobj)
return String.get_formatted_content(self, pyobj)
class Base64Binary(String):
parselist = [ (None,'base64Binary'), ]
type = (SCHEMA.XSD3, 'base64Binary')
logger = _GetLogger('ZSI.TC.Base64Binary')
def text_to_data(self, text, elt, ps):
'''convert text into typecode specific data.
'''
val = b64decode(text)
if self.pyclass is not None:
return self.pyclass(val)
return val
def get_formatted_content(self, pyobj):
pyobj = b64encode(pyobj).strip()
return pyobj
class HexBinaryString(String):
'''Hex-encoded binary (yuk).
'''
parselist = [ (None,'hexBinary') ]
type = (SCHEMA.XSD3, 'hexBinary')
logger = _GetLogger('ZSI.TC.HexBinaryString')
def text_to_data(self, text, elt, ps):
'''convert text into typecode specific data.
'''
val = hexdecode(text)
if self.pyclass is not None:
return self.pyclass(val)
return val
def get_formatted_content(self, pyobj):
pyobj = hexencode(pyobj).upper()
return String.get_formatted_content(self, pyobj)
class XMLString(String):
'''A string that represents an XML document
'''
logger = _GetLogger('ZSI.TC.XMLString')
def __init__(self, pname=None, readerclass=None, **kw):
String.__init__(self, pname, **kw)
self.readerclass = readerclass
def parse(self, elt, ps):
if not self.readerclass:
from xml.dom.ext.reader import PyExpat
self.readerclass = PyExpat.Reader
v = String.parse(self, elt, ps)
return self.readerclass().fromString(v)
def get_formatted_content(self, pyobj):
#pyobj = Canonicalize(pyobj)
return String.get_formatted_content(self, pyobj)
class Enumeration(String):
'''A string type, limited to a set of choices.
'''
logger = _GetLogger('ZSI.TC.Enumeration')
def __init__(self, choices, pname=None, **kw):
String.__init__(self, pname, **kw)
t = type(choices)
if t in _seqtypes:
self.choices = tuple(choices)
elif TypeCode.typechecks:
raise TypeError(
'Enumeration choices must be list or sequence, not ' + str(t))
if TypeCode.typechecks:
for c in self.choices:
if type(c) not in _stringtypes:
raise TypeError(
'Enumeration choice ' + str(c) + ' is not a string')
def parse(self, elt, ps):
val = String.parse(self, elt, ps)
if val not in self.choices:
raise EvaluateException('Value not in enumeration list',
ps.Backtrace(elt))
return val
def serialize(self, elt, sw, pyobj, name=None, orig=None, **kw):
if pyobj not in self.choices:
raise EvaluateException('Value not in enumeration list',
sw.Backtrace(elt))
String.serialize(self, elt, sw, pyobj, name=name, orig=orig, **kw)
# This is outside the Integer class purely for code esthetics.
_ignored = []
class Integer(SimpleType):
'''Common handling for all integers.
'''
ranges = {
'unsignedByte': (0, 255),
'unsignedShort': (0, 65535),
'unsignedInt': (0, 4294967295L),
'unsignedLong': (0, 18446744073709551615L),
'byte': (-128, 127),
'short': (-32768, 32767),
'int': (-2147483648L, 2147483647),
'long': (-9223372036854775808L, 9223372036854775807L),
'negativeInteger': (_ignored, -1),
'nonPositiveInteger': (_ignored, 0),
'nonNegativeInteger': (0, _ignored),
'positiveInteger': (1, _ignored),
'integer': (_ignored, _ignored)
}
parselist = [ (None,k) for k in ranges.keys() ]
seriallist = [ types.IntType, types.LongType ]
logger = _GetLogger('ZSI.TC.Integer')
def __init__(self, pname=None, format='%d', **kw):
TypeCode.__init__(self, pname, **kw)
self.format = format
def text_to_data(self, text, elt, ps):
'''convert text into typecode specific data.
'''
if self.pyclass is not None:
v = self.pyclass(text)
else:
try:
v = int(text)
except:
try:
v = long(text)
except:
raise EvaluateException('Unparseable integer',
ps.Backtrace(elt))
return v
def parse(self, elt, ps):
(ns,type) = self.checkname(elt, ps)
if self.nilled(elt, ps): return Nilled
elt = self.SimpleHREF(elt, ps, 'integer')
if not elt: return None
if type is None:
type = self.type[1]
elif self.type[1] is not None and type != self.type[1]:
raise EvaluateException('Integer type mismatch; ' \
'got %s wanted %s' % (type,self.type[1]), ps.Backtrace(elt))
v = self.simple_value(elt, ps)
v = self.text_to_data(v, elt, ps)
(rmin, rmax) = Integer.ranges.get(type, (_ignored, _ignored))
if rmin != _ignored and v < rmin:
raise EvaluateException('Underflow, less than ' + repr(rmin),
ps.Backtrace(elt))
if rmax != _ignored and v > rmax:
raise EvaluateException('Overflow, greater than ' + repr(rmax),
ps.Backtrace(elt))
return v
def get_formatted_content(self, pyobj):
return self.format %pyobj
# See credits, below.
def _make_inf():
x = 2.0
x2 = x * x
i = 0
while i < 100 and x != x2:
x = x2
x2 = x * x
i = i + 1
if x != x2:
raise ValueError("This machine's floats go on forever!")
return x
# This is outside the Decimal class purely for code esthetics.
_magicnums = { }
try:
_magicnums['INF'] = float('INF')
_magicnums['-INF'] = float('-INF')
except:
_magicnums['INF'] = _make_inf()
_magicnums['-INF'] = -_magicnums['INF']
# The following comment and code was written by Tim Peters in
# article <001401be92d2$09dcb800$5fa02299@tim> in comp.lang.python,
# also available at the following URL:
# http://groups.google.com/groups?selm=001401be92d2%2409dcb800%245fa02299%40tim
# Thanks, Tim!
# NaN-testing.
#
# The usual method (x != x) doesn't work.
# Python forces all comparisons thru a 3-outcome cmp protocol; unordered
# isn't a possible outcome. The float cmp outcome is essentially defined
# by this C expression (combining some cross-module implementation
# details, and where px and py are pointers to C double):
# px == py ? 0 : *px < *py ? -1 : *px > *py ? 1 : 0
# Comparing x to itself thus always yields 0 by the first clause, and so
# x != x is never true.
# If px and py point to distinct NaN objects, a strange thing happens:
# 1. On scrupulous 754 implementations, *px < *py returns false, and so
# does *px > *py. Python therefore returns 0, i.e. "equal"!
# 2. On Pentium HW, an unordered outcome sets an otherwise-impossible
# combination of condition codes, including both the "less than" and
# "equal to" flags. Microsoft C generates naive code that accepts
# the "less than" flag at face value, and so the *px < *py clause
# returns true, and Python returns -1, i.e. "not equal".
# So with a proper C 754 implementation Python returns the wrong result,
# and under MS's improper 754 implementation Python yields the right
# result -- both by accident. It's unclear who should be shot <wink>.
#
# Anyway, the point of all that was to convince you it's tricky getting
# the right answer in a portable way!
def isnan(x):
"""x -> true iff x is a NaN."""
# multiply by 1.0 to create a distinct object (x < x *always*
# false in Python, due to object identity forcing equality)
if x * 1.0 < x:
# it's a NaN and this is MS C on a Pentium
return 1
# Else it's non-NaN, or NaN on a non-MS+Pentium combo.
# If it's non-NaN, then x == 1.0 and x == 2.0 can't both be true,
# so we return false. If it is NaN, then assuming a good 754 C
# implementation Python maps both unordered outcomes to true.
return 1.0 == x and x == 2.0
class Decimal(SimpleType):
'''Parent class for floating-point numbers.
'''
parselist = [ (None,'decimal'), (None,'float'), (None,'double') ]
seriallist = _floattypes
type = None
ranges = {
'float': ( 7.0064923216240861E-46,
-3.4028234663852886E+38, 3.4028234663852886E+38 ),
'double': ( 2.4703282292062327E-324,
-1.7976931348623158E+308, 1.7976931348623157E+308),
}
zeropat = re.compile('[1-9]')
logger = _GetLogger('ZSI.TC.Decimal')
def __init__(self, pname=None, format='%f', **kw):
TypeCode.__init__(self, pname, **kw)
self.format = format
def text_to_data(self, text, elt, ps):
'''convert text into typecode specific data.
'''
v = text
if self.pyclass is not None:
return self.pyclass(v)
m = _magicnums.get(v)
if m: return m
try:
return float(v)
except:
raise EvaluateException('Unparseable floating point number',
ps.Backtrace(elt))
def parse(self, elt, ps):
(ns,type) = self.checkname(elt, ps)
elt = self.SimpleHREF(elt, ps, 'floating-point')
if not elt: return None
tag = getattr(self.__class__, 'type')
if tag:
if type is None:
type = tag
elif tag != (ns,type):
raise EvaluateException('Floating point type mismatch; ' \
'got (%s,%s) wanted %s' % (ns,type,tag), ps.Backtrace(elt))
# Special value?
if self.nilled(elt, ps): return Nilled
v = self.simple_value(elt, ps)
try:
fp = self.text_to_data(v, elt, ps)
except EvaluateException, ex:
ex.args.append(ps.Backtrace(elt))
raise ex
m = _magicnums.get(v)
if m:
return m
if str(fp).lower() in [ 'inf', '-inf', 'nan', '-nan' ]:
raise EvaluateException('Floating point number parsed as "' + \
str(fp) + '"', ps.Backtrace(elt))
if fp == 0 and Decimal.zeropat.search(v):
raise EvaluateException('Floating point number parsed as zero',
ps.Backtrace(elt))
(rtiny, rneg, rpos) = Decimal.ranges.get(type, (None, None, None))
if rneg and fp < 0 and fp < rneg:
raise EvaluateException('Negative underflow', ps.Backtrace(elt))
if rtiny and fp > 0 and fp < rtiny:
raise EvaluateException('Positive underflow', ps.Backtrace(elt))
if rpos and fp > 0 and fp > rpos:
raise EvaluateException('Overflow', ps.Backtrace(elt))
return fp
def get_formatted_content(self, pyobj):
if pyobj == _magicnums['INF']:
return 'INF'
elif pyobj == _magicnums['-INF']:
return '-INF'
elif isnan(pyobj):
return 'NaN'
else:
return self.format %pyobj
class Boolean(SimpleType):
'''A boolean.
'''
parselist = [ (None,'boolean') ]
seriallist = [ bool ]
type = (SCHEMA.XSD3, 'boolean')
logger = _GetLogger('ZSI.TC.Boolean')
def text_to_data(self, text, elt, ps):
'''convert text into typecode specific data.
'''
v = text
if v == 'false':
if self.pyclass is None:
return False
return self.pyclass(False)
if v == 'true':
if self.pyclass is None:
return True
return self.pyclass(True)
try:
v = int(v)
except:
try:
v = long(v)
except:
raise EvaluateException('Unparseable boolean',
ps.Backtrace(elt))
if v:
if self.pyclass is None:
return True
return self.pyclass(True)
if self.pyclass is None:
return False
return self.pyclass(False)
def parse(self, elt, ps):
self.checkname(elt, ps)
elt = self.SimpleHREF(elt, ps, 'boolean')
if not elt: return None
if self.nilled(elt, ps): return Nilled
v = self.simple_value(elt, ps).lower()
return self.text_to_data(v, elt, ps)
def get_formatted_content(self, pyobj):
if pyobj: return 'true'
return 'false'
#XXX NOT FIXED YET
class XML(TypeCode):
'''Opaque XML which shouldn't be parsed.
comments -- preserve comments
inline -- don't href/id when serializing
resolver -- object to resolve href's
wrapped -- put a wrapper element around it
'''
# Clone returned data?
copyit = 0
logger = _GetLogger('ZSI.TC.XML')
def __init__(self, pname=None, comments=0, inline=0, wrapped=True, **kw):
TypeCode.__init__(self, pname, **kw)
self.comments = comments
self.inline = inline
if kw.has_key('resolver'): self.resolver = kw['resolver']
self.wrapped = wrapped
self.copyit = kw.get('copyit', XML.copyit)
def parse(self, elt, ps):
if self.wrapped is False:
return elt
c = _child_elements(elt)
if not c:
href = _find_href(elt)
if not href:
if self.minOccurs == 0: return None
raise EvaluateException('Embedded XML document missing',
ps.Backtrace(elt))
if href[0] != '#':
return ps.ResolveHREF(href, self)
elt = ps.FindLocalHREF(href, elt)
c = _child_elements(elt)
if _find_encstyle(elt) != "":
#raise EvaluateException('Embedded XML has unknown encodingStyle',
# ps.Backtrace(elt)
pass
if len(c) != 1:
raise EvaluateException('Embedded XML has more than one child',
ps.Backtrace(elt))
if self.copyit: return c[0].cloneNode(1)
return c[0]
def serialize(self, elt, sw, pyobj, name=None, unsuppressedPrefixes=[], **kw):
objid = _get_idstr(pyobj)
ns,n = self.get_name(name, objid)
xmlelt = elt
if self.wrapped:
xmlelt = elt.createAppendElement(ns, n)
#if type(pyobj) in _stringtypes:
# self.set_attributes(xmlelt, pyobj)
# self.set_attribute_href(xmlelt, objid)
#elif kw.get('inline', self.inline):
# self.cb(xmlelt, sw, pyobj, unsuppressedPrefixes)
#else:
# self.set_attributes(xmlelt, pyobj)
# self.set_attribute_href(xmlelt, objid)
# sw.AddCallback(self.cb, elt, sw, pyobj, unsuppressedPrefixes)
self.cb(xmlelt, sw, pyobj, unsuppressedPrefixes)
def cb(self, elt, sw, pyobj, unsuppressedPrefixes=[]):
"""pyobj -- xml.dom.Node.ELEMENT_NODE
"""
#if sw.Known(pyobj):
# return
if type(pyobj) in _stringtypes:
elt.createAppendTextNode(pyobj)
return
## grab document and import node, and append it
doc = elt.getDocument()
node = doc.importNode(pyobj, deep=1)
child = elt.node.appendChild(node)
## copy xmlns: attributes into appended node
parent = pyobj.parentNode
while parent.nodeType == _Node.ELEMENT_NODE:
for attr in filter(lambda a: a.name.startswith('xmlns:') and a.name not in child.attributes.keys(), parent.attributes):
child.setAttributeNode(attr.cloneNode(1))
parent = parent.parentNode
class AnyType(TypeCode):
"""XML Schema xsi:anyType type definition wildCard.
class variables:
all -- specifies use of all namespaces.
other -- specifies use of other namespaces
type --
"""
all = '#all'
other = '#other'
type = (SCHEMA.XSD3, 'anyType')
logger = _GetLogger('ZSI.TC.AnyType')
def __init__(self, pname=None, namespaces=['#all'],
minOccurs=1, maxOccurs=1, strip=1, **kw):
TypeCode.__init__(self, pname=pname, minOccurs=minOccurs,
maxOccurs=maxOccurs, **kw)
self.namespaces = namespaces
def get_formatted_content(self, pyobj):
# TODO: not sure this makes sense,
# parse side will be clueless, but oh well..
what = getattr(pyobj, 'typecode', Any())
return what.get_formatted_content(pyobj)
def text_to_data(self, text, elt, ps):
'''convert text into typecode specific data. Used only with
attributes so will not know anything about this content so
why guess?
Parameters:
text -- text content
elt -- the DOM element being parsed
ps -- the ParsedSoap object.
'''
return text
def serialize(self, elt, sw, pyobj, **kw):
nsuri,typeName = _get_xsitype(pyobj)
if self.all not in self.namespaces and nsuri not in self.namespaces:
raise EvaluateException(
'<anyType> unsupported use of namespaces "%s"' %self.namespaces)
what = getattr(pyobj, 'typecode', None)
if what is None:
# TODO: resolve this, "strict" processing but no
# concrete schema makes little sense.
#what = _AnyStrict(pname=(self.nspname,self.pname))
what = Any(pname=(self.nspname,self.pname), unique=True,
aslist=False)
kw['typed'] = True
what.serialize(elt, sw, pyobj, **kw)
return
# Namespace if element AnyType was namespaced.
what.serialize(elt, sw, pyobj,
name=(self.nspname or what.nspname, self.pname or what.pname), **kw)
def parse(self, elt, ps):
#element name must be declared ..
nspname,pname = _get_element_nsuri_name(elt)
if nspname != self.nspname or pname != self.pname:
raise EvaluateException('<anyType> instance is (%s,%s) found (%s,%s)' %(
self.nspname,self.pname,nspname,pname), ps.Backtrace(elt))
#locate xsi:type
prefix, typeName = SplitQName(_find_type(elt))
namespaceURI = _resolve_prefix(elt, prefix)
pyclass = GTD(namespaceURI, typeName)
if not pyclass:
if _is_xsd_or_soap_ns(namespaceURI):
pyclass = Any
elif (str(namespaceURI).lower()==str(Apache.Map.type[0]).lower())\
and (str(typeName).lower() ==str(Apache.Map.type[1]).lower()):
pyclass = Apache.Map
else:
# Unknown type, so parse into a dictionary
pyobj = Any().parse_into_dict_or_list(elt, ps)
return pyobj
what = pyclass(pname=(self.nspname,self.pname))
pyobj = what.parse(elt, ps)
return pyobj
class AnyElement(AnyType):
"""XML Schema xsi:any element declaration wildCard.
class variables:
tag -- global element declaration
"""
tag = (SCHEMA.XSD3, 'any')
logger = _GetLogger('ZSI.TC.AnyElement')
def __init__(self, namespaces=['#all'],pname=None,
minOccurs=1, maxOccurs=1, strip=1, processContents='strict',
**kw):
if processContents not in ('lax', 'skip', 'strict'):
raise ValueError('processContents(%s) must be lax, skip, or strict')
self.processContents = processContents
AnyType.__init__(self, namespaces=namespaces,pname=pname,
minOccurs=minOccurs, maxOccurs=maxOccurs, strip=strip, **kw)
def serialize(self, elt, sw, pyobj, **kw):
'''Must provice typecode to AnyElement for serialization, else
try to use TC.Any to serialize instance which will serialize
based on the data type of pyobj w/o reference to XML schema
instance.
'''
if isinstance(pyobj, TypeCode):
raise TypeError, 'pyobj is a typecode instance.'
what = getattr(pyobj, 'typecode', None)
if what is not None and type(pyobj) is types.InstanceType:
tc = pyobj.__class__
what = Any.serialmap.get(tc)
if not what:
tc = (types.ClassType, pyobj.__class__.__name__)
what = Any.serialmap.get(tc)
self.logger.debug('processContents: %s', self.processContents)
# failed to find a registered type for class
if what is None:
#TODO: seems incomplete. what about facets.
#if self.processContents == 'strict':
what = Any(pname=(self.nspname,self.pname))
self.logger.debug('serialize with %s', what.__class__.__name__)
what.serialize(elt, sw, pyobj, **kw)
def parse(self, elt, ps):
'''
processContents -- 'lax' | 'skip' | 'strict', 'strict'
1) if 'skip' check namespaces, and return the DOM node.
2) if 'lax' look for declaration, or definition. If
not found return DOM node.
3) if 'strict' get declaration, or raise.
'''
skip = self.processContents == 'skip'
nspname,pname = _get_element_nsuri_name(elt)
what = GED(nspname, pname)
if not skip and what is not None:
pyobj = what.parse(elt, ps)
try:
pyobj.typecode = what
except AttributeError, ex:
# Assume this means builtin type.
pyobj = WrapImmutable(pyobj, what)
return pyobj
# Allow use of "<any>" element declarations w/ local
# element declarations
prefix, typeName = SplitQName(_find_type(elt))
if not skip and typeName:
namespaceURI = _resolve_prefix(elt, prefix or 'xmlns')
# First look thru user defined namespaces, if don't find
# look for 'primitives'.
pyclass = GTD(namespaceURI, typeName) or Any
what = pyclass(pname=(nspname,pname))
pyobj = what.parse(elt, ps)
try:
pyobj.typecode = what
except AttributeError, ex:
# Assume this means builtin type.
pyobj = WrapImmutable(pyobj, what)
what.typed = True
return pyobj
if skip:
what = XML(pname=(nspname,pname), wrapped=False)
elif self.processContents == 'lax':
what = Any(pname=(nspname,pname), unique=True)
else:
what = Any(pname=(nspname,pname), unique=True)
try:
pyobj = what.parse(elt, ps)
except EvaluateException, ex:
self.logger.debug("error parsing: %s" %str(ex))
if len(_children(elt)) != 0:
self.logger.debug('parse <any>, return as dict')
return Any(aslist=False).parse_into_dict_or_list(elt, ps)
self.logger.debug("Give up, parse (%s,%s) as a String",
what.nspname, what.pname)
what = String(pname=(nspname,pname), typed=False)
return WrapImmutable(what.parse(elt, ps), what)
if pyobj is None:
return
# dict is elementName:value pairs
if type(pyobj) is dict:
return pyobj
try:
pyobj.typecode = what
except AttributeError:
pyobj = WrapImmutable(pyobj, what)
return pyobj
class Union(SimpleType):
'''simpleType Union
class variables:
memberTypes -- list [(namespace,name),] tuples, each representing a type defintion.
'''
memberTypes = None
logger = _GetLogger('ZSI.TC.Union')
def __init__(self, pname=None, minOccurs=1, maxOccurs=1, **kw):
SimpleType.__init__(self, pname=pname, minOccurs=minOccurs, maxOccurs=maxOccurs, **kw)
self.memberTypeCodes = []
def setMemberTypeCodes(self):
if len(self.memberTypeCodes) > 0:
return
if self.__class__.memberTypes is None:
raise EvaluateException, 'uninitialized class variable memberTypes [(namespace,name),]'
for nsuri,name in self.__class__.memberTypes:
tcclass = GTD(nsuri,name)
if tcclass is None:
tc = Any.parsemap.get((nsuri,name)) or Any.parsemap.get((None, name))
typecode = tc.__class__(pname=(self.nspname,self.pname))
else:
typecode = tcclass(pname=(self.nspname,self.pname))
if typecode is None:
raise EvaluateException, \
'Typecode class for Union memberType (%s,%s) is missing' %(nsuri,name)
if isinstance(typecode, Struct):
raise EvaluateException, \
'Illegal: Union memberType (%s,%s) is complexType' %(nsuri,name)
self.memberTypeCodes.append(typecode)
def parse(self, elt, ps, **kw):
'''attempt to parse sequentially. No way to know ahead of time
what this instance represents. Must be simple type so it can
not have attributes nor children, so this isn't too bad.
'''
self.setMemberTypeCodes()
(nsuri,typeName) = self.checkname(elt, ps)
#if (nsuri,typeName) not in self.memberTypes:
# raise EvaluateException(
# 'Union Type mismatch got (%s,%s) not in %s' % \
# (nsuri, typeName, self.memberTypes), ps.Backtrace(elt))
for indx in range(len(self.memberTypeCodes)):
typecode = self.memberTypeCodes[indx]
try:
pyobj = typecode.parse(elt, ps)
except ParseException, ex:
continue
except Exception, ex:
continue
if indx > 0:
self.memberTypeCodes.remove(typecode)
self.memberTypeCodes.insert(0, typecode)
break
else:
raise
return pyobj
def get_formatted_content(self, pyobj, **kw):
self.setMemberTypeCodes()
for indx in range(len(self.memberTypeCodes)):
typecode = self.memberTypeCodes[indx]
try:
content = typecode.get_formatted_content(copy.copy(pyobj))
break
except (ParseException, TypeError):
pass
if indx > 0:
self.memberTypeCodes.remove(typecode)
self.memberTypeCodes.insert(0, typecode)
else:
raise
return content
class List(SimpleType):
'''simpleType List
Class data:
itemType -- sequence (namespaceURI,name) or a TypeCode instance
representing the type definition
'''
itemType = None
logger = _GetLogger('ZSI.TC.List')
def __init__(self, pname=None, itemType=None, **kw):
'''Currently need to require maxOccurs=1, so list
is interpreted as a single unit of data.
'''
assert kw.get('maxOccurs',1) == 1, \
'Currently only supporting SimpleType Lists with maxOccurs=1'
SimpleType.__init__(self, pname=pname, **kw)
self.itemType = itemType or self.itemType
self.itemTypeCode = self.itemType
itemTypeCode = None
if type(self.itemTypeCode) in _seqtypes:
namespaceURI,name = self.itemTypeCode
try:
itemTypeCode = GTD(*self.itemType)(None)
except:
if _is_xsd_or_soap_ns(namespaceURI) is False:
raise
for pyclass in TYPES:
if pyclass.type == self.itemTypeCode:
itemTypeCode = pyclass(None)
break
elif pyclass.type[1] == name:
itemTypeCode = pyclass(None)
if itemTypeCode is None:
raise EvaluateException('Failed to locate %s' %str(self.itemTypeCode))
if hasattr(itemTypeCode, 'text_to_data') is False:
raise EvaluateException('TypeCode class %s missing text_to_data method' %itemTypeCode)
self.itemTypeCode = itemTypeCode
def text_to_data(self, text, elt, ps):
'''convert text into typecode specific data. items in
list are space separated.
'''
v = []
items = text.split()
for item in items:
v.append(self.itemTypeCode.text_to_data(item, elt, ps))
if self.pyclass is not None:
return self.pyclass(v)
return v
def parse(self, elt, ps):
'''elt -- the DOM element being parsed
ps -- the ParsedSoap object.
'''
self.checkname(elt, ps)
if len(_children(elt)) == 0:
href = _find_href(elt)
if not href:
if self.nilled(elt, ps) is False:
return []
if self.nillable is True:
return Nilled
raise EvaluateException('Required string missing',
ps.Backtrace(elt))
if href[0] != '#':
return ps.ResolveHREF(href, self)
elt = ps.FindLocalHREF(href, elt)
self.checktype(elt, ps)
if self.nilled(elt, ps): return Nilled
if len(_children(elt)) == 0: return []
v = self.simple_value(elt, ps)
return self.text_to_data(v, elt, ps)
def serialize(self, elt, sw, pyobj, name=None, orig=None, **kw):
'''elt -- the current DOMWrapper element
sw -- soapWriter object
pyobj -- python object to serialize
'''
if pyobj is not None and type(pyobj) not in _seqtypes:
raise EvaluateException, 'expecting a list or None'
objid = _get_idstr(pyobj)
ns,n = self.get_name(name, objid)
el = elt.createAppendElement(ns, n)
if self.nillable is True and pyobj is None:
self.serialize_as_nil(el)
return None
tc = self.itemTypeCode
s = StringIO(); sep = ' '
for item in pyobj:
s.write(tc.get_formatted_content(item))
s.write(sep)
el.createAppendTextNode(s.getvalue())
def RegisterType(C, clobber=0, *args, **keywords):
instance = apply(C, args, keywords)
for t in C.__dict__.get('parselist', []):
prev = Any.parsemap.get(t)
if prev:
if prev.__class__ == C: continue
if not clobber:
raise TypeError(
str(C) + ' duplicating parse registration for ' + str(t))
Any.parsemap[t] = instance
for t in C.__dict__.get('seriallist', []):
ti = type(t)
if ti in [ types.TypeType, types.ClassType]:
key = t
elif ti in _stringtypes:
key = (types.ClassType, t)
else:
raise TypeError(str(t) + ' is not a class name')
prev = Any.serialmap.get(key)
if prev:
if prev.__class__ == C: continue
if not clobber:
raise TypeError(
str(C) + ' duplicating serial registration for ' + str(t))
Any.serialmap[key] = instance
#def _DynamicImport(moduleName, className):
# '''
# Utility function for RegisterTypeWithSchemaAndClass
# '''
# mod = __import__(moduleName)
# components = moduleName.split('.')
# for comp in components[1:]:
# mod = getattr(mod, comp)
# return getattr(mod, className)
#
#def _RegisterTypeWithSchemaAndClass(importedSchemaTypes, schemaTypeName, classModuleName, className, generatedClassSuffix="_"):
# '''
# Used by RegisterGeneratedTypesWithMapping.
# Helps register classes so they can be serialized and parsed as "any".
# Register a type by providing its schema and class. This allows
# Any and AnyType to reconstruct objects made up of your own classes.
# Note: The class module should be able to be imported (by being in your
# pythonpath). Your classes __init__ functions shoud have default
# arguments for all extra parameters.
# Example of use:
# import SchemaToPyTypeMap # Mapping written by you. Also used with wsdl2py -m
# # mapping = {"SomeDescription":("Descriptions", "SomeDescription"),
# # schemaTypeName : moduleName , className
# # The module on the next line is generated by wsdl2py
# from EchoServer_services_types import urn_ZSI_examples as ExampleTypes
#
# for key,value in SchemaToPyTypeMap.mapping.items():
# ZSI.TC.RegisterTypeWithSchemaAndClass(importedSchemaTypes = ExampleTypes, schemaTypeName=key, classModuleName=value[0], className=value[1])
#
# '''
# # Doing this: (schemaTypeName="ExampleTypes", classModuleName="Description",
# # className="SomeDescription")
# # sd_instance = ExampleTypes.SomeDescription_(pname="SomeDescription")
# # Any.serialmap[Descriptions.SomeDescription] = sd_instance
# # Any.parsemap[(None,'SomeDescription')] = sd_instance
# classDef = _DynamicImport(classModuleName, className)
# interfaceDef = getattr(importedSchemaTypes, schemaTypeName + generatedClassSuffix)
#
# instance = interfaceDef(pname=className)
# Any.serialmap[classDef] = instance
# Any.parsemap[(None,schemaTypeName)] = instance
#
#def RegisterGeneratedTypesWithMapping(generatedTypes, mapping, generatedClassSuffix="_"):
# '''
# Registers python classes so they can be serialized and parsed as "any".
# generatedTypes is a class containing typecode classes generated by zsi.
# mapping is a dictionary that maps
# {schemaTypeName : moduleName, className}
# and is also used with wsdl2py -m
#
# Example of use:
# import SchemaToPyTypeMap # See RegisterTypeWithSchemaAndClass for description
# # The module on the next line is generated by wsdl2py and
# # contains generated typecodes.
# from EchoServer_services_types import urn_ZSI_examples as ExampleTypes
# RegisterGeneratedTypesWithMapping(generatedTypes = ExampleTypes, mapping=SchemaToPyTypeMap.mapping)
# '''
# for key,value in mapping.items():
# _RegisterTypeWithSchemaAndClass(importedSchemaTypes = generatedTypes, schemaTypeName=key, classModuleName=value[0], className=value[1], generatedClassSuffix=generatedClassSuffix)
from TCnumbers import *
from TCtimes import *
from schema import GTD, GED, WrapImmutable
from TCcompound import *
from TCapache import *
# aliases backwards compatiblity
_get_type_definition, _get_global_element_declaration, Wrap = GTD, GED, WrapImmutable
f = lambda x: type(x) == types.ClassType and issubclass(x, TypeCode) and getattr(x, 'type', None) is not None
TYPES = filter(f, map(lambda y:eval(y),dir()))
if __name__ == '__main__': print _copyright
|