/
resourceclass.py
820 lines (719 loc) · 33.4 KB
/
resourceclass.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
import json
import re
from enum import Enum
from typing import Tuple, Optional, Any, Union
from urllib.parse import quote_plus
from pystrict import strict
from .connection import Connection
from .helpers import Actions, BaseError, Context, Cardinality, LastModificationDate
from .langstring import Languages, LangString
from .model import Model
from ..utils.set_encoder import SetEncoder
"""
This model implements the handling of resource classes. It contains two classes that work closely together:
* "HasProperty" deals with the association of Property-instances with the Resource-instances. This association
is done using the "cardinality"-clause
* "ResourceClass" is the main class representing a knora resource class.
"""
@strict
class HasProperty(Model):
ROUTE: str = "/v2/ontologies/cardinalities"
class Ptype(Enum):
system = 1
knora = 2
other = 3
_context: Context
_ontology_id: str
_property_id: str
_resclass_id: str
_cardinality: Cardinality
_gui_order: int
_is_inherited: bool
_ptype: Ptype
def __init__(self,
con: Connection,
context: Context,
ontology_id: Optional[str] = None,
property_id: Optional[str] = None,
resclass_id: Optional[str] = None,
cardinality: Optional[Cardinality] = None,
gui_order: Optional[int] = None,
is_inherited: Optional[bool] = None,
ptype: Optional[Ptype] = None):
super().__init__(con)
if not isinstance(context, Context):
raise BaseError('"context"-parameter must be an instance of Context')
self._context = context
if ontology_id is not None:
self._ontology_id = context.iri_from_prefix(ontology_id)
else:
self._ontology_id = None
self._property_id = property_id
self._resclass_id = resclass_id
self._cardinality = cardinality
self._gui_order = gui_order
self._is_inherited = is_inherited
self._ptype = ptype
self._changed = set()
#
# Here follows a list of getters/setters
#
@property
def ontology_id(self) -> Optional[str]:
return self._ontology_id
@ontology_id.setter
def ontology_id(self, value: Optional[str]) -> None:
self._ontology_id = value
@property
def property_id(self) -> Optional[str]:
return self._property_id
@property_id.setter
def property_id(self, value: str) -> None:
raise BaseError('property_id "{}" cannot be modified!'.format(self._property_id))
@property
def resclass_id(self) -> Optional[str]:
return self._resclass_id
@resclass_id.setter
def resclass_id(self, value: Optional[str]) -> None:
self._resclass_id = value
@property
def cardinality(self) -> Optional[Cardinality]:
return self._cardinality
@cardinality.setter
def cardinality(self, value: Optional[Cardinality]) -> None:
self._cardinality = value
self._changed.add('cardinality')
@property
def gui_order(self) -> Optional[int]:
return self._gui_order
@gui_order.setter
def gui_order(self, value: int) -> None:
self._gui_order = value
self._changed.add('gui_order')
@property
def ptype(self) -> Ptype:
return self._ptype
@classmethod
def fromJsonObj(cls, con: Connection, context: Context, jsonld_obj: Any) -> Tuple[str, 'HasProperty']:
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.prefix_from_iri("http://www.w3.org/1999/02/22-rdf-syntax-ns#")
rdfs = context.prefix_from_iri("http://www.w3.org/2000/01/rdf-schema#")
owl = context.prefix_from_iri("http://www.w3.org/2002/07/owl#")
xsd = context.prefix_from_iri("http://www.w3.org/2001/XMLSchema#")
knora_api = context.prefix_from_iri("http://api.knora.org/ontology/knora-api/v2#")
salsah_gui = context.prefix_from_iri("http://api.knora.org/ontology/salsah-gui/v2#")
if jsonld_obj.get('@type') is None or jsonld_obj.get('@type') != owl + ":Restriction":
raise BaseError('Expected restriction type')
#
# let's get the inherited field...
#
tmp = jsonld_obj.get(knora_api + ':isInherited')
is_inherited = tmp if tmp is not None else False
#
# let's get the cardinality
#
cardinality: Cardinality
if jsonld_obj.get(owl + ':cardinality') is not None:
cardinality = Cardinality.C_1
elif jsonld_obj.get(owl + ':maxCardinality') is not None:
cardinality = Cardinality.C_0_1
elif jsonld_obj.get(owl + ':minCardinality') is not None:
if jsonld_obj.get(owl + ':minCardinality') == 0:
cardinality = Cardinality.C_0_n
elif jsonld_obj.get(owl + ':minCardinality') == 1:
cardinality = Cardinality.C_1_n
else:
raise BaseError('Problem with cardinality')
else:
raise BaseError('Problem with cardinality')
#
# Now let's get the property IRI
#
property_id: str
ptype: HasProperty.Ptype
ontology_id: Optional[str] = None
if jsonld_obj.get(owl + ':onProperty') is None:
raise BaseError('No property IRI given')
p = jsonld_obj[owl + ':onProperty'].get('@id')
if p is None:
raise BaseError('No property IRI given')
pp = p.split(':')
if pp[0] == rdf or pp[0] == rdfs or pp[0] == owl:
ptype = HasProperty.Ptype.system
elif pp[0] == knora_api:
ptype = HasProperty.Ptype.knora
else:
ptype = HasProperty.Ptype.other
ontology_id = context.iri_from_prefix(pp[0])
property_id = p
gui_order: int = None
if jsonld_obj.get(salsah_gui + ':guiOrder') is not None:
gui_order = jsonld_obj[salsah_gui + ':guiOrder']
return property_id, cls(con=con,
context=context,
ontology_id=ontology_id,
property_id=property_id,
cardinality=cardinality,
gui_order=gui_order,
is_inherited=is_inherited,
ptype=ptype)
def toJsonObj(self, lastModificationDate: LastModificationDate, action: Actions) -> Any:
if self._cardinality is None:
raise BaseError("There must be a cardinality given!")
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()
}
if self._gui_order is not None:
tmp["@graph"][0]["rdfs:subClassOf"]["salsah-gui:guiOrder"] = self._gui_order
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()
}
if self._gui_order is not None and 'gui_order' in self._changed:
tmp["@graph"][0]["rdfs:subClassOf"]["salsah-gui:guiOrder"] = self._gui_order
return tmp
def create(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.Create)
jsondata = json.dumps(jsonobj, cls=SetEncoder, indent=2)
result = self._con.post(HasProperty.ROUTE, 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, indent=4, cls=SetEncoder)
result = self._con.put(HasProperty.ROUTE, 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 delete(self, last_modification_date: LastModificationDate) -> LastModificationDate:
raise BaseError("Cannot remove a single property from a class!")
# ToDo: Check with Ben if we could add this feature...
def createDefinitionFileObj(self, context: Context, shortname: str):
cardinality = {}
if self._ptype == HasProperty.Ptype.other:
cardinality["propname"] = context.reduce_iri(self._property_id, shortname)
cardinality["cardinality"] = self._cardinality.value
if self._gui_order is not None:
cardinality["gui_order"] = self._gui_order
return cardinality
def print(self, offset: int = 0):
blank = ' '
if self._ptype == HasProperty.Ptype.system:
print(f'{blank:>{offset}}Has Property (system)')
elif self._ptype == HasProperty.Ptype.knora:
print(f'{blank:>{offset}}Has Property (knora)')
else:
print(f'{blank:>{offset}}Has Property (project)')
print(f'{blank:>{offset + 2}}Property: {self._property_id}')
print(f'{blank:>{offset + 2}}Cardinality: {self._cardinality.value}')
if self._ptype == HasProperty.Ptype.other:
print(f'{blank:>{offset + 2}}Ontology_id: {self._ontology_id}')
print(f'{blank:>{offset + 2}}Resclass: {self._resclass_id}')
@strict
class ResourceClass(Model):
"""
This class represents a knora resource class
Attributes
----------
con : Connection
A Connection instance to a Knora server
id : str
IRI of the ResourceClass [readonly, cannot be modified after creation of instance]
name: str
The name of the resource class, e.g. "Book", "Person", "Portait". Usually these names start
with a capital letter
ontology_id: str
The IRI/Id of the ontology this resource class belongs to
superlcasses: str, list[str]
This is a list of superclasses for this resource class. Usually a project specific class must at least
be a subclass of "Resource", but can be subclassed of any other valid resource class. In addition, external
ontologies may be referenced:
e.g.:
```
"super": "Resource"
"super": ":MySpecialTYpe"
"super": [":MySpecialType", "dcterms:BibliographicResource"]
```
label: language dependent string, that is a dict like {"en": "Biblography", "de": "Literaturverzeichnis"}
A label (human readable name) for the resource
comment: language dependent string, that is a dict like {"en": "a comment", "de": "Ein Kommentar"}
A commentary to further explain what this resource class is used for
permission: str
The default permissions to be used if an instance of this resource class is being created
has_properties: dict[str, HasProperty]
Holds a dict with the property names as keys and a HasProperty instance. HasProperty holds
the information, how this resource class uses this property (basically the cardinality)
changed: bool
is set to True, if one of the fields has been chaned by the user (internal use only!)
Methods
-------
addLabel: Add a new label to the resource
addLabel(self, lang: Union[Languages, str], value: str) -> None
getProperty: Get information about a property defined for this resource class
getPropertery(prop_id: str) -> HasProperty
returns a HasProperty-instance
addProperty: Add a new property to the resource class
addProperty(property_id: str, cardinality: Cardinality, last_modification_date: LastModificationDate)
-> Optional[LastModificationDate]
updateProperty: Updates the cardinality parameters of the given property with the resource class
updateProperty(self, property_id: str, cardinality: Cardinality, last_modification_date: LastModificationDate)
-> Optional[LastModificationDate]
Please note that the cardinality usually can only be changed to be *less* restrictive!
create: Create a new resource class on the connected server
update: Update the information of a resource class on the connected server
delete: Mark a resource class as deleted (on the connected server)
createDefinitionFileObj: Create an object suitable for jsonification that conforms the the knora-py ontology tools
print: Print the content of this class to the console
"""
ROUTE: str = "/v2/ontologies/classes"
_context: Context
_id: str
_name: str
_ontology_id: str
_superclasses: list[str]
_label: LangString
_comment: LangString
_permissions: str
_has_properties: dict[str, HasProperty]
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):
"""
Create an instance of ResourceClass
:param con:
:param context:
:param id:
:param name:
:param ontology_id:
:param superclasses:
:param label:
:param comment:
:param permissions:
:param has_properties:
"""
super().__init__(con)
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._context = context
self._id = id
self._name = name
if ontology_id is not None:
self._ontology_id = context.iri_from_prefix(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()
#
# Here follows a list of getters/setters
#
@property
def name(self) -> Optional[str]:
return self._name
@name.setter
def name(self, value: str) -> None:
raise BaseError('"name" cannot be modified!')
@property
def id(self) -> Optional[str]:
return self._id
@id.setter
def id(self, value: str) -> None:
raise BaseError('"id" cannot be modified!')
@property
def ontology_id(self) -> Optional[str]:
return self._ontology_id
@ontology_id.setter
def ontology_id(self, value: str) -> None:
raise BaseError('"ontology_id" cannot be modified!')
@property
def superclasses(self) -> Optional[list[str]]:
return self._superclasses
@superclasses.setter
def superclasses(self, value: list[str]) -> None:
raise BaseError('"superclasses" cannot be modified!')
@property
def label(self) -> Optional[LangString]:
return self._label
@label.setter
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')
def addLabel(self, lang: Union[Languages, str], value: str) -> None:
self._label[lang] = value
self._changed.add('label')
def rmLabel(self, lang: Union[Languages, str]) -> None:
del self._label[lang]
self._changed.add('label')
@property
def comment(self) -> Optional[LangString]:
return self._comment
@comment.setter
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')
def addComment(self, lang: Union[Languages, str], value: str) -> None:
self._comment[lang] = value
self._changed.add('comment')
def rmComment(self, lang: Union[Languages, str]) -> None:
del self._comment[lang]
self._changed.add('comment')
@property
def permissions(self) -> Optional[str]:
return self._permissions
@permissions.setter
def permissions(self, value: str) -> None:
raise BaseError('"permissions" cannot be modified!')
@property
def has_properties(self) -> dict[str, HasProperty]:
return self._has_properties
@has_properties.setter
def has_properties(self, value: str) -> None:
raise BaseError('"has_property" cannot be modified!')
def getProperty(self, property_id) -> Optional[HasProperty]:
if self._has_properties is None:
return None
else:
return self._has_properties.get(self._context.get_prefixed_iri(property_id))
def addProperty(self,
last_modification_date: LastModificationDate,
property_id: str,
cardinality: Cardinality,
gui_order: Optional[int] = None,
) -> LastModificationDate:
if self._has_properties.get(property_id) is None:
latest_modification_date, resclass = HasProperty(con=self._con,
context=self._context,
ontology_id=self._ontology_id,
property_id=property_id,
resclass_id=self.id,
cardinality=cardinality,
gui_order=gui_order).create(last_modification_date)
hp = resclass.getProperty(property_id)
hp._ontology_id = self._context.iri_from_prefix(self._ontology_id)
hp._resclass_id = self._id
self._has_properties[hp.property_id] = hp
return latest_modification_date
else:
raise BaseError("Property already has cardinality in this class! " + property_id)
def updateProperty(self,
last_modification_date: LastModificationDate,
property_id: str,
cardinality: Optional[Cardinality],
gui_order: Optional[int] = None,
) -> Optional[LastModificationDate]:
property_id = self._context.get_prefixed_iri(property_id)
if self._has_properties.get(property_id) is not None:
has_properties = self._has_properties[property_id]
# onto_id = has_properties.ontology_id # save for later user
# rescl_id = has_properties.resclass_id # save for later user
has_properties.ontology_id = self._ontology_id
has_properties.resclass_id = self._id
if cardinality:
has_properties.cardinality = cardinality
if gui_order:
has_properties.gui_order = gui_order
latest_modification_date, resclass = has_properties.update(last_modification_date)
hp = resclass.getProperty(property_id)
hp.ontology_id = self._ontology_id # self.__context.iri_from_prefix(onto_id) # restore value
hp.resclass_id = self._id # rescl_id # restore value
self._has_properties[hp.property_id] = hp
return latest_modification_date
else:
return last_modification_date
@classmethod
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.prefix_from_iri("http://www.w3.org/1999/02/22-rdf-syntax-ns#")
rdfs = context.prefix_from_iri("http://www.w3.org/2000/01/rdf-schema#")
owl = context.prefix_from_iri("http://www.w3.org/2002/07/owl#")
xsd = context.prefix_from_iri("http://www.w3.org/2001/XMLSchema#")
knora_api = context.prefix_from_iri("http://api.knora.org/ontology/knora-api/v2#")
salsah_gui = context.prefix_from_iri("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.iri_from_prefix(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))
#
# now remove the ...Value stuff from resource pointers: A resource pointer is returned as 2 properties:
# one a direct link, the other the pointer to a link value
#
tmp = dict(has_properties)
for key in tmp.keys():
key_with_value = key
if key.endswith("Value"):
key = key.removesuffix("Value")
if key in has_properties:
del has_properties[key_with_value]
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)
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] and self._context.iri_from_prefix(tmp[0]) != self._ontology_id:
self._context.add_context(tmp[0])
return {"@id": resref} # fully qualified name in the form "prefix:name"
else:
return {"@id": self._context.prefix_from_iri(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.prefix_from_iri(self._ontology_id) + ":" + self._name
ontid = self._ontology_id
else:
resid = self._ontology_id + ":" + self._name
ontid = self._context.iri_from_prefix(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._label is None or self._label.isEmpty():
self._label = LangString("no label available")
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:subClassOf": superclasses
}],
"@context": self._context.toJsonObj(),
}
if self._comment:
tmp["@graph"][0]["rdfs:comment"] = self._comment.toJsonLdObj()
print(tmp)
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
def create(self, last_modification_date: LastModificationDate) -> Tuple[LastModificationDate, 'ResourceClass']:
jsonobj = self.toJsonObj(last_modification_date, Actions.Create)
jsondata = json.dumps(jsonobj, cls=SetEncoder, indent=4)
result = self._con.post(ResourceClass.ROUTE, 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']:
#
# 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(ResourceClass.ROUTE, 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(ResourceClass.ROUTE, jsondata)
last_modification_date = LastModificationDate(result['knora-api:lastModificationDate'])
something_changed = True
if something_changed:
return last_modification_date, ResourceClass.fromJsonObj(self._con, self._context, result['@graph'])
else:
return last_modification_date, self
def delete(self, last_modification_date: LastModificationDate) -> LastModificationDate:
result = self._con.delete(
ResourceClass.ROUTE + '/' + quote_plus(self._id) + '?lastModificationDate=' + str(last_modification_date))
return LastModificationDate(result['knora-api:lastModificationDate'])
def createDefinitionFileObj(self, context: Context, shortname: str, skiplist: list[str]):
resource = {
"name": self._name,
"labels": self._label.createDefinitionFileObj(),
}
if self._comment:
resource["comments"] = self._comment.createDefinitionFileObj()
if self._superclasses:
if len(self._superclasses) > 1:
superclasses = []
for sc in self._superclasses:
superclasses.append(context.reduce_iri(sc, shortname))
else:
superclasses = context.reduce_iri(self._superclasses[0], shortname)
resource["super"] = superclasses
if self._has_properties:
cardinalities = []
for pid, hp in self._has_properties.items():
if hp.property_id in skiplist:
continue
if hp.ptype == HasProperty.Ptype.other:
cardinalities.append(hp.createDefinitionFileObj(context, shortname))
resource["cardinalities"] = cardinalities
return resource
def print(self, offset: int = 0):
blank = ' '
print(f'{blank:>{offset}}Resource Class Info')
print(f'{blank:>{offset + 2}}Name: {self._name}')
print(f'{blank:>{offset + 2}}Ontology prefix: {self._ontology_id}')
print(f'{blank:>{offset + 2}}Superclasses:')
if self._superclasses is not None:
for sc in self._superclasses:
print(f'{blank:>{offset + 4}}{sc}')
if self._label is not None:
print(f'{blank:>{offset + 2}}Labels:')
self._label.print(offset + 4)
if self._comment is not None:
print(f'{blank:>{offset + 2}}Comments:')
self._comment.print(offset + 4)
if self._has_properties is not None:
print(f'{blank:>{offset + 2}}Has properties:')
if self._has_properties is not None:
for pid, hp in self._has_properties.items():
hp.print(offset + 4)