Ejemplo n.º 1
0
 def _checkNodeId (self, node, unambiguousPerFile=1):
     if node.hasAttribute("id"):
         # id must only be unambiguous within one file
         if unambiguousPerFile:
             nodeId = (node.getAbsUrl(), collapseString(node["id"]))
         else:
             nodeId = collapseString(node["id"])
         if not self.xsdIdDict.has_key(nodeId):
             self.xsdIdDict[nodeId] = node
         else:
             self._addError ("There are multiple occurences of ID value %s!" %repr(nodeId), node)
def _checkAnyUriType(inputNode, simpleType, attributeValue, returnDict):
    # TODO: any checks??
    if attributeValue[0:2] == "##":
        raise BaseTypeError("is not a valid URI!")
    returnDict["adaptedAttrValue"] = collapseString(attributeValue)
    returnDict["wsAction"] = "collapse"
    returnDict["length"] = len(attributeValue)
def _checkDurationType(inputNode, simpleType, attributeValue, returnDict):
    attributeValue = collapseString(attributeValue)
    regexObj = reDuration.match(attributeValue)
    if not regexObj or regexObj.end() != len(attributeValue) or attributeValue[-1] == "T" or attributeValue[-1] == "P":
        raise BaseTypeError("is not a valid duration value!")
    sign = ""
    if attributeValue[0] == "-":
        sign = "-"
    days = 0
    seconds = 0
    microseconds = 0
    if regexObj.group("years") != None:
        days = days + (int(sign + regexObj.group("years")[:-1]) * 365)
    if regexObj.group("months") != None:
        days = days + (int(sign + regexObj.group("months")[:-1]) * 30)
    if regexObj.group("days") != None:
        days = days + int(sign + regexObj.group("days")[:-1])
    if regexObj.group("hours") != None:
        seconds = seconds + int(sign + regexObj.group("hours")[:-1]) * 3600
    if regexObj.group("minutes") != None:
        seconds = seconds + (int(sign + regexObj.group("minutes")[:-1]) * 60)
    if regexObj.group("seconds") != None:
        seconds = seconds + int(sign + regexObj.group("seconds"))
    if regexObj.group("fracsec") != None:
        microseconds = int(Decimal(sign + regexObj.group("fracsec")) * 1000000)
    try:
        timeDeltaObj = datetime.timedelta(days=days, seconds=seconds, microseconds=microseconds)
    except ValueError, errstr:
        raise BaseTypeError("is invalid (%s)!" % (errstr))
def _checkBase64BinaryType(inputNode, simpleType, attributeValue, returnDict):
    attributeValue = collapseString(attributeValue)
    regexObj = reBase64Binary.match(attributeValue)
    if not regexObj or regexObj.end() != len(attributeValue):
        raise BaseTypeError("is not a base64Binary value (6 bits are represented by 1 character)!")
    returnDict["length"] = (len(regexObj.group("validBits")) * 6) / 8
    returnDict["adaptedAttrValue"] = attributeValue
    returnDict["wsAction"] = "collapse"
def _checkMonthDay(inputNode, simpleType, attributeValue, returnDict):
    attributeValue = collapseString(attributeValue)
    regexObj = reMonthDay.match(attributeValue)
    if not regexObj or regexObj.end() != len(attributeValue):
        raise BaseTypeError("is not a gMonthDay value!")
    try:
        dateObj = datetime.date(2004, int(attributeValue[2:4]), int(attributeValue[5:7]))
    except ValueError, errstr:
        raise BaseTypeError("is invalid (%s)!" % (errstr))
def _checkFloatType(inputNode, simpleType, attributeValue, returnDict):
    attributeValue = collapseString(attributeValue)
    if attributeValue not in ("INF", "-INF", "NaN"):
        try:
            value = float(attributeValue)
            returnDict["orderedValue"] = value
            returnDict["adaptedAttrValue"] = attributeValue
            returnDict["wsAction"] = "collapse"
        except:
            raise BaseTypeError("is not a float value!")
