Ejemplo n.º 1
0
    def __init__(self, source):
        self.__implicit = []
        self.__prioritized = []
        self.__required = []
        self.__optional = []
        self.__expected = set()

        for name, source_type in source.items():
            if isinstance(source_type, Optional):
                checker = TypeChecker.make(source_type.source)
                if isinstance(checker, Implicit):
                    raise base.ImplementationError(
                        "implicit parameter cannot be optional: %s" % name)
                self.__optional.append((name, checker))
            else:
                checker = TypeChecker.make(source_type)
                if isinstance(checker, Implicit):
                    self.__implicit.append((name, checker))
                elif isinstance(checker, Prioritized):
                    self.__prioritized.append((name, checker))
                else:
                    self.__required.append((name, checker))
            for suffix, _ in checker.getSuffixedCheckers():
                if name.endswith("_" + suffix):
                    raise base.ImplementationError(
                        "invalid parameter name: %s (includes optional suffix)"
                        % name)
Ejemplo n.º 2
0
    def fetchPreference(db, item, user=None, repository=None, filter_id=None):
        cursor = db.cursor()
        cursor.execute("SELECT type FROM preferences WHERE item=%s", (item, ))
        row = cursor.fetchone()
        if not row:
            raise base.ImplementationError("invalid preference: %s" % item)
        preference_type = row[0]

        arguments = [item]
        where = ["item=%s"]

        if preference_type in ("boolean", "integer"):
            columns = ["integer"]
        else:
            columns = ["string"]

        if user is not None and not user.isAnonymous():
            arguments.append(user.id)
            where.append("uid=%s OR uid IS NULL")
            columns.append("uid")
        else:
            where.append("uid IS NULL")

        if repository is not None:
            arguments.append(repository.id)
            where.append("repository=%s OR repository IS NULL")
            columns.append("repository")
        else:
            where.append("repository IS NULL")

        if filter_id is not None:
            arguments.append(filter_id)
            where.append("filter=%s OR filter IS NULL")
            columns.append("filter")
        else:
            where.append("filter IS NULL")

        query = (
            """SELECT %(columns)s
                      FROM userpreferences
                     WHERE %(where)s""" % {
                "columns": ", ".join(columns),
                "where": " AND ".join("(%s)" % condition
                                      for condition in where)
            })

        cursor.execute(query, arguments)

        rows = cursor.fetchall()
        if not rows:
            raise base.ImplementationError(
                "invalid preference read: %s (no value found)" % item)

        value = sorted(rows, key=lambda row: row[1:])[-1][0]
        if preference_type == "boolean":
            return bool(value)
        return value
Ejemplo n.º 3
0
    def __init__(self, parameter_types, accept_anonymous_user=False):
        """
        Initialize input data type checker.

        The parameter_types argument must be a dict object.  See TypeChecker and
        sub-classes for details on how it works.  A parameter types argument of

          { "name": str,
            "points": [{"x": int, "y": int }],
            "what": Optional(str) }

        would for instance represents an input object with two required
        properties named "name" and "points", and an optional property named
        "what".  The "name" and "what" property values should be a strings.  The
        "points" property value should be an array of objects, each with two
        properties named "x" and "y", whose values should be integer.

        The operation's process() method would be called with the keyword
        arguments "name", "points" and "what".
        """
        from operation.typechecker import TypeChecker
        if not type(parameter_types) is dict:
            raise base.ImplementationError("invalid source type")
        self.__checker = TypeChecker.make(parameter_types)
        self.__accept_anonymous_user = accept_anonymous_user
