示例#1
0
 def toJsonObj(self, action: Actions):
     tmp = {}
     if action == Actions.Create:
         if self._name is None:
             raise BaseError("There must be a valid name!")
         tmp['name'] = self._name
         if self._description is not None:
             tmp['description'] = self._description
         if self._project is None:
             raise BaseError("There must be a valid project!")
         tmp['project'] = self._project
         if self._selfjoin is None:
             raise BaseError("There must be a valid value for selfjoin!")
         tmp['selfjoin'] = self._selfjoin
         if self._status is None:
             raise BaseError("There must be a valid value for status!")
         tmp['status'] = self._status
     else:
         if self._name is not None and 'name' in self.changed:
             tmp['name'] = self._name
         if self._description is not None and 'description' in self.changed:
             tmp['description'] = self._description
         if self._selfjoin is not None and 'selfjoin' in self.changed:
             tmp['selfjoin'] = self._selfjoin
     return tmp
    def fromJsonObj(cls, con: Connection, json_obj: Any) -> Tuple[LastModificationDate, 'Ontology']:
        #
        # First let's get the ID (IRI) of the ontology
        #
        id = json_obj.get('@id')
        if id is None:
            raise BaseError('Ontology id is missing')

        #
        # evaluate the JSON-LD context to get the proper prefixes
        #
        context = Context(json_obj.get('@context'))
        tmps = json_obj['@id'].split('/')
        context.addContext(tmps[-2], json_obj['@id'] + '#')

        rdf = context.prefixFromIri("http://www.w3.org/1999/02/22-rdf-syntax-ns#")
        rdfs = context.prefixFromIri("http://www.w3.org/2000/01/rdf-schema#")
        owl = context.prefixFromIri("http://www.w3.org/2002/07/owl#")
        xsd = context.prefixFromIri("http://www.w3.org/2001/XMLSchema#")
        knora_api = context.prefixFromIri("http://api.knora.org/ontology/knora-api/v2#")
        salsah_gui = context.prefixFromIri("http://api.knora.org/ontology/salsah-gui/v2#")
        this_onto = context.prefixFromIri(id + "#")

        label = json_obj.get(rdfs + ':label')
        if label is None:
            raise BaseError('Ontology label is missing')
        if json_obj.get(knora_api + ':attachedToProject') is None:
            raise BaseError('Ontology not attached to a project')
        if json_obj[knora_api + ':attachedToProject'].get('@id') is None:
            raise BaseError('Ontology not attached to a project')
        project = json_obj[knora_api + ':attachedToProject']['@id']
        tmp = json_obj.get(knora_api + ':lastModificationDate')
        if tmp is not None:
            last_modification_date = LastModificationDate(json_obj.get(knora_api + ':lastModificationDate'))
        else:
            last_modification_date = None
        resource_classes = None
        property_classes = None
        if json_obj.get('@graph') is not None:
            resclasses_obj = list(filter(lambda a: a.get(knora_api + ':isResourceClass') is not None, json_obj.get('@graph')))
            resource_classes = list(map(lambda a: ResourceClass.fromJsonObj(con=con,
                                                                            context=context,
                                                                            json_obj=a), resclasses_obj))
            standoffclasses_obj = list(filter(lambda a: a.get(knora_api + ':isStandoffClass') is not None, json_obj.get('@graph')))
            # ToDo: parse standoff classes

            properties_obj = list(filter(lambda a: a.get(knora_api + ':isResourceProperty') is not None, json_obj.get('@graph')))
            property_classes = list(map(lambda a: PropertyClass.fromJsonObj(con=con,
                                                                            context=context,
                                                                            json_obj=a), properties_obj))
        return last_modification_date, cls(con=con,
                                           id=id,
                                           label=label,
                                           project=project,
                                           name=this_onto,  # TODO: corresponds the prefix always to the ontology name?
                                           lastModificationDate=last_modification_date,
                                           resource_classes=resource_classes,
                                           property_classes=property_classes,
                                           context=context)
