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.
 
 
 

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