Ejemplo n.º 4
0
    def make(source):
        """
        Construct a structure of TypeChecker objects.

        The source argument should be a dict object, single-element list object,
        a set object containing strings, or str, int or bool (the actual type
        objects, not a string, integer or boolean value).

        If the source argument is a dict object, per-element type checkers are
        constructed by calling this function on the value of each item in the
        dictionary.  See DictionaryChecker for details.

        If the source argument is a list object, a per-element type checker is
        constructed by calling this function on the value of the single element
        in the list.

        If the source argument is a set object, all elements in it should be
        strings, and the constructed checker verifies that the value is a string
        that is a member of the set.

        Otherwise the constructed checker verifies that the value is of the type
        of the source argument (or, in the case of source=str, that the value's
        type is either str or unicode).
        """

        if isinstance(source, TypeChecker):
            return source
        elif isinstance(source, dict):
            if (len(source) == 1 and all(key is str for key in source.keys())
                    and all(
                        isinstance(value, type) for value in source.values())):
                return GenericDictionaryChecker(source)
            return DictionaryChecker(source)
        elif isinstance(source, list):
            return ArrayChecker(source)
        elif isinstance(source, set):
            if all(type(x) is str for x in source):
                return EnumerationChecker(source)
            return VariantChecker(source)
        elif source is str:
            return StringChecker()
        elif source is int:
            return IntegerChecker()
        elif source is bool:
            return BooleanChecker()

        try:
            is_type_checker = issubclass(source, TypeChecker)
        except TypeError:
            pass
        else:
            if is_type_checker:
                return source()

        raise base.ImplementationError("invalid source type: %r" % source)
Ejemplo n.º 5
0
 def __init__(self, source):
     self.__checker = TypeChecker.make(str)
     for item in source:
         if not type(item) is str:
             raise base.ImplementationError("invalid source type")
     self.__enumeration = source
Ejemplo n.º 6
0
 def __init__(self, source):
     if len(source) != 1:
         raise base.ImplementationError("invalid source type")
     self.__checker = TypeChecker.make(source[0])
Ejemplo n.º 7
0
    def storePreference(db,
                        item,
                        value,
                        user=None,
                        repository=None,
                        filter_id=None):
        # A preference value can be set for either a repository or a filter, but
        # not for both at the same time.  A filter implies a repository anyway,
        # so there would be no point.
        assert repository is None or filter_id is None
        assert filter_id is None or user is not None

        # If all are None, we'd be deleting the global default and not setting a
        # new one, which would be bad.
        if value is None and user is None \
                and repository is None and filter is None:
            raise base.ImplementationError(
                "attempted to delete global default")

        if User.fetchPreference(db, item, user, repository,
                                filter_id) != value:
            cursor = db.cursor()

            arguments = [item]
            where = ["item=%s"]

            user_id = repository_id = None

            if user is not None:
                user_id = user.id
                arguments.append(user_id)
                where.append("uid=%s")
            else:
                where.append("uid IS NULL")

            if repository is not None:
                repository_id = repository.id
                arguments.append(repository_id)
                where.append("repository=%s")
            else:
                where.append("repository IS NULL")

            if filter_id is not None:
                arguments.append(filter_id)
                where.append("filter=%s")
            else:
                where.append("filter IS NULL")

            query = ("DELETE FROM userpreferences WHERE %s" %
                     (" AND ".join("(%s)" % condition for condition in where)))

            cursor.execute(query, arguments)

            if value is not None:
                cursor.execute("SELECT type FROM preferences WHERE item=%s",
                               (item, ))

                (value_type, ) = cursor.fetchone()
                integer = string = None

                if value_type == "boolean":
                    value = bool(value)
                    integer = int(value)
                elif value_type == "integer":
                    integer = int(value)
                else:
                    string = str(value)

                cursor.execute(
                    """INSERT INTO userpreferences (item, uid, repository, filter, integer, string)
                                       VALUES (%s, %s, %s, %s, %s, %s)""",
                    (item, user_id, repository_id, filter_id, integer, string))

            if user is not None:
                cache_key = _preferenceCacheKey(item, repository, filter_id)
                if cache_key in user.preferences:
                    del user.preferences[cache_key]

            return True
        else:
            return False