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.
 
 
 

1343 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 is None:
  414. raise DOMException('Value for prefix %s not found.' % prefix)
  415. if node.nodeType != ELEMENT_NODE:
  416. node = node.parentNode
  417. continue
  418. result = node._attrsNS.get(attrkey, None)
  419. if result is not None:
  420. return result.value
  421. if hasattr(node, '__imported__'):
  422. raise DOMException('Value for prefix %s not found.' % prefix)
  423. node = node.parentNode
  424. if node.nodeType == DOCUMENT_NODE:
  425. raise DOMException('Value for prefix %s not found.' % prefix)
  426. def findDefaultNS(self, node):
  427. """Return the current default namespace uri for the given node."""
  428. attrkey = (self.NS_XMLNS, 'xmlns')
  429. DOCUMENT_NODE = node.DOCUMENT_NODE
  430. ELEMENT_NODE = node.ELEMENT_NODE
  431. while 1:
  432. if node.nodeType != ELEMENT_NODE:
  433. node = node.parentNode
  434. continue
  435. result = node._attrsNS.get(attrkey, None)
  436. if result is not None:
  437. return result.value
  438. if hasattr(node, '__imported__'):
  439. raise DOMException('Cannot determine default namespace.')
  440. node = node.parentNode
  441. if node.nodeType == DOCUMENT_NODE:
  442. raise DOMException('Cannot determine default namespace.')
  443. def findTargetNS(self, node):
  444. """Return the defined target namespace uri for the given node."""
  445. attrget = self.getAttr
  446. attrkey = (self.NS_XMLNS, 'xmlns')
  447. DOCUMENT_NODE = node.DOCUMENT_NODE
  448. ELEMENT_NODE = node.ELEMENT_NODE
  449. while 1:
  450. if node.nodeType != ELEMENT_NODE:
  451. node = node.parentNode
  452. continue
  453. result = attrget(node, 'targetNamespace', default=None)
  454. if result is not None:
  455. return result
  456. node = node.parentNode
  457. if node.nodeType == DOCUMENT_NODE:
  458. raise DOMException('Cannot determine target namespace.')
  459. def getTypeRef(self, element):
  460. """Return (namespaceURI, name) for a type attribue of the given
  461. element, or None if the element does not have a type attribute."""
  462. typeattr = self.getAttr(element, 'type', default=None)
  463. if typeattr is None:
  464. return None
  465. parts = typeattr.split(':', 1)
  466. if len(parts) == 2:
  467. nsuri = self.findNamespaceURI(parts[0], element)
  468. else:
  469. nsuri = self.findDefaultNS(element)
  470. return (nsuri, parts[1])
  471. def importNode(self, document, node, deep=0):
  472. """Implements (well enough for our purposes) DOM node import."""
  473. nodetype = node.nodeType
  474. if nodetype in (node.DOCUMENT_NODE, node.DOCUMENT_TYPE_NODE):
  475. raise DOMException('Illegal node type for importNode')
  476. if nodetype == node.ENTITY_REFERENCE_NODE:
  477. deep = 0
  478. clone = node.cloneNode(deep)
  479. self._setOwnerDoc(document, clone)
  480. clone.__imported__ = 1
  481. return clone
  482. def _setOwnerDoc(self, document, node):
  483. node.ownerDocument = document
  484. for child in node.childNodes:
  485. self._setOwnerDoc(document, child)
  486. def nsUriMatch(self, value, wanted, strict=0, tt=type(())):
  487. """Return a true value if two namespace uri values match."""
  488. if value == wanted or (type(wanted) is tt) and value in wanted:
  489. return 1
  490. if not strict:
  491. wanted = type(wanted) is tt and wanted or (wanted,)
  492. value = value[-1:] != '/' and value or value[:-1]
  493. for item in wanted:
  494. if item == value or item[:-1] == value:
  495. return 1
  496. return 0
  497. def createDocument(self, nsuri, qname, doctype=None):
  498. """Create a new writable DOM document object."""
  499. impl = xml.dom.minidom.getDOMImplementation()
  500. return impl.createDocument(nsuri, qname, doctype)
  501. def loadDocument(self, data):
  502. """Load an xml file from a file-like object and return a DOM
  503. document instance."""
  504. return xml.dom.minidom.parse(data)
  505. def loadFromURL(self, url):
  506. """Load an xml file from a URL and return a DOM document."""
  507. file = urlopen(url)
  508. try:
  509. result = self.loadDocument(file)
  510. except Exception, ex:
  511. file.close()
  512. raise ParseError(('Failed to load document %s' %url,) + ex.args)
  513. else:
  514. file.close()
  515. return result
  516. DOM = DOM()
  517. class MessageInterface:
  518. '''Higher Level Interface, delegates to DOM singleton, must
  519. be subclassed and implement all methods that throw NotImplementedError.
  520. '''
  521. def __init__(self, sw):
  522. '''Constructor, May be extended, do not override.
  523. sw -- soapWriter instance
  524. '''
  525. self.sw = None
  526. if type(sw) != weakref.ReferenceType and sw is not None:
  527. self.sw = weakref.ref(sw)
  528. else:
  529. self.sw = sw
  530. def AddCallback(self, func, *arglist):
  531. self.sw().AddCallback(func, *arglist)
  532. def Known(self, obj):
  533. return self.sw().Known(obj)
  534. def Forget(self, obj):
  535. return self.sw().Forget(obj)
  536. def canonicalize(self):
  537. '''canonicalize the underlying DOM, and return as string.
  538. '''
  539. raise NotImplementedError, ''
  540. def createDocument(self, namespaceURI=SOAP.ENV, localName='Envelope'):
  541. '''create Document
  542. '''
  543. raise NotImplementedError, ''
  544. def createAppendElement(self, namespaceURI, localName):
  545. '''create and append element(namespaceURI,localName), and return
  546. the node.
  547. '''
  548. raise NotImplementedError, ''
  549. def findNamespaceURI(self, qualifiedName):
  550. raise NotImplementedError, ''
  551. def resolvePrefix(self, prefix):
  552. raise NotImplementedError, ''
  553. def setAttributeNS(self, namespaceURI, localName, value):
  554. '''set attribute (namespaceURI, localName)=value
  555. '''
  556. raise NotImplementedError, ''
  557. def setAttributeType(self, namespaceURI, localName):
  558. '''set attribute xsi:type=(namespaceURI, localName)
  559. '''
  560. raise NotImplementedError, ''
  561. def setNamespaceAttribute(self, namespaceURI, prefix):
  562. '''set namespace attribute xmlns:prefix=namespaceURI
  563. '''
  564. raise NotImplementedError, ''
  565. class ElementProxy(Base, MessageInterface):
  566. '''
  567. '''
  568. _soap_env_prefix = 'SOAP-ENV'
  569. _soap_enc_prefix = 'SOAP-ENC'
  570. _zsi_prefix = 'ZSI'
  571. _xsd_prefix = 'xsd'
  572. _xsi_prefix = 'xsi'
  573. _xml_prefix = 'xml'
  574. _xmlns_prefix = 'xmlns'
  575. _soap_env_nsuri = SOAP.ENV
  576. _soap_enc_nsuri = SOAP.ENC
  577. _zsi_nsuri = ZSI_SCHEMA_URI
  578. _xsd_nsuri = SCHEMA.XSD3
  579. _xsi_nsuri = SCHEMA.XSI3
  580. _xml_nsuri = XMLNS.XML
  581. _xmlns_nsuri = XMLNS.BASE
  582. standard_ns = {\
  583. _xml_prefix:_xml_nsuri,
  584. _xmlns_prefix:_xmlns_nsuri
  585. }
  586. reserved_ns = {\
  587. _soap_env_prefix:_soap_env_nsuri,
  588. _soap_enc_prefix:_soap_enc_nsuri,
  589. _zsi_prefix:_zsi_nsuri,
  590. _xsd_prefix:_xsd_nsuri,
  591. _xsi_prefix:_xsi_nsuri,
  592. }
  593. name = None
  594. namespaceURI = None
  595. def __init__(self, sw, message=None):
  596. '''Initialize.
  597. sw -- SoapWriter
  598. '''
  599. self._indx = 0
  600. MessageInterface.__init__(self, sw)
  601. Base.__init__(self)
  602. self._dom = DOM
  603. self.node = None
  604. if type(message) in (types.StringType,types.UnicodeType):
  605. self.loadFromString(message)
  606. elif isinstance(message, ElementProxy):
  607. self.node = message._getNode()
  608. else:
  609. self.node = message
  610. self.processorNss = self.standard_ns.copy()
  611. self.processorNss.update(self.reserved_ns)
  612. def __str__(self):
  613. return self.toString()
  614. def evaluate(self, expression, processorNss=None):
  615. '''expression -- XPath compiled expression
  616. '''
  617. from Ft.Xml import XPath
  618. if not processorNss:
  619. context = XPath.Context.Context(self.node, processorNss=self.processorNss)
  620. else:
  621. context = XPath.Context.Context(self.node, processorNss=processorNss)
  622. nodes = expression.evaluate(context)
  623. return map(lambda node: ElementProxy(self.sw,node), nodes)
  624. #############################################
  625. # Methods for checking/setting the
  626. # classes (namespaceURI,name) node.
  627. #############################################
  628. def checkNode(self, namespaceURI=None, localName=None):
  629. '''
  630. namespaceURI -- namespace of element
  631. localName -- local name of element
  632. '''
  633. namespaceURI = namespaceURI or self.namespaceURI
  634. localName = localName or self.name
  635. check = False
  636. if localName and self.node:
  637. check = self._dom.isElement(self.node, localName, namespaceURI)
  638. if not check:
  639. raise NamespaceError, 'unexpected node type %s, expecting %s' %(self.node, localName)
  640. def setNode(self, node=None):
  641. if node:
  642. if isinstance(node, ElementProxy):
  643. self.node = node._getNode()
  644. else:
  645. self.node = node
  646. elif self.node:
  647. node = self._dom.getElement(self.node, self.name, self.namespaceURI, default=None)
  648. if not node:
  649. raise NamespaceError, 'cant find element (%s,%s)' %(self.namespaceURI,self.name)
  650. self.node = node
  651. else:
  652. #self.node = self._dom.create(self.node, self.name, self.namespaceURI, default=None)
  653. self.createDocument(self.namespaceURI, localName=self.name, doctype=None)
  654. self.checkNode()
  655. #############################################
  656. # Wrapper Methods for direct DOM Element Node access
  657. #############################################
  658. def _getNode(self):
  659. return self.node
  660. def _getElements(self):
  661. return self._dom.getElements(self.node, name=None)
  662. def _getOwnerDocument(self):
  663. return self.node.ownerDocument or self.node
  664. def _getUniquePrefix(self):
  665. '''I guess we need to resolve all potential prefixes
  666. because when the current node is attached it copies the
  667. namespaces into the parent node.
  668. '''
  669. while 1:
  670. self._indx += 1
  671. prefix = 'ns%d' %self._indx
  672. try:
  673. self._dom.findNamespaceURI(prefix, self._getNode())
  674. except DOMException, ex:
  675. break
  676. return prefix
  677. def _getPrefix(self, node, nsuri):
  678. '''
  679. Keyword arguments:
  680. node -- DOM Element Node
  681. nsuri -- namespace of attribute value
  682. '''
  683. try:
  684. if node and (node.nodeType == node.ELEMENT_NODE) and \
  685. (nsuri == self._dom.findDefaultNS(node)):
  686. return None
  687. except DOMException, ex:
  688. pass
  689. if nsuri == XMLNS.XML:
  690. return self._xml_prefix
  691. if node.nodeType == Node.ELEMENT_NODE:
  692. for attr in node.attributes.values():
  693. if attr.namespaceURI == XMLNS.BASE \
  694. and nsuri == attr.value:
  695. return attr.localName
  696. else:
  697. if node.parentNode:
  698. return self._getPrefix(node.parentNode, nsuri)
  699. raise NamespaceError, 'namespaceURI "%s" is not defined' %nsuri
  700. def _appendChild(self, node):
  701. '''
  702. Keyword arguments:
  703. node -- DOM Element Node
  704. '''
  705. if node is None:
  706. raise TypeError, 'node is None'
  707. self.node.appendChild(node)
  708. def _insertBefore(self, newChild, refChild):
  709. '''
  710. Keyword arguments:
  711. child -- DOM Element Node to insert
  712. refChild -- DOM Element Node
  713. '''
  714. self.node.insertBefore(newChild, refChild)
  715. def _setAttributeNS(self, namespaceURI, qualifiedName, value):
  716. '''
  717. Keyword arguments:
  718. namespaceURI -- namespace of attribute
  719. qualifiedName -- qualified name of new attribute value
  720. value -- value of attribute
  721. '''
  722. self.node.setAttributeNS(namespaceURI, qualifiedName, value)
  723. #############################################
  724. #General Methods
  725. #############################################
  726. def isFault(self):
  727. '''check to see if this is a soap:fault message.
  728. '''
  729. return False
  730. def getPrefix(self, namespaceURI):
  731. try:
  732. prefix = self._getPrefix(node=self.node, nsuri=namespaceURI)
  733. except NamespaceError, ex:
  734. prefix = self._getUniquePrefix()
  735. self.setNamespaceAttribute(prefix, namespaceURI)
  736. return prefix
  737. def getDocument(self):
  738. return self._getOwnerDocument()
  739. def setDocument(self, document):
  740. self.node = document
  741. def importFromString(self, xmlString):
  742. doc = self._dom.loadDocument(StringIO(xmlString))
  743. node = self._dom.getElement(doc, name=None)
  744. clone = self.importNode(node)
  745. self._appendChild(clone)
  746. def importNode(self, node):
  747. if isinstance(node, ElementProxy):
  748. node = node._getNode()
  749. return self._dom.importNode(self._getOwnerDocument(), node, deep=1)
  750. def loadFromString(self, data):
  751. self.node = self._dom.loadDocument(StringIO(data))
  752. def canonicalize(self):
  753. return Canonicalize(self.node)
  754. def toString(self):
  755. return self.canonicalize()
  756. def createDocument(self, namespaceURI, localName, doctype=None):
  757. '''If specified must be a SOAP envelope, else may contruct an empty document.
  758. '''
  759. prefix = self._soap_env_prefix
  760. if namespaceURI == self.reserved_ns[prefix]:
  761. qualifiedName = '%s:%s' %(prefix,localName)
  762. elif namespaceURI is localName is None:
  763. self.node = self._dom.createDocument(None,None,None)
  764. return
  765. else:
  766. raise KeyError, 'only support creation of document in %s' %self.reserved_ns[prefix]
  767. document = self._dom.createDocument(nsuri=namespaceURI, qname=qualifiedName, doctype=doctype)
  768. self.node = document.childNodes[0]
  769. #set up reserved namespace attributes
  770. for prefix,nsuri in self.reserved_ns.items():
  771. self._setAttributeNS(namespaceURI=self._xmlns_nsuri,
  772. qualifiedName='%s:%s' %(self._xmlns_prefix,prefix),
  773. value=nsuri)
  774. #############################################
  775. #Methods for attributes
  776. #############################################
  777. def hasAttribute(self, namespaceURI, localName):
  778. return self._dom.hasAttr(self._getNode(), name=localName, nsuri=namespaceURI)
  779. def setAttributeType(self, namespaceURI, localName):
  780. '''set xsi:type
  781. Keyword arguments:
  782. namespaceURI -- namespace of attribute value
  783. localName -- name of new attribute value
  784. '''
  785. self.logger.debug('setAttributeType: (%s,%s)', namespaceURI, localName)
  786. value = localName
  787. if namespaceURI:
  788. value = '%s:%s' %(self.getPrefix(namespaceURI),localName)
  789. xsi_prefix = self.getPrefix(self._xsi_nsuri)
  790. self._setAttributeNS(self._xsi_nsuri, '%s:type' %xsi_prefix, value)
  791. def createAttributeNS(self, namespace, name, value):
  792. document = self._getOwnerDocument()
  793. attrNode = document.createAttributeNS(namespace, name, value)
  794. def setAttributeNS(self, namespaceURI, localName, value):
  795. '''
  796. Keyword arguments:
  797. namespaceURI -- namespace of attribute to create, None is for
  798. attributes in no namespace.
  799. localName -- local name of new attribute
  800. value -- value of new attribute
  801. '''
  802. prefix = None
  803. if namespaceURI:
  804. try:
  805. prefix = self.getPrefix(namespaceURI)
  806. except KeyError, ex:
  807. prefix = 'ns2'
  808. self.setNamespaceAttribute(prefix, namespaceURI)
  809. qualifiedName = localName
  810. if prefix:
  811. qualifiedName = '%s:%s' %(prefix, localName)
  812. self._setAttributeNS(namespaceURI, qualifiedName, value)
  813. def setNamespaceAttribute(self, prefix, namespaceURI):
  814. '''
  815. Keyword arguments:
  816. prefix -- xmlns prefix
  817. namespaceURI -- value of prefix
  818. '''
  819. self._setAttributeNS(XMLNS.BASE, 'xmlns:%s' %prefix, namespaceURI)
  820. #############################################
  821. #Methods for elements
  822. #############################################
  823. def createElementNS(self, namespace, qname):
  824. '''
  825. Keyword arguments:
  826. namespace -- namespace of element to create
  827. qname -- qualified name of new element
  828. '''
  829. document = self._getOwnerDocument()
  830. node = document.createElementNS(namespace, qname)
  831. return ElementProxy(self.sw, node)
  832. def createAppendSetElement(self, namespaceURI, localName, prefix=None):
  833. '''Create a new element (namespaceURI,name), append it
  834. to current node, then set it to be the current node.
  835. Keyword arguments:
  836. namespaceURI -- namespace of element to create
  837. localName -- local name of new element
  838. prefix -- if namespaceURI is not defined, declare prefix. defaults
  839. to 'ns1' if left unspecified.
  840. '''
  841. node = self.createAppendElement(namespaceURI, localName, prefix=None)
  842. node=node._getNode()
  843. self._setNode(node._getNode())
  844. def createAppendElement(self, namespaceURI, localName, prefix=None):
  845. '''Create a new element (namespaceURI,name), append it
  846. to current node, and return the newly created node.
  847. Keyword arguments:
  848. namespaceURI -- namespace of element to create
  849. localName -- local name of new element
  850. prefix -- if namespaceURI is not defined, declare prefix. defaults
  851. to 'ns1' if left unspecified.
  852. '''
  853. declare = False
  854. qualifiedName = localName
  855. if namespaceURI:
  856. try:
  857. prefix = self.getPrefix(namespaceURI)
  858. except:
  859. declare = True
  860. prefix = prefix or self._getUniquePrefix()
  861. if prefix:
  862. qualifiedName = '%s:%s' %(prefix, localName)
  863. node = self.createElementNS(namespaceURI, qualifiedName)
  864. if declare:
  865. node._setAttributeNS(XMLNS.BASE, 'xmlns:%s' %prefix, namespaceURI)
  866. self._appendChild(node=node._getNode())
  867. return node
  868. def createInsertBefore(self, namespaceURI, localName, refChild):
  869. qualifiedName = localName
  870. prefix = self.getPrefix(namespaceURI)
  871. if prefix:
  872. qualifiedName = '%s:%s' %(prefix, localName)
  873. node = self.createElementNS(namespaceURI, qualifiedName)
  874. self._insertBefore(newChild=node._getNode(), refChild=refChild._getNode())
  875. return node
  876. def getElement(self, namespaceURI, localName):
  877. '''
  878. Keyword arguments:
  879. namespaceURI -- namespace of element
  880. localName -- local name of element
  881. '''
  882. node = self._dom.getElement(self.node, localName, namespaceURI, default=None)
  883. if node:
  884. return ElementProxy(self.sw, node)
  885. return None
  886. def getAttributeValue(self, namespaceURI, localName):
  887. '''
  888. Keyword arguments:
  889. namespaceURI -- namespace of attribute
  890. localName -- local name of attribute
  891. '''
  892. if self.hasAttribute(namespaceURI, localName):
  893. attr = self.node.getAttributeNodeNS(namespaceURI,localName)
  894. return attr.value
  895. return None
  896. def getValue(self):
  897. return self._dom.getElementText(self.node, preserve_ws=True)
  898. #############################################
  899. #Methods for text nodes
  900. #############################################
  901. def createAppendTextNode(self, pyobj):
  902. node = self.createTextNode(pyobj)
  903. self._appendChild(node=node._getNode())
  904. return node
  905. def createTextNode(self, pyobj):
  906. document = self._getOwnerDocument()
  907. node = document.createTextNode(pyobj)
  908. return ElementProxy(self.sw, node)
  909. #############################################
  910. #Methods for retrieving namespaceURI's
  911. #############################################
  912. def findNamespaceURI(self, qualifiedName):
  913. parts = SplitQName(qualifiedName)
  914. element = self._getNode()
  915. if len(parts) == 1:
  916. return (self._dom.findTargetNS(element), value)
  917. return self._dom.findNamespaceURI(parts[0], element)
  918. def resolvePrefix(self, prefix):
  919. element = self._getNode()
  920. return self._dom.findNamespaceURI(prefix, element)
  921. def getSOAPEnvURI(self):
  922. return self._soap_env_nsuri
  923. def isEmpty(self):
  924. return not self.node
  925. class Collection(UserDict):
  926. """Helper class for maintaining ordered named collections."""
  927. default = lambda self,k: k.name
  928. def __init__(self, parent, key=None):
  929. UserDict.__init__(self)
  930. self.parent = weakref.ref(parent)
  931. self.list = []
  932. self._func = key or self.default
  933. def __getitem__(self, key):
  934. if type(key) is type(1):
  935. return self.list[key]
  936. return self.data[key]
  937. def __setitem__(self, key, item):
  938. item.parent = weakref.ref(self)
  939. self.list.append(item)
  940. self.data[key] = item
  941. def keys(self):
  942. return map(lambda i: self._func(i), self.list)
  943. def items(self):
  944. return map(lambda i: (self._func(i), i), self.list)
  945. def values(self):
  946. return self.list
  947. class CollectionNS(UserDict):
  948. """Helper class for maintaining ordered named collections."""
  949. default = lambda self,k: k.name
  950. def __init__(self, parent, key=None):
  951. UserDict.__init__(self)
  952. self.parent = weakref.ref(parent)
  953. self.targetNamespace = None
  954. self.list = []
  955. self._func = key or self.default
  956. def __getitem__(self, key):
  957. self.targetNamespace = self.parent().targetNamespace
  958. if type(key) is types.IntType:
  959. return self.list[key]
  960. elif self.__isSequence(key):
  961. nsuri,name = key
  962. return self.data[nsuri][name]
  963. return self.data[self.parent().targetNamespace][key]
  964. def __setitem__(self, key, item):
  965. item.parent = weakref.ref(self)
  966. self.list.append(item)
  967. targetNamespace = getattr(item, 'targetNamespace', self.parent().targetNamespace)
  968. if not self.data.has_key(targetNamespace):
  969. self.data[targetNamespace] = {}
  970. self.data[targetNamespace][key] = item
  971. def __isSequence(self, key):
  972. return (type(key) in (types.TupleType,types.ListType) and len(key) == 2)
  973. def keys(self):
  974. keys = []
  975. for tns in self.data.keys():
  976. keys.append(map(lambda i: (tns,self._func(i)), self.data[tns].values()))
  977. return keys
  978. def items(self):
  979. return map(lambda i: (self._func(i), i), self.list)
  980. def values(self):
  981. return self.list
  982. # This is a runtime guerilla patch for pulldom (used by minidom) so
  983. # that xml namespace declaration attributes are not lost in parsing.
  984. # We need them to do correct QName linking for XML Schema and WSDL.
  985. # The patch has been submitted to SF for the next Python version.
  986. from xml.dom.pulldom import PullDOM, START_ELEMENT
  987. if 1:
  988. def startPrefixMapping(self, prefix, uri):
  989. if not hasattr(self, '_xmlns_attrs'):
  990. self._xmlns_attrs = []
  991. self._xmlns_attrs.append((prefix or 'xmlns', uri))
  992. self._ns_contexts.append(self._current_context.copy())
  993. self._current_context[uri] = prefix or ''
  994. PullDOM.startPrefixMapping = startPrefixMapping
  995. def startElementNS(self, name, tagName , attrs):
  996. # Retrieve xml namespace declaration attributes.
  997. xmlns_uri = 'http://www.w3.org/2000/xmlns/'
  998. xmlns_attrs = getattr(self, '_xmlns_attrs', None)
  999. if xmlns_attrs is not None:
  1000. for aname, value in xmlns_attrs:
  1001. attrs._attrs[(xmlns_uri, aname)] = value
  1002. self._xmlns_attrs = []
  1003. uri, localname = name
  1004. if uri:
  1005. # When using namespaces, the reader may or may not
  1006. # provide us with the original name. If not, create
  1007. # *a* valid tagName from the current context.
  1008. if tagName is None:
  1009. prefix = self._current_context[uri]
  1010. if prefix:
  1011. tagName = prefix + ":" + localname
  1012. else:
  1013. tagName = localname
  1014. if self.document:
  1015. node = self.document.createElementNS(uri, tagName)
  1016. else:
  1017. node = self.buildDocument(uri, tagName)
  1018. else:
  1019. # When the tagname is not prefixed, it just appears as
  1020. # localname
  1021. if self.document:
  1022. node = self.document.createElement(localname)
  1023. else:
  1024. node = self.buildDocument(None, localname)
  1025. for aname,value in attrs.items():
  1026. a_uri, a_localname = aname
  1027. if a_uri == xmlns_uri:
  1028. if a_localname == 'xmlns':
  1029. qname = a_localname
  1030. else:
  1031. qname = 'xmlns:' + a_localname
  1032. attr = self.document.createAttributeNS(a_uri, qname)
  1033. node.setAttributeNodeNS(attr)
  1034. elif a_uri:
  1035. prefix = self._current_context[a_uri]
  1036. if prefix:
  1037. qname = prefix + ":" + a_localname
  1038. else:
  1039. qname = a_localname
  1040. attr = self.document.createAttributeNS(a_uri, qname)
  1041. node.setAttributeNodeNS(attr)
  1042. else:
  1043. attr = self.document.createAttribute(a_localname)
  1044. node.setAttributeNode(attr)
  1045. attr.value = value
  1046. self.lastEvent[1] = [(START_ELEMENT, node), None]
  1047. self.lastEvent = self.lastEvent[1]
  1048. self.push(node)
  1049. PullDOM.startElementNS = startElementNS
  1050. #
  1051. # This is a runtime guerilla patch for minidom so
  1052. # that xmlns prefixed attributes dont raise AttributeErrors
  1053. # during cloning.
  1054. #
  1055. # Namespace declarations can appear in any start-tag, must look for xmlns
  1056. # prefixed attribute names during cloning.
  1057. #
  1058. # key (attr.namespaceURI, tag)
  1059. # ('http://www.w3.org/2000/xmlns/', u'xsd') <xml.dom.minidom.Attr instance at 0x82227c4>
  1060. # ('http://www.w3.org/2000/xmlns/', 'xmlns') <xml.dom.minidom.Attr instance at 0x8414b3c>
  1061. #
  1062. # xml.dom.minidom.Attr.nodeName = xmlns:xsd
  1063. # xml.dom.minidom.Attr.value = = http://www.w3.org/2001/XMLSchema
  1064. if 1:
  1065. def _clone_node(node, deep, newOwnerDocument):
  1066. """
  1067. Clone a node and give it the new owner document.
  1068. Called by Node.cloneNode and Document.importNode
  1069. """
  1070. if node.ownerDocument.isSameNode(newOwnerDocument):
  1071. operation = xml.dom.UserDataHandler.NODE_CLONED
  1072. else:
  1073. operation = xml.dom.UserDataHandler.NODE_IMPORTED
  1074. if node.nodeType == xml.dom.minidom.Node.ELEMENT_NODE:
  1075. clone = newOwnerDocument.createElementNS(node.namespaceURI,
  1076. node.nodeName)
  1077. for attr in node.attributes.values():
  1078. clone.setAttributeNS(attr.namespaceURI, attr.nodeName, attr.value)
  1079. prefix, tag = xml.dom.minidom._nssplit(attr.nodeName)
  1080. if prefix == 'xmlns':
  1081. a = clone.getAttributeNodeNS(attr.namespaceURI, tag)
  1082. elif prefix:
  1083. a = clone.getAttributeNodeNS(attr.namespaceURI, tag)
  1084. else:
  1085. a = clone.getAttributeNodeNS(attr.namespaceURI, attr.nodeName)
  1086. a.specified = attr.specified
  1087. if deep:
  1088. for child in node.childNodes:
  1089. c = xml.dom.minidom._clone_node(child, deep, newOwnerDocument)
  1090. clone.appendChild(c)
  1091. elif node.nodeType == xml.dom.minidom.Node.DOCUMENT_FRAGMENT_NODE:
  1092. clone = newOwnerDocument.createDocumentFragment()
  1093. if deep:
  1094. for child in node.childNodes:
  1095. c = xml.dom.minidom._clone_node(child, deep, newOwnerDocument)
  1096. clone.appendChild(c)
  1097. elif node.nodeType == xml.dom.minidom.Node.TEXT_NODE:
  1098. clone = newOwnerDocument.createTextNode(node.data)
  1099. elif node.nodeType == xml.dom.minidom.Node.CDATA_SECTION_NODE:
  1100. clone = newOwnerDocument.createCDATASection(node.data)
  1101. elif node.nodeType == xml.dom.minidom.Node.PROCESSING_INSTRUCTION_NODE:
  1102. clone = newOwnerDocument.createProcessingInstruction(node.target,
  1103. node.data)
  1104. elif node.nodeType == xml.dom.minidom.Node.COMMENT_NODE:
  1105. clone = newOwnerDocument.createComment(node.data)
  1106. elif node.nodeType == xml.dom.minidom.Node.ATTRIBUTE_NODE:
  1107. clone = newOwnerDocument.createAttributeNS(node.namespaceURI,
  1108. node.nodeName)
  1109. clone.specified = True
  1110. clone.value = node.value
  1111. elif node.nodeType == xml.dom.minidom.Node.DOCUMENT_TYPE_NODE:
  1112. assert node.ownerDocument is not newOwnerDocument
  1113. operation = xml.dom.UserDataHandler.NODE_IMPORTED
  1114. clone = newOwnerDocument.implementation.createDocumentType(
  1115. node.name, node.publicId, node.systemId)
  1116. clone.ownerDocument = newOwnerDocument
  1117. if deep:
  1118. clone.entities._seq = []
  1119. clone.notations._seq = []
  1120. for n in node.notations._seq:
  1121. notation = xml.dom.minidom.Notation(n.nodeName, n.publicId, n.systemId)
  1122. notation.ownerDocument = newOwnerDocument
  1123. clone.notations._seq.append(notation)
  1124. if hasattr(n, '_call_user_data_handler'):
  1125. n._call_user_data_handler(operation, n, notation)
  1126. for e in node.entities._seq:
  1127. entity = xml.dom.minidom.Entity(e.nodeName, e.publicId, e.systemId,
  1128. e.notationName)
  1129. entity.actualEncoding = e.actualEncoding
  1130. entity.encoding = e.encoding
  1131. entity.version = e.version
  1132. entity.ownerDocument = newOwnerDocument
  1133. clone.entities._seq.append(entity)
  1134. if hasattr(e, '_call_user_data_handler'):
  1135. e._call_user_data_handler(operation, n, entity)
  1136. else:
  1137. # Note the cloning of Document and DocumentType nodes is
  1138. # implemenetation specific. minidom handles those cases
  1139. # directly in the cloneNode() methods.
  1140. raise xml.dom.NotSupportedErr("Cannot clone node %s" % repr(node))
  1141. # Check for _call_user_data_handler() since this could conceivably
  1142. # used with other DOM implementations (one of the FourThought
  1143. # DOMs, perhaps?).
  1144. if hasattr(node, '_call_user_data_handler'):
  1145. node._call_user_data_handler(operation, node, clone)
  1146. return clone
  1147. xml.dom.minidom._clone_node = _clone_node