You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

840 lines
30 KiB

  1. # Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
  2. #
  3. # This software is subject to the provisions of the Zope Public License,
  4. # Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
  5. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
  6. # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  7. # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
  8. # FOR A PARTICULAR PURPOSE.
  9. ident = "$Id$"
  10. import types
  11. import string, httplib, smtplib, urllib, socket, weakref
  12. import xml.dom.minidom
  13. from string import join, strip, split
  14. from UserDict import UserDict
  15. from StringIO import StringIO
  16. from TimeoutSocket import TimeoutSocket, TimeoutError
  17. from urlparse import urlparse
  18. from httplib import HTTPConnection, HTTPSConnection
  19. from exceptions import Exception
  20. try:
  21. from xml.dom.ext import SplitQName
  22. except:
  23. def SplitQName(qname):
  24. '''SplitQName(qname) -> (string, string)
  25. Split Qualified Name into a tuple of len 2, consisting
  26. of the prefix and the local name.
  27. (prefix, localName)
  28. Special Cases:
  29. xmlns -- (localName, 'xmlns')
  30. None -- (None, localName)
  31. '''
  32. l = qname.split(':')
  33. if len(l) == 1:
  34. l.insert(0, None)
  35. elif len(l) == 2:
  36. if l[0] == 'xmlns':
  37. l.reverse()
  38. else:
  39. return
  40. return tuple(l)
  41. class RecursionError(Exception):
  42. """Used to indicate a HTTP redirect recursion."""
  43. pass
  44. class HTTPResponse:
  45. """Captures the information in an HTTP response message."""
  46. def __init__(self, response):
  47. self.status = response.status
  48. self.reason = response.reason
  49. self.headers = response.msg
  50. self.body = response.read() or None
  51. response.close()
  52. class TimeoutHTTP(HTTPConnection):
  53. """A custom http connection object that supports socket timeout."""
  54. def __init__(self, host, port=None, timeout=20):
  55. HTTPConnection.__init__(self, host, port)
  56. self.timeout = timeout
  57. def connect(self):
  58. self.sock = TimeoutSocket(self.timeout)
  59. self.sock.connect((self.host, self.port))
  60. class TimeoutHTTPS(HTTPSConnection):
  61. """A custom https object that supports socket timeout. Note that this
  62. is not really complete. The builtin SSL support in the Python socket
  63. module requires a real socket (type) to be passed in to be hooked to
  64. SSL. That means our fake socket won't work and our timeout hacks are
  65. bypassed for send and recv calls. Since our hack _is_ in place at
  66. connect() time, it should at least provide some timeout protection."""
  67. def __init__(self, host, port=None, timeout=20, **kwargs):
  68. HTTPSConnection.__init__(self, str(host), port, **kwargs)
  69. self.timeout = timeout
  70. def connect(self):
  71. sock = TimeoutSocket(self.timeout)
  72. sock.connect((self.host, self.port))
  73. realsock = getattr(sock.sock, '_sock', sock.sock)
  74. ssl = socket.ssl(realsock, self.key_file, self.cert_file)
  75. self.sock = httplib.FakeSocket(sock, ssl)
  76. def urlopen(url, timeout=20, redirects=None):
  77. """A minimal urlopen replacement hack that supports timeouts for http.
  78. Note that this supports GET only."""
  79. scheme, host, path, params, query, frag = urlparse(url)
  80. if not scheme in ('http', 'https'):
  81. return urllib.urlopen(url)
  82. if params: path = '%s;%s' % (path, params)
  83. if query: path = '%s?%s' % (path, query)
  84. if frag: path = '%s#%s' % (path, frag)
  85. if scheme == 'https':
  86. # If ssl is not compiled into Python, you will not get an exception
  87. # until a conn.endheaders() call. We need to know sooner, so use
  88. # getattr.
  89. if hasattr(socket, 'ssl'):
  90. conn = TimeoutHTTPS(host, None, timeout)
  91. else:
  92. import M2Crypto
  93. ctx = M2Crypto.SSL.Context()
  94. ctx.set_session_timeout(timeout)
  95. conn = M2Crypto.httpslib.HTTPSConnection(host, ssl_context=ctx)
  96. #conn.set_debuglevel(1)
  97. else:
  98. conn = TimeoutHTTP(host, None, timeout)
  99. conn.putrequest('GET', path)
  100. conn.putheader('Connection', 'close')
  101. conn.endheaders()
  102. response = None
  103. while 1:
  104. response = conn.getresponse()
  105. if response.status != 100:
  106. break
  107. conn._HTTPConnection__state = httplib._CS_REQ_SENT
  108. conn._HTTPConnection__response = None
  109. status = response.status
  110. # If we get an HTTP redirect, we will follow it automatically.
  111. if status >= 300 and status < 400:
  112. location = response.msg.getheader('location')
  113. if location is not None:
  114. response.close()
  115. if redirects is not None and redirects.has_key(location):
  116. raise RecursionError(
  117. 'Circular HTTP redirection detected.'
  118. )
  119. if redirects is None:
  120. redirects = {}
  121. redirects[location] = 1
  122. return urlopen(location, timeout, redirects)
  123. raise HTTPResponse(response)
  124. if not (status >= 200 and status < 300):
  125. raise HTTPResponse(response)
  126. body = StringIO(response.read())
  127. response.close()
  128. return body
  129. class DOM:
  130. """The DOM singleton defines a number of XML related constants and
  131. provides a number of utility methods for DOM related tasks. It
  132. also provides some basic abstractions so that the rest of the
  133. package need not care about actual DOM implementation in use."""
  134. # Namespace stuff related to the SOAP specification.
  135. NS_SOAP_ENV_1_1 = 'http://schemas.xmlsoap.org/soap/envelope/'
  136. NS_SOAP_ENC_1_1 = 'http://schemas.xmlsoap.org/soap/encoding/'
  137. NS_SOAP_ENV_1_2 = 'http://www.w3.org/2001/06/soap-envelope'
  138. NS_SOAP_ENC_1_2 = 'http://www.w3.org/2001/06/soap-encoding'
  139. NS_SOAP_ENV_ALL = (NS_SOAP_ENV_1_1, NS_SOAP_ENV_1_2)
  140. NS_SOAP_ENC_ALL = (NS_SOAP_ENC_1_1, NS_SOAP_ENC_1_2)
  141. NS_SOAP_ENV = NS_SOAP_ENV_1_1
  142. NS_SOAP_ENC = NS_SOAP_ENC_1_1
  143. _soap_uri_mapping = {
  144. NS_SOAP_ENV_1_1 : '1.1',
  145. NS_SOAP_ENV_1_2 : '1.2',
  146. }
  147. SOAP_ACTOR_NEXT_1_1 = 'http://schemas.xmlsoap.org/soap/actor/next'
  148. SOAP_ACTOR_NEXT_1_2 = 'http://www.w3.org/2001/06/soap-envelope/actor/next'
  149. SOAP_ACTOR_NEXT_ALL = (SOAP_ACTOR_NEXT_1_1, SOAP_ACTOR_NEXT_1_2)
  150. def SOAPUriToVersion(self, uri):
  151. """Return the SOAP version related to an envelope uri."""
  152. value = self._soap_uri_mapping.get(uri)
  153. if value is not None:
  154. return value
  155. raise ValueError(
  156. 'Unsupported SOAP envelope uri: %s' % uri
  157. )
  158. def GetSOAPEnvUri(self, version):
  159. """Return the appropriate SOAP envelope uri for a given
  160. human-friendly SOAP version string (e.g. '1.1')."""
  161. attrname = 'NS_SOAP_ENV_%s' % join(split(version, '.'), '_')
  162. value = getattr(self, attrname, None)
  163. if value is not None:
  164. return value
  165. raise ValueError(
  166. 'Unsupported SOAP version: %s' % version
  167. )
  168. def GetSOAPEncUri(self, version):
  169. """Return the appropriate SOAP encoding uri for a given
  170. human-friendly SOAP version string (e.g. '1.1')."""
  171. attrname = 'NS_SOAP_ENC_%s' % join(split(version, '.'), '_')
  172. value = getattr(self, attrname, None)
  173. if value is not None:
  174. return value
  175. raise ValueError(
  176. 'Unsupported SOAP version: %s' % version
  177. )
  178. def GetSOAPActorNextUri(self, version):
  179. """Return the right special next-actor uri for a given
  180. human-friendly SOAP version string (e.g. '1.1')."""
  181. attrname = 'SOAP_ACTOR_NEXT_%s' % join(split(version, '.'), '_')
  182. value = getattr(self, attrname, None)
  183. if value is not None:
  184. return value
  185. raise ValueError(
  186. 'Unsupported SOAP version: %s' % version
  187. )
  188. # Namespace stuff related to XML Schema.
  189. NS_XSD_99 = 'http://www.w3.org/1999/XMLSchema'
  190. NS_XSI_99 = 'http://www.w3.org/1999/XMLSchema-instance'
  191. NS_XSD_00 = 'http://www.w3.org/2000/10/XMLSchema'
  192. NS_XSI_00 = 'http://www.w3.org/2000/10/XMLSchema-instance'
  193. NS_XSD_01 = 'http://www.w3.org/2001/XMLSchema'
  194. NS_XSI_01 = 'http://www.w3.org/2001/XMLSchema-instance'
  195. NS_XSD_ALL = (NS_XSD_99, NS_XSD_00, NS_XSD_01)
  196. NS_XSI_ALL = (NS_XSI_99, NS_XSI_00, NS_XSI_01)
  197. NS_XSD = NS_XSD_01
  198. NS_XSI = NS_XSI_01
  199. _xsd_uri_mapping = {
  200. NS_XSD_99 : NS_XSI_99,
  201. NS_XSD_00 : NS_XSI_00,
  202. NS_XSD_01 : NS_XSI_01,
  203. }
  204. for key, value in _xsd_uri_mapping.items():
  205. _xsd_uri_mapping[value] = key
  206. def InstanceUriForSchemaUri(self, uri):
  207. """Return the appropriate matching XML Schema instance uri for
  208. the given XML Schema namespace uri."""
  209. return self._xsd_uri_mapping.get(uri)
  210. def SchemaUriForInstanceUri(self, uri):
  211. """Return the appropriate matching XML Schema namespace uri for
  212. the given XML Schema instance namespace uri."""
  213. return self._xsd_uri_mapping.get(uri)
  214. # Namespace stuff related to WSDL.
  215. NS_WSDL_1_1 = 'http://schemas.xmlsoap.org/wsdl/'
  216. NS_WSDL_ALL = (NS_WSDL_1_1,)
  217. NS_WSDL = NS_WSDL_1_1
  218. NS_SOAP_BINDING_1_1 = 'http://schemas.xmlsoap.org/wsdl/soap/'
  219. NS_HTTP_BINDING_1_1 = 'http://schemas.xmlsoap.org/wsdl/http/'
  220. NS_MIME_BINDING_1_1 = 'http://schemas.xmlsoap.org/wsdl/mime/'
  221. NS_SOAP_BINDING_ALL = (NS_SOAP_BINDING_1_1,)
  222. NS_HTTP_BINDING_ALL = (NS_HTTP_BINDING_1_1,)
  223. NS_MIME_BINDING_ALL = (NS_MIME_BINDING_1_1,)
  224. NS_SOAP_BINDING = NS_SOAP_BINDING_1_1
  225. NS_HTTP_BINDING = NS_HTTP_BINDING_1_1
  226. NS_MIME_BINDING = NS_MIME_BINDING_1_1
  227. NS_SOAP_HTTP_1_1 = 'http://schemas.xmlsoap.org/soap/http'
  228. NS_SOAP_HTTP_ALL = (NS_SOAP_HTTP_1_1,)
  229. NS_SOAP_HTTP = NS_SOAP_HTTP_1_1
  230. _wsdl_uri_mapping = {
  231. NS_WSDL_1_1 : '1.1',
  232. }
  233. def WSDLUriToVersion(self, uri):
  234. """Return the WSDL version related to a WSDL namespace uri."""
  235. value = self._wsdl_uri_mapping.get(uri)
  236. if value is not None:
  237. return value
  238. raise ValueError(
  239. 'Unsupported SOAP envelope uri: %s' % uri
  240. )
  241. def GetWSDLUri(self, version):
  242. attr = 'NS_WSDL_%s' % join(split(version, '.'), '_')
  243. value = getattr(self, attr, None)
  244. if value is not None:
  245. return value
  246. raise ValueError(
  247. 'Unsupported WSDL version: %s' % version
  248. )
  249. def GetWSDLSoapBindingUri(self, version):
  250. attr = 'NS_SOAP_BINDING_%s' % join(split(version, '.'), '_')
  251. value = getattr(self, attr, None)
  252. if value is not None:
  253. return value
  254. raise ValueError(
  255. 'Unsupported WSDL version: %s' % version
  256. )
  257. def GetWSDLHttpBindingUri(self, version):
  258. attr = 'NS_HTTP_BINDING_%s' % join(split(version, '.'), '_')
  259. value = getattr(self, attr, None)
  260. if value is not None:
  261. return value
  262. raise ValueError(
  263. 'Unsupported WSDL version: %s' % version
  264. )
  265. def GetWSDLMimeBindingUri(self, version):
  266. attr = 'NS_MIME_BINDING_%s' % join(split(version, '.'), '_')
  267. value = getattr(self, attr, None)
  268. if value is not None:
  269. return value
  270. raise ValueError(
  271. 'Unsupported WSDL version: %s' % version
  272. )
  273. def GetWSDLHttpTransportUri(self, version):
  274. attr = 'NS_SOAP_HTTP_%s' % join(split(version, '.'), '_')
  275. value = getattr(self, attr, None)
  276. if value is not None:
  277. return value
  278. raise ValueError(
  279. 'Unsupported WSDL version: %s' % version
  280. )
  281. # Other xml namespace constants.
  282. NS_XMLNS = 'http://www.w3.org/2000/xmlns/'
  283. def isElement(self, node, name, nsuri=None):
  284. """Return true if the given node is an element with the given
  285. name and optional namespace uri."""
  286. if node.nodeType != node.ELEMENT_NODE:
  287. return 0
  288. return node.localName == name and \
  289. (nsuri is None or self.nsUriMatch(node.namespaceURI, nsuri))
  290. def getElement(self, node, name, nsuri=None, default=join):
  291. """Return the first child of node with a matching name and
  292. namespace uri, or the default if one is provided."""
  293. nsmatch = self.nsUriMatch
  294. ELEMENT_NODE = node.ELEMENT_NODE
  295. for child in node.childNodes:
  296. if child.nodeType == ELEMENT_NODE:
  297. if ((child.localName == name or name is None) and
  298. (nsuri is None or nsmatch(child.namespaceURI, nsuri))
  299. ):
  300. return child
  301. if default is not join:
  302. return default
  303. raise KeyError, name
  304. def getElementById(self, node, id, default=join):
  305. """Return the first child of node matching an id reference."""
  306. attrget = self.getAttr
  307. ELEMENT_NODE = node.ELEMENT_NODE
  308. for child in node.childNodes:
  309. if child.nodeType == ELEMENT_NODE:
  310. if attrget(child, 'id') == id:
  311. return child
  312. if default is not join:
  313. return default
  314. raise KeyError, name
  315. def getMappingById(self, document, depth=None, element=None,
  316. mapping=None, level=1):
  317. """Create an id -> element mapping of those elements within a
  318. document that define an id attribute. The depth of the search
  319. may be controlled by using the (1-based) depth argument."""
  320. if document is not None:
  321. element = document.documentElement
  322. mapping = {}
  323. attr = element._attrs.get('id', None)
  324. if attr is not None:
  325. mapping[attr.value] = element
  326. if depth is None or depth > level:
  327. level = level + 1
  328. ELEMENT_NODE = element.ELEMENT_NODE
  329. for child in element.childNodes:
  330. if child.nodeType == ELEMENT_NODE:
  331. self.getMappingById(None, depth, child, mapping, level)
  332. return mapping
  333. def getElements(self, node, name, nsuri=None):
  334. """Return a sequence of the child elements of the given node that
  335. match the given name and optional namespace uri."""
  336. nsmatch = self.nsUriMatch
  337. result = []
  338. ELEMENT_NODE = node.ELEMENT_NODE
  339. for child in node.childNodes:
  340. if child.nodeType == ELEMENT_NODE:
  341. if ((child.localName == name or name is None) and (
  342. (nsuri is None) or nsmatch(child.namespaceURI, nsuri))):
  343. result.append(child)
  344. return result
  345. def hasAttr(self, node, name, nsuri=None):
  346. """Return true if element has attribute with the given name and
  347. optional nsuri. If nsuri is not specified, returns true if an
  348. attribute exists with the given name with any namespace."""
  349. if nsuri is None:
  350. if node.hasAttribute(name):
  351. return True
  352. return False
  353. return node.hasAttributeNS(nsuri, name)
  354. def getAttr(self, node, name, nsuri=None, default=join):
  355. """Return the value of the attribute named 'name' with the
  356. optional nsuri, or the default if one is specified. If
  357. nsuri is not specified, an attribute that matches the
  358. given name will be returned regardless of namespace."""
  359. if nsuri is None:
  360. result = node._attrs.get(name, None)
  361. if result is None:
  362. for item in node._attrsNS.keys():
  363. if item[1] == name:
  364. result = node._attrsNS[item]
  365. break
  366. else:
  367. result = node._attrsNS.get((nsuri, name), None)
  368. if result is not None:
  369. return result.value
  370. if default is not join:
  371. return default
  372. return ''
  373. def getAttrs(self, node):
  374. """Return a Collection of all attributes
  375. """
  376. attrs = {}
  377. for k,v in node._attrs.items():
  378. attrs[k] = v.value
  379. return attrs
  380. def getElementText(self, node, preserve_ws=None):
  381. """Return the text value of an xml element node. Leading and trailing
  382. whitespace is stripped from the value unless the preserve_ws flag
  383. is passed with a true value."""
  384. result = []
  385. for child in node.childNodes:
  386. nodetype = child.nodeType
  387. if nodetype == child.TEXT_NODE or \
  388. nodetype == child.CDATA_SECTION_NODE:
  389. result.append(child.nodeValue)
  390. value = join(result, '')
  391. if preserve_ws is None:
  392. value = strip(value)
  393. return value
  394. def findNamespaceURI(self, prefix, node):
  395. """Find a namespace uri given a prefix and a context node."""
  396. attrkey = (self.NS_XMLNS, prefix)
  397. DOCUMENT_NODE = node.DOCUMENT_NODE
  398. ELEMENT_NODE = node.ELEMENT_NODE
  399. while 1:
  400. if node.nodeType != ELEMENT_NODE:
  401. node = node.parentNode
  402. continue
  403. result = node._attrsNS.get(attrkey, None)
  404. if result is not None:
  405. return result.value
  406. if hasattr(node, '__imported__'):
  407. raise DOMException('Value for prefix %s not found.' % prefix)
  408. node = node.parentNode
  409. if node.nodeType == DOCUMENT_NODE:
  410. raise DOMException('Value for prefix %s not found.' % prefix)
  411. def findDefaultNS(self, node):
  412. """Return the current default namespace uri for the given node."""
  413. attrkey = (self.NS_XMLNS, 'xmlns')
  414. DOCUMENT_NODE = node.DOCUMENT_NODE
  415. ELEMENT_NODE = node.ELEMENT_NODE
  416. while 1:
  417. if node.nodeType != ELEMENT_NODE:
  418. node = node.parentNode
  419. continue
  420. result = node._attrsNS.get(attrkey, None)
  421. if result is not None:
  422. return result.value
  423. if hasattr(node, '__imported__'):
  424. raise DOMException('Cannot determine default namespace.')
  425. node = node.parentNode
  426. if node.nodeType == DOCUMENT_NODE:
  427. raise DOMException('Cannot determine default namespace.')
  428. def findTargetNS(self, node):
  429. """Return the defined target namespace uri for the given node."""
  430. attrget = self.getAttr
  431. attrkey = (self.NS_XMLNS, 'xmlns')
  432. DOCUMENT_NODE = node.DOCUMENT_NODE
  433. ELEMENT_NODE = node.ELEMENT_NODE
  434. while 1:
  435. if node.nodeType != ELEMENT_NODE:
  436. node = node.parentNode
  437. continue
  438. result = attrget(node, 'targetNamespace', default=None)
  439. if result is not None:
  440. return result
  441. node = node.parentNode
  442. if node.nodeType == DOCUMENT_NODE:
  443. raise DOMException('Cannot determine target namespace.')
  444. def getTypeRef(self, element):
  445. """Return (namespaceURI, name) for a type attribue of the given
  446. element, or None if the element does not have a type attribute."""
  447. typeattr = self.getAttr(element, 'type', default=None)
  448. if typeattr is None:
  449. return None
  450. parts = typeattr.split(':', 1)
  451. if len(parts) == 2:
  452. nsuri = self.findNamespaceURI(parts[0], element)
  453. else:
  454. nsuri = self.findDefaultNS(element)
  455. return (nsuri, parts[1])
  456. def importNode(self, document, node, deep=0):
  457. """Implements (well enough for our purposes) DOM node import."""
  458. nodetype = node.nodeType
  459. if nodetype in (node.DOCUMENT_NODE, node.DOCUMENT_TYPE_NODE):
  460. raise DOMException('Illegal node type for importNode')
  461. if nodetype == node.ENTITY_REFERENCE_NODE:
  462. deep = 0
  463. clone = node.cloneNode(deep)
  464. self._setOwnerDoc(document, clone)
  465. clone.__imported__ = 1
  466. return clone
  467. def _setOwnerDoc(self, document, node):
  468. node.ownerDocument = document
  469. for child in node.childNodes:
  470. self._setOwnerDoc(document, child)
  471. def nsUriMatch(self, value, wanted, strict=0, tt=type(())):
  472. """Return a true value if two namespace uri values match."""
  473. if value == wanted or (type(wanted) is tt) and value in wanted:
  474. return 1
  475. if not strict:
  476. wanted = type(wanted) is tt and wanted or (wanted,)
  477. value = value[-1:] != '/' and value or value[:-1]
  478. for item in wanted:
  479. if item == value or item[:-1] == value:
  480. return 1
  481. return 0
  482. def createDocument(self, nsuri, qname, doctype=None):
  483. """Create a new writable DOM document object."""
  484. impl = xml.dom.minidom.getDOMImplementation()
  485. return impl.createDocument(nsuri, qname, doctype)
  486. def loadDocument(self, data):
  487. """Load an xml file from a file-like object and return a DOM
  488. document instance."""
  489. return xml.dom.minidom.parse(data)
  490. def loadFromURL(self, url):
  491. """Load an xml file from a URL and return a DOM document."""
  492. file = urlopen(url)
  493. try: result = self.loadDocument(file)
  494. finally: file.close()
  495. return result
  496. class DOMException(Exception):
  497. pass
  498. DOM = DOM()
  499. class Collection(UserDict):
  500. """Helper class for maintaining ordered named collections."""
  501. default = lambda self,k: k.name
  502. def __init__(self, parent, key=None):
  503. UserDict.__init__(self)
  504. self.parent = weakref.ref(parent)
  505. self.list = []
  506. self._func = key or self.default
  507. def __getitem__(self, key):
  508. if type(key) is type(1):
  509. return self.list[key]
  510. return self.data[key]
  511. def __setitem__(self, key, item):
  512. item.parent = weakref.ref(self)
  513. self.list.append(item)
  514. self.data[key] = item
  515. def keys(self):
  516. return map(lambda i: self._func(i), self.list)
  517. def items(self):
  518. return map(lambda i: (self._func(i), i), self.list)
  519. def values(self):
  520. return self.list
  521. class CollectionNS(UserDict):
  522. """Helper class for maintaining ordered named collections."""
  523. default = lambda self,k: k.name
  524. def __init__(self, parent, key=None):
  525. UserDict.__init__(self)
  526. self.parent = weakref.ref(parent)
  527. self.targetNamespace = None
  528. self.list = []
  529. self._func = key or self.default
  530. def __getitem__(self, key):
  531. self.targetNamespace = self.parent().targetNamespace
  532. if type(key) is types.IntType:
  533. return self.list[key]
  534. elif self.__isSequence(key):
  535. nsuri,name = key
  536. return self.data[nsuri][name]
  537. return self.data[self.parent().targetNamespace][key]
  538. def __setitem__(self, key, item):
  539. item.parent = weakref.ref(self)
  540. self.list.append(item)
  541. targetNamespace = getattr(item, 'targetNamespace', self.parent().targetNamespace)
  542. if not self.data.has_key(targetNamespace):
  543. self.data[targetNamespace] = {}
  544. self.data[targetNamespace][key] = item
  545. def __isSequence(self, key):
  546. return (type(key) in (types.TupleType,types.ListType) and len(key) == 2)
  547. def keys(self):
  548. keys = []
  549. for tns in self.data.keys():
  550. keys.append(map(lambda i: (tns,self._func(i)), self.data[tns].values()))
  551. return keys
  552. def items(self):
  553. return map(lambda i: (self._func(i), i), self.list)
  554. def values(self):
  555. return self.list
  556. # This is a runtime guerilla patch for pulldom (used by minidom) so
  557. # that xml namespace declaration attributes are not lost in parsing.
  558. # We need them to do correct QName linking for XML Schema and WSDL.
  559. # The patch has been submitted to SF for the next Python version.
  560. from xml.dom.pulldom import PullDOM, START_ELEMENT
  561. if 1:
  562. def startPrefixMapping(self, prefix, uri):
  563. if not hasattr(self, '_xmlns_attrs'):
  564. self._xmlns_attrs = []
  565. self._xmlns_attrs.append((prefix or 'xmlns', uri))
  566. self._ns_contexts.append(self._current_context.copy())
  567. self._current_context[uri] = prefix or ''
  568. PullDOM.startPrefixMapping = startPrefixMapping
  569. def startElementNS(self, name, tagName , attrs):
  570. # Retrieve xml namespace declaration attributes.
  571. xmlns_uri = 'http://www.w3.org/2000/xmlns/'
  572. xmlns_attrs = getattr(self, '_xmlns_attrs', None)
  573. if xmlns_attrs is not None:
  574. for aname, value in xmlns_attrs:
  575. attrs._attrs[(xmlns_uri, aname)] = value
  576. self._xmlns_attrs = []
  577. uri, localname = name
  578. if uri:
  579. # When using namespaces, the reader may or may not
  580. # provide us with the original name. If not, create
  581. # *a* valid tagName from the current context.
  582. if tagName is None:
  583. prefix = self._current_context[uri]
  584. if prefix:
  585. tagName = prefix + ":" + localname
  586. else:
  587. tagName = localname
  588. if self.document:
  589. node = self.document.createElementNS(uri, tagName)
  590. else:
  591. node = self.buildDocument(uri, tagName)
  592. else:
  593. # When the tagname is not prefixed, it just appears as
  594. # localname
  595. if self.document:
  596. node = self.document.createElement(localname)
  597. else:
  598. node = self.buildDocument(None, localname)
  599. for aname,value in attrs.items():
  600. a_uri, a_localname = aname
  601. if a_uri == xmlns_uri:
  602. if a_localname == 'xmlns':
  603. qname = a_localname
  604. else:
  605. qname = 'xmlns:' + a_localname
  606. attr = self.document.createAttributeNS(a_uri, qname)
  607. node.setAttributeNodeNS(attr)
  608. elif a_uri:
  609. prefix = self._current_context[a_uri]
  610. if prefix:
  611. qname = prefix + ":" + a_localname
  612. else:
  613. qname = a_localname
  614. attr = self.document.createAttributeNS(a_uri, qname)
  615. node.setAttributeNodeNS(attr)
  616. else:
  617. attr = self.document.createAttribute(a_localname)
  618. node.setAttributeNode(attr)
  619. attr.value = value
  620. self.lastEvent[1] = [(START_ELEMENT, node), None]
  621. self.lastEvent = self.lastEvent[1]
  622. self.push(node)
  623. PullDOM.startElementNS = startElementNS
  624. #
  625. # This is a runtime guerilla patch for minidom so
  626. # that xmlns prefixed attributes dont raise AttributeErrors
  627. # during cloning.
  628. #
  629. # Namespace declarations can appear in any start-tag, must look for xmlns
  630. # prefixed attribute names during cloning.
  631. #
  632. # key (attr.namespaceURI, tag)
  633. # ('http://www.w3.org/2000/xmlns/', u'xsd') <xml.dom.minidom.Attr instance at 0x82227c4>
  634. # ('http://www.w3.org/2000/xmlns/', 'xmlns') <xml.dom.minidom.Attr instance at 0x8414b3c>
  635. #
  636. # xml.dom.minidom.Attr.nodeName = xmlns:xsd
  637. # xml.dom.minidom.Attr.value = = http://www.w3.org/2001/XMLSchema
  638. if 1:
  639. def _clone_node(node, deep, newOwnerDocument):
  640. """
  641. Clone a node and give it the new owner document.
  642. Called by Node.cloneNode and Document.importNode
  643. """
  644. if node.ownerDocument.isSameNode(newOwnerDocument):
  645. operation = xml.dom.UserDataHandler.NODE_CLONED
  646. else:
  647. operation = xml.dom.UserDataHandler.NODE_IMPORTED
  648. if node.nodeType == xml.dom.minidom.Node.ELEMENT_NODE:
  649. clone = newOwnerDocument.createElementNS(node.namespaceURI,
  650. node.nodeName)
  651. for attr in node.attributes.values():
  652. clone.setAttributeNS(attr.namespaceURI, attr.nodeName, attr.value)
  653. prefix, tag = xml.dom.minidom._nssplit(attr.nodeName)
  654. if prefix == 'xmlns':
  655. a = clone.getAttributeNodeNS(attr.namespaceURI, tag)
  656. elif prefix:
  657. a = clone.getAttributeNodeNS(attr.namespaceURI, tag)
  658. else:
  659. a = clone.getAttributeNodeNS(attr.namespaceURI, attr.nodeName)
  660. a.specified = attr.specified
  661. if deep:
  662. for child in node.childNodes:
  663. c = xml.dom.minidom._clone_node(child, deep, newOwnerDocument)
  664. clone.appendChild(c)
  665. elif node.nodeType == xml.dom.minidom.Node.DOCUMENT_FRAGMENT_NODE:
  666. clone = newOwnerDocument.createDocumentFragment()
  667. if deep:
  668. for child in node.childNodes:
  669. c = xml.dom.minidom._clone_node(child, deep, newOwnerDocument)
  670. clone.appendChild(c)
  671. elif node.nodeType == xml.dom.minidom.Node.TEXT_NODE:
  672. clone = newOwnerDocument.createTextNode(node.data)
  673. elif node.nodeType == xml.dom.minidom.Node.CDATA_SECTION_NODE:
  674. clone = newOwnerDocument.createCDATASection(node.data)
  675. elif node.nodeType == xml.dom.minidom.Node.PROCESSING_INSTRUCTION_NODE:
  676. clone = newOwnerDocument.createProcessingInstruction(node.target,
  677. node.data)
  678. elif node.nodeType == xml.dom.minidom.Node.COMMENT_NODE:
  679. clone = newOwnerDocument.createComment(node.data)
  680. elif node.nodeType == xml.dom.minidom.Node.ATTRIBUTE_NODE:
  681. clone = newOwnerDocument.createAttributeNS(node.namespaceURI,
  682. node.nodeName)
  683. clone.specified = True
  684. clone.value = node.value
  685. elif node.nodeType == xml.dom.minidom.Node.DOCUMENT_TYPE_NODE:
  686. assert node.ownerDocument is not newOwnerDocument
  687. operation = xml.dom.UserDataHandler.NODE_IMPORTED
  688. clone = newOwnerDocument.implementation.createDocumentType(
  689. node.name, node.publicId, node.systemId)
  690. clone.ownerDocument = newOwnerDocument
  691. if deep:
  692. clone.entities._seq = []
  693. clone.notations._seq = []
  694. for n in node.notations._seq:
  695. notation = xml.dom.minidom.Notation(n.nodeName, n.publicId, n.systemId)
  696. notation.ownerDocument = newOwnerDocument
  697. clone.notations._seq.append(notation)
  698. if hasattr(n, '_call_user_data_handler'):
  699. n._call_user_data_handler(operation, n, notation)
  700. for e in node.entities._seq:
  701. entity = xml.dom.minidom.Entity(e.nodeName, e.publicId, e.systemId,
  702. e.notationName)
  703. entity.actualEncoding = e.actualEncoding
  704. entity.encoding = e.encoding
  705. entity.version = e.version
  706. entity.ownerDocument = newOwnerDocument
  707. clone.entities._seq.append(entity)
  708. if hasattr(e, '_call_user_data_handler'):
  709. e._call_user_data_handler(operation, n, entity)
  710. else:
  711. # Note the cloning of Document and DocumentType nodes is
  712. # implemenetation specific. minidom handles those cases
  713. # directly in the cloneNode() methods.
  714. raise xml.dom.NotSupportedErr("Cannot clone node %s" % repr(node))
  715. # Check for _call_user_data_handler() since this could conceivably
  716. # used with other DOM implementations (one of the FourThought
  717. # DOMs, perhaps?).
  718. if hasattr(node, '_call_user_data_handler'):
  719. node._call_user_data_handler(operation, node, clone)
  720. return clone
  721. xml.dom.minidom._clone_node = _clone_node