示例#3
0
    def fromJsonObj(cls, con: Connection, context: Context,
                    json_obj: Any) -> Any:
        if isinstance(json_obj, list):
            json_obj = json_obj[
                0]  # TODO: Is it possible to have more than one element in the list??
        if not isinstance(con, Connection):
            raise BaseError(
                '"con"-parameter must be an instance of Connection')
        if not isinstance(context, Context):
            raise BaseError(
                '"context"-parameter must be an instance of Context')
        rdf = context.prefixFromIri(
            "http://www.w3.org/1999/02/22-rdf-syntax-ns#")
        rdfs = context.prefixFromIri("http://www.w3.org/2000/01/rdf-schema#")
        owl = context.prefixFromIri("http://www.w3.org/2002/07/owl#")
        xsd = context.prefixFromIri("http://www.w3.org/2001/XMLSchema#")
        knora_api = context.prefixFromIri(
            "http://api.knora.org/ontology/knora-api/v2#")
        salsah_gui = context.prefixFromIri(
            "http://api.knora.org/ontology/salsah-gui/v2#")

        if not (json_obj.get(knora_api + ':isResourceClass')
                or json_obj.get(knora_api + ':isStandoffClass')):
            raise BaseError("This is not a resource!")

        if json_obj.get('@id') is None:
            raise BaseError('Resource class has no "@id"!')
        tmp_id = json_obj.get('@id').split(':')
        id = context.iriFromPrefix(tmp_id[0]) + '#' + tmp_id[1]
        ontology_id = tmp_id[0]
        name = tmp_id[1]
        superclasses_obj = json_obj.get(rdfs + ':subClassOf')
        if superclasses_obj is not None:
            supercls: List[Any] = list(
                filter(lambda a: a.get('@id') is not None, superclasses_obj))
            superclasses: List[str] = list(map(lambda a: a['@id'], supercls))
            has_props: List[Any] = list(
                filter(lambda a: a.get('@type') == (owl + ':Restriction'),
                       superclasses_obj))
            has_properties: Dict[HasProperty] = dict(
                map(lambda a: HasProperty.fromJsonObj(con, context, a),
                    has_props))
        else:
            superclasses = None
            has_properties = None

        label = LangString.fromJsonLdObj(json_obj.get(rdfs + ':label'))
        comment = LangString.fromJsonLdObj(json_obj.get(rdfs + ':comment'))
        return cls(con=con,
                   context=context,
                   name=name,
                   id=id,
                   ontology_id=ontology_id,
                   superclasses=superclasses,
                   label=label,
                   comment=comment,
                   has_properties=has_properties)
示例#4
0
    def fromJsonObj(cls, con: Connection, json_obj: Any):
        """
        Internal method! Should not be used directly!

        This method is used to create a User instance from the JSON data returned by Knora

        :param con: Connection instance
        :param json_obj: JSON data returned by Knora as python3 object
        :return: User instance
        """

        id = json_obj.get('id')
        if id is None:
            raise BaseError('User "id" is missing in JSON from knora')
        email = json_obj.get('email')
        if email is None:
            raise BaseError('User "email" is missing in JSON from knora')
        username = json_obj.get('username')
        if username is None:
            raise BaseError('User "username" is missing in JSON from knora')
        familyName = json_obj.get('familyName')
        givenName = json_obj.get('givenName')
        lang = json_obj.get('lang')
        status = json_obj.get('status')
        if status is None:
            raise BaseError("Status is missing in JSON from knora")

        in_projects: Dict[str, bool] = {}
        in_groups: Set[str] = set()
        if json_obj.get('permissions') is not None and json_obj['permissions'].get('groupsPerProject') is not None:
            sysadmin = False
            project_groups = json_obj['permissions']['groupsPerProject']
            for project in project_groups:
                if project == Project.SYSTEM_PROJECT:
                    if Group.PROJECT_SYSTEMADMIN_GROUP in project_groups[project]:
                        sysadmin = True
                else:
                    for group in project_groups[project]:
                        if group == Group.PROJECT_MEMBER_GROUP:
                            if in_projects.get(project) is None:
                                in_projects[project] = False
                        elif group == Group.PROJECT_ADMIN_GROUP:
                            in_projects[project] = True
                        else:
                            in_groups.add(group)
        return cls(con=con,
                   id=id,
                   username=username,
                   email=email,
                   givenName=givenName,
                   familyName=familyName,
                   lang=lang,
                   status=status,
                   sysadmin=sysadmin,
                   in_projects=in_projects,
                   in_groups=in_groups)
