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.
 
 
 

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