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.
 
 
 

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