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.
 
 
 

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