def _checkBooleanType(inputNode, simpleType, attributeValue, returnDict):
    attributeValue = collapseString(attributeValue)
    if attributeValue not in ("true", "false", "1", "0"):
        raise BaseTypeError("is not a boolean value!")
    if attributeValue in ("true", "1"):
        returnDict["orderedValue"] = "__BOOLEAN_TRUE__"
    else:
        returnDict["orderedValue"] = "__BOOLEAN_FALSE__"
    returnDict["adaptedAttrValue"] = attributeValue
    returnDict["wsAction"] = "collapse"
def _checkMonth(inputNode, simpleType, attributeValue, returnDict):
    attributeValue = collapseString(attributeValue)
    regexObj = reMonth.match(attributeValue)
    if not regexObj or regexObj.end() != len(attributeValue):
        raise BaseTypeError("is not a gMonth value!")
    month = int(attributeValue[2:4])
    if month < 1 or month > 12:
        raise BaseTypeError("is invalid (month must be in 1..12)!")
    returnDict["orderedValue"] = month
    returnDict["adaptedAttrValue"] = attributeValue
    returnDict["wsAction"] = "collapse"
def _checkDay(inputNode, simpleType, attributeValue, returnDict):
    attributeValue = collapseString(attributeValue)
    regexObj = reDay.match(attributeValue)
    if not regexObj or regexObj.end() != len(attributeValue):
        raise BaseTypeError("is not a gDay value!")
    day = int(attributeValue[3:5])
    if day < 1 or day > 31:
        raise BaseTypeError("is invalid (day must be in 1..31)!")
    returnDict["orderedValue"] = day
    returnDict["adaptedAttrValue"] = attributeValue
    returnDict["wsAction"] = "collapse"
def _checkIntegerType(inputNode, simpleType, attributeValue, returnDict):
    attributeValue = collapseString(attributeValue)
    regexObj = reInteger.match(attributeValue)
    if not regexObj or regexObj.end() != len(attributeValue):
        raise BaseTypeError("is not an integer value!")
    try:
        returnDict["orderedValue"] = Decimal(attributeValue)
        returnDict["adaptedAttrValue"] = attributeValue
        returnDict["wsAction"] = "collapse"
    except:
        raise BaseTypeError("is out of range for validation!")
def _checkDoubleType(inputNode, simpleType, attributeValue, returnDict):
    attributeValue = collapseString(attributeValue)
    regexObj = reDouble.match(attributeValue)
    if not regexObj or regexObj.end() != len(attributeValue):
        raise BaseTypeError("is not a double value!")
    try:
        value = Decimal(attributeValue)
        returnDict["orderedValue"] = value.normalize()
        returnDict["adaptedAttrValue"] = attributeValue
        returnDict["wsAction"] = "collapse"
    except:
        raise BaseTypeError("is not a double value!")
def _checkYear(inputNode, simpleType, attributeValue, returnDict):
    attributeValue = collapseString(attributeValue)
    regexObj = reYear.match(attributeValue)
    if not regexObj or regexObj.end() != len(attributeValue or regexObj.group("year") == None):
        raise BaseTypeError("is not a gYear value (1)!")
    try:
        year = int(regexObj.group("year"))
        if year < 1 or year > 9999:
            raise BaseTypeError("is not a valid gYear value!")
    except:
        raise BaseTypeError("is not a gYear value!")
    returnDict["orderedValue"] = year
    returnDict["adaptedAttrValue"] = attributeValue
    returnDict["wsAction"] = "collapse"
def _checkQNameType(inputNode, simpleType, attributeValue, returnDict):
    attributeValue = collapseString(attributeValue)
    regexObj = reQName.match(attributeValue)
    if not regexObj or regexObj.end() != len(attributeValue):
        raise BaseTypeError("is not a QName!")

    try:
        inputNode.getNamespace(attributeValue)
    except LookupError:
        raise BaseTypeError("is not a valid QName (namespace prefix unknown)!")

    returnDict["length"] = len(attributeValue)
    returnDict["orderedValue"] = inputNode.qName2NsName(attributeValue, useDefaultNs=1)
    returnDict["adaptedAttrValue"] = attributeValue
    returnDict["wsAction"] = "collapse"