示例#5
0
 def __init__(self,
              con: Connection,
              context: Context,
              id: Optional[str] = None,
              name: Optional[str] = None,
              ontology_id: Optional[str] = None,
              superclasses: Optional[List[Union['ResourceClass',
                                                str]]] = None,
              label: Optional[Union[LangString, str]] = None,
              comment: Optional[Union[LangString, str]] = None,
              permissions: Optional[str] = None,
              has_properties: Optional[Dict[str, HasProperty]] = None):
     if not isinstance(con, Connection):
         raise BaseError(
             '"con"-parameter must be an instance of Connection')
     if not isinstance(context, Context):
         raise BaseError(
             '"context"-parameter must be an instance of Context')
     self.con = con
     self._context = context
     self._id = id
     self._name = name
     self._ontology_id = ontology_id
     if isinstance(superclasses, ResourceClass):
         self._superclasses = list(map(lambda a: a.id, superclasses))
     else:
         self._superclasses = superclasses
     #
     # process label
     #
     if label is not None:
         if isinstance(label, str):
             self._label = LangString(label)
         elif isinstance(label, LangString):
             self._label = label
         else:
             raise BaseError('Invalid LangString for label!')
     else:
         self._label = None
     #
     # process comment
     #
     if comment is not None:
         if isinstance(comment, str):
             self._comment = LangString(comment)
         elif isinstance(comment, LangString):
             self._comment = comment
         else:
             raise BaseError('Invalid LangString for comment!')
     else:
         self._comment = None
     self._permissions = permissions
     self._has_properties = has_properties
     self._changed = set()
