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.
 
 
 

1349 lines
48 KiB

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