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.
 
 
 

1332 lines
47 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. from string import join, strip, split
  13. from UserDict import UserDict
  14. from cStringIO import StringIO
  15. from TimeoutSocket import TimeoutSocket, TimeoutError
  16. from urlparse import urlparse
  17. from httplib import HTTPConnection, HTTPSConnection
  18. from exceptions import Exception
  19. import xml.dom.minidom
  20. from xml.dom import Node
  21. import logging
  22. from c14n import Canonicalize
  23. from Namespaces import SCHEMA, SOAP, XMLNS, ZSI_SCHEMA_URI
  24. try:
  25. from xml.dom.ext import SplitQName
  26. except:
  27. def SplitQName(qname):
  28. '''SplitQName(qname) -> (string, string)
  29. Split Qualified Name into a tuple of len 2, consisting
  30. of the prefix and the local name.
  31. (prefix, localName)
  32. Special Cases:
  33. xmlns -- (localName, 'xmlns')
  34. None -- (None, localName)
  35. '''
  36. l = qname.split(':')
  37. if len(l) == 1:
  38. l.insert(0, None)
  39. elif len(l) == 2:
  40. if l[0] == 'xmlns':
  41. l.reverse()
  42. else:
  43. return
  44. return tuple(l)
  45. class NamespaceError(Exception):
  46. """Used to indicate a Namespace Error."""
  47. class RecursionError(Exception):
  48. """Used to indicate a HTTP redirect recursion."""
  49. class ParseError(Exception):
  50. """Used to indicate a XML parsing error."""
  51. class DOMException(Exception):
  52. """Used to indicate a problem processing DOM."""
  53. class Base:
  54. """Base class for instance level Logging"""
  55. def __init__(self, module=__name__):
  56. self.logger = logging.getLogger('%s-%s(%x)' %(module, self.__class__, id(self)))
  57. class HTTPResponse:
  58. """Captures the information in an HTTP response message."""
  59. def __init__(self, response):
  60. self.status = response.status
  61. self.reason = response.reason
  62. self.headers = response.msg
  63. self.body = response.read() or None
  64. response.close()
  65. class TimeoutHTTP(HTTPConnection):
  66. """A custom http connection object that supports socket timeout."""
  67. def __init__(self, host, port=None, timeout=20):
  68. HTTPConnection.__init__(self, host, port)
  69. self.timeout = timeout
  70. def connect(self):
  71. self.sock = TimeoutSocket(self.timeout)
  72. self.sock.connect((self.host, self.port))
  73. class TimeoutHTTPS(HTTPSConnection):
  74. """A custom https object that supports socket timeout. Note that this
  75. is not really complete. The builtin SSL support in the Python socket
  76. module requires a real socket (type) to be passed in to be hooked to
  77. SSL. That means our fake socket won't work and our timeout hacks are
  78. bypassed for send and recv calls. Since our hack _is_ in place at
  79. connect() time, it should at least provide some timeout protection."""
  80. def __init__(self, host, port=None, timeout=20, **kwargs):
  81. HTTPSConnection.__init__(self, str(host), port, **kwargs)
  82. self.timeout = timeout
  83. def connect(self):
  84. sock = TimeoutSocket(self.timeout)
  85. sock.connect((self.host, self.port))
  86. realsock = getattr(sock.sock, '_sock', sock.sock)
  87. ssl = socket.ssl(realsock, self.key_file, self.cert_file)
  88. self.sock = httplib.FakeSocket(sock, ssl)
  89. def urlopen(url, timeout=20, redirects=None):
  90. """A minimal urlopen replacement hack that supports timeouts for http.
  91. Note that this supports GET only."""
  92. scheme, host, path, params, query, frag = urlparse(url)
  93. if not scheme in ('http', 'https'):
  94. return urllib.urlopen(url)
  95. if params: path = '%s;%s' % (path, params)
  96. if query: path = '%s?%s' % (path, query)
  97. if frag: path = '%s#%s' % (path, frag)
  98. if scheme == 'https':
  99. # If ssl is not compiled into Python, you will not get an exception
  100. # until a conn.endheaders() call. We need to know sooner, so use
  101. # getattr.
  102. if hasattr(socket, 'ssl'):
  103. conn = TimeoutHTTPS(host, None, timeout)
  104. else:
  105. import M2Crypto
  106. ctx = M2Crypto.SSL.Context()
  107. ctx.set_session_timeout(timeout)
  108. conn = M2Crypto.httpslib.HTTPSConnection(host, ssl_context=ctx)
  109. #conn.set_debuglevel(1)
  110. else:
  111. conn = TimeoutHTTP(host, None, timeout)
  112. conn.putrequest('GET', path)
  113. conn.putheader('Connection', 'close')
  114. conn.endheaders()
  115. response = None
  116. while 1:
  117. response = conn.getresponse()
  118. if response.status != 100:
  119. break
  120. conn._HTTPConnection__state = httplib._CS_REQ_SENT
  121. conn._HTTPConnection__response = None
  122. status = response.status
  123. # If we get an HTTP redirect, we will follow it automatically.
  124. if status >= 300 and status < 400:
  125. location = response.msg.getheader('location')
  126. if location is not None:
  127. response.close()
  128. if redirects is not None and redirects.has_key(location):
  129. raise RecursionError(
  130. 'Circular HTTP redirection detected.'
  131. )
  132. if redirects is None:
  133. redirects = {}
  134. redirects[location] = 1
  135. return urlopen(location, timeout, redirects)
  136. raise HTTPResponse(response)
  137. if not (status >= 200 and status < 300):
  138. raise HTTPResponse(response)
  139. body = StringIO(response.read())
  140. response.close()
  141. return body
  142. class DOM:
  143. """The DOM singleton defines a number of XML related constants and
  144. provides a number of utility methods for DOM related tasks. It
  145. also provides some basic abstractions so that the rest of the
  146. package need not care about actual DOM implementation in use."""
  147. # Namespace stuff related to the SOAP specification.
  148. NS_SOAP_ENV_1_1 = 'http://schemas.xmlsoap.org/soap/envelope/'
  149. NS_SOAP_ENC_1_1 = 'http://schemas.xmlsoap.org/soap/encoding/'
  150. NS_SOAP_ENV_1_2 = 'http://www.w3.org/2001/06/soap-envelope'
  151. NS_SOAP_ENC_1_2 = 'http://www.w3.org/2001/06/soap-encoding'
  152. NS_SOAP_ENV_ALL = (NS_SOAP_ENV_1_1, NS_SOAP_ENV_1_2)
  153. NS_SOAP_ENC_ALL = (NS_SOAP_ENC_1_1, NS_SOAP_ENC_1_2)
  154. NS_SOAP_ENV = NS_SOAP_ENV_1_1
  155. NS_SOAP_ENC = NS_SOAP_ENC_1_1
  156. _soap_uri_mapping = {
  157. NS_SOAP_ENV_1_1 : '1.1',
  158. NS_SOAP_ENV_1_2 : '1.2',
  159. }
  160. SOAP_ACTOR_NEXT_1_1 = 'http://schemas.xmlsoap.org/soap/actor/next'
  161. SOAP_ACTOR_NEXT_1_2 = 'http://www.w3.org/2001/06/soap-envelope/actor/next'
  162. SOAP_ACTOR_NEXT_ALL = (SOAP_ACTOR_NEXT_1_1, SOAP_ACTOR_NEXT_1_2)
  163. def SOAPUriToVersion(self, uri):
  164. """Return the SOAP version related to an envelope uri."""
  165. value = self._soap_uri_mapping.get(uri)
  166. if value is not None:
  167. return value
  168. raise ValueError(
  169. 'Unsupported SOAP envelope uri: %s' % uri
  170. )
  171. def GetSOAPEnvUri(self, version):
  172. """Return the appropriate SOAP envelope uri for a given
  173. human-friendly SOAP version string (e.g. '1.1')."""
  174. attrname = 'NS_SOAP_ENV_%s' % join(split(version, '.'), '_')
  175. value = getattr(self, attrname, None)
  176. if value is not None:
  177. return value
  178. raise ValueError(
  179. 'Unsupported SOAP version: %s' % version
  180. )
  181. def GetSOAPEncUri(self, version):
  182. """Return the appropriate SOAP encoding uri for a given
  183. human-friendly SOAP version string (e.g. '1.1')."""
  184. attrname = 'NS_SOAP_ENC_%s' % join(split(version, '.'), '_')
  185. value = getattr(self, attrname, None)
  186. if value is not None:
  187. return value
  188. raise ValueError(
  189. 'Unsupported SOAP version: %s' % version
  190. )
  191. def GetSOAPActorNextUri(self, version):
  192. """Return the right special next-actor uri for a given
  193. human-friendly SOAP version string (e.g. '1.1')."""
  194. attrname = 'SOAP_ACTOR_NEXT_%s' % join(split(version, '.'), '_')
  195. value = getattr(self, attrname, None)
  196. if value is not None:
  197. return value
  198. raise ValueError(
  199. 'Unsupported SOAP version: %s' % version
  200. )
  201. # Namespace stuff related to XML Schema.
  202. NS_XSD_99 = 'http://www.w3.org/1999/XMLSchema'
  203. NS_XSI_99 = 'http://www.w3.org/1999/XMLSchema-instance'
  204. NS_XSD_00 = 'http://www.w3.org/2000/10/XMLSchema'
  205. NS_XSI_00 = 'http://www.w3.org/2000/10/XMLSchema-instance'
  206. NS_XSD_01 = 'http://www.w3.org/2001/XMLSchema'
  207. NS_XSI_01 = 'http://www.w3.org/2001/XMLSchema-instance'
  208. NS_XSD_ALL = (NS_XSD_99, NS_XSD_00, NS_XSD_01)
  209. NS_XSI_ALL = (NS_XSI_99, NS_XSI_00, NS_XSI_01)
  210. NS_XSD = NS_XSD_01
  211. NS_XSI = NS_XSI_01
  212. _xsd_uri_mapping = {
  213. NS_XSD_99 : NS_XSI_99,
  214. NS_XSD_00 : NS_XSI_00,
  215. NS_XSD_01 : NS_XSI_01,
  216. }
  217. for key, value in _xsd_uri_mapping.items():
  218. _xsd_uri_mapping[value] = key
  219. def InstanceUriForSchemaUri(self, uri):
  220. """Return the appropriate matching XML Schema instance uri for
  221. the given XML Schema namespace uri."""
  222. return self._xsd_uri_mapping.get(uri)
  223. def SchemaUriForInstanceUri(self, uri):
  224. """Return the appropriate matching XML Schema namespace uri for
  225. the given XML Schema instance namespace uri."""
  226. return self._xsd_uri_mapping.get(uri)
  227. # Namespace stuff related to WSDL.
  228. NS_WSDL_1_1 = 'http://schemas.xmlsoap.org/wsdl/'
  229. NS_WSDL_ALL = (NS_WSDL_1_1,)
  230. NS_WSDL = NS_WSDL_1_1
  231. NS_SOAP_BINDING_1_1 = 'http://schemas.xmlsoap.org/wsdl/soap/'
  232. NS_HTTP_BINDING_1_1 = 'http://schemas.xmlsoap.org/wsdl/http/'
  233. NS_MIME_BINDING_1_1 = 'http://schemas.xmlsoap.org/wsdl/mime/'
  234. NS_SOAP_BINDING_ALL = (NS_SOAP_BINDING_1_1,)
  235. NS_HTTP_BINDING_ALL = (NS_HTTP_BINDING_1_1,)
  236. NS_MIME_BINDING_ALL = (NS_MIME_BINDING_1_1,)
  237. NS_SOAP_BINDING = NS_SOAP_BINDING_1_1
  238. NS_HTTP_BINDING = NS_HTTP_BINDING_1_1
  239. NS_MIME_BINDING = NS_MIME_BINDING_1_1
  240. NS_SOAP_HTTP_1_1 = 'http://schemas.xmlsoap.org/soap/http'
  241. NS_SOAP_HTTP_ALL = (NS_SOAP_HTTP_1_1,)
  242. NS_SOAP_HTTP = NS_SOAP_HTTP_1_1
  243. _wsdl_uri_mapping = {
  244. NS_WSDL_1_1 : '1.1',
  245. }
  246. def WSDLUriToVersion(self, uri):
  247. """Return the WSDL version related to a WSDL namespace uri."""
  248. value = self._wsdl_uri_mapping.get(uri)
  249. if value is not None:
  250. return value
  251. raise ValueError(
  252. 'Unsupported SOAP envelope uri: %s' % uri
  253. )
  254. def GetWSDLUri(self, version):
  255. attr = 'NS_WSDL_%s' % join(split(version, '.'), '_')
  256. value = getattr(self, attr, None)
  257. if value is not None:
  258. return value
  259. raise ValueError(
  260. 'Unsupported WSDL version: %s' % version
  261. )
  262. def GetWSDLSoapBindingUri(self, version):
  263. attr = 'NS_SOAP_BINDING_%s' % join(split(version, '.'), '_')
  264. value = getattr(self, attr, None)
  265. if value is not None:
  266. return value
  267. raise ValueError(
  268. 'Unsupported WSDL version: %s' % version
  269. )
  270. def GetWSDLHttpBindingUri(self, version):
  271. attr = 'NS_HTTP_BINDING_%s' % join(split(version, '.'), '_')
  272. value = getattr(self, attr, None)
  273. if value is not None:
  274. return value
  275. raise ValueError(
  276. 'Unsupported WSDL version: %s' % version
  277. )
  278. def GetWSDLMimeBindingUri(self, version):
  279. attr = 'NS_MIME_BINDING_%s' % join(split(version, '.'), '_')
  280. value = getattr(self, attr, None)
  281. if value is not None:
  282. return value
  283. raise ValueError(
  284. 'Unsupported WSDL version: %s' % version
  285. )
  286. def GetWSDLHttpTransportUri(self, version):
  287. attr = 'NS_SOAP_HTTP_%s' % join(split(version, '.'), '_')
  288. value = getattr(self, attr, None)
  289. if value is not None:
  290. return value
  291. raise ValueError(
  292. 'Unsupported WSDL version: %s' % version
  293. )
  294. # Other xml namespace constants.
  295. NS_XMLNS = 'http://www.w3.org/2000/xmlns/'
  296. def isElement(self, node, name, nsuri=None):
  297. """Return true if the given node is an element with the given
  298. name and optional namespace uri."""
  299. if node.nodeType != node.ELEMENT_NODE:
  300. return 0
  301. return node.localName == name and \
  302. (nsuri is None or self.nsUriMatch(node.namespaceURI, nsuri))
  303. def getElement(self, node, name, nsuri=None, default=join):
  304. """Return the first child of node with a matching name and
  305. namespace uri, or the default if one is provided."""
  306. nsmatch = self.nsUriMatch
  307. ELEMENT_NODE = node.ELEMENT_NODE
  308. for child in node.childNodes:
  309. if child.nodeType == ELEMENT_NODE:
  310. if ((child.localName == name or name is None) and
  311. (nsuri is None or nsmatch(child.namespaceURI, nsuri))
  312. ):
  313. return child
  314. if default is not join:
  315. return default
  316. raise KeyError, name
  317. def getElementById(self, node, id, default=join):
  318. """Return the first child of node matching an id reference."""
  319. attrget = self.getAttr
  320. ELEMENT_NODE = node.ELEMENT_NODE
  321. for child in node.childNodes:
  322. if child.nodeType == ELEMENT_NODE:
  323. if attrget(child, 'id') == id:
  324. return child
  325. if default is not join:
  326. return default
  327. raise KeyError, name
  328. def getMappingById(self, document, depth=None, element=None,
  329. mapping=None, level=1):
  330. """Create an id -> element mapping of those elements within a
  331. document that define an id attribute. The depth of the search
  332. may be controlled by using the (1-based) depth argument."""
  333. if document is not None:
  334. element = document.documentElement
  335. mapping = {}
  336. attr = element._attrs.get('id', None)
  337. if attr is not None:
  338. mapping[attr.value] = element
  339. if depth is None or depth > level:
  340. level = level + 1
  341. ELEMENT_NODE = element.ELEMENT_NODE
  342. for child in element.childNodes:
  343. if child.nodeType == ELEMENT_NODE:
  344. self.getMappingById(None, depth, child, mapping, level)
  345. return mapping
  346. def getElements(self, node, name, nsuri=None):
  347. """Return a sequence of the child elements of the given node that
  348. match the given name and optional namespace uri."""
  349. nsmatch = self.nsUriMatch
  350. result = []
  351. ELEMENT_NODE = node.ELEMENT_NODE
  352. for child in node.childNodes:
  353. if child.nodeType == ELEMENT_NODE:
  354. if ((child.localName == name or name is None) and (
  355. (nsuri is None) or nsmatch(child.namespaceURI, nsuri))):
  356. result.append(child)
  357. return result
  358. def hasAttr(self, node, name, nsuri=None):
  359. """Return true if element has attribute with the given name and
  360. optional nsuri. If nsuri is not specified, returns true if an
  361. attribute exists with the given name with any namespace."""
  362. if nsuri is None:
  363. if node.hasAttribute(name):
  364. return True
  365. return False
  366. return node.hasAttributeNS(nsuri, name)
  367. def getAttr(self, node, name, nsuri=None, default=join):
  368. """Return the value of the attribute named 'name' with the
  369. optional nsuri, or the default if one is specified. If
  370. nsuri is not specified, an attribute that matches the
  371. given name will be returned regardless of namespace."""
  372. if nsuri is None:
  373. result = node._attrs.get(name, None)
  374. if result is None:
  375. for item in node._attrsNS.keys():
  376. if item[1] == name:
  377. result = node._attrsNS[item]
  378. break
  379. else:
  380. result = node._attrsNS.get((nsuri, name), None)
  381. if result is not None:
  382. return result.value
  383. if default is not join:
  384. return default
  385. return ''
  386. def getAttrs(self, node):
  387. """Return a Collection of all attributes
  388. """
  389. attrs = {}
  390. for k,v in node._attrs.items():
  391. attrs[k] = v.value
  392. return attrs
  393. def getElementText(self, node, preserve_ws=None):
  394. """Return the text value of an xml element node. Leading and trailing
  395. whitespace is stripped from the value unless the preserve_ws flag
  396. is passed with a true value."""
  397. result = []
  398. for child in node.childNodes:
  399. nodetype = child.nodeType
  400. if nodetype == child.TEXT_NODE or \
  401. nodetype == child.CDATA_SECTION_NODE:
  402. result.append(child.nodeValue)
  403. value = join(result, '')
  404. if preserve_ws is None:
  405. value = strip(value)
  406. return value
  407. def findNamespaceURI(self, prefix, node):
  408. """Find a namespace uri given a prefix and a context node."""
  409. attrkey = (self.NS_XMLNS, prefix)
  410. DOCUMENT_NODE = node.DOCUMENT_NODE
  411. ELEMENT_NODE = node.ELEMENT_NODE
  412. while 1:
  413. if node.nodeType != ELEMENT_NODE:
  414. node = node.parentNode
  415. continue
  416. result = node._attrsNS.get(attrkey, None)
  417. if result is not None:
  418. return result.value
  419. if hasattr(node, '__imported__'):
  420. raise DOMException('Value for prefix %s not found.' % prefix)
  421. node = node.parentNode
  422. if node.nodeType == DOCUMENT_NODE:
  423. raise DOMException('Value for prefix %s not found.' % prefix)
  424. def findDefaultNS(self, node):
  425. """Return the current default namespace uri for the given node."""
  426. attrkey = (self.NS_XMLNS, 'xmlns')
  427. DOCUMENT_NODE = node.DOCUMENT_NODE
  428. ELEMENT_NODE = node.ELEMENT_NODE
  429. while 1:
  430. if node.nodeType != ELEMENT_NODE:
  431. node = node.parentNode
  432. continue
  433. result = node._attrsNS.get(attrkey, None)
  434. if result is not None:
  435. return result.value
  436. if hasattr(node, '__imported__'):
  437. raise DOMException('Cannot determine default namespace.')
  438. node = node.parentNode
  439. if node.nodeType == DOCUMENT_NODE:
  440. raise DOMException('Cannot determine default namespace.')
  441. def findTargetNS(self, node):
  442. """Return the defined target namespace uri for the given node."""
  443. attrget = self.getAttr
  444. attrkey = (self.NS_XMLNS, 'xmlns')
  445. DOCUMENT_NODE = node.DOCUMENT_NODE
  446. ELEMENT_NODE = node.ELEMENT_NODE
  447. while 1:
  448. if node.nodeType != ELEMENT_NODE:
  449. node = node.parentNode
  450. continue
  451. result = attrget(node, 'targetNamespace', default=None)
  452. if result is not None:
  453. return result
  454. node = node.parentNode
  455. if node.nodeType == DOCUMENT_NODE:
  456. raise DOMException('Cannot determine target namespace.')
  457. def getTypeRef(self, element):
  458. """Return (namespaceURI, name) for a type attribue of the given
  459. element, or None if the element does not have a type attribute."""
  460. typeattr = self.getAttr(element, 'type', default=None)
  461. if typeattr is None:
  462. return None
  463. parts = typeattr.split(':', 1)
  464. if len(parts) == 2:
  465. nsuri = self.findNamespaceURI(parts[0], element)
  466. else:
  467. nsuri = self.findDefaultNS(element)
  468. return (nsuri, parts[1])
  469. def importNode(self, document, node, deep=0):
  470. """Implements (well enough for our purposes) DOM node import."""
  471. nodetype = node.nodeType
  472. if nodetype in (node.DOCUMENT_NODE, node.DOCUMENT_TYPE_NODE):
  473. raise DOMException('Illegal node type for importNode')
  474. if nodetype == node.ENTITY_REFERENCE_NODE:
  475. deep = 0
  476. clone = node.cloneNode(deep)
  477. self._setOwnerDoc(document, clone)
  478. clone.__imported__ = 1
  479. return clone
  480. def _setOwnerDoc(self, document, node):
  481. node.ownerDocument = document
  482. for child in node.childNodes:
  483. self._setOwnerDoc(document, child)
  484. def nsUriMatch(self, value, wanted, strict=0, tt=type(())):
  485. """Return a true value if two namespace uri values match."""
  486. if value == wanted or (type(wanted) is tt) and value in wanted:
  487. return 1
  488. if not strict:
  489. wanted = type(wanted) is tt and wanted or (wanted,)
  490. value = value[-1:] != '/' and value or value[:-1]
  491. for item in wanted:
  492. if item == value or item[:-1] == value:
  493. return 1
  494. return 0
  495. def createDocument(self, nsuri, qname, doctype=None):
  496. """Create a new writable DOM document object."""
  497. impl = xml.dom.minidom.getDOMImplementation()
  498. return impl.createDocument(nsuri, qname, doctype)
  499. def loadDocument(self, data):
  500. """Load an xml file from a file-like object and return a DOM
  501. document instance."""
  502. return xml.dom.minidom.parse(data)
  503. def loadFromURL(self, url):
  504. """Load an xml file from a URL and return a DOM document."""
  505. file = urlopen(url)
  506. try:
  507. result = self.loadDocument(file)
  508. except Exception, ex:
  509. file.close()
  510. raise ParseError(('Failed to load document %s' %url,) + ex.args)
  511. else:
  512. file.close()
  513. return result
  514. DOM = DOM()
  515. class MessageInterface:
  516. '''Higher Level Interface, delegates to DOM singleton, must
  517. be subclassed and implement all methods that throw NotImplementedError.
  518. '''
  519. def __init__(self, sw):
  520. '''Constructor, May be extended, do not override.
  521. sw -- soapWriter instance
  522. '''
  523. self.sw = None
  524. if type(sw) != weakref.ReferenceType and sw is not None:
  525. self.sw = weakref.ref(sw)
  526. else:
  527. self.sw = sw
  528. def AddCallback(self, func, *arglist):
  529. self.sw().AddCallback(func, *arglist)
  530. def Known(self, obj):
  531. return self.sw().Known(obj)
  532. def Forget(self, obj):
  533. return self.sw().Forget(obj)
  534. def canonicalize(self):
  535. '''canonicalize the underlying DOM, and return as string.
  536. '''
  537. raise NotImplementedError, ''
  538. def createDocument(self, namespaceURI=SOAP.ENV, localName='Envelope'):
  539. '''create Document
  540. '''
  541. raise NotImplementedError, ''
  542. def createAppendElement(self, namespaceURI, localName):
  543. '''create and append element(namespaceURI,localName), and return
  544. the node.
  545. '''
  546. raise NotImplementedError, ''
  547. def findNamespaceURI(self, qualifiedName):
  548. raise NotImplementedError, ''
  549. def resolvePrefix(self, prefix):
  550. raise NotImplementedError, ''
  551. def setAttributeNS(self, namespaceURI, localName, value):
  552. '''set attribute (namespaceURI, localName)=value
  553. '''
  554. raise NotImplementedError, ''
  555. def setAttributeType(self, namespaceURI, localName):
  556. '''set attribute xsi:type=(namespaceURI, localName)
  557. '''
  558. raise NotImplementedError, ''
  559. def setNamespaceAttribute(self, namespaceURI, prefix):
  560. '''set namespace attribute xmlns:prefix=namespaceURI
  561. '''
  562. raise NotImplementedError, ''
  563. class ElementProxy(Base, MessageInterface):
  564. '''
  565. '''
  566. _soap_env_prefix = 'SOAP-ENV'
  567. _soap_enc_prefix = 'SOAP-ENC'
  568. _zsi_prefix = 'ZSI'
  569. _xsd_prefix = 'xsd'
  570. _xsi_prefix = 'xsi'
  571. _xml_prefix = 'xml'
  572. _xmlns_prefix = 'xmlns'
  573. _soap_env_nsuri = SOAP.ENV
  574. _soap_enc_nsuri = SOAP.ENC
  575. _zsi_nsuri = ZSI_SCHEMA_URI
  576. _xsd_nsuri = SCHEMA.XSD3
  577. _xsi_nsuri = SCHEMA.XSI3
  578. _xml_nsuri = XMLNS.XML
  579. _xmlns_nsuri = XMLNS.BASE
  580. standard_ns = {\
  581. _xml_prefix:_xml_nsuri,
  582. _xmlns_prefix:_xmlns_nsuri
  583. }
  584. reserved_ns = {\
  585. _soap_env_prefix:_soap_env_nsuri,
  586. _soap_enc_prefix:_soap_enc_nsuri,
  587. _zsi_prefix:_zsi_nsuri,
  588. _xsd_prefix:_xsd_nsuri,
  589. _xsi_prefix:_xsi_nsuri,
  590. }
  591. name = None
  592. namespaceURI = None
  593. def __init__(self, sw, message=None):
  594. '''Initialize.
  595. sw -- SoapWriter
  596. '''
  597. self._indx = 0
  598. MessageInterface.__init__(self, sw)
  599. Base.__init__(self)
  600. self._dom = DOM
  601. self.node = None
  602. if type(message) in (types.StringType,types.UnicodeType):
  603. self.loadFromString(message)
  604. elif isinstance(message, ElementProxy):
  605. self.node = message._getNode()
  606. else:
  607. self.node = message
  608. self.processorNss = self.standard_ns.copy()
  609. self.processorNss.update(self.reserved_ns)
  610. def __str__(self):
  611. return self.toString()
  612. def evaluate(self, expression, processorNss=None):
  613. '''expression -- XPath compiled expression
  614. '''
  615. from Ft.Xml import XPath
  616. if not processorNss:
  617. context = XPath.Context.Context(self.node, processorNss=self.processorNss)
  618. else:
  619. context = XPath.Context.Context(self.node, processorNss=processorNss)
  620. nodes = expression.evaluate(context)
  621. return map(lambda node: ElementProxy(self.sw,node), nodes)
  622. #############################################
  623. # Methods for checking/setting the
  624. # classes (namespaceURI,name) node.
  625. #############################################
  626. def checkNode(self, namespaceURI=None, localName=None):
  627. '''
  628. namespaceURI -- namespace of element
  629. localName -- local name of element
  630. '''
  631. namespaceURI = namespaceURI or self.namespaceURI
  632. localName = localName or self.name
  633. check = False
  634. if localName and self.node:
  635. check = self._dom.isElement(self.node, localName, namespaceURI)
  636. if not check:
  637. raise NamespaceError, 'unexpected node type %s, expecting %s' %(self.node, localName)
  638. def setNode(self, node=None):
  639. if node:
  640. if isinstance(node, ElementProxy):
  641. self.node = node._getNode()
  642. else:
  643. self.node = node
  644. elif self.node:
  645. node = self._dom.getElement(self.node, self.name, self.namespaceURI, default=None)
  646. if not node:
  647. raise NamespaceError, 'cant find element (%s,%s)' %(self.namespaceURI,self.name)
  648. self.node = node
  649. else:
  650. #self.node = self._dom.create(self.node, self.name, self.namespaceURI, default=None)
  651. self.createDocument(self.namespaceURI, localName=self.name, doctype=None)
  652. self.checkNode()
  653. #############################################
  654. # Wrapper Methods for direct DOM Element Node access
  655. #############################################
  656. def _getNode(self):
  657. return self.node
  658. def _getElements(self):
  659. return self._dom.getElements(self.node, name=None)
  660. def _getOwnerDocument(self):
  661. return self.node.ownerDocument or self.node
  662. def _getUniquePrefix(self):
  663. '''I guess we need to resolve all potential prefixes
  664. because when the current node is attached it copies the
  665. namespaces into the parent node.
  666. '''
  667. while 1:
  668. self._indx += 1
  669. prefix = 'ns%d' %self._indx
  670. try:
  671. self._dom.findNamespaceURI(prefix, self._getNode())
  672. except DOMException, ex:
  673. break
  674. return prefix
  675. def _getPrefix(self, node, nsuri):
  676. '''
  677. Keyword arguments:
  678. node -- DOM Element Node
  679. nsuri -- namespace of attribute value
  680. '''
  681. try:
  682. if node and (node.nodeType == node.ELEMENT_NODE) and \
  683. (nsuri == self._dom.findDefaultNS(node)):
  684. return None
  685. except DOMException, ex:
  686. pass
  687. if nsuri == XMLNS.XML:
  688. return self._xml_prefix
  689. if node.nodeType == Node.ELEMENT_NODE:
  690. for attr in node.attributes.values():
  691. if attr.namespaceURI == XMLNS.BASE \
  692. and nsuri == attr.value:
  693. return attr.localName
  694. else:
  695. if node.parentNode:
  696. return self._getPrefix(node.parentNode, nsuri)
  697. raise NamespaceError, 'namespaceURI "%s" is not defined' %nsuri
  698. def _appendChild(self, node):
  699. '''
  700. Keyword arguments:
  701. node -- DOM Element Node
  702. '''
  703. if node is None:
  704. raise TypeError, 'node is None'
  705. self.node.appendChild(node)
  706. def _insertBefore(self, newChild, refChild):
  707. '''
  708. Keyword arguments:
  709. child -- DOM Element Node to insert
  710. refChild -- DOM Element Node
  711. '''
  712. self.node.insertBefore(newChild, refChild)
  713. def _setAttributeNS(self, namespaceURI, qualifiedName, value):
  714. '''
  715. Keyword arguments:
  716. namespaceURI -- namespace of attribute
  717. qualifiedName -- qualified name of new attribute value
  718. value -- value of attribute
  719. '''
  720. self.node.setAttributeNS(namespaceURI, qualifiedName, value)
  721. #############################################
  722. #General Methods
  723. #############################################
  724. def isFault(self):
  725. '''check to see if this is a soap:fault message.
  726. '''
  727. return False
  728. def getPrefix(self, namespaceURI):
  729. try:
  730. prefix = self._getPrefix(node=self.node, nsuri=namespaceURI)
  731. except NamespaceError, ex:
  732. prefix = self._getUniquePrefix()
  733. self.setNamespaceAttribute(prefix, namespaceURI)
  734. return prefix
  735. def getDocument(self):
  736. return self._getOwnerDocument()
  737. def setDocument(self, document):
  738. self.node = document
  739. def importFromString(self, xmlString):
  740. doc = self._dom.loadDocument(StringIO(xmlString))
  741. node = self._dom.getElement(doc, name=None)
  742. clone = self.importNode(node)
  743. self._appendChild(clone)
  744. def importNode(self, node):
  745. if isinstance(node, ElementProxy):
  746. node = node._getNode()
  747. return self._dom.importNode(self._getOwnerDocument(), node, deep=1)
  748. def loadFromString(self, data):
  749. self.node = self._dom.loadDocument(StringIO(data))
  750. def canonicalize(self):
  751. return Canonicalize(self.node)
  752. def toString(self):
  753. return self.canonicalize()
  754. def createDocument(self, namespaceURI, localName, doctype=None):
  755. prefix = self._soap_env_prefix
  756. if namespaceURI != self.reserved_ns[prefix]:
  757. raise KeyError, 'only support creation of document in %s' %self.reserved_ns[prefix]
  758. qualifiedName = '%s:%s' %(prefix,localName)
  759. document = self._dom.createDocument(nsuri=namespaceURI, qname=qualifiedName, doctype=doctype)
  760. self.node = document.childNodes[0]
  761. #set up reserved namespace attributes
  762. for prefix,nsuri in self.reserved_ns.items():
  763. self._setAttributeNS(namespaceURI=self._xmlns_nsuri,
  764. qualifiedName='%s:%s' %(self._xmlns_prefix,prefix),
  765. value=nsuri)
  766. #############################################
  767. #Methods for attributes
  768. #############################################
  769. def hasAttribute(self, namespaceURI, localName):
  770. return self._dom.hasAttr(self._getNode(), name=localName, nsuri=namespaceURI)
  771. def setAttributeType(self, namespaceURI, localName):
  772. '''set xsi:type
  773. Keyword arguments:
  774. namespaceURI -- namespace of attribute value
  775. localName -- name of new attribute value
  776. '''
  777. self.logger.debug('setAttributeType: (%s,%s)', namespaceURI, localName)
  778. value = localName
  779. if namespaceURI:
  780. value = '%s:%s' %(self.getPrefix(namespaceURI),localName)
  781. self._setAttributeNS(self._xsi_nsuri, '%s:type' %self._xsi_prefix, value)
  782. def createAttributeNS(self, namespace, name, value):
  783. document = self._getOwnerDocument()
  784. attrNode = document.createAttributeNS(namespace, name, value)
  785. def setAttributeNS(self, namespaceURI, localName, value):
  786. '''
  787. Keyword arguments:
  788. namespaceURI -- namespace of attribute to create, None is for
  789. attributes in no namespace.
  790. localName -- local name of new attribute
  791. value -- value of new attribute
  792. '''
  793. prefix = None
  794. if namespaceURI:
  795. try:
  796. prefix = self.getPrefix(namespaceURI)
  797. except KeyError, ex:
  798. prefix = 'ns2'
  799. self.setNamespaceAttribute(prefix, namespaceURI)
  800. qualifiedName = localName
  801. if prefix:
  802. qualifiedName = '%s:%s' %(prefix, localName)
  803. self._setAttributeNS(namespaceURI, qualifiedName, value)
  804. def setNamespaceAttribute(self, prefix, namespaceURI):
  805. '''
  806. Keyword arguments:
  807. prefix -- xmlns prefix
  808. namespaceURI -- value of prefix
  809. '''
  810. self._setAttributeNS(XMLNS.BASE, 'xmlns:%s' %prefix, namespaceURI)
  811. #############################################
  812. #Methods for elements
  813. #############################################
  814. def createElementNS(self, namespace, qname):
  815. '''
  816. Keyword arguments:
  817. namespace -- namespace of element to create
  818. qname -- qualified name of new element
  819. '''
  820. document = self._getOwnerDocument()
  821. node = document.createElementNS(namespace, qname)
  822. return ElementProxy(self.sw, node)
  823. def createAppendSetElement(self, namespaceURI, localName, prefix=None):
  824. '''Create a new element (namespaceURI,name), append it
  825. to current node, then set it to be the current node.
  826. Keyword arguments:
  827. namespaceURI -- namespace of element to create
  828. localName -- local name of new element
  829. prefix -- if namespaceURI is not defined, declare prefix. defaults
  830. to 'ns1' if left unspecified.
  831. '''
  832. node = self.createAppendElement(namespaceURI, localName, prefix=None)
  833. node=node._getNode()
  834. self._setNode(node._getNode())
  835. def createAppendElement(self, namespaceURI, localName, prefix=None):
  836. '''Create a new element (namespaceURI,name), append it
  837. to current node, and return the newly created node.
  838. Keyword arguments:
  839. namespaceURI -- namespace of element to create
  840. localName -- local name of new element
  841. prefix -- if namespaceURI is not defined, declare prefix. defaults
  842. to 'ns1' if left unspecified.
  843. '''
  844. declare = False
  845. qualifiedName = localName
  846. if namespaceURI:
  847. try:
  848. prefix = self.getPrefix(namespaceURI)
  849. except:
  850. declare = True
  851. prefix = prefix or self._getUniquePrefix()
  852. if prefix:
  853. qualifiedName = '%s:%s' %(prefix, localName)
  854. node = self.createElementNS(namespaceURI, qualifiedName)
  855. if declare:
  856. node._setAttributeNS(XMLNS.BASE, 'xmlns:%s' %prefix, namespaceURI)
  857. self._appendChild(node=node._getNode())
  858. return node
  859. def createInsertBefore(self, namespaceURI, localName, refChild):
  860. qualifiedName = localName
  861. prefix = self.getPrefix(namespaceURI)
  862. if prefix:
  863. qualifiedName = '%s:%s' %(prefix, localName)
  864. node = self.createElementNS(namespaceURI, qualifiedName)
  865. self._insertBefore(newChild=node._getNode(), refChild=refChild._getNode())
  866. return node
  867. def getElement(self, namespaceURI, localName):
  868. '''
  869. Keyword arguments:
  870. namespaceURI -- namespace of element
  871. localName -- local name of element
  872. '''
  873. node = self._dom.getElement(self.node, localName, namespaceURI, default=None)
  874. if node:
  875. return ElementProxy(self.sw, node)
  876. return None
  877. def getAttributeValue(self, namespaceURI, localName):
  878. '''
  879. Keyword arguments:
  880. namespaceURI -- namespace of attribute
  881. localName -- local name of attribute
  882. '''
  883. if self.hasAttribute(namespaceURI, localName):
  884. attr = self.node.getAttributeNodeNS(namespaceURI,localName)
  885. return attr.value
  886. return None
  887. def getValue(self):
  888. return self._dom.getElementText(self.node, preserve_ws=True)
  889. #############################################
  890. #Methods for text nodes
  891. #############################################
  892. def createAppendTextNode(self, pyobj):
  893. node = self.createTextNode(pyobj)
  894. self._appendChild(node=node._getNode())
  895. return node
  896. def createTextNode(self, pyobj):
  897. document = self._getOwnerDocument()
  898. node = document.createTextNode(pyobj)
  899. return ElementProxy(self.sw, node)
  900. #############################################
  901. #Methods for retrieving namespaceURI's
  902. #############################################
  903. def findNamespaceURI(self, qualifiedName):
  904. parts = SplitQName(qualifiedName)
  905. element = self._getNode()
  906. if len(parts) == 1:
  907. return (self._dom.findTargetNS(element), value)
  908. return self._dom.findNamespaceURI(parts[0], element)
  909. def resolvePrefix(self, prefix):
  910. element = self._getNode()
  911. return self._dom.findNamespaceURI(prefix, element)
  912. def getSOAPEnvURI(self):
  913. return self._soap_env_nsuri
  914. def isEmpty(self):
  915. return not self.node
  916. class Collection(UserDict):
  917. """Helper class for maintaining ordered named collections."""
  918. default = lambda self,k: k.name
  919. def __init__(self, parent, key=None):
  920. UserDict.__init__(self)
  921. self.parent = weakref.ref(parent)
  922. self.list = []
  923. self._func = key or self.default
  924. def __getitem__(self, key):
  925. if type(key) is type(1):
  926. return self.list[key]
  927. return self.data[key]
  928. def __setitem__(self, key, item):
  929. item.parent = weakref.ref(self)
  930. self.list.append(item)
  931. self.data[key] = item
  932. def keys(self):
  933. return map(lambda i: self._func(i), self.list)
  934. def items(self):
  935. return map(lambda i: (self._func(i), i), self.list)
  936. def values(self):
  937. return self.list
  938. class CollectionNS(UserDict):
  939. """Helper class for maintaining ordered named collections."""
  940. default = lambda self,k: k.name
  941. def __init__(self, parent, key=None):
  942. UserDict.__init__(self)
  943. self.parent = weakref.ref(parent)
  944. self.targetNamespace = None
  945. self.list = []
  946. self._func = key or self.default
  947. def __getitem__(self, key):
  948. self.targetNamespace = self.parent().targetNamespace
  949. if type(key) is types.IntType:
  950. return self.list[key]
  951. elif self.__isSequence(key):
  952. nsuri,name = key
  953. return self.data[nsuri][name]
  954. return self.data[self.parent().targetNamespace][key]
  955. def __setitem__(self, key, item):
  956. item.parent = weakref.ref(self)
  957. self.list.append(item)
  958. targetNamespace = getattr(item, 'targetNamespace', self.parent().targetNamespace)
  959. if not self.data.has_key(targetNamespace):
  960. self.data[targetNamespace] = {}
  961. self.data[targetNamespace][key] = item
  962. def __isSequence(self, key):
  963. return (type(key) in (types.TupleType,types.ListType) and len(key) == 2)
  964. def keys(self):
  965. keys = []
  966. for tns in self.data.keys():
  967. keys.append(map(lambda i: (tns,self._func(i)), self.data[tns].values()))
  968. return keys
  969. def items(self):
  970. return map(lambda i: (self._func(i), i), self.list)
  971. def values(self):
  972. return self.list
  973. # This is a runtime guerilla patch for pulldom (used by minidom) so
  974. # that xml namespace declaration attributes are not lost in parsing.
  975. # We need them to do correct QName linking for XML Schema and WSDL.
  976. # The patch has been submitted to SF for the next Python version.
  977. from xml.dom.pulldom import PullDOM, START_ELEMENT
  978. if 1:
  979. def startPrefixMapping(self, prefix, uri):
  980. if not hasattr(self, '_xmlns_attrs'):
  981. self._xmlns_attrs = []
  982. self._xmlns_attrs.append((prefix or 'xmlns', uri))
  983. self._ns_contexts.append(self._current_context.copy())
  984. self._current_context[uri] = prefix or ''
  985. PullDOM.startPrefixMapping = startPrefixMapping
  986. def startElementNS(self, name, tagName , attrs):
  987. # Retrieve xml namespace declaration attributes.
  988. xmlns_uri = 'http://www.w3.org/2000/xmlns/'
  989. xmlns_attrs = getattr(self, '_xmlns_attrs', None)
  990. if xmlns_attrs is not None:
  991. for aname, value in xmlns_attrs:
  992. attrs._attrs[(xmlns_uri, aname)] = value
  993. self._xmlns_attrs = []
  994. uri, localname = name
  995. if uri:
  996. # When using namespaces, the reader may or may not
  997. # provide us with the original name. If not, create
  998. # *a* valid tagName from the current context.
  999. if tagName is None:
  1000. prefix = self._current_context[uri]
  1001. if prefix:
  1002. tagName = prefix + ":" + localname
  1003. else:
  1004. tagName = localname
  1005. if self.document:
  1006. node = self.document.createElementNS(uri, tagName)
  1007. else:
  1008. node = self.buildDocument(uri, tagName)
  1009. else:
  1010. # When the tagname is not prefixed, it just appears as
  1011. # localname
  1012. if self.document:
  1013. node = self.document.createElement(localname)
  1014. else:
  1015. node = self.buildDocument(None, localname)
  1016. for aname,value in attrs.items():
  1017. a_uri, a_localname = aname
  1018. if a_uri == xmlns_uri:
  1019. if a_localname == 'xmlns':
  1020. qname = a_localname
  1021. else:
  1022. qname = 'xmlns:' + a_localname
  1023. attr = self.document.createAttributeNS(a_uri, qname)
  1024. node.setAttributeNodeNS(attr)
  1025. elif a_uri:
  1026. prefix = self._current_context[a_uri]
  1027. if prefix:
  1028. qname = prefix + ":" + a_localname
  1029. else:
  1030. qname = a_localname
  1031. attr = self.document.createAttributeNS(a_uri, qname)
  1032. node.setAttributeNodeNS(attr)
  1033. else:
  1034. attr = self.document.createAttribute(a_localname)
  1035. node.setAttributeNode(attr)
  1036. attr.value = value
  1037. self.lastEvent[1] = [(START_ELEMENT, node), None]
  1038. self.lastEvent = self.lastEvent[1]
  1039. self.push(node)
  1040. PullDOM.startElementNS = startElementNS
  1041. #
  1042. # This is a runtime guerilla patch for minidom so
  1043. # that xmlns prefixed attributes dont raise AttributeErrors
  1044. # during cloning.
  1045. #
  1046. # Namespace declarations can appear in any start-tag, must look for xmlns
  1047. # prefixed attribute names during cloning.
  1048. #
  1049. # key (attr.namespaceURI, tag)
  1050. # ('http://www.w3.org/2000/xmlns/', u'xsd') <xml.dom.minidom.Attr instance at 0x82227c4>
  1051. # ('http://www.w3.org/2000/xmlns/', 'xmlns') <xml.dom.minidom.Attr instance at 0x8414b3c>
  1052. #
  1053. # xml.dom.minidom.Attr.nodeName = xmlns:xsd
  1054. # xml.dom.minidom.Attr.value = = http://www.w3.org/2001/XMLSchema
  1055. if 1:
  1056. def _clone_node(node, deep, newOwnerDocument):
  1057. """
  1058. Clone a node and give it the new owner document.
  1059. Called by Node.cloneNode and Document.importNode
  1060. """
  1061. if node.ownerDocument.isSameNode(newOwnerDocument):
  1062. operation = xml.dom.UserDataHandler.NODE_CLONED
  1063. else:
  1064. operation = xml.dom.UserDataHandler.NODE_IMPORTED
  1065. if node.nodeType == xml.dom.minidom.Node.ELEMENT_NODE:
  1066. clone = newOwnerDocument.createElementNS(node.namespaceURI,
  1067. node.nodeName)
  1068. for attr in node.attributes.values():
  1069. clone.setAttributeNS(attr.namespaceURI, attr.nodeName, attr.value)
  1070. prefix, tag = xml.dom.minidom._nssplit(attr.nodeName)
  1071. if prefix == 'xmlns':
  1072. a = clone.getAttributeNodeNS(attr.namespaceURI, tag)
  1073. elif prefix:
  1074. a = clone.getAttributeNodeNS(attr.namespaceURI, tag)
  1075. else:
  1076. a = clone.getAttributeNodeNS(attr.namespaceURI, attr.nodeName)
  1077. a.specified = attr.specified
  1078. if deep:
  1079. for child in node.childNodes:
  1080. c = xml.dom.minidom._clone_node(child, deep, newOwnerDocument)
  1081. clone.appendChild(c)
  1082. elif node.nodeType == xml.dom.minidom.Node.DOCUMENT_FRAGMENT_NODE:
  1083. clone = newOwnerDocument.createDocumentFragment()
  1084. if deep:
  1085. for child in node.childNodes:
  1086. c = xml.dom.minidom._clone_node(child, deep, newOwnerDocument)
  1087. clone.appendChild(c)
  1088. elif node.nodeType == xml.dom.minidom.Node.TEXT_NODE:
  1089. clone = newOwnerDocument.createTextNode(node.data)
  1090. elif node.nodeType == xml.dom.minidom.Node.CDATA_SECTION_NODE:
  1091. clone = newOwnerDocument.createCDATASection(node.data)
  1092. elif node.nodeType == xml.dom.minidom.Node.PROCESSING_INSTRUCTION_NODE:
  1093. clone = newOwnerDocument.createProcessingInstruction(node.target,
  1094. node.data)
  1095. elif node.nodeType == xml.dom.minidom.Node.COMMENT_NODE:
  1096. clone = newOwnerDocument.createComment(node.data)
  1097. elif node.nodeType == xml.dom.minidom.Node.ATTRIBUTE_NODE:
  1098. clone = newOwnerDocument.createAttributeNS(node.namespaceURI,
  1099. node.nodeName)
  1100. clone.specified = True
  1101. clone.value = node.value
  1102. elif node.nodeType == xml.dom.minidom.Node.DOCUMENT_TYPE_NODE:
  1103. assert node.ownerDocument is not newOwnerDocument
  1104. operation = xml.dom.UserDataHandler.NODE_IMPORTED
  1105. clone = newOwnerDocument.implementation.createDocumentType(
  1106. node.name, node.publicId, node.systemId)
  1107. clone.ownerDocument = newOwnerDocument
  1108. if deep:
  1109. clone.entities._seq = []
  1110. clone.notations._seq = []
  1111. for n in node.notations._seq:
  1112. notation = xml.dom.minidom.Notation(n.nodeName, n.publicId, n.systemId)
  1113. notation.ownerDocument = newOwnerDocument
  1114. clone.notations._seq.append(notation)
  1115. if hasattr(n, '_call_user_data_handler'):
  1116. n._call_user_data_handler(operation, n, notation)
  1117. for e in node.entities._seq:
  1118. entity = xml.dom.minidom.Entity(e.nodeName, e.publicId, e.systemId,
  1119. e.notationName)
  1120. entity.actualEncoding = e.actualEncoding
  1121. entity.encoding = e.encoding
  1122. entity.version = e.version
  1123. entity.ownerDocument = newOwnerDocument
  1124. clone.entities._seq.append(entity)
  1125. if hasattr(e, '_call_user_data_handler'):
  1126. e._call_user_data_handler(operation, n, entity)
  1127. else:
  1128. # Note the cloning of Document and DocumentType nodes is
  1129. # implemenetation specific. minidom handles those cases
  1130. # directly in the cloneNode() methods.
  1131. raise xml.dom.NotSupportedErr("Cannot clone node %s" % repr(node))
  1132. # Check for _call_user_data_handler() since this could conceivably
  1133. # used with other DOM implementations (one of the FourThought
  1134. # DOMs, perhaps?).
  1135. if hasattr(node, '_call_user_data_handler'):
  1136. node._call_user_data_handler(operation, node, clone)
  1137. return clone
  1138. xml.dom.minidom._clone_node = _clone_node