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.
 
 
 

1392 lines
50 KiB

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