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.
 
 
 

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