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