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.
 
 
 

2930 lines
100 KiB

  1. # Copyright (c) 2003, The Regents of the University of California,
  2. # through Lawrence Berkeley National Laboratory (subject to receipt of
  3. # any required approvals from the U.S. Dept. of Energy). All rights
  4. # reserved.
  5. #
  6. # Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
  7. #
  8. # This software is subject to the provisions of the Zope Public License,
  9. # Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
  10. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
  11. # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  12. # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
  13. # FOR A PARTICULAR PURPOSE.
  14. ident = "$Id$"
  15. import types, weakref, urllib, sys
  16. from threading import RLock
  17. try:
  18. from xml.ns import XMLNS
  19. except ImportError:
  20. # ref:
  21. # http://cvs.sourceforge.net/viewcvs.py/pyxml/xml/xml/ns.py?view=markup
  22. class XMLNS:
  23. """XMLNS, Namespaces in XML
  24. XMLNS (14-Jan-1999) is a W3C Recommendation. It is specified in
  25. http://www.w3.org/TR/REC-xml-names
  26. BASE -- the basic namespace defined by the specification
  27. XML -- the namespace for XML 1.0
  28. HTML -- the namespace for HTML4.0
  29. """
  30. BASE = "http://www.w3.org/2000/xmlns/"
  31. XML = "http://www.w3.org/XML/1998/namespace"
  32. HTML = "http://www.w3.org/TR/REC-html40"
  33. from Utility import DOM, Collection
  34. from StringIO import StringIO
  35. try:
  36. from xml.dom.ext import SplitQName
  37. except ImportError, ex:
  38. def SplitQName(qname):
  39. l = qname.split(':')
  40. if len(l) == 1:
  41. l.insert(0, None)
  42. elif len(l) == 2:
  43. if l[0] == 'xmlns':
  44. l.reverse()
  45. else:
  46. return
  47. return tuple(l)
  48. def GetSchema(component):
  49. """convience function for finding the parent XMLSchema instance.
  50. """
  51. parent = component
  52. while not isinstance(parent, XMLSchema):
  53. parent = parent._parent()
  54. return parent
  55. class SchemaReader:
  56. """A SchemaReader creates XMLSchema objects from urls and xml data.
  57. """
  58. def __init__(self, domReader=None, base_url=None):
  59. """domReader -- class must implement DOMAdapterInterface
  60. base_url -- base url string
  61. """
  62. self.__base_url = base_url
  63. self.__readerClass = domReader
  64. if not self.__readerClass:
  65. self.__readerClass = DOMAdapter
  66. self._includes = {}
  67. self._imports = {}
  68. def __setImports(self, schema):
  69. """Add dictionary of imports to schema instance.
  70. schema -- XMLSchema instance
  71. """
  72. for ns,val in schema.imports.items():
  73. if self._imports.has_key(ns):
  74. schema.addImportSchema(self._imports[ns])
  75. def __setIncludes(self, schema):
  76. """Add dictionary of includes to schema instance.
  77. schema -- XMLSchema instance
  78. """
  79. for schemaLocation, val in schema.includes.items():
  80. if self._includes.has_key(schemaLocation):
  81. schema.addIncludeSchema(self._imports[schemaLocation])
  82. def addSchemaByLocation(self, location, schema):
  83. """provide reader with schema document for a location.
  84. """
  85. self._includes[location] = schema
  86. def addSchemaByNamespace(self, schema):
  87. """provide reader with schema document for a targetNamespace.
  88. """
  89. self._imports[schema.targetNamespace] = schema
  90. def loadFromNode(self, parent, element):
  91. """element -- DOM node or document
  92. parent -- WSDLAdapter instance
  93. """
  94. reader = self.__readerClass(element)
  95. schema = XMLSchema(parent)
  96. #HACK to keep a reference
  97. schema.wsdl = parent
  98. schema.setBaseUrl(self.__base_url)
  99. schema.load(reader)
  100. return schema
  101. def loadFromStream(self, file):
  102. """Return an XMLSchema instance loaded from a file object.
  103. file -- file object
  104. """
  105. reader = self.__readerClass()
  106. reader.loadDocument(file)
  107. schema = XMLSchema()
  108. schema.setBaseUrl(self.__base_url)
  109. schema.load(reader)
  110. self.__setIncludes(schema)
  111. self.__setImports(schema)
  112. return schema
  113. def loadFromString(self, data):
  114. """Return an XMLSchema instance loaded from an XML string.
  115. data -- XML string
  116. """
  117. return self.loadFromStream(StringIO(data))
  118. def loadFromURL(self, url):
  119. """Return an XMLSchema instance loaded from the given url.
  120. url -- URL to dereference
  121. """
  122. if not url.endswith('xsd'):
  123. raise SchemaError, 'unknown file type %s' %url
  124. reader = self.__readerClass()
  125. if self.__base_url:
  126. url = urllib.basejoin(self.__base_url,url)
  127. reader.loadFromURL(url)
  128. schema = XMLSchema()
  129. schema.setBaseUrl(self.__base_url)
  130. schema.load(reader)
  131. self.__setIncludes(schema)
  132. self.__setImports(schema)
  133. return schema
  134. def loadFromFile(self, filename):
  135. """Return an XMLSchema instance loaded from the given file.
  136. filename -- name of file to open
  137. """
  138. file = open(filename, 'rb')
  139. try: schema = self.loadFromStream(file)
  140. finally: file.close()
  141. return schema
  142. class SchemaError(Exception):
  143. pass
  144. ###########################
  145. # DOM Utility Adapters
  146. ##########################
  147. class DOMAdapterInterface:
  148. def hasattr(self, attr, ns=None):
  149. """return true if node has attribute
  150. attr -- attribute to check for
  151. ns -- namespace of attribute, by default None
  152. """
  153. raise NotImplementedError, 'adapter method not implemented'
  154. def getContentList(self, *contents):
  155. """returns an ordered list of child nodes
  156. *contents -- list of node names to return
  157. """
  158. raise NotImplementedError, 'adapter method not implemented'
  159. def setAttributeDictionary(self, attributes):
  160. """set attribute dictionary
  161. """
  162. raise NotImplementedError, 'adapter method not implemented'
  163. def getAttributeDictionary(self):
  164. """returns a dict of node's attributes
  165. """
  166. raise NotImplementedError, 'adapter method not implemented'
  167. def getNamespace(self, prefix):
  168. """returns namespace referenced by prefix.
  169. """
  170. raise NotImplementedError, 'adapter method not implemented'
  171. def getTagName(self):
  172. """returns tagName of node
  173. """
  174. raise NotImplementedError, 'adapter method not implemented'
  175. def getParentNode(self):
  176. """returns parent element in DOMAdapter or None
  177. """
  178. raise NotImplementedError, 'adapter method not implemented'
  179. def loadDocument(self, file):
  180. """load a Document from a file object
  181. file --
  182. """
  183. raise NotImplementedError, 'adapter method not implemented'
  184. def loadFromURL(self, url):
  185. """load a Document from an url
  186. url -- URL to dereference
  187. """
  188. raise NotImplementedError, 'adapter method not implemented'
  189. class DOMAdapter(DOMAdapterInterface):
  190. """Adapter for ZSI.Utility.DOM
  191. """
  192. def __init__(self, node=None):
  193. """Reset all instance variables.
  194. element -- DOM document, node, or None
  195. """
  196. if hasattr(node, 'documentElement'):
  197. self.__node = node.documentElement
  198. else:
  199. self.__node = node
  200. self.__attributes = None
  201. def hasattr(self, attr, ns=None):
  202. """attr -- attribute
  203. ns -- optional namespace, None means unprefixed attribute.
  204. """
  205. if not self.__attributes:
  206. self.setAttributeDictionary()
  207. if ns:
  208. return self.__attributes.get(ns,{}).has_key(attr)
  209. return self.__attributes.has_key(attr)
  210. def getContentList(self, *contents):
  211. nodes = []
  212. ELEMENT_NODE = self.__node.ELEMENT_NODE
  213. for child in DOM.getElements(self.__node, None):
  214. if child.nodeType == ELEMENT_NODE and\
  215. SplitQName(child.tagName)[1] in contents:
  216. nodes.append(child)
  217. return map(self.__class__, nodes)
  218. def setAttributeDictionary(self):
  219. self.__attributes = {}
  220. for v in self.__node._attrs.values():
  221. self.__attributes[v.nodeName] = v.nodeValue
  222. def getAttributeDictionary(self):
  223. if not self.__attributes:
  224. self.setAttributeDictionary()
  225. return self.__attributes
  226. def getTagName(self):
  227. return self.__node.tagName
  228. def getParentNode(self):
  229. if self.__node.parentNode.nodeType == self.__node.ELEMENT_NODE:
  230. return DOMAdapter(self.__node.parentNode)
  231. return None
  232. def getNamespace(self, prefix):
  233. """prefix -- deference namespace prefix in node's context.
  234. Ascends parent nodes until found.
  235. """
  236. namespace = None
  237. if prefix == 'xmlns':
  238. namespace = DOM.findDefaultNS(prefix, self.__node)
  239. else:
  240. try:
  241. namespace = DOM.findNamespaceURI(prefix, self.__node)
  242. except DOMException, ex:
  243. if prefix != 'xml':
  244. raise SchemaError, '%s namespace not declared for %s'\
  245. %(prefix, self.__node._get_tagName())
  246. namespace = XMLNS
  247. return namespace
  248. def loadDocument(self, file):
  249. self.__node = DOM.loadDocument(file)
  250. if hasattr(self.__node, 'documentElement'):
  251. self.__node = self.__node.documentElement
  252. def loadFromURL(self, url):
  253. self.__node = DOM.loadFromURL(url)
  254. if hasattr(self.__node, 'documentElement'):
  255. self.__node = self.__node.documentElement
  256. class XMLBase:
  257. """ These class variables are for string indentation.
  258. """
  259. __indent = 0
  260. __rlock = RLock()
  261. def __str__(self):
  262. XMLBase.__rlock.acquire()
  263. XMLBase.__indent += 1
  264. tmp = "<" + str(self.__class__) + '>\n'
  265. for k,v in self.__dict__.items():
  266. tmp += "%s* %s = %s\n" %(XMLBase.__indent*' ', k, v)
  267. XMLBase.__indent -= 1
  268. XMLBase.__rlock.release()
  269. return tmp
  270. ##########################################################
  271. # Schema Components
  272. #########################################################
  273. class XMLSchemaComponent(XMLBase):
  274. """
  275. class variables:
  276. required -- list of required attributes
  277. attributes -- dict of default attribute values, including None.
  278. Value can be a function for runtime dependencies.
  279. contents -- dict of namespace keyed content lists.
  280. 'xsd' content of xsd namespace.
  281. xmlns_key -- key for declared xmlns namespace.
  282. xmlns -- xmlns is special prefix for namespace dictionary
  283. xml -- special xml prefix for xml namespace.
  284. """
  285. required = []
  286. attributes = {}
  287. contents = {}
  288. xmlns_key = ''
  289. xmlns = 'xmlns'
  290. xml = 'xml'
  291. def __init__(self, parent=None):
  292. """parent -- parent instance
  293. instance variables:
  294. attributes -- dictionary of node's attributes
  295. """
  296. self.attributes = None
  297. self._parent = parent
  298. if self._parent:
  299. self._parent = weakref.ref(parent)
  300. if not self.__class__ == XMLSchemaComponent\
  301. and not (type(self.__class__.required) == type(XMLSchemaComponent.required)\
  302. and type(self.__class__.attributes) == type(XMLSchemaComponent.attributes)\
  303. and type(self.__class__.contents) == type(XMLSchemaComponent.contents)):
  304. raise RuntimeError, 'Bad type for a class variable in %s' %self.__class__
  305. def getTargetNamespace(self):
  306. """return targetNamespace
  307. """
  308. parent = self
  309. targetNamespace = 'targetNamespace'
  310. tns = self.attributes.get(targetNamespace)
  311. while not tns:
  312. parent = parent._parent()
  313. tns = parent.attributes.get(targetNamespace)
  314. return tns
  315. def getTypeDefinition(self, attribute):
  316. """attribute -- attribute with a QName value (eg. type).
  317. collection -- check types collection in parent Schema instance
  318. """
  319. return self.getQNameAttribute('types', attribute)
  320. def getElementDeclaration(self, attribute):
  321. """attribute -- attribute with a QName value (eg. element).
  322. collection -- check elements collection in parent Schema instance.
  323. """
  324. return self.getQNameAttribute('elements', attribute)
  325. def getQNameAttribute(self, collection, attribute):
  326. """returns object instance representing QName --> (namespace,name),
  327. or if does not exist return None.
  328. attribute -- an information item attribute, with a QName value.
  329. collection -- collection in parent Schema instance to search.
  330. """
  331. obj = None
  332. tdc = self.attributes.get(attribute)
  333. if tdc:
  334. parent = GetSchema(self)
  335. if parent.targetNamespace == tdc.getTargetNamespace():
  336. obj = getattr(parent, collection)[tdc.getName()]
  337. elif parent.imports.has_key(tdc.getTargetNamespace()):
  338. schema = parent.imports[tdc.getTargetNamespace()].getSchema()
  339. obj = getattr(schema, collection)[tdc.getName()]
  340. return obj
  341. def getXMLNS(self, prefix=None):
  342. """deference prefix or by default xmlns, returns namespace.
  343. """
  344. parent = self
  345. ns = self.attributes[XMLSchemaComponent.xmlns].get(prefix or\
  346. XMLSchemaComponent.xmlns_key)
  347. while not ns:
  348. parent = parent._parent()
  349. ns = parent.attributes[XMLSchemaComponent.xmlns].get(prefix or\
  350. XMLSchemaComponent.xmlns_key)
  351. if not ns and isinstance(parent, WSDLToolsAdapter):
  352. raise SchemaError, 'unknown prefix %s' %prefix
  353. return ns
  354. def getAttribute(self, attribute):
  355. """return requested attribute or None
  356. """
  357. return self.attributes.get(attribute)
  358. def setAttributes(self, node):
  359. """Sets up attribute dictionary, checks for required attributes and
  360. sets default attribute values. attr is for default attribute values
  361. determined at runtime.
  362. structure of attributes dictionary
  363. ['xmlns'][xmlns_key] -- xmlns namespace
  364. ['xmlns'][prefix] -- declared namespace prefix
  365. [namespace][prefix] -- attributes declared in a namespace
  366. [attribute] -- attributes w/o prefix, default namespaces do
  367. not directly apply to attributes, ie Name can't collide
  368. with QName.
  369. """
  370. self.attributes = {XMLSchemaComponent.xmlns:{}}
  371. for k,v in node.getAttributeDictionary().items():
  372. prefix,value = SplitQName(k)
  373. if value == XMLSchemaComponent.xmlns:
  374. self.attributes[value][prefix or XMLSchemaComponent.xmlns_key] = v
  375. elif prefix:
  376. ns = node.getNamespace(prefix)
  377. if not ns:
  378. raise SchemaError, 'no namespace for attribute prefix %s'\
  379. %prefix
  380. if not self.attributes.has_key(ns):
  381. self.attributes[ns] = {}
  382. elif self.attributes[ns].has_key(value):
  383. raise SchemaError, 'attribute %s declared multiple times in %s'\
  384. %(value, ns)
  385. self.attributes[ns][value] = v
  386. elif not self.attributes.has_key(value):
  387. self.attributes[value] = v
  388. else:
  389. raise SchemaError, 'attribute %s declared multiple times' %value
  390. self.__checkAttributes()
  391. self.__setAttributeDefaults()
  392. #set QNames
  393. for k in ['type', 'element', 'base', 'ref', 'substitutionGroup', 'itemType']:
  394. if self.attributes.has_key(k):
  395. prefix, value = SplitQName(self.attributes.get(k))
  396. self.attributes[k] = \
  397. TypeDescriptionComponent((self.getXMLNS(prefix), value))
  398. #Union, memberTypes is a whitespace separated list of QNames
  399. for k in ['memberTypes']:
  400. if self.attributes.has_key(k):
  401. qnames = self.attributes[k]
  402. self.attributes[k] = []
  403. for qname in qnames.split():
  404. prefix, value = SplitQName(qname)
  405. self.attributes['memberTypes'].append(\
  406. TypeDescriptionComponent(\
  407. (self.getXMLNS(prefix), value)))
  408. def getContents(self, node):
  409. """retrieve xsd contents
  410. """
  411. return node.getContentList(*self.__class__.contents['xsd'])
  412. def __setAttributeDefaults(self):
  413. """Looks for default values for unset attributes. If
  414. class variable representing attribute is None, then
  415. it must be defined as an instance variable.
  416. """
  417. for k,v in self.__class__.attributes.items():
  418. if v and not self.attributes.has_key(k):
  419. if isinstance(v, types.FunctionType):
  420. self.attributes[k] = v(self)
  421. else:
  422. self.attributes[k] = v
  423. def __checkAttributes(self):
  424. """Checks that required attributes have been defined,
  425. attributes w/default cannot be required. Checks
  426. all defined attributes are legal, attribute
  427. references are not subject to this test.
  428. """
  429. for a in self.__class__.required:
  430. if not self.attributes.has_key(a):
  431. raise SchemaError,\
  432. 'class instance %s, missing required attribute %s'\
  433. %(self.__class__, a)
  434. for a in self.attributes.keys():
  435. if (a != XMLSchemaComponent.xmlns) and\
  436. (a not in self.__class__.attributes.keys()) and not\
  437. (self.isAttribute() and self.isReference()):
  438. raise SchemaError, '%s, unknown attribute' %a
  439. class WSDLToolsAdapter(XMLSchemaComponent):
  440. """WSDL Adapter to grab the attributes from the wsdl document node.
  441. """
  442. attributes = {'name':None, 'targetNamespace':None}
  443. def __init__(self, wsdl):
  444. #XMLSchemaComponent.__init__(self, None)
  445. XMLSchemaComponent.__init__(self, parent=wsdl)
  446. self.setAttributes(DOMAdapter(wsdl.document))
  447. def getImportSchemas(self):
  448. """returns WSDLTools.WSDL types Collection
  449. """
  450. return self._parent().types
  451. """Marker Interface: can determine something about an instances properties by using
  452. the provided convenience functions.
  453. """
  454. class DefinitionMarker:
  455. """marker for definitions
  456. """
  457. pass
  458. class DeclarationMarker:
  459. """marker for declarations
  460. """
  461. pass
  462. class AttributeMarker:
  463. """marker for attributes
  464. """
  465. pass
  466. class AttributeGroupMarker:
  467. """marker for attribute groups
  468. """
  469. pass
  470. class WildCardMarker:
  471. """marker for wildcards
  472. """
  473. pass
  474. class ElementMarker:
  475. """marker for wildcards
  476. """
  477. pass
  478. class ReferenceMarker:
  479. """marker for references
  480. """
  481. pass
  482. class ModelGroupMarker:
  483. """marker for model groups
  484. """
  485. pass
  486. class ExtensionMarker:
  487. """marker for extensions
  488. """
  489. pass
  490. class RestrictionMarker:
  491. """marker for restrictions
  492. """
  493. facets = ['enumeration', 'length', 'maxExclusive', 'maxInclusive',\
  494. 'maxLength', 'minExclusive', 'minInclusive', 'minLength',\
  495. 'pattern', 'fractionDigits', 'totalDigits', 'whiteSpace']
  496. class SimpleMarker:
  497. """marker for simple type information
  498. """
  499. pass
  500. class ComplexMarker:
  501. """marker for complex type information
  502. """
  503. pass
  504. class MarkerInterface:
  505. def isDefinition(self):
  506. return isinstance(self, DefinitionMarker)
  507. def isDeclaration(self):
  508. return isinstance(self, DeclarationMarker)
  509. def isAttribute(self):
  510. return isinstance(self, AttributeMarker)
  511. def isAttributeGroup(self):
  512. return isinstance(self, AttributeGroupMarker)
  513. def isElement(self):
  514. return isinstance(self, ElementMarker)
  515. def isReference(self):
  516. return isinstance(self, ReferenceMarker)
  517. def isWildCard(self):
  518. return isinstance(self, WildCardMarker)
  519. def isModelGroup(self):
  520. return isinstance(self, ModelGroupMarker)
  521. def isExtension(self):
  522. return isinstance(self, ExtensionMarker)
  523. def isRestriction(self):
  524. return isinstance(self, RestrictionMarker)
  525. def isSimple(self):
  526. return isinstance(self, SimpleMarker)
  527. def isComplex(self):
  528. return isinstance(self, ComplexMarker)
  529. class Notation(XMLSchemaComponent):
  530. """<notation>
  531. parent:
  532. schema
  533. attributes:
  534. id -- ID
  535. name -- NCName, Required
  536. public -- token, Required
  537. system -- anyURI
  538. contents:
  539. annotation?
  540. """
  541. required = ['name', 'public']
  542. attributes = {'id':None, 'name':None, 'public':None, 'system':None}
  543. contents = {'xsd':('annotation')}
  544. def __init__(self, parent):
  545. XMLSchemaComponent.__init__(self, parent)
  546. self.annotation = None
  547. def fromDom(self, node):
  548. self.setAttributes(node)
  549. contents = self.getContents(node)
  550. for i in contents:
  551. component = SplitQName(i.getTagName())[1]
  552. if component == 'annotation' and not self.annotation:
  553. self.annotation = Annotation(self)
  554. self.annotation.fromDom(i)
  555. else:
  556. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  557. class Annotation(XMLSchemaComponent):
  558. """<annotation>
  559. parent:
  560. all,any,anyAttribute,attribute,attributeGroup,choice,complexContent,
  561. complexType,element,extension,field,group,import,include,key,keyref,
  562. list,notation,redefine,restriction,schema,selector,simpleContent,
  563. simpleType,union,unique
  564. attributes:
  565. id -- ID
  566. contents:
  567. (documentation | appinfo)*
  568. """
  569. attributes = {'id':None}
  570. contents = {'xsd':('documentation', 'appinfo')}
  571. def __init__(self, parent):
  572. XMLSchemaComponent.__init__(self, parent)
  573. self.content = None
  574. def fromDom(self, node):
  575. self.setAttributes(node)
  576. contents = self.getContents(node)
  577. content = []
  578. for i in contents:
  579. component = SplitQName(i.getTagName())[1]
  580. if component == 'documentation':
  581. #print_debug('class %s, documentation skipped' %self.__class__, 5)
  582. continue
  583. elif component == 'appinfo':
  584. #print_debug('class %s, appinfo skipped' %self.__class__, 5)
  585. continue
  586. else:
  587. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  588. self.content = tuple(content)
  589. class Documentation(XMLSchemaComponent):
  590. """<documentation>
  591. parent:
  592. annotation
  593. attributes:
  594. source, anyURI
  595. xml:lang, language
  596. contents:
  597. mixed, any
  598. """
  599. attributes = {'source':None, 'xml:lang':None}
  600. contents = {'xsd':('mixed', 'any')}
  601. def __init__(self, parent):
  602. XMLSchemaComponent.__init__(self, parent)
  603. self.content = None
  604. def fromDom(self, node):
  605. self.setAttributes(node)
  606. contents = self.getContents(node)
  607. content = []
  608. for i in contents:
  609. component = SplitQName(i.getTagName())[1]
  610. if component == 'mixed':
  611. #print_debug('class %s, mixed skipped' %self.__class__, 5)
  612. continue
  613. elif component == 'any':
  614. #print_debug('class %s, any skipped' %self.__class__, 5)
  615. continue
  616. else:
  617. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  618. self.content = tuple(content)
  619. class Appinfo(XMLSchemaComponent):
  620. """<appinfo>
  621. parent:
  622. annotation
  623. attributes:
  624. source, anyURI
  625. contents:
  626. mixed, any
  627. """
  628. attributes = {'source':None, 'anyURI':None}
  629. contents = {'xsd':('mixed', 'any')}
  630. def __init__(self, parent):
  631. XMLSchemaComponent.__init__(self, parent)
  632. self.content = None
  633. def fromDom(self, node):
  634. self.setAttributes(node)
  635. contents = self.getContents(node)
  636. content = []
  637. for i in contents:
  638. component = SplitQName(i.getTagName())[1]
  639. if component == 'mixed':
  640. #print_debug('class %s, mixed skipped' %self.__class__, 5)
  641. continue
  642. elif component == 'any':
  643. #print_debug('class %s, any skipped' %self.__class__, 5)
  644. continue
  645. else:
  646. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  647. self.content = tuple(content)
  648. class XMLSchemaFake:
  649. # This is temporary, for the benefit of WSDL until the real thing works.
  650. def __init__(self, element):
  651. self.targetNamespace = DOM.getAttr(element, 'targetNamespace')
  652. self.element = element
  653. class XMLSchema(XMLSchemaComponent):
  654. """A schema is a collection of schema components derived from one
  655. or more schema documents, that is, one or more <schema> element
  656. information items. It represents the abstract notion of a schema
  657. rather than a single schema document (or other representation).
  658. <schema>
  659. parent:
  660. ROOT
  661. attributes:
  662. id -- ID
  663. version -- token
  664. xml:lang -- language
  665. targetNamespace -- anyURI
  666. attributeFormDefault -- 'qualified' | 'unqualified', 'unqualified'
  667. elementFormDefault -- 'qualified' | 'unqualified', 'unqualified'
  668. blockDefault -- '#all' | list of
  669. ('substitution | 'extension' | 'restriction')
  670. finalDefault -- '#all' | list of
  671. ('extension' | 'restriction' | 'list' | 'union')
  672. contents:
  673. ((include | import | redefine | annotation)*,
  674. (attribute, attributeGroup, complexType, element, group,
  675. notation, simpleType)*, annotation*)*
  676. attributes -- schema attributes
  677. imports -- import statements
  678. includes -- include statements
  679. redefines --
  680. types -- global simpleType, complexType definitions
  681. elements -- global element declarations
  682. attr_decl -- global attribute declarations
  683. attr_groups -- attribute Groups
  684. model_groups -- model Groups
  685. notations -- global notations
  686. """
  687. attributes = {'id':None,
  688. 'version':None,
  689. 'xml:lang':None,
  690. 'targetNamespace':None,
  691. 'attributeFormDefault':'unqualified',
  692. 'elementFormDefault':'unqualified',
  693. 'blockDefault':None,
  694. 'finalDefault':None}
  695. contents = {'xsd':('include', 'import', 'redefine', 'annotation', 'attribute',\
  696. 'attributeGroup', 'complexType', 'element', 'group',\
  697. 'notation', 'simpleType', 'annotation')}
  698. empty_namespace = ''
  699. def __init__(self, parent=None):
  700. """parent --
  701. instance variables:
  702. targetNamespace -- schema's declared targetNamespace, or empty string.
  703. _imported_schemas -- namespace keyed dict of schema dependencies, if
  704. a schema is provided instance will not resolve import statement.
  705. _included_schemas -- schemaLocation keyed dict of component schemas,
  706. if schema is provided instance will not resolve include statement.
  707. _base_url -- needed for relative URLs support, only works with URLs
  708. relative to initial document.
  709. includes -- collection of include statements
  710. imports -- collection of import statements
  711. elements -- collection of global element declarations
  712. types -- collection of global type definitions
  713. attr_decl -- collection of global attribute declarations
  714. attr_groups -- collection of global attribute group definitions
  715. model_groups -- collection of model group definitions
  716. notations -- collection of notations
  717. """
  718. self.targetNamespace = None
  719. XMLSchemaComponent.__init__(self, parent)
  720. f = lambda k: k.attributes['name']
  721. ns = lambda k: k.attributes['namespace']
  722. sl = lambda k: k.attributes['schemaLocation']
  723. self.includes = Collection(self, key=sl)
  724. self.imports = Collection(self, key=ns)
  725. self.elements = Collection(self, key=f)
  726. self.types = Collection(self, key=f)
  727. self.attr_decl = Collection(self, key=f)
  728. self.attr_groups = Collection(self, key=f)
  729. self.model_groups = Collection(self, key=f)
  730. self.notations = Collection(self, key=f)
  731. self._imported_schemas = {}
  732. self._included_schemas = {}
  733. self._base_url = None
  734. def addImportSchema(self, schema):
  735. """for resolving import statements in Schema instance
  736. schema -- schema instance
  737. _imported_schemas
  738. """
  739. if not isinstance(schema, Schema):
  740. raise TypeError, 'expecting a Schema instance'
  741. if schema.targetNamespace != self.targetNamespace:
  742. self._imported_schemas[schema.targetNamespace]
  743. else:
  744. raise SchemaError, 'import schema bad targetNamespace'
  745. def addIncludeSchema(self, schemaLocation, schema):
  746. """for resolving include statements in Schema instance
  747. schemaLocation -- schema location
  748. schema -- schema instance
  749. _included_schemas
  750. """
  751. if not isinstance(schema, Schema):
  752. raise TypeError, 'expecting a Schema instance'
  753. if not schema.targetNamespace or\
  754. schema.targetNamespace == self.targetNamespace:
  755. self._included_schemas[schemaLocation] = schema
  756. else:
  757. raise SchemaError, 'include schema bad targetNamespace'
  758. def setImportSchemas(self, schema_dict):
  759. """set the import schema dictionary, which is used to
  760. reference depedent schemas.
  761. """
  762. self._imported_schemas = schema_dict
  763. def getImportSchemas(self):
  764. """get the import schema dictionary, which is used to
  765. reference depedent schemas.
  766. """
  767. return self._imported_schemas
  768. def getSchemaNamespacesToImport(self):
  769. """returns tuple of namespaces the schema instance has declared
  770. itself to be depedent upon.
  771. """
  772. return tuple(self.includes.keys())
  773. def setIncludeSchemas(self, schema_dict):
  774. """set the include schema dictionary, which is keyed with
  775. schemaLocation (uri).
  776. This is a means of providing
  777. schemas to the current schema for content inclusion.
  778. """
  779. self._included_schemas = schema_dict
  780. def getIncludeSchemas(self):
  781. """get the include schema dictionary, which is keyed with
  782. schemaLocation (uri).
  783. """
  784. return self._included_schemas
  785. def getBaseUrl(self):
  786. """get base url, used for normalizing all relative uri's
  787. """
  788. return self._base_url
  789. def setBaseUrl(self, url):
  790. """set base url, used for normalizing all relative uri's
  791. """
  792. self._base_url = url
  793. def getElementFormDefault(self):
  794. """return elementFormDefault attribute
  795. """
  796. return self.attributes.get('elementFormDefault')
  797. def getAttributeFormDefault(self):
  798. """return attributeFormDefault attribute
  799. """
  800. return self.attributes.get('attributeFormDefault')
  801. def getBlockDefault(self):
  802. """return blockDefault attribute
  803. """
  804. return self.attributes.get('blockDefault')
  805. def getFinalDefault(self):
  806. """return finalDefault attribute
  807. """
  808. return self.attributes.get('finalDefault')
  809. def load(self, node):
  810. pnode = node.getParentNode()
  811. if pnode:
  812. pname = SplitQName(pnode.getTagName())[1]
  813. if pname == 'types':
  814. attributes = {}
  815. self.setAttributes(pnode)
  816. attributes.update(self.attributes)
  817. self.setAttributes(node)
  818. for k,v in attributes['xmlns'].items():
  819. if not self.attributes['xmlns'].has_key(k):
  820. self.attributes['xmlns'][k] = v
  821. else:
  822. self.setAttributes(node)
  823. else:
  824. self.setAttributes(node)
  825. self.targetNamespace = self.getTargetNamespace()
  826. contents = self.getContents(node)
  827. indx = 0
  828. num = len(contents)
  829. while indx < num:
  830. while indx < num:
  831. node = contents[indx]
  832. component = SplitQName(node.getTagName())[1]
  833. if component == 'include':
  834. tp = self.__class__.Include(self)
  835. tp.fromDom(node)
  836. self.includes[tp.attributes['schemaLocation']] = tp
  837. schema = tp.getSchema()
  838. if schema.targetNamespace and \
  839. schema.targetNamespace != self.targetNamespace:
  840. raise SchemaError, 'included schema bad targetNamespace'
  841. for collection in ['imports','elements','types',\
  842. 'attr_decl','attr_groups','model_groups','notations']:
  843. for k,v in getattr(schema,collection).items():
  844. if not getattr(self,collection).has_key(k):
  845. v._parent = weakref.ref(self)
  846. getattr(self,collection)[k] = v
  847. elif component == 'import':
  848. tp = self.__class__.Import(self)
  849. tp.fromDom(node)
  850. if tp.attributes['namespace']:
  851. if tp.attributes['namespace'] == self.targetNamespace:
  852. raise SchemaError,\
  853. 'import and schema have same targetNamespace'
  854. self.imports[tp.attributes['namespace']] = tp
  855. else:
  856. self.imports[self.__class__.empty_namespace] = tp
  857. elif component == 'redefine':
  858. #print_debug('class %s, redefine skipped' %self.__class__, 5)
  859. pass
  860. elif component == 'annotation':
  861. #print_debug('class %s, annotation skipped' %self.__class__, 5)
  862. pass
  863. else:
  864. break
  865. indx += 1
  866. # (attribute, attributeGroup, complexType, element, group,
  867. # notation, simpleType)*, annotation*)*
  868. while indx < num:
  869. node = contents[indx]
  870. component = SplitQName(node.getTagName())[1]
  871. if component == 'attribute':
  872. tp = AttributeDeclaration(self)
  873. tp.fromDom(node)
  874. self.attr_decl[tp.getAttribute('name')] = tp
  875. elif component == 'attributeGroup':
  876. tp = AttributeGroupDefinition(self)
  877. tp.fromDom(node)
  878. self.attr_groups[tp.getAttribute('name')] = tp
  879. elif component == 'complexType':
  880. tp = ComplexType(self)
  881. tp.fromDom(node)
  882. self.types[tp.getAttribute('name')] = tp
  883. elif component == 'element':
  884. tp = ElementDeclaration(self)
  885. tp.fromDom(node)
  886. self.elements[tp.getAttribute('name')] = tp
  887. elif component == 'group':
  888. tp = ModelGroupDefinition(self)
  889. tp.fromDom(node)
  890. self.model_groups[tp.getAttribute('name')] = tp
  891. elif component == 'notation':
  892. tp = Notation(self)
  893. tp.fromDom(node)
  894. self.notations[tp.getAttribute('name')] = tp
  895. elif component == 'simpleType':
  896. tp = SimpleType(self)
  897. tp.fromDom(node)
  898. self.types[tp.getAttribute('name')] = tp
  899. else:
  900. break
  901. indx += 1
  902. while indx < num:
  903. node = contents[indx]
  904. component = SplitQName(node.getTagName())[1]
  905. if component == 'annotation':
  906. #print_debug('class %s, annotation 2 skipped' %self.__class__, 5)
  907. pass
  908. else:
  909. break
  910. indx += 1
  911. class Import(XMLSchemaComponent, MarkerInterface):
  912. """<import>
  913. parent:
  914. schema
  915. attributes:
  916. id -- ID
  917. namespace -- anyURI
  918. schemaLocation -- anyURI
  919. contents:
  920. annotation?
  921. """
  922. attributes = {'id':None,
  923. 'namespace':None,
  924. 'schemaLocation':None}
  925. contents = {'xsd':['annotation']}
  926. def __init__(self, parent):
  927. XMLSchemaComponent.__init__(self, parent)
  928. self.annotation = None
  929. self._schema = None
  930. def fromDom(self, node):
  931. self.setAttributes(node)
  932. contents = self.getContents(node)
  933. if self.attributes['namespace'] == self._parent().attributes['targetNamespace']:
  934. raise SchemaError, 'namespace of schema and import match'
  935. for i in contents:
  936. component = SplitQName(i.getTagName())[1]
  937. if component == 'annotation' and not self.annotation:
  938. self.annotation = Annotation(self)
  939. self.annotation.fromDom(i)
  940. else:
  941. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  942. def getSchema(self):
  943. """if schema is not defined, first look for a Schema class instance
  944. in parent Schema. Else if not defined resolve schemaLocation
  945. and create a new Schema class instance, and keep a hard reference.
  946. """
  947. if not self._schema:
  948. ns = self.attributes['namespace']
  949. schema = self._parent().getImportSchemas().get(ns)
  950. if not schema and self._parent()._parent:
  951. schema = self._parent()._parent().getImportSchemas().get(ns)
  952. if not schema:
  953. if not self.attributes.has_key('schemaLocation'):
  954. raise SchemaError, 'namespace(%s) is unknown' %ns
  955. base_url = self._parent().getBaseUrl()
  956. reader = SchemaReader(base_url=base_url)
  957. reader._imports = self._parent().getImportSchemas()
  958. reader._includes = self._parent().getIncludeSchemas()
  959. self._schema = reader.loadFromURL(url)
  960. return self._schema or schema
  961. class Include(XMLSchemaComponent, MarkerInterface):
  962. """<include schemaLocation>
  963. parent:
  964. schema
  965. attributes:
  966. id -- ID
  967. schemaLocation -- anyURI, required
  968. contents:
  969. annotation?
  970. """
  971. required = ['schemaLocation']
  972. attributes = {'id':None,
  973. 'schemaLocation':None}
  974. contents = {'xsd':['annotation']}
  975. def __init__(self, parent):
  976. XMLSchemaComponent.__init__(self, parent)
  977. self.annotation = None
  978. self._schema = None
  979. def fromDom(self, node):
  980. self.setAttributes(node)
  981. contents = self.getContents(node)
  982. for i in contents:
  983. component = SplitQName(i.getTagName())[1]
  984. if component == 'annotation' and not self.annotation:
  985. self.annotation = Annotation(self)
  986. self.annotation.fromDom(i)
  987. else:
  988. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  989. def getSchema(self):
  990. """if schema is not defined, first look for a Schema class instance
  991. in parent Schema. Else if not defined resolve schemaLocation
  992. and create a new Schema class instance.
  993. """
  994. if not self._schema:
  995. #schema = self._parent()._parent()
  996. schema = self._parent()
  997. #self._schema = schema.getIncludeSchemas(\
  998. # self.attributes['schemaLocation'])
  999. self._schema = schema.getIncludeSchemas().get(\
  1000. self.attributes['schemaLocation']
  1001. )
  1002. if not self._schema:
  1003. url = self.attributes['schemaLocation']
  1004. reader = SchemaReader(base_url=schema.getBaseUrl())
  1005. reader._imports = schema.getImportSchemas()
  1006. reader._includes = schema.getIncludeSchemas()
  1007. self._schema = reader.loadFromURL(url)
  1008. return self._schema
  1009. class AttributeDeclaration(XMLSchemaComponent,\
  1010. MarkerInterface,\
  1011. AttributeMarker,\
  1012. DeclarationMarker):
  1013. """<attribute name>
  1014. parent:
  1015. schema
  1016. attributes:
  1017. id -- ID
  1018. name -- NCName, required
  1019. type -- QName
  1020. default -- string
  1021. fixed -- string
  1022. contents:
  1023. annotation?, simpleType?
  1024. """
  1025. required = ['name']
  1026. attributes = {'id':None,
  1027. 'name':None,
  1028. 'type':None,
  1029. 'default':None,
  1030. 'fixed':None}
  1031. contents = {'xsd':['annotation','simpleType']}
  1032. def __init__(self, parent):
  1033. XMLSchemaComponent.__init__(self, parent)
  1034. self.annotation = None
  1035. self.content = None
  1036. def fromDom(self, node):
  1037. """ No list or union support
  1038. """
  1039. self.setAttributes(node)
  1040. contents = self.getContents(node)
  1041. for i in contents:
  1042. component = SplitQName(i.getTagName())[1]
  1043. if component == 'annotation' and not self.annotation:
  1044. self.annotation = Annotation(self)
  1045. self.annotation.fromDom(i)
  1046. elif component == 'simpleType':
  1047. self.content = AnonymousSimpleType(self)
  1048. self.content.fromDom(i)
  1049. else:
  1050. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  1051. class LocalAttributeDeclaration(AttributeDeclaration,\
  1052. MarkerInterface,\
  1053. AttributeMarker,\
  1054. DeclarationMarker):
  1055. """<attribute name>
  1056. parent:
  1057. complexType, restriction, extension, attributeGroup
  1058. attributes:
  1059. id -- ID
  1060. name -- NCName, required
  1061. type -- QName
  1062. form -- ('qualified' | 'unqualified'), schema.attributeFormDefault
  1063. use -- ('optional' | 'prohibited' | 'required'), optional
  1064. default -- string
  1065. fixed -- string
  1066. contents:
  1067. annotation?, simpleType?
  1068. """
  1069. required = ['name']
  1070. attributes = {'id':None,
  1071. 'name':None,
  1072. 'type':None,
  1073. 'form':lambda self: GetSchema(self).getAttributeFormDefault(),
  1074. 'use':'optional',
  1075. 'default':None,
  1076. 'fixed':None}
  1077. contents = {'xsd':['annotation','simpleType']}
  1078. def __init__(self, parent):
  1079. AttributeDeclaration.__init__(self, parent)
  1080. self.annotation = None
  1081. self.content = None
  1082. def fromDom(self, node):
  1083. self.setAttributes(node)
  1084. contents = self.getContents(node)
  1085. for i in contents:
  1086. component = SplitQName(i.getTagName())[1]
  1087. if component == 'annotation' and not self.annotation:
  1088. self.annotation = Annotation(self)
  1089. self.annotation.fromDom(i)
  1090. elif component == 'simpleType':
  1091. self.content = AnonymousSimpleType(self)
  1092. self.content.fromDom(i)
  1093. else:
  1094. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  1095. class AttributeWildCard(XMLSchemaComponent,\
  1096. MarkerInterface,\
  1097. AttributeMarker,\
  1098. DeclarationMarker,\
  1099. WildCardMarker):
  1100. """<anyAttribute>
  1101. parents:
  1102. complexType, restriction, extension, attributeGroup
  1103. attributes:
  1104. id -- ID
  1105. namespace -- '##any' | '##other' |
  1106. (anyURI* | '##targetNamespace' | '##local'), ##any
  1107. processContents -- 'lax' | 'skip' | 'strict', strict
  1108. contents:
  1109. annotation?
  1110. """
  1111. attributes = {'id':None,
  1112. 'namespace':'##any',
  1113. 'processContents':'strict'}
  1114. contents = {'xsd':['annotation']}
  1115. def __init__(self, parent):
  1116. XMLSchemaComponent.__init__(self, parent)
  1117. self.annotation = None
  1118. def fromDom(self, node):
  1119. self.setAttributes(node)
  1120. contents = self.getContents(node)
  1121. for i in contents:
  1122. component = SplitQName(i.getTagName())[1]
  1123. if component == 'annotation' and not self.annotation:
  1124. self.annotation = Annotation(self)
  1125. self.annotation.fromDom(i)
  1126. else:
  1127. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  1128. class AttributeReference(XMLSchemaComponent,\
  1129. MarkerInterface,\
  1130. AttributeMarker,\
  1131. ReferenceMarker):
  1132. """<attribute ref>
  1133. parents:
  1134. complexType, restriction, extension, attributeGroup
  1135. attributes:
  1136. id -- ID
  1137. ref -- QName, required
  1138. use -- ('optional' | 'prohibited' | 'required'), optional
  1139. default -- string
  1140. fixed -- string
  1141. contents:
  1142. annotation?
  1143. """
  1144. required = ['ref']
  1145. attributes = {'id':None,
  1146. 'ref':None,
  1147. 'use':'optional',
  1148. 'default':None,
  1149. 'fixed':None}
  1150. contents = {'xsd':['annotation']}
  1151. def __init__(self, parent):
  1152. XMLSchemaComponent.__init__(self, parent)
  1153. self.annotation = None
  1154. def fromDom(self, node):
  1155. self.setAttributes(node)
  1156. contents = self.getContents(node)
  1157. for i in contents:
  1158. component = SplitQName(i.getTagName())[1]
  1159. if component == 'annotation' and not self.annotation:
  1160. self.annotation = Annotation(self)
  1161. self.annotation.fromDom(i)
  1162. else:
  1163. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  1164. class AttributeGroupDefinition(XMLSchemaComponent,\
  1165. MarkerInterface,\
  1166. AttributeGroupMarker,\
  1167. DefinitionMarker):
  1168. """<attributeGroup name>
  1169. parents:
  1170. schema, redefine
  1171. attributes:
  1172. id -- ID
  1173. name -- NCName, required
  1174. contents:
  1175. annotation?, (attribute | attributeGroup)*, anyAttribute?
  1176. """
  1177. required = ['name']
  1178. attributes = {'id':None,
  1179. 'name':None}
  1180. contents = {'xsd':['annotation']}
  1181. def __init__(self, parent):
  1182. XMLSchemaComponent.__init__(self, parent)
  1183. self.annotation = None
  1184. self.attr_content = None
  1185. def fromDom(self, node):
  1186. self.setAttributes(node)
  1187. contents = self.getContents(node)
  1188. content = []
  1189. for indx in range(len(contents)):
  1190. component = SplitQName(i.getTagName())[1]
  1191. if (component == 'annotation') and (not indx):
  1192. self.annotation = Annotation(self)
  1193. self.annotation.fromDom(contents[indx])
  1194. elif (component == 'attribute'):
  1195. if contents[indx].hasattr('name'):
  1196. content.append(AttributeDeclaration())
  1197. elif contents[indx].hasattr('ref'):
  1198. content.append(AttributeReference())
  1199. else:
  1200. raise SchemaError, 'Unknown attribute type'
  1201. content[-1].fromDom(contents[indx])
  1202. elif (component == 'attributeGroup'):
  1203. content.append(AttributeGroupReference())
  1204. content[-1].fromDom(contents[indx])
  1205. elif (component == 'anyAttribute') and (len(contents) == x+1):
  1206. content.append(AttributeWildCard())
  1207. content[-1].fromDom(contents[indx])
  1208. else:
  1209. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  1210. self.attr_content = tuple(content)
  1211. class AttributeGroupReference(XMLSchemaComponent,\
  1212. MarkerInterface,\
  1213. AttributeGroupMarker,\
  1214. ReferenceMarker):
  1215. """<attributeGroup ref>
  1216. parents:
  1217. complexType, restriction, extension, attributeGroup
  1218. attributes:
  1219. id -- ID
  1220. ref -- QName, required
  1221. contents:
  1222. annotation?
  1223. """
  1224. required = ['ref']
  1225. attributes = {'id':None,
  1226. 'ref':None}
  1227. contents = {'xsd':['annotation']}
  1228. def __init__(self, parent):
  1229. XMLSchemaComponent.__init__(self, parent)
  1230. self.annotation = None
  1231. def fromDom(self, node):
  1232. self.setAttributes(node)
  1233. contents = self.getContents(node)
  1234. for i in contents:
  1235. component = SplitQName(i.getTagName())[1]
  1236. if component == 'annotation' and not self.annotation:
  1237. self.annotation = Annotation(self)
  1238. self.annotation.fromDom(i)
  1239. else:
  1240. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  1241. ######################################################
  1242. # Elements
  1243. #####################################################
  1244. class IdentityConstrants(XMLSchemaComponent):
  1245. """Allow one to uniquely identify nodes in a document and ensure the
  1246. integrity of references between them.
  1247. attributes -- dictionary of attributes
  1248. selector -- XPath to selected nodes
  1249. fields -- list of XPath to key field
  1250. """
  1251. def __init__(self, parent):
  1252. XMLSchemaComponent.__init__(self, parent)
  1253. self.selector = None
  1254. self.fields = None
  1255. self.annotation = None
  1256. def fromDom(self, node):
  1257. self.setAttributes(node)
  1258. contents = self.getContents(node)
  1259. fields = []
  1260. for i in contents:
  1261. component = SplitQName(i.getTagName())[1]
  1262. if component in self.__class__.contents['xsd']:
  1263. if component == 'annotation' and not self.annotation:
  1264. self.annotation = Annotation(self)
  1265. self.annotation.fromDom(i)
  1266. elif component == 'selector':
  1267. self.selector = self.Selector(self)
  1268. self.selector.fromDom(i)
  1269. continue
  1270. elif component == 'field':
  1271. fields.append(self.Field(self))
  1272. fields[-1].fromDom(i)
  1273. continue
  1274. else:
  1275. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  1276. else:
  1277. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  1278. self.fields = tuple(fields)
  1279. class Constraint(XMLSchemaComponent):
  1280. def __init__(self, parent):
  1281. XMLSchemaComponent.__init__(self, parent)
  1282. self.annotation = None
  1283. def fromDom(self, node):
  1284. self.setAttributes(node)
  1285. contents = self.getContents(node)
  1286. for i in contents:
  1287. component = SplitQName(i.getTagName())[1]
  1288. if component in self.__class__.contents['xsd']:
  1289. if component == 'annotation' and not self.annotation:
  1290. self.annotation = Annotation(self)
  1291. self.annotation.fromDom(i)
  1292. else:
  1293. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  1294. else:
  1295. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  1296. class Selector(Constraint):
  1297. """<selector xpath>
  1298. parent:
  1299. unique, key, keyref
  1300. attributes:
  1301. id -- ID
  1302. xpath -- XPath subset, required
  1303. contents:
  1304. annotation?
  1305. """
  1306. required = ['xpath']
  1307. attributes = {'id':None,
  1308. 'xpath':None}
  1309. contents = {'xsd':['annotation']}
  1310. class Field(Constraint):
  1311. """<field xpath>
  1312. parent:
  1313. unique, key, keyref
  1314. attributes:
  1315. id -- ID
  1316. xpath -- XPath subset, required
  1317. contents:
  1318. annotation?
  1319. """
  1320. required = ['xpath']
  1321. attributes = {'id':None,
  1322. 'xpath':None}
  1323. contents = {'xsd':['annotation']}
  1324. class Unique(IdentityConstrants):
  1325. """<unique name> Enforce fields are unique w/i a specified scope.
  1326. parent:
  1327. element
  1328. attributes:
  1329. id -- ID
  1330. name -- NCName, required
  1331. contents:
  1332. annotation?, selector, field+
  1333. """
  1334. required = ['name']
  1335. attributes = {'id':None,
  1336. 'name':None}
  1337. contents = {'xsd':['annotation', 'selector', 'field']}
  1338. class Key(IdentityConstrants):
  1339. """<key name> Enforce fields are unique w/i a specified scope, and all
  1340. field values are present w/i document. Fields cannot
  1341. be nillable.
  1342. parent:
  1343. element
  1344. attributes:
  1345. id -- ID
  1346. name -- NCName, required
  1347. contents:
  1348. annotation?, selector, field+
  1349. """
  1350. required = ['name']
  1351. attributes = {'id':None,
  1352. 'name':None}
  1353. contents = {'xsd':['annotation', 'selector', 'field']}
  1354. class KeyRef(IdentityConstrants):
  1355. """<keyref name refer> Ensure a match between two sets of values in an
  1356. instance.
  1357. parent:
  1358. element
  1359. attributes:
  1360. id -- ID
  1361. name -- NCName, required
  1362. refer -- QName, required
  1363. contents:
  1364. annotation?, selector, field+
  1365. """
  1366. required = ['name', 'refer']
  1367. attributes = {'id':None,
  1368. 'name':None,
  1369. 'refer':None}
  1370. contents = {'xsd':['annotation', 'selector', 'field']}
  1371. class ElementDeclaration(XMLSchemaComponent,\
  1372. MarkerInterface,\
  1373. ElementMarker,\
  1374. DeclarationMarker):
  1375. """<element name>
  1376. parents:
  1377. schema
  1378. attributes:
  1379. id -- ID
  1380. name -- NCName, required
  1381. type -- QName
  1382. default -- string
  1383. fixed -- string
  1384. nillable -- boolean, false
  1385. abstract -- boolean, false
  1386. substitutionGroup -- QName
  1387. block -- ('#all' | ('substition' | 'extension' | 'restriction')*),
  1388. schema.blockDefault
  1389. final -- ('#all' | ('extension' | 'restriction')*),
  1390. schema.finalDefault
  1391. contents:
  1392. annotation?, (simpleType,complexType)?, (key | keyref | unique)*
  1393. """
  1394. required = ['name']
  1395. attributes = {'id':None,
  1396. 'name':None,
  1397. 'type':None,
  1398. 'default':None,
  1399. 'fixed':None,
  1400. 'nillable':0,
  1401. 'abstract':0,
  1402. 'block':lambda self: self._parent().getBlockDefault(),
  1403. 'final':lambda self: self._parent().getFinalDefault()}
  1404. contents = {'xsd':['annotation', 'simpleType', 'complexType', 'key',\
  1405. 'keyref', 'unique']}
  1406. def __init__(self, parent):
  1407. XMLSchemaComponent.__init__(self, parent)
  1408. self.annotation = None
  1409. self.content = None
  1410. self.constraints = None
  1411. def fromDom(self, node):
  1412. self.setAttributes(node)
  1413. contents = self.getContents(node)
  1414. constraints = []
  1415. for i in contents:
  1416. component = SplitQName(i.getTagName())[1]
  1417. if component in self.__class__.contents['xsd']:
  1418. if component == 'annotation' and not self.annotation:
  1419. self.annotation = Annotation(self)
  1420. self.annotation.fromDom(i)
  1421. elif component == 'simpleType' and not self.content:
  1422. self.content = AnonymousSimpleType(self)
  1423. self.content.fromDom(i)
  1424. elif component == 'complexType' and not self.content:
  1425. self.content = LocalComplexType(self)
  1426. self.content.fromDom(i)
  1427. elif component == 'key':
  1428. constraints.append(Key(self))
  1429. constraints[-1].fromDom(i)
  1430. elif component == 'keyref':
  1431. constraints.append(KeyRef(self))
  1432. constraints[-1].fromDom(i)
  1433. elif component == 'unique':
  1434. constraints.append(Unique(self))
  1435. constraints[-1].fromDom(i)
  1436. else:
  1437. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  1438. else:
  1439. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  1440. self.constraints = tuple(constraints)
  1441. class LocalElementDeclaration(ElementDeclaration):
  1442. """<element>
  1443. parents:
  1444. all, choice, sequence
  1445. attributes:
  1446. id -- ID
  1447. name -- NCName, required
  1448. form -- ('qualified' | 'unqualified'), schema.elementFormDefault
  1449. type -- QName
  1450. minOccurs -- Whole Number, 1
  1451. maxOccurs -- (Whole Number | 'unbounded'), 1
  1452. default -- string
  1453. fixed -- string
  1454. nillable -- boolean, false
  1455. block -- ('#all' | ('extension' | 'restriction')*), schema.blockDefault
  1456. contents:
  1457. annotation?, (simpleType,complexType)?, (key | keyref | unique)*
  1458. """
  1459. required = ['name']
  1460. attributes = {'id':None,
  1461. 'name':None,
  1462. 'form':lambda self: GetSchema(self).getElementFormDefault(),
  1463. 'type':None,
  1464. 'minOccurs':'1',
  1465. 'maxOccurs':'1',
  1466. 'default':None,
  1467. 'fixed':None,
  1468. 'nillable':0,
  1469. 'abstract':0,
  1470. 'block':lambda self: GetSchema(self).getBlockDefault()}
  1471. contents = {'xsd':['annotation', 'simpleType', 'complexType', 'key',\
  1472. 'keyref', 'unique']}
  1473. class ElementReference(XMLSchemaComponent,\
  1474. MarkerInterface,\
  1475. ElementMarker,\
  1476. ReferenceMarker):
  1477. """<element ref>
  1478. parents:
  1479. all, choice, sequence
  1480. attributes:
  1481. id -- ID
  1482. ref -- QName, required
  1483. minOccurs -- Whole Number, 1
  1484. maxOccurs -- (Whole Number | 'unbounded'), 1
  1485. contents:
  1486. annotation?
  1487. """
  1488. required = ['ref']
  1489. attributes = {'id':None,
  1490. 'ref':None,
  1491. 'minOccurs':'1',
  1492. 'maxOccurs':'1'}
  1493. contents = {'xsd':['annotation']}
  1494. def __init__(self, parent):
  1495. XMLSchemaComponent.__init__(self, parent)
  1496. self.annotation = None
  1497. def fromDom(self, node):
  1498. self.annotation = None
  1499. self.setAttributes(node)
  1500. for i in self.getContents(node):
  1501. component = SplitQName(i.getTagName())[1]
  1502. if component in self.__class__.contents['xsd']:
  1503. if component == 'annotation' and not self.annotation:
  1504. self.annotation = Annotation(self)
  1505. self.annotation.fromDom(i)
  1506. else:
  1507. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  1508. class ElementWildCard(LocalElementDeclaration,\
  1509. WildCardMarker):
  1510. """<any>
  1511. parents:
  1512. choice, sequence
  1513. attributes:
  1514. id -- ID
  1515. minOccurs -- Whole Number, 1
  1516. maxOccurs -- (Whole Number | 'unbounded'), 1
  1517. namespace -- '##any' | '##other' |
  1518. (anyURI* | '##targetNamespace' | '##local'), ##any
  1519. processContents -- 'lax' | 'skip' | 'strict', strict
  1520. contents:
  1521. annotation?
  1522. """
  1523. required = []
  1524. attributes = {'id':None,
  1525. 'minOccurs':'1',
  1526. 'maxOccurs':'1',
  1527. 'namespace':'##any',
  1528. 'processContents':'strict'}
  1529. contents = {'xsd':['annotation']}
  1530. def __init__(self, parent):
  1531. XMLSchemaComponent.__init__(self, parent)
  1532. self.annotation = None
  1533. def fromDom(self, node):
  1534. self.annotation = None
  1535. self.setAttributes(node)
  1536. for i in self.getContents(node):
  1537. component = SplitQName(i.getTagName())[1]
  1538. if component in self.__class__.contents['xsd']:
  1539. if component == 'annotation' and not self.annotation:
  1540. self.annotation = Annotation(self)
  1541. self.annotation.fromDom(i)
  1542. else:
  1543. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  1544. ######################################################
  1545. # Model Groups
  1546. #####################################################
  1547. class Sequence(XMLSchemaComponent,\
  1548. MarkerInterface,\
  1549. ModelGroupMarker):
  1550. """<sequence>
  1551. parents:
  1552. complexType, extension, restriction, group, choice, sequence
  1553. attributes:
  1554. id -- ID
  1555. minOccurs -- Whole Number, 1
  1556. maxOccurs -- (Whole Number | 'unbounded'), 1
  1557. contents:
  1558. annotation?, (element | group | choice | sequence | any)*
  1559. """
  1560. attributes = {'id':None,
  1561. 'minOccurs':'1',
  1562. 'maxOccurs':'1'}
  1563. contents = {'xsd':['annotation', 'element', 'group', 'choice', 'sequence',\
  1564. 'any']}
  1565. def __init__(self, parent):
  1566. XMLSchemaComponent.__init__(self, parent)
  1567. self.annotation = None
  1568. self.content = None
  1569. def fromDom(self, node):
  1570. self.setAttributes(node)
  1571. contents = self.getContents(node)
  1572. content = []
  1573. for i in contents:
  1574. component = SplitQName(i.getTagName())[1]
  1575. if component in self.__class__.contents['xsd']:
  1576. if component == 'annotation' and not self.annotation:
  1577. self.annotation = Annotation(self)
  1578. self.annotation.fromDom(i)
  1579. continue
  1580. elif component == 'element':
  1581. if i.hasattr('ref'):
  1582. content.append(ElementReference(self))
  1583. else:
  1584. content.append(LocalElementDeclaration(self))
  1585. elif component == 'group':
  1586. content.append(ModelGroupReference(self))
  1587. elif component == 'choice':
  1588. content.append(Choice(self))
  1589. elif component == 'sequence':
  1590. content.append(Sequence(self))
  1591. elif component == 'any':
  1592. content.append(ElementWildCard(self))
  1593. else:
  1594. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  1595. content[-1].fromDom(i)
  1596. else:
  1597. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  1598. self.content = tuple(content)
  1599. class All(XMLSchemaComponent,\
  1600. MarkerInterface,\
  1601. ModelGroupMarker):
  1602. """<all>
  1603. parents:
  1604. complexType, extension, restriction, group
  1605. attributes:
  1606. id -- ID
  1607. minOccurs -- '0' | '1', 1
  1608. maxOccurs -- '1', 1
  1609. contents:
  1610. annotation?, element*
  1611. """
  1612. attributes = {'id':None,
  1613. 'minOccurs':'1',
  1614. 'maxOccurs':'1'}
  1615. contents = {'xsd':['annotation', 'element']}
  1616. def __init__(self, parent):
  1617. XMLSchemaComponent.__init__(self, parent)
  1618. self.annotation = None
  1619. self.content = None
  1620. def fromDom(self, node):
  1621. self.setAttributes(node)
  1622. contents = self.getContents(node)
  1623. content = []
  1624. for i in contents:
  1625. component = SplitQName(i.getTagName())[1]
  1626. if component in self.__class__.contents['xsd']:
  1627. if component == 'annotation' and not self.annotation:
  1628. self.annotation = Annotation(self)
  1629. self.annotation.fromDom(i)
  1630. continue
  1631. elif component == 'element':
  1632. if i.hasattr('ref'):
  1633. content.append(ElementReference(self))
  1634. else:
  1635. content.append(LocalElementDeclaration(self))
  1636. else:
  1637. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  1638. content[-1].fromDom(i)
  1639. else:
  1640. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  1641. self.content = tuple(content)
  1642. class Choice(XMLSchemaComponent,\
  1643. MarkerInterface,\
  1644. ModelGroupMarker):
  1645. """<choice>
  1646. parents:
  1647. complexType, extension, restriction, group, choice, sequence
  1648. attributes:
  1649. id -- ID
  1650. minOccurs -- Whole Number, 1
  1651. maxOccurs -- (Whole Number | 'unbounded'), 1
  1652. contents:
  1653. annotation?, (element | group | choice | sequence | any)*
  1654. """
  1655. attributes = {'id':None,
  1656. 'minOccurs':'1',
  1657. 'maxOccurs':'1'}
  1658. contents = {'xsd':['annotation', 'element', 'group', 'choice', 'sequence',\
  1659. 'any']}
  1660. def __init__(self, parent):
  1661. XMLSchemaComponent.__init__(self, parent)
  1662. self.annotation = None
  1663. self.content = None
  1664. def fromDom(self, node):
  1665. self.setAttributes(node)
  1666. contents = self.getContents(node)
  1667. content = []
  1668. for i in contents:
  1669. component = SplitQName(i.getTagName())[1]
  1670. if component in self.__class__.contents['xsd']:
  1671. if component == 'annotation' and not self.annotation:
  1672. self.annotation = Annotation(self)
  1673. self.annotation.fromDom(i)
  1674. continue
  1675. elif component == 'element':
  1676. if i.hasattr('ref'):
  1677. content.append(ElementReference(self))
  1678. else:
  1679. content.append(LocalElementDeclaration(self))
  1680. elif component == 'group':
  1681. content.append(ModelGroupReference(self))
  1682. elif component == 'choice':
  1683. content.append(Choice(self))
  1684. elif component == 'sequence':
  1685. content.append(Sequence(self))
  1686. elif component == 'any':
  1687. content.append(ElementWildCard(self))
  1688. else:
  1689. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  1690. content[-1].fromDom(i)
  1691. else:
  1692. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  1693. self.content = tuple(content)
  1694. class ModelGroupDefinition(XMLSchemaComponent,\
  1695. MarkerInterface,\
  1696. ModelGroupMarker,\
  1697. DefinitionMarker):
  1698. """<group name>
  1699. parents:
  1700. redefine, schema
  1701. attributes:
  1702. id -- ID
  1703. name -- NCName, required
  1704. contents:
  1705. annotation?, (all | choice | sequence)?
  1706. """
  1707. required = ['name']
  1708. attributes = {'id':None,
  1709. 'name':None}
  1710. contents = {'xsd':['annotation', 'all', 'choice', 'sequence']}
  1711. def __init__(self, parent):
  1712. XMLSchemaComponent.__init__(self, parent)
  1713. self.annotation = None
  1714. self.content = None
  1715. def fromDom(self, node):
  1716. self.setAttributes(node)
  1717. contents = self.getContents(node)
  1718. for i in contents:
  1719. component = SplitQName(i.getTagName())[1]
  1720. if component in self.__class__.contents['xsd']:
  1721. if component == 'annotation' and not self.annotation:
  1722. self.annotation = Annotation()
  1723. self.annotation.fromDom(i)
  1724. continue
  1725. elif component == 'all' and not self.content:
  1726. self.content = All(self)
  1727. elif component == 'choice' and not self.content:
  1728. self.content = Choice(self)
  1729. elif component == 'sequence' and not self.content:
  1730. self.content = Sequence(self)
  1731. else:
  1732. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  1733. self.content.fromDom(i)
  1734. else:
  1735. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  1736. class ModelGroupReference(XMLSchemaComponent,\
  1737. MarkerInterface,\
  1738. ModelGroupMarker,\
  1739. ReferenceMarker):
  1740. """<group ref>
  1741. parents:
  1742. choice, complexType, extension, restriction, sequence
  1743. attributes:
  1744. id -- ID
  1745. ref -- NCName, required
  1746. contents:
  1747. annotation?
  1748. """
  1749. required = ['ref']
  1750. attributes = {'id':None,
  1751. 'ref':None}
  1752. contents = {'xsd':['annotation']}
  1753. def __init__(self, parent):
  1754. XMLSchemaComponent.__init__(self, parent)
  1755. self.annotation = None
  1756. def fromDom(self, node):
  1757. self.setAttributes(node)
  1758. contents = self.getContents(node)
  1759. for i in contents:
  1760. component = SplitQName(i.getTagName())[1]
  1761. if component in self.__class__.contents['xsd']:
  1762. if component == 'annotation' and not self.annotation:
  1763. self.annotation = Annotation(self)
  1764. self.annotation.fromDom(i)
  1765. else:
  1766. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  1767. else:
  1768. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  1769. class ComplexType(XMLSchemaComponent,\
  1770. MarkerInterface,\
  1771. DefinitionMarker,\
  1772. ComplexMarker):
  1773. """<complexType name>
  1774. parents:
  1775. redefine, schema
  1776. attributes:
  1777. id -- ID
  1778. name -- NCName, required
  1779. mixed -- boolean, false
  1780. abstract -- boolean, false
  1781. block -- ('#all' | ('extension' | 'restriction')*), schema.blockDefault
  1782. final -- ('#all' | ('extension' | 'restriction')*), schema.finalDefault
  1783. contents:
  1784. annotation?, (simpleContent | complexContent |
  1785. ((group | all | choice | sequence)?, (attribute | attributeGroup)*, anyAttribute?))
  1786. """
  1787. required = ['name']
  1788. attributes = {'id':None,
  1789. 'name':None,
  1790. 'mixed':0,
  1791. 'abstract':0,
  1792. 'block':lambda self: self._parent().getBlockDefault(),
  1793. 'final':lambda self: self._parent().getFinalDefault()}
  1794. contents = {'xsd':['annotation', 'simpleContent', 'complexContent',\
  1795. 'group', 'all', 'choice', 'sequence', 'attribute', 'attributeGroup',\
  1796. 'anyAttribute', 'any']}
  1797. def __init__(self, parent):
  1798. XMLSchemaComponent.__init__(self, parent)
  1799. self.annotation = None
  1800. self.content = None
  1801. self.attr_content = None
  1802. def fromDom(self, node):
  1803. self.setAttributes(node)
  1804. contents = self.getContents(node)
  1805. indx = 0
  1806. num = len(contents)
  1807. #XXX ugly
  1808. if not num:
  1809. return
  1810. component = SplitQName(contents[indx].getTagName())[1]
  1811. if component == 'annotation':
  1812. self.annotation = Annotation(self)
  1813. self.annotation.fromDom(contents[indx])
  1814. indx += 1
  1815. component = SplitQName(contents[indx].getTagName())[1]
  1816. self.content = None
  1817. if component == 'simpleContent':
  1818. self.content = self.__class__.SimpleContent(self)
  1819. self.content.fromDom(contents[indx])
  1820. elif component == 'complexContent':
  1821. self.content = self.__class__.ComplexContent(self)
  1822. self.content.fromDom(contents[indx])
  1823. else:
  1824. if component == 'all':
  1825. self.content = All(self)
  1826. elif component == 'choice':
  1827. self.content = Choice(self)
  1828. elif component == 'sequence':
  1829. self.content = Sequence(self)
  1830. elif component == 'group':
  1831. self.content = ModelGroupReference(self)
  1832. if self.content:
  1833. self.content.fromDom(contents[indx])
  1834. indx += 1
  1835. self.attr_content = []
  1836. while indx < num:
  1837. component = SplitQName(contents[indx].getTagName())[1]
  1838. if component == 'attribute':
  1839. if contents[indx].hasattr('ref'):
  1840. self.attr_content.append(AttributeReference(self))
  1841. else:
  1842. self.attr_content.append(LocalAttributeDeclaration(self))
  1843. elif component == 'attributeGroup':
  1844. self.attr_content.append(AttributeGroupReference(self))
  1845. elif component == 'anyAttribute':
  1846. self.attr_content.append(AttributeWildCard(self))
  1847. else:
  1848. raise SchemaError, 'Unknown component (%s)' %(contents[indx].getTagName())
  1849. self.attr_content[-1].fromDom(contents[indx])
  1850. indx += 1
  1851. class _DerivedType(XMLSchemaComponent):
  1852. def __init__(self, parent):
  1853. XMLSchemaComponent.__init__(self, parent)
  1854. self.annotation = None
  1855. self.derivation = None
  1856. def fromDom(self, node):
  1857. self.setAttributes(node)
  1858. contents = self.getContents(node)
  1859. for i in contents:
  1860. component = SplitQName(i.getTagName())[1]
  1861. if component in self.__class__.contents['xsd']:
  1862. if component == 'annotation' and not self.annotation:
  1863. self.annotation = Annotation(self)
  1864. self.annotation.fromDom(i)
  1865. continue
  1866. elif component == 'restriction' and not self.derivation:
  1867. self.derivation = self.__class__.Restriction(self)
  1868. elif component == 'extension' and not self.derivation:
  1869. self.derivation = self.__class__.Extension(self)
  1870. else:
  1871. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  1872. else:
  1873. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  1874. self.derivation.fromDom(i)
  1875. class ComplexContent(_DerivedType,\
  1876. MarkerInterface,\
  1877. ComplexMarker):
  1878. """<complexContent>
  1879. parents:
  1880. complexType
  1881. attributes:
  1882. id -- ID
  1883. mixed -- boolean, false
  1884. contents:
  1885. annotation?, (restriction | extension)
  1886. """
  1887. attributes = {'id':None,
  1888. 'mixed':0 }
  1889. contents = {'xsd':['annotation', 'restriction', 'extension']}
  1890. class _DerivationBase(XMLSchemaComponent):
  1891. """<extension>,<restriction>
  1892. parents:
  1893. complexContent
  1894. attributes:
  1895. id -- ID
  1896. base -- QName, required
  1897. contents:
  1898. annotation?, (group | all | choice | sequence)?,
  1899. (attribute | attributeGroup)*, anyAttribute?
  1900. """
  1901. required = ['base']
  1902. attributes = {'id':None,
  1903. 'base':None }
  1904. contents = {'xsd':['annotation', 'group', 'all', 'choice',\
  1905. 'sequence', 'attribute', 'attributeGroup', 'anyAttribute']}
  1906. def fromDom(self, node):
  1907. self.setAttributes(node)
  1908. contents = self.getContents(node)
  1909. indx = 0
  1910. num = len(contents)
  1911. #XXX ugly
  1912. if not num:
  1913. return
  1914. component = SplitQName(contents[indx].getTagName())[1]
  1915. if component == 'annotation':
  1916. self.annotation = Annotation(self)
  1917. self.annotation.fromDom(contents[indx])
  1918. indx += 1
  1919. component = SplitQName(contents[indx].getTagName())[1]
  1920. if component == 'all':
  1921. self.content = All(self)
  1922. self.content.fromDom(contents[indx])
  1923. indx += 1
  1924. elif component == 'choice':
  1925. self.content = Choice(self)
  1926. self.content.fromDom(contents[indx])
  1927. indx += 1
  1928. elif component == 'sequence':
  1929. self.content = Sequence(self)
  1930. self.content.fromDom(contents[indx])
  1931. indx += 1
  1932. elif component == 'group':
  1933. self.content = ModelGroupReference(self)
  1934. self.content.fromDom(contents[indx])
  1935. indx += 1
  1936. else:
  1937. self.content = None
  1938. self.attr_content = []
  1939. while indx < num:
  1940. component = SplitQName(contents[indx].getTagName())[1]
  1941. if component == 'attribute':
  1942. if contents[indx].hasattr('ref'):
  1943. self.attr_content.append(AttributeReference(self))
  1944. else:
  1945. self.attr_content.append(LocalAttributeDeclaration(self))
  1946. elif component == 'attributeGroup':
  1947. self.attr_content.append(AttributeGroupDefinition(self))
  1948. elif component == 'anyAttribute':
  1949. self.attr_content.append(AttributeWildCard(self))
  1950. else:
  1951. raise SchemaError, 'Unknown component (%s)' %(contents[indx].getTagName())
  1952. self.attr_content[-1].fromDom(contents[indx])
  1953. indx += 1
  1954. class Extension(_DerivationBase, MarkerInterface, ExtensionMarker):
  1955. """<extension base>
  1956. parents:
  1957. complexContent
  1958. attributes:
  1959. id -- ID
  1960. base -- QName, required
  1961. contents:
  1962. annotation?, (group | all | choice | sequence)?,
  1963. (attribute | attributeGroup)*, anyAttribute?
  1964. """
  1965. pass
  1966. class Restriction(_DerivationBase,\
  1967. MarkerInterface,\
  1968. RestrictionMarker):
  1969. """<restriction base>
  1970. parents:
  1971. complexContent
  1972. attributes:
  1973. id -- ID
  1974. base -- QName, required
  1975. contents:
  1976. annotation?, (group | all | choice | sequence)?,
  1977. (attribute | attributeGroup)*, anyAttribute?
  1978. """
  1979. pass
  1980. class SimpleContent(_DerivedType,\
  1981. MarkerInterface,\
  1982. SimpleMarker):
  1983. """<simpleContent>
  1984. parents:
  1985. complexType
  1986. attributes:
  1987. id -- ID
  1988. contents:
  1989. annotation?, (restriction | extension)
  1990. """
  1991. attributes = {'id':None}
  1992. contents = {'xsd':['annotation', 'restriction', 'extension']}
  1993. class Extension(XMLSchemaComponent,\
  1994. MarkerInterface,\
  1995. ExtensionMarker):
  1996. """<extension base>
  1997. parents:
  1998. simpleContent
  1999. attributes:
  2000. id -- ID
  2001. base -- QName, required
  2002. contents:
  2003. annotation?, (attribute | attributeGroup)*, anyAttribute?
  2004. """
  2005. required = ['base']
  2006. attributes = {'id':None,
  2007. 'base':None }
  2008. contents = {'xsd':['annotation', 'attribute', 'attributeGroup',
  2009. 'anyAttribute']}
  2010. def __init__(self, parent):
  2011. XMLSchemaComponent.__init__(self, parent)
  2012. self.annotation = None
  2013. self.attr_content = None
  2014. def fromDom(self, node):
  2015. self.setAttributes(node)
  2016. contents = self.getContents(node)
  2017. indx = 0
  2018. num = len(contents)
  2019. component = SplitQName(contents[indx].getTagName())[1]
  2020. if component == 'annotation':
  2021. self.annotation = Annotation(self)
  2022. self.annotation.fromDom(contents[indx])
  2023. indx += 1
  2024. component = SplitQName(contents[indx].getTagName())[1]
  2025. content = []
  2026. while indx < num:
  2027. component = SplitQName(contents[indx].getTagName())[1]
  2028. if component == 'attribute':
  2029. if contents[indx].hasattr('ref'):
  2030. content.append(AttributeReference(self))
  2031. else:
  2032. content.append(LocalAttributeDeclaration(self))
  2033. elif component == 'attributeGroup':
  2034. content.append(AttributeGroupReference(self))
  2035. elif component == 'anyAttribute':
  2036. content.append(AttributeWildCard(self))
  2037. else:
  2038. raise SchemaError, 'Unknown component (%s)'\
  2039. %(contents[indx].getTagName())
  2040. content[-1].fromDom(contents[indx])
  2041. indx += 1
  2042. self.attr_content = tuple(content)
  2043. class Restriction(XMLSchemaComponent,\
  2044. MarkerInterface,\
  2045. RestrictionMarker):
  2046. """<restriction base>
  2047. parents:
  2048. simpleContent
  2049. attributes:
  2050. id -- ID
  2051. base -- QName, required
  2052. contents:
  2053. annotation?, simpleType?, (enumeration | length |
  2054. maxExclusive | maxInclusive | maxLength | minExclusive |
  2055. minInclusive | minLength | pattern | fractionDigits |
  2056. totalDigits | whiteSpace)*, (attribute | attributeGroup)*,
  2057. anyAttribute?
  2058. """
  2059. required = ['base']
  2060. attributes = {'id':None,
  2061. 'base':None }
  2062. contents = {'xsd':['annotation', 'simpleType', 'attribute',\
  2063. 'attributeGroup', 'anyAttribute'] + RestrictionMarker.facets}
  2064. class LocalComplexType(ComplexType):
  2065. """<complexType>
  2066. parents:
  2067. element
  2068. attributes:
  2069. id -- ID
  2070. mixed -- boolean, false
  2071. contents:
  2072. annotation?, (simpleContent | complexContent |
  2073. ((group | all | choice | sequence)?, (attribute | attributeGroup)*, anyAttribute?))
  2074. """
  2075. required = []
  2076. attributes = {'id':None,
  2077. 'mixed':0}
  2078. class SimpleType(XMLSchemaComponent,\
  2079. MarkerInterface,\
  2080. DefinitionMarker,\
  2081. SimpleMarker):
  2082. """<simpleType name>
  2083. parents:
  2084. redefine, schema
  2085. attributes:
  2086. id -- ID
  2087. name -- NCName, required
  2088. final -- ('#all' | ('extension' | 'restriction' | 'list' | 'union')*),
  2089. schema.finalDefault
  2090. contents:
  2091. annotation?, (restriction | list | union)
  2092. """
  2093. required = ['name']
  2094. attributes = {'id':None,
  2095. 'name':None,
  2096. 'final':lambda self: self._parent().getFinalDefault()}
  2097. contents = {'xsd':['annotation', 'restriction', 'list', 'union']}
  2098. def __init__(self, parent):
  2099. XMLSchemaComponent.__init__(self, parent)
  2100. self.annotation = None
  2101. self.content = None
  2102. self.attr_content = None
  2103. def fromDom(self, node):
  2104. self.setAttributes(node)
  2105. contents = self.getContents(node)
  2106. for child in contents:
  2107. component = SplitQName(child.getTagName())[1]
  2108. if component == 'annotation':
  2109. self.annotation = Annotation(self)
  2110. self.annotation.fromDom(child)
  2111. break
  2112. else:
  2113. return
  2114. if component == 'restriction':
  2115. self.content = self.__class__.Restriction(self)
  2116. elif component == 'list':
  2117. self.content = self.__class__.List(self)
  2118. elif component == 'union':
  2119. self.content = self.__class__.Union(self)
  2120. else:
  2121. raise SchemaError, 'Unknown component (%s)' %(contents[indx].getTagName())
  2122. self.content.fromDom(child)
  2123. class Restriction(XMLSchemaComponent,\
  2124. MarkerInterface,\
  2125. RestrictionMarker):
  2126. """<restriction base>
  2127. parents:
  2128. simpleType
  2129. attributes:
  2130. id -- ID
  2131. base -- QName, required or simpleType child
  2132. contents:
  2133. annotation?, simpleType?, (enumeration | length |
  2134. maxExclusive | maxInclusive | maxLength | minExclusive |
  2135. minInclusive | minLength | pattern | fractionDigits |
  2136. totalDigits | whiteSpace)*
  2137. """
  2138. attributes = {'id':None,
  2139. 'base':None }
  2140. contents = {'xsd':['annotation', 'simpleType']+RestrictionMarker.facets}
  2141. def __init__(self, parent):
  2142. XMLSchemaComponent.__init__(self, parent)
  2143. self.annotation = None
  2144. self.content = None
  2145. self.attr_content = None
  2146. def fromDom(self, node):
  2147. self.setAttributes(node)
  2148. contents = self.getContents(node)
  2149. content = []
  2150. self.attr_content = []
  2151. for indx in range(len(contents)):
  2152. component = SplitQName(contents[indx].getTagName())[1]
  2153. if (component == 'annotation') and (not indx):
  2154. self.annotation = Annotation(self)
  2155. self.annotation.fromDom(contents[indx])
  2156. continue
  2157. elif (component == 'simpleType') and (not indx or indx == 1):
  2158. content.append(AnonymousSimpleType(self))
  2159. content[-1].fromDom(contents[indx])
  2160. elif component in RestrictionMarker.facets:
  2161. #print_debug('%s class instance, skipping %s' %(self.__class__, component))
  2162. pass
  2163. else:
  2164. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  2165. self.content = tuple(content)
  2166. class Union(XMLSchemaComponent):
  2167. """<union>
  2168. parents:
  2169. simpleType
  2170. attributes:
  2171. id -- ID
  2172. memberTypes -- list of QNames, required or simpleType child.
  2173. contents:
  2174. annotation?, simpleType*
  2175. """
  2176. attributes = {'id':None,
  2177. 'memberTypes':None }
  2178. contents = {'xsd':['annotation', 'simpleType']}
  2179. def __init__(self, parent):
  2180. XMLSchemaComponent.__init__(self, parent)
  2181. self.annotation = None
  2182. self.content = None
  2183. self.attr_content = None
  2184. def fromDom(self, node):
  2185. self.setAttributes(node)
  2186. contents = self.getContents(node)
  2187. content = []
  2188. self.attr_content = []
  2189. for indx in range(len(contents)):
  2190. component = SplitQName(contents[indx].getTagName())[1]
  2191. if (component == 'annotation') and (not indx):
  2192. self.annotation = Annotation(self)
  2193. self.annotation.fromDom(contents[indx])
  2194. elif (component == 'simpleType'):
  2195. content.append(AnonymousSimpleType(self))
  2196. content[-1].fromDom(contents[indx])
  2197. else:
  2198. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  2199. self.content = tuple(content)
  2200. class List(XMLSchemaComponent):
  2201. """<list>
  2202. parents:
  2203. simpleType
  2204. attributes:
  2205. id -- ID
  2206. itemType -- QName, required or simpleType child.
  2207. contents:
  2208. annotation?, simpleType?
  2209. """
  2210. attributes = {'id':None,
  2211. 'itemType':None }
  2212. contents = {'xsd':['annotation', 'simpleType']}
  2213. def __init__(self, parent):
  2214. XMLSchemaComponent.__init__(self, parent)
  2215. self.annotation = None
  2216. self.content = None
  2217. self.attr_content = None
  2218. def fromDom(self, node):
  2219. self.setAttributes(node)
  2220. contents = self.getContents(node)
  2221. self.content = []
  2222. self.attr_content = []
  2223. for indx in range(len(contents)):
  2224. component = SplitQName(contents[indx].getTagName())[1]
  2225. if (component == 'annotation') and (not indx):
  2226. self.annotation = Annotation(self)
  2227. self.annotation.fromDom(contents[indx])
  2228. elif (component == 'simpleType'):
  2229. self.content = AnonymousSimpleType(self)
  2230. self.content.fromDom(contents[indx])
  2231. break
  2232. else:
  2233. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  2234. class AnonymousSimpleType(SimpleType,\
  2235. MarkerInterface,\
  2236. SimpleMarker):
  2237. """<simpleType>
  2238. parents:
  2239. attribute, element, list, restriction, union
  2240. attributes:
  2241. id -- ID
  2242. contents:
  2243. annotation?, (restriction | list | union)
  2244. """
  2245. required = []
  2246. attributes = {'id':None}
  2247. class Redefine:
  2248. """<redefine>
  2249. parents:
  2250. attributes:
  2251. contents:
  2252. """
  2253. pass
  2254. ###########################
  2255. ###########################
  2256. if sys.version_info[:2] >= (2, 2):
  2257. tupleClass = tuple
  2258. else:
  2259. import UserTuple
  2260. tupleClass = UserTuple.UserTuple
  2261. class TypeDescriptionComponent(tupleClass):
  2262. """Tuple of length 2, consisting of
  2263. a namespace and unprefixed name.
  2264. """
  2265. def __init__(self, args):
  2266. """args -- (namespace, name)
  2267. Remove the name's prefix, irrelevant.
  2268. """
  2269. if len(args) != 2:
  2270. raise TypeError, 'expecting tuple (namespace, name), got %s' %args
  2271. elif args[1].find(':') >= 0:
  2272. args = (args[0], SplitQName(args[1])[1])
  2273. tuple.__init__(self, args)
  2274. return
  2275. def getTargetNamespace(self):
  2276. return self[0]
  2277. def getName(self):
  2278. return self[1]
  2279. '''
  2280. import string, types, base64, re
  2281. from Utility import DOM, Collection
  2282. from StringIO import StringIO
  2283. class SchemaReader:
  2284. """A SchemaReader creates XMLSchema objects from urls and xml data."""
  2285. def loadFromStream(self, file):
  2286. """Return an XMLSchema instance loaded from a file object."""
  2287. document = DOM.loadDocument(file)
  2288. schema = XMLSchema()
  2289. schema.load(document)
  2290. return schema
  2291. def loadFromString(self, data):
  2292. """Return an XMLSchema instance loaded from an xml string."""
  2293. return self.loadFromStream(StringIO(data))
  2294. def loadFromURL(self, url):
  2295. """Return an XMLSchema instance loaded from the given url."""
  2296. document = DOM.loadFromURL(url)
  2297. schema = XMLSchema()
  2298. schema.location = url
  2299. schema.load(document)
  2300. return schema
  2301. def loadFromFile(self, filename):
  2302. """Return an XMLSchema instance loaded from the given file."""
  2303. file = open(filename, 'rb')
  2304. try: schema = self.loadFromStream(file)
  2305. finally: file.close()
  2306. return schema
  2307. class SchemaError(Exception):
  2308. pass
  2309. class XMLSchema:
  2310. # This is temporary, for the benefit of WSDL until the real thing works.
  2311. def __init__(self, element):
  2312. self.targetNamespace = DOM.getAttr(element, 'targetNamespace')
  2313. self.element = element
  2314. class realXMLSchema:
  2315. """A schema is a collection of schema components derived from one
  2316. or more schema documents, that is, one or more <schema> element
  2317. information items. It represents the abstract notion of a schema
  2318. rather than a single schema document (or other representation)."""
  2319. def __init__(self):
  2320. self.simpleTypes = Collection(self)
  2321. self.complexTypes = Collection(self)
  2322. self.attributes = Collection(self)
  2323. self.elements = Collection(self)
  2324. self.attrGroups = Collection(self)
  2325. self.idConstraints=None
  2326. self.modelGroups = None
  2327. self.notations = None
  2328. self.extensions = []
  2329. targetNamespace = None
  2330. attributeFormDefault = 'unqualified'
  2331. elementFormDefault = 'unqualified'
  2332. blockDefault = None
  2333. finalDefault = None
  2334. location = None
  2335. version = None
  2336. id = None
  2337. def load(self, document):
  2338. if document.nodeType == document.DOCUMENT_NODE:
  2339. schema = DOM.getElement(document, 'schema', None, None)
  2340. else:
  2341. schema = document
  2342. if schema is None:
  2343. raise SchemaError('Missing <schema> element.')
  2344. self.namespace = namespace = schema.namespaceURI
  2345. if not namespace in DOM.NS_XSD_ALL:
  2346. raise SchemaError(
  2347. 'Unknown XML schema namespace: %s.' % self.namespace
  2348. )
  2349. for attrname in (
  2350. 'targetNamespace', 'attributeFormDefault', 'elementFormDefault',
  2351. 'blockDefault', 'finalDefault', 'version', 'id'
  2352. ):
  2353. value = DOM.getAttr(schema, attrname, None, None)
  2354. if value is not None:
  2355. setattr(self, attrname, value)
  2356. # Resolve imports and includes here?
  2357. ## imported = {}
  2358. ## while 1:
  2359. ## imports = []
  2360. ## for element in DOM.getElements(definitions, 'import', NS_WSDL):
  2361. ## location = DOM.getAttr(element, 'location')
  2362. ## if not imported.has_key(location):
  2363. ## imports.append(element)
  2364. ## if not imports:
  2365. ## break
  2366. ## for element in imports:
  2367. ## self._import(document, element)
  2368. ## imported[location] = 1
  2369. for element in DOM.getElements(schema, None, None):
  2370. localName = element.localName
  2371. if not DOM.nsUriMatch(element.namespaceURI, namespace):
  2372. self.extensions.append(element)
  2373. continue
  2374. elif localName == 'message':
  2375. name = DOM.getAttr(element, 'name')
  2376. docs = GetDocumentation(element)
  2377. message = self.addMessage(name, docs)
  2378. parts = DOM.getElements(element, 'part', NS_WSDL)
  2379. message.load(parts)
  2380. continue
  2381. def _import(self, document, element):
  2382. namespace = DOM.getAttr(element, 'namespace', default=None)
  2383. location = DOM.getAttr(element, 'location', default=None)
  2384. if namespace is None or location is None:
  2385. raise WSDLError(
  2386. 'Invalid import element (missing namespace or location).'
  2387. )
  2388. # Sort-of support relative locations to simplify unit testing. The
  2389. # WSDL specification actually doesn't allow relative URLs, so its
  2390. # ok that this only works with urls relative to the initial document.
  2391. location = urllib.basejoin(self.location, location)
  2392. obimport = self.addImport(namespace, location)
  2393. obimport._loaded = 1
  2394. importdoc = DOM.loadFromURL(location)
  2395. try:
  2396. if location.find('#') > -1:
  2397. idref = location.split('#')[-1]
  2398. imported = DOM.getElementById(importdoc, idref)
  2399. else:
  2400. imported = importdoc.documentElement
  2401. if imported is None:
  2402. raise WSDLError(
  2403. 'Import target element not found for: %s' % location
  2404. )
  2405. imported_tns = DOM.getAttr(imported, 'targetNamespace')
  2406. importer_tns = namespace
  2407. if imported_tns != importer_tns:
  2408. return
  2409. if imported.localName == 'definitions':
  2410. imported_nodes = imported.childNodes
  2411. else:
  2412. imported_nodes = [imported]
  2413. parent = element.parentNode
  2414. for node in imported_nodes:
  2415. if node.nodeType != node.ELEMENT_NODE:
  2416. continue
  2417. child = DOM.importNode(document, node, 1)
  2418. parent.appendChild(child)
  2419. child.setAttribute('targetNamespace', importer_tns)
  2420. attrsNS = imported._attrsNS
  2421. for attrkey in attrsNS.keys():
  2422. if attrkey[0] == DOM.NS_XMLNS:
  2423. attr = attrsNS[attrkey].cloneNode(1)
  2424. child.setAttributeNode(attr)
  2425. finally:
  2426. importdoc.unlink()
  2427. class Element:
  2428. """Common base class for element representation classes."""
  2429. def __init__(self, name=None, documentation=''):
  2430. self.name = name
  2431. self.documentation = documentation
  2432. self.extensions = []
  2433. def addExtension(self, item):
  2434. self.extensions.append(item)
  2435. class SimpleTypeDefinition:
  2436. """Represents an xml schema simple type definition."""
  2437. class ComplexTypeDefinition:
  2438. """Represents an xml schema complex type definition."""
  2439. class AttributeDeclaration:
  2440. """Represents an xml schema attribute declaration."""
  2441. class ElementDeclaration:
  2442. """Represents an xml schema element declaration."""
  2443. def __init__(self, name, type=None, targetNamespace=None):
  2444. self.name = name
  2445. targetNamespace = None
  2446. annotation = None
  2447. nillable = 0
  2448. abstract = 0
  2449. default = None
  2450. fixed = None
  2451. scope = 'global'
  2452. type = None
  2453. form = 0
  2454. # Things we will not worry about for now.
  2455. id_constraint_defs = None
  2456. sub_group_exclude = None
  2457. sub_group_affils = None
  2458. disallowed_subs = None
  2459. class AttributeGroupDefinition:
  2460. """Represents an xml schema attribute group definition."""
  2461. class IdentityConstraintDefinition:
  2462. """Represents an xml schema identity constraint definition."""
  2463. class ModelGroupDefinition:
  2464. """Represents an xml schema model group definition."""
  2465. class NotationDeclaration:
  2466. """Represents an xml schema notation declaration."""
  2467. class Annotation:
  2468. """Represents an xml schema annotation."""
  2469. class ModelGroup:
  2470. """Represents an xml schema model group."""
  2471. class Particle:
  2472. """Represents an xml schema particle."""
  2473. class WildCard:
  2474. """Represents an xml schema wildcard."""
  2475. class AttributeUse:
  2476. """Represents an xml schema attribute use."""
  2477. class ElementComponent:
  2478. namespace = ''
  2479. name = ''
  2480. type = None
  2481. form = 'qualified | unqualified'
  2482. scope = 'global or complex def'
  2483. constraint = ('value', 'default | fixed')
  2484. nillable = 0
  2485. id_constraint_defs = None
  2486. sub_group_affil = None
  2487. sub_group_exclusions = None
  2488. disallowed_subs = 'substitution, extension, restriction'
  2489. abstract = 0
  2490. minOccurs = 1
  2491. maxOccurs = 1
  2492. ref = ''
  2493. class AttributeThing:
  2494. name = ''
  2495. namespace = ''
  2496. typeName = ''
  2497. typeUri = ''
  2498. scope = 'global | local to complex def'
  2499. constraint = ('value:default', 'value:fixed')
  2500. use = 'optional | prohibited | required'
  2501. class ElementDataType:
  2502. namespace = ''
  2503. name = ''
  2504. element_form = 'qualified | unqualified'
  2505. attr_form = None
  2506. type_name = ''
  2507. type_uri = ''
  2508. def __init__(self, name, namespace, type_name, type_uri):
  2509. self.namespace = namespace
  2510. self.name = name
  2511. # type may be anonymous...
  2512. self.type_name = type_name
  2513. self.type_uri = type_uri
  2514. def checkValue(self, value, context):
  2515. # Delegate value checking to the type of the element.
  2516. typeref = (self.type_uri, self.type_name)
  2517. handler = context.serializer.getType(typeref)
  2518. return handler.checkValue(value, context)
  2519. def serialize(self, name, namespace, value, context, **kwargs):
  2520. if context.check_values:
  2521. self.checkValue(value, context)
  2522. # Delegate serialization to the type of the element.
  2523. typeref = (self.type_uri, self.type_name)
  2524. handler = context.serializer.getType(typeref)
  2525. return handler.serialize(self.name, self.namespace, value, context)
  2526. def deserialize(self, element, context):
  2527. if element_is_null(element, context):
  2528. return None
  2529. # Delegate deserialization to the type of the element.
  2530. typeref = (self.type_uri, self.type_name)
  2531. handler = context.serializer.getType(typeref)
  2532. return handler.deserialize(element, context)
  2533. def parse_schema(data):
  2534. targetNS = ''
  2535. attributeFormDefault = 0
  2536. elementFormDefault = 0
  2537. blockDefault = ''
  2538. finalDefault = ''
  2539. language = None
  2540. version = None
  2541. id = ''
  2542. '''