def _checkDateTimeType(inputNode, simpleType, attributeValue, returnDict):
    attributeValue = collapseString(attributeValue)
    regexObj = reDateTime.match(attributeValue)
    if not regexObj or regexObj.end() != len(attributeValue):
        raise BaseTypeError("is not a dateTime value!")
    date = regexObj.group("date")
    time = regexObj.group("time")
    offset = regexObj.group("offset")
    try:
        if offset != None:
            tz = TimezoneFixedOffset(offset)
        else:
            tz = None
        dtObj = datetime.datetime(
            int(date[0:4]), int(date[5:7]), int(date[8:10]), int(time[0:2]), int(time[3:5]), int(time[6:8]), 0, tz
        )
    except ValueError, errstr:
        raise BaseTypeError("is invalid (%s)!" % (errstr))
 def _checkUnionTag(self, inputNode, xsdElement, attrName, attributeValue, returnDict, idCheck):
     memberTypes = xsdElement.getAttribute("memberTypes")
     if memberTypes != None:
         # substitute multiple whitespace characters by a single ' '
         # divide up attributeValue => store it into list
         for memberType in string.split(collapseString(memberTypes), " "):
             try:
                 self.checkSimpleType(
                     inputNode,
                     attrName,
                     xsdElement.qName2NsName(memberType, useDefaultNs=1),
                     attributeValue,
                     returnDict,
                     idCheck,
                 )
                 return
             except SimpleTypeError, errstr:
                 pass
