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.
 
 
 

1694 lines
59 KiB

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