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.
 
 
 

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