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.
 
 
 

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