def _checkTimeType(inputNode, simpleType, attributeValue, returnDict):
    attributeValue = collapseString(attributeValue)
    regexObj = reTime.match(attributeValue)
    if not regexObj or regexObj.end() != len(attributeValue):
        raise BaseTypeError("is not a time value!")
    time = regexObj.group("time")
    fracsec = regexObj.group("fracsec")
    offset = regexObj.group("offset")
    try:
        if offset != None:
            tz = TimezoneFixedOffset(offset)
        else:
            tz = None
        if fracsec != None:
            fracSec = int(fracsec[1:])
        else:
            fracSec = 0
        timeObj = datetime.time(int(time[0:2]), int(time[3:5]), int(time[6:8]), fracSec, tz)
    except ValueError, errstr:
        raise BaseTypeError("is invalid (%s)!" % (errstr))
    def _checkListTag(self, inputNode, xsdElement, attrName, attributeValue, returnDict, idCheck):
        if attributeValue != "":
            itemType = xsdElement.getQNameAttribute("itemType")
            # substitute multiple whitespace characters by a single ' '
            collapsedValue = collapseString(attributeValue)
            returnDict["wsAction"] = "collapse"
            returnDict["adaptedAttrValue"] = collapsedValue

            # divide up attributeValue => store it into list
            attributeList = string.split(collapsedValue, " ")
            for attrValue in attributeList:
                elementReturnDict = {"BaseTypes": [], "primitiveType": None}
                if itemType != (None, None):
                    self.checkSimpleType(inputNode, attrName, itemType, attrValue, elementReturnDict, idCheck)
                else:
                    itemTypeNode = xsdElement.getFirstChildNS(self.xsdNsURI, "simpleType")
                    self.checkSimpleTypeDef(inputNode, itemTypeNode, attrName, attrValue, elementReturnDict, idCheck)

            returnDict["BaseTypes"].extend(elementReturnDict["BaseTypes"])
            returnDict["length"] = len(attributeList)
        else:
            returnDict["length"] = 0
    def _checkRestrictionTag(self, inputNode, xsdElement, attrName, attributeValue, returnDict, idCheck):
        savedAttrValue = attributeValue
        # first check against base type
        self.checkBaseType(inputNode, xsdElement, attrName, attributeValue, returnDict, idCheck)

        minExcl = xsdElement.getFirstChildNS(self.xsdNsURI, "minExclusive")
        minIncl = xsdElement.getFirstChildNS(self.xsdNsURI, "minInclusive")
        maxExcl = xsdElement.getFirstChildNS(self.xsdNsURI, "maxExclusive")
        maxIncl = xsdElement.getFirstChildNS(self.xsdNsURI, "maxInclusive")

        if minExcl != None:
            minExclReturnDict = {"BaseTypes": [], "primitiveType": None}
            minExclValue = minExcl.getAttribute("value")
            self.checkBaseType(inputNode, xsdElement, attrName, minExclValue, minExclReturnDict, idCheck=0)
            if returnDict.has_key("orderedValue") and minExclReturnDict.has_key("orderedValue"):
                if returnDict["orderedValue"] <= minExclReturnDict["orderedValue"]:
                    raise SimpleTypeError(
                        "Value of %s (%s) is <= minExclusive (%s)"
                        % (repr(attrName), repr(attributeValue), repr(minExclValue))
                    )
        elif minIncl != None:
            minInclReturnDict = {"BaseTypes": [], "primitiveType": None}
            minInclValue = minIncl.getAttribute("value")
            self.checkBaseType(inputNode, xsdElement, attrName, minInclValue, minInclReturnDict, idCheck=0)
            if returnDict.has_key("orderedValue") and minInclReturnDict.has_key("orderedValue"):
                if returnDict["orderedValue"] < minInclReturnDict["orderedValue"]:
                    raise SimpleTypeError(
                        "Value of %s (%s) is < minInclusive (%s)"
                        % (repr(attrName), repr(attributeValue), repr(minInclValue))
                    )
        if maxExcl != None:
            maxExclReturnDict = {"BaseTypes": [], "primitiveType": None}
            maxExclValue = maxExcl.getAttribute("value")
            self.checkBaseType(inputNode, xsdElement, attrName, maxExclValue, maxExclReturnDict, idCheck=0)
            if returnDict.has_key("orderedValue") and maxExclReturnDict.has_key("orderedValue"):
                if returnDict["orderedValue"] >= maxExclReturnDict["orderedValue"]:
                    raise SimpleTypeError(
                        "Value of %s (%s) is >= maxExclusive (%s)"
                        % (repr(attrName), repr(attributeValue), repr(maxExclValue))
                    )
        elif maxIncl != None:
            maxInclReturnDict = {"BaseTypes": [], "primitiveType": None}
            maxInclValue = maxIncl.getAttribute("value")
            self.checkBaseType(inputNode, xsdElement, attrName, maxInclValue, maxInclReturnDict, idCheck=0)
            if returnDict.has_key("orderedValue") and maxInclReturnDict.has_key("orderedValue"):
                if returnDict["orderedValue"] > maxInclReturnDict["orderedValue"]:
                    raise SimpleTypeError(
                        "Value of %s (%s) is > maxInclusive (%s)"
                        % (repr(attrName), repr(attributeValue), repr(maxInclValue))
                    )

        totalDigitsNode = xsdElement.getFirstChildNS(self.xsdNsURI, "totalDigits")
        if totalDigitsNode != None:
            orderedValueStr = repr(returnDict["orderedValue"])
            digits = re.findall("\d", orderedValueStr)
            if digits[0] == "0" and len(digits) > 1:
                digits = digits[1:]
            totalDigitsValue = totalDigitsNode.getAttribute("value")
            if totalDigitsNode.getAttribute("fixed") == "true":
                if len(digits) != string.atoi(totalDigitsValue):
                    raise SimpleTypeError(
                        "Total number of digits != %s for %s (%s)"
                        % (repr(totalDigitsValue), repr(attrName), repr(attributeValue))
                    )
            else:
                if len(digits) > string.atoi(totalDigitsValue):
                    raise SimpleTypeError(
                        "Total number of digits > %s for %s (%s)"
                        % (repr(totalDigitsValue), repr(attrName), repr(attributeValue))
                    )

        fractionDigitsNode = xsdElement.getFirstChildNS(self.xsdNsURI, "fractionDigits")
        if fractionDigitsNode != None:
            orderedValueStr = repr(returnDict["orderedValue"])
            fractionDigitsValue = fractionDigitsNode.getAttribute("value")
            result = re.search("(?P<intDigits>\d*)(?P<dot>\.)(?P<fracDigits>\d+)", orderedValueStr)
            if result != None:
                numberOfFracDigits = len(result.group("fracDigits"))
            else:
                numberOfFracDigits = 0
            if fractionDigitsNode.getAttribute("fixed") == "true" and numberOfFracDigits != string.atoi(
                fractionDigitsValue
            ):
                raise SimpleTypeError(
                    "Fraction number of digits != %s for %s (%s)"
                    % (repr(fractionDigitsValue), repr(attrName), repr(attributeValue))
                )
            elif numberOfFracDigits > string.atoi(fractionDigitsValue):
                raise SimpleTypeError(
                    "Fraction number of digits > %s for %s (%s)"
                    % (repr(fractionDigitsValue), repr(attrName), repr(attributeValue))
                )

        if returnDict.has_key("length"):
            lengthNode = xsdElement.getFirstChildNS(self.xsdNsURI, "length")
            if lengthNode != None:
                length = string.atoi(lengthNode.getAttribute("value"))
                if returnDict["length"] != length:
                    raise SimpleTypeError(
                        "Length of %s (%s) must be %d!" % (repr(attrName), repr(attributeValue), length)
                    )
            minLengthNode = xsdElement.getFirstChildNS(self.xsdNsURI, "minLength")
            if minLengthNode != None:
                minLength = string.atoi(minLengthNode.getAttribute("value"))
                if returnDict["length"] < minLength:
                    raise SimpleTypeError(
                        "Length of %s (%s) must be >= %d!" % (repr(attrName), repr(attributeValue), minLength)
                    )
            maxLengthNode = xsdElement.getFirstChildNS(self.xsdNsURI, "maxLength")
            if maxLengthNode != None:
                maxLength = string.atoi(maxLengthNode.getAttribute("value"))
                if returnDict["length"] > maxLength:
                    raise SimpleTypeError(
                        "Length of %s (%s) must be <= %d!" % (repr(attrName), repr(attributeValue), maxLength)
                    )

        whiteSpace = xsdElement.getFirstChildNS(self.xsdNsURI, "whiteSpace")
        if whiteSpace != None:
            returnDict["wsAction"] = whiteSpace.getAttribute("value")
            if returnDict["wsAction"] == "replace":
                normalizedValue = normalizeString(attributeValue)
                if normalizedValue != attributeValue:
                    returnDict["adaptedAttrValue"] = normalizedValue
            elif returnDict["wsAction"] == "collapse":
                collapsedValue = collapseString(attributeValue)
                if collapsedValue != attributeValue:
                    returnDict["adaptedAttrValue"] = collapsedValue

        enumerationElementList = xsdElement.getChildrenNS(self.xsdNsURI, "enumeration")
        if enumerationElementList != []:
            if returnDict.has_key("orderedValue"):
                attributeValue = returnDict["orderedValue"]
            elif returnDict.has_key("adaptedAttrValue"):
                attributeValue = returnDict["adaptedAttrValue"]

            for enumeration in enumerationElementList:
                enumReturnDict = {"BaseTypes": [], "primitiveType": None}
                enumValue = enumeration["value"]
                self.checkBaseType(inputNode, xsdElement, attrName, enumValue, enumReturnDict, idCheck=0)
                if enumReturnDict.has_key("orderedValue"):
                    enumValue = enumReturnDict["orderedValue"]
                elif enumReturnDict.has_key("adaptedAttrValue"):
                    enumValue = enumReturnDict["adaptedAttrValue"]

                if enumValue == attributeValue:
                    break
            else:
                raise SimpleTypeError("Enumeration value %s not allowed!" % repr(attributeValue))

        if returnDict.has_key("adaptedAttrValue"):
            attributeValue = returnDict["adaptedAttrValue"]

        patternMatch = 1
        notMatchedPatternList = []
        for patternNode in xsdElement.getChildrenNS(self.xsdNsURI, "pattern"):
            rePattern = patternNode.getAttribute("value")
            intRePattern = rePattern
            try:
                intRePattern = substituteSpecialEscChars(intRePattern)
            except SyntaxError, errInst:
                raise SimpleTypeError, str(errInst)
            patternMatch = self._matchesPattern(intRePattern, attributeValue)

            if patternMatch:
                break
            else:
                notMatchedPatternList.append(rePattern)