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.
 
 
 

1461 lines
51 KiB

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