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.
 
 
 

1289 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 addOperation(self, name, documentation='', parameterOrder=None):
  345. item = Operation(name, documentation, parameterOrder)
  346. self.operations[name] = item
  347. return item
  348. def load(self, element):
  349. self.name = DOM.getAttr(element, 'name')
  350. self.documentation = GetDocumentation(element)
  351. if DOM.hasAttr(element, 'ResourceProperties', WSR.PROPERTIES):
  352. rpref = DOM.getAttr(element, 'ResourceProperties', WSR.PROPERTIES)
  353. self.resourceProperties = ParseQName(rpref, element)
  354. NS_WSDL = DOM.GetWSDLUri(self.getWSDL().version)
  355. elements = DOM.getElements(element, 'operation', NS_WSDL)
  356. for element in elements:
  357. name = DOM.getAttr(element, 'name')
  358. docs = GetDocumentation(element)
  359. param_order = DOM.getAttr(element, 'parameterOrder', default=None)
  360. if param_order is not None:
  361. param_order = param_order.split(' ')
  362. operation = self.addOperation(name, docs, param_order)
  363. item = DOM.getElement(element, 'input', None, None)
  364. if item is not None:
  365. name = DOM.getAttr(item, 'name')
  366. docs = GetDocumentation(item)
  367. msgref = DOM.getAttr(item, 'message')
  368. message = ParseQName(msgref, item)
  369. action = DOM.getAttr(item, 'Action', WSA.ADDRESS, None)
  370. operation.setInput(message, name, docs, action)
  371. item = DOM.getElement(element, 'output', None, None)
  372. if item is not None:
  373. name = DOM.getAttr(item, 'name')
  374. docs = GetDocumentation(item)
  375. msgref = DOM.getAttr(item, 'message')
  376. message = ParseQName(msgref, item)
  377. action = DOM.getAttr(item, 'Action', WSA.ADDRESS, None)
  378. operation.setOutput(message, name, docs, action)
  379. for item in DOM.getElements(element, 'fault', None):
  380. name = DOM.getAttr(item, 'name')
  381. docs = GetDocumentation(item)
  382. msgref = DOM.getAttr(item, 'message')
  383. message = ParseQName(msgref, item)
  384. action = DOM.getAttr(item, 'Action', WSA.ADDRESS, None)
  385. operation.addFault(message, name, docs, action)
  386. class Operation(Element):
  387. def __init__(self, name, documentation='', parameterOrder=None):
  388. Element.__init__(self, name, documentation)
  389. self.parameterOrder = parameterOrder
  390. self.faults = Collection(self)
  391. self.input = None
  392. self.output = None
  393. def getPortType(self):
  394. return self.parent().parent()
  395. def getInputAction(self):
  396. """wsa:Action attribute"""
  397. return GetWSAActionInput(self)
  398. def getInputMessage(self):
  399. if self.input is None:
  400. return None
  401. wsdl = self.getPortType().getWSDL()
  402. return wsdl.messages[self.input.message]
  403. def getOutputAction(self):
  404. """wsa:Action attribute"""
  405. return GetWSAActionOutput(self)
  406. def getOutputMessage(self):
  407. if self.output is None:
  408. return None
  409. wsdl = self.getPortType().getWSDL()
  410. return wsdl.messages[self.output.message]
  411. def getFaultAction(self, name):
  412. """wsa:Action attribute"""
  413. return GetWSAActionFault(self, name)
  414. def getFaultMessage(self, name):
  415. wsdl = self.getPortType().getWSDL()
  416. return wsdl.messages[self.faults[name].message]
  417. def addFault(self, message, name, documentation='', action=None):
  418. if self.faults.has_key(name):
  419. raise WSDLError(
  420. 'Duplicate fault element: %s' % name
  421. )
  422. item = MessageRole('fault', message, name, documentation, action)
  423. self.faults[name] = item
  424. return item
  425. def setInput(self, message, name='', documentation='', action=None):
  426. self.input = MessageRole('input', message, name, documentation, action)
  427. return self.input
  428. def setOutput(self, message, name='', documentation='', action=None):
  429. self.output = MessageRole('output', message, name, documentation, action)
  430. return self.output
  431. class MessageRole(Element):
  432. def __init__(self, type, message, name='', documentation='', action=None):
  433. Element.__init__(self, name, documentation)
  434. self.message = message
  435. self.type = type
  436. self.action = action
  437. class Binding(Element):
  438. def __init__(self, name, type, documentation=''):
  439. Element.__init__(self, name, documentation)
  440. self.operations = Collection(self)
  441. self.type = type
  442. def getWSDL(self):
  443. """Return the WSDL object that contains this binding."""
  444. return self.parent().parent()
  445. def getPortType(self):
  446. """Return the PortType object associated with this binding."""
  447. return self.getWSDL().portTypes[self.type]
  448. def findBinding(self, kind):
  449. for item in self.extensions:
  450. if isinstance(item, kind):
  451. return item
  452. return None
  453. def findBindings(self, kind):
  454. return [ item for item in self.extensions if isinstance(item, kind) ]
  455. def addOperationBinding(self, name, documentation=''):
  456. item = OperationBinding(name, documentation)
  457. self.operations[name] = item
  458. return item
  459. def load(self, elements):
  460. for element in elements:
  461. name = DOM.getAttr(element, 'name')
  462. docs = GetDocumentation(element)
  463. opbinding = self.addOperationBinding(name, docs)
  464. opbinding.load_ex(GetExtensions(element))
  465. item = DOM.getElement(element, 'input', None, None)
  466. if item is not None:
  467. mbinding = MessageRoleBinding('input')
  468. mbinding.documentation = GetDocumentation(item)
  469. opbinding.input = mbinding
  470. mbinding.load_ex(GetExtensions(item))
  471. item = DOM.getElement(element, 'output', None, None)
  472. if item is not None:
  473. mbinding = MessageRoleBinding('output')
  474. mbinding.documentation = GetDocumentation(item)
  475. opbinding.output = mbinding
  476. mbinding.load_ex(GetExtensions(item))
  477. for item in DOM.getElements(element, 'fault', None):
  478. name = DOM.getAttr(item, 'name')
  479. mbinding = MessageRoleBinding('fault', name)
  480. mbinding.documentation = GetDocumentation(item)
  481. opbinding.faults[name] = mbinding
  482. mbinding.load_ex(GetExtensions(item))
  483. def load_ex(self, elements):
  484. for e in elements:
  485. ns, name = e.namespaceURI, e.localName
  486. if ns in DOM.NS_SOAP_BINDING_ALL and name == 'binding':
  487. transport = DOM.getAttr(e, 'transport', default=None)
  488. style = DOM.getAttr(e, 'style', default='document')
  489. ob = SoapBinding(transport, style)
  490. self.addExtension(ob)
  491. continue
  492. elif ns in DOM.NS_HTTP_BINDING_ALL and name == 'binding':
  493. verb = DOM.getAttr(e, 'verb')
  494. ob = HttpBinding(verb)
  495. self.addExtension(ob)
  496. continue
  497. else:
  498. self.addExtension(e)
  499. class OperationBinding(Element):
  500. def __init__(self, name, documentation=''):
  501. Element.__init__(self, name, documentation)
  502. self.input = None
  503. self.output = None
  504. self.faults = Collection(self)
  505. def getBinding(self):
  506. """Return the parent Binding object of the operation binding."""
  507. return self.parent().parent()
  508. def getOperation(self):
  509. """Return the abstract Operation associated with this binding."""
  510. return self.getBinding().getPortType().operations[self.name]
  511. def findBinding(self, kind):
  512. for item in self.extensions:
  513. if isinstance(item, kind):
  514. return item
  515. return None
  516. def findBindings(self, kind):
  517. return [ item for item in self.extensions if isinstance(item, kind) ]
  518. def addInputBinding(self, binding):
  519. if self.input is None:
  520. self.input = MessageRoleBinding('input')
  521. self.input.addExtension(binding)
  522. return binding
  523. def addOutputBinding(self, binding):
  524. if self.output is None:
  525. self.output = MessageRoleBinding('output')
  526. self.output.addExtension(binding)
  527. return binding
  528. def addFaultBinding(self, name, binding):
  529. fault = self.get(name, None)
  530. if fault is None:
  531. fault = MessageRoleBinding('fault', name)
  532. fault.addExtension(binding)
  533. return binding
  534. def load_ex(self, elements):
  535. for e in elements:
  536. ns, name = e.namespaceURI, e.localName
  537. if ns in DOM.NS_SOAP_BINDING_ALL and name == 'operation':
  538. soapaction = DOM.getAttr(e, 'soapAction', default=None)
  539. style = DOM.getAttr(e, 'style', default=None)
  540. ob = SoapOperationBinding(soapaction, style)
  541. self.addExtension(ob)
  542. continue
  543. elif ns in DOM.NS_HTTP_BINDING_ALL and name == 'operation':
  544. location = DOM.getAttr(e, 'location')
  545. ob = HttpOperationBinding(location)
  546. self.addExtension(ob)
  547. continue
  548. else:
  549. self.addExtension(e)
  550. class MessageRoleBinding(Element):
  551. def __init__(self, type, name='', documentation=''):
  552. Element.__init__(self, name, documentation)
  553. self.type = type
  554. def findBinding(self, kind):
  555. for item in self.extensions:
  556. if isinstance(item, kind):
  557. return item
  558. return None
  559. def findBindings(self, kind):
  560. return [ item for item in self.extensions if isinstance(item, kind) ]
  561. def load_ex(self, elements):
  562. for e in elements:
  563. ns, name = e.namespaceURI, e.localName
  564. if ns in DOM.NS_SOAP_BINDING_ALL and name == 'body':
  565. encstyle = DOM.getAttr(e, 'encodingStyle', default=None)
  566. namespace = DOM.getAttr(e, 'namespace', default=None)
  567. parts = DOM.getAttr(e, 'parts', default=None)
  568. use = DOM.getAttr(e, 'use', default=None)
  569. if use is None:
  570. raise WSDLError(
  571. 'Invalid soap:body binding element.'
  572. )
  573. ob = SoapBodyBinding(use, namespace, encstyle, parts)
  574. self.addExtension(ob)
  575. continue
  576. elif ns in DOM.NS_SOAP_BINDING_ALL and name == 'fault':
  577. encstyle = DOM.getAttr(e, 'encodingStyle', default=None)
  578. namespace = DOM.getAttr(e, 'namespace', default=None)
  579. name = DOM.getAttr(e, 'name', default=None)
  580. use = DOM.getAttr(e, 'use', default=None)
  581. if use is None or name is None:
  582. raise WSDLError(
  583. 'Invalid soap:fault binding element.'
  584. )
  585. ob = SoapFaultBinding(name, use, namespace, encstyle)
  586. self.addExtension(ob)
  587. continue
  588. elif ns in DOM.NS_SOAP_BINDING_ALL and name in (
  589. 'header', 'headerfault'
  590. ):
  591. encstyle = DOM.getAttr(e, 'encodingStyle', default=None)
  592. namespace = DOM.getAttr(e, 'namespace', default=None)
  593. message = DOM.getAttr(e, 'message')
  594. part = DOM.getAttr(e, 'part')
  595. use = DOM.getAttr(e, 'use')
  596. if name == 'header':
  597. _class = SoapHeaderBinding
  598. else:
  599. _class = SoapHeaderFaultBinding
  600. ob = _class(message, part, use, namespace, encstyle)
  601. self.addExtension(ob)
  602. continue
  603. elif ns in DOM.NS_HTTP_BINDING_ALL and name == 'urlReplacement':
  604. ob = HttpUrlReplacementBinding()
  605. self.addExtension(ob)
  606. continue
  607. elif ns in DOM.NS_HTTP_BINDING_ALL and name == 'urlEncoded':
  608. ob = HttpUrlEncodedBinding()
  609. self.addExtension(ob)
  610. continue
  611. elif ns in DOM.NS_MIME_BINDING_ALL and name == 'multipartRelated':
  612. ob = MimeMultipartRelatedBinding()
  613. self.addExtension(ob)
  614. ob.load_ex(GetExtensions(e))
  615. continue
  616. elif ns in DOM.NS_MIME_BINDING_ALL and name == 'content':
  617. part = DOM.getAttr(e, 'part', default=None)
  618. type = DOM.getAttr(e, 'type', default=None)
  619. ob = MimeContentBinding(part, type)
  620. self.addExtension(ob)
  621. continue
  622. elif ns in DOM.NS_MIME_BINDING_ALL and name == 'mimeXml':
  623. part = DOM.getAttr(e, 'part', default=None)
  624. ob = MimeXmlBinding(part)
  625. self.addExtension(ob)
  626. continue
  627. else:
  628. self.addExtension(e)
  629. class Service(Element):
  630. def __init__(self, name, documentation=''):
  631. Element.__init__(self, name, documentation)
  632. self.ports = Collection(self)
  633. def getWSDL(self):
  634. return self.parent().parent()
  635. def addPort(self, name, binding, documentation=''):
  636. item = Port(name, binding, documentation)
  637. self.ports[name] = item
  638. return item
  639. def load(self, elements):
  640. for element in elements:
  641. name = DOM.getAttr(element, 'name', default=None)
  642. docs = GetDocumentation(element)
  643. binding = DOM.getAttr(element, 'binding', default=None)
  644. if name is None or binding is None:
  645. raise WSDLError(
  646. 'Invalid port element.'
  647. )
  648. binding = ParseQName(binding, element)
  649. port = self.addPort(name, binding, docs)
  650. port.load_ex(GetExtensions(element))
  651. def load_ex(self, elements):
  652. for e in elements:
  653. self.addExtension(e)
  654. class Port(Element):
  655. def __init__(self, name, binding, documentation=''):
  656. Element.__init__(self, name, documentation)
  657. self.binding = binding
  658. def getService(self):
  659. """Return the Service object associated with this port."""
  660. return self.parent().parent()
  661. def getBinding(self):
  662. """Return the Binding object that is referenced by this port."""
  663. wsdl = self.getService().getWSDL()
  664. return wsdl.bindings[self.binding]
  665. def getPortType(self):
  666. """Return the PortType object that is referenced by this port."""
  667. wsdl = self.getService().getWSDL()
  668. binding = wsdl.bindings[self.binding]
  669. return wsdl.portTypes[binding.type]
  670. def getAddressBinding(self):
  671. """A convenience method to obtain the extension element used
  672. as the address binding for the port, or None if undefined."""
  673. for item in self.extensions:
  674. if isinstance(item, SoapAddressBinding) or \
  675. isinstance(item, HttpAddressBinding):
  676. return item
  677. raise WSDLError(
  678. 'No address binding found in port.'
  679. )
  680. def load_ex(self, elements):
  681. for e in elements:
  682. ns, name = e.namespaceURI, e.localName
  683. if ns in DOM.NS_SOAP_BINDING_ALL and name == 'address':
  684. location = DOM.getAttr(e, 'location', default=None)
  685. ob = SoapAddressBinding(location)
  686. self.addExtension(ob)
  687. continue
  688. elif ns in DOM.NS_HTTP_BINDING_ALL and name == 'address':
  689. location = DOM.getAttr(e, 'location', default=None)
  690. ob = HttpAddressBinding(location)
  691. self.addExtension(ob)
  692. continue
  693. else:
  694. self.addExtension(e)
  695. class SoapBinding:
  696. def __init__(self, transport, style='rpc'):
  697. self.transport = transport
  698. self.style = style
  699. class SoapAddressBinding:
  700. def __init__(self, location):
  701. self.location = location
  702. class SoapOperationBinding:
  703. def __init__(self, soapAction=None, style=None):
  704. self.soapAction = soapAction
  705. self.style = style
  706. class SoapBodyBinding:
  707. def __init__(self, use, namespace=None, encodingStyle=None, parts=None):
  708. if not use in ('literal', 'encoded'):
  709. raise WSDLError(
  710. 'Invalid use attribute value: %s' % use
  711. )
  712. self.encodingStyle = encodingStyle
  713. self.namespace = namespace
  714. if type(parts) in (type(''), type(u'')):
  715. parts = parts.split()
  716. self.parts = parts
  717. self.use = use
  718. class SoapFaultBinding:
  719. def __init__(self, name, use, namespace=None, encodingStyle=None):
  720. if not use in ('literal', 'encoded'):
  721. raise WSDLError(
  722. 'Invalid use attribute value: %s' % use
  723. )
  724. self.encodingStyle = encodingStyle
  725. self.namespace = namespace
  726. self.name = name
  727. self.use = use
  728. class SoapHeaderBinding:
  729. def __init__(self, message, part, use, namespace=None, encodingStyle=None):
  730. if not use in ('literal', 'encoded'):
  731. raise WSDLError(
  732. 'Invalid use attribute value: %s' % use
  733. )
  734. self.encodingStyle = encodingStyle
  735. self.namespace = namespace
  736. self.message = message
  737. self.part = part
  738. self.use = use
  739. tagname = 'header'
  740. class SoapHeaderFaultBinding(SoapHeaderBinding):
  741. tagname = 'headerfault'
  742. class HttpBinding:
  743. def __init__(self, verb):
  744. self.verb = verb
  745. class HttpAddressBinding:
  746. def __init__(self, location):
  747. self.location = location
  748. class HttpOperationBinding:
  749. def __init__(self, location):
  750. self.location = location
  751. class HttpUrlReplacementBinding:
  752. pass
  753. class HttpUrlEncodedBinding:
  754. pass
  755. class MimeContentBinding:
  756. def __init__(self, part=None, type=None):
  757. self.part = part
  758. self.type = type
  759. class MimeXmlBinding:
  760. def __init__(self, part=None):
  761. self.part = part
  762. class MimeMultipartRelatedBinding:
  763. def __init__(self):
  764. self.parts = []
  765. def load_ex(self, elements):
  766. for e in elements:
  767. ns, name = e.namespaceURI, e.localName
  768. if ns in DOM.NS_MIME_BINDING_ALL and name == 'part':
  769. self.parts.append(MimePartBinding())
  770. continue
  771. class MimePartBinding:
  772. def __init__(self):
  773. self.items = []
  774. def load_ex(self, elements):
  775. for e in elements:
  776. ns, name = e.namespaceURI, e.localName
  777. if ns in DOM.NS_MIME_BINDING_ALL and name == 'content':
  778. part = DOM.getAttr(e, 'part', default=None)
  779. type = DOM.getAttr(e, 'type', default=None)
  780. ob = MimeContentBinding(part, type)
  781. self.items.append(ob)
  782. continue
  783. elif ns in DOM.NS_MIME_BINDING_ALL and name == 'mimeXml':
  784. part = DOM.getAttr(e, 'part', default=None)
  785. ob = MimeXmlBinding(part)
  786. self.items.append(ob)
  787. continue
  788. elif ns in DOM.NS_SOAP_BINDING_ALL and name == 'body':
  789. encstyle = DOM.getAttr(e, 'encodingStyle', default=None)
  790. namespace = DOM.getAttr(e, 'namespace', default=None)
  791. parts = DOM.getAttr(e, 'parts', default=None)
  792. use = DOM.getAttr(e, 'use', default=None)
  793. if use is None:
  794. raise WSDLError(
  795. 'Invalid soap:body binding element.'
  796. )
  797. ob = SoapBodyBinding(use, namespace, encstyle, parts)
  798. self.items.append(ob)
  799. continue
  800. class WSDLError(Exception):
  801. pass
  802. def DeclareNSPrefix(writer, prefix, nsuri):
  803. if writer.hasNSPrefix(nsuri):
  804. return
  805. writer.declareNSPrefix(prefix, nsuri)
  806. def ParseTypeRef(value, element):
  807. parts = value.split(':', 1)
  808. if len(parts) == 1:
  809. return (DOM.findTargetNS(element), value)
  810. nsuri = DOM.findNamespaceURI(parts[0], element)
  811. return (nsuri, parts[1])
  812. def ParseQName(value, element):
  813. nameref = value.split(':', 1)
  814. if len(nameref) == 2:
  815. nsuri = DOM.findNamespaceURI(nameref[0], element)
  816. name = nameref[-1]
  817. else:
  818. nsuri = DOM.findTargetNS(element)
  819. name = nameref[-1]
  820. return nsuri, name
  821. def GetDocumentation(element):
  822. docnode = DOM.getElement(element, 'documentation', None, None)
  823. if docnode is not None:
  824. return DOM.getElementText(docnode)
  825. return ''
  826. def GetExtensions(element):
  827. return [ item for item in DOM.getElements(element, None, None)
  828. if item.namespaceURI != DOM.NS_WSDL ]
  829. def GetWSAActionFault(operation, name):
  830. """Find wsa:Action attribute, and return value or WSA.FAULT
  831. for the default.
  832. """
  833. attr = operation.faults[name].action
  834. if attr is not None:
  835. return attr
  836. return WSA.FAULT
  837. def GetWSAActionInput(operation):
  838. """Find wsa:Action attribute, and return value or the default."""
  839. attr = operation.input.action
  840. if attr is not None:
  841. return attr
  842. targetNamespace = operation.getPortType().getWSDL().targetNamespace
  843. ptName = operation.getPortType().name
  844. msgName = operation.getInputMessage().name
  845. if targetNamespace.endswith('/'):
  846. return '%s%s/%s' %(targetNamespace, ptName, msgName)
  847. return '%s/%s/%s' %(targetNamespace, ptName, msgName)
  848. def GetWSAActionOutput(operation):
  849. """Find wsa:Action attribute, and return value or the default."""
  850. attr = operation.output.action
  851. if attr is not None:
  852. return attr.value
  853. targetNamespace = operation.getPortType().getWSDL().targetNamespace
  854. ptName = operation.getPortType().name
  855. msgName = operation.getOutputMessage().name
  856. if targetNamespace.endswith('/'):
  857. return '%s%s/%s' %(targetNamespace, ptName, msgName)
  858. return '%s/%s/%s' %(targetNamespace, ptName, msgName)
  859. def FindExtensions(object, kind, t_type=type(())):
  860. if isinstance(kind, t_type):
  861. result = []
  862. namespaceURI, name = kind
  863. return [ item for item in object.extensions
  864. if hasattr(item, 'nodeType') \
  865. and DOM.nsUriMatch(namespaceURI, item.namespaceURI) \
  866. and item.name == name ]
  867. return [ item for item in object.extensions if isinstance(item, kind) ]
  868. def FindExtension(object, kind, t_type=type(())):
  869. if isinstance(kind, t_type):
  870. namespaceURI, name = kind
  871. for item in object.extensions:
  872. if hasattr(item, 'nodeType') \
  873. and DOM.nsUriMatch(namespaceURI, item.namespaceURI) \
  874. and item.name == name:
  875. return item
  876. else:
  877. for item in object.extensions:
  878. if isinstance(item, kind):
  879. return item
  880. return None
  881. class SOAPCallInfo:
  882. """SOAPCallInfo captures the important binding information about a
  883. SOAP operation, in a structure that is easier to work with than
  884. raw WSDL structures."""
  885. def __init__(self, methodName):
  886. self.methodName = methodName
  887. self.inheaders = []
  888. self.outheaders = []
  889. self.inparams = []
  890. self.outparams = []
  891. self.retval = None
  892. encodingStyle = DOM.NS_SOAP_ENC
  893. documentation = ''
  894. soapAction = None
  895. transport = None
  896. namespace = None
  897. location = None
  898. use = 'encoded'
  899. style = 'rpc'
  900. def addInParameter(self, name, type, namespace=None, element_type=0):
  901. """Add an input parameter description to the call info."""
  902. parameter = ParameterInfo(name, type, namespace, element_type)
  903. self.inparams.append(parameter)
  904. return parameter
  905. def addOutParameter(self, name, type, namespace=None, element_type=0):
  906. """Add an output parameter description to the call info."""
  907. parameter = ParameterInfo(name, type, namespace, element_type)
  908. self.outparams.append(parameter)
  909. return parameter
  910. def setReturnParameter(self, name, type, namespace=None, element_type=0):
  911. """Set the return parameter description for the call info."""
  912. parameter = ParameterInfo(name, type, namespace, element_type)
  913. self.retval = parameter
  914. return parameter
  915. def addInHeaderInfo(self, name, type, namespace, element_type=0,
  916. mustUnderstand=0):
  917. """Add an input SOAP header description to the call info."""
  918. headerinfo = HeaderInfo(name, type, namespace, element_type)
  919. if mustUnderstand:
  920. headerinfo.mustUnderstand = 1
  921. self.inheaders.append(headerinfo)
  922. return headerinfo
  923. def addOutHeaderInfo(self, name, type, namespace, element_type=0,
  924. mustUnderstand=0):
  925. """Add an output SOAP header description to the call info."""
  926. headerinfo = HeaderInfo(name, type, namespace, element_type)
  927. if mustUnderstand:
  928. headerinfo.mustUnderstand = 1
  929. self.outheaders.append(headerinfo)
  930. return headerinfo
  931. def getInParameters(self):
  932. """Return a sequence of the in parameters of the method."""
  933. return self.inparams
  934. def getOutParameters(self):
  935. """Return a sequence of the out parameters of the method."""
  936. return self.outparams
  937. def getReturnParameter(self):
  938. """Return param info about the return value of the method."""
  939. return self.retval
  940. def getInHeaders(self):
  941. """Return a sequence of the in headers of the method."""
  942. return self.inheaders
  943. def getOutHeaders(self):
  944. """Return a sequence of the out headers of the method."""
  945. return self.outheaders
  946. class ParameterInfo:
  947. """A ParameterInfo object captures parameter binding information."""
  948. def __init__(self, name, type, namespace=None, element_type=0):
  949. if element_type:
  950. self.element_type = 1
  951. if namespace is not None:
  952. self.namespace = namespace
  953. self.name = name
  954. self.type = type
  955. element_type = 0
  956. namespace = None
  957. default = None
  958. class HeaderInfo(ParameterInfo):
  959. """A HeaderInfo object captures SOAP header binding information."""
  960. def __init__(self, name, type, namespace, element_type=None):
  961. ParameterInfo.__init__(self, name, type, namespace, element_type)
  962. mustUnderstand = 0
  963. actor = None
  964. def callInfoFromWSDL(port, name):
  965. """Return a SOAPCallInfo given a WSDL port and operation name."""
  966. wsdl = port.getService().getWSDL()
  967. binding = port.getBinding()
  968. portType = binding.getPortType()
  969. operation = portType.operations[name]
  970. opbinding = binding.operations[name]
  971. messages = wsdl.messages
  972. callinfo = SOAPCallInfo(name)
  973. addrbinding = port.getAddressBinding()
  974. if not isinstance(addrbinding, SoapAddressBinding):
  975. raise ValueError, 'Unsupported binding type.'
  976. callinfo.location = addrbinding.location
  977. soapbinding = binding.findBinding(SoapBinding)
  978. if soapbinding is None:
  979. raise ValueError, 'Missing soap:binding element.'
  980. callinfo.transport = soapbinding.transport
  981. callinfo.style = soapbinding.style or 'document'
  982. soap_op_binding = opbinding.findBinding(SoapOperationBinding)
  983. if soap_op_binding is not None:
  984. callinfo.soapAction = soap_op_binding.soapAction
  985. callinfo.style = soap_op_binding.style or callinfo.style
  986. parameterOrder = operation.parameterOrder
  987. if operation.input is not None:
  988. message = messages[operation.input.message]
  989. msgrole = opbinding.input
  990. mime = msgrole.findBinding(MimeMultipartRelatedBinding)
  991. if mime is not None:
  992. raise ValueError, 'Mime bindings are not supported.'
  993. else:
  994. for item in msgrole.findBindings(SoapHeaderBinding):
  995. part = messages[item.message].parts[item.part]
  996. header = callinfo.addInHeaderInfo(
  997. part.name,
  998. part.element or part.type,
  999. item.namespace,
  1000. element_type = part.element and 1 or 0
  1001. )
  1002. header.encodingStyle = item.encodingStyle
  1003. body = msgrole.findBinding(SoapBodyBinding)
  1004. if body is None:
  1005. raise ValueError, 'Missing soap:body binding.'
  1006. callinfo.encodingStyle = body.encodingStyle
  1007. callinfo.namespace = body.namespace
  1008. callinfo.use = body.use
  1009. if body.parts is not None:
  1010. parts = []
  1011. for name in body.parts:
  1012. parts.append(message.parts[name])
  1013. else:
  1014. parts = message.parts.values()
  1015. for part in parts:
  1016. callinfo.addInParameter(
  1017. part.name,
  1018. part.element or part.type,
  1019. element_type = part.element and 1 or 0
  1020. )
  1021. if operation.output is not None:
  1022. try:
  1023. message = messages[operation.output.message]
  1024. except KeyError:
  1025. if self.strict:
  1026. raise RuntimeError(
  1027. "Recieved message not defined in the WSDL schema: %s" %
  1028. operation.output.message)
  1029. else:
  1030. message = wsdl.addMessage(operation.output.message)
  1031. print "Warning:", \
  1032. "Recieved message not defined in the WSDL schema.", \
  1033. "Adding it."
  1034. print "Message:", operation.output.message
  1035. msgrole = opbinding.output
  1036. mime = msgrole.findBinding(MimeMultipartRelatedBinding)
  1037. if mime is not None:
  1038. raise ValueError, 'Mime bindings are not supported.'
  1039. else:
  1040. for item in msgrole.findBindings(SoapHeaderBinding):
  1041. part = messages[item.message].parts[item.part]
  1042. header = callinfo.addOutHeaderInfo(
  1043. part.name,
  1044. part.element or part.type,
  1045. item.namespace,
  1046. element_type = part.element and 1 or 0
  1047. )
  1048. header.encodingStyle = item.encodingStyle
  1049. body = msgrole.findBinding(SoapBodyBinding)
  1050. if body is None:
  1051. raise ValueError, 'Missing soap:body binding.'
  1052. callinfo.encodingStyle = body.encodingStyle
  1053. callinfo.namespace = body.namespace
  1054. callinfo.use = body.use
  1055. if body.parts is not None:
  1056. parts = []
  1057. for name in body.parts:
  1058. parts.append(message.parts[name])
  1059. else:
  1060. parts = message.parts.values()
  1061. if parts:
  1062. # XXX no idea what this is for, but it breaks everything. jrb
  1063. #callinfo.setReturnParameter(
  1064. # parts[0].name,
  1065. # parts[0].element or parts[0].type,
  1066. # element_type = parts[0].element and 1 or 0
  1067. # )
  1068. #for part in parts[1:]:
  1069. for part in parts:
  1070. callinfo.addOutParameter(
  1071. part.name,
  1072. part.element or part.type,
  1073. element_type = part.element and 1 or 0
  1074. )
  1075. return callinfo