def update( self, last_modification_date: LastModificationDate ) -> Tuple[LastModificationDate, 'ResourceClass']: # # Note: Knora is able to change only one thing per call, either label or comment! # result = None something_changed = False if 'label' in self._changed: jsonobj = self.toJsonObj(last_modification_date, Actions.Update, 'label') jsondata = json.dumps(jsonobj, cls=SetEncoder, indent=4) result = self.con.put('/v2/ontologies/properties', jsondata) last_modification_date = LastModificationDate( result['knora-api:lastModificationDate']) something_changed = True if 'comment' in self._changed: jsonobj = self.toJsonObj(last_modification_date, Actions.Update, 'comment') jsondata = json.dumps(jsonobj, cls=SetEncoder, indent=4) result = self.con.put('/v2/ontologies/properties', jsondata) last_modification_date = LastModificationDate( result['knora-api:lastModificationDate']) something_changed = True if something_changed: return last_modification_date, PropertyClass.fromJsonObj( self.con, self._context, result['@graph']) else: return last_modification_date, self
def toJsonObj(self, lastModificationDate: LastModificationDate, action: Actions) -> Any: tmp = {} switcher = { Cardinality.C_1: ("owl:cardinality", 1), Cardinality.C_0_1: ("owl:maxCardinality", 1), Cardinality.C_0_n: ("owl:minCardinality", 0), Cardinality.C_1_n: ("owl:minCardinality", 1) } occurrence = switcher.get(self._cardinality) if action == Actions.Create: tmp = { "@id": self._ontology_id, "@type": "owl:Ontology", "knora-api:lastModificationDate": lastModificationDate.toJsonObj(), "@graph": [{ "@id": self._resclass_id, "@type": "owl:Class", "rdfs:subClassOf": { "@type": "owl:Restriction", occurrence[0]: occurrence[1], "owl:onProperty": { "@id": self._property_id } } }], "@context": self._context.toJsonObj() } elif action == Actions.Update: tmp = { "@id": self._ontology_id, "@type": "owl:Ontology", "knora-api:lastModificationDate": lastModificationDate.toJsonObj(), "@graph": [{ "@id": self._resclass_id, "@type": "owl:Class", "rdfs:subClassOf": { "@type": "owl:Restriction", occurrence[0]: occurrence[1], "owl:onProperty": { "@id": self._property_id } } }], "@context": self._context.toJsonObj() } return tmp
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 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)
def delete( self, last_modification_date: LastModificationDate ) -> LastModificationDate: result = self.con.delete('/v2/ontologies/properties/' + quote_plus(self._id) + '?lastModificationDate=' + str(last_modification_date)) return LastModificationDate(result['knora-api:lastModificationDate'])
def create( self, last_modification_date: LastModificationDate ) -> Tuple[LastModificationDate, 'PropertyClass']: jsonobj = self.toJsonObj(last_modification_date, Actions.Create) jsondata = json.dumps(jsonobj, cls=SetEncoder, indent=2) result = self.con.post('/v2/ontologies/properties', jsondata) last_modification_date = LastModificationDate( result['knora-api:lastModificationDate']) return last_modification_date, PropertyClass.fromJsonObj( self.con, self._context, result['@graph'])
def create( self, last_modification_date: LastModificationDate ) -> Tuple[LastModificationDate, 'ResourceClass']: jsonobj = self.toJsonObj(last_modification_date, Actions.Create) jsondata = json.dumps(jsonobj) result = self.con.post('/v2/ontologies/classes', jsondata) last_modification_date = LastModificationDate( result['knora-api:lastModificationDate']) return last_modification_date, ResourceClass.fromJsonObj( self.con, self._context, result['@graph'])
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'])
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 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
def toJsonObj(self, lastModificationDate: LastModificationDate, action: Actions, what: Optional[str] = None) -> Any: def resolve_propref(resref: str): tmp = resref.split(':') if len(tmp) > 1: if tmp[0]: return { "@id": resref } # fully qualified name in the form "prefix:name" else: return { "@id": self._context.prefixFromIri(self._ontology_id) + ':' + tmp[1] } # ":name" in current ontology else: return { "@id": "knora-api:" + resref } # no ":", must be from knora-api! tmp = {} exp = re.compile('^http.*') # It is already a fully IRI if exp.match(self._ontology_id): propid = self._context.prefixFromIri( self._ontology_id) + ":" + self._name ontid = self._ontology_id else: propid = self._ontology_id + ":" + self._name ontid = self._context.iriFromPrefix(self._ontology_id) if action == Actions.Create: if self._name is None: raise BaseError("There must be a valid property class name!") if self._ontology_id is None: raise BaseError("There must be a valid ontology_id given!") if self._superproperties is None: superproperties = [{"@id": "knora-api:hasValue"}] else: superproperties = list( map(resolve_propref, self._superproperties)) tmp = { "@id": ontid, # self._ontology_id, "@type": "owl:Ontology", "knora-api:lastModificationDate": lastModificationDate.toJsonObj(), "@graph": [{ "@id": propid, "@type": "owl:ObjectProperty", "rdfs:label": self._label.toJsonLdObj(), "rdfs:subPropertyOf": superproperties }], "@context": self._context.toJsonObj() } if self._comment is not None: if not self._comment.isEmpty(): tmp['@graph'][0][ "rdfs:comment"] = self._comment.toJsonLdObj() if self._subject is not None: tmp['@graph'][0]["knora-api:subjectType"] = resolve_propref( self._subject) if self._object is not None: tmp['@graph'][0]["knora-api:objectType"] = resolve_propref( self._object) if self._gui_element is not None: tmp['@graph'][0]["salsah-gui:guiElement"] = { "@id": self._gui_element } if self._gui_attributes: ga = list( map(lambda x: x[0] + '=' + str(x[1]), self._gui_attributes.items())) tmp['@graph'][0]["salsah-gui:guiAttribute"] = ga elif action == Actions.Update: tmp = { "@id": ontid, # self._ontology_id, "@type": "owl:Ontology", "knora-api:lastModificationDate": lastModificationDate.toJsonObj(), "@graph": [{ "@id": propid, "@type": "owl:ObjectProperty", }], "@context": self._context.toJsonObj(), } if what == 'label': if not self._label.isEmpty() and 'label' in self._changed: tmp['@graph'][0]['rdfs:label'] = self._label.toJsonLdObj() if what == 'comment': if not self._comment.isEmpty() and 'comment' in self._changed: tmp['@graph'][0][ 'rdfs:comment'] = self._comment.toJsonLdObj() return tmp
def toJsonObj(self, lastModificationDate: LastModificationDate, action: Actions, what: Optional[str] = None) -> Any: def resolve_resref(resref: str): tmp = resref.split(':') if len(tmp) > 1: if tmp[0]: return { "@id": resref } # fully qualified name in the form "prefix:name" else: return { "@id": self._context.prefixFromIri(self._ontology_id) + ':' + tmp[1] } # ":name" in current ontology else: return { "@id": "knora-api:" + resref } # no ":", must be from knora-api! tmp = {} exp = re.compile('^http.*') # It is already a fully IRI if exp.match(self._ontology_id): resid = self._context.prefixFromIri( self._ontology_id) + ":" + self._name ontid = self._ontology_id else: resid = self._ontology_id + ":" + self._name ontid = self._context.iriFromPrefix(self._ontology_id) if action == Actions.Create: if self._name is None: raise BaseError("There must be a valid resource class name!") if self._ontology_id is None: raise BaseError("There must be a valid ontology_id given!") if self._superclasses is None: superclasses = [{"@id": "knora-api:Resource"}] else: superclasses = list(map(resolve_resref, self._superclasses)) if self._comment is None or self._comment.isEmpty(): self._comment = LangString("no comment vailable") tmp = { "@id": ontid, # self._ontology_id, "@type": "owl:Ontology", "knora-api:lastModificationDate": lastModificationDate.toJsonObj(), "@graph": [{ "@id": resid, "@type": "owl:Class", "rdfs:label": self._label.toJsonLdObj(), "rdfs:comment": self._comment.toJsonLdObj(), "rdfs:subClassOf": superclasses }], "@context": self._context.toJsonObj(), } elif action == Actions.Update: tmp = { "@id": ontid, # self._ontology_id, "@type": "owl:Ontology", "knora-api:lastModificationDate": lastModificationDate.toJsonObj(), "@graph": [{ "@id": resid, "@type": "owl:Class", }], "@context": self._context.toJsonObj(), } if what == 'label': if not self._label.isEmpty() and 'label' in self._changed: tmp['@graph'][0]['rdfs:label'] = self._label.toJsonLdObj() if what == 'comment': if not self._comment.isEmpty() and 'comment' in self._changed: tmp['@graph'][0][ 'rdfs:comment'] = self._comment.toJsonLdObj() return tmp