示例#6
0
    def update(self, requesterPassword: Optional[str] = None) -> Any:
        """
        Udate the user info in Knora with the modified data in this user instance

        :param requesterPassword: Old password if a user wants to change it's own password
        :return: JSON-object from Knora
        """

        jsonobj = self.toJsonObj(Actions.Update)
        if jsonobj:
            jsondata = json.dumps(jsonobj)
            result = self.con.put('/admin/users/iri/' + quote_plus(self.id) + '/BasicUserInformation', jsondata)
        if 'status' in self.changed:
            jsonobj = {'status': self._status}
            jsondata = json.dumps(jsonobj)
            result = self.con.put('/admin/users/iri/' + quote_plus(self.id) + '/Status', jsondata)
        if 'password' in self.changed:
            if requesterPassword is None:
                raise BaseError("Requester's password is missing!")
            jsonobj = {
                "requesterPassword": requesterPassword,
                "newPassword": self._password
            }
            jsondata = json.dumps(jsonobj)
            result = self.con.put('/admin/users/iri/' + quote_plus(self.id) + '/Password', jsondata)
        if 'sysadmin' in self.changed:
            jsonobj = {'systemAdmin': self._sysadmin}
            jsondata = json.dumps(jsonobj)
            result = self.con.put('/admin/users/iri/' + quote_plus(self.id) + '/SystemAdmin', jsondata)
        for p in self.add_to_project.items():
            result = self.con.post('/admin/users/iri/' + quote_plus(self._id) + '/project-memberships/' + quote_plus(p[0]))
            if p[1]:
                result = self.con.post('/admin/users/iri/' + quote_plus(self._id) + '/project-admin-memberships/' + quote_plus(p[0]))

        for p in self.rm_from_project:
            if self._in_projects.get(p) is not None and self._in_projects[p]:
                result = self.con.delete('/admin/users/iri/' + quote_plus(self._id) + '/project-admin-memberships/' + quote_plus(p))
            result = self.con.delete('/admin/users/iri/' + quote_plus(self._id) + '/project-memberships/' + quote_plus(p))

        for p in self.change_admin.items():
            if not p[0] in self._in_projects:
                raise BaseError('user must be member of project!')
            if p[1]:
                result = self.con.post('/admin/users/iri/' + quote_plus(self._id) + '/project-admin-memberships/' + quote_plus(p[0]))
            else:
                result = self.con.delete('/admin/users/iri/' + quote_plus(self._id) + '/project-admin-memberships/' + quote_plus(p[0]))

        for p in self.add_to_group:
            result = self.con.post('/admin/users/iri/' + quote_plus(self._id) + '/group-memberships/' + quote_plus(p))
        for p in self.rm_from_group:
            result = self.con.delete('/admin/users/iri/' + quote_plus(self._id) + '/group-memberships/' + quote_plus(p))
        return User.fromJsonObj(self.con, result['user'])
    def __init__(self, initvalue: LangStringParam = None):
        def mymapper(
                p: Tuple[Union[Languages, str], str]) -> Tuple[Languages, str]:
            lmap = dict(map(lambda a: (a.value, a), Languages))
            if isinstance(p[0], str) and p[0] in lmap:
                lang = lmap[p[0].lower()]
            elif isinstance(p[0], Languages):
                lang = p[0]
            else:
                raise BaseError("No a valid language definition!")
            return lang, p[1]

        if initvalue is None:
            self._simplestring = None
            self._langstrs = {}
        elif isinstance(initvalue, str):
            self._simplestring = initvalue
            self._langstrs = {}
        elif isinstance(initvalue, dict):
            self._simplestring = None
            self._langstrs = dict(map(mymapper, initvalue.items()))
        elif isinstance(initvalue, LangString):
            self._simplestring = initvalue._simplestring
            self._langstrs = initvalue._langstrs
        else:
            raise BaseError("No a valid language definition!")
 def __init__(self,
              con:  Connection,
              id: Optional[str] = None,
              project: Optional[Union[str, Project]] = None,
              name: Optional[str] = None,
              label: Optional[str] = None,
              lastModificationDate: Optional[Union[str, LastModificationDate]] = None,
              resource_classes: List[ResourceClass] = None,
              property_classes: List[PropertyClass] = None,
              context: Context = None):
     if not isinstance(con, Connection):
         raise BaseError('"con"-parameter must be an instance of Connection')
     self.con = con
     self._id = id
     if isinstance(project, Project):
         self._project = project.id
     else:
         self._project = project
     self._name = name
     self._label = label
     if lastModificationDate is None:
         self._lastModificationDate = None
     elif isinstance(lastModificationDate, LastModificationDate):
         self._lastModificationDate = lastModificationDate
     else:
         self._lastModificationDate = LastModificationDate(lastModificationDate)
     self._resource_classes = resource_classes
     self._property_classes = property_classes
     self._context = context if context is not None else Context()
     self.changed = set()
 def __delitem__(self, key: Union[Languages, str]):
     if isinstance(key, Languages):
         del self._langstrs[key]
     else:
         lmap = dict(map(lambda a: (a.value, a), Languages))
         if lmap.get(key.lower()) is None:
             raise BaseError('Invalid language string "' + key + '"!')
         del self._langstrs[lmap[key.lower()]]
示例#10
0
 def update(
     self, last_modification_date: LastModificationDate
 ) -> Tuple[LastModificationDate, 'ResourceClass']:
     if self._ontology_id is None:
         raise BaseError("Ontology id required")
     if self._property_id is None:
         raise BaseError("Property id required")
     if self._cardinality is None:
         raise BaseError("Cardinality id required")
     jsonobj = self.toJsonObj(last_modification_date, Actions.Update)
     jsondata = json.dumps(jsonobj, cls=SetEncoder)
     result = self.con.put('/v2/ontologies/cardinalities', jsondata)
     last_modification_date = LastModificationDate(
         result['knora-api:lastModificationDate'])
     # TODO: self._changed = str()
     return last_modification_date, ResourceClass.fromJsonObj(
         self.con, self._context, result['@graph'])
