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.
 
 
 

1627 lines
58 KiB

  1. # Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
  2. #
  3. # This software is subject to the provisions of the Zope Public License,
  4. # Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
  5. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
  6. # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  7. # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
  8. # FOR A PARTICULAR PURPOSE.
  9. ident = "$Id$"
  10. import weakref
  11. from cStringIO import StringIO
  12. from Namespaces import OASIS, XMLNS, WSA, WSA_LIST, WSRF_V1_2
  13. from Utility import Collection, CollectionNS, DOM, ElementProxy, basejoin
  14. from XMLSchema import XMLSchema, SchemaReader, WSDLToolsAdapter
  15. class WSDLReader:
  16. """A WSDLReader creates WSDL instances from urls and xml data."""
  17. # Custom subclasses of WSDLReader may wish to implement a caching
  18. # strategy or other optimizations. Because application needs vary
  19. # so widely, we don't try to provide any caching by default.
  20. def loadFromStream(self, stream, name=None):
  21. """Return a WSDL instance loaded from a stream object."""
  22. document = DOM.loadDocument(stream)
  23. wsdl = WSDL()
  24. if name:
  25. wsdl.location = name
  26. elif hasattr(stream, 'name'):
  27. wsdl.location = stream.name
  28. wsdl.load(document)
  29. return wsdl
  30. def loadFromURL(self, url):
  31. """Return a WSDL instance loaded from the given url."""
  32. document = DOM.loadFromURL(url)
  33. wsdl = WSDL()
  34. wsdl.location = url
  35. wsdl.load(document)
  36. return wsdl
  37. def loadFromString(self, data):
  38. """Return a WSDL instance loaded from an xml string."""
  39. return self.loadFromStream(StringIO(data))
  40. def loadFromFile(self, filename):
  41. """Return a WSDL instance loaded from the given file."""
  42. file = open(filename, 'rb')
  43. try:
  44. wsdl = self.loadFromStream(file)
  45. finally:
  46. file.close()
  47. return wsdl
  48. class WSDL:
  49. """A WSDL object models a WSDL service description. WSDL objects
  50. may be created manually or loaded from an xml representation
  51. using a WSDLReader instance."""
  52. def __init__(self, targetNamespace=None, strict=1):
  53. self.targetNamespace = targetNamespace or 'urn:this-document.wsdl'
  54. self.documentation = ''
  55. self.location = None
  56. self.document = None
  57. self.name = None
  58. self.services = CollectionNS(self)
  59. self.messages = CollectionNS(self)
  60. self.portTypes = CollectionNS(self)
  61. self.bindings = CollectionNS(self)
  62. self.imports = Collection(self)
  63. self.types = Types(self)
  64. self.extensions = []
  65. self.strict = strict
  66. def __del__(self):
  67. if self.document is not None:
  68. self.document.unlink()
  69. version = '1.1'
  70. def addService(self, name, documentation='', targetNamespace=None):
  71. if self.services.has_key(name):
  72. raise WSDLError(
  73. 'Duplicate service element: %s' % name
  74. )
  75. item = Service(name, documentation)
  76. if targetNamespace:
  77. item.targetNamespace = targetNamespace
  78. self.services[name] = item
  79. return item
  80. def addMessage(self, name, documentation='', targetNamespace=None):
  81. if self.messages.has_key(name):
  82. raise WSDLError(
  83. 'Duplicate message element: %s.' % name
  84. )
  85. item = Message(name, documentation)
  86. if targetNamespace:
  87. item.targetNamespace = targetNamespace
  88. self.messages[name] = item
  89. return item
  90. def addPortType(self, name, documentation='', targetNamespace=None):
  91. if self.portTypes.has_key(name):
  92. raise WSDLError(
  93. 'Duplicate portType element: name'
  94. )
  95. item = PortType(name, documentation)
  96. if targetNamespace:
  97. item.targetNamespace = targetNamespace
  98. self.portTypes[name] = item
  99. return item
  100. def addBinding(self, name, type, documentation='', targetNamespace=None):
  101. if self.bindings.has_key(name):
  102. raise WSDLError(
  103. 'Duplicate binding element: %s' % name
  104. )
  105. item = Binding(name, type, documentation)
  106. if targetNamespace:
  107. item.targetNamespace = targetNamespace
  108. self.bindings[name] = item
  109. return item
  110. def addImport(self, namespace, location):
  111. item = ImportElement(namespace, location)
  112. self.imports[namespace] = item
  113. return item
  114. def toDom(self):
  115. """ Generate a DOM representation of the WSDL instance.
  116. Not dealing with generating XML Schema, thus the targetNamespace
  117. of all XML Schema elements or types used by WSDL message parts
  118. needs to be specified via import information items.
  119. """
  120. namespaceURI = DOM.GetWSDLUri(self.version)
  121. self.document = DOM.createDocument(namespaceURI ,'wsdl:definitions')
  122. # Set up a couple prefixes for easy reading.
  123. child = DOM.getElement(self.document, None)
  124. child.setAttributeNS(None, 'targetNamespace', self.targetNamespace)
  125. child.setAttributeNS(XMLNS.BASE, 'xmlns:wsdl', namespaceURI)
  126. child.setAttributeNS(XMLNS.BASE, 'xmlns:xsd', 'http://www.w3.org/1999/XMLSchema')
  127. child.setAttributeNS(XMLNS.BASE, 'xmlns:soap', 'http://schemas.xmlsoap.org/wsdl/soap/')
  128. child.setAttributeNS(XMLNS.BASE, 'xmlns:tns', self.targetNamespace)
  129. # wsdl:import
  130. for item in self.imports:
  131. item.toDom()
  132. # wsdl:message
  133. for item in self.messages:
  134. item.toDom()
  135. # wsdl:portType
  136. for item in self.portTypes:
  137. item.toDom()
  138. # wsdl:binding
  139. for item in self.bindings:
  140. item.toDom()
  141. # wsdl:service
  142. for item in self.services:
  143. item.toDom()
  144. def load(self, document):
  145. # We save a reference to the DOM document to ensure that elements
  146. # saved as "extensions" will continue to have a meaningful context
  147. # for things like namespace references. The lifetime of the DOM
  148. # document is bound to the lifetime of the WSDL instance.
  149. self.document = document
  150. definitions = DOM.getElement(document, 'definitions', None, None)
  151. if definitions is None:
  152. raise WSDLError(
  153. 'Missing <definitions> element.'
  154. )
  155. self.version = DOM.WSDLUriToVersion(definitions.namespaceURI)
  156. NS_WSDL = DOM.GetWSDLUri(self.version)
  157. self.targetNamespace = DOM.getAttr(definitions, 'targetNamespace',
  158. None, None)
  159. self.name = DOM.getAttr(definitions, 'name', None, None)
  160. self.documentation = GetDocumentation(definitions)
  161. #
  162. # Retrieve all <wsdl:import>'s, append all children of imported
  163. # document to main document. First iteration grab all original
  164. # <wsdl:import>'s from document, second iteration grab all
  165. # "imported" <wsdl:imports> from document, etc break out when
  166. # no more <wsdl:import>'s.
  167. #
  168. imported = []
  169. base_location = self.location
  170. do_it = True
  171. while do_it:
  172. do_it = False
  173. for element in DOM.getElements(definitions, 'import', NS_WSDL):
  174. location = DOM.getAttr(element, 'location')
  175. if base_location is not None:
  176. location = basejoin(base_location, location)
  177. if location not in imported:
  178. do_it = True
  179. self._import(document, element, base_location)
  180. imported.append(location)
  181. else:
  182. definitions.removeChild(element)
  183. base_location = None
  184. #
  185. # No more <wsdl:import>'s, now load up all other
  186. # WSDL information items.
  187. #
  188. for element in DOM.getElements(definitions, None, None):
  189. targetNamespace = DOM.getAttr(element, 'targetNamespace')
  190. localName = element.localName
  191. if not DOM.nsUriMatch(element.namespaceURI, NS_WSDL):
  192. if localName == 'schema':
  193. tns = DOM.getAttr(element, 'targetNamespace')
  194. reader = SchemaReader(base_url=self.imports[tns].location)
  195. schema = reader.loadFromNode(WSDLToolsAdapter(self),
  196. element)
  197. # schema.setBaseUrl(self.location)
  198. self.types.addSchema(schema)
  199. else:
  200. self.extensions.append(element)
  201. continue
  202. elif localName == 'message':
  203. name = DOM.getAttr(element, 'name')
  204. docs = GetDocumentation(element)
  205. message = self.addMessage(name, docs, targetNamespace)
  206. parts = DOM.getElements(element, 'part', NS_WSDL)
  207. message.load(parts)
  208. continue
  209. elif localName == 'portType':
  210. name = DOM.getAttr(element, 'name')
  211. docs = GetDocumentation(element)
  212. ptype = self.addPortType(name, docs, targetNamespace)
  213. #operations = DOM.getElements(element, 'operation', NS_WSDL)
  214. #ptype.load(operations)
  215. ptype.load(element)
  216. continue
  217. elif localName == 'binding':
  218. name = DOM.getAttr(element, 'name')
  219. type = DOM.getAttr(element, 'type', default=None)
  220. if type is None:
  221. raise WSDLError(
  222. 'Missing type attribute for binding %s.' % name
  223. )
  224. type = ParseQName(type, element)
  225. docs = GetDocumentation(element)
  226. binding = self.addBinding(name, type, docs, targetNamespace)
  227. operations = DOM.getElements(element, 'operation', NS_WSDL)
  228. binding.load(operations)
  229. binding.load_ex(GetExtensions(element))
  230. continue
  231. elif localName == 'service':
  232. name = DOM.getAttr(element, 'name')
  233. docs = GetDocumentation(element)
  234. service = self.addService(name, docs, targetNamespace)
  235. ports = DOM.getElements(element, 'port', NS_WSDL)
  236. service.load(ports)
  237. service.load_ex(GetExtensions(element))
  238. continue
  239. elif localName == 'types':
  240. self.types.documentation = GetDocumentation(element)
  241. base_location = DOM.getAttr(element, 'base-location')
  242. if base_location:
  243. element.removeAttribute('base-location')
  244. base_location = base_location or self.location
  245. reader = SchemaReader(base_url=base_location)
  246. for item in DOM.getElements(element, None, None):
  247. if item.localName == 'schema':
  248. schema = reader.loadFromNode(WSDLToolsAdapter(self), item)
  249. # XXX <types> could have been imported
  250. #schema.setBaseUrl(self.location)
  251. schema.setBaseUrl(base_location)
  252. self.types.addSchema(schema)
  253. else:
  254. self.types.addExtension(item)
  255. # XXX remove the attribute
  256. # element.removeAttribute('base-location')
  257. continue
  258. def _import(self, document, element, base_location=None):
  259. '''Algo take <import> element's children, clone them,
  260. and add them to the main document. Support for relative
  261. locations is a bit complicated. The orig document context
  262. is lost, so we need to store base location in DOM elements
  263. representing <types>, by creating a special temporary
  264. "base-location" attribute, and <import>, by resolving
  265. the relative "location" and storing it as "location".
  266. document -- document we are loading
  267. element -- DOM Element representing <import>
  268. base_location -- location of document from which this
  269. <import> was gleaned.
  270. '''
  271. namespace = DOM.getAttr(element, 'namespace', default=None)
  272. location = DOM.getAttr(element, 'location', default=None)
  273. if namespace is None or location is None:
  274. raise WSDLError(
  275. 'Invalid import element (missing namespace or location).'
  276. )
  277. if base_location:
  278. location = basejoin(base_location, location)
  279. element.setAttributeNS(None, 'location', location)
  280. obimport = self.addImport(namespace, location)
  281. obimport._loaded = 1
  282. importdoc = DOM.loadFromURL(location)
  283. try:
  284. if location.find('#') > -1:
  285. idref = location.split('#')[-1]
  286. imported = DOM.getElementById(importdoc, idref)
  287. else:
  288. imported = importdoc.documentElement
  289. if imported is None:
  290. raise WSDLError(
  291. 'Import target element not found for: %s' % location
  292. )
  293. imported_tns = DOM.findTargetNS(imported)
  294. if imported_tns != namespace:
  295. return
  296. if imported.localName == 'definitions':
  297. imported_nodes = imported.childNodes
  298. else:
  299. imported_nodes = [imported]
  300. parent = element.parentNode
  301. parent.removeChild(element)
  302. for node in imported_nodes:
  303. if node.nodeType != node.ELEMENT_NODE:
  304. continue
  305. child = DOM.importNode(document, node, 1)
  306. parent.appendChild(child)
  307. child.setAttribute('targetNamespace', namespace)
  308. attrsNS = imported._attrsNS
  309. for attrkey in attrsNS.keys():
  310. if attrkey[0] == DOM.NS_XMLNS:
  311. attr = attrsNS[attrkey].cloneNode(1)
  312. child.setAttributeNode(attr)
  313. #XXX Quick Hack, should be in WSDL Namespace.
  314. if child.localName == 'import':
  315. rlocation = child.getAttributeNS(None, 'location')
  316. alocation = basejoin(location, rlocation)
  317. child.setAttribute('location', alocation)
  318. elif child.localName == 'types':
  319. child.setAttribute('base-location', location)
  320. finally:
  321. importdoc.unlink()
  322. return location
  323. class Element:
  324. """A class that provides common functions for WSDL element classes."""
  325. def __init__(self, name=None, documentation=''):
  326. self.name = name
  327. self.documentation = documentation
  328. self.extensions = []
  329. def addExtension(self, item):
  330. item.parent = weakref.ref(self)
  331. self.extensions.append(item)
  332. class ImportElement(Element):
  333. def __init__(self, namespace, location):
  334. self.namespace = namespace
  335. self.location = location
  336. def getWSDL(self):
  337. """Return the WSDL object that contains this Message Part."""
  338. return self.parent().parent()
  339. def toDom(self):
  340. wsdl = self.getWSDL()
  341. ep = ElementProxy(None, DOM.getElement(wsdl.document, None))
  342. epc = ep.createAppendElement(DOM.GetWSDLUri(wsdl.version), 'import')
  343. epc.setAttributeNS(None, 'namespace', self.namespace)
  344. epc.setAttributeNS(None, 'location', self.location)
  345. _loaded = None
  346. class Types(Collection):
  347. default = lambda self,k: k.targetNamespace
  348. def __init__(self, parent):
  349. Collection.__init__(self, parent)
  350. self.documentation = ''
  351. self.extensions = []
  352. def addSchema(self, schema):
  353. name = schema.targetNamespace
  354. self[name] = schema
  355. return schema
  356. def addExtension(self, item):
  357. self.extensions.append(item)
  358. class Message(Element):
  359. def __init__(self, name, documentation=''):
  360. Element.__init__(self, name, documentation)
  361. self.parts = Collection(self)
  362. def addPart(self, name, type=None, element=None):
  363. if self.parts.has_key(name):
  364. raise WSDLError(
  365. 'Duplicate message part element: %s' % name
  366. )
  367. if type is None and element is None:
  368. raise WSDLError(
  369. 'Missing type or element attribute for part: %s' % name
  370. )
  371. item = MessagePart(name)
  372. item.element = element
  373. item.type = type
  374. self.parts[name] = item
  375. return item
  376. def load(self, elements):
  377. for element in elements:
  378. name = DOM.getAttr(element, 'name')
  379. part = MessagePart(name)
  380. self.parts[name] = part
  381. elemref = DOM.getAttr(element, 'element', default=None)
  382. typeref = DOM.getAttr(element, 'type', default=None)
  383. if typeref is None and elemref is None:
  384. raise WSDLError(
  385. 'No type or element attribute for part: %s' % name
  386. )
  387. if typeref is not None:
  388. part.type = ParseTypeRef(typeref, element)
  389. if elemref is not None:
  390. part.element = ParseTypeRef(elemref, element)
  391. def getElementDeclaration(self):
  392. """Return the XMLSchema.ElementDeclaration instance or None"""
  393. element = None
  394. if self.element:
  395. nsuri,name = self.element
  396. wsdl = self.getWSDL()
  397. if wsdl.types.has_key(nsuri) and wsdl.types[nsuri].elements.has_key(name):
  398. element = wsdl.types[nsuri].elements[name]
  399. return element
  400. def getTypeDefinition(self):
  401. """Return the XMLSchema.TypeDefinition instance or None"""
  402. type = None
  403. if self.type:
  404. nsuri,name = self.type
  405. wsdl = self.getWSDL()
  406. if wsdl.types.has_key(nsuri) and wsdl.types[nsuri].types.has_key(name):
  407. type = wsdl.types[nsuri].types[name]
  408. return type
  409. def getWSDL(self):
  410. """Return the WSDL object that contains this Message Part."""
  411. return self.parent().parent()
  412. def toDom(self):
  413. wsdl = self.getWSDL()
  414. ep = ElementProxy(None, DOM.getElement(wsdl.document, None))
  415. epc = ep.createAppendElement(DOM.GetWSDLUri(wsdl.version), 'message')
  416. epc.setAttributeNS(None, 'name', self.name)
  417. for part in self.parts:
  418. part.toDom(epc._getNode())
  419. class MessagePart(Element):
  420. def __init__(self, name):
  421. Element.__init__(self, name, '')
  422. self.element = None
  423. self.type = None
  424. def getWSDL(self):
  425. """Return the WSDL object that contains this Message Part."""
  426. return self.parent().parent().parent().parent()
  427. def getTypeDefinition(self):
  428. wsdl = self.getWSDL()
  429. nsuri,name = self.type
  430. schema = wsdl.types.get(nsuri, {})
  431. return schema.get(name)
  432. def getElementDeclaration(self):
  433. wsdl = self.getWSDL()
  434. nsuri,name = self.element
  435. schema = wsdl.types.get(nsuri, {})
  436. return schema.get(name)
  437. def toDom(self, node):
  438. """node -- node representing message"""
  439. wsdl = self.getWSDL()
  440. ep = ElementProxy(None, node)
  441. epc = ep.createAppendElement(DOM.GetWSDLUri(wsdl.version), 'part')
  442. epc.setAttributeNS(None, 'name', self.name)
  443. if self.element is not None:
  444. ns,name = self.element
  445. prefix = epc.getPrefix(ns)
  446. epc.setAttributeNS(None, 'element', '%s:%s'%(prefix,name))
  447. elif self.type is not None:
  448. ns,name = self.type
  449. prefix = epc.getPrefix(ns)
  450. epc.setAttributeNS(None, 'type', '%s:%s'%(prefix,name))
  451. class PortType(Element):
  452. '''PortType has a anyAttribute, thus must provide for an extensible
  453. mechanism for supporting such attributes. ResourceProperties is
  454. specified in WS-ResourceProperties. wsa:Action is specified in
  455. WS-Address.
  456. Instance Data:
  457. name -- name attribute
  458. resourceProperties -- optional. wsr:ResourceProperties attribute,
  459. value is a QName this is Parsed into a (namespaceURI, name)
  460. that represents a Global Element Declaration.
  461. operations
  462. '''
  463. def __init__(self, name, documentation=''):
  464. Element.__init__(self, name, documentation)
  465. self.operations = Collection(self)
  466. self.resourceProperties = None
  467. def getWSDL(self):
  468. return self.parent().parent()
  469. def getTargetNamespace(self):
  470. return self.targetNamespace or self.getWSDL().targetNamespace
  471. def getResourceProperties(self):
  472. return self.resourceProperties
  473. def addOperation(self, name, documentation='', parameterOrder=None):
  474. item = Operation(name, documentation, parameterOrder)
  475. self.operations[name] = item
  476. return item
  477. def load(self, element):
  478. self.name = DOM.getAttr(element, 'name')
  479. self.documentation = GetDocumentation(element)
  480. self.targetNamespace = DOM.getAttr(element, 'targetNamespace')
  481. for nsuri in WSRF_V1_2.PROPERTIES.XSD_LIST:
  482. if DOM.hasAttr(element, 'ResourceProperties', nsuri):
  483. rpref = DOM.getAttr(element, 'ResourceProperties', nsuri)
  484. self.resourceProperties = ParseQName(rpref, element)
  485. NS_WSDL = DOM.GetWSDLUri(self.getWSDL().version)
  486. elements = DOM.getElements(element, 'operation', NS_WSDL)
  487. for element in elements:
  488. name = DOM.getAttr(element, 'name')
  489. docs = GetDocumentation(element)
  490. param_order = DOM.getAttr(element, 'parameterOrder', default=None)
  491. if param_order is not None:
  492. param_order = param_order.split(' ')
  493. operation = self.addOperation(name, docs, param_order)
  494. item = DOM.getElement(element, 'input', None, None)
  495. if item is not None:
  496. name = DOM.getAttr(item, 'name')
  497. docs = GetDocumentation(item)
  498. msgref = DOM.getAttr(item, 'message')
  499. message = ParseQName(msgref, item)
  500. for WSA in WSA_LIST:
  501. action = DOM.getAttr(item, 'Action', WSA.ADDRESS, None)
  502. if action: break
  503. operation.setInput(message, name, docs, action)
  504. item = DOM.getElement(element, 'output', None, None)
  505. if item is not None:
  506. name = DOM.getAttr(item, 'name')
  507. docs = GetDocumentation(item)
  508. msgref = DOM.getAttr(item, 'message')
  509. message = ParseQName(msgref, item)
  510. for WSA in WSA_LIST:
  511. action = DOM.getAttr(item, 'Action', WSA.ADDRESS, None)
  512. if action: break
  513. operation.setOutput(message, name, docs, action)
  514. for item in DOM.getElements(element, 'fault', None):
  515. name = DOM.getAttr(item, 'name')
  516. docs = GetDocumentation(item)
  517. msgref = DOM.getAttr(item, 'message')
  518. message = ParseQName(msgref, item)
  519. for WSA in WSA_LIST:
  520. action = DOM.getAttr(item, 'Action', WSA.ADDRESS, None)
  521. if action: break
  522. operation.addFault(message, name, docs, action)
  523. def toDom(self):
  524. wsdl = self.getWSDL()
  525. ep = ElementProxy(None, DOM.getElement(wsdl.document, None))
  526. epc = ep.createAppendElement(DOM.GetWSDLUri(wsdl.version), 'portType')
  527. epc.setAttributeNS(None, 'name', self.name)
  528. if self.resourceProperties:
  529. ns,name = self.resourceProperties
  530. prefix = epc.getPrefix(ns)
  531. epc.setAttributeNS(WSRF.PROPERTIES.LATEST, 'ResourceProperties', '%s:%s'%(prefix,name))
  532. for op in self.operations:
  533. op.toDom(epc._getNode())
  534. class Operation(Element):
  535. def __init__(self, name, documentation='', parameterOrder=None):
  536. Element.__init__(self, name, documentation)
  537. self.parameterOrder = parameterOrder
  538. self.faults = Collection(self)
  539. self.input = None
  540. self.output = None
  541. def getWSDL(self):
  542. """Return the WSDL object that contains this Operation."""
  543. return self.parent().parent().parent().parent()
  544. def getPortType(self):
  545. return self.parent().parent()
  546. def getInputAction(self):
  547. """wsa:Action attribute"""
  548. return GetWSAActionInput(self)
  549. def getInputMessage(self):
  550. if self.input is None:
  551. return None
  552. wsdl = self.getPortType().getWSDL()
  553. return wsdl.messages[self.input.message]
  554. def getOutputAction(self):
  555. """wsa:Action attribute"""
  556. return GetWSAActionOutput(self)
  557. def getOutputMessage(self):
  558. if self.output is None:
  559. return None
  560. wsdl = self.getPortType().getWSDL()
  561. return wsdl.messages[self.output.message]
  562. def getFaultAction(self, name):
  563. """wsa:Action attribute"""
  564. return GetWSAActionFault(self, name)
  565. def getFaultMessage(self, name):
  566. wsdl = self.getPortType().getWSDL()
  567. return wsdl.messages[self.faults[name].message]
  568. def addFault(self, message, name, documentation='', action=None):
  569. if self.faults.has_key(name):
  570. raise WSDLError(
  571. 'Duplicate fault element: %s' % name
  572. )
  573. item = MessageRole('fault', message, name, documentation, action)
  574. self.faults[name] = item
  575. return item
  576. def setInput(self, message, name='', documentation='', action=None):
  577. self.input = MessageRole('input', message, name, documentation, action)
  578. self.input.parent = weakref.ref(self)
  579. return self.input
  580. def setOutput(self, message, name='', documentation='', action=None):
  581. self.output = MessageRole('output', message, name, documentation, action)
  582. self.output.parent = weakref.ref(self)
  583. return self.output
  584. def toDom(self, node):
  585. wsdl = self.getWSDL()
  586. ep = ElementProxy(None, node)
  587. epc = ep.createAppendElement(DOM.GetWSDLUri(wsdl.version), 'operation')
  588. epc.setAttributeNS(None, 'name', self.name)
  589. node = epc._getNode()
  590. if self.input:
  591. self.input.toDom(node)
  592. if self.output:
  593. self.output.toDom(node)
  594. for fault in self.faults:
  595. fault.toDom(node)
  596. class MessageRole(Element):
  597. def __init__(self, type, message, name='', documentation='', action=None):
  598. Element.__init__(self, name, documentation)
  599. self.message = message
  600. self.type = type
  601. self.action = action
  602. def getWSDL(self):
  603. """Return the WSDL object that contains this MessageRole."""
  604. if self.parent().getWSDL() == 'fault':
  605. return self.parent().parent().getWSDL()
  606. return self.parent().getWSDL()
  607. def getMessage(self):
  608. """Return the WSDL object that represents the attribute message
  609. (namespaceURI, name) tuple
  610. """
  611. wsdl = self.getWSDL()
  612. return wsdl.messages[self.message]
  613. def toDom(self, node):
  614. wsdl = self.getWSDL()
  615. ep = ElementProxy(None, node)
  616. epc = ep.createAppendElement(DOM.GetWSDLUri(wsdl.version), self.type)
  617. epc.setAttributeNS(None, 'message', self.message)
  618. if self.action:
  619. epc.setAttributeNS(WSA.ADDRESS, 'Action', self.action)
  620. class Binding(Element):
  621. def __init__(self, name, type, documentation=''):
  622. Element.__init__(self, name, documentation)
  623. self.operations = Collection(self)
  624. self.type = type
  625. def getWSDL(self):
  626. """Return the WSDL object that contains this binding."""
  627. return self.parent().parent()
  628. def getPortType(self):
  629. """Return the PortType object associated with this binding."""
  630. return self.getWSDL().portTypes[self.type]
  631. def findBinding(self, kind):
  632. for item in self.extensions:
  633. if isinstance(item, kind):
  634. return item
  635. return None
  636. def findBindings(self, kind):
  637. return [ item for item in self.extensions if isinstance(item, kind) ]
  638. def addOperationBinding(self, name, documentation=''):
  639. item = OperationBinding(name, documentation)
  640. self.operations[name] = item
  641. return item
  642. def load(self, elements):
  643. for element in elements:
  644. name = DOM.getAttr(element, 'name')
  645. docs = GetDocumentation(element)
  646. opbinding = self.addOperationBinding(name, docs)
  647. opbinding.load_ex(GetExtensions(element))
  648. item = DOM.getElement(element, 'input', None, None)
  649. if item is not None:
  650. mbinding = MessageRoleBinding('input')
  651. mbinding.documentation = GetDocumentation(item)
  652. opbinding.input = mbinding
  653. mbinding.load_ex(GetExtensions(item))
  654. item = DOM.getElement(element, 'output', None, None)
  655. if item is not None:
  656. mbinding = MessageRoleBinding('output')
  657. mbinding.documentation = GetDocumentation(item)
  658. opbinding.output = mbinding
  659. mbinding.load_ex(GetExtensions(item))
  660. for item in DOM.getElements(element, 'fault', None):
  661. name = DOM.getAttr(item, 'name')
  662. mbinding = MessageRoleBinding('fault', name)
  663. mbinding.documentation = GetDocumentation(item)
  664. opbinding.faults[name] = mbinding
  665. mbinding.load_ex(GetExtensions(item))
  666. def load_ex(self, elements):
  667. for e in elements:
  668. ns, name = e.namespaceURI, e.localName
  669. if ns in DOM.NS_SOAP_BINDING_ALL and name == 'binding':
  670. transport = DOM.getAttr(e, 'transport', default=None)
  671. style = DOM.getAttr(e, 'style', default='document')
  672. ob = SoapBinding(transport, style)
  673. self.addExtension(ob)
  674. continue
  675. elif ns in DOM.NS_HTTP_BINDING_ALL and name == 'binding':
  676. verb = DOM.getAttr(e, 'verb')
  677. ob = HttpBinding(verb)
  678. self.addExtension(ob)
  679. continue
  680. else:
  681. self.addExtension(e)
  682. def toDom(self):
  683. wsdl = self.getWSDL()
  684. ep = ElementProxy(None, DOM.getElement(wsdl.document, None))
  685. epc = ep.createAppendElement(DOM.GetWSDLUri(wsdl.version), 'binding')
  686. epc.setAttributeNS(None, 'name', self.name)
  687. ns,name = self.type
  688. prefix = epc.getPrefix(ns)
  689. epc.setAttributeNS(None, 'type', '%s:%s' %(prefix,name))
  690. node = epc._getNode()
  691. for ext in self.extensions:
  692. ext.toDom(node)
  693. for op_binding in self.operations:
  694. op_binding.toDom(node)
  695. class OperationBinding(Element):
  696. def __init__(self, name, documentation=''):
  697. Element.__init__(self, name, documentation)
  698. self.input = None
  699. self.output = None
  700. self.faults = Collection(self)
  701. def getWSDL(self):
  702. """Return the WSDL object that contains this binding."""
  703. return self.parent().parent().parent().parent()
  704. def getBinding(self):
  705. """Return the parent Binding object of the operation binding."""
  706. return self.parent().parent()
  707. def getOperation(self):
  708. """Return the abstract Operation associated with this binding."""
  709. return self.getBinding().getPortType().operations[self.name]
  710. def findBinding(self, kind):
  711. for item in self.extensions:
  712. if isinstance(item, kind):
  713. return item
  714. return None
  715. def findBindings(self, kind):
  716. return [ item for item in self.extensions if isinstance(item, kind) ]
  717. def addInputBinding(self, binding):
  718. if self.input is None:
  719. self.input = MessageRoleBinding('input')
  720. self.input.parent = weakref.ref(self)
  721. self.input.addExtension(binding)
  722. return binding
  723. def addOutputBinding(self, binding):
  724. if self.output is None:
  725. self.output = MessageRoleBinding('output')
  726. self.output.parent = weakref.ref(self)
  727. self.output.addExtension(binding)
  728. return binding
  729. def addFaultBinding(self, name, binding):
  730. fault = self.get(name, None)
  731. if fault is None:
  732. fault = MessageRoleBinding('fault', name)
  733. fault.addExtension(binding)
  734. return binding
  735. def load_ex(self, elements):
  736. for e in elements:
  737. ns, name = e.namespaceURI, e.localName
  738. if ns in DOM.NS_SOAP_BINDING_ALL and name == 'operation':
  739. soapaction = DOM.getAttr(e, 'soapAction', default=None)
  740. style = DOM.getAttr(e, 'style', default=None)
  741. ob = SoapOperationBinding(soapaction, style)
  742. self.addExtension(ob)
  743. continue
  744. elif ns in DOM.NS_HTTP_BINDING_ALL and name == 'operation':
  745. location = DOM.getAttr(e, 'location')
  746. ob = HttpOperationBinding(location)
  747. self.addExtension(ob)
  748. continue
  749. else:
  750. self.addExtension(e)
  751. def toDom(self, node):
  752. wsdl = self.getWSDL()
  753. ep = ElementProxy(None, node)
  754. epc = ep.createAppendElement(DOM.GetWSDLUri(wsdl.version), 'operation')
  755. epc.setAttributeNS(None, 'name', self.name)
  756. node = epc._getNode()
  757. for ext in self.extensions:
  758. ext.toDom(node)
  759. if self.input:
  760. self.input.toDom(node)
  761. if self.output:
  762. self.output.toDom(node)
  763. for fault in self.faults:
  764. fault.toDom(node)
  765. class MessageRoleBinding(Element):
  766. def __init__(self, type, name='', documentation=''):
  767. Element.__init__(self, name, documentation)
  768. self.type = type
  769. def getWSDL(self):
  770. """Return the WSDL object that contains this MessageRole."""
  771. if self.type == 'fault':
  772. return self.parent().parent().getWSDL()
  773. return self.parent().getWSDL()
  774. def findBinding(self, kind):
  775. for item in self.extensions:
  776. if isinstance(item, kind):
  777. return item
  778. return None
  779. def findBindings(self, kind):
  780. return [ item for item in self.extensions if isinstance(item, kind) ]
  781. def load_ex(self, elements):
  782. for e in elements:
  783. ns, name = e.namespaceURI, e.localName
  784. if ns in DOM.NS_SOAP_BINDING_ALL and name == 'body':
  785. encstyle = DOM.getAttr(e, 'encodingStyle', default=None)
  786. namespace = DOM.getAttr(e, 'namespace', default=None)
  787. parts = DOM.getAttr(e, 'parts', default=None)
  788. use = DOM.getAttr(e, 'use', default=None)
  789. if use is None:
  790. raise WSDLError(
  791. 'Invalid soap:body binding element.'
  792. )
  793. ob = SoapBodyBinding(use, namespace, encstyle, parts)
  794. self.addExtension(ob)
  795. continue
  796. elif ns in DOM.NS_SOAP_BINDING_ALL and name == 'fault':
  797. encstyle = DOM.getAttr(e, 'encodingStyle', default=None)
  798. namespace = DOM.getAttr(e, 'namespace', default=None)
  799. name = DOM.getAttr(e, 'name', default=None)
  800. use = DOM.getAttr(e, 'use', default=None)
  801. if use is None or name is None:
  802. raise WSDLError(
  803. 'Invalid soap:fault binding element.'
  804. )
  805. ob = SoapFaultBinding(name, use, namespace, encstyle)
  806. self.addExtension(ob)
  807. continue
  808. elif ns in DOM.NS_SOAP_BINDING_ALL and name in (
  809. 'header', 'headerfault'
  810. ):
  811. encstyle = DOM.getAttr(e, 'encodingStyle', default=None)
  812. namespace = DOM.getAttr(e, 'namespace', default=None)
  813. message = DOM.getAttr(e, 'message')
  814. part = DOM.getAttr(e, 'part')
  815. use = DOM.getAttr(e, 'use')
  816. if name == 'header':
  817. _class = SoapHeaderBinding
  818. else:
  819. _class = SoapHeaderFaultBinding
  820. message = ParseQName(message, e)
  821. ob = _class(message, part, use, namespace, encstyle)
  822. self.addExtension(ob)
  823. continue
  824. elif ns in DOM.NS_HTTP_BINDING_ALL and name == 'urlReplacement':
  825. ob = HttpUrlReplacementBinding()
  826. self.addExtension(ob)
  827. continue
  828. elif ns in DOM.NS_HTTP_BINDING_ALL and name == 'urlEncoded':
  829. ob = HttpUrlEncodedBinding()
  830. self.addExtension(ob)
  831. continue
  832. elif ns in DOM.NS_MIME_BINDING_ALL and name == 'multipartRelated':
  833. ob = MimeMultipartRelatedBinding()
  834. self.addExtension(ob)
  835. ob.load_ex(GetExtensions(e))
  836. continue
  837. elif ns in DOM.NS_MIME_BINDING_ALL and name == 'content':
  838. part = DOM.getAttr(e, 'part', default=None)
  839. type = DOM.getAttr(e, 'type', default=None)
  840. ob = MimeContentBinding(part, type)
  841. self.addExtension(ob)
  842. continue
  843. elif ns in DOM.NS_MIME_BINDING_ALL and name == 'mimeXml':
  844. part = DOM.getAttr(e, 'part', default=None)
  845. ob = MimeXmlBinding(part)
  846. self.addExtension(ob)
  847. continue
  848. else:
  849. self.addExtension(e)
  850. def toDom(self, node):
  851. wsdl = self.getWSDL()
  852. ep = ElementProxy(None, node)
  853. epc = ep.createAppendElement(DOM.GetWSDLUri(wsdl.version), self.type)
  854. node = epc._getNode()
  855. for item in self.extensions:
  856. if item: item.toDom(node)
  857. class Service(Element):
  858. def __init__(self, name, documentation=''):
  859. Element.__init__(self, name, documentation)
  860. self.ports = Collection(self)
  861. def getWSDL(self):
  862. return self.parent().parent()
  863. def addPort(self, name, binding, documentation=''):
  864. item = Port(name, binding, documentation)
  865. self.ports[name] = item
  866. return item
  867. def load(self, elements):
  868. for element in elements:
  869. name = DOM.getAttr(element, 'name', default=None)
  870. docs = GetDocumentation(element)
  871. binding = DOM.getAttr(element, 'binding', default=None)
  872. if name is None or binding is None:
  873. raise WSDLError(
  874. 'Invalid port element.'
  875. )
  876. binding = ParseQName(binding, element)
  877. port = self.addPort(name, binding, docs)
  878. port.load_ex(GetExtensions(element))
  879. def load_ex(self, elements):
  880. for e in elements:
  881. self.addExtension(e)
  882. def toDom(self):
  883. wsdl = self.getWSDL()
  884. ep = ElementProxy(None, DOM.getElement(wsdl.document, None))
  885. epc = ep.createAppendElement(DOM.GetWSDLUri(wsdl.version), "service")
  886. epc.setAttributeNS(None, "name", self.name)
  887. node = epc._getNode()
  888. for port in self.ports:
  889. port.toDom(node)
  890. class Port(Element):
  891. def __init__(self, name, binding, documentation=''):
  892. Element.__init__(self, name, documentation)
  893. self.binding = binding
  894. def getWSDL(self):
  895. return self.parent().parent().getWSDL()
  896. def getService(self):
  897. """Return the Service object associated with this port."""
  898. return self.parent().parent()
  899. def getBinding(self):
  900. """Return the Binding object that is referenced by this port."""
  901. wsdl = self.getService().getWSDL()
  902. return wsdl.bindings[self.binding]
  903. def getPortType(self):
  904. """Return the PortType object that is referenced by this port."""
  905. wsdl = self.getService().getWSDL()
  906. binding = wsdl.bindings[self.binding]
  907. return wsdl.portTypes[binding.type]
  908. def getAddressBinding(self):
  909. """A convenience method to obtain the extension element used
  910. as the address binding for the port."""
  911. for item in self.extensions:
  912. if isinstance(item, SoapAddressBinding) or \
  913. isinstance(item, HttpAddressBinding):
  914. return item
  915. raise WSDLError(
  916. 'No address binding found in port.'
  917. )
  918. def load_ex(self, elements):
  919. for e in elements:
  920. ns, name = e.namespaceURI, e.localName
  921. if ns in DOM.NS_SOAP_BINDING_ALL and name == 'address':
  922. location = DOM.getAttr(e, 'location', default=None)
  923. ob = SoapAddressBinding(location)
  924. self.addExtension(ob)
  925. continue
  926. elif ns in DOM.NS_HTTP_BINDING_ALL and name == 'address':
  927. location = DOM.getAttr(e, 'location', default=None)
  928. ob = HttpAddressBinding(location)
  929. self.addExtension(ob)
  930. continue
  931. else:
  932. self.addExtension(e)
  933. def toDom(self, node):
  934. wsdl = self.getWSDL()
  935. ep = ElementProxy(None, node)
  936. epc = ep.createAppendElement(DOM.GetWSDLUri(wsdl.version), "port")
  937. epc.setAttributeNS(None, "name", self.name)
  938. ns,name = self.binding
  939. prefix = epc.getPrefix(ns)
  940. epc.setAttributeNS(None, "binding", "%s:%s" %(prefix,name))
  941. node = epc._getNode()
  942. for ext in self.extensions:
  943. ext.toDom(node)
  944. class SoapBinding:
  945. def __init__(self, transport, style='rpc'):
  946. self.transport = transport
  947. self.style = style
  948. def getWSDL(self):
  949. return self.parent().getWSDL()
  950. def toDom(self, node):
  951. wsdl = self.getWSDL()
  952. ep = ElementProxy(None, node)
  953. epc = ep.createAppendElement(DOM.GetWSDLSoapBindingUri(wsdl.version), 'binding')
  954. if self.transport:
  955. epc.setAttributeNS(None, "transport", self.transport)
  956. if self.style:
  957. epc.setAttributeNS(None, "style", self.style)
  958. class SoapAddressBinding:
  959. def __init__(self, location):
  960. self.location = location
  961. def getWSDL(self):
  962. return self.parent().getWSDL()
  963. def toDom(self, node):
  964. wsdl = self.getWSDL()
  965. ep = ElementProxy(None, node)
  966. epc = ep.createAppendElement(DOM.GetWSDLSoapBindingUri(wsdl.version), 'address')
  967. epc.setAttributeNS(None, "location", self.location)
  968. class SoapOperationBinding:
  969. def __init__(self, soapAction=None, style=None):
  970. self.soapAction = soapAction
  971. self.style = style
  972. def getWSDL(self):
  973. return self.parent().getWSDL()
  974. def toDom(self, node):
  975. wsdl = self.getWSDL()
  976. ep = ElementProxy(None, node)
  977. epc = ep.createAppendElement(DOM.GetWSDLSoapBindingUri(wsdl.version), 'operation')
  978. if self.soapAction:
  979. epc.setAttributeNS(None, 'soapAction', self.soapAction)
  980. if self.style:
  981. epc.setAttributeNS(None, 'style', self.style)
  982. class SoapBodyBinding:
  983. def __init__(self, use, namespace=None, encodingStyle=None, parts=None):
  984. if not use in ('literal', 'encoded'):
  985. raise WSDLError(
  986. 'Invalid use attribute value: %s' % use
  987. )
  988. self.encodingStyle = encodingStyle
  989. self.namespace = namespace
  990. if type(parts) in (type(''), type(u'')):
  991. parts = parts.split()
  992. self.parts = parts
  993. self.use = use
  994. def getWSDL(self):
  995. return self.parent().getWSDL()
  996. def toDom(self, node):
  997. wsdl = self.getWSDL()
  998. ep = ElementProxy(None, node)
  999. epc = ep.createAppendElement(DOM.GetWSDLSoapBindingUri(wsdl.version), 'body')
  1000. epc.setAttributeNS(None, "use", self.use)
  1001. epc.setAttributeNS(None, "namespace", self.namespace)
  1002. class SoapFaultBinding:
  1003. def __init__(self, name, use, namespace=None, encodingStyle=None):
  1004. if not use in ('literal', 'encoded'):
  1005. raise WSDLError(
  1006. 'Invalid use attribute value: %s' % use
  1007. )
  1008. self.encodingStyle = encodingStyle
  1009. self.namespace = namespace
  1010. self.name = name
  1011. self.use = use
  1012. class SoapHeaderBinding:
  1013. def __init__(self, message, part, use, namespace=None, encodingStyle=None):
  1014. if not use in ('literal', 'encoded'):
  1015. raise WSDLError(
  1016. 'Invalid use attribute value: %s' % use
  1017. )
  1018. self.encodingStyle = encodingStyle
  1019. self.namespace = namespace
  1020. self.message = message
  1021. self.part = part
  1022. self.use = use
  1023. tagname = 'header'
  1024. class SoapHeaderFaultBinding(SoapHeaderBinding):
  1025. tagname = 'headerfault'
  1026. class HttpBinding:
  1027. def __init__(self, verb):
  1028. self.verb = verb
  1029. class HttpAddressBinding:
  1030. def __init__(self, location):
  1031. self.location = location
  1032. class HttpOperationBinding:
  1033. def __init__(self, location):
  1034. self.location = location
  1035. class HttpUrlReplacementBinding:
  1036. pass
  1037. class HttpUrlEncodedBinding:
  1038. pass
  1039. class MimeContentBinding:
  1040. def __init__(self, part=None, type=None):
  1041. self.part = part
  1042. self.type = type
  1043. class MimeXmlBinding:
  1044. def __init__(self, part=None):
  1045. self.part = part
  1046. class MimeMultipartRelatedBinding:
  1047. def __init__(self):
  1048. self.parts = []
  1049. def load_ex(self, elements):
  1050. for e in elements:
  1051. ns, name = e.namespaceURI, e.localName
  1052. if ns in DOM.NS_MIME_BINDING_ALL and name == 'part':
  1053. self.parts.append(MimePartBinding())
  1054. continue
  1055. class MimePartBinding:
  1056. def __init__(self):
  1057. self.items = []
  1058. def load_ex(self, elements):
  1059. for e in elements:
  1060. ns, name = e.namespaceURI, e.localName
  1061. if ns in DOM.NS_MIME_BINDING_ALL and name == 'content':
  1062. part = DOM.getAttr(e, 'part', default=None)
  1063. type = DOM.getAttr(e, 'type', default=None)
  1064. ob = MimeContentBinding(part, type)
  1065. self.items.append(ob)
  1066. continue
  1067. elif ns in DOM.NS_MIME_BINDING_ALL and name == 'mimeXml':
  1068. part = DOM.getAttr(e, 'part', default=None)
  1069. ob = MimeXmlBinding(part)
  1070. self.items.append(ob)
  1071. continue
  1072. elif ns in DOM.NS_SOAP_BINDING_ALL and name == 'body':
  1073. encstyle = DOM.getAttr(e, 'encodingStyle', default=None)
  1074. namespace = DOM.getAttr(e, 'namespace', default=None)
  1075. parts = DOM.getAttr(e, 'parts', default=None)
  1076. use = DOM.getAttr(e, 'use', default=None)
  1077. if use is None:
  1078. raise WSDLError(
  1079. 'Invalid soap:body binding element.'
  1080. )
  1081. ob = SoapBodyBinding(use, namespace, encstyle, parts)
  1082. self.items.append(ob)
  1083. continue
  1084. class WSDLError(Exception):
  1085. pass
  1086. def DeclareNSPrefix(writer, prefix, nsuri):
  1087. if writer.hasNSPrefix(nsuri):
  1088. return
  1089. writer.declareNSPrefix(prefix, nsuri)
  1090. def ParseTypeRef(value, element):
  1091. parts = value.split(':', 1)
  1092. if len(parts) == 1:
  1093. return (DOM.findTargetNS(element), value)
  1094. nsuri = DOM.findNamespaceURI(parts[0], element)
  1095. return (nsuri, parts[1])
  1096. def ParseQName(value, element):
  1097. nameref = value.split(':', 1)
  1098. if len(nameref) == 2:
  1099. nsuri = DOM.findNamespaceURI(nameref[0], element)
  1100. name = nameref[-1]
  1101. else:
  1102. nsuri = DOM.findTargetNS(element)
  1103. name = nameref[-1]
  1104. return nsuri, name
  1105. def GetDocumentation(element):
  1106. docnode = DOM.getElement(element, 'documentation', None, None)
  1107. if docnode is not None:
  1108. return DOM.getElementText(docnode)
  1109. return ''
  1110. def GetExtensions(element):
  1111. return [ item for item in DOM.getElements(element, None, None)
  1112. if item.namespaceURI != DOM.NS_WSDL ]
  1113. def GetWSAActionFault(operation, name):
  1114. """Find wsa:Action attribute, and return value or WSA.FAULT
  1115. for the default.
  1116. """
  1117. attr = operation.faults[name].action
  1118. if attr is not None:
  1119. return attr
  1120. return WSA.FAULT
  1121. def GetWSAActionInput(operation):
  1122. """Find wsa:Action attribute, and return value or the default."""
  1123. attr = operation.input.action
  1124. if attr is not None:
  1125. return attr
  1126. portType = operation.getPortType()
  1127. targetNamespace = portType.getTargetNamespace()
  1128. ptName = portType.name
  1129. msgName = operation.input.name
  1130. if not msgName:
  1131. msgName = operation.name + 'Request'
  1132. if targetNamespace.endswith('/'):
  1133. return '%s%s/%s' %(targetNamespace, ptName, msgName)
  1134. return '%s/%s/%s' %(targetNamespace, ptName, msgName)
  1135. def GetWSAActionOutput(operation):
  1136. """Find wsa:Action attribute, and return value or the default."""
  1137. attr = operation.output.action
  1138. if attr is not None:
  1139. return attr
  1140. targetNamespace = operation.getPortType().getTargetNamespace()
  1141. ptName = operation.getPortType().name
  1142. msgName = operation.output.name
  1143. if not msgName:
  1144. msgName = operation.name + 'Response'
  1145. if targetNamespace.endswith('/'):
  1146. return '%s%s/%s' %(targetNamespace, ptName, msgName)
  1147. return '%s/%s/%s' %(targetNamespace, ptName, msgName)
  1148. def FindExtensions(object, kind, t_type=type(())):
  1149. if isinstance(kind, t_type):
  1150. result = []
  1151. namespaceURI, name = kind
  1152. return [ item for item in object.extensions
  1153. if hasattr(item, 'nodeType') \
  1154. and DOM.nsUriMatch(namespaceURI, item.namespaceURI) \
  1155. and item.name == name ]
  1156. return [ item for item in object.extensions if isinstance(item, kind) ]
  1157. def FindExtension(object, kind, t_type=type(())):
  1158. if isinstance(kind, t_type):
  1159. namespaceURI, name = kind
  1160. for item in object.extensions:
  1161. if hasattr(item, 'nodeType') \
  1162. and DOM.nsUriMatch(namespaceURI, item.namespaceURI) \
  1163. and item.name == name:
  1164. return item
  1165. else:
  1166. for item in object.extensions:
  1167. if isinstance(item, kind):
  1168. return item
  1169. return None
  1170. class SOAPCallInfo:
  1171. """SOAPCallInfo captures the important binding information about a
  1172. SOAP operation, in a structure that is easier to work with than
  1173. raw WSDL structures."""
  1174. def __init__(self, methodName):
  1175. self.methodName = methodName
  1176. self.inheaders = []
  1177. self.outheaders = []
  1178. self.inparams = []
  1179. self.outparams = []
  1180. self.retval = None
  1181. encodingStyle = DOM.NS_SOAP_ENC
  1182. documentation = ''
  1183. soapAction = None
  1184. transport = None
  1185. namespace = None
  1186. location = None
  1187. use = 'encoded'
  1188. style = 'rpc'
  1189. def addInParameter(self, name, type, namespace=None, element_type=0):
  1190. """Add an input parameter description to the call info."""
  1191. parameter = ParameterInfo(name, type, namespace, element_type)
  1192. self.inparams.append(parameter)
  1193. return parameter
  1194. def addOutParameter(self, name, type, namespace=None, element_type=0):
  1195. """Add an output parameter description to the call info."""
  1196. parameter = ParameterInfo(name, type, namespace, element_type)
  1197. self.outparams.append(parameter)
  1198. return parameter
  1199. def setReturnParameter(self, name, type, namespace=None, element_type=0):
  1200. """Set the return parameter description for the call info."""
  1201. parameter = ParameterInfo(name, type, namespace, element_type)
  1202. self.retval = parameter
  1203. return parameter
  1204. def addInHeaderInfo(self, name, type, namespace, element_type=0,
  1205. mustUnderstand=0):
  1206. """Add an input SOAP header description to the call info."""
  1207. headerinfo = HeaderInfo(name, type, namespace, element_type)
  1208. if mustUnderstand:
  1209. headerinfo.mustUnderstand = 1
  1210. self.inheaders.append(headerinfo)
  1211. return headerinfo
  1212. def addOutHeaderInfo(self, name, type, namespace, element_type=0,
  1213. mustUnderstand=0):
  1214. """Add an output SOAP header description to the call info."""
  1215. headerinfo = HeaderInfo(name, type, namespace, element_type)
  1216. if mustUnderstand:
  1217. headerinfo.mustUnderstand = 1
  1218. self.outheaders.append(headerinfo)
  1219. return headerinfo
  1220. def getInParameters(self):
  1221. """Return a sequence of the in parameters of the method."""
  1222. return self.inparams
  1223. def getOutParameters(self):
  1224. """Return a sequence of the out parameters of the method."""
  1225. return self.outparams
  1226. def getReturnParameter(self):
  1227. """Return param info about the return value of the method."""
  1228. return self.retval
  1229. def getInHeaders(self):
  1230. """Return a sequence of the in headers of the method."""
  1231. return self.inheaders
  1232. def getOutHeaders(self):
  1233. """Return a sequence of the out headers of the method."""
  1234. return self.outheaders
  1235. class ParameterInfo:
  1236. """A ParameterInfo object captures parameter binding information."""
  1237. def __init__(self, name, type, namespace=None, element_type=0):
  1238. if element_type:
  1239. self.element_type = 1
  1240. if namespace is not None:
  1241. self.namespace = namespace
  1242. self.name = name
  1243. self.type = type
  1244. element_type = 0
  1245. namespace = None
  1246. default = None
  1247. class HeaderInfo(ParameterInfo):
  1248. """A HeaderInfo object captures SOAP header binding information."""
  1249. def __init__(self, name, type, namespace, element_type=None):
  1250. ParameterInfo.__init__(self, name, type, namespace, element_type)
  1251. mustUnderstand = 0
  1252. actor = None
  1253. def callInfoFromWSDL(port, name):
  1254. """Return a SOAPCallInfo given a WSDL port and operation name."""
  1255. wsdl = port.getService().getWSDL()
  1256. binding = port.getBinding()
  1257. portType = binding.getPortType()
  1258. operation = portType.operations[name]
  1259. opbinding = binding.operations[name]
  1260. messages = wsdl.messages
  1261. callinfo = SOAPCallInfo(name)
  1262. addrbinding = port.getAddressBinding()
  1263. if not isinstance(addrbinding, SoapAddressBinding):
  1264. raise ValueError, 'Unsupported binding type.'
  1265. callinfo.location = addrbinding.location
  1266. soapbinding = binding.findBinding(SoapBinding)
  1267. if soapbinding is None:
  1268. raise ValueError, 'Missing soap:binding element.'
  1269. callinfo.transport = soapbinding.transport
  1270. callinfo.style = soapbinding.style or 'document'
  1271. soap_op_binding = opbinding.findBinding(SoapOperationBinding)
  1272. if soap_op_binding is not None:
  1273. callinfo.soapAction = soap_op_binding.soapAction
  1274. callinfo.style = soap_op_binding.style or callinfo.style
  1275. parameterOrder = operation.parameterOrder
  1276. if operation.input is not None:
  1277. message = messages[operation.input.message]
  1278. msgrole = opbinding.input
  1279. mime = msgrole.findBinding(MimeMultipartRelatedBinding)
  1280. if mime is not None:
  1281. raise ValueError, 'Mime bindings are not supported.'
  1282. else:
  1283. for item in msgrole.findBindings(SoapHeaderBinding):
  1284. part = messages[item.message].parts[item.part]
  1285. header = callinfo.addInHeaderInfo(
  1286. part.name,
  1287. part.element or part.type,
  1288. item.namespace,
  1289. element_type = part.element and 1 or 0
  1290. )
  1291. header.encodingStyle = item.encodingStyle
  1292. body = msgrole.findBinding(SoapBodyBinding)
  1293. if body is None:
  1294. raise ValueError, 'Missing soap:body binding.'
  1295. callinfo.encodingStyle = body.encodingStyle
  1296. callinfo.namespace = body.namespace
  1297. callinfo.use = body.use
  1298. if body.parts is not None:
  1299. parts = []
  1300. for name in body.parts:
  1301. parts.append(message.parts[name])
  1302. else:
  1303. parts = message.parts.values()
  1304. for part in parts:
  1305. callinfo.addInParameter(
  1306. part.name,
  1307. part.element or part.type,
  1308. element_type = part.element and 1 or 0
  1309. )
  1310. if operation.output is not None:
  1311. try:
  1312. message = messages[operation.output.message]
  1313. except KeyError:
  1314. if self.strict:
  1315. raise RuntimeError(
  1316. "Recieved message not defined in the WSDL schema: %s" %
  1317. operation.output.message)
  1318. else:
  1319. message = wsdl.addMessage(operation.output.message)
  1320. print "Warning:", \
  1321. "Recieved message not defined in the WSDL schema.", \
  1322. "Adding it."
  1323. print "Message:", operation.output.message
  1324. msgrole = opbinding.output
  1325. mime = msgrole.findBinding(MimeMultipartRelatedBinding)
  1326. if mime is not None:
  1327. raise ValueError, 'Mime bindings are not supported.'
  1328. else:
  1329. for item in msgrole.findBindings(SoapHeaderBinding):
  1330. part = messages[item.message].parts[item.part]
  1331. header = callinfo.addOutHeaderInfo(
  1332. part.name,
  1333. part.element or part.type,
  1334. item.namespace,
  1335. element_type = part.element and 1 or 0
  1336. )
  1337. header.encodingStyle = item.encodingStyle
  1338. body = msgrole.findBinding(SoapBodyBinding)
  1339. if body is None:
  1340. raise ValueError, 'Missing soap:body binding.'
  1341. callinfo.encodingStyle = body.encodingStyle
  1342. callinfo.namespace = body.namespace
  1343. callinfo.use = body.use
  1344. if body.parts is not None:
  1345. parts = []
  1346. for name in body.parts:
  1347. parts.append(message.parts[name])
  1348. else:
  1349. parts = message.parts.values()
  1350. if parts:
  1351. for part in parts:
  1352. callinfo.addOutParameter(
  1353. part.name,
  1354. part.element or part.type,
  1355. element_type = part.element and 1 or 0
  1356. )
  1357. return callinfo