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.
 
 
 

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