示例#11
0
    def getAllNodes(self):
        """
        Get all nodes of the list. Mus be called from a ListNode instance that has at least set the
        list iri!

        :return: Root node of list with recursive ListNodes ("children"-attributes)
        """

        result = self.con.get('/admin/lists/' + quote_plus(self._id))
        if 'list' not in result:
            raise BaseError("Request got no list!")
        if 'listinfo' not in result['list']:
            raise BaseError("Request got no proper list information!")
        root = ListNode.fromJsonObj(self.con, result['list']['listinfo'])
        if 'children' in result['list']:
            root._children = ListNode._getChildren(self.con, result['list']['children'])
        return root
示例#12
0
    def __init__(self,
                 con: Connection,
                 id: Optional[str] = None,
                 shortcode: Optional[str] = None,
                 shortname: Optional[str] = None,
                 longname: Optional[str] = None,
                 description: LangStringParam = None,
                 keywords: Optional[Set[str]] = None,
                 ontologies: Optional[Set[str]] = None,
                 selfjoin: Optional[bool] = None,
                 status: Optional[bool] = None,
                 logo: Optional[str] = None):
        """
        Constructor for Project

        :param con: Connection instance
        :param id: IRI of the project [required for CREATE, READ]
        :param shortcode: Shortcode of the project. String inf the form 'XXXX' where each X is a hexadezimal sign 0-1,A,B,C,D,E,F. [required for CREATE]
        :param shortname: Shortname of the project [required for CREATE]
        :param longname: Longname of the project [required for CREATE]
        :param description: LangString instance containing the description [required for CREATE]
        :param keywords: Set of keywords [required for CREATE]
        :param ontologies: Set of ontologies that belong to this project [optional]
        :param selfjoin: Allow selfjoin [required for CREATE]
        :param status: Status of project (active if True) [required for CREATE]
        :param logo: Path to logo image file [optional] NOT YET USED
        """

        if not isinstance(con, Connection):
            raise BaseError(
                '"con"-parameter must be an instance of Connection')
        self.con = con
        self._id = id
        self._shortcode = shortcode
        self._shortname = shortname
        self._longname = longname
        self._description = LangString(description)
        self._keywords = keywords
        if not isinstance(ontologies, set) and ontologies is not None:
            raise BaseError('Ontologies must be a set of strings or None!')
        self._ontologies = ontologies
        self._selfjoin = selfjoin
        self._status = status
        self._logo = logo
        self.changed = set()
示例#13
0
 def keywords(self, value: Union[List[str], Set[str]]):
     if isinstance(value, set):
         self._keywords = value
         self.changed.add('keywords')
     elif isinstance(value, list):
         self._keywords = set(value)
         self.changed.add('keywords')
     else:
         raise BaseError('Must be a set of strings!')
示例#14
0
    def delete(self) -> None:
        """
        Delete the given ListNode

        :return: Knora response
        """
        raise BaseError("NOT YET IMPLEMENTED BY KNORA BACKEND!")
        result = self.con.delete('/admin/lists/' + quote_plus(self._id))
        return result
 def mymapper(
         p: Tuple[Union[Languages, str], str]) -> Tuple[Languages, str]:
     lmap = dict(map(lambda a: (a.value, a), Languages))
     if isinstance(p[0], str) and p[0] in lmap:
         lang = lmap[p[0].lower()]
     elif isinstance(p[0], Languages):
         lang = p[0]
     else:
         raise BaseError("No a valid language definition!")
     return lang, p[1]
示例#16
0
 def comment(self, value: Optional[LangString]) -> None:
     if value is None:
         self._comment.empty()  # clear all comments!
     else:
         if isinstance(value, LangString):
             self._comment = value
         elif isinstance(value, str):
             self._comment = LangString(value)
         else:
             raise BaseError('Not a valid LangString')
     self._changed.add('comment')
