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.
 
 
 

1675 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 getWSDL(self):
  800. # """Return the WSDL object that contains this MessageRole."""
  801. # if self.type == 'fault':
  802. # return self.parent().parent().getWSDL()
  803. # return self.parent().getWSDL()
  804. def findBinding(self, kind):
  805. for item in self.extensions:
  806. if isinstance(item, kind):
  807. return item
  808. return None
  809. def findBindings(self, kind):
  810. return [ item for item in self.extensions if isinstance(item, kind) ]
  811. def load_ex(self, elements):
  812. for e in elements:
  813. ns, name = e.namespaceURI, e.localName
  814. if ns in DOM.NS_SOAP_BINDING_ALL and name == 'body':
  815. encstyle = DOM.getAttr(e, 'encodingStyle', default=None)
  816. namespace = DOM.getAttr(e, 'namespace', default=None)
  817. parts = DOM.getAttr(e, 'parts', default=None)
  818. use = DOM.getAttr(e, 'use', default=None)
  819. if use is None:
  820. raise WSDLError(
  821. 'Invalid soap:body binding element.'
  822. )
  823. ob = SoapBodyBinding(use, namespace, encstyle, parts)
  824. self.addExtension(ob)
  825. continue
  826. elif ns in DOM.NS_SOAP_BINDING_ALL and name == 'fault':
  827. encstyle = DOM.getAttr(e, 'encodingStyle', default=None)
  828. namespace = DOM.getAttr(e, 'namespace', default=None)
  829. name = DOM.getAttr(e, 'name', default=None)
  830. use = DOM.getAttr(e, 'use', default=None)
  831. if use is None or name is None:
  832. raise WSDLError(
  833. 'Invalid soap:fault binding element.'
  834. )
  835. ob = SoapFaultBinding(name, use, namespace, encstyle)
  836. self.addExtension(ob)
  837. continue
  838. elif ns in DOM.NS_SOAP_BINDING_ALL and name in (
  839. 'header', 'headerfault'
  840. ):
  841. encstyle = DOM.getAttr(e, 'encodingStyle', default=None)
  842. namespace = DOM.getAttr(e, 'namespace', default=None)
  843. message = DOM.getAttr(e, 'message')
  844. part = DOM.getAttr(e, 'part')
  845. use = DOM.getAttr(e, 'use')
  846. if name == 'header':
  847. _class = SoapHeaderBinding
  848. else:
  849. _class = SoapHeaderFaultBinding
  850. message = ParseQName(message, e)
  851. ob = _class(message, part, use, namespace, encstyle)
  852. self.addExtension(ob)
  853. continue
  854. elif ns in DOM.NS_HTTP_BINDING_ALL and name == 'urlReplacement':
  855. ob = HttpUrlReplacementBinding()
  856. self.addExtension(ob)
  857. continue
  858. elif ns in DOM.NS_HTTP_BINDING_ALL and name == 'urlEncoded':
  859. ob = HttpUrlEncodedBinding()
  860. self.addExtension(ob)
  861. continue
  862. elif ns in DOM.NS_MIME_BINDING_ALL and name == 'multipartRelated':
  863. ob = MimeMultipartRelatedBinding()
  864. self.addExtension(ob)
  865. ob.load_ex(GetExtensions(e))
  866. continue
  867. elif ns in DOM.NS_MIME_BINDING_ALL and name == 'content':
  868. part = DOM.getAttr(e, 'part', default=None)
  869. type = DOM.getAttr(e, 'type', default=None)
  870. ob = MimeContentBinding(part, type)
  871. self.addExtension(ob)
  872. continue
  873. elif ns in DOM.NS_MIME_BINDING_ALL and name == 'mimeXml':
  874. part = DOM.getAttr(e, 'part', default=None)
  875. ob = MimeXmlBinding(part)
  876. self.addExtension(ob)
  877. continue
  878. else:
  879. self.addExtension(e)
  880. def toDom(self, node):
  881. wsdl = self.getWSDL()
  882. ep = ElementProxy(None, node)
  883. epc = ep.createAppendElement(DOM.GetWSDLUri(wsdl.version), self.type)
  884. node = epc._getNode()
  885. for item in self.extensions:
  886. if item: item.toDom(node)
  887. class Service(Element):
  888. def __init__(self, name, documentation=''):
  889. Element.__init__(self, name, documentation)
  890. self.ports = Collection(self)
  891. def getWSDL(self):
  892. return self.parent().parent()
  893. def addPort(self, name, binding, documentation=''):
  894. item = Port(name, binding, documentation)
  895. self.ports[name] = item
  896. return item
  897. def load(self, elements):
  898. for element in elements:
  899. name = DOM.getAttr(element, 'name', default=None)
  900. docs = GetDocumentation(element)
  901. binding = DOM.getAttr(element, 'binding', default=None)
  902. if name is None or binding is None:
  903. raise WSDLError(
  904. 'Invalid port element.'
  905. )
  906. binding = ParseQName(binding, element)
  907. port = self.addPort(name, binding, docs)
  908. port.load_ex(GetExtensions(element))
  909. def load_ex(self, elements):
  910. for e in elements:
  911. self.addExtension(e)
  912. def toDom(self):
  913. wsdl = self.getWSDL()
  914. ep = ElementProxy(None, DOM.getElement(wsdl.document, None))
  915. epc = ep.createAppendElement(DOM.GetWSDLUri(wsdl.version), "service")
  916. epc.setAttributeNS(None, "name", self.name)
  917. node = epc._getNode()
  918. for port in self.ports:
  919. port.toDom(node)
  920. class Port(Element):
  921. def __init__(self, name, binding, documentation=''):
  922. Element.__init__(self, name, documentation)
  923. self.binding = binding
  924. # def getWSDL(self):
  925. # return self.parent().parent().getWSDL()
  926. def getService(self):
  927. """Return the Service object associated with this port."""
  928. return self.parent().parent()
  929. def getBinding(self):
  930. """Return the Binding object that is referenced by this port."""
  931. wsdl = self.getService().getWSDL()
  932. return wsdl.bindings[self.binding]
  933. def getPortType(self):
  934. """Return the PortType object that is referenced by this port."""
  935. wsdl = self.getService().getWSDL()
  936. binding = wsdl.bindings[self.binding]
  937. return wsdl.portTypes[binding.type]
  938. def getAddressBinding(self):
  939. """A convenience method to obtain the extension element used
  940. as the address binding for the port."""
  941. for item in self.extensions:
  942. if isinstance(item, SoapAddressBinding) or \
  943. isinstance(item, HttpAddressBinding):
  944. return item
  945. raise WSDLError(
  946. 'No address binding found in port.'
  947. )
  948. def load_ex(self, elements):
  949. for e in elements:
  950. ns, name = e.namespaceURI, e.localName
  951. if ns in DOM.NS_SOAP_BINDING_ALL and name == 'address':
  952. location = DOM.getAttr(e, 'location', default=None)
  953. ob = SoapAddressBinding(location)
  954. self.addExtension(ob)
  955. continue
  956. elif ns in DOM.NS_HTTP_BINDING_ALL and name == 'address':
  957. location = DOM.getAttr(e, 'location', default=None)
  958. ob = HttpAddressBinding(location)
  959. self.addExtension(ob)
  960. continue
  961. else:
  962. self.addExtension(e)
  963. def toDom(self, node):
  964. wsdl = self.getWSDL()
  965. ep = ElementProxy(None, node)
  966. epc = ep.createAppendElement(DOM.GetWSDLUri(wsdl.version), "port")
  967. epc.setAttributeNS(None, "name", self.name)
  968. ns,name = self.binding
  969. prefix = epc.getPrefix(ns)
  970. epc.setAttributeNS(None, "binding", "%s:%s" %(prefix,name))
  971. node = epc._getNode()
  972. for ext in self.extensions:
  973. ext.toDom(node)
  974. class SoapBinding:
  975. def __init__(self, transport, style='rpc'):
  976. self.transport = transport
  977. self.style = style
  978. def getWSDL(self):
  979. return self.parent().getWSDL()
  980. def toDom(self, node):
  981. wsdl = self.getWSDL()
  982. ep = ElementProxy(None, node)
  983. epc = ep.createAppendElement(DOM.GetWSDLSoapBindingUri(wsdl.version), 'binding')
  984. if self.transport:
  985. epc.setAttributeNS(None, "transport", self.transport)
  986. if self.style:
  987. epc.setAttributeNS(None, "style", self.style)
  988. class SoapAddressBinding:
  989. def __init__(self, location):
  990. self.location = location
  991. def getWSDL(self):
  992. return self.parent().getWSDL()
  993. def toDom(self, node):
  994. wsdl = self.getWSDL()
  995. ep = ElementProxy(None, node)
  996. epc = ep.createAppendElement(DOM.GetWSDLSoapBindingUri(wsdl.version), 'address')
  997. epc.setAttributeNS(None, "location", self.location)
  998. class SoapOperationBinding:
  999. def __init__(self, soapAction=None, style=None):
  1000. self.soapAction = soapAction
  1001. self.style = style
  1002. def getWSDL(self):
  1003. return self.parent().getWSDL()
  1004. def toDom(self, node):
  1005. wsdl = self.getWSDL()
  1006. ep = ElementProxy(None, node)
  1007. epc = ep.createAppendElement(DOM.GetWSDLSoapBindingUri(wsdl.version), 'operation')
  1008. if self.soapAction:
  1009. epc.setAttributeNS(None, 'soapAction', self.soapAction)
  1010. if self.style:
  1011. epc.setAttributeNS(None, 'style', self.style)
  1012. class SoapBodyBinding:
  1013. def __init__(self, use, namespace=None, encodingStyle=None, parts=None):
  1014. if not use in ('literal', 'encoded'):
  1015. raise WSDLError(
  1016. 'Invalid use attribute value: %s' % use
  1017. )
  1018. self.encodingStyle = encodingStyle
  1019. self.namespace = namespace
  1020. if type(parts) in (type(''), type(u'')):
  1021. parts = parts.split()
  1022. self.parts = parts
  1023. self.use = use
  1024. def getWSDL(self):
  1025. return self.parent().getWSDL()
  1026. def toDom(self, node):
  1027. wsdl = self.getWSDL()
  1028. ep = ElementProxy(None, node)
  1029. epc = ep.createAppendElement(DOM.GetWSDLSoapBindingUri(wsdl.version), 'body')
  1030. epc.setAttributeNS(None, "use", self.use)
  1031. epc.setAttributeNS(None, "namespace", self.namespace)
  1032. class SoapFaultBinding:
  1033. def __init__(self, name, use, namespace=None, encodingStyle=None):
  1034. if not use in ('literal', 'encoded'):
  1035. raise WSDLError(
  1036. 'Invalid use attribute value: %s' % use
  1037. )
  1038. self.encodingStyle = encodingStyle
  1039. self.namespace = namespace
  1040. self.name = name
  1041. self.use = use
  1042. def getWSDL(self):
  1043. return self.parent().getWSDL()
  1044. def toDom(self, node):
  1045. wsdl = self.getWSDL()
  1046. ep = ElementProxy(None, node)
  1047. epc = ep.createAppendElement(DOM.GetWSDLSoapBindingUri(wsdl.version), 'body')
  1048. epc.setAttributeNS(None, "use", self.use)
  1049. epc.setAttributeNS(None, "name", self.name)
  1050. if self.namespace is not None:
  1051. epc.setAttributeNS(None, "namespace", self.namespace)
  1052. if self.encodingStyle is not None:
  1053. epc.setAttributeNS(None, "encodingStyle", self.encodingStyle)
  1054. class SoapHeaderBinding:
  1055. def __init__(self, message, part, use, namespace=None, encodingStyle=None):
  1056. if not use in ('literal', 'encoded'):
  1057. raise WSDLError(
  1058. 'Invalid use attribute value: %s' % use
  1059. )
  1060. self.encodingStyle = encodingStyle
  1061. self.namespace = namespace
  1062. self.message = message
  1063. self.part = part
  1064. self.use = use
  1065. tagname = 'header'
  1066. class SoapHeaderFaultBinding(SoapHeaderBinding):
  1067. tagname = 'headerfault'
  1068. class HttpBinding:
  1069. def __init__(self, verb):
  1070. self.verb = verb
  1071. class HttpAddressBinding:
  1072. def __init__(self, location):
  1073. self.location = location
  1074. class HttpOperationBinding:
  1075. def __init__(self, location):
  1076. self.location = location
  1077. class HttpUrlReplacementBinding:
  1078. pass
  1079. class HttpUrlEncodedBinding:
  1080. pass
  1081. class MimeContentBinding:
  1082. def __init__(self, part=None, type=None):
  1083. self.part = part
  1084. self.type = type
  1085. class MimeXmlBinding:
  1086. def __init__(self, part=None):
  1087. self.part = part
  1088. class MimeMultipartRelatedBinding:
  1089. def __init__(self):
  1090. self.parts = []
  1091. def load_ex(self, elements):
  1092. for e in elements:
  1093. ns, name = e.namespaceURI, e.localName
  1094. if ns in DOM.NS_MIME_BINDING_ALL and name == 'part':
  1095. self.parts.append(MimePartBinding())
  1096. continue
  1097. class MimePartBinding:
  1098. def __init__(self):
  1099. self.items = []
  1100. def load_ex(self, elements):
  1101. for e in elements:
  1102. ns, name = e.namespaceURI, e.localName
  1103. if ns in DOM.NS_MIME_BINDING_ALL and name == 'content':
  1104. part = DOM.getAttr(e, 'part', default=None)
  1105. type = DOM.getAttr(e, 'type', default=None)
  1106. ob = MimeContentBinding(part, type)
  1107. self.items.append(ob)
  1108. continue
  1109. elif ns in DOM.NS_MIME_BINDING_ALL and name == 'mimeXml':
  1110. part = DOM.getAttr(e, 'part', default=None)
  1111. ob = MimeXmlBinding(part)
  1112. self.items.append(ob)
  1113. continue
  1114. elif ns in DOM.NS_SOAP_BINDING_ALL and name == 'body':
  1115. encstyle = DOM.getAttr(e, 'encodingStyle', default=None)
  1116. namespace = DOM.getAttr(e, 'namespace', default=None)
  1117. parts = DOM.getAttr(e, 'parts', default=None)
  1118. use = DOM.getAttr(e, 'use', default=None)
  1119. if use is None:
  1120. raise WSDLError(
  1121. 'Invalid soap:body binding element.'
  1122. )
  1123. ob = SoapBodyBinding(use, namespace, encstyle, parts)
  1124. self.items.append(ob)
  1125. continue
  1126. class WSDLError(Exception):
  1127. pass
  1128. def DeclareNSPrefix(writer, prefix, nsuri):
  1129. if writer.hasNSPrefix(nsuri):
  1130. return
  1131. writer.declareNSPrefix(prefix, nsuri)
  1132. def ParseTypeRef(value, element):
  1133. parts = value.split(':', 1)
  1134. if len(parts) == 1:
  1135. return (DOM.findTargetNS(element), value)
  1136. nsuri = DOM.findNamespaceURI(parts[0], element)
  1137. return (nsuri, parts[1])
  1138. def ParseQName(value, element):
  1139. nameref = value.split(':', 1)
  1140. if len(nameref) == 2:
  1141. nsuri = DOM.findNamespaceURI(nameref[0], element)
  1142. name = nameref[-1]
  1143. else:
  1144. nsuri = DOM.findTargetNS(element)
  1145. name = nameref[-1]
  1146. return nsuri, name
  1147. def GetDocumentation(element):
  1148. docnode = DOM.getElement(element, 'documentation', None, None)
  1149. if docnode is not None:
  1150. return DOM.getElementText(docnode)
  1151. return ''
  1152. def GetExtensions(element):
  1153. return [ item for item in DOM.getElements(element, None, None)
  1154. if item.namespaceURI != DOM.NS_WSDL ]
  1155. def GetWSAActionFault(operation, name):
  1156. """Find wsa:Action attribute, and return value or WSA.FAULT
  1157. for the default.
  1158. """
  1159. attr = operation.faults[name].action
  1160. if attr is not None:
  1161. return attr
  1162. return WSA.FAULT
  1163. def GetWSAActionInput(operation):
  1164. """Find wsa:Action attribute, and return value or the default."""
  1165. attr = operation.input.action
  1166. if attr is not None:
  1167. return attr
  1168. portType = operation.getPortType()
  1169. targetNamespace = portType.getTargetNamespace()
  1170. ptName = portType.name
  1171. msgName = operation.input.name
  1172. if not msgName:
  1173. msgName = operation.name + 'Request'
  1174. if targetNamespace.endswith('/'):
  1175. return '%s%s/%s' %(targetNamespace, ptName, msgName)
  1176. return '%s/%s/%s' %(targetNamespace, ptName, msgName)
  1177. def GetWSAActionOutput(operation):
  1178. """Find wsa:Action attribute, and return value or the default."""
  1179. attr = operation.output.action
  1180. if attr is not None:
  1181. return attr
  1182. targetNamespace = operation.getPortType().getTargetNamespace()
  1183. ptName = operation.getPortType().name
  1184. msgName = operation.output.name
  1185. if not msgName:
  1186. msgName = operation.name + 'Response'
  1187. if targetNamespace.endswith('/'):
  1188. return '%s%s/%s' %(targetNamespace, ptName, msgName)
  1189. return '%s/%s/%s' %(targetNamespace, ptName, msgName)
  1190. def FindExtensions(object, kind, t_type=type(())):
  1191. if isinstance(kind, t_type):
  1192. result = []
  1193. namespaceURI, name = kind
  1194. return [ item for item in object.extensions
  1195. if hasattr(item, 'nodeType') \
  1196. and DOM.nsUriMatch(namespaceURI, item.namespaceURI) \
  1197. and item.name == name ]
  1198. return [ item for item in object.extensions if isinstance(item, kind) ]
  1199. def FindExtension(object, kind, t_type=type(())):
  1200. if isinstance(kind, t_type):
  1201. namespaceURI, name = kind
  1202. for item in object.extensions:
  1203. if hasattr(item, 'nodeType') \
  1204. and DOM.nsUriMatch(namespaceURI, item.namespaceURI) \
  1205. and item.name == name:
  1206. return item
  1207. else:
  1208. for item in object.extensions:
  1209. if isinstance(item, kind):
  1210. return item
  1211. return None
  1212. class SOAPCallInfo:
  1213. """SOAPCallInfo captures the important binding information about a
  1214. SOAP operation, in a structure that is easier to work with than
  1215. raw WSDL structures."""
  1216. def __init__(self, methodName):
  1217. self.methodName = methodName
  1218. self.inheaders = []
  1219. self.outheaders = []
  1220. self.inparams = []
  1221. self.outparams = []
  1222. self.retval = None
  1223. encodingStyle = DOM.NS_SOAP_ENC
  1224. documentation = ''
  1225. soapAction = None
  1226. transport = None
  1227. namespace = None
  1228. location = None
  1229. use = 'encoded'
  1230. style = 'rpc'
  1231. def addInParameter(self, name, type, namespace=None, element_type=0):
  1232. """Add an input parameter description to the call info."""
  1233. parameter = ParameterInfo(name, type, namespace, element_type)
  1234. self.inparams.append(parameter)
  1235. return parameter
  1236. def addOutParameter(self, name, type, namespace=None, element_type=0):
  1237. """Add an output parameter description to the call info."""
  1238. parameter = ParameterInfo(name, type, namespace, element_type)
  1239. self.outparams.append(parameter)
  1240. return parameter
  1241. def setReturnParameter(self, name, type, namespace=None, element_type=0):
  1242. """Set the return parameter description for the call info."""
  1243. parameter = ParameterInfo(name, type, namespace, element_type)
  1244. self.retval = parameter
  1245. return parameter
  1246. def addInHeaderInfo(self, name, type, namespace, element_type=0,
  1247. mustUnderstand=0):
  1248. """Add an input SOAP header description to the call info."""
  1249. headerinfo = HeaderInfo(name, type, namespace, element_type)
  1250. if mustUnderstand:
  1251. headerinfo.mustUnderstand = 1
  1252. self.inheaders.append(headerinfo)
  1253. return headerinfo
  1254. def addOutHeaderInfo(self, name, type, namespace, element_type=0,
  1255. mustUnderstand=0):
  1256. """Add an output SOAP header description to the call info."""
  1257. headerinfo = HeaderInfo(name, type, namespace, element_type)
  1258. if mustUnderstand:
  1259. headerinfo.mustUnderstand = 1
  1260. self.outheaders.append(headerinfo)
  1261. return headerinfo
  1262. def getInParameters(self):
  1263. """Return a sequence of the in parameters of the method."""
  1264. return self.inparams
  1265. def getOutParameters(self):
  1266. """Return a sequence of the out parameters of the method."""
  1267. return self.outparams
  1268. def getReturnParameter(self):
  1269. """Return param info about the return value of the method."""
  1270. return self.retval
  1271. def getInHeaders(self):
  1272. """Return a sequence of the in headers of the method."""
  1273. return self.inheaders
  1274. def getOutHeaders(self):
  1275. """Return a sequence of the out headers of the method."""
  1276. return self.outheaders
  1277. class ParameterInfo:
  1278. """A ParameterInfo object captures parameter binding information."""
  1279. def __init__(self, name, type, namespace=None, element_type=0):
  1280. if element_type:
  1281. self.element_type = 1
  1282. if namespace is not None:
  1283. self.namespace = namespace
  1284. self.name = name
  1285. self.type = type
  1286. element_type = 0
  1287. namespace = None
  1288. default = None
  1289. class HeaderInfo(ParameterInfo):
  1290. """A HeaderInfo object captures SOAP header binding information."""
  1291. def __init__(self, name, type, namespace, element_type=None):
  1292. ParameterInfo.__init__(self, name, type, namespace, element_type)
  1293. mustUnderstand = 0
  1294. actor = None
  1295. def callInfoFromWSDL(port, name):
  1296. """Return a SOAPCallInfo given a WSDL port and operation name."""
  1297. wsdl = port.getService().getWSDL()
  1298. binding = port.getBinding()
  1299. portType = binding.getPortType()
  1300. operation = portType.operations[name]
  1301. opbinding = binding.operations[name]
  1302. messages = wsdl.messages
  1303. callinfo = SOAPCallInfo(name)
  1304. addrbinding = port.getAddressBinding()
  1305. if not isinstance(addrbinding, SoapAddressBinding):
  1306. raise ValueError, 'Unsupported binding type.'
  1307. callinfo.location = addrbinding.location
  1308. soapbinding = binding.findBinding(SoapBinding)
  1309. if soapbinding is None:
  1310. raise ValueError, 'Missing soap:binding element.'
  1311. callinfo.transport = soapbinding.transport
  1312. callinfo.style = soapbinding.style or 'document'
  1313. soap_op_binding = opbinding.findBinding(SoapOperationBinding)
  1314. if soap_op_binding is not None:
  1315. callinfo.soapAction = soap_op_binding.soapAction
  1316. callinfo.style = soap_op_binding.style or callinfo.style
  1317. parameterOrder = operation.parameterOrder
  1318. if operation.input is not None:
  1319. message = messages[operation.input.message]
  1320. msgrole = opbinding.input
  1321. mime = msgrole.findBinding(MimeMultipartRelatedBinding)
  1322. if mime is not None:
  1323. raise ValueError, 'Mime bindings are not supported.'
  1324. else:
  1325. for item in msgrole.findBindings(SoapHeaderBinding):
  1326. part = messages[item.message].parts[item.part]
  1327. header = callinfo.addInHeaderInfo(
  1328. part.name,
  1329. part.element or part.type,
  1330. item.namespace,
  1331. element_type = part.element and 1 or 0
  1332. )
  1333. header.encodingStyle = item.encodingStyle
  1334. body = msgrole.findBinding(SoapBodyBinding)
  1335. if body is None:
  1336. raise ValueError, 'Missing soap:body binding.'
  1337. callinfo.encodingStyle = body.encodingStyle
  1338. callinfo.namespace = body.namespace
  1339. callinfo.use = body.use
  1340. if body.parts is not None:
  1341. parts = []
  1342. for name in body.parts:
  1343. parts.append(message.parts[name])
  1344. else:
  1345. parts = message.parts.values()
  1346. for part in parts:
  1347. callinfo.addInParameter(
  1348. part.name,
  1349. part.element or part.type,
  1350. element_type = part.element and 1 or 0
  1351. )
  1352. if operation.output is not None:
  1353. try:
  1354. message = messages[operation.output.message]
  1355. except KeyError:
  1356. if self.strict:
  1357. raise RuntimeError(
  1358. "Recieved message not defined in the WSDL schema: %s" %
  1359. operation.output.message)
  1360. else:
  1361. message = wsdl.addMessage(operation.output.message)
  1362. print "Warning:", \
  1363. "Recieved message not defined in the WSDL schema.", \
  1364. "Adding it."
  1365. print "Message:", operation.output.message
  1366. msgrole = opbinding.output
  1367. mime = msgrole.findBinding(MimeMultipartRelatedBinding)
  1368. if mime is not None:
  1369. raise ValueError, 'Mime bindings are not supported.'
  1370. else:
  1371. for item in msgrole.findBindings(SoapHeaderBinding):
  1372. part = messages[item.message].parts[item.part]
  1373. header = callinfo.addOutHeaderInfo(
  1374. part.name,
  1375. part.element or part.type,
  1376. item.namespace,
  1377. element_type = part.element and 1 or 0
  1378. )
  1379. header.encodingStyle = item.encodingStyle
  1380. body = msgrole.findBinding(SoapBodyBinding)
  1381. if body is None:
  1382. raise ValueError, 'Missing soap:body binding.'
  1383. callinfo.encodingStyle = body.encodingStyle
  1384. callinfo.namespace = body.namespace
  1385. callinfo.use = body.use
  1386. if body.parts is not None:
  1387. parts = []
  1388. for name in body.parts:
  1389. parts.append(message.parts[name])
  1390. else:
  1391. parts = message.parts.values()
  1392. if parts:
  1393. for part in parts:
  1394. callinfo.addOutParameter(
  1395. part.name,
  1396. part.element or part.type,
  1397. element_type = part.element and 1 or 0
  1398. )
  1399. return callinfo