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.
 
 
 

1177 lines
41 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. from Utility import DOM, Collection
  11. from XMLSchema import XMLSchema, SchemaReader, WSDLToolsAdapter
  12. from StringIO import StringIO
  13. import urllib
  14. class WSDLReader:
  15. """A WSDLReader creates WSDL instances from urls and xml data."""
  16. # Custom subclasses of WSDLReader may wish to implement a caching
  17. # strategy or other optimizations. Because application needs vary
  18. # so widely, we don't try to provide any caching by default.
  19. def loadFromStream(self, file):
  20. """Return a WSDL instance loaded from a file object."""
  21. document = DOM.loadDocument(file)
  22. wsdl = WSDL()
  23. wsdl.location = file.name
  24. wsdl.load(document)
  25. return wsdl
  26. def loadFromURL(self, url):
  27. """Return a WSDL instance loaded from the given url."""
  28. document = DOM.loadFromURL(url)
  29. wsdl = WSDL()
  30. wsdl.location = url
  31. wsdl.load(document)
  32. return wsdl
  33. def loadFromString(self, data):
  34. """Return a WSDL instance loaded from an xml string."""
  35. return self.loadFromStream(StringIO(data))
  36. def loadFromFile(self, filename):
  37. """Return a WSDL instance loaded from the given file."""
  38. file = open(filename, 'rb')
  39. try:
  40. wsdl = self.loadFromStream(file)
  41. finally:
  42. file.close()
  43. return wsdl
  44. class WSDL:
  45. """A WSDL object models a WSDL service description. WSDL objects
  46. may be created manually or loaded from an xml representation
  47. using a WSDLReader instance."""
  48. def __init__(self, targetNamespace=None):
  49. self.targetNamespace = targetNamespace or 'urn:this-document.wsdl'
  50. self.documentation = ''
  51. self.location = None
  52. self.document = None
  53. self.name = None
  54. self.services = Collection(self)
  55. self.messages = Collection(self)
  56. self.portTypes = Collection(self)
  57. self.bindings = Collection(self)
  58. self.imports = Collection(self)
  59. self.types = Types(self)
  60. self.extensions = []
  61. def __del__(self):
  62. if self.document is not None:
  63. self.document.unlink()
  64. self.document = None
  65. version = '1.1'
  66. def addService(self, name, documentation=''):
  67. if self.services.has_key(name):
  68. raise WSDLError(
  69. 'Duplicate service element: %s' % name
  70. )
  71. item = Service(name, documentation)
  72. self.services[name] = item
  73. return item
  74. def addMessage(self, name, documentation=''):
  75. if self.messages.has_key(name):
  76. raise WSDLError(
  77. 'Duplicate message element: %s.' % name
  78. )
  79. item = Message(name, documentation)
  80. self.messages[name] = item
  81. return item
  82. def addPortType(self, name, documentation=''):
  83. if self.portTypes.has_key(name):
  84. raise WSDLError(
  85. 'Duplicate portType element: name'
  86. )
  87. item = PortType(name, documentation)
  88. self.portTypes[name] = item
  89. return item
  90. def addBinding(self, name, type, documentation=''):
  91. if self.bindings.has_key(name):
  92. raise WSDLError(
  93. 'Duplicate binding element: %s' % name
  94. )
  95. item = Binding(name, type, documentation)
  96. self.bindings[name] = item
  97. return item
  98. def addImport(self, namespace, location):
  99. item = ImportElement(namespace, location)
  100. self.imports[namespace] = item
  101. return item
  102. def load(self, document):
  103. # We save a reference to the DOM document to ensure that elements
  104. # saved as "extensions" will continue to have a meaningful context
  105. # for things like namespace references. The lifetime of the DOM
  106. # document is bound to the lifetime of the WSDL instance.
  107. self.document = document
  108. definitions = DOM.getElement(document, 'definitions', None, None)
  109. if definitions is None:
  110. raise WSDLError(
  111. 'Missing <definitions> element.'
  112. )
  113. self.version = DOM.WSDLUriToVersion(definitions.namespaceURI)
  114. NS_WSDL = DOM.GetWSDLUri(self.version)
  115. self.targetNamespace = DOM.getAttr(definitions, 'targetNamespace',
  116. None, None)
  117. self.name = DOM.getAttr(definitions, 'name', None, None)
  118. self.documentation = GetDocumentation(definitions)
  119. # Resolve (recursively) any import elements in the document.
  120. imported = {}
  121. while 1:
  122. imports = []
  123. for element in DOM.getElements(definitions, 'import', NS_WSDL):
  124. location = DOM.getAttr(element, 'location')
  125. if not imported.has_key(location):
  126. imports.append(element)
  127. if not imports:
  128. break
  129. for element in imports:
  130. self._import(document, element)
  131. location = DOM.getAttr(element, 'location')
  132. imported[location] = 1
  133. reader = SchemaReader()
  134. for element in DOM.getElements(definitions, None, None):
  135. localName = element.localName
  136. if not DOM.nsUriMatch(element.namespaceURI, NS_WSDL):
  137. if localName == 'schema':
  138. self.types.addSchema(
  139. reader.loadFromNode(WSDLToolsAdapter(self), element)
  140. )
  141. else:
  142. self.extensions.append(element)
  143. continue
  144. elif localName == 'message':
  145. name = DOM.getAttr(element, 'name')
  146. docs = GetDocumentation(element)
  147. message = self.addMessage(name, docs)
  148. parts = DOM.getElements(element, 'part', NS_WSDL)
  149. message.load(parts)
  150. continue
  151. elif localName == 'portType':
  152. name = DOM.getAttr(element, 'name')
  153. docs = GetDocumentation(element)
  154. ptype = self.addPortType(name, docs)
  155. operations = DOM.getElements(element, 'operation', NS_WSDL)
  156. ptype.load(operations)
  157. continue
  158. elif localName == 'binding':
  159. name = DOM.getAttr(element, 'name')
  160. type = DOM.getAttr(element, 'type', default=None)
  161. if type is None:
  162. raise WSDLError(
  163. 'Missing type attribute for binding %s.' % name
  164. )
  165. type = type.split(':', 1)[-1]
  166. docs = GetDocumentation(element)
  167. binding = self.addBinding(name, type, docs)
  168. operations = DOM.getElements(element, 'operation', NS_WSDL)
  169. binding.load(operations)
  170. binding.load_ex(GetExtensions(element))
  171. continue
  172. elif localName == 'service':
  173. name = DOM.getAttr(element, 'name')
  174. docs = GetDocumentation(element)
  175. service = self.addService(name, docs)
  176. ports = DOM.getElements(element, 'port', NS_WSDL)
  177. service.load(ports)
  178. service.load_ex(GetExtensions(element))
  179. continue
  180. elif localName == 'types':
  181. self.types.documentation = GetDocumentation(element)
  182. for item in DOM.getElements(element, None, None):
  183. if item.localName == 'schema':
  184. self.types.addSchema(
  185. reader.loadFromNode(WSDLToolsAdapter(self), item)
  186. )
  187. else:
  188. self.types.addExtension(item)
  189. continue
  190. def _import(self, document, element):
  191. namespace = DOM.getAttr(element, 'namespace', default=None)
  192. location = DOM.getAttr(element, 'location', default=None)
  193. if namespace is None or location is None:
  194. raise WSDLError(
  195. 'Invalid import element (missing namespace or location).'
  196. )
  197. # Sort-of support relative locations to simplify unit testing. The
  198. # WSDL specification actually doesn't allow relative URLs, so its
  199. # ok that this only works with urls relative to the initial document.
  200. location = urllib.basejoin(self.location, location)
  201. obimport = self.addImport(namespace, location)
  202. obimport._loaded = 1
  203. importdoc = DOM.loadFromURL(location)
  204. try:
  205. if location.find('#') > -1:
  206. idref = location.split('#')[-1]
  207. imported = DOM.getElementById(importdoc, idref)
  208. else:
  209. imported = importdoc.documentElement
  210. if imported is None:
  211. raise WSDLError(
  212. 'Import target element not found for: %s' % location
  213. )
  214. imported_tns = DOM.findTargetNS(imported)
  215. if imported_tns != namespace:
  216. return
  217. if imported.localName == 'definitions':
  218. imported_nodes = imported.childNodes
  219. else:
  220. imported_nodes = [imported]
  221. parent = element.parentNode
  222. for node in imported_nodes:
  223. if node.nodeType != node.ELEMENT_NODE:
  224. continue
  225. child = DOM.importNode(document, node, 1)
  226. parent.appendChild(child)
  227. child.setAttribute('targetNamespace', namespace)
  228. attrsNS = imported._attrsNS
  229. for attrkey in attrsNS.keys():
  230. if attrkey[0] == DOM.NS_XMLNS:
  231. attr = attrsNS[attrkey].cloneNode(1)
  232. child.setAttributeNode(attr)
  233. finally:
  234. importdoc.unlink()
  235. class Element:
  236. """A class that provides common functions for WSDL element classes."""
  237. def __init__(self, name=None, documentation=''):
  238. self.name = name
  239. self.documentation = documentation
  240. self.extensions = []
  241. def addExtension(self, item):
  242. self.extensions.append(item)
  243. class ImportElement(Element):
  244. def __init__(self, namespace, location):
  245. self.namespace = namespace
  246. self.location = location
  247. _loaded = None
  248. class Types(Collection):
  249. def __init__(self, parent):
  250. Collection.__init__(self, parent)
  251. self.documentation = ''
  252. self.extensions = []
  253. def addSchema(self, schema):
  254. name = schema.targetNamespace
  255. self[name] = schema
  256. return schema
  257. def keys(self):
  258. return map(lambda i: i.targetNamespace, self.list)
  259. def items(self):
  260. return map(lambda i: i.targetNamespace, self.list)
  261. def addExtension(self, item):
  262. self.extensions.append(item)
  263. class Message(Element):
  264. def __init__(self, name, documentation=''):
  265. Element.__init__(self, name, documentation)
  266. self.parts = Collection(self)
  267. def addPart(self, name, type=None, element=None):
  268. if self.parts.has_key(name):
  269. raise WSDLError(
  270. 'Duplicate message part element: %s' % name
  271. )
  272. if type is None and element is None:
  273. raise WSDLError(
  274. 'Missing type or element attribute for part: %s' % name
  275. )
  276. item = MessagePart(name)
  277. item.element = element
  278. item.type = type
  279. self.parts[name] = item
  280. return item
  281. def load(self, elements):
  282. for element in elements:
  283. name = DOM.getAttr(element, 'name')
  284. part = MessagePart(name)
  285. self.parts[name] = part
  286. elemref = DOM.getAttr(element, 'element', default=None)
  287. typeref = DOM.getAttr(element, 'type', default=None)
  288. if typeref is None and elemref is None:
  289. raise WSDLError(
  290. 'No type or element attribute for part: %s' % name
  291. )
  292. if typeref is not None:
  293. part.type = ParseTypeRef(typeref, element)
  294. if elemref is not None:
  295. part.element = ParseTypeRef(elemref, element)
  296. class MessagePart(Element):
  297. def __init__(self, name):
  298. Element.__init__(self, name, '')
  299. self.element = None
  300. self.type = None
  301. class PortType(Element):
  302. def __init__(self, name, documentation=''):
  303. Element.__init__(self, name, documentation)
  304. self.operations = Collection(self)
  305. def getWSDL(self):
  306. return self.parent().parent()
  307. def addOperation(self, name, documentation='', parameterOrder=None):
  308. item = Operation(name, documentation, parameterOrder)
  309. self.operations[name] = item
  310. return item
  311. def load(self, elements):
  312. for element in elements:
  313. name = DOM.getAttr(element, 'name')
  314. docs = GetDocumentation(element)
  315. param_order = DOM.getAttr(element, 'parameterOrder', default=None)
  316. if param_order is not None:
  317. param_order = param_order.split(' ')
  318. operation = self.addOperation(name, docs, param_order)
  319. item = DOM.getElement(element, 'input', None, None)
  320. if item is not None:
  321. name = DOM.getAttr(item, 'name')
  322. docs = GetDocumentation(item)
  323. msgref = DOM.getAttr(item, 'message')
  324. message = msgref.split(':', 1)[-1]
  325. operation.setInput(message, name, docs)
  326. item = DOM.getElement(element, 'output', None, None)
  327. if item is not None:
  328. name = DOM.getAttr(item, 'name')
  329. docs = GetDocumentation(item)
  330. msgref = DOM.getAttr(item, 'message')
  331. message = msgref.split(':', 1)[-1]
  332. operation.setOutput(message, name, docs)
  333. for item in DOM.getElements(element, 'fault', None):
  334. name = DOM.getAttr(item, 'name')
  335. docs = GetDocumentation(item)
  336. msgref = DOM.getAttr(item, 'message')
  337. message = msgref.split(':', 1)[-1]
  338. operation.addFault(message, name, docs)
  339. class Operation(Element):
  340. def __init__(self, name, documentation='', parameterOrder=None):
  341. Element.__init__(self, name, documentation)
  342. self.parameterOrder = parameterOrder
  343. self.faults = Collection(self)
  344. self.input = None
  345. self.output = None
  346. def getPortType(self):
  347. return self.parent().parent()
  348. def getInputMessage(self):
  349. if self.input is None:
  350. return None
  351. wsdl = self.getPortType().getWSDL()
  352. return wsdl.messages[self.input.message]
  353. def getOutputMessage(self):
  354. if self.output is None:
  355. return None
  356. wsdl = self.getPortType().getWSDL()
  357. return wsdl.messages[self.output.message]
  358. def getFaultMessage(self, name):
  359. wsdl = self.getPortType().getWSDL()
  360. return wsdl.messages[self.faults[name].message]
  361. def addFault(self, name, message, documentation=''):
  362. if self.faults.has_key(name):
  363. raise WSDLError(
  364. 'Duplicate fault element: %s' % name
  365. )
  366. item = MessageRole('fault', message, name, documentation)
  367. self.faults[name] = item
  368. return item
  369. def setInput(self, message, name='', documentation=''):
  370. self.input = MessageRole('input', message, name, documentation)
  371. return self.input
  372. def setOutput(self, message, name='', documentation=''):
  373. self.output = MessageRole('output', message, name, documentation)
  374. return self.output
  375. class MessageRole(Element):
  376. def __init__(self, type, message, name='', documentation=''):
  377. Element.__init__(self, name, documentation)
  378. self.message = message
  379. self.type = type
  380. class Binding(Element):
  381. def __init__(self, name, type, documentation=''):
  382. Element.__init__(self, name, documentation)
  383. self.operations = Collection(self)
  384. self.type = type
  385. def getWSDL(self):
  386. """Return the WSDL object that contains this binding."""
  387. return self.parent().parent()
  388. def getPortType(self):
  389. """Return the PortType object associated with this binding."""
  390. return self.getWSDL().portTypes[self.type]
  391. def findBinding(self, kind):
  392. for item in self.extensions:
  393. if isinstance(item, kind):
  394. return item
  395. return None
  396. def findBindings(self, kind):
  397. return [ item for item in self.extensions if isinstance(item, kind) ]
  398. def addOperationBinding(self, name, documentation=''):
  399. item = OperationBinding(name, documentation)
  400. self.operations[name] = item
  401. return item
  402. def load(self, elements):
  403. for element in elements:
  404. name = DOM.getAttr(element, 'name')
  405. docs = GetDocumentation(element)
  406. opbinding = self.addOperationBinding(name, docs)
  407. opbinding.load_ex(GetExtensions(element))
  408. item = DOM.getElement(element, 'input', None, None)
  409. if item is not None:
  410. mbinding = MessageRoleBinding('input')
  411. mbinding.documentation = GetDocumentation(item)
  412. opbinding.input = mbinding
  413. mbinding.load_ex(GetExtensions(item))
  414. item = DOM.getElement(element, 'output', None, None)
  415. if item is not None:
  416. mbinding = MessageRoleBinding('output')
  417. mbinding.documentation = GetDocumentation(item)
  418. opbinding.output = mbinding
  419. mbinding.load_ex(GetExtensions(item))
  420. for item in DOM.getElements(element, 'fault', None):
  421. name = DOM.getAttr(item, 'name')
  422. mbinding = MessageRoleBinding('fault', name)
  423. mbinding.documentation = GetDocumentation(item)
  424. opbinding.faults[name] = mbinding
  425. mbinding.load_ex(GetExtensions(item))
  426. def load_ex(self, elements):
  427. for e in elements:
  428. ns, name = e.namespaceURI, e.localName
  429. if ns in DOM.NS_SOAP_BINDING_ALL and name == 'binding':
  430. transport = DOM.getAttr(e, 'transport', default=None)
  431. style = DOM.getAttr(e, 'style', default='document')
  432. ob = SoapBinding(transport, style)
  433. self.addExtension(ob)
  434. continue
  435. elif ns in DOM.NS_HTTP_BINDING_ALL and name == 'binding':
  436. verb = DOM.getAttr(e, 'verb')
  437. ob = HttpBinding(verb)
  438. self.addExtension(ob)
  439. continue
  440. else:
  441. self.addExtension(e)
  442. class OperationBinding(Element):
  443. def __init__(self, name, documentation=''):
  444. Element.__init__(self, name, documentation)
  445. self.input = None
  446. self.output = None
  447. self.faults = Collection(self)
  448. def getBinding(self):
  449. """Return the parent Binding object of the operation binding."""
  450. return self.parent().parent()
  451. def getOperation(self):
  452. """Return the abstract Operation associated with this binding."""
  453. return self.getBinding().getPortType().operations[self.name]
  454. def findBinding(self, kind):
  455. for item in self.extensions:
  456. if isinstance(item, kind):
  457. return item
  458. return None
  459. def findBindings(self, kind):
  460. return [ item for item in self.extensions if isinstance(item, kind) ]
  461. def addInputBinding(self, binding):
  462. if self.input is None:
  463. self.input = MessageRoleBinding('input')
  464. self.input.addExtension(binding)
  465. return binding
  466. def addOutputBinding(self, binding):
  467. if self.output is None:
  468. self.output = MessageRoleBinding('output')
  469. self.output.addExtension(binding)
  470. return binding
  471. def addFaultBinding(self, name, binding):
  472. fault = self.get(name, None)
  473. if fault is None:
  474. fault = MessageRoleBinding('fault', name)
  475. fault.addExtension(binding)
  476. return binding
  477. def load_ex(self, elements):
  478. for e in elements:
  479. ns, name = e.namespaceURI, e.localName
  480. if ns in DOM.NS_SOAP_BINDING_ALL and name == 'operation':
  481. soapaction = DOM.getAttr(e, 'soapAction', default=None)
  482. style = DOM.getAttr(e, 'style', default=None)
  483. ob = SoapOperationBinding(soapaction, style)
  484. self.addExtension(ob)
  485. continue
  486. elif ns in DOM.NS_HTTP_BINDING_ALL and name == 'operation':
  487. location = DOM.getAttr(e, 'location')
  488. ob = HttpOperationBinding(location)
  489. self.addExtension(ob)
  490. continue
  491. else:
  492. self.addExtension(e)
  493. class MessageRoleBinding(Element):
  494. def __init__(self, type, name='', documentation=''):
  495. Element.__init__(self, name, documentation)
  496. self.type = type
  497. def findBinding(self, kind):
  498. for item in self.extensions:
  499. if isinstance(item, kind):
  500. return item
  501. return None
  502. def findBindings(self, kind):
  503. return [ item for item in self.extensions if isinstance(item, kind) ]
  504. def load_ex(self, elements):
  505. for e in elements:
  506. ns, name = e.namespaceURI, e.localName
  507. if ns in DOM.NS_SOAP_BINDING_ALL and name == 'body':
  508. encstyle = DOM.getAttr(e, 'encodingStyle', default=None)
  509. namespace = DOM.getAttr(e, 'namespace', default=None)
  510. parts = DOM.getAttr(e, 'parts', default=None)
  511. use = DOM.getAttr(e, 'use', default=None)
  512. if use is None:
  513. raise WSDLError(
  514. 'Invalid soap:body binding element.'
  515. )
  516. ob = SoapBodyBinding(use, namespace, encstyle, parts)
  517. self.addExtension(ob)
  518. continue
  519. elif ns in DOM.NS_SOAP_BINDING_ALL and name == 'fault':
  520. encstyle = DOM.getAttr(e, 'encodingStyle', default=None)
  521. namespace = DOM.getAttr(e, 'namespace', default=None)
  522. name = DOM.getAttr(e, 'name', default=None)
  523. use = DOM.getAttr(e, 'use', default=None)
  524. if use is None or name is None:
  525. raise WSDLError(
  526. 'Invalid soap:fault binding element.'
  527. )
  528. ob = SoapFaultBinding(name, use, namespace, encstyle)
  529. self.addExtension(ob)
  530. continue
  531. elif ns in DOM.NS_SOAP_BINDING_ALL and name in (
  532. 'header', 'headerfault'
  533. ):
  534. encstyle = DOM.getAttr(e, 'encodingStyle', default=None)
  535. namespace = DOM.getAttr(e, 'namespace', default=None)
  536. message = DOM.getAttr(e, 'message')
  537. part = DOM.getAttr(e, 'part')
  538. use = DOM.getAttr(e, 'use')
  539. if name == 'header':
  540. _class = SoapHeaderBinding
  541. else:
  542. _class = SoapHeaderFaultBinding
  543. ob = _class(message, part, use, namespace, encstyle)
  544. self.addExtension(ob)
  545. continue
  546. elif ns in DOM.NS_HTTP_BINDING_ALL and name == 'urlReplacement':
  547. ob = HttpUrlReplacementBinding()
  548. self.addExtension(ob)
  549. continue
  550. elif ns in DOM.NS_HTTP_BINDING_ALL and name == 'urlEncoded':
  551. ob = HttpUrlEncodedBinding()
  552. self.addExtension(ob)
  553. continue
  554. elif ns in DOM.NS_MIME_BINDING_ALL and name == 'multipartRelated':
  555. ob = MimeMultipartRelatedBinding()
  556. self.addExtension(ob)
  557. ob.load_ex(GetExtensions(e))
  558. continue
  559. elif ns in DOM.NS_MIME_BINDING_ALL and name == 'content':
  560. part = DOM.getAttr(e, 'part', default=None)
  561. type = DOM.getAttr(e, 'type', default=None)
  562. ob = MimeContentBinding(part, type)
  563. self.addExtension(ob)
  564. continue
  565. elif ns in DOM.NS_MIME_BINDING_ALL and name == 'mimeXml':
  566. part = DOM.getAttr(e, 'part', default=None)
  567. ob = MimeXmlBinding(part)
  568. self.addExtension(ob)
  569. continue
  570. else:
  571. self.addExtension(e)
  572. class Service(Element):
  573. def __init__(self, name, documentation=''):
  574. Element.__init__(self, name, documentation)
  575. self.ports = Collection(self)
  576. def getWSDL(self):
  577. return self.parent().parent()
  578. def addPort(self, name, binding, documentation=''):
  579. item = Port(name, binding, documentation)
  580. self.ports[name] = item
  581. return item
  582. def load(self, elements):
  583. for element in elements:
  584. name = DOM.getAttr(element, 'name', default=None)
  585. docs = GetDocumentation(element)
  586. binding = DOM.getAttr(element, 'binding', default=None)
  587. if name is None or binding is None:
  588. raise WSDLError(
  589. 'Invalid port element.'
  590. )
  591. binding = binding.split(':', 1)[-1]
  592. port = self.addPort(name, binding, docs)
  593. port.load_ex(GetExtensions(element))
  594. def load_ex(self, elements):
  595. for e in elements:
  596. self.addExtension(e)
  597. class Port(Element):
  598. def __init__(self, name, binding, documentation=''):
  599. Element.__init__(self, name, documentation)
  600. self.binding = binding
  601. def getService(self):
  602. """Return the Service object associated with this port."""
  603. return self.parent().parent()
  604. def getBinding(self):
  605. """Return the Binding object that is referenced by this port."""
  606. wsdl = self.getService().getWSDL()
  607. return wsdl.bindings[self.binding]
  608. def getPortType(self):
  609. """Return the PortType object that is referenced by this port."""
  610. wsdl = self.getService().getWSDL()
  611. binding = wsdl.bindings[self.binding]
  612. return wsdl.portTypes[binding.type]
  613. def getAddressBinding(self):
  614. """A convenience method to obtain the extension element used
  615. as the address binding for the port, or None if undefined."""
  616. for item in self.extensions:
  617. if isinstance(item, SoapAddressBinding) or \
  618. isinstance(item, HttpAddressBinding):
  619. return item
  620. raise WSDLError(
  621. 'No address binding found in port.'
  622. )
  623. def load_ex(self, elements):
  624. for e in elements:
  625. ns, name = e.namespaceURI, e.localName
  626. if ns in DOM.NS_SOAP_BINDING_ALL and name == 'address':
  627. location = DOM.getAttr(e, 'location', default=None)
  628. ob = SoapAddressBinding(location)
  629. self.addExtension(ob)
  630. continue
  631. elif ns in DOM.NS_HTTP_BINDING_ALL and name == 'address':
  632. location = DOM.getAttr(e, 'location', default=None)
  633. ob = HttpAddressBinding(location)
  634. self.addExtension(ob)
  635. continue
  636. else:
  637. self.addExtension(e)
  638. class SoapBinding:
  639. def __init__(self, transport, style='rpc'):
  640. self.transport = transport
  641. self.style = style
  642. class SoapAddressBinding:
  643. def __init__(self, location):
  644. self.location = location
  645. class SoapOperationBinding:
  646. def __init__(self, soapAction=None, style=None):
  647. self.soapAction = soapAction
  648. self.style = style
  649. class SoapBodyBinding:
  650. def __init__(self, use, namespace=None, encodingStyle=None, parts=None):
  651. if not use in ('literal', 'encoded'):
  652. raise WSDLError(
  653. 'Invalid use attribute value: %s' % use
  654. )
  655. self.encodingStyle = encodingStyle
  656. self.namespace = namespace
  657. if type(parts) in (type(''), type(u'')):
  658. raise WSDLError(
  659. 'The parts argument must be a sequence.'
  660. )
  661. self.parts = parts
  662. self.use = use
  663. class SoapFaultBinding:
  664. def __init__(self, name, use, namespace=None, encodingStyle=None):
  665. if not use in ('literal', 'encoded'):
  666. raise WSDLError(
  667. 'Invalid use attribute value: %s' % use
  668. )
  669. self.encodingStyle = encodingStyle
  670. self.namespace = namespace
  671. self.name = name
  672. self.use = use
  673. class SoapHeaderBinding:
  674. def __init__(self, message, part, use, namespace=None, encodingStyle=None):
  675. if not use in ('literal', 'encoded'):
  676. raise WSDLError(
  677. 'Invalid use attribute value: %s' % use
  678. )
  679. self.encodingStyle = encodingStyle
  680. self.namespace = namespace
  681. self.message = message
  682. self.part = part
  683. self.use = use
  684. tagname = 'header'
  685. class SoapHeaderFaultBinding(SoapHeaderBinding):
  686. tagname = 'headerfault'
  687. class HttpBinding:
  688. def __init__(self, verb):
  689. self.verb = verb
  690. class HttpAddressBinding:
  691. def __init__(self, location):
  692. self.location = location
  693. class HttpOperationBinding:
  694. def __init__(self, location):
  695. self.location = location
  696. class HttpUrlReplacementBinding:
  697. pass
  698. class HttpUrlEncodedBinding:
  699. pass
  700. class MimeContentBinding:
  701. def __init__(self, part=None, type=None):
  702. self.part = part
  703. self.type = type
  704. class MimeXmlBinding:
  705. def __init__(self, part=None):
  706. self.part = part
  707. class MimeMultipartRelatedBinding:
  708. def __init__(self):
  709. self.parts = []
  710. def load_ex(self, elements):
  711. for e in elements:
  712. ns, name = e.namespaceURI, e.localName
  713. if ns in DOM.NS_MIME_BINDING_ALL and name == 'part':
  714. self.parts.append(MimePartBinding())
  715. continue
  716. class MimePartBinding:
  717. def __init__(self):
  718. self.items = []
  719. def load_ex(self, elements):
  720. for e in elements:
  721. ns, name = e.namespaceURI, e.localName
  722. if ns in DOM.NS_MIME_BINDING_ALL and name == 'content':
  723. part = DOM.getAttr(e, 'part', default=None)
  724. type = DOM.getAttr(e, 'type', default=None)
  725. ob = MimeContentBinding(part, type)
  726. self.items.append(ob)
  727. continue
  728. elif ns in DOM.NS_MIME_BINDING_ALL and name == 'mimeXml':
  729. part = DOM.getAttr(e, 'part', default=None)
  730. ob = MimeXmlBinding(part)
  731. self.items.append(ob)
  732. continue
  733. elif ns in DOM.NS_SOAP_BINDING_ALL and name == 'body':
  734. encstyle = DOM.getAttr(e, 'encodingStyle', default=None)
  735. namespace = DOM.getAttr(e, 'namespace', default=None)
  736. parts = DOM.getAttr(e, 'parts', default=None)
  737. use = DOM.getAttr(e, 'use', default=None)
  738. if use is None:
  739. raise WSDLError(
  740. 'Invalid soap:body binding element.'
  741. )
  742. ob = SoapBodyBinding(use, namespace, encstyle, parts)
  743. self.items.append(ob)
  744. continue
  745. class WSDLError(Exception):
  746. pass
  747. def DeclareNSPrefix(writer, prefix, nsuri):
  748. if writer.hasNSPrefix(nsuri):
  749. return
  750. writer.declareNSPrefix(prefix, nsuri)
  751. def ParseTypeRef(value, element):
  752. parts = value.split(':', 1)
  753. if len(parts) == 1:
  754. return (DOM.findTargetNS(element), value)
  755. nsuri = DOM.findNamespaceURI(parts[0], element)
  756. return (nsuri, parts[1])
  757. def ParseQName(value, element):
  758. nameref = value.split(':', 1)
  759. if len(nameref) == 2:
  760. nsuri = DOM.findNamespaceURI(nameref[0], element)
  761. name = nameref[-1]
  762. else:
  763. nsuri = DOM.findTargetNS(element)
  764. name = nameref[-1]
  765. return nsuri, name
  766. def GetDocumentation(element):
  767. docnode = DOM.getElement(element, 'documentation', None, None)
  768. if docnode is not None:
  769. return DOM.getElementText(docnode)
  770. return ''
  771. def GetExtensions(element):
  772. return [ item for item in DOM.getElements(element, None, None)
  773. if item.namespaceURI != DOM.NS_WSDL ]
  774. def FindExtensions(object, kind, t_type=type(())):
  775. if isinstance(kind, t_type):
  776. result = []
  777. namespaceURI, name = kind
  778. return [ item for item in object.extensions
  779. if hasattr(item, 'nodeType') \
  780. and DOM.nsUriMatch(namespaceURI, item.namespaceURI) \
  781. and item.name == name ]
  782. return [ item for item in object.extensions if isinstance(item, kind) ]
  783. def FindExtension(object, kind, t_type=type(())):
  784. if isinstance(kind, t_type):
  785. namespaceURI, name = kind
  786. for item in object.extensions:
  787. if hasattr(item, 'nodeType') \
  788. and DOM.nsUriMatch(namespaceURI, item.namespaceURI) \
  789. and item.name == name:
  790. return item
  791. else:
  792. for item in object.extensions:
  793. if isinstance(item, kind):
  794. return item
  795. return None
  796. class SOAPCallInfo:
  797. """SOAPCallInfo captures the important binding information about a
  798. SOAP operation, in a structure that is easier to work with than
  799. raw WSDL structures."""
  800. def __init__(self, methodName):
  801. self.methodName = methodName
  802. self.inheaders = []
  803. self.outheaders = []
  804. self.inparams = []
  805. self.outparams = []
  806. self.retval = None
  807. encodingStyle = DOM.NS_SOAP_ENC
  808. documentation = ''
  809. soapAction = None
  810. transport = None
  811. namespace = None
  812. location = None
  813. use = 'encoded'
  814. style = 'rpc'
  815. def addInParameter(self, name, type, namespace=None, element_type=0):
  816. """Add an input parameter description to the call info."""
  817. parameter = ParameterInfo(name, type, namespace, element_type)
  818. self.inparams.append(parameter)
  819. return parameter
  820. def addOutParameter(self, name, type, namespace=None, element_type=0):
  821. """Add an output parameter description to the call info."""
  822. parameter = ParameterInfo(name, type, namespace, element_type)
  823. self.outparams.append(parameter)
  824. return parameter
  825. def setReturnParameter(self, name, type, namespace=None, element_type=0):
  826. """Set the return parameter description for the call info."""
  827. parameter = ParameterInfo(name, type, namespace, element_type)
  828. self.retval = parameter
  829. return parameter
  830. def addInHeaderInfo(self, name, type, namespace, element_type=0,
  831. mustUnderstand=0):
  832. """Add an input SOAP header description to the call info."""
  833. headerinfo = HeaderInfo(name, type, namespace, element_type)
  834. if mustUnderstand:
  835. headerinfo.mustUnderstand = 1
  836. self.inheaders.append(headerinfo)
  837. return headerinfo
  838. def addOutHeaderInfo(self, name, type, namespace, element_type=0,
  839. mustUnderstand=0):
  840. """Add an output SOAP header description to the call info."""
  841. headerinfo = HeaderInfo(name, type, namespace, element_type)
  842. if mustUnderstand:
  843. headerinfo.mustUnderstand = 1
  844. self.outheaders.append(headerinfo)
  845. return headerinfo
  846. def getInParameters(self):
  847. """Return a sequence of the in parameters of the method."""
  848. return self.inparams
  849. def getOutParameters(self):
  850. """Return a sequence of the out parameters of the method."""
  851. return self.outparams
  852. def getReturnParameter(self):
  853. """Return param info about the return value of the method."""
  854. return self.retval
  855. def getInHeaders(self):
  856. """Return a sequence of the in headers of the method."""
  857. return self.inheaders
  858. def getOutHeaders(self):
  859. """Return a sequence of the out headers of the method."""
  860. return self.outheaders
  861. class ParameterInfo:
  862. """A ParameterInfo object captures parameter binding information."""
  863. def __init__(self, name, type, namespace=None, element_type=0):
  864. if element_type:
  865. self.element_type = 1
  866. if namespace is not None:
  867. self.namespace = namespace
  868. self.name = name
  869. self.type = type
  870. element_type = 0
  871. namespace = None
  872. default = None
  873. class HeaderInfo(ParameterInfo):
  874. """A HeaderInfo object captures SOAP header binding information."""
  875. def __init__(self, name, type, namespace, element_type=None):
  876. ParameterInfo.__init__(self, name, type, namespace, element_type)
  877. mustUnderstand = 0
  878. actor = None
  879. def callInfoFromWSDL(port, name):
  880. """Return a SOAPCallInfo given a WSDL port and operation name."""
  881. wsdl = port.getService().getWSDL()
  882. binding = port.getBinding()
  883. portType = binding.getPortType()
  884. operation = portType.operations[name]
  885. opbinding = binding.operations[name]
  886. messages = wsdl.messages
  887. callinfo = SOAPCallInfo(name)
  888. addrbinding = port.getAddressBinding()
  889. if not isinstance(addrbinding, SoapAddressBinding):
  890. raise ValueError, 'Unsupported binding type.'
  891. callinfo.location = addrbinding.location
  892. soapbinding = binding.findBinding(SoapBinding)
  893. if soapbinding is None:
  894. raise ValueError, 'Missing soap:binding element.'
  895. callinfo.transport = soapbinding.transport
  896. callinfo.style = soapbinding.style or 'document'
  897. soap_op_binding = opbinding.findBinding(SoapOperationBinding)
  898. if soap_op_binding is not None:
  899. callinfo.soapAction = soap_op_binding.soapAction
  900. callinfo.style = soap_op_binding.style or callinfo.style
  901. parameterOrder = operation.parameterOrder
  902. if operation.input is not None:
  903. message = messages[operation.input.message]
  904. msgrole = opbinding.input
  905. mime = msgrole.findBinding(MimeMultipartRelatedBinding)
  906. if mime is not None:
  907. raise ValueError, 'Mime bindings are not supported.'
  908. else:
  909. for item in msgrole.findBindings(SoapHeaderBinding):
  910. part = messages[item.message].parts[item.part]
  911. header = callinfo.addInHeaderInfo(
  912. part.name,
  913. part.element or part.type,
  914. item.namespace,
  915. element_type = part.element and 1 or 0
  916. )
  917. header.encodingStyle = item.encodingStyle
  918. body = msgrole.findBinding(SoapBodyBinding)
  919. if body is None:
  920. raise ValueError, 'Missing soap:body binding.'
  921. callinfo.encodingStyle = body.encodingStyle
  922. callinfo.namespace = body.namespace
  923. callinfo.use = body.use
  924. if body.parts is not None:
  925. parts = []
  926. for name in body.parts:
  927. parts.append(message.parts[name])
  928. else:
  929. parts = message.parts.values()
  930. for part in parts:
  931. callinfo.addInParameter(
  932. part.name,
  933. part.element or part.type,
  934. element_type = part.element and 1 or 0
  935. )
  936. if operation.output is not None:
  937. message = messages[operation.output.message]
  938. msgrole = opbinding.output
  939. mime = msgrole.findBinding(MimeMultipartRelatedBinding)
  940. if mime is not None:
  941. raise ValueError, 'Mime bindings are not supported.'
  942. else:
  943. for item in msgrole.findBindings(SoapHeaderBinding):
  944. part = messages[item.message].parts[item.part]
  945. header = callinfo.addOutHeaderInfo(
  946. part.name,
  947. part.element or part.type,
  948. item.namespace,
  949. element_type = part.element and 1 or 0
  950. )
  951. header.encodingStyle = item.encodingStyle
  952. body = msgrole.findBinding(SoapBodyBinding)
  953. if body is None:
  954. raise ValueError, 'Missing soap:body binding.'
  955. callinfo.encodingStyle = body.encodingStyle
  956. callinfo.namespace = body.namespace
  957. callinfo.use = body.use
  958. if body.parts is not None:
  959. parts = []
  960. for name in body.parts:
  961. parts.append(message.parts[name])
  962. else:
  963. parts = message.parts.values()
  964. if parts:
  965. callinfo.setReturnParameter(
  966. parts[0].name,
  967. parts[0].element or parts[0].type,
  968. element_type = parts[0].element and 1 or 0
  969. )
  970. for part in parts[1:]:
  971. callinfo.addOutParameter(
  972. part.name,
  973. part.element or part.type,
  974. element_type = part.element and 1 or 0
  975. )
  976. return callinfo