示例#17
0
 def label(self, value: Optional[Union[LangString, str]]) -> None:
     if value is None:
         self._label.empty()  # clear all labels
     else:
         if isinstance(value, LangString):
             self._label = value
         elif isinstance(value, str):
             self._label = LangString(value)
         else:
             raise BaseError('Not a valid LangString')
     self._changed.add('label')
示例#18
0
    def getAllUsers(con: Connection) -> List[Any]:
        """
        Get a list of all users (static method)

        :param con: Connection instance
        :return: List of users
        """

        result = con.get('/admin/users')
        if 'users' not in result:
            raise BaseError("Request got no users!")
        return list(map(lambda a: User.fromJsonObj(con, a), result['users']))
示例#19
0
    def getAllLists(con: Connection, project_iri: str) -> List['ListNode']:
        """
        Get all lists of the specified project

        :param con: Connection instance
        :param project_iri: Iri/id of project
        :return: list of ListNodes
        """
        result = con.get('/admin/lists?projectIri=' + quote_plus(project_iri))
        if 'lists' not in result:
            raise BaseError("Request got no lists!")
        return list(map(lambda a: ListNode.fromJsonObj(con, a), result['lists']))
示例#20
0
 def lang(self, value: Optional[Union[str, Languages]]):
     if value is None:
         return
     if isinstance(value, Languages):
         self._lang = value
         self.changed.add('lang')
     else:
         lmap = dict(map(lambda a: (a.value, a), Languages))
         if lmap.get(value) is None:
             raise BaseError('Invalid language string "' + value + '"!')
         self._lang = lmap[value]
         self.changed.add('lang')
示例#21
0
    def getAllProjects(con: Connection) -> List['Project']:
        """
        Get all existing projects in Knora

        :param con: Connection instance
        :return:
        """
        result = con.get('/admin/projects')
        if 'projects' not in result:
            raise BaseError("Request got no projects!")
        return list(
            map(lambda a: Project.fromJsonObj(con, a), result['projects']))
示例#22
0
    def toJsonObj(self, action: Actions, listIri: str = None) -> Any:
        """
        Internal method! Should not be used directly!

        Creates a JSON-object from the ListNode instance that can be used to call Knora

        :param action: Action the object is used for (Action.CREATE or Action.UPDATE)
        :return: JSON-object
        """

        tmp = {}
        if action == Actions.Create:
            if self._project is None:
                raise BaseError("There must be a project id given!")
            tmp['projectIri'] = self._project
            if self._label.isEmpty():
                raise BaseError("There must be a valid ListNode label!")
            tmp['labels'] = self._label.toJsonObj()
            if not self._comment.isEmpty():
                tmp['comments'] = self._comment.toJsonObj()
            else:
                tmp['comments'] = []
            if self._name is not None:
                tmp['name'] = self._name
            if self._parent is not None:
                tmp['parentNodeIri'] = self._parent
        elif action == Actions.Update:
            if self.id is None:
                raise BaseError("There must be a node id given!")
            tmp['listIri'] = listIri
            if self._project is None:
                raise BaseError("There must be a project id given!")
            tmp['projectIri'] = self._project
            if not self._label.isEmpty() and 'label' in self.changed:
                tmp['labels'] = self._label.toJsonObj()
            if not self._comment.isEmpty() and 'comment' in self.changed:
                tmp['comments'] = self._comment.toJsonObj()
            if self._name is not None and 'name' in self.changed:
                tmp['name'] = self._name
        return tmp
