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.
 
 
 

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