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.
 
 
 

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