示例#23
0
 def fromJsonObj(cls, con: Connection, json_obj: Any):
     id = json_obj.get('id')
     if id is None:
         raise BaseError('Group "id" is missing in JSON from knora')
     name = json_obj.get('name')
     if name is None:
         raise BaseError('Group "name" is missing in JSON from knora')
     description = json_obj.get('description')
     tmp = json_obj.get('project')
     if tmp is None:
         raise BaseError('Group "project" is missing in JSON from knora')
     project = tmp.get('id')
     if project is None:
         raise BaseError('Group "project" has no "id" in JSON from knora')
     selfjoin = json_obj.get('selfjoin')
     if selfjoin is None:
         raise BaseError("selfjoin is missing in JSON from knora")
     status = json_obj.get('status')
     if status is None:
         raise BaseError("Status is missing in JSON from knora")
     return cls(con=con,
                name=name,
                id=id,
                description=description,
                project=project,
                selfjoin=selfjoin,
                status=status)
 def toJsonObj(self, action: Actions, last_modification_date: Optional[LastModificationDate] = None) -> Any:
     rdf = self._context.prefixFromIri("http://www.w3.org/1999/02/22-rdf-syntax-ns#")
     rdfs = self._context.prefixFromIri("http://www.w3.org/2000/01/rdf-schema#")
     owl = self._context.prefixFromIri("http://www.w3.org/2002/07/owl#")
     xsd = self._context.prefixFromIri("http://www.w3.org/2001/XMLSchema#")
     knora_api = self._context.prefixFromIri("http://api.knora.org/ontology/knora-api/v2#")
     salsah_gui = self._context.prefixFromIri("http://api.knora.org/ontology/salsah-gui/v2#")
     # this_onto = self._context.prefixFromIri(self._id + "#")
     tmp = {}
     if action == Actions.Create:
         if self._name is None:
             raise BaseError('There must be a valid name given!')
         if self._label is None:
             raise BaseError('There must be a valid label given!')
         if self._project is None:
             raise BaseError('There must be a valid project given!')
         tmp = {
             knora_api + ":ontologyName": self._name,
             knora_api + ":attachedToProject": {
                 "@id": self._project
             },
             rdfs + ":label": self._label,
             "@context": self._context
         }
     elif action == Actions.Update:
         if last_modification_date is None:
             raise BaseError("'last_modification_date' must be given!")
         if isinstance(last_modification_date, str):
             last_modification_date = LastModificationDate(last_modification_date)
         elif not isinstance(last_modification_date, LastModificationDate):
             raise BaseError("Must be string or LastModificationClass instance!")
         if self._label is not None and 'label' in self.changed:
             tmp = {
                 '@id': self._id,
                 rdfs + ':label': self._label,
                 knora_api + ':lastModificationDate': last_modification_date.toJsonObj(),
                 "@context": self._context.toJsonObj()
             }
     return tmp
 def __setitem__(self, key: Optional[Union[Languages, str]], value: str):
     if key is None:
         self._simplestring = value
         self._langstrs = {
         }  # Delete language dependent string! Needs Caution!!!
         return
     if isinstance(key, Languages):
         self._langstrs[key] = value
     else:
         lmap = dict(map(lambda a: (a.value, a), Languages))
         if lmap.get(key.lower()) is None:
             raise BaseError('Invalid language string "' + key + '"!')
         self._langstrs[lmap[key.lower()]] = value
