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.
 
 
 

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