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.
 
 
 

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