PageRenderTime 68ms CodeModel.GetById 25ms RepoModel.GetById 1ms app.codeStats 0ms

/pymavlink/generator/lib/minixsv/xsvalSimpleTypes.py

https://github.com/dagoodma/mavlink
Python | 704 lines | 618 code | 29 blank | 57 comment | 79 complexity | abc470baddd1e5d7056f968577d70be4 MD5 | raw file
Possible License(s): LGPL-3.0, BSD-3-Clause
  1. #
  2. # minixsv, Release 0.9.0
  3. # file: xsvalSimpleTypes.py
  4. #
  5. # class for validation of XML schema simple types
  6. #
  7. # history:
  8. # 2004-09-09 rl created
  9. # 2006-08-18 rl W3C testsuite passed for supported features
  10. # 2007-05-24 rl Features for release 0.8 added, some bugs fixed
  11. #
  12. # Copyright (c) 2004-2007 by Roland Leuthe. All rights reserved.
  13. #
  14. # --------------------------------------------------------------------
  15. # The minixsv XML schema validator is
  16. #
  17. # Copyright (c) 2004-2007 by Roland Leuthe
  18. #
  19. # By obtaining, using, and/or copying this software and/or its
  20. # associated documentation, you agree that you have read, understood,
  21. # and will comply with the following terms and conditions:
  22. #
  23. # Permission to use, copy, modify, and distribute this software and
  24. # its associated documentation for any purpose and without fee is
  25. # hereby granted, provided that the above copyright notice appears in
  26. # all copies, and that both that copyright notice and this permission
  27. # notice appear in supporting documentation, and that the name of
  28. # the author not be used in advertising or publicity
  29. # pertaining to distribution of the software without specific, written
  30. # prior permission.
  31. #
  32. # THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
  33. # TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT-
  34. # ABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR
  35. # BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY
  36. # DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
  37. # WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
  38. # ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
  39. # OF THIS SOFTWARE.
  40. # --------------------------------------------------------------------
  41. import sys
  42. import string
  43. import re
  44. import datetime
  45. from decimal import Decimal
  46. from ..genxmlif.xmlifUtils import removeWhitespaces, collapseString, normalizeString, NsNameTupleFactory
  47. from ..minixsv import XSD_NAMESPACE
  48. from xsvalUtils import substituteSpecialEscChars
  49. ###################################################
  50. # Validator class for simple types
  51. ###################################################
  52. class XsSimpleTypeVal:
  53. def __init__ (self, parent):
  54. self.parent = parent
  55. self.xmlIf = parent.xmlIf
  56. self.xsdNsURI = parent.xsdNsURI
  57. self.xsdIdDict = parent.xsdIdDict
  58. self.xsdIdRefDict = parent.xsdIdRefDict
  59. def unlink (self):
  60. self.parent = None
  61. ########################################
  62. # validate given value against simpleType
  63. #
  64. def checkSimpleType (self, inputNode, attrName, typeName, attributeValue, returnDict, idCheck):
  65. returnDict["adaptedAttrValue"] = attributeValue
  66. returnDict["BaseTypes"].append(str(typeName))
  67. if _suppBaseTypeDict.has_key(typeName):
  68. try:
  69. _suppBaseTypeDict[typeName] (inputNode, typeName, attributeValue, returnDict)
  70. returnDict["primitiveType"] = typeName
  71. except BaseTypeError, errstr:
  72. raise SimpleTypeError("Value of %s (%s) %s" %(repr(attrName), repr(attributeValue), errstr))
  73. elif self.parent.xsdTypeDict.has_key(typeName):
  74. typedefNode = self.parent.xsdTypeDict[typeName]
  75. if typedefNode.getNsName() == (XSD_NAMESPACE, "simpleType"):
  76. self.checkSimpleTypeDef (inputNode, typedefNode, attrName, attributeValue, returnDict, idCheck)
  77. elif (typedefNode.getNsName() == (XSD_NAMESPACE, "complexType") and
  78. typedefNode.getFirstChild().getNsName() == (XSD_NAMESPACE, "simpleContent")):
  79. self.checkSimpleTypeDef (inputNode, typedefNode.getFirstChild(), attrName, attributeValue, returnDict, idCheck)
  80. elif typedefNode.getAttribute("mixed") == "true":
  81. self.checkSimpleType (inputNode, attrName, (XSD_NAMESPACE, "string"), attributeValue, returnDict, idCheck)
  82. elif typeName != (XSD_NAMESPACE, "anyType"):
  83. raise SimpleTypeError("Attribute %s requires a simple type!" %repr(attrName))
  84. if idCheck:
  85. adaptedAttrValue = returnDict["adaptedAttrValue"]
  86. if typeName == (XSD_NAMESPACE, "ID"):
  87. if not self.xsdIdDict.has_key(adaptedAttrValue):
  88. self.xsdIdDict[adaptedAttrValue] = inputNode
  89. else:
  90. raise SimpleTypeError("There are multiple occurences of ID value %s!" %repr(adaptedAttrValue))
  91. if typeName == (XSD_NAMESPACE, "IDREF"):
  92. self.xsdIdRefDict[adaptedAttrValue] = inputNode
  93. else:
  94. # TODO: Fehler im XSD-File => Check muss an anderer Stelle erfolgen
  95. raise SimpleTypeError("%s uses unknown type %s!" %(repr(attrName), repr(typeName)))
  96. ########################################
  97. # validate given value against simpleType node
  98. #
  99. def checkSimpleTypeDef (self, inputNode, xsdElement, attrName, attributeValue, returnDict, idCheck):
  100. returnDict["adaptedAttrValue"] = attributeValue
  101. restrictionElement = xsdElement.getFirstChildNS(self.xsdNsURI, "restriction")
  102. extensionElement = xsdElement.getFirstChildNS(self.xsdNsURI, "extension")
  103. listElement = xsdElement.getFirstChildNS(self.xsdNsURI, "list")
  104. unionElement = xsdElement.getFirstChildNS(self.xsdNsURI, "union")
  105. if restrictionElement != None:
  106. self._checkRestrictionTag (inputNode, restrictionElement, attrName, attributeValue, returnDict, idCheck)
  107. if extensionElement != None:
  108. self._checkExtensionTag (inputNode, extensionElement, attrName, attributeValue, returnDict, idCheck)
  109. elif listElement != None:
  110. self._checkListTag (inputNode, listElement, attrName, attributeValue, returnDict, idCheck)
  111. elif unionElement != None:
  112. self._checkUnionTag (inputNode, unionElement, attrName, attributeValue, returnDict, idCheck)
  113. ########################################
  114. # validate given value against base type
  115. #
  116. def checkBaseType (self, inputNode, xsdElement, attrName, attributeValue, returnDict, idCheck):
  117. baseType = xsdElement.getQNameAttribute("base")
  118. if baseType != NsNameTupleFactory(None):
  119. self.checkSimpleType (inputNode, attrName, baseType, attributeValue, returnDict, idCheck)
  120. else:
  121. baseTypeNode = xsdElement.getFirstChildNS(self.xsdNsURI, "simpleType")
  122. self.checkSimpleTypeDef (inputNode, baseTypeNode, attrName, attributeValue, returnDict, idCheck)
  123. ########################################
  124. # validate given value against restriction node
  125. #
  126. def _checkRestrictionTag (self, inputNode, xsdElement, attrName, attributeValue, returnDict, idCheck):
  127. savedAttrValue = attributeValue
  128. # first check against base type
  129. self.checkBaseType (inputNode, xsdElement, attrName, attributeValue, returnDict, idCheck)
  130. minExcl = xsdElement.getFirstChildNS(self.xsdNsURI, "minExclusive")
  131. minIncl = xsdElement.getFirstChildNS(self.xsdNsURI, "minInclusive")
  132. maxExcl = xsdElement.getFirstChildNS(self.xsdNsURI, "maxExclusive")
  133. maxIncl = xsdElement.getFirstChildNS(self.xsdNsURI, "maxInclusive")
  134. if minExcl != None:
  135. minExclReturnDict = {"BaseTypes":[], "primitiveType":None}
  136. minExclValue = minExcl.getAttribute("value")
  137. self.checkBaseType (inputNode, xsdElement, attrName, minExclValue, minExclReturnDict, idCheck=0)
  138. if returnDict.has_key("orderedValue") and minExclReturnDict.has_key("orderedValue"):
  139. if returnDict["orderedValue"] <= minExclReturnDict["orderedValue"]:
  140. raise SimpleTypeError ("Value of %s (%s) is <= minExclusive (%s)" %(repr(attrName), repr(attributeValue), repr(minExclValue)))
  141. elif minIncl != None:
  142. minInclReturnDict = {"BaseTypes":[], "primitiveType":None}
  143. minInclValue = minIncl.getAttribute("value")
  144. self.checkBaseType (inputNode, xsdElement, attrName, minInclValue, minInclReturnDict, idCheck=0)
  145. if returnDict.has_key("orderedValue") and minInclReturnDict.has_key("orderedValue"):
  146. if returnDict["orderedValue"] < minInclReturnDict["orderedValue"]:
  147. raise SimpleTypeError ("Value of %s (%s) is < minInclusive (%s)" %(repr(attrName), repr(attributeValue), repr(minInclValue)))
  148. if maxExcl != None:
  149. maxExclReturnDict = {"BaseTypes":[], "primitiveType":None}
  150. maxExclValue = maxExcl.getAttribute("value")
  151. self.checkBaseType (inputNode, xsdElement, attrName, maxExclValue, maxExclReturnDict, idCheck=0)
  152. if returnDict.has_key("orderedValue") and maxExclReturnDict.has_key("orderedValue"):
  153. if returnDict["orderedValue"] >= maxExclReturnDict["orderedValue"]:
  154. raise SimpleTypeError ("Value of %s (%s) is >= maxExclusive (%s)" %(repr(attrName), repr(attributeValue), repr(maxExclValue)))
  155. elif maxIncl != None:
  156. maxInclReturnDict = {"BaseTypes":[], "primitiveType":None}
  157. maxInclValue = maxIncl.getAttribute("value")
  158. self.checkBaseType (inputNode, xsdElement, attrName, maxInclValue, maxInclReturnDict, idCheck=0)
  159. if returnDict.has_key("orderedValue") and maxInclReturnDict.has_key("orderedValue"):
  160. if returnDict["orderedValue"] > maxInclReturnDict["orderedValue"]:
  161. raise SimpleTypeError ("Value of %s (%s) is > maxInclusive (%s)" %(repr(attrName), repr(attributeValue), repr(maxInclValue)))
  162. totalDigitsNode = xsdElement.getFirstChildNS(self.xsdNsURI, "totalDigits")
  163. if totalDigitsNode != None:
  164. orderedValueStr = repr(returnDict["orderedValue"])
  165. digits = re.findall("\d" ,orderedValueStr)
  166. if digits[0] == "0" and len(digits) > 1:
  167. digits = digits[1:]
  168. totalDigitsValue = totalDigitsNode.getAttribute("value")
  169. if totalDigitsNode.getAttribute("fixed") == "true":
  170. if len(digits) != string.atoi(totalDigitsValue):
  171. raise SimpleTypeError ("Total number of digits != %s for %s (%s)" %(repr(totalDigitsValue), repr(attrName), repr(attributeValue)))
  172. else:
  173. if len(digits) > string.atoi(totalDigitsValue):
  174. raise SimpleTypeError ("Total number of digits > %s for %s (%s)" %(repr(totalDigitsValue), repr(attrName), repr(attributeValue)))
  175. fractionDigitsNode = xsdElement.getFirstChildNS(self.xsdNsURI, "fractionDigits")
  176. if fractionDigitsNode != None:
  177. orderedValueStr = repr(returnDict["orderedValue"])
  178. fractionDigitsValue = fractionDigitsNode.getAttribute("value")
  179. result = re.search("(?P<intDigits>\d*)(?P<dot>\.)(?P<fracDigits>\d+)", orderedValueStr)
  180. if result != None:
  181. numberOfFracDigits = len (result.group('fracDigits'))
  182. else:
  183. numberOfFracDigits = 0
  184. if fractionDigitsNode.getAttribute("fixed") == "true" and numberOfFracDigits != string.atoi(fractionDigitsValue):
  185. raise SimpleTypeError ("Fraction number of digits != %s for %s (%s)" %(repr(fractionDigitsValue), repr(attrName), repr(attributeValue)))
  186. elif numberOfFracDigits > string.atoi(fractionDigitsValue):
  187. raise SimpleTypeError ("Fraction number of digits > %s for %s (%s)" %(repr(fractionDigitsValue), repr(attrName), repr(attributeValue)))
  188. if returnDict.has_key("length"):
  189. lengthNode = xsdElement.getFirstChildNS(self.xsdNsURI, "length")
  190. if lengthNode != None:
  191. length = string.atoi(lengthNode.getAttribute("value"))
  192. if returnDict["length"] != length:
  193. raise SimpleTypeError ("Length of %s (%s) must be %d!" %(repr(attrName), repr(attributeValue), length))
  194. minLengthNode = xsdElement.getFirstChildNS(self.xsdNsURI, "minLength")
  195. if minLengthNode != None:
  196. minLength = string.atoi(minLengthNode.getAttribute("value"))
  197. if returnDict["length"] < minLength:
  198. raise SimpleTypeError ("Length of %s (%s) must be >= %d!" %(repr(attrName), repr(attributeValue), minLength))
  199. maxLengthNode = xsdElement.getFirstChildNS(self.xsdNsURI, "maxLength")
  200. if maxLengthNode != None:
  201. maxLength = string.atoi(maxLengthNode.getAttribute("value"))
  202. if returnDict["length"] > maxLength:
  203. raise SimpleTypeError ("Length of %s (%s) must be <= %d!" %(repr(attrName), repr(attributeValue), maxLength))
  204. whiteSpace = xsdElement.getFirstChildNS(self.xsdNsURI, "whiteSpace")
  205. if whiteSpace != None:
  206. returnDict["wsAction"] = whiteSpace.getAttribute("value")
  207. if returnDict["wsAction"] == "replace":
  208. normalizedValue = normalizeString(attributeValue)
  209. if normalizedValue != attributeValue:
  210. returnDict["adaptedAttrValue"] = normalizedValue
  211. elif returnDict["wsAction"] == "collapse":
  212. collapsedValue = collapseString(attributeValue)
  213. if collapsedValue != attributeValue:
  214. returnDict["adaptedAttrValue"] = collapsedValue
  215. enumerationElementList = xsdElement.getChildrenNS(self.xsdNsURI, "enumeration")
  216. if enumerationElementList != []:
  217. if returnDict.has_key("orderedValue"):
  218. attributeValue = returnDict["orderedValue"]
  219. elif returnDict.has_key("adaptedAttrValue"):
  220. attributeValue = returnDict["adaptedAttrValue"]
  221. for enumeration in enumerationElementList:
  222. enumReturnDict = {"BaseTypes":[], "primitiveType":None}
  223. enumValue = enumeration["value"]
  224. self.checkBaseType (inputNode, xsdElement, attrName, enumValue, enumReturnDict, idCheck=0)
  225. if enumReturnDict.has_key("orderedValue"):
  226. enumValue = enumReturnDict["orderedValue"]
  227. elif enumReturnDict.has_key("adaptedAttrValue"):
  228. enumValue = enumReturnDict["adaptedAttrValue"]
  229. if enumValue == attributeValue:
  230. break
  231. else:
  232. raise SimpleTypeError ("Enumeration value %s not allowed!" %repr(attributeValue))
  233. if returnDict.has_key("adaptedAttrValue"):
  234. attributeValue = returnDict["adaptedAttrValue"]
  235. patternMatch = 1
  236. notMatchedPatternList = []
  237. for patternNode in xsdElement.getChildrenNS(self.xsdNsURI, "pattern"):
  238. rePattern = patternNode.getAttribute("value")
  239. intRePattern = rePattern
  240. try:
  241. intRePattern = substituteSpecialEscChars (intRePattern)
  242. except SyntaxError, errInst:
  243. raise SimpleTypeError, str(errInst)
  244. patternMatch = self._matchesPattern (intRePattern, attributeValue)
  245. if patternMatch:
  246. break
  247. else:
  248. notMatchedPatternList.append(rePattern)
  249. if not patternMatch:
  250. try:
  251. pattern = " nor ".join(notMatchedPatternList)
  252. except:
  253. pattern = ""
  254. raise SimpleTypeError ("Value of attribute %s (%s) does not match pattern %s!" %(repr(attrName), repr(attributeValue), repr(pattern)))
  255. ########################################
  256. # checks if 'value' matches 'rePattern' completely
  257. #
  258. def _matchesPattern (self, intRePattern, attributeValue):
  259. completePatternMatch = 0
  260. try:
  261. regexObj = re.match(intRePattern, attributeValue, re.U)
  262. if regexObj and regexObj.end() == len(attributeValue):
  263. completePatternMatch = 1
  264. except Exception:
  265. pass
  266. return completePatternMatch
  267. ########################################
  268. # validate given value against list node
  269. #
  270. def _checkListTag (self, inputNode, xsdElement, attrName, attributeValue, returnDict, idCheck):
  271. if attributeValue != "":
  272. itemType = xsdElement.getQNameAttribute ("itemType")
  273. # substitute multiple whitespace characters by a single ' '
  274. collapsedValue = collapseString(attributeValue)
  275. returnDict["wsAction"] = "collapse"
  276. returnDict["adaptedAttrValue"] = collapsedValue
  277. # divide up attributeValue => store it into list
  278. attributeList = string.split(collapsedValue, " ")
  279. for attrValue in attributeList:
  280. elementReturnDict = {"BaseTypes":[], "primitiveType":None}
  281. if itemType != (None, None):
  282. self.checkSimpleType (inputNode, attrName, itemType, attrValue, elementReturnDict, idCheck)
  283. else:
  284. itemTypeNode = xsdElement.getFirstChildNS(self.xsdNsURI, "simpleType")
  285. self.checkSimpleTypeDef (inputNode, itemTypeNode, attrName, attrValue, elementReturnDict, idCheck)
  286. returnDict["BaseTypes"].extend(elementReturnDict["BaseTypes"])
  287. returnDict["length"] = len(attributeList)
  288. else:
  289. returnDict["length"] = 0
  290. ########################################
  291. # validate given value against extension node
  292. #
  293. def _checkExtensionTag (self, inputNode, xsdElement, attrName, attributeValue, returnDict, idCheck):
  294. # first check against base type
  295. self.checkBaseType (inputNode, xsdElement, attrName, attributeValue, returnDict, idCheck)
  296. ########################################
  297. # validate given value against union node
  298. #
  299. def _checkUnionTag (self, inputNode, xsdElement, attrName, attributeValue, returnDict, idCheck):
  300. memberTypes = xsdElement.getAttribute ("memberTypes")
  301. if memberTypes != None:
  302. # substitute multiple whitespace characters by a single ' '
  303. # divide up attributeValue => store it into list
  304. for memberType in string.split(collapseString(memberTypes), " "):
  305. try:
  306. self.checkSimpleType (inputNode, attrName, xsdElement.qName2NsName(memberType, useDefaultNs=1), attributeValue, returnDict, idCheck)
  307. return
  308. except SimpleTypeError, errstr:
  309. pass
  310. # memberTypes and additional type definitions is legal!
  311. for childSimpleType in xsdElement.getChildrenNS(self.xsdNsURI, "simpleType"):
  312. try:
  313. self.checkSimpleTypeDef (inputNode, childSimpleType, attrName, attributeValue, returnDict, idCheck)
  314. return
  315. except SimpleTypeError, errstr:
  316. pass
  317. raise SimpleTypeError ("%s (%s) is no valid union member type!" %(repr(attrName), repr(attributeValue)))
  318. ###############################################################
  319. # Base type check functions
  320. ###############################################################
  321. reDecimal = re.compile("[+-]?[0-9]*\.?[0-9]+", re.U)
  322. reInteger = re.compile("[+-]?[0-9]+", re.U)
  323. reDouble = re.compile("([+-]?[0-9]*\.?[0-9]+([eE][+\-]?[0-9]+)?)|INF|-INF|NaN", re.U)
  324. reHexBinary = re.compile("([a-fA-F0-9]{2})*", re.U)
  325. reBase64Binary = re.compile("(?P<validBits>[a-zA-Z0-9+/]*)={0,3}", re.U)
  326. reQName = re.compile(substituteSpecialEscChars("\i\c*"), re.U)
  327. 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)
  328. 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)
  329. reDate = re.compile("\d{4}-\d{2}-\d{2}(?P<offset>Z|[+-]\d{2}:\d{2})?", re.U)
  330. reTime = re.compile("(?P<time>\d{2}:\d{2}:\d{2})(?P<fracsec>\.\d+)?(?P<offset>Z|[+-]\d{2}:\d{2})?", re.U)
  331. reYearMonth = re.compile("\d{4}-\d{2}(?P<offset>Z|[+-]\d{2}:\d{2})?", re.U)
  332. reMonthDay = re.compile("--\d{2}-\d{2}(?P<offset>Z|[+-]\d{2}:\d{2})?", re.U)
  333. reYear = re.compile("(?P<year>\d{1,4})(?P<offset>Z|[+-]\d{2}:\d{2})?", re.U)
  334. reMonth = re.compile("--\d{2}(--)?(?P<offset>Z|[+-]\d{2}:\d{2})?", re.U)
  335. reDay = re.compile("---\d{2}(?P<offset>Z|[+-]\d{2}:\d{2})?", re.U)
  336. def _checkAnySimpleType (inputNode, simpleType, attributeValue, returnDict):
  337. # TODO: Nothing to check??
  338. returnDict["length"] = len(attributeValue)
  339. def _checkStringType (inputNode, simpleType, attributeValue, returnDict):
  340. # TODO: all valid??
  341. returnDict["length"] = len(attributeValue)
  342. def _checkAnyUriType (inputNode, simpleType, attributeValue, returnDict):
  343. # TODO: any checks??
  344. if attributeValue[0:2] == '##':
  345. raise BaseTypeError("is not a valid URI!")
  346. returnDict["adaptedAttrValue"] = collapseString(attributeValue)
  347. returnDict["wsAction"] = "collapse"
  348. returnDict["length"] = len(attributeValue)
  349. def _checkDecimalType (inputNode, simpleType, attributeValue, returnDict):
  350. attributeValue = collapseString(attributeValue)
  351. regexObj = reDecimal.match(attributeValue)
  352. if not regexObj or regexObj.end() != len(attributeValue):
  353. raise BaseTypeError("is not a decimal value!")
  354. try:
  355. value = Decimal(attributeValue)
  356. returnDict["orderedValue"] = value.normalize()
  357. returnDict["adaptedAttrValue"] = attributeValue
  358. returnDict["wsAction"] = "collapse"
  359. except:
  360. raise BaseTypeError("is not a decimal value!")
  361. def _checkIntegerType (inputNode, simpleType, attributeValue, returnDict):
  362. attributeValue = collapseString(attributeValue)
  363. regexObj = reInteger.match(attributeValue)
  364. if not regexObj or regexObj.end() != len(attributeValue):
  365. raise BaseTypeError("is not an integer value!")
  366. try:
  367. returnDict["orderedValue"] = Decimal(attributeValue)
  368. returnDict["adaptedAttrValue"] = attributeValue
  369. returnDict["wsAction"] = "collapse"
  370. except:
  371. raise BaseTypeError("is out of range for validation!")
  372. def _checkFloatType (inputNode, simpleType, attributeValue, returnDict):
  373. attributeValue = collapseString(attributeValue)
  374. if attributeValue not in ("INF", "-INF", "NaN"):
  375. try:
  376. value = float(attributeValue)
  377. returnDict["orderedValue"] = value
  378. returnDict["adaptedAttrValue"] = attributeValue
  379. returnDict["wsAction"] = "collapse"
  380. except:
  381. raise BaseTypeError("is not a float value!")
  382. def _checkDoubleType (inputNode, simpleType, attributeValue, returnDict):
  383. attributeValue = collapseString(attributeValue)
  384. regexObj = reDouble.match(attributeValue)
  385. if not regexObj or regexObj.end() != len(attributeValue):
  386. raise BaseTypeError("is not a double value!")
  387. try:
  388. value = Decimal(attributeValue)
  389. returnDict["orderedValue"] = value.normalize()
  390. returnDict["adaptedAttrValue"] = attributeValue
  391. returnDict["wsAction"] = "collapse"
  392. except:
  393. raise BaseTypeError("is not a double value!")
  394. def _checkHexBinaryType (inputNode, simpleType, attributeValue, returnDict):
  395. attributeValue = removeWhitespaces(attributeValue)
  396. regexObj = reHexBinary.match(attributeValue)
  397. if not regexObj or regexObj.end() != len(attributeValue):
  398. raise BaseTypeError("is not a hexBinary value (each byte is represented by 2 characters)!")
  399. returnDict["length"] = len(attributeValue) / 2
  400. returnDict["adaptedAttrValue"] = attributeValue
  401. returnDict["wsAction"] = "collapse"
  402. def _checkBase64BinaryType (inputNode, simpleType, attributeValue, returnDict):
  403. attributeValue = collapseString(attributeValue)
  404. regexObj = reBase64Binary.match(attributeValue)
  405. if not regexObj or regexObj.end() != len(attributeValue):
  406. raise BaseTypeError("is not a base64Binary value (6 bits are represented by 1 character)!")
  407. returnDict["length"] = (len(regexObj.group("validBits")) * 6) / 8
  408. returnDict["adaptedAttrValue"] = attributeValue
  409. returnDict["wsAction"] = "collapse"
  410. def _checkBooleanType (inputNode, simpleType, attributeValue, returnDict):
  411. attributeValue = collapseString(attributeValue)
  412. if attributeValue not in ("true", "false", "1", "0"):
  413. raise BaseTypeError("is not a boolean value!")
  414. if attributeValue in ("true", "1"):
  415. returnDict["orderedValue"] = "__BOOLEAN_TRUE__"
  416. else:
  417. returnDict["orderedValue"] = "__BOOLEAN_FALSE__"
  418. returnDict["adaptedAttrValue"] = attributeValue
  419. returnDict["wsAction"] = "collapse"
  420. def _checkQNameType (inputNode, simpleType, attributeValue, returnDict):
  421. attributeValue = collapseString(attributeValue)
  422. regexObj = reQName.match(attributeValue)
  423. if not regexObj or regexObj.end() != len(attributeValue):
  424. raise BaseTypeError("is not a QName!")
  425. try:
  426. inputNode.getNamespace(attributeValue)
  427. except LookupError:
  428. raise BaseTypeError("is not a valid QName (namespace prefix unknown)!")
  429. returnDict["length"] = len(attributeValue)
  430. returnDict["orderedValue"] = inputNode.qName2NsName(attributeValue, useDefaultNs=1)
  431. returnDict["adaptedAttrValue"] = attributeValue
  432. returnDict["wsAction"] = "collapse"
  433. def _checkDurationType (inputNode, simpleType, attributeValue, returnDict):
  434. attributeValue = collapseString(attributeValue)
  435. regexObj = reDuration.match(attributeValue)
  436. if not regexObj or regexObj.end() != len(attributeValue) or attributeValue[-1] == "T" or attributeValue[-1] == "P":
  437. raise BaseTypeError("is not a valid duration value!")
  438. sign = ""
  439. if attributeValue[0] == "-": sign = "-"
  440. days = 0
  441. seconds = 0
  442. microseconds = 0
  443. if regexObj.group("years") != None:
  444. days = days + (int(sign + regexObj.group("years")[:-1]) * 365)
  445. if regexObj.group("months") != None:
  446. days = days + (int(sign + regexObj.group("months")[:-1]) * 30)
  447. if regexObj.group("days") != None:
  448. days = days + int(sign + regexObj.group("days")[:-1])
  449. if regexObj.group("hours") != None:
  450. seconds = seconds + int(sign + regexObj.group("hours")[:-1]) * 3600
  451. if regexObj.group("minutes") != None:
  452. seconds = seconds + (int(sign + regexObj.group("minutes")[:-1]) * 60)
  453. if regexObj.group("seconds") != None:
  454. seconds = seconds + int(sign + regexObj.group("seconds"))
  455. if regexObj.group("fracsec") != None:
  456. microseconds = int(Decimal(sign + regexObj.group("fracsec")) * 1000000)
  457. try:
  458. timeDeltaObj = datetime.timedelta(days=days, seconds=seconds, microseconds=microseconds)
  459. except ValueError, errstr:
  460. raise BaseTypeError("is invalid (%s)!" %(errstr))
  461. returnDict["orderedValue"] = timeDeltaObj
  462. returnDict["adaptedAttrValue"] = attributeValue
  463. returnDict["wsAction"] = "collapse"
  464. def _checkDateTimeType (inputNode, simpleType, attributeValue, returnDict):
  465. attributeValue = collapseString(attributeValue)
  466. regexObj = reDateTime.match(attributeValue)
  467. if not regexObj or regexObj.end() != len(attributeValue):
  468. raise BaseTypeError("is not a dateTime value!")
  469. date = regexObj.group("date")
  470. time = regexObj.group("time")
  471. offset = regexObj.group("offset")
  472. try:
  473. if offset != None:
  474. tz = TimezoneFixedOffset(offset)
  475. else:
  476. tz = None
  477. dtObj = datetime.datetime(int(date[0:4]),int(date[5:7]),int(date[8:10]),
  478. int(time[0:2]),int(time[3:5]),int(time[6:8]), 0, tz)
  479. except ValueError, errstr:
  480. raise BaseTypeError("is invalid (%s)!" %(errstr))
  481. returnDict["orderedValue"] = dtObj
  482. returnDict["adaptedAttrValue"] = attributeValue
  483. returnDict["wsAction"] = "collapse"
  484. def _checkDateType (inputNode, simpleType, attributeValue, returnDict):
  485. attributeValue = collapseString(attributeValue)
  486. regexObj = reDate.match(attributeValue)
  487. if not regexObj or regexObj.end() != len(attributeValue):
  488. raise BaseTypeError("is not a date value!")
  489. try:
  490. dateObj = datetime.date(int(attributeValue[0:4]),int(attributeValue[5:7]),int(attributeValue[8:10]))
  491. except ValueError, errstr:
  492. raise BaseTypeError("is invalid (%s)!" %(errstr))
  493. returnDict["orderedValue"] = dateObj
  494. returnDict["adaptedAttrValue"] = attributeValue
  495. returnDict["wsAction"] = "collapse"
  496. def _checkTimeType (inputNode, simpleType, attributeValue, returnDict):
  497. attributeValue = collapseString(attributeValue)
  498. regexObj = reTime.match(attributeValue)
  499. if not regexObj or regexObj.end() != len(attributeValue):
  500. raise BaseTypeError("is not a time value!")
  501. time = regexObj.group("time")
  502. fracsec = regexObj.group("fracsec")
  503. offset = regexObj.group("offset")
  504. try:
  505. if offset != None:
  506. tz = TimezoneFixedOffset(offset)
  507. else:
  508. tz = None
  509. if fracsec != None:
  510. fracSec = int(fracsec[1:])
  511. else:
  512. fracSec = 0
  513. timeObj = datetime.time(int(time[0:2]),int(time[3:5]),int(time[6:8]), fracSec, tz)
  514. except ValueError, errstr:
  515. raise BaseTypeError("is invalid (%s)!" %(errstr))
  516. returnDict["orderedValue"] = timeObj
  517. returnDict["adaptedAttrValue"] = attributeValue
  518. returnDict["wsAction"] = "collapse"
  519. def _checkYearMonth (inputNode, simpleType, attributeValue, returnDict):
  520. attributeValue = collapseString(attributeValue)
  521. regexObj = reYearMonth.match(attributeValue)
  522. if not regexObj or regexObj.end() != len(attributeValue):
  523. raise BaseTypeError("is not a gYearMonth value!")
  524. try:
  525. dateObj = datetime.date(int(attributeValue[0:4]),int(attributeValue[5:7]),1)
  526. except ValueError, errstr:
  527. raise BaseTypeError("is invalid (%s)!" %(errstr))
  528. returnDict["orderedValue"] = dateObj
  529. returnDict["adaptedAttrValue"] = attributeValue
  530. returnDict["wsAction"] = "collapse"
  531. def _checkMonthDay (inputNode, simpleType, attributeValue, returnDict):
  532. attributeValue = collapseString(attributeValue)
  533. regexObj = reMonthDay.match(attributeValue)
  534. if not regexObj or regexObj.end() != len(attributeValue):
  535. raise BaseTypeError("is not a gMonthDay value!")
  536. try:
  537. dateObj = datetime.date(2004, int(attributeValue[2:4]),int(attributeValue[5:7]))
  538. except ValueError, errstr:
  539. raise BaseTypeError("is invalid (%s)!" %(errstr))
  540. returnDict["orderedValue"] = dateObj
  541. returnDict["adaptedAttrValue"] = attributeValue
  542. returnDict["wsAction"] = "collapse"
  543. def _checkYear (inputNode, simpleType, attributeValue, returnDict):
  544. attributeValue = collapseString(attributeValue)
  545. regexObj = reYear.match(attributeValue)
  546. if not regexObj or regexObj.end() != len(attributeValue or regexObj.group("year") == None):
  547. raise BaseTypeError("is not a gYear value (1)!")
  548. try:
  549. year = int(regexObj.group("year"))
  550. if year < 1 or year > 9999:
  551. raise BaseTypeError("is not a valid gYear value!")
  552. except:
  553. raise BaseTypeError("is not a gYear value!")
  554. returnDict["orderedValue"] = year
  555. returnDict["adaptedAttrValue"] = attributeValue
  556. returnDict["wsAction"] = "collapse"
  557. def _checkMonth (inputNode, simpleType, attributeValue, returnDict):
  558. attributeValue = collapseString(attributeValue)
  559. regexObj = reMonth.match(attributeValue)
  560. if not regexObj or regexObj.end() != len(attributeValue):
  561. raise BaseTypeError("is not a gMonth value!")
  562. month = int(attributeValue[2:4])
  563. if month < 1 or month > 12:
  564. raise BaseTypeError("is invalid (month must be in 1..12)!")
  565. returnDict["orderedValue"] = month
  566. returnDict["adaptedAttrValue"] = attributeValue
  567. returnDict["wsAction"] = "collapse"
  568. def _checkDay (inputNode, simpleType, attributeValue, returnDict):
  569. attributeValue = collapseString(attributeValue)
  570. regexObj = reDay.match(attributeValue)
  571. if not regexObj or regexObj.end() != len(attributeValue):
  572. raise BaseTypeError("is not a gDay value!")
  573. day = int(attributeValue[3:5])
  574. if day < 1 or day > 31:
  575. raise BaseTypeError("is invalid (day must be in 1..31)!")
  576. returnDict["orderedValue"] = day
  577. returnDict["adaptedAttrValue"] = attributeValue
  578. returnDict["wsAction"] = "collapse"
  579. ########################################
  580. # timezone class
  581. #
  582. class TimezoneFixedOffset(datetime.tzinfo):
  583. def __init__(self, offset):
  584. if offset == "Z":
  585. self.__offset = datetime.timedelta(0)
  586. else:
  587. self.__offset = datetime.timedelta(hours=int(offset[0:3]),
  588. minutes=int(offset[0] + offset[4:5]))
  589. def utcoffset(self, dt):
  590. return self.__offset
  591. def tzname(self, dt):
  592. return None
  593. def dst(self, dt):
  594. return datetime.timedelta(0)
  595. ########################################
  596. # define own exception for XML schema validation errors
  597. #
  598. class SimpleTypeError (StandardError):
  599. pass
  600. class BaseTypeError (StandardError):
  601. pass
  602. ########################################
  603. # Base type dictionaries
  604. #
  605. _suppBaseTypeDict = {(XSD_NAMESPACE, "anySimpleType"): _checkAnySimpleType,
  606. (XSD_NAMESPACE, "string"): _checkStringType,
  607. (XSD_NAMESPACE, "anyURI"): _checkAnyUriType,
  608. (XSD_NAMESPACE, "decimal"): _checkDecimalType,
  609. (XSD_NAMESPACE, "integer"): _checkIntegerType,
  610. (XSD_NAMESPACE, "float"): _checkFloatType,
  611. (XSD_NAMESPACE, "double"): _checkDoubleType,
  612. (XSD_NAMESPACE, "hexBinary"): _checkHexBinaryType,
  613. (XSD_NAMESPACE, "base64Binary"): _checkBase64BinaryType,
  614. (XSD_NAMESPACE, "boolean"): _checkBooleanType,
  615. (XSD_NAMESPACE, "QName"): _checkQNameType,
  616. (XSD_NAMESPACE, "NOTATION"): _checkQNameType,
  617. (XSD_NAMESPACE, "duration"): _checkDurationType,
  618. (XSD_NAMESPACE, "dateTime"): _checkDateTimeType,
  619. (XSD_NAMESPACE, "date"): _checkDateType,
  620. (XSD_NAMESPACE, "time"): _checkTimeType,
  621. (XSD_NAMESPACE, "gYearMonth"): _checkYearMonth,
  622. (XSD_NAMESPACE, "gMonthDay"): _checkMonthDay,
  623. (XSD_NAMESPACE, "gYear"): _checkYear,
  624. (XSD_NAMESPACE, "gMonth"): _checkMonth,
  625. (XSD_NAMESPACE, "gDay"): _checkDay,
  626. }