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.
 
 
 

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