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.
 
 
 

1377 lines
50 KiB

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