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.
 
 
 

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