示例#26
0
    def rmKeyword(self, value: str):
        """
        Remove a keyword from the list of keywords (executed at next update)
        May raise a BaseError

        :param value: keyword
        :return: None
        """
        try:
            self._keywords.remove(value)
        except KeyError as ke:
            raise BaseError('Keyword "' + value + '" is not in keyword set')
        self.changed.add('keywords')
 def allOntologiesFromJsonObj(cls, con: Connection, json_obj: Any) -> Dict[str, 'Ontology']:
     context = Context(json_obj.get('@context'))
     rdf = context.prefixFromIri("http://www.w3.org/1999/02/22-rdf-syntax-ns#")
     rdfs = context.prefixFromIri("http://www.w3.org/2000/01/rdf-schema#")
     owl = context.prefixFromIri("http://www.w3.org/2002/07/owl#")
     xsd = context.prefixFromIri("http://www.w3.org/2001/XMLSchema#")
     knora_api = context.prefixFromIri("http://api.knora.org/ontology/knora-api/v2#")
     salsah_gui = context.prefixFromIri("http://api.knora.org/ontology/salsah-gui/v2#")
     ontos: Dict[std, 'Ontology'] = {}
     for o in json_obj['@graph']:
         if o.get('@type') != owl + ':Ontology':
             raise BaseError("Found something that is not an ontology!")
         id = o.get('@id')
         if id is None:
             raise BaseError('Ontology id is missing')
         if o.get(knora_api + ':attachedToProject') is None:
             raise BaseError('Ontology not attached to a project (1)')
         if o[knora_api + ':attachedToProject'].get('@id') is None:
             raise BaseError('Ontology not attached to a project (2)')
         project = o[knora_api + ':attachedToProject']['@id']
         tmp = o.get(knora_api + ':lastModificationDate')
         if tmp is not None:
             last_modification_date = LastModificationDate(o.get(knora_api + ':lastModificationDate'))
         else:
             last_modification_date = None
         label = o.get(rdfs + ':label')
         if label is None:
             raise BaseError('Ontology label is missing')
         this_onto = id.split('/')[-2]
         context2 = copy.deepcopy(context)
         context2.addContext(this_onto, id)
         onto = cls(con=con,
                    id=id,
                    label=label,
                    name=this_onto,
                    lastModificationDate=last_modification_date,
                    context=context2)
         ontos[id] = onto
     return ontos
示例#28
0
    def fromJsonObj(cls, con: Connection, json_obj: Any) -> Any:
        """
        Internal method! Should not be used directly!

        This method is used to create a Project instance from the JSON data returned by Knora

        :param con: Connection instance
        :param json_obj: JSON data returned by Knora as python3 object
        :return: Project instance
        """

        id = json_obj.get('id')
        if id is None:
            raise BaseError('Project id is missing')
        shortcode = json_obj.get('shortcode')
        if shortcode is None:
            raise BaseError("Shortcode is missing")
        shortname = json_obj.get('shortname')
        if shortname is None:
            raise BaseError("Shortname is missing")
        longname = json_obj.get('longname')
        if longname is None:
            raise BaseError("Longname is missing")
        description = LangString.fromJsonObj(json_obj.get('description'))
        keywords = set(json_obj.get('keywords'))
        if keywords is None:
            raise BaseError("Keywords are missing")
        ontologies = set(json_obj.get('ontologies'))
        if ontologies is None:
            raise BaseError("Keywords are missing")
        selfjoin = json_obj.get('selfjoin')
        if selfjoin is None:
            raise BaseError("Selfjoin is missing")
        status = json_obj.get('status')
        if status is None:
            raise BaseError("Status is missing")
        logo = json_obj.get('logo')
        return cls(con=con,
                   id=id,
                   shortcode=shortcode,
                   shortname=shortname,
                   longname=longname,
                   description=description,
                   keywords=keywords,
                   ontologies=ontologies,
                   selfjoin=selfjoin,
                   status=status,
                   logo=logo)
示例#29
0
    def unmakeProjectAdmin(self, value: str):
        """
        Revoke project administrator right for the user from the given project  (executed at next update)

        :param value: Project IRI
        :return: None
        """
        if value in self._in_projects:
            self.change_admin[value] = False
            self.changed.add('in_projects')
        elif value in self.add_to_project:
            self.add_to_project[value] = False
        else:
            raise BaseError("User is not member of project!")
示例#30
0
    def read(self) -> Any:
        """
        Read the user information from Knora. The User object must have a valid id or email!

        :return: JSON-object from Knora
        """
        if self._id is not None:
            result = self.con.get('/admin/users/iri/' + quote_plus(self._id))
        elif self._email is not None:
            result = self.con.get('/admin/users/email/' + quote_plus(self._email))
        elif self._username is not None:
            result = self.con.get('/admin/users/username/' + quote_plus(self._username))
        else:
            raise BaseError('Either user-id or email is required!')
        return User.fromJsonObj(self.con, result['user'])