xsvalSimpleTypes.py
Go to the documentation of this file.
00001 #
00002 # minixsv, Release 0.9.0
00003 # file: xsvalSimpleTypes.py
00004 #
00005 # class for validation of XML schema simple types
00006 #
00007 # history:
00008 # 2004-09-09 rl   created
00009 # 2006-08-18 rl   W3C testsuite passed for supported features
00010 # 2007-05-24 rl   Features for release 0.8 added, some bugs fixed
00011 #
00012 # Copyright (c) 2004-2007 by Roland Leuthe.  All rights reserved.
00013 #
00014 # --------------------------------------------------------------------
00015 # The minixsv XML schema validator is
00016 #
00017 # Copyright (c) 2004-2007 by Roland Leuthe
00018 #
00019 # By obtaining, using, and/or copying this software and/or its
00020 # associated documentation, you agree that you have read, understood,
00021 # and will comply with the following terms and conditions:
00022 #
00023 # Permission to use, copy, modify, and distribute this software and
00024 # its associated documentation for any purpose and without fee is
00025 # hereby granted, provided that the above copyright notice appears in
00026 # all copies, and that both that copyright notice and this permission
00027 # notice appear in supporting documentation, and that the name of
00028 # the author not be used in advertising or publicity
00029 # pertaining to distribution of the software without specific, written
00030 # prior permission.
00031 #
00032 # THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
00033 # TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT-
00034 # ABILITY AND FITNESS.  IN NO EVENT SHALL THE AUTHOR
00035 # BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY
00036 # DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
00037 # WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
00038 # ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
00039 # OF THIS SOFTWARE.
00040 # --------------------------------------------------------------------
00041 
00042 import sys
00043 import string
00044 import re
00045 import datetime
00046 from decimal             import Decimal
00047 from ..genxmlif.xmlifUtils import removeWhitespaces, collapseString, normalizeString, NsNameTupleFactory
00048 from ..minixsv             import XSD_NAMESPACE
00049 from xsvalUtils          import substituteSpecialEscChars
00050 
00051 ###################################################
00052 # Validator class for simple types
00053 ###################################################
00054 class XsSimpleTypeVal:
00055 
00056     def __init__ (self, parent):
00057         self.parent = parent
00058         self.xmlIf  = parent.xmlIf
00059         self.xsdNsURI = parent.xsdNsURI
00060         self.xsdIdDict = parent.xsdIdDict
00061         self.xsdIdRefDict = parent.xsdIdRefDict
00062 
00063 
00064     def unlink (self):
00065         self.parent = None
00066         
00067 
00068     ########################################
00069     # validate given value against simpleType
00070     #
00071     def checkSimpleType (self, inputNode, attrName, typeName, attributeValue, returnDict, idCheck):
00072         returnDict["adaptedAttrValue"] = attributeValue
00073         returnDict["BaseTypes"].append(str(typeName))
00074         if _suppBaseTypeDict.has_key(typeName):
00075             try:
00076                 _suppBaseTypeDict[typeName] (inputNode, typeName, attributeValue, returnDict)
00077                 returnDict["primitiveType"] = typeName
00078             except BaseTypeError, errstr:
00079                 raise SimpleTypeError("Value of %s (%s) %s" %(repr(attrName), repr(attributeValue), errstr))
00080 
00081         elif self.parent.xsdTypeDict.has_key(typeName):
00082             typedefNode = self.parent.xsdTypeDict[typeName]
00083             if typedefNode.getNsName() == (XSD_NAMESPACE, "simpleType"):
00084                 self.checkSimpleTypeDef (inputNode, typedefNode, attrName, attributeValue, returnDict, idCheck)
00085             elif (typedefNode.getNsName() == (XSD_NAMESPACE, "complexType") and
00086                   typedefNode.getFirstChild().getNsName() == (XSD_NAMESPACE, "simpleContent")):
00087                 self.checkSimpleTypeDef (inputNode, typedefNode.getFirstChild(), attrName, attributeValue, returnDict, idCheck)
00088             elif typedefNode.getAttribute("mixed") == "true":
00089                 self.checkSimpleType (inputNode, attrName, (XSD_NAMESPACE, "string"), attributeValue, returnDict, idCheck)
00090             elif typeName != (XSD_NAMESPACE, "anyType"):
00091                 raise SimpleTypeError("Attribute %s requires a simple type!" %repr(attrName))
00092             
00093             if idCheck:
00094                 adaptedAttrValue = returnDict["adaptedAttrValue"]
00095                 if typeName == (XSD_NAMESPACE, "ID"):
00096                     if not self.xsdIdDict.has_key(adaptedAttrValue):
00097                         self.xsdIdDict[adaptedAttrValue] = inputNode
00098                     else:
00099                         raise SimpleTypeError("There are multiple occurences of ID value %s!" %repr(adaptedAttrValue))
00100                 if typeName == (XSD_NAMESPACE, "IDREF"):
00101                     self.xsdIdRefDict[adaptedAttrValue] = inputNode
00102         else:
00103             # TODO: Fehler im XSD-File => Check muss an anderer Stelle erfolgen
00104             raise SimpleTypeError("%s uses unknown type %s!" %(repr(attrName), repr(typeName)))
00105 
00106 
00107     ########################################
00108     # validate given value against simpleType node
00109     #
00110     def checkSimpleTypeDef (self, inputNode, xsdElement, attrName, attributeValue, returnDict, idCheck):
00111         returnDict["adaptedAttrValue"] = attributeValue
00112         restrictionElement = xsdElement.getFirstChildNS(self.xsdNsURI, "restriction")
00113         extensionElement   = xsdElement.getFirstChildNS(self.xsdNsURI, "extension")
00114         listElement        = xsdElement.getFirstChildNS(self.xsdNsURI, "list")
00115         unionElement       = xsdElement.getFirstChildNS(self.xsdNsURI, "union")
00116         if restrictionElement != None:
00117             self._checkRestrictionTag (inputNode, restrictionElement, attrName, attributeValue, returnDict, idCheck)
00118         if extensionElement != None:
00119             self._checkExtensionTag (inputNode, extensionElement, attrName, attributeValue, returnDict, idCheck)
00120         elif listElement != None:
00121             self._checkListTag (inputNode, listElement, attrName, attributeValue, returnDict, idCheck)
00122         elif unionElement != None:
00123             self._checkUnionTag (inputNode, unionElement, attrName, attributeValue, returnDict, idCheck)
00124 
00125 
00126     ########################################
00127     # validate given value against base type
00128     #
00129     def checkBaseType (self, inputNode, xsdElement, attrName, attributeValue, returnDict, idCheck):
00130         baseType = xsdElement.getQNameAttribute("base")
00131         if baseType != NsNameTupleFactory(None):
00132             self.checkSimpleType (inputNode, attrName, baseType, attributeValue, returnDict, idCheck)
00133         else:
00134             baseTypeNode = xsdElement.getFirstChildNS(self.xsdNsURI, "simpleType")
00135             self.checkSimpleTypeDef (inputNode, baseTypeNode, attrName, attributeValue, returnDict, idCheck)
00136     
00137     
00138     ########################################
00139     # validate given value against restriction node
00140     #
00141     def _checkRestrictionTag (self, inputNode, xsdElement, attrName, attributeValue, returnDict, idCheck):
00142         savedAttrValue = attributeValue
00143         # first check against base type
00144         self.checkBaseType (inputNode, xsdElement, attrName, attributeValue, returnDict, idCheck)
00145 
00146         minExcl = xsdElement.getFirstChildNS(self.xsdNsURI, "minExclusive")
00147         minIncl = xsdElement.getFirstChildNS(self.xsdNsURI, "minInclusive")
00148         maxExcl = xsdElement.getFirstChildNS(self.xsdNsURI, "maxExclusive")
00149         maxIncl = xsdElement.getFirstChildNS(self.xsdNsURI, "maxInclusive")
00150 
00151         if minExcl != None:
00152             minExclReturnDict = {"BaseTypes":[], "primitiveType":None}
00153             minExclValue = minExcl.getAttribute("value")
00154             self.checkBaseType (inputNode, xsdElement, attrName, minExclValue, minExclReturnDict, idCheck=0)
00155             if returnDict.has_key("orderedValue") and minExclReturnDict.has_key("orderedValue"):
00156                 if returnDict["orderedValue"] <= minExclReturnDict["orderedValue"]:
00157                     raise SimpleTypeError ("Value of %s (%s) is <= minExclusive (%s)" %(repr(attrName), repr(attributeValue), repr(minExclValue)))
00158         elif minIncl != None:
00159             minInclReturnDict = {"BaseTypes":[], "primitiveType":None}
00160             minInclValue = minIncl.getAttribute("value")
00161             self.checkBaseType (inputNode, xsdElement, attrName, minInclValue, minInclReturnDict, idCheck=0)
00162             if returnDict.has_key("orderedValue") and minInclReturnDict.has_key("orderedValue"):
00163                 if returnDict["orderedValue"] < minInclReturnDict["orderedValue"]:
00164                     raise SimpleTypeError ("Value of %s (%s) is < minInclusive (%s)" %(repr(attrName), repr(attributeValue), repr(minInclValue)))
00165         if maxExcl != None:
00166             maxExclReturnDict = {"BaseTypes":[], "primitiveType":None}
00167             maxExclValue = maxExcl.getAttribute("value")
00168             self.checkBaseType (inputNode, xsdElement, attrName, maxExclValue, maxExclReturnDict, idCheck=0)
00169             if returnDict.has_key("orderedValue") and maxExclReturnDict.has_key("orderedValue"):
00170                 if returnDict["orderedValue"] >= maxExclReturnDict["orderedValue"]:
00171                     raise SimpleTypeError ("Value of %s (%s) is >= maxExclusive (%s)" %(repr(attrName), repr(attributeValue), repr(maxExclValue)))
00172         elif maxIncl != None:
00173             maxInclReturnDict = {"BaseTypes":[], "primitiveType":None}
00174             maxInclValue = maxIncl.getAttribute("value")
00175             self.checkBaseType (inputNode, xsdElement, attrName, maxInclValue, maxInclReturnDict, idCheck=0)
00176             if returnDict.has_key("orderedValue") and maxInclReturnDict.has_key("orderedValue"):
00177                 if returnDict["orderedValue"] > maxInclReturnDict["orderedValue"]:
00178                     raise SimpleTypeError ("Value of %s (%s) is > maxInclusive (%s)" %(repr(attrName), repr(attributeValue), repr(maxInclValue)))
00179 
00180         totalDigitsNode = xsdElement.getFirstChildNS(self.xsdNsURI, "totalDigits")
00181         if totalDigitsNode != None:
00182             orderedValueStr = repr(returnDict["orderedValue"])
00183             digits = re.findall("\d" ,orderedValueStr)
00184             if digits[0] == "0" and len(digits) > 1:
00185                 digits = digits[1:]
00186             totalDigitsValue = totalDigitsNode.getAttribute("value")
00187             if totalDigitsNode.getAttribute("fixed") == "true":
00188                 if len(digits) != string.atoi(totalDigitsValue):
00189                     raise SimpleTypeError ("Total number of digits != %s for %s (%s)" %(repr(totalDigitsValue), repr(attrName), repr(attributeValue)))
00190             else:
00191                 if len(digits) > string.atoi(totalDigitsValue):
00192                     raise SimpleTypeError ("Total number of digits > %s for %s (%s)" %(repr(totalDigitsValue), repr(attrName), repr(attributeValue)))
00193 
00194         fractionDigitsNode = xsdElement.getFirstChildNS(self.xsdNsURI, "fractionDigits")
00195         if fractionDigitsNode != None:
00196             orderedValueStr = repr(returnDict["orderedValue"])
00197             fractionDigitsValue = fractionDigitsNode.getAttribute("value")
00198             result = re.search("(?P<intDigits>\d*)(?P<dot>\.)(?P<fracDigits>\d+)", orderedValueStr)
00199             if result != None:
00200                 numberOfFracDigits = len (result.group('fracDigits'))
00201             else:
00202                 numberOfFracDigits = 0
00203             if fractionDigitsNode.getAttribute("fixed") == "true" and numberOfFracDigits != string.atoi(fractionDigitsValue):
00204                 raise SimpleTypeError ("Fraction number of digits != %s for %s (%s)" %(repr(fractionDigitsValue), repr(attrName), repr(attributeValue)))
00205             elif numberOfFracDigits > string.atoi(fractionDigitsValue):
00206                 raise SimpleTypeError ("Fraction number of digits > %s for %s (%s)" %(repr(fractionDigitsValue), repr(attrName), repr(attributeValue)))
00207 
00208         if returnDict.has_key("length"):
00209             lengthNode = xsdElement.getFirstChildNS(self.xsdNsURI, "length")
00210             if lengthNode != None:
00211                 length = string.atoi(lengthNode.getAttribute("value"))
00212                 if returnDict["length"] != length:
00213                     raise SimpleTypeError ("Length of %s (%s) must be %d!" %(repr(attrName), repr(attributeValue), length))
00214             minLengthNode = xsdElement.getFirstChildNS(self.xsdNsURI, "minLength")
00215             if minLengthNode != None:
00216                 minLength = string.atoi(minLengthNode.getAttribute("value"))
00217                 if returnDict["length"] < minLength:
00218                     raise SimpleTypeError ("Length of %s (%s) must be >= %d!" %(repr(attrName), repr(attributeValue), minLength))
00219             maxLengthNode = xsdElement.getFirstChildNS(self.xsdNsURI, "maxLength")
00220             if maxLengthNode != None:
00221                 maxLength = string.atoi(maxLengthNode.getAttribute("value"))
00222                 if returnDict["length"] > maxLength:
00223                     raise SimpleTypeError ("Length of %s (%s) must be <= %d!" %(repr(attrName), repr(attributeValue), maxLength))
00224 
00225         whiteSpace = xsdElement.getFirstChildNS(self.xsdNsURI, "whiteSpace")
00226         if whiteSpace != None:
00227             returnDict["wsAction"] = whiteSpace.getAttribute("value")
00228             if returnDict["wsAction"] == "replace":
00229                 normalizedValue = normalizeString(attributeValue)
00230                 if normalizedValue != attributeValue:
00231                     returnDict["adaptedAttrValue"] = normalizedValue
00232             elif returnDict["wsAction"] == "collapse":
00233                 collapsedValue = collapseString(attributeValue)
00234                 if collapsedValue != attributeValue:
00235                     returnDict["adaptedAttrValue"] = collapsedValue
00236 
00237         enumerationElementList = xsdElement.getChildrenNS(self.xsdNsURI, "enumeration")
00238         if enumerationElementList != []:
00239             if returnDict.has_key("orderedValue"):
00240                 attributeValue = returnDict["orderedValue"]
00241             elif returnDict.has_key("adaptedAttrValue"):
00242                 attributeValue = returnDict["adaptedAttrValue"]
00243 
00244             for enumeration in enumerationElementList:
00245                 enumReturnDict = {"BaseTypes":[], "primitiveType":None}
00246                 enumValue = enumeration["value"]
00247                 self.checkBaseType (inputNode, xsdElement, attrName, enumValue, enumReturnDict, idCheck=0)
00248                 if enumReturnDict.has_key("orderedValue"):
00249                     enumValue = enumReturnDict["orderedValue"]
00250                 elif enumReturnDict.has_key("adaptedAttrValue"):
00251                     enumValue = enumReturnDict["adaptedAttrValue"]
00252                 
00253                 if enumValue == attributeValue:
00254                     break
00255             else:
00256                 raise SimpleTypeError ("Enumeration value %s not allowed!" %repr(attributeValue))
00257 
00258         
00259         if returnDict.has_key("adaptedAttrValue"):
00260             attributeValue = returnDict["adaptedAttrValue"]
00261 
00262         patternMatch = 1
00263         notMatchedPatternList = []
00264         for patternNode in xsdElement.getChildrenNS(self.xsdNsURI, "pattern"):
00265             rePattern = patternNode.getAttribute("value")
00266             intRePattern = rePattern
00267             try:
00268                 intRePattern = substituteSpecialEscChars (intRePattern)
00269             except SyntaxError, errInst:
00270                 raise SimpleTypeError, str(errInst)
00271             patternMatch = self._matchesPattern (intRePattern, attributeValue)
00272 
00273             if patternMatch:
00274                 break
00275             else:
00276                 notMatchedPatternList.append(rePattern)
00277         
00278         if not patternMatch:
00279             try:
00280                 pattern = " nor ".join(notMatchedPatternList)
00281             except:
00282                 pattern = ""
00283             raise SimpleTypeError ("Value of attribute %s (%s) does not match pattern %s!" %(repr(attrName), repr(attributeValue), repr(pattern)))
00284 
00285 
00286     ########################################
00287     # checks if 'value' matches 'rePattern' completely
00288     #
00289     def _matchesPattern (self, intRePattern, attributeValue):
00290         completePatternMatch = 0
00291         try:
00292             regexObj = re.match(intRePattern, attributeValue, re.U)
00293             if regexObj and regexObj.end() == len(attributeValue):
00294                 completePatternMatch = 1
00295         except Exception:
00296             pass
00297         return completePatternMatch
00298 
00299 
00300     ########################################
00301     # validate given value against list node
00302     #
00303     def _checkListTag (self, inputNode, xsdElement, attrName, attributeValue, returnDict, idCheck):
00304         if attributeValue != "":
00305             itemType = xsdElement.getQNameAttribute ("itemType")
00306             # substitute multiple whitespace characters by a single ' '
00307             collapsedValue = collapseString(attributeValue)
00308             returnDict["wsAction"] = "collapse"
00309             returnDict["adaptedAttrValue"] = collapsedValue
00310 
00311             # divide up attributeValue => store it into list
00312             attributeList = string.split(collapsedValue, " ")
00313             for attrValue in attributeList:
00314                 elementReturnDict = {"BaseTypes":[], "primitiveType":None}
00315                 if itemType != (None, None):
00316                     self.checkSimpleType (inputNode, attrName, itemType, attrValue, elementReturnDict, idCheck)
00317                 else:
00318                     itemTypeNode = xsdElement.getFirstChildNS(self.xsdNsURI, "simpleType")
00319                     self.checkSimpleTypeDef (inputNode, itemTypeNode, attrName, attrValue, elementReturnDict, idCheck)
00320 
00321             returnDict["BaseTypes"].extend(elementReturnDict["BaseTypes"])
00322             returnDict["length"] = len(attributeList)
00323         else:
00324             returnDict["length"] = 0
00325 
00326 
00327     ########################################
00328     # validate given value against extension node
00329     #
00330     def _checkExtensionTag (self, inputNode, xsdElement, attrName, attributeValue, returnDict, idCheck):
00331         # first check against base type
00332         self.checkBaseType (inputNode, xsdElement, attrName, attributeValue, returnDict, idCheck)
00333 
00334 
00335     ########################################
00336     # validate given value against union node
00337     #
00338     def _checkUnionTag (self, inputNode, xsdElement, attrName, attributeValue, returnDict, idCheck):
00339         memberTypes = xsdElement.getAttribute ("memberTypes")
00340         if memberTypes != None:
00341             # substitute multiple whitespace characters by a single ' '
00342             # divide up attributeValue => store it into list
00343             for memberType in string.split(collapseString(memberTypes), " "):
00344                 try:
00345                     self.checkSimpleType (inputNode, attrName, xsdElement.qName2NsName(memberType, useDefaultNs=1), attributeValue, returnDict, idCheck)
00346                     return
00347                 except SimpleTypeError, errstr:
00348                     pass
00349 
00350         # memberTypes and additional type definitions is legal!
00351         for childSimpleType in xsdElement.getChildrenNS(self.xsdNsURI, "simpleType"):
00352             try:
00353                 self.checkSimpleTypeDef (inputNode, childSimpleType, attrName, attributeValue, returnDict, idCheck)
00354                 return
00355             except SimpleTypeError, errstr:
00356                 pass
00357 
00358         raise SimpleTypeError ("%s (%s) is no valid union member type!" %(repr(attrName), repr(attributeValue)))
00359 
00360 
00361 ###############################################################
00362 #  Base type check functions
00363 ###############################################################
00364 
00365 reDecimal      = re.compile("[+-]?[0-9]*\.?[0-9]+", re.U)
00366 reInteger      = re.compile("[+-]?[0-9]+", re.U)
00367 reDouble       = re.compile("([+-]?[0-9]*\.?[0-9]+([eE][+\-]?[0-9]+)?)|INF|-INF|NaN", re.U)
00368 reHexBinary    = re.compile("([a-fA-F0-9]{2})*", re.U)
00369 reBase64Binary = re.compile("(?P<validBits>[a-zA-Z0-9+/]*)={0,3}", re.U)
00370 reQName        = re.compile(substituteSpecialEscChars("\i\c*"), re.U)
00371 reDuration     = re.compile("-?P(?P<years>\d+Y)?(?P<months>\d+M)?(?P<days>\d+D)?(T(?P<hours>\d+H)?(?P<minutes>\d+M)?((?P<seconds>\d+)(?P<fracsec>\.\d+)?S)?)?", re.U)
00372 
00373 reDateTime     = re.compile("(?P<date>\d{4}-\d{2}-\d{2})T(?P<time>\d{2}:\d{2}:\d{2}(\.\d+)?)(?P<offset>Z|[+-]\d{2}:\d{2})?", re.U)
00374 reDate         = re.compile("\d{4}-\d{2}-\d{2}(?P<offset>Z|[+-]\d{2}:\d{2})?", re.U)
00375 reTime         = re.compile("(?P<time>\d{2}:\d{2}:\d{2})(?P<fracsec>\.\d+)?(?P<offset>Z|[+-]\d{2}:\d{2})?", re.U)
00376 reYearMonth    = re.compile("\d{4}-\d{2}(?P<offset>Z|[+-]\d{2}:\d{2})?", re.U)
00377 reMonthDay     = re.compile("--\d{2}-\d{2}(?P<offset>Z|[+-]\d{2}:\d{2})?", re.U)
00378 reYear         = re.compile("(?P<year>\d{1,4})(?P<offset>Z|[+-]\d{2}:\d{2})?", re.U)
00379 reMonth        = re.compile("--\d{2}(--)?(?P<offset>Z|[+-]\d{2}:\d{2})?", re.U)
00380 reDay          = re.compile("---\d{2}(?P<offset>Z|[+-]\d{2}:\d{2})?", re.U)
00381 
00382 
00383 def _checkAnySimpleType (inputNode, simpleType, attributeValue, returnDict):
00384     # TODO: Nothing to check??
00385     returnDict["length"] = len(attributeValue)
00386 
00387 def _checkStringType (inputNode, simpleType, attributeValue, returnDict):
00388     # TODO: all valid??
00389     returnDict["length"] = len(attributeValue)
00390 
00391 def _checkAnyUriType (inputNode, simpleType, attributeValue, returnDict):
00392     # TODO: any checks??
00393     if attributeValue[0:2] == '##':
00394         raise BaseTypeError("is not a valid URI!")
00395     returnDict["adaptedAttrValue"] = collapseString(attributeValue)
00396     returnDict["wsAction"] = "collapse"
00397     returnDict["length"] = len(attributeValue)
00398 
00399 def _checkDecimalType (inputNode, simpleType, attributeValue, returnDict):
00400     attributeValue = collapseString(attributeValue)
00401     regexObj = reDecimal.match(attributeValue)
00402     if not regexObj or regexObj.end() != len(attributeValue):
00403         raise BaseTypeError("is not a decimal value!")
00404     try:
00405         value = Decimal(attributeValue)
00406         returnDict["orderedValue"] = value.normalize()
00407         returnDict["adaptedAttrValue"] = attributeValue
00408         returnDict["wsAction"] = "collapse"
00409     except:
00410         raise BaseTypeError("is not a decimal value!")
00411 
00412 
00413 def _checkIntegerType (inputNode, simpleType, attributeValue, returnDict):
00414     attributeValue = collapseString(attributeValue)
00415     regexObj = reInteger.match(attributeValue)
00416     if not regexObj or regexObj.end() != len(attributeValue):
00417         raise BaseTypeError("is not an integer value!")
00418     try:
00419         returnDict["orderedValue"] = Decimal(attributeValue)
00420         returnDict["adaptedAttrValue"] = attributeValue
00421         returnDict["wsAction"] = "collapse"
00422     except:
00423         raise BaseTypeError("is out of range for validation!")
00424 
00425 
00426 def _checkFloatType (inputNode, simpleType, attributeValue, returnDict):
00427     attributeValue = collapseString(attributeValue)
00428     if attributeValue not in ("INF", "-INF", "NaN"):
00429         try:
00430             value = float(attributeValue)
00431             returnDict["orderedValue"] = value
00432             returnDict["adaptedAttrValue"] = attributeValue
00433             returnDict["wsAction"] = "collapse"
00434         except:
00435             raise BaseTypeError("is not a float value!")
00436 
00437 def _checkDoubleType (inputNode, simpleType, attributeValue, returnDict):
00438     attributeValue = collapseString(attributeValue)
00439     regexObj = reDouble.match(attributeValue)
00440     if not regexObj or regexObj.end() != len(attributeValue):
00441         raise BaseTypeError("is not a double value!")
00442     try:
00443         value = Decimal(attributeValue)
00444         returnDict["orderedValue"] = value.normalize()
00445         returnDict["adaptedAttrValue"] = attributeValue
00446         returnDict["wsAction"] = "collapse"
00447     except:
00448         raise BaseTypeError("is not a double value!")
00449 
00450 def _checkHexBinaryType (inputNode, simpleType, attributeValue, returnDict):
00451     attributeValue = removeWhitespaces(attributeValue)
00452     regexObj = reHexBinary.match(attributeValue)
00453     if not regexObj or regexObj.end() != len(attributeValue):
00454         raise BaseTypeError("is not a hexBinary value (each byte is represented by 2 characters)!")
00455     returnDict["length"] = len(attributeValue) / 2
00456     returnDict["adaptedAttrValue"] = attributeValue
00457     returnDict["wsAction"] = "collapse"
00458 
00459 def _checkBase64BinaryType (inputNode, simpleType, attributeValue, returnDict):
00460     attributeValue = collapseString(attributeValue)
00461     regexObj = reBase64Binary.match(attributeValue)
00462     if not regexObj or regexObj.end() != len(attributeValue):
00463         raise BaseTypeError("is not a base64Binary value (6 bits are represented by 1 character)!")
00464     returnDict["length"] = (len(regexObj.group("validBits")) * 6) / 8
00465     returnDict["adaptedAttrValue"] = attributeValue
00466     returnDict["wsAction"] = "collapse"
00467 
00468 def _checkBooleanType (inputNode, simpleType, attributeValue, returnDict):
00469     attributeValue = collapseString(attributeValue)
00470     if attributeValue not in ("true", "false", "1", "0"):
00471         raise BaseTypeError("is not a boolean value!")
00472     if attributeValue in ("true", "1"):
00473         returnDict["orderedValue"] = "__BOOLEAN_TRUE__"
00474     else:
00475         returnDict["orderedValue"] = "__BOOLEAN_FALSE__"
00476     returnDict["adaptedAttrValue"] = attributeValue
00477     returnDict["wsAction"] = "collapse"
00478 
00479 def _checkQNameType (inputNode, simpleType, attributeValue, returnDict):
00480     attributeValue = collapseString(attributeValue)
00481     regexObj = reQName.match(attributeValue)
00482     if not regexObj or regexObj.end() != len(attributeValue):
00483         raise BaseTypeError("is not a QName!")
00484     
00485     try:
00486         inputNode.getNamespace(attributeValue)
00487     except LookupError:
00488         raise BaseTypeError("is not a valid QName (namespace prefix unknown)!")
00489 
00490     returnDict["length"] = len(attributeValue)
00491     returnDict["orderedValue"] = inputNode.qName2NsName(attributeValue, useDefaultNs=1)
00492     returnDict["adaptedAttrValue"] = attributeValue
00493     returnDict["wsAction"] = "collapse"
00494 
00495 def _checkDurationType (inputNode, simpleType, attributeValue, returnDict):
00496     attributeValue = collapseString(attributeValue)
00497     regexObj = reDuration.match(attributeValue)
00498     if not regexObj or regexObj.end() != len(attributeValue) or attributeValue[-1] == "T" or attributeValue[-1] == "P":
00499         raise BaseTypeError("is not a valid duration value!")
00500     sign = ""
00501     if attributeValue[0] == "-": sign = "-"
00502     days = 0
00503     seconds = 0
00504     microseconds = 0
00505     if regexObj.group("years") != None:
00506         days = days + (int(sign + regexObj.group("years")[:-1]) * 365)
00507     if regexObj.group("months") != None:
00508         days = days + (int(sign + regexObj.group("months")[:-1]) * 30)
00509     if regexObj.group("days") != None:
00510         days = days + int(sign + regexObj.group("days")[:-1])
00511     if regexObj.group("hours") != None:
00512         seconds = seconds + int(sign + regexObj.group("hours")[:-1]) * 3600
00513     if regexObj.group("minutes") != None:
00514         seconds = seconds + (int(sign + regexObj.group("minutes")[:-1]) * 60)
00515     if regexObj.group("seconds") != None:
00516         seconds = seconds + int(sign + regexObj.group("seconds"))
00517     if regexObj.group("fracsec") != None:
00518         microseconds = int(Decimal(sign + regexObj.group("fracsec")) * 1000000)
00519     try:
00520         timeDeltaObj = datetime.timedelta(days=days, seconds=seconds, microseconds=microseconds)
00521     except ValueError, errstr:
00522         raise BaseTypeError("is invalid (%s)!" %(errstr))
00523     returnDict["orderedValue"] = timeDeltaObj
00524     returnDict["adaptedAttrValue"] = attributeValue
00525     returnDict["wsAction"] = "collapse"
00526     
00527 def _checkDateTimeType (inputNode, simpleType, attributeValue, returnDict):
00528     attributeValue = collapseString(attributeValue)
00529     regexObj = reDateTime.match(attributeValue)
00530     if not regexObj or regexObj.end() != len(attributeValue):
00531         raise BaseTypeError("is not a dateTime value!")
00532     date = regexObj.group("date")
00533     time = regexObj.group("time")
00534     offset = regexObj.group("offset")
00535     try:
00536         if offset != None:
00537             tz = TimezoneFixedOffset(offset)
00538         else:
00539             tz = None
00540         dtObj = datetime.datetime(int(date[0:4]),int(date[5:7]),int(date[8:10]),
00541                                   int(time[0:2]),int(time[3:5]),int(time[6:8]), 0, tz)
00542     except ValueError, errstr:
00543         raise BaseTypeError("is invalid (%s)!" %(errstr))
00544     returnDict["orderedValue"] = dtObj
00545     returnDict["adaptedAttrValue"] = attributeValue
00546     returnDict["wsAction"] = "collapse"
00547     
00548 def _checkDateType (inputNode, simpleType, attributeValue, returnDict):
00549     attributeValue = collapseString(attributeValue)
00550     regexObj = reDate.match(attributeValue)
00551     if not regexObj or regexObj.end() != len(attributeValue):
00552         raise BaseTypeError("is not a date value!")
00553     try:
00554         dateObj = datetime.date(int(attributeValue[0:4]),int(attributeValue[5:7]),int(attributeValue[8:10]))
00555     except ValueError, errstr:
00556         raise BaseTypeError("is invalid (%s)!" %(errstr))
00557     returnDict["orderedValue"] = dateObj
00558     returnDict["adaptedAttrValue"] = attributeValue
00559     returnDict["wsAction"] = "collapse"
00560     
00561 def _checkTimeType (inputNode, simpleType, attributeValue, returnDict):
00562     attributeValue = collapseString(attributeValue)
00563     regexObj = reTime.match(attributeValue)
00564     if not regexObj or regexObj.end() != len(attributeValue):
00565         raise BaseTypeError("is not a time value!")
00566     time = regexObj.group("time")
00567     fracsec = regexObj.group("fracsec")
00568     offset = regexObj.group("offset")
00569     try:
00570         if offset != None:
00571             tz = TimezoneFixedOffset(offset)
00572         else:
00573             tz = None
00574         if fracsec != None:
00575             fracSec = int(fracsec[1:])
00576         else:
00577             fracSec = 0
00578         timeObj = datetime.time(int(time[0:2]),int(time[3:5]),int(time[6:8]), fracSec, tz)
00579     except ValueError, errstr:
00580         raise BaseTypeError("is invalid (%s)!" %(errstr))
00581     returnDict["orderedValue"] = timeObj
00582     returnDict["adaptedAttrValue"] = attributeValue
00583     returnDict["wsAction"] = "collapse"
00584     
00585 def _checkYearMonth (inputNode, simpleType, attributeValue, returnDict):
00586     attributeValue = collapseString(attributeValue)
00587     regexObj = reYearMonth.match(attributeValue)
00588     if not regexObj or regexObj.end() != len(attributeValue):
00589         raise BaseTypeError("is not a gYearMonth value!")
00590     try:
00591         dateObj = datetime.date(int(attributeValue[0:4]),int(attributeValue[5:7]),1)
00592     except ValueError, errstr:
00593         raise BaseTypeError("is invalid (%s)!" %(errstr))
00594     returnDict["orderedValue"] = dateObj
00595     returnDict["adaptedAttrValue"] = attributeValue
00596     returnDict["wsAction"] = "collapse"
00597 
00598 def _checkMonthDay (inputNode, simpleType, attributeValue, returnDict):
00599     attributeValue = collapseString(attributeValue)
00600     regexObj = reMonthDay.match(attributeValue)
00601     if not regexObj or regexObj.end() != len(attributeValue):
00602         raise BaseTypeError("is not a gMonthDay value!")
00603     try:
00604         dateObj = datetime.date(2004, int(attributeValue[2:4]),int(attributeValue[5:7]))
00605     except ValueError, errstr:
00606         raise BaseTypeError("is invalid (%s)!" %(errstr))
00607     returnDict["orderedValue"] = dateObj
00608     returnDict["adaptedAttrValue"] = attributeValue
00609     returnDict["wsAction"] = "collapse"
00610     
00611 def _checkYear (inputNode, simpleType, attributeValue, returnDict):
00612     attributeValue = collapseString(attributeValue)
00613     regexObj = reYear.match(attributeValue)
00614     if not regexObj or regexObj.end() != len(attributeValue or regexObj.group("year") == None):
00615         raise BaseTypeError("is not a gYear value (1)!")
00616     try:
00617         year = int(regexObj.group("year"))
00618         if year < 1 or year > 9999:
00619             raise BaseTypeError("is not a valid gYear value!")
00620     except:
00621         raise BaseTypeError("is not a gYear value!")
00622     returnDict["orderedValue"] = year
00623     returnDict["adaptedAttrValue"] = attributeValue
00624     returnDict["wsAction"] = "collapse"
00625 
00626 def _checkMonth (inputNode, simpleType, attributeValue, returnDict):
00627     attributeValue = collapseString(attributeValue)
00628     regexObj = reMonth.match(attributeValue)
00629     if not regexObj or regexObj.end() != len(attributeValue):
00630         raise BaseTypeError("is not a gMonth value!")
00631     month = int(attributeValue[2:4])
00632     if month < 1 or month > 12:
00633         raise BaseTypeError("is invalid (month must be in 1..12)!")
00634     returnDict["orderedValue"] = month
00635     returnDict["adaptedAttrValue"] = attributeValue
00636     returnDict["wsAction"] = "collapse"
00637 
00638 def _checkDay (inputNode, simpleType, attributeValue, returnDict):
00639     attributeValue = collapseString(attributeValue)
00640     regexObj = reDay.match(attributeValue)
00641     if not regexObj or regexObj.end() != len(attributeValue):
00642         raise BaseTypeError("is not a gDay value!")
00643     day = int(attributeValue[3:5])
00644     if day < 1 or day > 31:
00645         raise BaseTypeError("is invalid (day must be in 1..31)!")
00646     returnDict["orderedValue"] = day
00647     returnDict["adaptedAttrValue"] = attributeValue
00648     returnDict["wsAction"] = "collapse"
00649 
00650 ########################################
00651 # timezone class
00652 #
00653 class TimezoneFixedOffset(datetime.tzinfo):
00654     def __init__(self, offset):
00655         if offset == "Z":
00656             self.__offset = datetime.timedelta(0)
00657         else:
00658             self.__offset = datetime.timedelta(hours=int(offset[0:3]), 
00659                                                minutes=int(offset[0] + offset[4:5]))
00660 
00661     def utcoffset(self, dt):
00662         return self.__offset
00663     def tzname(self, dt):
00664         return None
00665 
00666     def dst(self, dt):
00667         return datetime.timedelta(0)
00668 
00669 ########################################
00670 # define own exception for XML schema validation errors
00671 #
00672 class SimpleTypeError (StandardError):
00673     pass
00674 
00675 class BaseTypeError (StandardError):
00676     pass
00677 
00678 
00679 ########################################
00680 # Base type dictionaries
00681 #
00682 _suppBaseTypeDict = {(XSD_NAMESPACE, "anySimpleType"):    _checkAnySimpleType,
00683                      (XSD_NAMESPACE, "string"):           _checkStringType,
00684                      (XSD_NAMESPACE, "anyURI"):           _checkAnyUriType,
00685                      (XSD_NAMESPACE, "decimal"):          _checkDecimalType,
00686                      (XSD_NAMESPACE, "integer"):          _checkIntegerType,
00687                      (XSD_NAMESPACE, "float"):            _checkFloatType,
00688                      (XSD_NAMESPACE, "double"):           _checkDoubleType,
00689                      (XSD_NAMESPACE, "hexBinary"):        _checkHexBinaryType,
00690                      (XSD_NAMESPACE, "base64Binary"):     _checkBase64BinaryType,
00691                      (XSD_NAMESPACE, "boolean"):          _checkBooleanType,
00692                      (XSD_NAMESPACE, "QName"):            _checkQNameType,
00693                      (XSD_NAMESPACE, "NOTATION"):         _checkQNameType,
00694                      (XSD_NAMESPACE, "duration"):         _checkDurationType,
00695                      (XSD_NAMESPACE, "dateTime"):         _checkDateTimeType,
00696                      (XSD_NAMESPACE, "date"):             _checkDateType,
00697                      (XSD_NAMESPACE, "time"):             _checkTimeType,
00698                      (XSD_NAMESPACE, "gYearMonth"):       _checkYearMonth,
00699                      (XSD_NAMESPACE, "gMonthDay"):        _checkMonthDay,
00700                      (XSD_NAMESPACE, "gYear"):            _checkYear,
00701                      (XSD_NAMESPACE, "gMonth"):           _checkMonth,
00702                      (XSD_NAMESPACE, "gDay"):             _checkDay,
00703                     }
00704 


mavlink
Author(s): Lorenz Meier
autogenerated on Sun May 22 2016 04:05:43