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.
 
 
 

1433 lines
51 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, logger=None):
  90. self.logger = logger or logging.getLogger(__name__)
  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. # if can't find a referenced namespace, try the default one
  188. looseNamespaces = False
  189. # Namespace stuff related to the SOAP specification.
  190. NS_SOAP_ENV_1_1 = 'http://schemas.xmlsoap.org/soap/envelope/'
  191. NS_SOAP_ENC_1_1 = 'http://schemas.xmlsoap.org/soap/encoding/'
  192. NS_SOAP_ENV_1_2 = 'http://www.w3.org/2001/06/soap-envelope'
  193. NS_SOAP_ENC_1_2 = 'http://www.w3.org/2001/06/soap-encoding'
  194. NS_SOAP_ENV_ALL = (NS_SOAP_ENV_1_1, NS_SOAP_ENV_1_2)
  195. NS_SOAP_ENC_ALL = (NS_SOAP_ENC_1_1, NS_SOAP_ENC_1_2)
  196. NS_SOAP_ENV = NS_SOAP_ENV_1_1
  197. NS_SOAP_ENC = NS_SOAP_ENC_1_1
  198. _soap_uri_mapping = {
  199. NS_SOAP_ENV_1_1: '1.1',
  200. NS_SOAP_ENV_1_2: '1.2',
  201. }
  202. SOAP_ACTOR_NEXT_1_1 = 'http://schemas.xmlsoap.org/soap/actor/next'
  203. SOAP_ACTOR_NEXT_1_2 = 'http://www.w3.org/2001/06/soap-envelope/actor/next'
  204. SOAP_ACTOR_NEXT_ALL = (SOAP_ACTOR_NEXT_1_1, SOAP_ACTOR_NEXT_1_2)
  205. def SOAPUriToVersion(self, uri):
  206. """Return the SOAP version related to an envelope uri."""
  207. value = self._soap_uri_mapping.get(uri)
  208. if value is not None:
  209. return value
  210. raise ValueError(
  211. 'Unsupported SOAP envelope uri: %s' % uri
  212. )
  213. def GetSOAPEnvUri(self, version):
  214. """Return the appropriate SOAP envelope uri for a given
  215. human-friendly SOAP version string (e.g. '1.1')."""
  216. attrname = 'NS_SOAP_ENV_%s' % join(split(version, '.'), '_')
  217. value = getattr(self, attrname, None)
  218. if value is not None:
  219. return value
  220. raise ValueError(
  221. 'Unsupported SOAP version: %s' % version
  222. )
  223. def GetSOAPEncUri(self, version):
  224. """Return the appropriate SOAP encoding uri for a given
  225. human-friendly SOAP version string (e.g. '1.1')."""
  226. attrname = 'NS_SOAP_ENC_%s' % join(split(version, '.'), '_')
  227. value = getattr(self, attrname, None)
  228. if value is not None:
  229. return value
  230. raise ValueError(
  231. 'Unsupported SOAP version: %s' % version
  232. )
  233. def GetSOAPActorNextUri(self, version):
  234. """Return the right special next-actor uri for a given
  235. human-friendly SOAP version string (e.g. '1.1')."""
  236. attrname = 'SOAP_ACTOR_NEXT_%s' % join(split(version, '.'), '_')
  237. value = getattr(self, attrname, None)
  238. if value is not None:
  239. return value
  240. raise ValueError(
  241. 'Unsupported SOAP version: %s' % version
  242. )
  243. # Namespace stuff related to XML Schema.
  244. NS_XSD_99 = 'http://www.w3.org/1999/XMLSchema'
  245. NS_XSI_99 = 'http://www.w3.org/1999/XMLSchema-instance'
  246. NS_XSD_00 = 'http://www.w3.org/2000/10/XMLSchema'
  247. NS_XSI_00 = 'http://www.w3.org/2000/10/XMLSchema-instance'
  248. NS_XSD_01 = 'http://www.w3.org/2001/XMLSchema'
  249. NS_XSI_01 = 'http://www.w3.org/2001/XMLSchema-instance'
  250. NS_XSD_ALL = (NS_XSD_99, NS_XSD_00, NS_XSD_01)
  251. NS_XSI_ALL = (NS_XSI_99, NS_XSI_00, NS_XSI_01)
  252. NS_XSD = NS_XSD_01
  253. NS_XSI = NS_XSI_01
  254. _xsd_uri_mapping = {
  255. NS_XSD_99: NS_XSI_99,
  256. NS_XSD_00: NS_XSI_00,
  257. NS_XSD_01: NS_XSI_01,
  258. }
  259. for key, value in _xsd_uri_mapping.items():
  260. _xsd_uri_mapping[value] = key
  261. def InstanceUriForSchemaUri(self, uri):
  262. """Return the appropriate matching XML Schema instance uri for
  263. the given XML Schema namespace uri."""
  264. return self._xsd_uri_mapping.get(uri)
  265. def SchemaUriForInstanceUri(self, uri):
  266. """Return the appropriate matching XML Schema namespace uri for
  267. the given XML Schema instance namespace uri."""
  268. return self._xsd_uri_mapping.get(uri)
  269. # Namespace stuff related to WSDL.
  270. NS_WSDL_1_1 = 'http://schemas.xmlsoap.org/wsdl/'
  271. NS_WSDL_ALL = (NS_WSDL_1_1,)
  272. NS_WSDL = NS_WSDL_1_1
  273. NS_SOAP_BINDING_1_1 = 'http://schemas.xmlsoap.org/wsdl/soap/'
  274. NS_HTTP_BINDING_1_1 = 'http://schemas.xmlsoap.org/wsdl/http/'
  275. NS_MIME_BINDING_1_1 = 'http://schemas.xmlsoap.org/wsdl/mime/'
  276. NS_SOAP_BINDING_ALL = (NS_SOAP_BINDING_1_1,)
  277. NS_HTTP_BINDING_ALL = (NS_HTTP_BINDING_1_1,)
  278. NS_MIME_BINDING_ALL = (NS_MIME_BINDING_1_1,)
  279. NS_SOAP_BINDING = NS_SOAP_BINDING_1_1
  280. NS_HTTP_BINDING = NS_HTTP_BINDING_1_1
  281. NS_MIME_BINDING = NS_MIME_BINDING_1_1
  282. NS_SOAP_HTTP_1_1 = 'http://schemas.xmlsoap.org/soap/http'
  283. NS_SOAP_HTTP_ALL = (NS_SOAP_HTTP_1_1,)
  284. NS_SOAP_HTTP = NS_SOAP_HTTP_1_1
  285. _wsdl_uri_mapping = {
  286. NS_WSDL_1_1: '1.1',
  287. }
  288. def WSDLUriToVersion(self, uri):
  289. """Return the WSDL version related to a WSDL namespace uri."""
  290. value = self._wsdl_uri_mapping.get(uri)
  291. if value is not None:
  292. return value
  293. raise ValueError(
  294. 'Unsupported SOAP envelope uri: %s' % uri
  295. )
  296. def GetWSDLUri(self, version):
  297. attr = 'NS_WSDL_%s' % join(split(version, '.'), '_')
  298. value = getattr(self, attr, None)
  299. if value is not None:
  300. return value
  301. raise ValueError(
  302. 'Unsupported WSDL version: %s' % version
  303. )
  304. def GetWSDLSoapBindingUri(self, version):
  305. attr = 'NS_SOAP_BINDING_%s' % join(split(version, '.'), '_')
  306. value = getattr(self, attr, None)
  307. if value is not None:
  308. return value
  309. raise ValueError(
  310. 'Unsupported WSDL version: %s' % version
  311. )
  312. def GetWSDLHttpBindingUri(self, version):
  313. attr = 'NS_HTTP_BINDING_%s' % join(split(version, '.'), '_')
  314. value = getattr(self, attr, None)
  315. if value is not None:
  316. return value
  317. raise ValueError(
  318. 'Unsupported WSDL version: %s' % version
  319. )
  320. def GetWSDLMimeBindingUri(self, version):
  321. attr = 'NS_MIME_BINDING_%s' % join(split(version, '.'), '_')
  322. value = getattr(self, attr, None)
  323. if value is not None:
  324. return value
  325. raise ValueError(
  326. 'Unsupported WSDL version: %s' % version
  327. )
  328. def GetWSDLHttpTransportUri(self, version):
  329. attr = 'NS_SOAP_HTTP_%s' % join(split(version, '.'), '_')
  330. value = getattr(self, attr, None)
  331. if value is not None:
  332. return value
  333. raise ValueError(
  334. 'Unsupported WSDL version: %s' % version
  335. )
  336. # Other xml namespace constants.
  337. NS_XMLNS = 'http://www.w3.org/2000/xmlns/'
  338. def isElement(self, node, name, nsuri=None):
  339. """Return true if the given node is an element with the given
  340. name and optional namespace uri."""
  341. if node.nodeType != node.ELEMENT_NODE:
  342. return 0
  343. return node.localName == name and \
  344. (nsuri is None or self.nsUriMatch(node.namespaceURI, nsuri))
  345. def getElement(self, node, name, nsuri=None, default=join):
  346. """Return the first child of node with a matching name and
  347. namespace uri, or the default if one is provided."""
  348. nsmatch = self.nsUriMatch
  349. ELEMENT_NODE = node.ELEMENT_NODE
  350. for child in node.childNodes:
  351. if child.nodeType == ELEMENT_NODE:
  352. if ((child.localName == name or name is None) and
  353. (nsuri is None or nsmatch(child.namespaceURI, nsuri))):
  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.'
  471. % prefix)
  472. def findDefaultNS(self, node):
  473. """Return the current default namespace uri for the given node."""
  474. attrkey = (self.NS_XMLNS, 'xmlns')
  475. DOCUMENT_NODE = node.DOCUMENT_NODE
  476. ELEMENT_NODE = node.ELEMENT_NODE
  477. while 1:
  478. if node.nodeType != ELEMENT_NODE:
  479. node = node.parentNode
  480. continue
  481. result = node._attrsNS.get(attrkey, None)
  482. if result is not None:
  483. return result.value
  484. if hasattr(node, '__imported__'):
  485. raise DOMException('Cannot determine default namespace.')
  486. node = node.parentNode
  487. if node.nodeType == DOCUMENT_NODE:
  488. raise DOMException('Cannot determine default namespace.')
  489. def findTargetNS(self, node):
  490. """Return the defined target namespace uri for the given node."""
  491. attrget = self.getAttr
  492. attrkey = (self.NS_XMLNS, 'xmlns')
  493. DOCUMENT_NODE = node.DOCUMENT_NODE
  494. ELEMENT_NODE = node.ELEMENT_NODE
  495. while 1:
  496. if node.nodeType != ELEMENT_NODE:
  497. node = node.parentNode
  498. continue
  499. result = attrget(node, 'targetNamespace', default=None)
  500. if result is not None:
  501. return result
  502. node = node.parentNode
  503. if node.nodeType == DOCUMENT_NODE:
  504. raise DOMException('Cannot determine target namespace.')
  505. def getTypeRef(self, element):
  506. """Return (namespaceURI, name) for a type attribue of the given
  507. element, or None if the element does not have a type attribute."""
  508. typeattr = self.getAttr(element, 'type', default=None)
  509. if typeattr is None:
  510. return None
  511. parts = typeattr.split(':', 1)
  512. if len(parts) == 2:
  513. nsuri = self.findNamespaceURI(parts[0], element)
  514. else:
  515. nsuri = self.findDefaultNS(element)
  516. return (nsuri, parts[1])
  517. def importNode(self, document, node, deep=0):
  518. """Implements (well enough for our purposes) DOM node import."""
  519. nodetype = node.nodeType
  520. if nodetype in (node.DOCUMENT_NODE, node.DOCUMENT_TYPE_NODE):
  521. raise DOMException('Illegal node type for importNode')
  522. if nodetype == node.ENTITY_REFERENCE_NODE:
  523. deep = 0
  524. clone = node.cloneNode(deep)
  525. self._setOwnerDoc(document, clone)
  526. clone.__imported__ = 1
  527. return clone
  528. def _setOwnerDoc(self, document, node):
  529. node.ownerDocument = document
  530. for child in node.childNodes:
  531. self._setOwnerDoc(document, child)
  532. def nsUriMatch(self, value, wanted, strict=0, tt=type(())):
  533. """Return a true value if two namespace uri values match."""
  534. if value == wanted or (type(wanted) is tt) and value in wanted:
  535. return 1
  536. if not strict and value is not None:
  537. wanted = type(wanted) is tt and wanted or (wanted,)
  538. value = value[-1:] != '/' and value or value[:-1]
  539. for item in wanted:
  540. if item == value or item[:-1] == value:
  541. return 1
  542. return 0
  543. def createDocument(self, nsuri, qname, doctype=None):
  544. """Create a new writable DOM document object."""
  545. impl = xml.dom.minidom.getDOMImplementation()
  546. return impl.createDocument(nsuri, qname, doctype)
  547. def loadDocument(self, data):
  548. """Load an xml file from a file-like object and return a DOM
  549. document instance."""
  550. return xml.dom.minidom.parse(data)
  551. def loadFromURL(self, url):
  552. """Load an xml file from a URL and return a DOM document."""
  553. if isfile(url) is True:
  554. file = open(url, 'r')
  555. else:
  556. file = urlopen(url)
  557. try:
  558. result = self.loadDocument(file)
  559. except Exception, ex:
  560. file.close()
  561. raise ParseError(('Failed to load document %s' % url,) + ex.args)
  562. else:
  563. file.close()
  564. return result
  565. DOM = DOM()
  566. class MessageInterface:
  567. '''Higher Level Interface, delegates to DOM singleton, must
  568. be subclassed and implement all methods that throw NotImplementedError.
  569. '''
  570. def __init__(self, sw):
  571. '''Constructor, May be extended, do not override.
  572. sw -- soapWriter instance
  573. '''
  574. self.sw = None
  575. if type(sw) != weakref.ReferenceType and sw is not None:
  576. self.sw = weakref.ref(sw)
  577. else:
  578. self.sw = sw
  579. def AddCallback(self, func, *arglist):
  580. self.sw().AddCallback(func, *arglist)
  581. def Known(self, obj):
  582. return self.sw().Known(obj)
  583. def Forget(self, obj):
  584. return self.sw().Forget(obj)
  585. def canonicalize(self):
  586. '''canonicalize the underlying DOM, and return as string.
  587. '''
  588. raise NotImplementedError('')
  589. def createDocument(self, namespaceURI=SOAP.ENV, localName='Envelope'):
  590. '''create Document
  591. '''
  592. raise NotImplementedError('')
  593. def createAppendElement(self, namespaceURI, localName):
  594. '''create and append element(namespaceURI,localName), and return
  595. the node.
  596. '''
  597. raise NotImplementedError('')
  598. def findNamespaceURI(self, qualifiedName):
  599. raise NotImplementedError('')
  600. def resolvePrefix(self, prefix):
  601. raise NotImplementedError('')
  602. def setAttributeNS(self, namespaceURI, localName, value):
  603. '''set attribute (namespaceURI, localName)=value
  604. '''
  605. raise NotImplementedError('')
  606. def setAttributeType(self, namespaceURI, localName):
  607. '''set attribute xsi:type=(namespaceURI, localName)
  608. '''
  609. raise NotImplementedError('')
  610. def setNamespaceAttribute(self, namespaceURI, prefix):
  611. '''set namespace attribute xmlns:prefix=namespaceURI
  612. '''
  613. raise NotImplementedError('')
  614. class ElementProxy(Base, MessageInterface):
  615. _soap_env_prefix = 'SOAP-ENV'
  616. _soap_enc_prefix = 'SOAP-ENC'
  617. _zsi_prefix = 'ZSI'
  618. _xsd_prefix = 'xsd'
  619. _xsi_prefix = 'xsi'
  620. _xml_prefix = 'xml'
  621. _xmlns_prefix = 'xmlns'
  622. _soap_env_nsuri = SOAP.ENV
  623. _soap_enc_nsuri = SOAP.ENC
  624. _zsi_nsuri = ZSI_SCHEMA_URI
  625. _xsd_nsuri = SCHEMA.XSD3
  626. _xsi_nsuri = SCHEMA.XSI3
  627. _xml_nsuri = XMLNS.XML
  628. _xmlns_nsuri = XMLNS.BASE
  629. standard_ns = {
  630. _xml_prefix: _xml_nsuri,
  631. _xmlns_prefix: _xmlns_nsuri
  632. }
  633. reserved_ns = {
  634. _soap_env_prefix: _soap_env_nsuri,
  635. _soap_enc_prefix: _soap_enc_nsuri,
  636. _zsi_prefix: _zsi_nsuri,
  637. _xsd_prefix: _xsd_nsuri,
  638. _xsi_prefix: _xsi_nsuri,
  639. }
  640. name = None
  641. namespaceURI = None
  642. def __init__(self, sw, message=None):
  643. '''Initialize.
  644. sw -- SoapWriter
  645. '''
  646. self._indx = 0
  647. MessageInterface.__init__(self, sw)
  648. Base.__init__(self)
  649. self._dom = DOM
  650. self.node = None
  651. if type(message) in (types.StringType, types.UnicodeType):
  652. self.loadFromString(message)
  653. elif isinstance(message, ElementProxy):
  654. self.node = message._getNode()
  655. else:
  656. self.node = message
  657. self.processorNss = self.standard_ns.copy()
  658. self.processorNss.update(self.reserved_ns)
  659. def __str__(self):
  660. return self.toString()
  661. def evaluate(self, expression, processorNss=None):
  662. '''expression -- XPath compiled expression
  663. '''
  664. from Ft.Xml import XPath
  665. if not processorNss:
  666. context = XPath.Context.Context(self.node,
  667. processorNss=self.processorNss)
  668. else:
  669. context = XPath.Context.Context(self.node,
  670. processorNss=processorNss)
  671. nodes = expression.evaluate(context)
  672. return map(lambda node: ElementProxy(self.sw, node), nodes)
  673. #############################################
  674. # Methods for checking/setting the
  675. # classes (namespaceURI,name) node.
  676. #############################################
  677. def checkNode(self, namespaceURI=None, localName=None):
  678. '''
  679. namespaceURI -- namespace of element
  680. localName -- local name of element
  681. '''
  682. namespaceURI = namespaceURI or self.namespaceURI
  683. localName = localName or self.name
  684. check = False
  685. if localName and self.node:
  686. check = self._dom.isElement(self.node, localName, namespaceURI)
  687. if not check:
  688. raise NamespaceError('unexpected node type %s, expecting %s'
  689. % (self.node, localName))
  690. def setNode(self, node=None):
  691. if node:
  692. if isinstance(node, ElementProxy):
  693. self.node = node._getNode()
  694. else:
  695. self.node = node
  696. elif self.node:
  697. node = self._dom.getElement(self.node, self.name,
  698. self.namespaceURI, default=None)
  699. if not node:
  700. raise NamespaceError('cant find element (%s, %s)' %
  701. (self.namespaceURI, self.name))
  702. self.node = node
  703. else:
  704. self.createDocument(self.namespaceURI, localName=self.name,
  705. doctype=None)
  706. self.checkNode()
  707. #############################################
  708. # Wrapper Methods for direct DOM Element Node access
  709. #############################################
  710. def _getNode(self):
  711. return self.node
  712. def _getElements(self):
  713. return self._dom.getElements(self.node, name=None)
  714. def _getOwnerDocument(self):
  715. return self.node.ownerDocument or self.node
  716. def _getUniquePrefix(self):
  717. '''I guess we need to resolve all potential prefixes
  718. because when the current node is attached it copies the
  719. namespaces into the parent node.
  720. '''
  721. while 1:
  722. self._indx += 1
  723. prefix = 'ns%d' % self._indx
  724. try:
  725. self._dom.findNamespaceURI(prefix, self._getNode())
  726. except DOMException, ex:
  727. break
  728. return prefix
  729. def _getPrefix(self, node, nsuri):
  730. '''
  731. Keyword arguments:
  732. node -- DOM Element Node
  733. nsuri -- namespace of attribute value
  734. '''
  735. try:
  736. if node and (node.nodeType == node.ELEMENT_NODE) and \
  737. (nsuri == self._dom.findDefaultNS(node)):
  738. return None
  739. except DOMException, ex:
  740. pass
  741. if nsuri == XMLNS.XML:
  742. return self._xml_prefix
  743. if node.nodeType == Node.ELEMENT_NODE:
  744. for attr in node.attributes.values():
  745. if attr.namespaceURI == XMLNS.BASE \
  746. and nsuri == attr.value:
  747. return attr.localName
  748. else:
  749. if node.parentNode:
  750. return self._getPrefix(node.parentNode, nsuri)
  751. raise NamespaceError('namespaceURI "%s" is not defined' % nsuri)
  752. def _appendChild(self, node):
  753. '''
  754. Keyword arguments:
  755. node -- DOM Element Node
  756. '''
  757. if node is None:
  758. raise TypeError('node is None')
  759. self.node.appendChild(node)
  760. def _insertBefore(self, newChild, refChild):
  761. '''
  762. Keyword arguments:
  763. child -- DOM Element Node to insert
  764. refChild -- DOM Element Node
  765. '''
  766. self.node.insertBefore(newChild, refChild)
  767. def _setAttributeNS(self, namespaceURI, qualifiedName, value):
  768. '''
  769. Keyword arguments:
  770. namespaceURI -- namespace of attribute
  771. qualifiedName -- qualified name of new attribute value
  772. value -- value of attribute
  773. '''
  774. self.node.setAttributeNS(namespaceURI, qualifiedName, value)
  775. #############################################
  776. #General Methods
  777. #############################################
  778. def isFault(self):
  779. '''check to see if this is a soap:fault message.
  780. '''
  781. return False
  782. def getPrefix(self, namespaceURI):
  783. try:
  784. prefix = self._getPrefix(node=self.node, nsuri=namespaceURI)
  785. except NamespaceError, ex:
  786. prefix = self._getUniquePrefix()
  787. self.setNamespaceAttribute(prefix, namespaceURI)
  788. return prefix
  789. def getDocument(self):
  790. return self._getOwnerDocument()
  791. def setDocument(self, document):
  792. self.node = document
  793. def importFromString(self, xmlString):
  794. doc = self._dom.loadDocument(StringIO(xmlString))
  795. node = self._dom.getElement(doc, name=None)
  796. clone = self.importNode(node)
  797. self._appendChild(clone)
  798. def importNode(self, node):
  799. if isinstance(node, ElementProxy):
  800. node = node._getNode()
  801. return self._dom.importNode(self._getOwnerDocument(), node, deep=1)
  802. def loadFromString(self, data):
  803. self.node = self._dom.loadDocument(StringIO(data))
  804. def canonicalize(self):
  805. return Canonicalize(self.node)
  806. def toString(self):
  807. return self.canonicalize()
  808. def createDocument(self, namespaceURI, localName, doctype=None):
  809. '''If specified must be a SOAP envelope, else may contruct an empty
  810. document.
  811. '''
  812. prefix = self._soap_env_prefix
  813. if namespaceURI == self.reserved_ns[prefix]:
  814. qualifiedName = '%s:%s' % (prefix, localName)
  815. elif namespaceURI is localName is None:
  816. self.node = self._dom.createDocument(None, None, None)
  817. return
  818. else:
  819. raise KeyError('only support creation of document in %s' %
  820. self.reserved_ns[prefix])
  821. document = self._dom.createDocument(nsuri=namespaceURI,
  822. qname=qualifiedName,
  823. doctype=doctype)
  824. self.node = document.childNodes[0]
  825. #set up reserved namespace attributes
  826. for prefix, nsuri in self.reserved_ns.items():
  827. self._setAttributeNS(namespaceURI=self._xmlns_nsuri,
  828. qualifiedName='%s:%s' % (self._xmlns_prefix,
  829. prefix),
  830. value=nsuri)
  831. #############################################
  832. #Methods for attributes
  833. #############################################
  834. def hasAttribute(self, namespaceURI, localName):
  835. return self._dom.hasAttr(self._getNode(), name=localName,
  836. nsuri=namespaceURI)
  837. def setAttributeType(self, namespaceURI, localName):
  838. '''set xsi:type
  839. Keyword arguments:
  840. namespaceURI -- namespace of attribute value
  841. localName -- name of new attribute value
  842. '''
  843. self.logger.debug('setAttributeType: (%s,%s)', namespaceURI, localName)
  844. value = localName
  845. if namespaceURI:
  846. value = '%s:%s' % (self.getPrefix(namespaceURI), localName)
  847. xsi_prefix = self.getPrefix(self._xsi_nsuri)
  848. self._setAttributeNS(self._xsi_nsuri, '%s:type' % xsi_prefix, value)
  849. def createAttributeNS(self, namespace, name, value):
  850. document = self._getOwnerDocument()
  851. ##this function doesn't exist!! it has only two arguments
  852. attrNode = document.createAttributeNS(namespace, name, value)
  853. def setAttributeNS(self, namespaceURI, localName, value):
  854. '''
  855. Keyword arguments:
  856. namespaceURI -- namespace of attribute to create, None is for
  857. attributes in no namespace.
  858. localName -- local name of new attribute
  859. value -- value of new attribute
  860. '''
  861. prefix = None
  862. if namespaceURI:
  863. try:
  864. prefix = self.getPrefix(namespaceURI)
  865. except KeyError, ex:
  866. prefix = 'ns2'
  867. self.setNamespaceAttribute(prefix, namespaceURI)
  868. qualifiedName = localName
  869. if prefix:
  870. qualifiedName = '%s:%s' % (prefix, localName)
  871. self._setAttributeNS(namespaceURI, qualifiedName, value)
  872. def setNamespaceAttribute(self, prefix, namespaceURI):
  873. '''
  874. Keyword arguments:
  875. prefix -- xmlns prefix
  876. namespaceURI -- value of prefix
  877. '''
  878. self._setAttributeNS(XMLNS.BASE, 'xmlns:%s' % prefix, namespaceURI)
  879. #############################################
  880. #Methods for elements
  881. #############################################
  882. def createElementNS(self, namespace, qname):
  883. '''
  884. Keyword arguments:
  885. namespace -- namespace of element to create
  886. qname -- qualified name of new element
  887. '''
  888. document = self._getOwnerDocument()
  889. node = document.createElementNS(namespace, qname)
  890. return ElementProxy(self.sw, node)
  891. def createAppendSetElement(self, namespaceURI, localName, prefix=None):
  892. '''Create a new element (namespaceURI,name), append it
  893. to current node, then set it to be the current node.
  894. Keyword arguments:
  895. namespaceURI -- namespace of element to create
  896. localName -- local name of new element
  897. prefix -- if namespaceURI is not defined, declare prefix. defaults
  898. to 'ns1' if left unspecified.
  899. '''
  900. node = self.createAppendElement(namespaceURI, localName, prefix=None)
  901. node = node._getNode()
  902. self._setNode(node._getNode())
  903. def createAppendElement(self, namespaceURI, localName, prefix=None):
  904. '''Create a new element (namespaceURI,name), append it
  905. to current node, and return the newly created node.
  906. Keyword arguments:
  907. namespaceURI -- namespace of element to create
  908. localName -- local name of new element
  909. prefix -- if namespaceURI is not defined, declare prefix. defaults
  910. to 'ns1' if left unspecified.
  911. '''
  912. declare = False
  913. qualifiedName = localName
  914. if namespaceURI:
  915. try:
  916. prefix = self.getPrefix(namespaceURI)
  917. except:
  918. declare = True
  919. prefix = prefix or self._getUniquePrefix()
  920. if prefix:
  921. qualifiedName = '%s:%s' % (prefix, localName)
  922. node = self.createElementNS(namespaceURI, qualifiedName)
  923. if declare:
  924. node._setAttributeNS(XMLNS.BASE, 'xmlns:%s' % prefix, namespaceURI)
  925. self._appendChild(node=node._getNode())
  926. return node
  927. def createInsertBefore(self, namespaceURI, localName, refChild):
  928. qualifiedName = localName
  929. prefix = self.getPrefix(namespaceURI)
  930. if prefix:
  931. qualifiedName = '%s:%s' % (prefix, localName)
  932. node = self.createElementNS(namespaceURI, qualifiedName)
  933. self._insertBefore(newChild=node._getNode(),
  934. refChild=refChild._getNode())
  935. return node
  936. def getElement(self, namespaceURI, localName):
  937. '''
  938. Keyword arguments:
  939. namespaceURI -- namespace of element
  940. localName -- local name of element
  941. '''
  942. node = self._dom.getElement(self.node, localName, namespaceURI,
  943. default=None)
  944. if node:
  945. return ElementProxy(self.sw, node)
  946. return None
  947. def getAttributeValue(self, namespaceURI, localName):
  948. '''
  949. Keyword arguments:
  950. namespaceURI -- namespace of attribute
  951. localName -- local name of attribute
  952. '''
  953. if self.hasAttribute(namespaceURI, localName):
  954. attr = self.node.getAttributeNodeNS(namespaceURI, localName)
  955. return attr.value
  956. return None
  957. def getValue(self):
  958. return self._dom.getElementText(self.node, preserve_ws=True)
  959. #############################################
  960. #Methods for text nodes
  961. #############################################
  962. def createAppendTextNode(self, pyobj):
  963. node = self.createTextNode(pyobj)
  964. self._appendChild(node=node._getNode())
  965. return node
  966. def createTextNode(self, pyobj):
  967. document = self._getOwnerDocument()
  968. node = document.createTextNode(pyobj)
  969. return ElementProxy(self.sw, node)
  970. #############################################
  971. #Methods for retrieving namespaceURI's
  972. #############################################
  973. def findNamespaceURI(self, qualifiedName):
  974. parts = SplitQName(qualifiedName)
  975. element = self._getNode()
  976. if len(parts) == 1:
  977. return (self._dom.findTargetNS(element), value)
  978. return self._dom.findNamespaceURI(parts[0], element)
  979. def resolvePrefix(self, prefix):
  980. element = self._getNode()
  981. return self._dom.findNamespaceURI(prefix, element)
  982. def getSOAPEnvURI(self):
  983. return self._soap_env_nsuri
  984. def isEmpty(self):
  985. return not self.node
  986. class Collection(UserDict):
  987. """Helper class for maintaining ordered named collections."""
  988. default = lambda self, k: k.name
  989. def __init__(self, parent, key=None):
  990. UserDict.__init__(self)
  991. self.parent = weakref.ref(parent)
  992. self.list = []
  993. self._func = key or self.default
  994. def __getitem__(self, key):
  995. NumberTypes = (types.IntType, types.LongType, types.FloatType,
  996. types.ComplexType)
  997. if isinstance(key, NumberTypes):
  998. return self.list[key]
  999. return self.data[key]
  1000. def __setitem__(self, key, item):
  1001. item.parent = weakref.ref(self)
  1002. self.list.append(item)
  1003. self.data[key] = item
  1004. def keys(self):
  1005. return map(lambda i: self._func(i), self.list)
  1006. def items(self):
  1007. return map(lambda i: (self._func(i), i), self.list)
  1008. def values(self):
  1009. return self.list
  1010. class CollectionNS(UserDict):
  1011. """Helper class for maintaining ordered named collections."""
  1012. default = lambda self, k: k.name
  1013. def __init__(self, parent, key=None):
  1014. UserDict.__init__(self)
  1015. self.parent = weakref.ref(parent)
  1016. self.targetNamespace = None
  1017. self.list = []
  1018. self._func = key or self.default
  1019. def __getitem__(self, key):
  1020. self.targetNamespace = self.parent().targetNamespace
  1021. if isinstance(key, types.IntType):
  1022. return self.list[key]
  1023. elif self.__isSequence(key):
  1024. nsuri, name = key
  1025. return self.data[nsuri][name]
  1026. return self.data[self.parent().targetNamespace][key]
  1027. def __setitem__(self, key, item):
  1028. item.parent = weakref.ref(self)
  1029. self.list.append(item)
  1030. targetNamespace = getattr(item, 'targetNamespace',
  1031. self.parent().targetNamespace)
  1032. if not targetNamespace in self.data:
  1033. self.data[targetNamespace] = {}
  1034. self.data[targetNamespace][key] = item
  1035. def __isSequence(self, key):
  1036. return (type(key) in (types.TupleType, types.ListType)
  1037. and len(key) == 2)
  1038. def keys(self):
  1039. keys = []
  1040. for tns in self.data.keys():
  1041. keys.append(map(lambda i: (tns, self._func(i)),
  1042. self.data[tns].values()))
  1043. return keys
  1044. def items(self):
  1045. return map(lambda i: (self._func(i), i), self.list)
  1046. def values(self):
  1047. return self.list
  1048. # This is a runtime guerilla patch for pulldom (used by minidom) so
  1049. # that xml namespace declaration attributes are not lost in parsing.
  1050. # We need them to do correct QName linking for XML Schema and WSDL.
  1051. # The patch has been submitted to SF for the next Python version.
  1052. from xml.dom.pulldom import PullDOM, START_ELEMENT
  1053. if 1:
  1054. def startPrefixMapping(self, prefix, uri):
  1055. if not hasattr(self, '_xmlns_attrs'):
  1056. self._xmlns_attrs = []
  1057. self._xmlns_attrs.append((prefix or 'xmlns', uri))
  1058. self._ns_contexts.append(self._current_context.copy())
  1059. self._current_context[uri] = prefix or ''
  1060. PullDOM.startPrefixMapping = startPrefixMapping
  1061. def startElementNS(self, name, tagName, attrs):
  1062. # Retrieve xml namespace declaration attributes.
  1063. xmlns_uri = 'http://www.w3.org/2000/xmlns/'
  1064. xmlns_attrs = getattr(self, '_xmlns_attrs', None)
  1065. if xmlns_attrs is not None:
  1066. for aname, value in xmlns_attrs:
  1067. attrs._attrs[(xmlns_uri, aname)] = value
  1068. self._xmlns_attrs = []
  1069. uri, localname = name
  1070. if uri:
  1071. # When using namespaces, the reader may or may not
  1072. # provide us with the original name. If not, create
  1073. # *a* valid tagName from the current context.
  1074. if tagName is None:
  1075. prefix = self._current_context[uri]
  1076. if prefix:
  1077. tagName = prefix + ":" + localname
  1078. else:
  1079. tagName = localname
  1080. if self.document:
  1081. node = self.document.createElementNS(uri, tagName)
  1082. else:
  1083. node = self.buildDocument(uri, tagName)
  1084. else:
  1085. # When the tagname is not prefixed, it just appears as
  1086. # localname
  1087. if self.document:
  1088. node = self.document.createElement(localname)
  1089. else:
  1090. node = self.buildDocument(None, localname)
  1091. for aname, value in attrs.items():
  1092. a_uri, a_localname = aname
  1093. if a_uri == xmlns_uri:
  1094. if a_localname == 'xmlns':
  1095. qname = a_localname
  1096. else:
  1097. qname = 'xmlns:' + a_localname
  1098. attr = self.document.createAttributeNS(a_uri, qname)
  1099. node.setAttributeNodeNS(attr)
  1100. elif a_uri:
  1101. prefix = self._current_context[a_uri]
  1102. if prefix:
  1103. qname = prefix + ":" + a_localname
  1104. else:
  1105. qname = a_localname
  1106. attr = self.document.createAttributeNS(a_uri, qname)
  1107. node.setAttributeNodeNS(attr)
  1108. else:
  1109. attr = self.document.createAttribute(a_localname)
  1110. node.setAttributeNode(attr)
  1111. attr.value = value
  1112. self.lastEvent[1] = [(START_ELEMENT, node), None]
  1113. self.lastEvent = self.lastEvent[1]
  1114. self.push(node)
  1115. PullDOM.startElementNS = startElementNS
  1116. #
  1117. # This is a runtime guerilla patch for minidom so
  1118. # that xmlns prefixed attributes dont raise AttributeErrors
  1119. # during cloning.
  1120. #
  1121. # Namespace declarations can appear in any start-tag, must look for xmlns
  1122. # prefixed attribute names during cloning.
  1123. #
  1124. # key (attr.namespaceURI, tag)
  1125. # ('http://www.w3.org/2000/xmlns/', u'xsd')
  1126. # <xml.dom.minidom.Attr instance at 0x82227c4>
  1127. # ('http://www.w3.org/2000/xmlns/', 'xmlns')
  1128. # <xml.dom.minidom.Attr instance at 0x8414b3c>
  1129. #
  1130. # xml.dom.minidom.Attr.nodeName = xmlns:xsd
  1131. # xml.dom.minidom.Attr.value = = http://www.w3.org/2001/XMLSchema
  1132. if 1:
  1133. def _clone_node(node, deep, newOwnerDocument):
  1134. """
  1135. Clone a node and give it the new owner document.
  1136. Called by Node.cloneNode and Document.importNode
  1137. """
  1138. if node.ownerDocument.isSameNode(newOwnerDocument):
  1139. operation = xml.dom.UserDataHandler.NODE_CLONED
  1140. else:
  1141. operation = xml.dom.UserDataHandler.NODE_IMPORTED
  1142. if node.nodeType == xml.dom.minidom.Node.ELEMENT_NODE:
  1143. clone = newOwnerDocument.createElementNS(node.namespaceURI,
  1144. node.nodeName)
  1145. for attr in node.attributes.values():
  1146. clone.setAttributeNS(attr.namespaceURI, attr.nodeName,
  1147. attr.value)
  1148. prefix, tag = xml.dom.minidom._nssplit(attr.nodeName)
  1149. if prefix == 'xmlns':
  1150. a = clone.getAttributeNodeNS(attr.namespaceURI, tag)
  1151. elif prefix:
  1152. a = clone.getAttributeNodeNS(attr.namespaceURI, tag)
  1153. else:
  1154. a = clone.getAttributeNodeNS(attr.namespaceURI,
  1155. attr.nodeName)
  1156. a.specified = attr.specified
  1157. if deep:
  1158. for child in node.childNodes:
  1159. c = xml.dom.minidom._clone_node(child, deep,
  1160. newOwnerDocument)
  1161. clone.appendChild(c)
  1162. elif node.nodeType == xml.dom.minidom.Node.DOCUMENT_FRAGMENT_NODE:
  1163. clone = newOwnerDocument.createDocumentFragment()
  1164. if deep:
  1165. for child in node.childNodes:
  1166. c = xml.dom.minidom._clone_node(child, deep,
  1167. newOwnerDocument)
  1168. clone.appendChild(c)
  1169. elif node.nodeType == xml.dom.minidom.Node.TEXT_NODE:
  1170. clone = newOwnerDocument.createTextNode(node.data)
  1171. elif node.nodeType == xml.dom.minidom.Node.CDATA_SECTION_NODE:
  1172. clone = newOwnerDocument.createCDATASection(node.data)
  1173. elif node.nodeType == xml.dom.minidom.Node.PROCESSING_INSTRUCTION_NODE:
  1174. clone = newOwnerDocument.createProcessingInstruction(node.target,
  1175. node.data)
  1176. elif node.nodeType == xml.dom.minidom.Node.COMMENT_NODE:
  1177. clone = newOwnerDocument.createComment(node.data)
  1178. elif node.nodeType == xml.dom.minidom.Node.ATTRIBUTE_NODE:
  1179. clone = newOwnerDocument.createAttributeNS(node.namespaceURI,
  1180. node.nodeName)
  1181. clone.specified = True
  1182. clone.value = node.value
  1183. elif node.nodeType == xml.dom.minidom.Node.DOCUMENT_TYPE_NODE:
  1184. assert node.ownerDocument is not newOwnerDocument
  1185. operation = xml.dom.UserDataHandler.NODE_IMPORTED
  1186. clone = newOwnerDocument.implementation.createDocumentType(
  1187. node.name, node.publicId, node.systemId)
  1188. clone.ownerDocument = newOwnerDocument
  1189. if deep:
  1190. clone.entities._seq = []
  1191. clone.notations._seq = []
  1192. for n in node.notations._seq:
  1193. notation = xml.dom.minidom.Notation(n.nodeName, n.publicId,
  1194. n.systemId)
  1195. notation.ownerDocument = newOwnerDocument
  1196. clone.notations._seq.append(notation)
  1197. if hasattr(n, '_call_user_data_handler'):
  1198. n._call_user_data_handler(operation, n, notation)
  1199. for e in node.entities._seq:
  1200. entity = xml.dom.minidom.Entity(e.nodeName, e.publicId,
  1201. e.systemId,
  1202. e.notationName)
  1203. entity.actualEncoding = e.actualEncoding
  1204. entity.encoding = e.encoding
  1205. entity.version = e.version
  1206. entity.ownerDocument = newOwnerDocument
  1207. clone.entities._seq.append(entity)
  1208. if hasattr(e, '_call_user_data_handler'):
  1209. e._call_user_data_handler(operation, n, entity)
  1210. else:
  1211. # Note the cloning of Document and DocumentType nodes is
  1212. # implemenetation specific. minidom handles those cases
  1213. # directly in the cloneNode() methods.
  1214. raise xml.dom.NotSupportedErr("Cannot clone node %s" % repr(node))
  1215. # Check for _call_user_data_handler() since this could conceivably
  1216. # used with other DOM implementations (one of the FourThought
  1217. # DOMs, perhaps?).
  1218. if hasattr(node, '_call_user_data_handler'):
  1219. node._call_user_data_handler(operation, node, clone)
  1220. return clone
  1221. xml.dom.minidom._clone_node = _clone_node